| 1 | /** Helpers for dynamic canvas → Framework image textures (e.g. HP bars). */ |
| 2 | |
| 3 | export function frameworkImageFromCanvas (canvas) |
| 4 | { |
| 5 | const fw = new image(canvas, 1, 1, false); |
| 6 | fw.cacheWidth = -1; |
| 7 | fw.cacheHeight = -1; |
| 8 | return fw; |
| 9 | } |
| 10 | |
| 11 | export function invalidateCanvasTexture (scene, canvas) |
| 12 | { |
| 13 | const glContext = scene?.glContext; |
| 14 | if (!glContext?.textures || !canvas) |
| 15 | { return; } |
| 16 | const texture = glContext.textures.get(canvas); |
| 17 | if (!texture) |
| 18 | { return; } |
| 19 | glContext.gl.deleteTexture(texture); |
| 20 | glContext.textures.delete(canvas); |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Upload/replace RGBA pixels for a canvas-keyed GL texture. |
| 25 | * Reuses the existing texture via texSubImage2D when possible (no delete/recreate). |
| 26 | * @returns {boolean} true when a new texture was created |
| 27 | */ |
| 28 | export function uploadCanvasTextureRgba (scene, canvas, pixels, width, height, filter = null) |
| 29 | { |
| 30 | const glContext = scene?.glContext; |
| 31 | const gl = glContext?.gl; |
| 32 | if (!gl || !glContext?.textures || !canvas || !pixels) |
| 33 | { return false; } |
| 34 | |
| 35 | let texture = glContext.textures.get(canvas); |
| 36 | if (texture) |
| 37 | { |
| 38 | gl.bindTexture(gl.TEXTURE_2D, texture); |
| 39 | gl.texSubImage2D( |
| 40 | gl.TEXTURE_2D, |
| 41 | 0, |
| 42 | 0, |
| 43 | 0, |
| 44 | width, |
| 45 | height, |
| 46 | gl.RGBA, |
| 47 | gl.UNSIGNED_BYTE, |
| 48 | pixels |
| 49 | ); |
| 50 | return false; |
| 51 | } |
| 52 | |
| 53 | texture = gl.createTexture(); |
| 54 | gl.bindTexture(gl.TEXTURE_2D, texture); |
| 55 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); |
| 56 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); |
| 57 | const minFilter = filter ?? glContext.textureMinFilter ?? gl.LINEAR; |
| 58 | const magFilter = filter ?? glContext.textureMagFilter ?? gl.LINEAR; |
| 59 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); |
| 60 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); |
| 61 | gl.texImage2D( |
| 62 | gl.TEXTURE_2D, |
| 63 | 0, |
| 64 | gl.RGBA, |
| 65 | width, |
| 66 | height, |
| 67 | 0, |
| 68 | gl.RGBA, |
| 69 | gl.UNSIGNED_BYTE, |
| 70 | pixels |
| 71 | ); |
| 72 | glContext.textures.set(canvas, texture); |
| 73 | return true; |
| 74 | } |