@lightningjs/renderer 2.9.0-beta2 → 2.9.0-beta4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/COPYING +1 -0
  2. package/LICENSE +202 -202
  3. package/NOTICE +3 -3
  4. package/README.md +147 -147
  5. package/dist/src/core/CoreNode.d.ts +29 -6
  6. package/dist/src/core/CoreNode.js +118 -79
  7. package/dist/src/core/CoreNode.js.map +1 -1
  8. package/dist/src/core/CoreTextNode.d.ts +2 -2
  9. package/dist/src/core/CoreTextNode.js +7 -4
  10. package/dist/src/core/CoreTextNode.js.map +1 -1
  11. package/dist/src/core/CoreTextureManager.d.ts +61 -15
  12. package/dist/src/core/CoreTextureManager.js +179 -104
  13. package/dist/src/core/CoreTextureManager.js.map +1 -1
  14. package/dist/src/core/Stage.d.ts +7 -0
  15. package/dist/src/core/Stage.js +34 -1
  16. package/dist/src/core/Stage.js.map +1 -1
  17. package/dist/src/core/TextureMemoryManager.js +2 -5
  18. package/dist/src/core/TextureMemoryManager.js.map +1 -1
  19. package/dist/src/core/lib/ImageWorker.js +31 -28
  20. package/dist/src/core/lib/ImageWorker.js.map +1 -1
  21. package/dist/src/core/lib/WebGlContextWrapper.d.ts +1 -0
  22. package/dist/src/core/lib/WebGlContextWrapper.js +2 -0
  23. package/dist/src/core/lib/WebGlContextWrapper.js.map +1 -1
  24. package/dist/src/core/renderers/CoreContextTexture.d.ts +1 -0
  25. package/dist/src/core/renderers/CoreContextTexture.js +1 -0
  26. package/dist/src/core/renderers/CoreContextTexture.js.map +1 -1
  27. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.d.ts +1 -1
  28. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.js +13 -5
  29. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.js.map +1 -1
  30. package/dist/src/core/renderers/canvas/CanvasCoreTexture.js +6 -8
  31. package/dist/src/core/renderers/canvas/CanvasCoreTexture.js.map +1 -1
  32. package/dist/src/core/renderers/webgl/WebGlCoreCtxSubTexture.js +3 -1
  33. package/dist/src/core/renderers/webgl/WebGlCoreCtxSubTexture.js.map +1 -1
  34. package/dist/src/core/renderers/webgl/WebGlCoreCtxTexture.d.ts +1 -2
  35. package/dist/src/core/renderers/webgl/WebGlCoreCtxTexture.js +26 -24
  36. package/dist/src/core/renderers/webgl/WebGlCoreCtxTexture.js.map +1 -1
  37. package/dist/src/core/renderers/webgl/WebGlCoreRenderer.d.ts +0 -1
  38. package/dist/src/core/renderers/webgl/WebGlCoreRenderer.js +7 -17
  39. package/dist/src/core/renderers/webgl/WebGlCoreRenderer.js.map +1 -1
  40. package/dist/src/core/renderers/webgl/shaders/DefaultShader.js +45 -45
  41. package/dist/src/core/renderers/webgl/shaders/DefaultShaderBatched.js +61 -61
  42. package/dist/src/core/renderers/webgl/shaders/DynamicShader.js +93 -93
  43. package/dist/src/core/renderers/webgl/shaders/RoundedRectangle.js +63 -63
  44. package/dist/src/core/renderers/webgl/shaders/SdfShader.js +62 -62
  45. package/dist/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.js +15 -15
  46. package/dist/src/core/renderers/webgl/shaders/effects/BorderEffect.js +6 -6
  47. package/dist/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.js +15 -15
  48. package/dist/src/core/renderers/webgl/shaders/effects/BorderRightEffect.js +15 -15
  49. package/dist/src/core/renderers/webgl/shaders/effects/BorderTopEffect.js +15 -15
  50. package/dist/src/core/renderers/webgl/shaders/effects/FadeOutEffect.js +42 -42
  51. package/dist/src/core/renderers/webgl/shaders/effects/GlitchEffect.js +44 -44
  52. package/dist/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.js +3 -3
  53. package/dist/src/core/renderers/webgl/shaders/effects/HolePunchEffect.js +22 -22
  54. package/dist/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.js +28 -28
  55. package/dist/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.js +12 -12
  56. package/dist/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.js +37 -37
  57. package/dist/src/core/renderers/webgl/shaders/effects/RadiusEffect.js +19 -19
  58. package/dist/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.js +9 -5
  59. package/dist/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.js.map +1 -1
  60. package/dist/src/core/text-rendering/renderers/CanvasTextRenderer.js +2 -1
  61. package/dist/src/core/text-rendering/renderers/CanvasTextRenderer.js.map +1 -1
  62. package/dist/src/core/textures/ColorTexture.d.ts +1 -1
  63. package/dist/src/core/textures/ColorTexture.js +2 -1
  64. package/dist/src/core/textures/ColorTexture.js.map +1 -1
  65. package/dist/src/core/textures/ImageTexture.d.ts +8 -1
  66. package/dist/src/core/textures/ImageTexture.js +39 -1
  67. package/dist/src/core/textures/ImageTexture.js.map +1 -1
  68. package/dist/src/core/textures/NoiseTexture.d.ts +1 -1
  69. package/dist/src/core/textures/NoiseTexture.js +2 -1
  70. package/dist/src/core/textures/NoiseTexture.js.map +1 -1
  71. package/dist/src/core/textures/RenderTexture.d.ts +1 -1
  72. package/dist/src/core/textures/RenderTexture.js +2 -1
  73. package/dist/src/core/textures/RenderTexture.js.map +1 -1
  74. package/dist/src/core/textures/SubTexture.d.ts +1 -1
  75. package/dist/src/core/textures/SubTexture.js +21 -4
  76. package/dist/src/core/textures/SubTexture.js.map +1 -1
  77. package/dist/src/core/textures/Texture.d.ts +44 -22
  78. package/dist/src/core/textures/Texture.js +116 -36
  79. package/dist/src/core/textures/Texture.js.map +1 -1
  80. package/dist/src/main-api/Renderer.d.ts +18 -0
  81. package/dist/src/main-api/Renderer.js +6 -4
  82. package/dist/src/main-api/Renderer.js.map +1 -1
  83. package/dist/tsconfig.dist.tsbuildinfo +1 -1
  84. package/exports/canvas.ts +39 -39
  85. package/exports/index.ts +89 -89
  86. package/exports/inspector.ts +24 -24
  87. package/exports/utils.ts +44 -44
  88. package/exports/webgl.ts +38 -38
  89. package/package.json +1 -1
  90. package/scripts/please-use-pnpm.js +13 -13
  91. package/src/common/CommonTypes.ts +139 -139
  92. package/src/common/EventEmitter.ts +77 -77
  93. package/src/common/IAnimationController.ts +92 -92
  94. package/src/common/IEventEmitter.ts +28 -28
  95. package/src/core/CoreNode.test.ts +199 -95
  96. package/src/core/CoreNode.ts +2313 -2258
  97. package/src/core/CoreShaderManager.ts +292 -292
  98. package/src/core/CoreTextNode.ts +455 -450
  99. package/src/core/CoreTextureManager.ts +522 -432
  100. package/src/core/Stage.ts +700 -652
  101. package/src/core/TextureMemoryManager.ts +277 -279
  102. package/src/core/animations/AnimationManager.ts +38 -38
  103. package/src/core/animations/CoreAnimation.ts +340 -340
  104. package/src/core/animations/CoreAnimationController.ts +157 -157
  105. package/src/core/lib/ContextSpy.ts +41 -41
  106. package/src/core/lib/ImageWorker.ts +270 -267
  107. package/src/core/lib/Matrix3d.ts +244 -244
  108. package/src/core/lib/RenderCoords.ts +86 -86
  109. package/src/core/lib/WebGlContextWrapper.ts +1322 -1320
  110. package/src/core/lib/textureCompression.ts +152 -152
  111. package/src/core/lib/textureSvg.ts +78 -78
  112. package/src/core/lib/utils.ts +306 -306
  113. package/src/core/platform.ts +61 -61
  114. package/src/core/renderers/CoreContextTexture.ts +43 -42
  115. package/src/core/renderers/CoreRenderOp.ts +22 -22
  116. package/src/core/renderers/CoreRenderer.ts +114 -114
  117. package/src/core/renderers/CoreShader.ts +41 -41
  118. package/src/core/renderers/canvas/CanvasCoreRenderer.ts +364 -353
  119. package/src/core/renderers/canvas/CanvasCoreTexture.ts +150 -149
  120. package/src/core/renderers/canvas/internal/C2DShaderUtils.ts +231 -231
  121. package/src/core/renderers/canvas/internal/ColorUtils.ts +69 -69
  122. package/src/core/renderers/canvas/shaders/UnsupportedShader.ts +48 -48
  123. package/src/core/renderers/webgl/WebGlCoreCtxRenderTexture.ts +79 -79
  124. package/src/core/renderers/webgl/WebGlCoreCtxSubTexture.ts +50 -48
  125. package/src/core/renderers/webgl/WebGlCoreCtxTexture.ts +298 -290
  126. package/src/core/renderers/webgl/WebGlCoreRenderOp.ts +125 -125
  127. package/src/core/renderers/webgl/WebGlCoreRenderer.ts +805 -817
  128. package/src/core/renderers/webgl/WebGlCoreShader.ts +362 -362
  129. package/src/core/renderers/webgl/internal/BufferCollection.ts +54 -54
  130. package/src/core/renderers/webgl/internal/RendererUtils.ts +155 -155
  131. package/src/core/renderers/webgl/internal/ShaderUtils.ts +143 -143
  132. package/src/core/renderers/webgl/internal/WebGlUtils.ts +35 -35
  133. package/src/core/renderers/webgl/shaders/DefaultShader.ts +93 -93
  134. package/src/core/renderers/webgl/shaders/DefaultShaderBatched.ts +132 -132
  135. package/src/core/renderers/webgl/shaders/DynamicShader.ts +580 -580
  136. package/src/core/renderers/webgl/shaders/RoundedRectangle.ts +167 -167
  137. package/src/core/renderers/webgl/shaders/SdfShader.ts +204 -204
  138. package/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.ts +101 -101
  139. package/src/core/renderers/webgl/shaders/effects/BorderEffect.ts +87 -87
  140. package/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.ts +101 -101
  141. package/src/core/renderers/webgl/shaders/effects/BorderRightEffect.ts +101 -101
  142. package/src/core/renderers/webgl/shaders/effects/BorderTopEffect.ts +101 -101
  143. package/src/core/renderers/webgl/shaders/effects/EffectUtils.ts +159 -159
  144. package/src/core/renderers/webgl/shaders/effects/FadeOutEffect.ts +127 -127
  145. package/src/core/renderers/webgl/shaders/effects/GlitchEffect.ts +148 -148
  146. package/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.ts +67 -67
  147. package/src/core/renderers/webgl/shaders/effects/HolePunchEffect.ts +157 -157
  148. package/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.ts +171 -171
  149. package/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.ts +168 -168
  150. package/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.ts +187 -187
  151. package/src/core/renderers/webgl/shaders/effects/RadiusEffect.ts +110 -110
  152. package/src/core/renderers/webgl/shaders/effects/ShaderEffect.ts +196 -196
  153. package/src/core/text-rendering/TextRenderingUtils.ts +36 -36
  154. package/src/core/text-rendering/TextTextureRendererUtils.ts +263 -263
  155. package/src/core/text-rendering/TrFontManager.ts +183 -183
  156. package/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.ts +176 -171
  157. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/FontShaper.ts +139 -139
  158. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.test.ts +173 -173
  159. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.ts +171 -171
  160. package/src/core/text-rendering/font-face-types/TrFontFace.ts +187 -187
  161. package/src/core/text-rendering/font-face-types/WebTrFontFace.ts +89 -89
  162. package/src/core/text-rendering/renderers/CanvasTextRenderer.ts +509 -507
  163. package/src/core/text-rendering/renderers/LightningTextTextureRenderer.ts +798 -798
  164. package/src/core/text-rendering/renderers/SdfTextRenderer/SdfTextRenderer.ts +853 -853
  165. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.test.ts +48 -48
  166. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.ts +66 -66
  167. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/SpecialCodepoints.ts +52 -52
  168. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/constants.ts +32 -32
  169. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getStartConditions.ts +117 -117
  170. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.test.ts +133 -133
  171. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.ts +38 -38
  172. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText.ts +403 -403
  173. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.test.ts +49 -49
  174. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.ts +52 -52
  175. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.test.ts +205 -205
  176. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.ts +93 -93
  177. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/util.ts +40 -40
  178. package/src/core/text-rendering/renderers/TextRenderer.ts +557 -557
  179. package/src/core/textures/ColorTexture.ts +102 -100
  180. package/src/core/textures/ImageTexture.ts +378 -337
  181. package/src/core/textures/NoiseTexture.ts +104 -101
  182. package/src/core/textures/RenderTexture.ts +85 -83
  183. package/src/core/textures/SubTexture.ts +171 -146
  184. package/src/core/textures/Texture.ts +423 -318
  185. package/src/core/utils.ts +227 -227
  186. package/src/env.d.ts +7 -7
  187. package/src/main-api/DynamicShaderController.ts +104 -104
  188. package/src/main-api/INode.ts +101 -101
  189. package/src/main-api/Inspector.ts +505 -505
  190. package/src/main-api/Renderer.ts +693 -670
  191. package/src/main-api/ShaderController.ts +80 -80
  192. package/src/main-api/utils.ts +45 -45
  193. package/src/utils.ts +248 -248
@@ -1,817 +1,805 @@
1
- /*
2
- * If not stated otherwise in this file or this component's LICENSE file the
3
- * following copyright and licenses apply:
4
- *
5
- * Copyright 2023 Comcast Cable Communications Management, LLC.
6
- *
7
- * Licensed under the Apache License, Version 2.0 (the License);
8
- * you may not use this file except in compliance with the License.
9
- * You may obtain a copy of the License at
10
- *
11
- * http://www.apache.org/licenses/LICENSE-2.0
12
- *
13
- * Unless required by applicable law or agreed to in writing, software
14
- * distributed under the License is distributed on an "AS IS" BASIS,
15
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- * See the License for the specific language governing permissions and
17
- * limitations under the License.
18
- */
19
-
20
- import { assertTruthy, createWebGLContext, hasOwn } from '../../../utils.js';
21
- import {
22
- CoreRenderer,
23
- type BufferInfo,
24
- type CoreRendererOptions,
25
- type QuadOptions,
26
- } from '../CoreRenderer.js';
27
- import { WebGlCoreRenderOp } from './WebGlCoreRenderOp.js';
28
- import type { CoreContextTexture } from '../CoreContextTexture.js';
29
- import {
30
- createIndexBuffer,
31
- type CoreWebGlParameters,
32
- type CoreWebGlExtensions,
33
- getWebGlParameters,
34
- getWebGlExtensions,
35
- type WebGlColor,
36
- } from './internal/RendererUtils.js';
37
- import { WebGlCoreCtxTexture } from './WebGlCoreCtxTexture.js';
38
- import { Texture, TextureType } from '../../textures/Texture.js';
39
- import { ColorTexture } from '../../textures/ColorTexture.js';
40
- import { SubTexture } from '../../textures/SubTexture.js';
41
- import { WebGlCoreCtxSubTexture } from './WebGlCoreCtxSubTexture.js';
42
- import { CoreShaderManager } from '../../CoreShaderManager.js';
43
- import { BufferCollection } from './internal/BufferCollection.js';
44
- import {
45
- compareRect,
46
- getNormalizedRgbaComponents,
47
- type RectWithValid,
48
- } from '../../lib/utils.js';
49
- import type { Dimensions } from '../../../common/CommonTypes.js';
50
- import { WebGlCoreShader } from './WebGlCoreShader.js';
51
- import { WebGlContextWrapper } from '../../lib/WebGlContextWrapper.js';
52
- import { RenderTexture } from '../../textures/RenderTexture.js';
53
- import type { CoreNode } from '../../CoreNode.js';
54
- import { WebGlCoreCtxRenderTexture } from './WebGlCoreCtxRenderTexture.js';
55
- import type { BaseShaderController } from '../../../main-api/ShaderController.js';
56
- import { ImageTexture } from '../../textures/ImageTexture.js';
57
-
58
- const WORDS_PER_QUAD = 24;
59
- // const BYTES_PER_QUAD = WORDS_PER_QUAD * 4;
60
-
61
- export type WebGlCoreRendererOptions = CoreRendererOptions;
62
-
63
- interface CoreWebGlSystem {
64
- parameters: CoreWebGlParameters;
65
- extensions: CoreWebGlExtensions;
66
- }
67
-
68
- export class WebGlCoreRenderer extends CoreRenderer {
69
- //// WebGL Native Context and Data
70
- glw: WebGlContextWrapper;
71
- system: CoreWebGlSystem;
72
-
73
- //// Persistent data
74
- quadBuffer: ArrayBuffer;
75
- fQuadBuffer: Float32Array;
76
- uiQuadBuffer: Uint32Array;
77
- renderOps: WebGlCoreRenderOp[] = [];
78
-
79
- //// Render Op / Buffer Filling State
80
- curBufferIdx = 0;
81
- curRenderOp: WebGlCoreRenderOp | null = null;
82
- override rttNodes: CoreNode[] = [];
83
- activeRttNode: CoreNode | null = null;
84
-
85
- //// Default Shader
86
- defShaderCtrl: BaseShaderController;
87
- defaultShader: WebGlCoreShader;
88
- quadBufferCollection: BufferCollection;
89
-
90
- clearColor: WebGlColor = {
91
- raw: 0x00000000,
92
- normalized: [0, 0, 0, 0],
93
- };
94
-
95
- /**
96
- * White pixel texture used by default when no texture is specified.
97
- */
98
- defaultTexture: Texture;
99
-
100
- quadBufferUsage = 0;
101
- /**
102
- * Whether the renderer is currently rendering to a texture.
103
- */
104
- public renderToTextureActive = false;
105
-
106
- constructor(options: WebGlCoreRendererOptions) {
107
- super(options);
108
-
109
- this.quadBuffer = new ArrayBuffer(this.stage.options.quadBufferSize);
110
- this.fQuadBuffer = new Float32Array(this.quadBuffer);
111
- this.uiQuadBuffer = new Uint32Array(this.quadBuffer);
112
-
113
- this.mode = 'webgl';
114
-
115
- const { canvas, clearColor, bufferMemory } = options;
116
-
117
- this.defaultTexture = new ColorTexture(this.txManager);
118
-
119
- // Mark the default texture as ALWAYS renderable
120
- // This prevents it from ever being cleaned up.
121
- // Fixes https://github.com/lightning-js/renderer/issues/262
122
- this.defaultTexture.setRenderableOwner(this, true);
123
-
124
- // When the default texture is loaded, request a render in case the
125
- // RAF is paused. Fixes: https://github.com/lightning-js/renderer/issues/123
126
- this.defaultTexture.once('loaded', () => {
127
- this.stage.requestRender();
128
- });
129
-
130
- const gl = createWebGLContext(
131
- canvas,
132
- options.forceWebGL2,
133
- options.contextSpy,
134
- );
135
- const glw = (this.glw = new WebGlContextWrapper(gl));
136
- glw.viewport(0, 0, canvas.width, canvas.height);
137
-
138
- this.updateClearColor(clearColor);
139
-
140
- glw.setBlend(true);
141
- glw.blendFunc(glw.ONE, glw.ONE_MINUS_SRC_ALPHA);
142
-
143
- createIndexBuffer(glw, bufferMemory);
144
-
145
- this.system = {
146
- parameters: getWebGlParameters(this.glw),
147
- extensions: getWebGlExtensions(this.glw),
148
- };
149
- this.shManager.renderer = this;
150
- this.defShaderCtrl = this.shManager.loadShader('DefaultShader');
151
- this.defaultShader = this.defShaderCtrl.shader as WebGlCoreShader;
152
- const quadBuffer = glw.createBuffer();
153
- assertTruthy(quadBuffer);
154
- const stride = 6 * Float32Array.BYTES_PER_ELEMENT;
155
- this.quadBufferCollection = new BufferCollection([
156
- {
157
- buffer: quadBuffer,
158
- attributes: {
159
- a_position: {
160
- name: 'a_position',
161
- size: 2, // 2 components per iteration
162
- type: glw.FLOAT, // the data is 32bit floats
163
- normalized: false, // don't normalize the data
164
- stride, // 0 = move forward size * sizeof(type) each iteration to get the next position
165
- offset: 0, // start at the beginning of the buffer
166
- },
167
- a_textureCoordinate: {
168
- name: 'a_textureCoordinate',
169
- size: 2,
170
- type: glw.FLOAT,
171
- normalized: false,
172
- stride,
173
- offset: 2 * Float32Array.BYTES_PER_ELEMENT,
174
- },
175
- a_color: {
176
- name: 'a_color',
177
- size: 4,
178
- type: glw.UNSIGNED_BYTE,
179
- normalized: true,
180
- stride,
181
- offset: 4 * Float32Array.BYTES_PER_ELEMENT,
182
- },
183
- a_textureIndex: {
184
- name: 'a_textureIndex',
185
- size: 1,
186
- type: glw.FLOAT,
187
- normalized: false,
188
- stride,
189
- offset: 5 * Float32Array.BYTES_PER_ELEMENT,
190
- },
191
- },
192
- },
193
- ]);
194
- }
195
-
196
- reset() {
197
- const { glw } = this;
198
- this.curBufferIdx = 0;
199
- this.curRenderOp = null;
200
- this.renderOps.length = 0;
201
- glw.setScissorTest(false);
202
- glw.clear();
203
- }
204
-
205
- override getShaderManager(): CoreShaderManager {
206
- return this.shManager;
207
- }
208
-
209
- override createCtxTexture(textureSource: Texture): CoreContextTexture {
210
- if (textureSource instanceof SubTexture) {
211
- return new WebGlCoreCtxSubTexture(
212
- this.glw,
213
- this.txMemManager,
214
- textureSource,
215
- );
216
- } else if (textureSource instanceof RenderTexture) {
217
- return new WebGlCoreCtxRenderTexture(
218
- this.glw,
219
- this.txMemManager,
220
- textureSource,
221
- );
222
- }
223
- return new WebGlCoreCtxTexture(this.glw, this.txMemManager, textureSource);
224
- }
225
-
226
- /**
227
- * This function adds a quad (a rectangle composed of two triangles) to the WebGL rendering pipeline.
228
- *
229
- * It takes a set of options that define the quad's properties, such as its dimensions, colors, texture, shader, and transformation matrix.
230
- * The function first updates the shader properties with the current dimensions if necessary, then sets the default texture if none is provided.
231
- * It then checks if a new render operation is needed, based on the current shader and clipping rectangle.
232
- * If a new render operation is needed, it creates one and updates the current render operation.
233
- * The function then adjusts the texture coordinates based on the texture options and adds the texture to the texture manager.
234
- *
235
- * Finally, it calculates the vertices for the quad, taking into account any transformations, and adds them to the quad buffer.
236
- * The function updates the length and number of quads in the current render operation, and updates the current buffer index.
237
- */
238
- addQuad(params: QuadOptions) {
239
- const { fQuadBuffer, uiQuadBuffer } = this;
240
- let texture = params.texture || this.defaultTexture;
241
-
242
- /**
243
- * If the shader props contain any automatic properties, update it with the
244
- * current dimensions and or alpha that will be used to render the quad.
245
- */
246
- if (params.shaderProps !== null) {
247
- if (hasOwn(params.shaderProps, '$dimensions') == true) {
248
- const dimensions = params.shaderProps.$dimensions as Dimensions;
249
- dimensions.width = params.width;
250
- dimensions.height = params.height;
251
- }
252
-
253
- if (hasOwn(params.shaderProps, '$alpha') === true) {
254
- params.shaderProps.$alpha = params.alpha;
255
- }
256
- }
257
-
258
- assertTruthy(texture.ctxTexture !== undefined, 'Invalid texture type');
259
-
260
- let { curBufferIdx: bufferIdx, curRenderOp } = this;
261
- const targetDims = { width: -1, height: -1 };
262
- targetDims.width = params.width;
263
- targetDims.height = params.height;
264
-
265
- const targetShader =
266
- (params.shader as WebGlCoreShader) || this.defaultShader;
267
- assertTruthy(
268
- targetShader.getUniformLocation !== undefined,
269
- 'Invalid WebGL shader',
270
- );
271
-
272
- if (this.reuseRenderOp(params) === false) {
273
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
274
- this.newRenderOp(
275
- targetShader,
276
- params.shaderProps as Record<string, unknown>,
277
- params.alpha,
278
- targetDims,
279
- params.clippingRect,
280
- bufferIdx,
281
- params.rtt,
282
- params.parentHasRenderTexture,
283
- params.framebufferDimensions,
284
- );
285
- curRenderOp = this.curRenderOp;
286
- assertTruthy(curRenderOp);
287
- }
288
-
289
- let texCoordX1 = 0;
290
- let texCoordY1 = 0;
291
- let texCoordX2 = 1;
292
- let texCoordY2 = 1;
293
-
294
- if (texture.type === TextureType.subTexture) {
295
- const {
296
- x: tx,
297
- y: ty,
298
- width: tw,
299
- height: th,
300
- } = (texture as SubTexture).props;
301
- const { width: parentW = 0, height: parentH = 0 } = (
302
- texture as SubTexture
303
- ).parentTexture.dimensions || { width: 0, height: 0 };
304
- texCoordX1 = tx / parentW;
305
- texCoordX2 = texCoordX1 + tw / parentW;
306
- texCoordY1 = ty / parentH;
307
- texCoordY2 = texCoordY1 + th / parentH;
308
- texture = (texture as SubTexture).parentTexture;
309
- }
310
-
311
- if (
312
- texture.type === TextureType.image &&
313
- params.textureOptions !== null &&
314
- params.textureOptions.resizeMode !== undefined &&
315
- texture.dimensions !== null
316
- ) {
317
- const resizeMode = params.textureOptions.resizeMode;
318
- const { width: tw, height: th } = texture.dimensions;
319
- if (resizeMode.type === 'cover') {
320
- const scaleX = params.width / tw;
321
- const scaleY = params.height / th;
322
- const scale = Math.max(scaleX, scaleY);
323
- const precision = 1 / scale;
324
- // Determine based on width
325
- if (scale && scaleX && scaleX < scale) {
326
- const desiredSize = precision * params.width;
327
- texCoordX1 = (1 - desiredSize / tw) * (resizeMode.clipX ?? 0.5);
328
- texCoordX2 = texCoordX1 + desiredSize / tw;
329
- }
330
- // Determine based on height
331
- if (scale && scaleY && scaleY < scale) {
332
- const desiredSize = precision * params.height;
333
- texCoordY1 = (1 - desiredSize / th) * (resizeMode.clipY ?? 0.5);
334
- texCoordY2 = texCoordY1 + desiredSize / th;
335
- }
336
- }
337
- }
338
-
339
- // Flip texture coordinates if dictated by texture options
340
- let flipY = 0;
341
- if (params.textureOptions !== null) {
342
- if (params.textureOptions.flipX === true) {
343
- [texCoordX1, texCoordX2] = [texCoordX2, texCoordX1];
344
- }
345
-
346
- // convert to integer for bitwise operation below
347
- flipY = +(params.textureOptions.flipY || false);
348
- }
349
-
350
- // Eitherone should be true
351
- if (flipY ^ +(texture.type === TextureType.renderToTexture)) {
352
- [texCoordY1, texCoordY2] = [texCoordY2, texCoordY1];
353
- }
354
-
355
- const ctxTexture = texture.ctxTexture as WebGlCoreCtxTexture;
356
- assertTruthy(ctxTexture.ctxTexture !== undefined);
357
- const textureIdx = this.addTexture(ctxTexture, bufferIdx);
358
-
359
- assertTruthy(this.curRenderOp !== null);
360
- if (params.renderCoords) {
361
- // Upper-Left
362
- fQuadBuffer[bufferIdx++] = params.renderCoords.x1; // vertexX
363
- fQuadBuffer[bufferIdx++] = params.renderCoords.y1; // vertexY
364
- fQuadBuffer[bufferIdx++] = texCoordX1; // texCoordX
365
- fQuadBuffer[bufferIdx++] = texCoordY1; // texCoordY
366
- uiQuadBuffer[bufferIdx++] = params.colorTl; // color
367
- fQuadBuffer[bufferIdx++] = textureIdx; // texIndex
368
-
369
- // Upper-Right
370
- fQuadBuffer[bufferIdx++] = params.renderCoords.x2;
371
- fQuadBuffer[bufferIdx++] = params.renderCoords.y2;
372
- fQuadBuffer[bufferIdx++] = texCoordX2;
373
- fQuadBuffer[bufferIdx++] = texCoordY1;
374
- uiQuadBuffer[bufferIdx++] = params.colorTr;
375
- fQuadBuffer[bufferIdx++] = textureIdx;
376
-
377
- // Lower-Left
378
- fQuadBuffer[bufferIdx++] = params.renderCoords.x4;
379
- fQuadBuffer[bufferIdx++] = params.renderCoords.y4;
380
- fQuadBuffer[bufferIdx++] = texCoordX1;
381
- fQuadBuffer[bufferIdx++] = texCoordY2;
382
- uiQuadBuffer[bufferIdx++] = params.colorBl;
383
- fQuadBuffer[bufferIdx++] = textureIdx;
384
-
385
- // Lower-Right
386
- fQuadBuffer[bufferIdx++] = params.renderCoords.x3;
387
- fQuadBuffer[bufferIdx++] = params.renderCoords.y3;
388
- fQuadBuffer[bufferIdx++] = texCoordX2;
389
- fQuadBuffer[bufferIdx++] = texCoordY2;
390
- uiQuadBuffer[bufferIdx++] = params.colorBr;
391
- fQuadBuffer[bufferIdx++] = textureIdx;
392
- } else if (params.tb !== 0 || params.tc !== 0) {
393
- // Upper-Left
394
- fQuadBuffer[bufferIdx++] = params.tx; // vertexX
395
- fQuadBuffer[bufferIdx++] = params.ty; // vertexY
396
- fQuadBuffer[bufferIdx++] = texCoordX1; // texCoordX
397
- fQuadBuffer[bufferIdx++] = texCoordY1; // texCoordY
398
- uiQuadBuffer[bufferIdx++] = params.colorTl; // color
399
- fQuadBuffer[bufferIdx++] = textureIdx; // texIndex
400
-
401
- // Upper-Right
402
- fQuadBuffer[bufferIdx++] = params.tx + params.width * params.ta;
403
- fQuadBuffer[bufferIdx++] = params.ty + params.width * params.tc;
404
- fQuadBuffer[bufferIdx++] = texCoordX2;
405
- fQuadBuffer[bufferIdx++] = texCoordY1;
406
- uiQuadBuffer[bufferIdx++] = params.colorTr;
407
- fQuadBuffer[bufferIdx++] = textureIdx;
408
-
409
- // Lower-Left
410
- fQuadBuffer[bufferIdx++] = params.tx + params.height * params.tb;
411
- fQuadBuffer[bufferIdx++] = params.ty + params.height * params.td;
412
- fQuadBuffer[bufferIdx++] = texCoordX1;
413
- fQuadBuffer[bufferIdx++] = texCoordY2;
414
- uiQuadBuffer[bufferIdx++] = params.colorBl;
415
- fQuadBuffer[bufferIdx++] = textureIdx;
416
-
417
- // Lower-Right
418
- fQuadBuffer[bufferIdx++] =
419
- params.tx + params.width * params.ta + params.height * params.tb;
420
- fQuadBuffer[bufferIdx++] =
421
- params.ty + params.width * params.tc + params.height * params.td;
422
- fQuadBuffer[bufferIdx++] = texCoordX2;
423
- fQuadBuffer[bufferIdx++] = texCoordY2;
424
- uiQuadBuffer[bufferIdx++] = params.colorBr;
425
- fQuadBuffer[bufferIdx++] = textureIdx;
426
- } else {
427
- // Calculate the right corner of the quad
428
- // multiplied by the scale
429
- const rightCornerX = params.tx + params.width * params.ta;
430
- const rightCornerY = params.ty + params.height * params.td;
431
-
432
- // Upper-Left
433
- fQuadBuffer[bufferIdx++] = params.tx; // vertexX
434
- fQuadBuffer[bufferIdx++] = params.ty; // vertexY
435
- fQuadBuffer[bufferIdx++] = texCoordX1; // texCoordX
436
- fQuadBuffer[bufferIdx++] = texCoordY1; // texCoordY
437
- uiQuadBuffer[bufferIdx++] = params.colorTl; // color
438
- fQuadBuffer[bufferIdx++] = textureIdx; // texIndex
439
-
440
- // Upper-Right
441
- fQuadBuffer[bufferIdx++] = rightCornerX;
442
- fQuadBuffer[bufferIdx++] = params.ty;
443
- fQuadBuffer[bufferIdx++] = texCoordX2;
444
- fQuadBuffer[bufferIdx++] = texCoordY1;
445
- uiQuadBuffer[bufferIdx++] = params.colorTr;
446
- fQuadBuffer[bufferIdx++] = textureIdx;
447
-
448
- // Lower-Left
449
- fQuadBuffer[bufferIdx++] = params.tx;
450
- fQuadBuffer[bufferIdx++] = rightCornerY;
451
- fQuadBuffer[bufferIdx++] = texCoordX1;
452
- fQuadBuffer[bufferIdx++] = texCoordY2;
453
- uiQuadBuffer[bufferIdx++] = params.colorBl;
454
- fQuadBuffer[bufferIdx++] = textureIdx;
455
-
456
- // Lower-Right
457
- fQuadBuffer[bufferIdx++] = rightCornerX;
458
- fQuadBuffer[bufferIdx++] = rightCornerY;
459
- fQuadBuffer[bufferIdx++] = texCoordX2;
460
- fQuadBuffer[bufferIdx++] = texCoordY2;
461
- uiQuadBuffer[bufferIdx++] = params.colorBr;
462
- fQuadBuffer[bufferIdx++] = textureIdx;
463
- }
464
- // Update the length of the current render op
465
- this.curRenderOp.length += WORDS_PER_QUAD;
466
- this.curRenderOp.numQuads++;
467
- this.curBufferIdx = bufferIdx;
468
- }
469
-
470
- /**
471
- * Replace the existing RenderOp with a new one that uses the specified Shader
472
- * and starts at the specified buffer index.
473
- *
474
- * @param shader
475
- * @param bufferIdx
476
- */
477
- private newRenderOp(
478
- shader: WebGlCoreShader,
479
- shaderProps: Record<string, unknown>,
480
- alpha: number,
481
- dimensions: Dimensions,
482
- clippingRect: RectWithValid,
483
- bufferIdx: number,
484
- renderToTexture?: boolean,
485
- parentHasRenderTexture?: boolean,
486
- framebufferDimensions?: Dimensions,
487
- ) {
488
- const curRenderOp = new WebGlCoreRenderOp(
489
- this.glw,
490
- this.options,
491
- this.quadBufferCollection,
492
- shader,
493
- shaderProps,
494
- alpha,
495
- clippingRect,
496
- dimensions,
497
- bufferIdx,
498
- 0, // Z-Index is only used for explictly added Render Ops
499
- renderToTexture,
500
- parentHasRenderTexture,
501
- framebufferDimensions,
502
- );
503
- this.curRenderOp = curRenderOp;
504
- this.renderOps.push(curRenderOp);
505
- }
506
-
507
- /**
508
- * Add a texture to the current RenderOp. If the texture cannot be added to the
509
- * current RenderOp, a new RenderOp will be created and the texture will be added
510
- * to that one.
511
- *
512
- * If the texture cannot be added to the new RenderOp, an error will be thrown.
513
- *
514
- * @param texture
515
- * @param bufferIdx
516
- * @param recursive
517
- * @returns Assigned Texture Index of the texture in the render op
518
- */
519
- private addTexture(
520
- texture: WebGlCoreCtxTexture,
521
- bufferIdx: number,
522
- recursive?: boolean,
523
- ): number {
524
- const { curRenderOp } = this;
525
- assertTruthy(curRenderOp);
526
- const textureIdx = curRenderOp.addTexture(texture);
527
- // TODO: Refactor to be more DRY
528
- if (textureIdx === 0xffffffff) {
529
- if (recursive) {
530
- throw new Error('Unable to add texture to render op');
531
- }
532
-
533
- this.newRenderOp(
534
- curRenderOp.shader,
535
- curRenderOp.shaderProps,
536
- curRenderOp.alpha,
537
- curRenderOp.dimensions,
538
- curRenderOp.clippingRect,
539
- bufferIdx,
540
- );
541
- return this.addTexture(texture, bufferIdx, true);
542
- }
543
- return textureIdx;
544
- }
545
-
546
- /**
547
- * Test if the current Render operation can be reused for the specified parameters.
548
- * @param params
549
- * @returns
550
- */
551
- reuseRenderOp(params: QuadOptions): boolean {
552
- const { shader, shaderProps, parentHasRenderTexture, rtt, clippingRect } =
553
- params;
554
-
555
- const targetShader = shader || this.defaultShader;
556
-
557
- // Switching shader program will require a new render operation
558
- if (this.curRenderOp?.shader !== targetShader) {
559
- return false;
560
- }
561
-
562
- // Switching clipping rect will require a new render operation
563
- if (!compareRect(this.curRenderOp.clippingRect, clippingRect)) {
564
- return false;
565
- }
566
-
567
- // Force new render operation if rendering to texture
568
- // @todo: This needs to be improved, render operations could also be reused
569
- // for rendering to texture
570
- if (parentHasRenderTexture || rtt) {
571
- return false;
572
- }
573
-
574
- // Check if the shader can batch the shader properties
575
- if (
576
- this.curRenderOp.shader !== this.defaultShader &&
577
- (!shaderProps ||
578
- !this.curRenderOp.shader.canBatchShaderProps(
579
- this.curRenderOp.shaderProps,
580
- shaderProps,
581
- ))
582
- ) {
583
- return false;
584
- }
585
-
586
- // Render operation can be reused
587
- return true;
588
- }
589
-
590
- /**
591
- * add RenderOp to the render pipeline
592
- */
593
- addRenderOp(renderable: WebGlCoreRenderOp) {
594
- this.renderOps.push(renderable);
595
- this.curRenderOp = null;
596
- }
597
-
598
- /**
599
- * Render the current set of RenderOps to render to the specified surface.
600
- *
601
- * TODO: 'screen' is the only supported surface at the moment.
602
- *
603
- * @param surface
604
- */
605
- render(surface: 'screen' | CoreContextTexture = 'screen'): void {
606
- const { glw, quadBuffer } = this;
607
-
608
- const arr = new Float32Array(quadBuffer, 0, this.curBufferIdx);
609
-
610
- const buffer = this.quadBufferCollection.getBuffer('a_position') ?? null;
611
- glw.arrayBufferData(buffer, arr, glw.STATIC_DRAW);
612
-
613
- const doLog = false; // idx++ % 100 === 0;
614
- if (doLog) {
615
- console.log('renderOps', this.renderOps.length);
616
- }
617
-
618
- for (let i = 0, length = this.renderOps.length; i < length; i++) {
619
- const renderOp = this.renderOps[i] as WebGlCoreRenderOp;
620
- if (doLog) {
621
- console.log('Quads per operation', renderOp.numQuads);
622
- }
623
- renderOp.draw();
624
- }
625
- this.quadBufferUsage = this.curBufferIdx * arr.BYTES_PER_ELEMENT;
626
- }
627
-
628
- renderToTexture(node: CoreNode) {
629
- for (let i = 0; i < this.rttNodes.length; i++) {
630
- if (this.rttNodes[i] === node) {
631
- return;
632
- }
633
- }
634
-
635
- this.insertRTTNodeInOrder(node);
636
- }
637
-
638
- /**
639
- * Inserts an RTT node into `this.rttNodes` while maintaining the correct rendering order based on hierarchy.
640
- *
641
- * Rendering order for RTT nodes is critical when nested RTT nodes exist in a parent-child relationship.
642
- * Specifically:
643
- * - Child RTT nodes must be rendered before their RTT-enabled parents to ensure proper texture composition.
644
- * - If an RTT node is added and it has existing RTT children, it should be rendered after those children.
645
- *
646
- * This function addresses both cases by:
647
- * 1. **Checking Upwards**: It traverses the node's hierarchy upwards to identify any RTT parent
648
- * already in `rttNodes`. If an RTT parent is found, the new node is placed before this parent.
649
- * 2. **Checking Downwards**: It traverses the node’s children recursively to find any RTT-enabled
650
- * children that are already in `rttNodes`. If such children are found, the new node is inserted
651
- * after the last (highest index) RTT child node.
652
- *
653
- * The final calculated insertion index ensures the new node is positioned in `rttNodes` to respect
654
- * both parent-before-child and child-before-parent rendering rules, preserving the correct order
655
- * for the WebGL renderer.
656
- *
657
- * @param node - The RTT-enabled CoreNode to be added to `rttNodes` in the appropriate hierarchical position.
658
- */
659
- private insertRTTNodeInOrder(node: CoreNode) {
660
- let insertIndex = this.rttNodes.length; // Default to the end of the array
661
-
662
- // 1. Traverse upwards to ensure the node is placed before its RTT parent (if any).
663
- let currentNode: CoreNode = node;
664
- while (currentNode) {
665
- if (!currentNode.parent) {
666
- break;
667
- }
668
-
669
- const parentIndex = this.rttNodes.indexOf(currentNode.parent);
670
- if (parentIndex !== -1) {
671
- // Found an RTT parent in the list; set insertIndex to place node before the parent
672
- insertIndex = parentIndex;
673
- break;
674
- }
675
-
676
- currentNode = currentNode.parent;
677
- }
678
-
679
- // 2. Traverse downwards to ensure the node is placed after any RTT children.
680
- // Look through each child recursively to see if any are already in rttNodes.
681
- const maxChildIndex = this.findMaxChildRTTIndex(node);
682
- if (maxChildIndex !== -1) {
683
- // Adjust insertIndex to be after the last child RTT node
684
- insertIndex = Math.max(insertIndex, maxChildIndex + 1);
685
- }
686
-
687
- // 3. Insert the node at the calculated position
688
- this.rttNodes.splice(insertIndex, 0, node);
689
- }
690
-
691
- // Helper function to find the highest index of any RTT children of a node within rttNodes
692
- private findMaxChildRTTIndex(node: CoreNode): number {
693
- let maxIndex = -1;
694
-
695
- const traverseChildren = (currentNode: CoreNode) => {
696
- const currentIndex = this.rttNodes.indexOf(currentNode);
697
- if (currentIndex !== -1) {
698
- maxIndex = Math.max(maxIndex, currentIndex);
699
- }
700
-
701
- // Recursively check all children of the current node
702
- for (const child of currentNode.children) {
703
- traverseChildren(child);
704
- }
705
- };
706
-
707
- // Start traversal directly with the provided node
708
- traverseChildren(node);
709
-
710
- return maxIndex;
711
- }
712
-
713
- renderRTTNodes() {
714
- const { glw } = this;
715
- const { txManager } = this.stage;
716
-
717
- // Render all associated RTT nodes to their textures
718
- for (let i = 0; i < this.rttNodes.length; i++) {
719
- const node = this.rttNodes[i];
720
-
721
- // Skip nodes that don't have RTT updates
722
- if (!node || !node.hasRTTupdates) {
723
- continue;
724
- }
725
-
726
- // Set the active RTT node to the current node
727
- // So we can prevent rendering children of nested RTT nodes
728
- this.activeRttNode = node;
729
-
730
- assertTruthy(node.texture, 'RTT node missing texture');
731
- const ctxTexture = node.texture.ctxTexture;
732
- assertTruthy(ctxTexture instanceof WebGlCoreCtxRenderTexture);
733
- this.renderToTextureActive = true;
734
-
735
- // Bind the the texture's framebuffer
736
- glw.bindFramebuffer(ctxTexture.framebuffer);
737
-
738
- glw.viewport(0, 0, ctxTexture.w, ctxTexture.h);
739
- // Set the clear color to transparent
740
- glw.clearColor(0, 0, 0, 0);
741
- glw.clear();
742
-
743
- // Render all associated quads to the texture
744
- for (let i = 0; i < node.children.length; i++) {
745
- const child = node.children[i];
746
-
747
- if (!child) {
748
- continue;
749
- }
750
-
751
- this.stage.addQuads(child);
752
- child.hasRTTupdates = false;
753
- }
754
-
755
- // Render all associated quads to the texture
756
- this.render();
757
-
758
- // Reset render operations
759
- this.renderOps.length = 0;
760
- node.hasRTTupdates = false;
761
- }
762
-
763
- const clearColor = this.clearColor.normalized;
764
- // Restore the default clear color
765
- glw.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
766
-
767
- // Bind the default framebuffer
768
- glw.bindFramebuffer(null);
769
-
770
- glw.viewport(0, 0, this.glw.canvas.width, this.glw.canvas.height);
771
- this.renderToTextureActive = false;
772
- }
773
-
774
- removeRTTNode(node: CoreNode) {
775
- const index = this.rttNodes.indexOf(node);
776
- if (index === -1) {
777
- return;
778
- }
779
- this.rttNodes.splice(index, 1);
780
- }
781
-
782
- getBufferInfo(): BufferInfo | null {
783
- const bufferInfo: BufferInfo = {
784
- totalAvailable: this.stage.options.quadBufferSize,
785
- totalUsed: this.quadBufferUsage,
786
- };
787
- return bufferInfo;
788
- }
789
-
790
- override getDefShaderCtr(): BaseShaderController {
791
- return this.defShaderCtrl;
792
- }
793
-
794
- /**
795
- * Updates the WebGL context's clear color and clears the color buffer.
796
- *
797
- * @param color - The color to set as the clear color, represented as a 32-bit integer.
798
- */
799
- updateClearColor(color: number) {
800
- if (this.clearColor.raw === color) {
801
- return;
802
- }
803
- const glw = this.glw;
804
- const normalizedColor = getNormalizedRgbaComponents(color);
805
- glw.clearColor(
806
- normalizedColor[0],
807
- normalizedColor[1],
808
- normalizedColor[2],
809
- normalizedColor[3],
810
- );
811
- this.clearColor = {
812
- raw: color,
813
- normalized: normalizedColor,
814
- };
815
- glw.clear();
816
- }
817
- }
1
+ /*
2
+ * If not stated otherwise in this file or this component's LICENSE file the
3
+ * following copyright and licenses apply:
4
+ *
5
+ * Copyright 2023 Comcast Cable Communications Management, LLC.
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the License);
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ import { assertTruthy, createWebGLContext, hasOwn } from '../../../utils.js';
21
+ import {
22
+ CoreRenderer,
23
+ type BufferInfo,
24
+ type CoreRendererOptions,
25
+ type QuadOptions,
26
+ } from '../CoreRenderer.js';
27
+ import { WebGlCoreRenderOp } from './WebGlCoreRenderOp.js';
28
+ import type { CoreContextTexture } from '../CoreContextTexture.js';
29
+ import {
30
+ createIndexBuffer,
31
+ type CoreWebGlParameters,
32
+ type CoreWebGlExtensions,
33
+ getWebGlParameters,
34
+ getWebGlExtensions,
35
+ type WebGlColor,
36
+ } from './internal/RendererUtils.js';
37
+ import { WebGlCoreCtxTexture } from './WebGlCoreCtxTexture.js';
38
+ import { Texture, TextureType } from '../../textures/Texture.js';
39
+ import { SubTexture } from '../../textures/SubTexture.js';
40
+ import { WebGlCoreCtxSubTexture } from './WebGlCoreCtxSubTexture.js';
41
+ import { CoreShaderManager } from '../../CoreShaderManager.js';
42
+ import { BufferCollection } from './internal/BufferCollection.js';
43
+ import {
44
+ compareRect,
45
+ getNormalizedRgbaComponents,
46
+ type RectWithValid,
47
+ } from '../../lib/utils.js';
48
+ import type { Dimensions } from '../../../common/CommonTypes.js';
49
+ import { WebGlCoreShader } from './WebGlCoreShader.js';
50
+ import { WebGlContextWrapper } from '../../lib/WebGlContextWrapper.js';
51
+ import { RenderTexture } from '../../textures/RenderTexture.js';
52
+ import type { CoreNode } from '../../CoreNode.js';
53
+ import { WebGlCoreCtxRenderTexture } from './WebGlCoreCtxRenderTexture.js';
54
+ import type { BaseShaderController } from '../../../main-api/ShaderController.js';
55
+
56
+ const WORDS_PER_QUAD = 24;
57
+ // const BYTES_PER_QUAD = WORDS_PER_QUAD * 4;
58
+
59
+ export type WebGlCoreRendererOptions = CoreRendererOptions;
60
+
61
+ interface CoreWebGlSystem {
62
+ parameters: CoreWebGlParameters;
63
+ extensions: CoreWebGlExtensions;
64
+ }
65
+
66
+ export class WebGlCoreRenderer extends CoreRenderer {
67
+ //// WebGL Native Context and Data
68
+ glw: WebGlContextWrapper;
69
+ system: CoreWebGlSystem;
70
+
71
+ //// Persistent data
72
+ quadBuffer: ArrayBuffer;
73
+ fQuadBuffer: Float32Array;
74
+ uiQuadBuffer: Uint32Array;
75
+ renderOps: WebGlCoreRenderOp[] = [];
76
+
77
+ //// Render Op / Buffer Filling State
78
+ curBufferIdx = 0;
79
+ curRenderOp: WebGlCoreRenderOp | null = null;
80
+ override rttNodes: CoreNode[] = [];
81
+ activeRttNode: CoreNode | null = null;
82
+
83
+ //// Default Shader
84
+ defShaderCtrl: BaseShaderController;
85
+ defaultShader: WebGlCoreShader;
86
+ quadBufferCollection: BufferCollection;
87
+
88
+ clearColor: WebGlColor = {
89
+ raw: 0x00000000,
90
+ normalized: [0, 0, 0, 0],
91
+ };
92
+
93
+ /**
94
+ * White pixel texture used by default when no texture is specified.
95
+ */
96
+
97
+ quadBufferUsage = 0;
98
+ /**
99
+ * Whether the renderer is currently rendering to a texture.
100
+ */
101
+ public renderToTextureActive = false;
102
+
103
+ constructor(options: WebGlCoreRendererOptions) {
104
+ super(options);
105
+
106
+ this.quadBuffer = new ArrayBuffer(this.stage.options.quadBufferSize);
107
+ this.fQuadBuffer = new Float32Array(this.quadBuffer);
108
+ this.uiQuadBuffer = new Uint32Array(this.quadBuffer);
109
+
110
+ this.mode = 'webgl';
111
+
112
+ const { canvas, clearColor, bufferMemory } = options;
113
+
114
+ const gl = createWebGLContext(
115
+ canvas,
116
+ options.forceWebGL2,
117
+ options.contextSpy,
118
+ );
119
+ const glw = (this.glw = new WebGlContextWrapper(gl));
120
+ glw.viewport(0, 0, canvas.width, canvas.height);
121
+
122
+ this.updateClearColor(clearColor);
123
+
124
+ glw.setBlend(true);
125
+ glw.blendFunc(glw.ONE, glw.ONE_MINUS_SRC_ALPHA);
126
+
127
+ createIndexBuffer(glw, bufferMemory);
128
+
129
+ this.system = {
130
+ parameters: getWebGlParameters(this.glw),
131
+ extensions: getWebGlExtensions(this.glw),
132
+ };
133
+ this.shManager.renderer = this;
134
+ this.defShaderCtrl = this.shManager.loadShader('DefaultShader');
135
+ this.defaultShader = this.defShaderCtrl.shader as WebGlCoreShader;
136
+ const quadBuffer = glw.createBuffer();
137
+ assertTruthy(quadBuffer);
138
+ const stride = 6 * Float32Array.BYTES_PER_ELEMENT;
139
+ this.quadBufferCollection = new BufferCollection([
140
+ {
141
+ buffer: quadBuffer,
142
+ attributes: {
143
+ a_position: {
144
+ name: 'a_position',
145
+ size: 2, // 2 components per iteration
146
+ type: glw.FLOAT, // the data is 32bit floats
147
+ normalized: false, // don't normalize the data
148
+ stride, // 0 = move forward size * sizeof(type) each iteration to get the next position
149
+ offset: 0, // start at the beginning of the buffer
150
+ },
151
+ a_textureCoordinate: {
152
+ name: 'a_textureCoordinate',
153
+ size: 2,
154
+ type: glw.FLOAT,
155
+ normalized: false,
156
+ stride,
157
+ offset: 2 * Float32Array.BYTES_PER_ELEMENT,
158
+ },
159
+ a_color: {
160
+ name: 'a_color',
161
+ size: 4,
162
+ type: glw.UNSIGNED_BYTE,
163
+ normalized: true,
164
+ stride,
165
+ offset: 4 * Float32Array.BYTES_PER_ELEMENT,
166
+ },
167
+ a_textureIndex: {
168
+ name: 'a_textureIndex',
169
+ size: 1,
170
+ type: glw.FLOAT,
171
+ normalized: false,
172
+ stride,
173
+ offset: 5 * Float32Array.BYTES_PER_ELEMENT,
174
+ },
175
+ },
176
+ },
177
+ ]);
178
+ }
179
+
180
+ reset() {
181
+ const { glw } = this;
182
+ this.curBufferIdx = 0;
183
+ this.curRenderOp = null;
184
+ this.renderOps.length = 0;
185
+ glw.setScissorTest(false);
186
+ glw.clear();
187
+ }
188
+
189
+ override getShaderManager(): CoreShaderManager {
190
+ return this.shManager;
191
+ }
192
+
193
+ override createCtxTexture(textureSource: Texture): CoreContextTexture {
194
+ if (textureSource instanceof SubTexture) {
195
+ return new WebGlCoreCtxSubTexture(
196
+ this.glw,
197
+ this.txMemManager,
198
+ textureSource,
199
+ );
200
+ } else if (textureSource instanceof RenderTexture) {
201
+ return new WebGlCoreCtxRenderTexture(
202
+ this.glw,
203
+ this.txMemManager,
204
+ textureSource,
205
+ );
206
+ }
207
+ return new WebGlCoreCtxTexture(this.glw, this.txMemManager, textureSource);
208
+ }
209
+
210
+ /**
211
+ * This function adds a quad (a rectangle composed of two triangles) to the WebGL rendering pipeline.
212
+ *
213
+ * It takes a set of options that define the quad's properties, such as its dimensions, colors, texture, shader, and transformation matrix.
214
+ * The function first updates the shader properties with the current dimensions if necessary, then sets the default texture if none is provided.
215
+ * It then checks if a new render operation is needed, based on the current shader and clipping rectangle.
216
+ * If a new render operation is needed, it creates one and updates the current render operation.
217
+ * The function then adjusts the texture coordinates based on the texture options and adds the texture to the texture manager.
218
+ *
219
+ * Finally, it calculates the vertices for the quad, taking into account any transformations, and adds them to the quad buffer.
220
+ * The function updates the length and number of quads in the current render operation, and updates the current buffer index.
221
+ */
222
+ addQuad(params: QuadOptions) {
223
+ const { fQuadBuffer, uiQuadBuffer } = this;
224
+ let texture = params.texture;
225
+
226
+ assertTruthy(texture !== null, 'Texture is required');
227
+
228
+ /**
229
+ * If the shader props contain any automatic properties, update it with the
230
+ * current dimensions and or alpha that will be used to render the quad.
231
+ */
232
+ if (params.shaderProps !== null) {
233
+ if (hasOwn(params.shaderProps, '$dimensions') == true) {
234
+ const dimensions = params.shaderProps.$dimensions as Dimensions;
235
+ dimensions.width = params.width;
236
+ dimensions.height = params.height;
237
+ }
238
+
239
+ if (hasOwn(params.shaderProps, '$alpha') === true) {
240
+ params.shaderProps.$alpha = params.alpha;
241
+ }
242
+ }
243
+
244
+ let { curBufferIdx: bufferIdx, curRenderOp } = this;
245
+ const targetDims = { width: -1, height: -1 };
246
+ targetDims.width = params.width;
247
+ targetDims.height = params.height;
248
+
249
+ const targetShader =
250
+ (params.shader as WebGlCoreShader) || this.defaultShader;
251
+ assertTruthy(
252
+ targetShader.getUniformLocation !== undefined,
253
+ 'Invalid WebGL shader',
254
+ );
255
+
256
+ if (this.reuseRenderOp(params) === false) {
257
+ this.newRenderOp(
258
+ targetShader,
259
+ params.shaderProps as Record<string, unknown>,
260
+ params.alpha,
261
+ targetDims,
262
+ params.clippingRect,
263
+ bufferIdx,
264
+ params.rtt,
265
+ params.parentHasRenderTexture,
266
+ params.framebufferDimensions,
267
+ );
268
+ curRenderOp = this.curRenderOp;
269
+ assertTruthy(curRenderOp);
270
+ }
271
+
272
+ let texCoordX1 = 0;
273
+ let texCoordY1 = 0;
274
+ let texCoordX2 = 1;
275
+ let texCoordY2 = 1;
276
+
277
+ if (texture.type === TextureType.subTexture) {
278
+ const {
279
+ x: tx,
280
+ y: ty,
281
+ width: tw,
282
+ height: th,
283
+ } = (texture as SubTexture).props;
284
+ const { width: parentW = 0, height: parentH = 0 } = (
285
+ texture as SubTexture
286
+ ).parentTexture.dimensions || { width: 0, height: 0 };
287
+ texCoordX1 = tx / parentW;
288
+ texCoordX2 = texCoordX1 + tw / parentW;
289
+ texCoordY1 = ty / parentH;
290
+ texCoordY2 = texCoordY1 + th / parentH;
291
+ texture = (texture as SubTexture).parentTexture;
292
+ }
293
+
294
+ if (
295
+ texture.type === TextureType.image &&
296
+ params.textureOptions !== null &&
297
+ params.textureOptions.resizeMode !== undefined &&
298
+ texture.dimensions !== null
299
+ ) {
300
+ const resizeMode = params.textureOptions.resizeMode;
301
+ const { width: tw, height: th } = texture.dimensions;
302
+ if (resizeMode.type === 'cover') {
303
+ const scaleX = params.width / tw;
304
+ const scaleY = params.height / th;
305
+ const scale = Math.max(scaleX, scaleY);
306
+ const precision = 1 / scale;
307
+ // Determine based on width
308
+ if (scale && scaleX && scaleX < scale) {
309
+ const desiredSize = precision * params.width;
310
+ texCoordX1 = (1 - desiredSize / tw) * (resizeMode.clipX ?? 0.5);
311
+ texCoordX2 = texCoordX1 + desiredSize / tw;
312
+ }
313
+ // Determine based on height
314
+ if (scale && scaleY && scaleY < scale) {
315
+ const desiredSize = precision * params.height;
316
+ texCoordY1 = (1 - desiredSize / th) * (resizeMode.clipY ?? 0.5);
317
+ texCoordY2 = texCoordY1 + desiredSize / th;
318
+ }
319
+ }
320
+ }
321
+
322
+ // Flip texture coordinates if dictated by texture options
323
+ let flipY = 0;
324
+ if (params.textureOptions !== null) {
325
+ if (params.textureOptions.flipX === true) {
326
+ [texCoordX1, texCoordX2] = [texCoordX2, texCoordX1];
327
+ }
328
+
329
+ // convert to integer for bitwise operation below
330
+ flipY = +(params.textureOptions.flipY || false);
331
+ }
332
+
333
+ // Eitherone should be true
334
+ if (flipY ^ +(texture.type === TextureType.renderToTexture)) {
335
+ [texCoordY1, texCoordY2] = [texCoordY2, texCoordY1];
336
+ }
337
+
338
+ const ctxTexture = texture.ctxTexture as WebGlCoreCtxTexture;
339
+ assertTruthy(ctxTexture instanceof WebGlCoreCtxTexture);
340
+ const textureIdx = this.addTexture(ctxTexture, bufferIdx);
341
+
342
+ assertTruthy(this.curRenderOp !== null);
343
+ if (params.renderCoords) {
344
+ // Upper-Left
345
+ fQuadBuffer[bufferIdx++] = params.renderCoords.x1; // vertexX
346
+ fQuadBuffer[bufferIdx++] = params.renderCoords.y1; // vertexY
347
+ fQuadBuffer[bufferIdx++] = texCoordX1; // texCoordX
348
+ fQuadBuffer[bufferIdx++] = texCoordY1; // texCoordY
349
+ uiQuadBuffer[bufferIdx++] = params.colorTl; // color
350
+ fQuadBuffer[bufferIdx++] = textureIdx; // texIndex
351
+
352
+ // Upper-Right
353
+ fQuadBuffer[bufferIdx++] = params.renderCoords.x2;
354
+ fQuadBuffer[bufferIdx++] = params.renderCoords.y2;
355
+ fQuadBuffer[bufferIdx++] = texCoordX2;
356
+ fQuadBuffer[bufferIdx++] = texCoordY1;
357
+ uiQuadBuffer[bufferIdx++] = params.colorTr;
358
+ fQuadBuffer[bufferIdx++] = textureIdx;
359
+
360
+ // Lower-Left
361
+ fQuadBuffer[bufferIdx++] = params.renderCoords.x4;
362
+ fQuadBuffer[bufferIdx++] = params.renderCoords.y4;
363
+ fQuadBuffer[bufferIdx++] = texCoordX1;
364
+ fQuadBuffer[bufferIdx++] = texCoordY2;
365
+ uiQuadBuffer[bufferIdx++] = params.colorBl;
366
+ fQuadBuffer[bufferIdx++] = textureIdx;
367
+
368
+ // Lower-Right
369
+ fQuadBuffer[bufferIdx++] = params.renderCoords.x3;
370
+ fQuadBuffer[bufferIdx++] = params.renderCoords.y3;
371
+ fQuadBuffer[bufferIdx++] = texCoordX2;
372
+ fQuadBuffer[bufferIdx++] = texCoordY2;
373
+ uiQuadBuffer[bufferIdx++] = params.colorBr;
374
+ fQuadBuffer[bufferIdx++] = textureIdx;
375
+ } else if (params.tb !== 0 || params.tc !== 0) {
376
+ // Upper-Left
377
+ fQuadBuffer[bufferIdx++] = params.tx; // vertexX
378
+ fQuadBuffer[bufferIdx++] = params.ty; // vertexY
379
+ fQuadBuffer[bufferIdx++] = texCoordX1; // texCoordX
380
+ fQuadBuffer[bufferIdx++] = texCoordY1; // texCoordY
381
+ uiQuadBuffer[bufferIdx++] = params.colorTl; // color
382
+ fQuadBuffer[bufferIdx++] = textureIdx; // texIndex
383
+
384
+ // Upper-Right
385
+ fQuadBuffer[bufferIdx++] = params.tx + params.width * params.ta;
386
+ fQuadBuffer[bufferIdx++] = params.ty + params.width * params.tc;
387
+ fQuadBuffer[bufferIdx++] = texCoordX2;
388
+ fQuadBuffer[bufferIdx++] = texCoordY1;
389
+ uiQuadBuffer[bufferIdx++] = params.colorTr;
390
+ fQuadBuffer[bufferIdx++] = textureIdx;
391
+
392
+ // Lower-Left
393
+ fQuadBuffer[bufferIdx++] = params.tx + params.height * params.tb;
394
+ fQuadBuffer[bufferIdx++] = params.ty + params.height * params.td;
395
+ fQuadBuffer[bufferIdx++] = texCoordX1;
396
+ fQuadBuffer[bufferIdx++] = texCoordY2;
397
+ uiQuadBuffer[bufferIdx++] = params.colorBl;
398
+ fQuadBuffer[bufferIdx++] = textureIdx;
399
+
400
+ // Lower-Right
401
+ fQuadBuffer[bufferIdx++] =
402
+ params.tx + params.width * params.ta + params.height * params.tb;
403
+ fQuadBuffer[bufferIdx++] =
404
+ params.ty + params.width * params.tc + params.height * params.td;
405
+ fQuadBuffer[bufferIdx++] = texCoordX2;
406
+ fQuadBuffer[bufferIdx++] = texCoordY2;
407
+ uiQuadBuffer[bufferIdx++] = params.colorBr;
408
+ fQuadBuffer[bufferIdx++] = textureIdx;
409
+ } else {
410
+ // Calculate the right corner of the quad
411
+ // multiplied by the scale
412
+ const rightCornerX = params.tx + params.width * params.ta;
413
+ const rightCornerY = params.ty + params.height * params.td;
414
+
415
+ // Upper-Left
416
+ fQuadBuffer[bufferIdx++] = params.tx; // vertexX
417
+ fQuadBuffer[bufferIdx++] = params.ty; // vertexY
418
+ fQuadBuffer[bufferIdx++] = texCoordX1; // texCoordX
419
+ fQuadBuffer[bufferIdx++] = texCoordY1; // texCoordY
420
+ uiQuadBuffer[bufferIdx++] = params.colorTl; // color
421
+ fQuadBuffer[bufferIdx++] = textureIdx; // texIndex
422
+
423
+ // Upper-Right
424
+ fQuadBuffer[bufferIdx++] = rightCornerX;
425
+ fQuadBuffer[bufferIdx++] = params.ty;
426
+ fQuadBuffer[bufferIdx++] = texCoordX2;
427
+ fQuadBuffer[bufferIdx++] = texCoordY1;
428
+ uiQuadBuffer[bufferIdx++] = params.colorTr;
429
+ fQuadBuffer[bufferIdx++] = textureIdx;
430
+
431
+ // Lower-Left
432
+ fQuadBuffer[bufferIdx++] = params.tx;
433
+ fQuadBuffer[bufferIdx++] = rightCornerY;
434
+ fQuadBuffer[bufferIdx++] = texCoordX1;
435
+ fQuadBuffer[bufferIdx++] = texCoordY2;
436
+ uiQuadBuffer[bufferIdx++] = params.colorBl;
437
+ fQuadBuffer[bufferIdx++] = textureIdx;
438
+
439
+ // Lower-Right
440
+ fQuadBuffer[bufferIdx++] = rightCornerX;
441
+ fQuadBuffer[bufferIdx++] = rightCornerY;
442
+ fQuadBuffer[bufferIdx++] = texCoordX2;
443
+ fQuadBuffer[bufferIdx++] = texCoordY2;
444
+ uiQuadBuffer[bufferIdx++] = params.colorBr;
445
+ fQuadBuffer[bufferIdx++] = textureIdx;
446
+ }
447
+ // Update the length of the current render op
448
+ this.curRenderOp.length += WORDS_PER_QUAD;
449
+ this.curRenderOp.numQuads++;
450
+ this.curBufferIdx = bufferIdx;
451
+ }
452
+
453
+ /**
454
+ * Replace the existing RenderOp with a new one that uses the specified Shader
455
+ * and starts at the specified buffer index.
456
+ *
457
+ * @param shader
458
+ * @param bufferIdx
459
+ */
460
+ private newRenderOp(
461
+ shader: WebGlCoreShader,
462
+ shaderProps: Record<string, unknown>,
463
+ alpha: number,
464
+ dimensions: Dimensions,
465
+ clippingRect: RectWithValid,
466
+ bufferIdx: number,
467
+ renderToTexture?: boolean,
468
+ parentHasRenderTexture?: boolean,
469
+ framebufferDimensions?: Dimensions,
470
+ ) {
471
+ const curRenderOp = new WebGlCoreRenderOp(
472
+ this.glw,
473
+ this.options,
474
+ this.quadBufferCollection,
475
+ shader,
476
+ shaderProps,
477
+ alpha,
478
+ clippingRect,
479
+ dimensions,
480
+ bufferIdx,
481
+ 0, // Z-Index is only used for explictly added Render Ops
482
+ renderToTexture,
483
+ parentHasRenderTexture,
484
+ framebufferDimensions,
485
+ );
486
+ this.curRenderOp = curRenderOp;
487
+ this.renderOps.push(curRenderOp);
488
+ }
489
+
490
+ /**
491
+ * Add a texture to the current RenderOp. If the texture cannot be added to the
492
+ * current RenderOp, a new RenderOp will be created and the texture will be added
493
+ * to that one.
494
+ *
495
+ * If the texture cannot be added to the new RenderOp, an error will be thrown.
496
+ *
497
+ * @param texture
498
+ * @param bufferIdx
499
+ * @param recursive
500
+ * @returns Assigned Texture Index of the texture in the render op
501
+ */
502
+ private addTexture(
503
+ texture: WebGlCoreCtxTexture,
504
+ bufferIdx: number,
505
+ recursive?: boolean,
506
+ ): number {
507
+ const { curRenderOp } = this;
508
+ assertTruthy(curRenderOp);
509
+ const textureIdx = curRenderOp.addTexture(texture);
510
+ // TODO: Refactor to be more DRY
511
+ if (textureIdx === 0xffffffff) {
512
+ if (recursive) {
513
+ throw new Error('Unable to add texture to render op');
514
+ }
515
+
516
+ this.newRenderOp(
517
+ curRenderOp.shader,
518
+ curRenderOp.shaderProps,
519
+ curRenderOp.alpha,
520
+ curRenderOp.dimensions,
521
+ curRenderOp.clippingRect,
522
+ bufferIdx,
523
+ );
524
+ return this.addTexture(texture, bufferIdx, true);
525
+ }
526
+ return textureIdx;
527
+ }
528
+
529
+ /**
530
+ * Test if the current Render operation can be reused for the specified parameters.
531
+ * @param params
532
+ * @returns
533
+ */
534
+ reuseRenderOp(params: QuadOptions): boolean {
535
+ const { shader, shaderProps, parentHasRenderTexture, rtt, clippingRect } =
536
+ params;
537
+
538
+ const targetShader = shader || this.defaultShader;
539
+
540
+ // Switching shader program will require a new render operation
541
+ if (this.curRenderOp?.shader !== targetShader) {
542
+ return false;
543
+ }
544
+
545
+ // Switching clipping rect will require a new render operation
546
+ if (!compareRect(this.curRenderOp.clippingRect, clippingRect)) {
547
+ return false;
548
+ }
549
+
550
+ // Force new render operation if rendering to texture
551
+ // @todo: This needs to be improved, render operations could also be reused
552
+ // for rendering to texture
553
+ if (parentHasRenderTexture || rtt) {
554
+ return false;
555
+ }
556
+
557
+ // Check if the shader can batch the shader properties
558
+ if (
559
+ this.curRenderOp.shader !== this.defaultShader &&
560
+ (!shaderProps ||
561
+ !this.curRenderOp.shader.canBatchShaderProps(
562
+ this.curRenderOp.shaderProps,
563
+ shaderProps,
564
+ ))
565
+ ) {
566
+ return false;
567
+ }
568
+
569
+ // Render operation can be reused
570
+ return true;
571
+ }
572
+
573
+ /**
574
+ * add RenderOp to the render pipeline
575
+ */
576
+ addRenderOp(renderable: WebGlCoreRenderOp) {
577
+ this.renderOps.push(renderable);
578
+ this.curRenderOp = null;
579
+ }
580
+
581
+ /**
582
+ * Render the current set of RenderOps to render to the specified surface.
583
+ *
584
+ * TODO: 'screen' is the only supported surface at the moment.
585
+ *
586
+ * @param surface
587
+ */
588
+ render(surface: 'screen' | CoreContextTexture = 'screen'): void {
589
+ const { glw, quadBuffer } = this;
590
+
591
+ const arr = new Float32Array(quadBuffer, 0, this.curBufferIdx);
592
+
593
+ const buffer = this.quadBufferCollection.getBuffer('a_position') ?? null;
594
+ glw.arrayBufferData(buffer, arr, glw.STATIC_DRAW);
595
+
596
+ const doLog = false; // idx++ % 100 === 0;
597
+ if (doLog) {
598
+ console.log('renderOps', this.renderOps.length);
599
+ }
600
+
601
+ for (let i = 0, length = this.renderOps.length; i < length; i++) {
602
+ const renderOp = this.renderOps[i] as WebGlCoreRenderOp;
603
+ if (doLog) {
604
+ console.log('Quads per operation', renderOp.numQuads);
605
+ }
606
+ renderOp.draw();
607
+ }
608
+ this.quadBufferUsage = this.curBufferIdx * arr.BYTES_PER_ELEMENT;
609
+ }
610
+
611
+ renderToTexture(node: CoreNode) {
612
+ for (let i = 0; i < this.rttNodes.length; i++) {
613
+ if (this.rttNodes[i] === node) {
614
+ return;
615
+ }
616
+ }
617
+
618
+ this.insertRTTNodeInOrder(node);
619
+ }
620
+
621
+ /**
622
+ * Inserts an RTT node into `this.rttNodes` while maintaining the correct rendering order based on hierarchy.
623
+ *
624
+ * Rendering order for RTT nodes is critical when nested RTT nodes exist in a parent-child relationship.
625
+ * Specifically:
626
+ * - Child RTT nodes must be rendered before their RTT-enabled parents to ensure proper texture composition.
627
+ * - If an RTT node is added and it has existing RTT children, it should be rendered after those children.
628
+ *
629
+ * This function addresses both cases by:
630
+ * 1. **Checking Upwards**: It traverses the node's hierarchy upwards to identify any RTT parent
631
+ * already in `rttNodes`. If an RTT parent is found, the new node is placed before this parent.
632
+ * 2. **Checking Downwards**: It traverses the node’s children recursively to find any RTT-enabled
633
+ * children that are already in `rttNodes`. If such children are found, the new node is inserted
634
+ * after the last (highest index) RTT child node.
635
+ *
636
+ * The final calculated insertion index ensures the new node is positioned in `rttNodes` to respect
637
+ * both parent-before-child and child-before-parent rendering rules, preserving the correct order
638
+ * for the WebGL renderer.
639
+ *
640
+ * @param node - The RTT-enabled CoreNode to be added to `rttNodes` in the appropriate hierarchical position.
641
+ */
642
+ private insertRTTNodeInOrder(node: CoreNode) {
643
+ let insertIndex = this.rttNodes.length; // Default to the end of the array
644
+
645
+ // 1. Traverse upwards to ensure the node is placed before its RTT parent (if any).
646
+ let currentNode: CoreNode = node;
647
+ while (currentNode) {
648
+ if (!currentNode.parent) {
649
+ break;
650
+ }
651
+
652
+ const parentIndex = this.rttNodes.indexOf(currentNode.parent);
653
+ if (parentIndex !== -1) {
654
+ // Found an RTT parent in the list; set insertIndex to place node before the parent
655
+ insertIndex = parentIndex;
656
+ break;
657
+ }
658
+
659
+ currentNode = currentNode.parent;
660
+ }
661
+
662
+ // 2. Traverse downwards to ensure the node is placed after any RTT children.
663
+ // Look through each child recursively to see if any are already in rttNodes.
664
+ const maxChildIndex = this.findMaxChildRTTIndex(node);
665
+ if (maxChildIndex !== -1) {
666
+ // Adjust insertIndex to be after the last child RTT node
667
+ insertIndex = Math.max(insertIndex, maxChildIndex + 1);
668
+ }
669
+
670
+ // 3. Insert the node at the calculated position
671
+ this.rttNodes.splice(insertIndex, 0, node);
672
+ }
673
+
674
+ // Helper function to find the highest index of any RTT children of a node within rttNodes
675
+ private findMaxChildRTTIndex(node: CoreNode): number {
676
+ let maxIndex = -1;
677
+
678
+ const traverseChildren = (currentNode: CoreNode) => {
679
+ const currentIndex = this.rttNodes.indexOf(currentNode);
680
+ if (currentIndex !== -1) {
681
+ maxIndex = Math.max(maxIndex, currentIndex);
682
+ }
683
+
684
+ // Recursively check all children of the current node
685
+ for (const child of currentNode.children) {
686
+ traverseChildren(child);
687
+ }
688
+ };
689
+
690
+ // Start traversal directly with the provided node
691
+ traverseChildren(node);
692
+
693
+ return maxIndex;
694
+ }
695
+
696
+ renderRTTNodes() {
697
+ const { glw } = this;
698
+ const { txManager } = this.stage;
699
+
700
+ // Render all associated RTT nodes to their textures
701
+ for (let i = 0; i < this.rttNodes.length; i++) {
702
+ const node = this.rttNodes[i];
703
+
704
+ // Skip nodes that don't have RTT updates
705
+ if (!node || !node.hasRTTupdates) {
706
+ continue;
707
+ }
708
+
709
+ if (!node.texture || !node.texture.ctxTexture) {
710
+ console.warn('Texture not loaded for RTT node', node);
711
+ continue;
712
+ }
713
+
714
+ // Set the active RTT node to the current node
715
+ // So we can prevent rendering children of nested RTT nodes
716
+ this.activeRttNode = node;
717
+
718
+ assertTruthy(node.texture, 'RTT node missing texture');
719
+ const ctxTexture = node.texture.ctxTexture;
720
+ assertTruthy(ctxTexture instanceof WebGlCoreCtxRenderTexture);
721
+ this.renderToTextureActive = true;
722
+
723
+ // Bind the the texture's framebuffer
724
+ glw.bindFramebuffer(ctxTexture.framebuffer);
725
+
726
+ glw.viewport(0, 0, ctxTexture.w, ctxTexture.h);
727
+ // Set the clear color to transparent
728
+ glw.clearColor(0, 0, 0, 0);
729
+ glw.clear();
730
+
731
+ // Render all associated quads to the texture
732
+ for (let i = 0; i < node.children.length; i++) {
733
+ const child = node.children[i];
734
+
735
+ if (!child) {
736
+ continue;
737
+ }
738
+
739
+ this.stage.addQuads(child);
740
+ child.hasRTTupdates = false;
741
+ }
742
+
743
+ // Render all associated quads to the texture
744
+ this.render();
745
+
746
+ // Reset render operations
747
+ this.renderOps.length = 0;
748
+ node.hasRTTupdates = false;
749
+ }
750
+
751
+ const clearColor = this.clearColor.normalized;
752
+ // Restore the default clear color
753
+ glw.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
754
+
755
+ // Bind the default framebuffer
756
+ glw.bindFramebuffer(null);
757
+
758
+ glw.viewport(0, 0, this.glw.canvas.width, this.glw.canvas.height);
759
+ this.renderToTextureActive = false;
760
+ }
761
+
762
+ removeRTTNode(node: CoreNode) {
763
+ const index = this.rttNodes.indexOf(node);
764
+ if (index === -1) {
765
+ return;
766
+ }
767
+ this.rttNodes.splice(index, 1);
768
+ }
769
+
770
+ getBufferInfo(): BufferInfo | null {
771
+ const bufferInfo: BufferInfo = {
772
+ totalAvailable: this.stage.options.quadBufferSize,
773
+ totalUsed: this.quadBufferUsage,
774
+ };
775
+ return bufferInfo;
776
+ }
777
+
778
+ override getDefShaderCtr(): BaseShaderController {
779
+ return this.defShaderCtrl;
780
+ }
781
+
782
+ /**
783
+ * Updates the WebGL context's clear color and clears the color buffer.
784
+ *
785
+ * @param color - The color to set as the clear color, represented as a 32-bit integer.
786
+ */
787
+ updateClearColor(color: number) {
788
+ if (this.clearColor.raw === color) {
789
+ return;
790
+ }
791
+ const glw = this.glw;
792
+ const normalizedColor = getNormalizedRgbaComponents(color);
793
+ glw.clearColor(
794
+ normalizedColor[0],
795
+ normalizedColor[1],
796
+ normalizedColor[2],
797
+ normalizedColor[3],
798
+ );
799
+ this.clearColor = {
800
+ raw: color,
801
+ normalized: normalizedColor,
802
+ };
803
+ glw.clear();
804
+ }
805
+ }