@luma.gl/engine 9.0.0-beta.4 → 9.0.0-beta.5

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 (78) hide show
  1. package/dist/animation/key-frames.js +54 -54
  2. package/dist/animation/timeline.js +95 -100
  3. package/dist/animation-loop/animation-loop-template.js +17 -5
  4. package/dist/animation-loop/animation-loop.js +425 -356
  5. package/dist/animation-loop/animation-props.js +0 -1
  6. package/dist/animation-loop/make-animation-loop.js +27 -25
  7. package/dist/debug/copy-texture-to-image.js +39 -43
  8. package/dist/debug/debug-framebuffer.js +43 -39
  9. package/dist/debug/debug-shader-layout.js +24 -25
  10. package/dist/debug/pixel-data-utils.js +33 -36
  11. package/dist/dist.dev.js +3784 -8643
  12. package/dist/geometries/cone-geometry.js +12 -18
  13. package/dist/geometries/cube-geometry.js +189 -62
  14. package/dist/geometries/cylinder-geometry.js +10 -15
  15. package/dist/geometries/ico-sphere-geometry.js +142 -161
  16. package/dist/geometries/plane-geometry.js +94 -112
  17. package/dist/geometries/sphere-geometry.js +77 -96
  18. package/dist/geometries/truncated-cone-geometry.js +100 -118
  19. package/dist/geometry/geometry-table.js +0 -1
  20. package/dist/geometry/geometry-utils.js +35 -32
  21. package/dist/geometry/geometry.js +77 -71
  22. package/dist/geometry/gpu-geometry.js +80 -99
  23. package/dist/geometry/gpu-table.js +41 -1
  24. package/dist/index.cjs +80 -127
  25. package/dist/index.cjs.map +7 -0
  26. package/dist/index.js +27 -24
  27. package/dist/lib/clip-space.js +25 -30
  28. package/dist/lib/pipeline-factory.d.ts +1 -5
  29. package/dist/lib/pipeline-factory.d.ts.map +1 -1
  30. package/dist/lib/pipeline-factory.js +61 -68
  31. package/dist/model/model.d.ts +2 -2
  32. package/dist/model/model.d.ts.map +1 -1
  33. package/dist/model/model.js +539 -413
  34. package/dist/scenegraph/group-node.js +69 -84
  35. package/dist/scenegraph/model-node.js +32 -25
  36. package/dist/scenegraph/scenegraph-node.js +136 -124
  37. package/dist/shader-inputs.js +96 -58
  38. package/dist/transform/buffer-transform.js +65 -58
  39. package/dist/transform/texture-transform.d.ts.map +1 -1
  40. package/dist/transform/texture-transform.js +108 -115
  41. package/dist.min.js +2 -272
  42. package/package.json +10 -9
  43. package/src/lib/pipeline-factory.ts +8 -21
  44. package/src/model/model.ts +5 -5
  45. package/src/transform/buffer-transform.ts +3 -3
  46. package/src/transform/texture-transform.ts +0 -2
  47. package/dist/animation/key-frames.js.map +0 -1
  48. package/dist/animation/timeline.js.map +0 -1
  49. package/dist/animation-loop/animation-loop-template.js.map +0 -1
  50. package/dist/animation-loop/animation-loop.js.map +0 -1
  51. package/dist/animation-loop/animation-props.js.map +0 -1
  52. package/dist/animation-loop/make-animation-loop.js.map +0 -1
  53. package/dist/debug/copy-texture-to-image.js.map +0 -1
  54. package/dist/debug/debug-framebuffer.js.map +0 -1
  55. package/dist/debug/debug-shader-layout.js.map +0 -1
  56. package/dist/debug/pixel-data-utils.js.map +0 -1
  57. package/dist/geometries/cone-geometry.js.map +0 -1
  58. package/dist/geometries/cube-geometry.js.map +0 -1
  59. package/dist/geometries/cylinder-geometry.js.map +0 -1
  60. package/dist/geometries/ico-sphere-geometry.js.map +0 -1
  61. package/dist/geometries/plane-geometry.js.map +0 -1
  62. package/dist/geometries/sphere-geometry.js.map +0 -1
  63. package/dist/geometries/truncated-cone-geometry.js.map +0 -1
  64. package/dist/geometry/geometry-table.js.map +0 -1
  65. package/dist/geometry/geometry-utils.js.map +0 -1
  66. package/dist/geometry/geometry.js.map +0 -1
  67. package/dist/geometry/gpu-geometry.js.map +0 -1
  68. package/dist/geometry/gpu-table.js.map +0 -1
  69. package/dist/index.js.map +0 -1
  70. package/dist/lib/clip-space.js.map +0 -1
  71. package/dist/lib/pipeline-factory.js.map +0 -1
  72. package/dist/model/model.js.map +0 -1
  73. package/dist/scenegraph/group-node.js.map +0 -1
  74. package/dist/scenegraph/model-node.js.map +0 -1
  75. package/dist/scenegraph/scenegraph-node.js.map +0 -1
  76. package/dist/shader-inputs.js.map +0 -1
  77. package/dist/transform/buffer-transform.js.map +0 -1
  78. package/dist/transform/texture-transform.js.map +0 -1
@@ -1,440 +1,566 @@
1
+ // luma.gl, MIT license
2
+ // Copyright (c) vis.gl contributors
1
3
  import { Buffer, RenderPipeline, UniformStore, getTypedArrayFromDataType } from '@luma.gl/core';
2
4
  import { log, uid, deepEqual, splitUniformsAndBindings, isNumberArray } from '@luma.gl/core';
3
5
  import { getAttributeInfosFromLayouts } from '@luma.gl/core';
4
6
  import { ShaderAssembler, getShaderLayoutFromWGSL } from '@luma.gl/shadertools';
5
- import { ShaderInputs } from "../shader-inputs.js";
6
- import { makeGPUGeometry } from "../geometry/gpu-geometry.js";
7
- import { PipelineFactory } from "../lib/pipeline-factory.js";
8
- import { getDebugTableForShaderLayout } from "../debug/debug-shader-layout.js";
9
- import { debugFramebuffer } from "../debug/debug-framebuffer.js";
7
+ import { ShaderInputs } from '../shader-inputs';
8
+ import { makeGPUGeometry } from '../geometry/gpu-geometry';
9
+ import { PipelineFactory } from '../lib/pipeline-factory';
10
+ import { getDebugTableForShaderLayout } from '../debug/debug-shader-layout';
11
+ import { debugFramebuffer } from '../debug/debug-framebuffer';
10
12
  const LOG_DRAW_PRIORITY = 2;
11
13
  const LOG_DRAW_TIMEOUT = 10000;
14
+ /**
15
+ * v9 Model API
16
+ * A model
17
+ * - automatically reuses pipelines (programs) when possible
18
+ * - automatically rebuilds pipelines if necessary to accommodate changed settings
19
+ * shadertools integration
20
+ * - accepts modules and performs shader transpilation
21
+ */
12
22
  export class Model {
13
- constructor(device, props) {
14
- var _this$props$modules, _this$props$modules2, _this$shaderInputs;
15
- this.device = void 0;
16
- this.id = void 0;
17
- this.vs = void 0;
18
- this.fs = void 0;
19
- this.pipelineFactory = void 0;
20
- this.userData = {};
21
- this.parameters = void 0;
22
- this.topology = void 0;
23
- this.bufferLayout = void 0;
24
- this.vertexCount = void 0;
25
- this.instanceCount = 0;
26
- this.indexBuffer = null;
27
- this.bufferAttributes = {};
28
- this.constantAttributes = {};
29
- this.bindings = {};
30
- this.uniforms = {};
31
- this.vertexArray = void 0;
32
- this.transformFeedback = null;
33
- this.pipeline = void 0;
34
- this.shaderInputs = void 0;
35
- this._uniformStore = void 0;
36
- this._pipelineNeedsUpdate = 'newly created';
37
- this._attributeInfos = {};
38
- this._gpuGeometry = null;
39
- this._getModuleUniforms = void 0;
40
- this.props = void 0;
41
- this._lastLogTime = 0;
42
- this._logOpen = false;
43
- this._drawCount = 0;
44
- this.props = {
45
- ...Model.defaultProps,
46
- ...props
23
+ static defaultProps = {
24
+ ...RenderPipeline.defaultProps,
25
+ source: null,
26
+ vs: null,
27
+ fs: null,
28
+ id: 'unnamed',
29
+ handle: undefined,
30
+ userData: {},
31
+ defines: {},
32
+ modules: [],
33
+ moduleSettings: undefined,
34
+ geometry: null,
35
+ indexBuffer: null,
36
+ attributes: {},
37
+ constantAttributes: {},
38
+ varyings: [],
39
+ shaderInputs: undefined,
40
+ pipelineFactory: undefined,
41
+ transformFeedback: undefined,
42
+ shaderAssembler: ShaderAssembler.getDefaultShaderAssembler()
47
43
  };
48
- props = this.props;
49
- this.id = props.id || uid('model');
50
- this.device = device;
51
- Object.assign(this.userData, props.userData);
52
- const moduleMap = Object.fromEntries(((_this$props$modules = this.props.modules) === null || _this$props$modules === void 0 ? void 0 : _this$props$modules.map(module => [module.name, module])) || []);
53
- this.setShaderInputs(props.shaderInputs || new ShaderInputs(moduleMap));
54
- const isWebGPU = this.device.info.type === 'webgpu';
55
- if (this.props.source) {
56
- if (isWebGPU) {
57
- var _this$props;
58
- (_this$props = this.props).shaderLayout || (_this$props.shaderLayout = getShaderLayoutFromWGSL(this.props.source));
59
- }
60
- this.props.fs = this.props.source;
61
- this.props.vs = this.props.source;
62
- }
63
- if (isWebGPU && typeof this.props.vs !== 'string') {
64
- var _this$props2;
65
- (_this$props2 = this.props).shaderLayout || (_this$props2.shaderLayout = getShaderLayoutFromWGSL(this.props.vs.wgsl));
66
- }
67
- const platformInfo = getPlatformInfo(device);
68
- const modules = (((_this$props$modules2 = this.props.modules) === null || _this$props$modules2 === void 0 ? void 0 : _this$props$modules2.length) > 0 ? this.props.modules : (_this$shaderInputs = this.shaderInputs) === null || _this$shaderInputs === void 0 ? void 0 : _this$shaderInputs.getModules()) || [];
69
- const {
70
- vs,
71
- fs,
72
- getUniforms
73
- } = this.props.shaderAssembler.assembleShaders({
74
- platformInfo,
75
- ...this.props,
76
- modules
77
- });
78
- this.vs = vs;
79
- this.fs = fs;
80
- this._getModuleUniforms = getUniforms;
81
- this.vertexCount = this.props.vertexCount;
82
- this.instanceCount = this.props.instanceCount;
83
- this.topology = this.props.topology;
84
- this.bufferLayout = this.props.bufferLayout;
85
- this.parameters = this.props.parameters;
86
- if (props.geometry) {
87
- this._gpuGeometry = this.setGeometry(props.geometry);
88
- }
89
- this.pipelineFactory = props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);
90
- this.pipeline = this._updatePipeline();
91
- this.vertexArray = device.createVertexArray({
92
- renderPipeline: this.pipeline
93
- });
94
- if (this._gpuGeometry) {
95
- this._setGeometryAttributes(this._gpuGeometry);
96
- }
97
- if (props.vertexCount) {
98
- this.setVertexCount(props.vertexCount);
99
- }
100
- if (props.instanceCount) {
101
- this.setInstanceCount(props.instanceCount);
102
- }
103
- if (props.indices) {
104
- throw new Error('Model.props.indices removed. Use props.indexBuffer');
105
- }
106
- if (props.indexBuffer) {
107
- this.setIndexBuffer(props.indexBuffer);
108
- }
109
- if (props.attributes) {
110
- this.setAttributes(props.attributes);
111
- }
112
- if (props.constantAttributes) {
113
- this.setConstantAttributes(props.constantAttributes);
114
- }
115
- if (props.bindings) {
116
- this.setBindings(props.bindings);
117
- }
118
- if (props.uniforms) {
119
- this.setUniforms(props.uniforms);
120
- }
121
- if (props.moduleSettings) {
122
- log.warn('Model.props.moduleSettings is deprecated. Use Model.shaderInputs.setProps()')();
123
- this.updateModuleSettings(props.moduleSettings);
124
- }
125
- if (props.transformFeedback) {
126
- this.transformFeedback = props.transformFeedback;
127
- }
128
- Object.seal(this);
129
- }
130
- destroy() {
131
- this.pipelineFactory.release(this.pipeline);
132
- this._uniformStore.destroy();
133
- }
134
- predraw() {
135
- this.updateShaderInputs();
136
- }
137
- draw(renderPass) {
138
- this.predraw();
139
- try {
140
- this._logDrawCallStart();
141
- this.pipeline = this._updatePipeline();
142
- this.pipeline.setBindings(this.bindings);
143
- this.pipeline.setUniforms(this.uniforms);
144
- const {
145
- indexBuffer
146
- } = this.vertexArray;
147
- const indexCount = indexBuffer ? indexBuffer.byteLength / (indexBuffer.indexType === 'uint32' ? 4 : 2) : undefined;
148
- this.pipeline.draw({
149
- renderPass,
150
- vertexArray: this.vertexArray,
151
- vertexCount: this.vertexCount,
152
- instanceCount: this.instanceCount,
153
- indexCount,
154
- transformFeedback: this.transformFeedback
155
- });
156
- } finally {
157
- this._logDrawCallEnd();
158
- }
159
- this._logFramebuffer(renderPass);
160
- }
161
- setGeometry(geometry) {
162
- const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry);
163
- this.setTopology(gpuGeometry.topology || 'triangle-list');
164
- this.bufferLayout = mergeBufferLayouts(gpuGeometry.bufferLayout, this.bufferLayout);
165
- if (this.vertexArray) {
166
- this._setGeometryAttributes(gpuGeometry);
167
- }
168
- return gpuGeometry;
169
- }
170
- _setGeometryAttributes(gpuGeometry) {
171
- const attributes = {
172
- ...gpuGeometry.attributes
173
- };
174
- for (const [attributeName] of Object.entries(attributes)) {
175
- if (!this.pipeline.shaderLayout.attributes.find(layout => layout.name === attributeName) && attributeName !== 'positions') {
176
- delete attributes[attributeName];
177
- }
178
- }
179
- this.vertexCount = gpuGeometry.vertexCount;
180
- this.setIndexBuffer(gpuGeometry.indices);
181
- this.setAttributes(gpuGeometry.attributes, 'ignore-unknown');
182
- this.setAttributes(attributes);
183
- }
184
- setTopology(topology) {
185
- if (topology !== this.topology) {
186
- this.topology = topology;
187
- this._setPipelineNeedsUpdate('topology');
188
- }
189
- }
190
- setBufferLayout(bufferLayout) {
191
- this.bufferLayout = this._gpuGeometry ? mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout) : bufferLayout;
192
- this._setPipelineNeedsUpdate('bufferLayout');
193
- this.pipeline = this._updatePipeline();
194
- this.vertexArray = this.device.createVertexArray({
195
- renderPipeline: this.pipeline
196
- });
197
- if (this._gpuGeometry) {
198
- this._setGeometryAttributes(this._gpuGeometry);
199
- }
200
- }
201
- setParameters(parameters) {
202
- if (!deepEqual(parameters, this.parameters, 2)) {
203
- this.parameters = parameters;
204
- this._setPipelineNeedsUpdate('parameters');
205
- }
206
- }
207
- setVertexCount(vertexCount) {
208
- this.vertexCount = vertexCount;
209
- }
210
- setInstanceCount(instanceCount) {
211
- this.instanceCount = instanceCount;
212
- }
213
- setShaderInputs(shaderInputs) {
214
- this.shaderInputs = shaderInputs;
215
- this._uniformStore = new UniformStore(this.shaderInputs.modules);
216
- for (const moduleName of Object.keys(this.shaderInputs.modules)) {
217
- const uniformBuffer = this._uniformStore.getManagedUniformBuffer(this.device, moduleName);
218
- this.bindings[`${moduleName}Uniforms`] = uniformBuffer;
219
- }
220
- }
221
- setShaderModuleProps(props) {
222
- const uniforms = this._getModuleUniforms(props);
223
- const keys = Object.keys(uniforms).filter(k => {
224
- const uniform = uniforms[k];
225
- return !isNumberArray(uniform) && typeof uniform !== 'number' && typeof uniform !== 'boolean';
226
- });
227
- const bindings = {};
228
- for (const k of keys) {
229
- bindings[k] = uniforms[k];
230
- delete uniforms[k];
44
+ device;
45
+ id;
46
+ vs;
47
+ fs;
48
+ pipelineFactory;
49
+ userData = {};
50
+ // Fixed properties (change can trigger pipeline rebuild)
51
+ /** The render pipeline GPU parameters, depth testing etc */
52
+ parameters;
53
+ /** The primitive topology */
54
+ topology;
55
+ /** Buffer layout */
56
+ bufferLayout;
57
+ // Dynamic properties
58
+ /** Vertex count */
59
+ vertexCount;
60
+ /** instance count */
61
+ instanceCount = 0;
62
+ /** Index buffer */
63
+ indexBuffer = null;
64
+ /** Buffer-valued attributes */
65
+ bufferAttributes = {};
66
+ /** Constant-valued attributes */
67
+ constantAttributes = {};
68
+ /** Bindings (textures, samplers, uniform buffers) */
69
+ bindings = {};
70
+ /** Sets uniforms @deprecated Use uniform buffers and setBindings() for portability*/
71
+ uniforms = {};
72
+ /**
73
+ * VertexArray
74
+ * @note not implemented: if bufferLayout is updated, vertex array has to be rebuilt!
75
+ * @todo - allow application to define multiple vertex arrays?
76
+ * */
77
+ vertexArray;
78
+ /** TransformFeedback, WebGL 2 only. */
79
+ transformFeedback = null;
80
+ /** The underlying GPU "program". @note May be recreated if parameters change */
81
+ pipeline;
82
+ /** ShaderInputs instance */
83
+ shaderInputs;
84
+ _uniformStore;
85
+ _pipelineNeedsUpdate = 'newly created';
86
+ _attributeInfos = {};
87
+ _gpuGeometry = null;
88
+ _getModuleUniforms;
89
+ props;
90
+ constructor(device, props) {
91
+ this.props = { ...Model.defaultProps, ...props };
92
+ props = this.props;
93
+ this.id = props.id || uid('model');
94
+ this.device = device;
95
+ Object.assign(this.userData, props.userData);
96
+ // Setup shader module inputs
97
+ const moduleMap = Object.fromEntries(this.props.modules?.map(module => [module.name, module]) || []);
98
+ this.setShaderInputs(props.shaderInputs || new ShaderInputs(moduleMap));
99
+ const isWebGPU = this.device.info.type === 'webgpu';
100
+ // TODO - hack to support unified WGSL shader
101
+ // TODO - this is wrong, compile a single shader
102
+ if (this.props.source) {
103
+ if (isWebGPU) {
104
+ this.props.shaderLayout ||= getShaderLayoutFromWGSL(this.props.source);
105
+ }
106
+ this.props.fs = this.props.source;
107
+ this.props.vs = this.props.source;
108
+ }
109
+ // Support WGSL shader layout introspection
110
+ if (isWebGPU && typeof this.props.vs !== 'string') {
111
+ this.props.shaderLayout ||= getShaderLayoutFromWGSL(this.props.vs.wgsl);
112
+ }
113
+ // Setup shader assembler
114
+ const platformInfo = getPlatformInfo(device);
115
+ // Extract modules from shader inputs if not supplied
116
+ const modules = (this.props.modules?.length > 0 ? this.props.modules : this.shaderInputs?.getModules()) || [];
117
+ const { vs, fs, getUniforms } = this.props.shaderAssembler.assembleShaders({
118
+ platformInfo,
119
+ ...this.props,
120
+ modules
121
+ });
122
+ this.vs = vs;
123
+ this.fs = fs;
124
+ this._getModuleUniforms = getUniforms;
125
+ this.vertexCount = this.props.vertexCount;
126
+ this.instanceCount = this.props.instanceCount;
127
+ this.topology = this.props.topology;
128
+ this.bufferLayout = this.props.bufferLayout;
129
+ this.parameters = this.props.parameters;
130
+ // Geometry, if provided, sets topology and vertex cound
131
+ if (props.geometry) {
132
+ this._gpuGeometry = this.setGeometry(props.geometry);
133
+ }
134
+ this.pipelineFactory =
135
+ props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);
136
+ // Create the pipeline
137
+ // @note order is important
138
+ this.pipeline = this._updatePipeline();
139
+ this.vertexArray = device.createVertexArray({
140
+ renderPipeline: this.pipeline
141
+ });
142
+ // Now we can apply geometry attributes
143
+ if (this._gpuGeometry) {
144
+ this._setGeometryAttributes(this._gpuGeometry);
145
+ }
146
+ // Apply any dynamic settings that will not trigger pipeline change
147
+ if (props.vertexCount) {
148
+ this.setVertexCount(props.vertexCount);
149
+ }
150
+ if (props.instanceCount) {
151
+ this.setInstanceCount(props.instanceCount);
152
+ }
153
+ // @ts-expect-error
154
+ if (props.indices) {
155
+ throw new Error('Model.props.indices removed. Use props.indexBuffer');
156
+ }
157
+ if (props.indexBuffer) {
158
+ this.setIndexBuffer(props.indexBuffer);
159
+ }
160
+ if (props.attributes) {
161
+ this.setAttributes(props.attributes);
162
+ }
163
+ if (props.constantAttributes) {
164
+ this.setConstantAttributes(props.constantAttributes);
165
+ }
166
+ if (props.bindings) {
167
+ this.setBindings(props.bindings);
168
+ }
169
+ if (props.uniforms) {
170
+ this.setUniforms(props.uniforms);
171
+ }
172
+ if (props.moduleSettings) {
173
+ log.warn('Model.props.moduleSettings is deprecated. Use Model.shaderInputs.setProps()')();
174
+ this.updateModuleSettings(props.moduleSettings);
175
+ }
176
+ if (props.transformFeedback) {
177
+ this.transformFeedback = props.transformFeedback;
178
+ }
179
+ // TODO - restore?
180
+ // this.setUniforms(this._getModuleUniforms()); // Get all default module uniforms
181
+ // Catch any access to non-standard props
182
+ Object.seal(this);
183
+ }
184
+ destroy() {
185
+ this.pipelineFactory.release(this.pipeline);
186
+ this._uniformStore.destroy();
187
+ }
188
+ // Draw call
189
+ predraw() {
190
+ // Update uniform buffers if needed
191
+ this.updateShaderInputs();
192
+ }
193
+ draw(renderPass) {
194
+ this.predraw();
195
+ try {
196
+ this._logDrawCallStart();
197
+ // Check if the pipeline is invalidated
198
+ // TODO - this is likely the worst place to do this from performance perspective. Perhaps add a predraw()?
199
+ this.pipeline = this._updatePipeline();
200
+ // Set pipeline state, we may be sharing a pipeline so we need to set all state on every draw
201
+ // Any caching needs to be done inside the pipeline functions
202
+ this.pipeline.setBindings(this.bindings);
203
+ this.pipeline.setUniforms(this.uniforms);
204
+ const { indexBuffer } = this.vertexArray;
205
+ const indexCount = indexBuffer ? indexBuffer.byteLength / (indexBuffer.indexType === 'uint32' ? 4 : 2) : undefined;
206
+ this.pipeline.draw({
207
+ renderPass,
208
+ vertexArray: this.vertexArray,
209
+ vertexCount: this.vertexCount,
210
+ instanceCount: this.instanceCount,
211
+ indexCount,
212
+ transformFeedback: this.transformFeedback
213
+ });
214
+ }
215
+ finally {
216
+ this._logDrawCallEnd();
217
+ }
218
+ this._logFramebuffer(renderPass);
219
+ }
220
+ // Update fixed fields (can trigger pipeline rebuild)
221
+ /**
222
+ * Updates the optional geometry
223
+ * Geometry, set topology and bufferLayout
224
+ * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU
225
+ */
226
+ setGeometry(geometry) {
227
+ const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry);
228
+ this.setTopology(gpuGeometry.topology || 'triangle-list');
229
+ this.bufferLayout = mergeBufferLayouts(gpuGeometry.bufferLayout, this.bufferLayout);
230
+ if (this.vertexArray) {
231
+ this._setGeometryAttributes(gpuGeometry);
232
+ }
233
+ return gpuGeometry;
234
+ }
235
+ /**
236
+ * Updates the optional geometry attributes
237
+ * Geometry, sets several attributes, indexBuffer, and also vertex count
238
+ * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU
239
+ */
240
+ _setGeometryAttributes(gpuGeometry) {
241
+ // Filter geometry attribute so that we don't issue warnings for unused attributes
242
+ const attributes = { ...gpuGeometry.attributes };
243
+ for (const [attributeName] of Object.entries(attributes)) {
244
+ if (!this.pipeline.shaderLayout.attributes.find(layout => layout.name === attributeName) &&
245
+ attributeName !== 'positions') {
246
+ delete attributes[attributeName];
247
+ }
248
+ }
249
+ // TODO - delete previous geometry?
250
+ this.vertexCount = gpuGeometry.vertexCount;
251
+ this.setIndexBuffer(gpuGeometry.indices);
252
+ this.setAttributes(gpuGeometry.attributes, 'ignore-unknown');
253
+ this.setAttributes(attributes);
254
+ }
255
+ /**
256
+ * Updates the primitive topology ('triangle-list', 'triangle-strip' etc).
257
+ * @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU
258
+ */
259
+ setTopology(topology) {
260
+ if (topology !== this.topology) {
261
+ this.topology = topology;
262
+ this._setPipelineNeedsUpdate('topology');
263
+ }
231
264
  }
232
- }
233
- updateShaderInputs() {
234
- this._uniformStore.setUniforms(this.shaderInputs.getUniformValues());
235
- }
236
- updateModuleSettings(props) {
237
- log.warn('Model.updateModuleSettings is deprecated. Use Model.shaderInputs.setProps()')();
238
- const {
239
- bindings,
240
- uniforms
241
- } = splitUniformsAndBindings(this._getModuleUniforms(props));
242
- Object.assign(this.bindings, bindings);
243
- Object.assign(this.uniforms, uniforms);
244
- }
245
- setBindings(bindings) {
246
- Object.assign(this.bindings, bindings);
247
- }
248
- setUniforms(uniforms) {
249
- this.pipeline.setUniforms(uniforms);
250
- Object.assign(this.uniforms, uniforms);
251
- }
252
- setIndexBuffer(indexBuffer) {
253
- this.vertexArray.setIndexBuffer(indexBuffer);
254
- }
255
- setTransformFeedback(transformFeedback) {
256
- this.transformFeedback = transformFeedback;
257
- }
258
- setAttributes(buffers, _option) {
259
- if (buffers.indices) {
260
- log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)();
265
+ /**
266
+ * Updates the buffer layout.
267
+ * @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU
268
+ */
269
+ setBufferLayout(bufferLayout) {
270
+ this.bufferLayout = this._gpuGeometry
271
+ ? mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout)
272
+ : bufferLayout;
273
+ this._setPipelineNeedsUpdate('bufferLayout');
274
+ // Recreate the pipeline
275
+ this.pipeline = this._updatePipeline();
276
+ // vertex array needs to be updated if we update buffer layout,
277
+ // but not if we update parameters
278
+ this.vertexArray = this.device.createVertexArray({
279
+ renderPipeline: this.pipeline
280
+ });
281
+ // Reapply geometry attributes to the new vertex array
282
+ if (this._gpuGeometry) {
283
+ this._setGeometryAttributes(this._gpuGeometry);
284
+ }
261
285
  }
262
- for (const [bufferName, buffer] of Object.entries(buffers)) {
263
- const bufferLayout = this.bufferLayout.find(layout => getAttributeNames(layout).includes(bufferName));
264
- if (!bufferLayout) {
265
- log.warn(`Model(${this.id}): Missing layout for buffer "${bufferName}".`)();
266
- continue;
267
- }
268
- const attributeNames = getAttributeNames(bufferLayout);
269
- let set = false;
270
- for (const attributeName of attributeNames) {
271
- const attributeInfo = this._attributeInfos[attributeName];
272
- if (attributeInfo) {
273
- this.vertexArray.setBuffer(attributeInfo.location, buffer);
274
- set = true;
275
- }
276
- }
277
- if (!set && _option !== 'ignore-unknown') {
278
- log.warn(`Model(${this.id}): Ignoring buffer "${buffer.id}" for unknown attribute "${bufferName}"`)();
279
- }
286
+ /**
287
+ * Set GPU parameters.
288
+ * @note Can trigger a pipeline rebuild / pipeline cache fetch.
289
+ * @param parameters
290
+ */
291
+ setParameters(parameters) {
292
+ if (!deepEqual(parameters, this.parameters, 2)) {
293
+ this.parameters = parameters;
294
+ this._setPipelineNeedsUpdate('parameters');
295
+ }
280
296
  }
281
- }
282
- setConstantAttributes(attributes) {
283
- for (const [attributeName, value] of Object.entries(attributes)) {
284
- const attributeInfo = this._attributeInfos[attributeName];
285
- if (attributeInfo) {
286
- this.vertexArray.setConstant(attributeInfo.location, value);
287
- } else {
288
- log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${attributeName}"`)();
289
- }
297
+ // Update dynamic fields
298
+ /**
299
+ * Updates the vertex count (used in draw calls)
300
+ * @note Any attributes with stepMode=vertex need to be at least this big
301
+ */
302
+ setVertexCount(vertexCount) {
303
+ this.vertexCount = vertexCount;
304
+ }
305
+ /**
306
+ * Updates the instance count (used in draw calls)
307
+ * @note Any attributes with stepMode=instance need to be at least this big
308
+ */
309
+ setInstanceCount(instanceCount) {
310
+ this.instanceCount = instanceCount;
311
+ }
312
+ setShaderInputs(shaderInputs) {
313
+ this.shaderInputs = shaderInputs;
314
+ this._uniformStore = new UniformStore(this.shaderInputs.modules);
315
+ // Create uniform buffer bindings for all modules
316
+ for (const moduleName of Object.keys(this.shaderInputs.modules)) {
317
+ const uniformBuffer = this._uniformStore.getManagedUniformBuffer(this.device, moduleName);
318
+ this.bindings[`${moduleName}Uniforms`] = uniformBuffer;
319
+ }
290
320
  }
291
- }
292
- _setPipelineNeedsUpdate(reason) {
293
- this._pipelineNeedsUpdate = this._pipelineNeedsUpdate || reason;
294
- }
295
- _updatePipeline() {
296
- if (this._pipelineNeedsUpdate) {
297
- if (this.pipeline) {
298
- log.log(1, `Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)();
299
- }
300
- this._pipelineNeedsUpdate = false;
301
- const vs = this.device.createShader({
302
- id: `${this.id}-vertex`,
303
- stage: 'vertex',
304
- source: this.vs
305
- });
306
- const fs = this.fs ? this.device.createShader({
307
- id: `${this.id}-fragment`,
308
- stage: 'fragment',
309
- source: this.fs
310
- }) : null;
311
- this.pipeline = this.device.createRenderPipeline({
312
- ...this.props,
313
- bufferLayout: this.bufferLayout,
314
- topology: this.topology,
315
- parameters: this.parameters,
316
- vs,
317
- fs
318
- });
319
- this._attributeInfos = getAttributeInfosFromLayouts(this.pipeline.shaderLayout, this.bufferLayout);
321
+ /**
322
+ * Updates shader module settings (which results in uniforms being set)
323
+ */
324
+ setShaderModuleProps(props) {
325
+ const uniforms = this._getModuleUniforms(props);
326
+ // Extract textures & framebuffers set by the modules
327
+ // TODO better way to extract bindings
328
+ const keys = Object.keys(uniforms).filter(k => {
329
+ const uniform = uniforms[k];
330
+ return !isNumberArray(uniform) && typeof uniform !== 'number' && typeof uniform !== 'boolean';
331
+ });
332
+ const bindings = {};
333
+ for (const k of keys) {
334
+ bindings[k] = uniforms[k];
335
+ delete uniforms[k];
336
+ }
320
337
  }
321
- return this.pipeline;
322
- }
323
- _logDrawCallStart() {
324
- const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;
325
- if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {
326
- return;
338
+ updateShaderInputs() {
339
+ this._uniformStore.setUniforms(this.shaderInputs.getUniformValues());
340
+ }
341
+ /**
342
+ * @deprecated Updates shader module settings (which results in uniforms being set)
343
+ */
344
+ updateModuleSettings(props) {
345
+ log.warn('Model.updateModuleSettings is deprecated. Use Model.shaderInputs.setProps()')();
346
+ const { bindings, uniforms } = splitUniformsAndBindings(this._getModuleUniforms(props));
347
+ Object.assign(this.bindings, bindings);
348
+ Object.assign(this.uniforms, uniforms);
349
+ }
350
+ /**
351
+ * Sets bindings (textures, samplers, uniform buffers)
352
+ */
353
+ setBindings(bindings) {
354
+ Object.assign(this.bindings, bindings);
355
+ }
356
+ /**
357
+ * Sets individual uniforms
358
+ * @deprecated WebGL only, use uniform buffers for portability
359
+ * @param uniforms
360
+ * @returns self for chaining
361
+ */
362
+ setUniforms(uniforms) {
363
+ this.pipeline.setUniforms(uniforms);
364
+ Object.assign(this.uniforms, uniforms);
365
+ }
366
+ /**
367
+ * Sets the index buffer
368
+ * @todo - how to unset it if we change geometry?
369
+ */
370
+ setIndexBuffer(indexBuffer) {
371
+ this.vertexArray.setIndexBuffer(indexBuffer);
372
+ }
373
+ /**
374
+ * Updates optional transform feedback. WebGL only.
375
+ */
376
+ setTransformFeedback(transformFeedback) {
377
+ this.transformFeedback = transformFeedback;
378
+ }
379
+ /**
380
+ * Sets attributes (buffers)
381
+ * @note Overrides any attributes previously set with the same name
382
+ */
383
+ setAttributes(buffers, _option) {
384
+ if (buffers.indices) {
385
+ log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)();
386
+ }
387
+ for (const [bufferName, buffer] of Object.entries(buffers)) {
388
+ const bufferLayout = this.bufferLayout.find(layout => getAttributeNames(layout).includes(bufferName));
389
+ if (!bufferLayout) {
390
+ log.warn(`Model(${this.id}): Missing layout for buffer "${bufferName}".`)();
391
+ continue; // eslint-disable-line no-continue
392
+ }
393
+ // For an interleaved attribute we may need to set multiple attributes
394
+ const attributeNames = getAttributeNames(bufferLayout);
395
+ let set = false;
396
+ for (const attributeName of attributeNames) {
397
+ const attributeInfo = this._attributeInfos[attributeName];
398
+ if (attributeInfo) {
399
+ this.vertexArray.setBuffer(attributeInfo.location, buffer);
400
+ set = true;
401
+ }
402
+ }
403
+ if (!set && _option !== 'ignore-unknown') {
404
+ log.warn(`Model(${this.id}): Ignoring buffer "${buffer.id}" for unknown attribute "${bufferName}"`)();
405
+ }
406
+ }
327
407
  }
328
- this._lastLogTime = Date.now();
329
- this._logOpen = true;
330
- log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {
331
- collapsed: log.level <= 2
332
- })();
333
- }
334
- _logDrawCallEnd() {
335
- if (this._logOpen) {
336
- const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id);
337
- log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();
338
- const uniformTable = this.shaderInputs.getDebugTable();
339
- for (const [name, value] of Object.entries(this.uniforms)) {
340
- uniformTable[name] = {
341
- value
342
- };
343
- }
344
- log.table(LOG_DRAW_PRIORITY, uniformTable)();
345
- const attributeTable = this._getAttributeDebugTable();
346
- log.table(LOG_DRAW_PRIORITY, this._attributeInfos)();
347
- log.table(LOG_DRAW_PRIORITY, attributeTable)();
348
- log.groupEnd(LOG_DRAW_PRIORITY)();
349
- this._logOpen = false;
408
+ /**
409
+ * Sets constant attributes
410
+ * @note Overrides any attributes previously set with the same name
411
+ * Constant attributes are only supported in WebGL, not in WebGPU
412
+ * Any attribute that is disabled in the current vertex array object
413
+ * is read from the context's global constant value for that attribute location.
414
+ * @param constantAttributes
415
+ */
416
+ setConstantAttributes(attributes) {
417
+ for (const [attributeName, value] of Object.entries(attributes)) {
418
+ const attributeInfo = this._attributeInfos[attributeName];
419
+ if (attributeInfo) {
420
+ this.vertexArray.setConstant(attributeInfo.location, value);
421
+ }
422
+ else {
423
+ log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${attributeName}"`)();
424
+ }
425
+ }
350
426
  }
351
- }
352
- _logFramebuffer(renderPass) {
353
- const debugFramebuffers = log.get('framebuffer');
354
- this._drawCount++;
355
- if (!debugFramebuffers || this._drawCount++ > 3 && this._drawCount % 60) {
356
- return;
427
+ _setPipelineNeedsUpdate(reason) {
428
+ this._pipelineNeedsUpdate = this._pipelineNeedsUpdate || reason;
429
+ }
430
+ _updatePipeline() {
431
+ if (this._pipelineNeedsUpdate) {
432
+ if (this.pipeline) {
433
+ log.log(1, `Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)();
434
+ }
435
+ this._pipelineNeedsUpdate = false;
436
+ const vs = this.device.createShader({
437
+ id: `${this.id}-vertex`,
438
+ stage: 'vertex',
439
+ source: this.vs
440
+ });
441
+ const fs = this.fs
442
+ ? this.device.createShader({
443
+ id: `${this.id}-fragment`,
444
+ stage: 'fragment',
445
+ source: this.fs
446
+ })
447
+ : null;
448
+ this.pipeline = this.pipelineFactory.createRenderPipeline({
449
+ ...this.props,
450
+ bufferLayout: this.bufferLayout,
451
+ topology: this.topology,
452
+ parameters: this.parameters,
453
+ vs,
454
+ fs
455
+ });
456
+ this._attributeInfos = getAttributeInfosFromLayouts(this.pipeline.shaderLayout, this.bufferLayout);
457
+ }
458
+ return this.pipeline;
459
+ }
460
+ /** Throttle draw call logging */
461
+ _lastLogTime = 0;
462
+ _logOpen = false;
463
+ _logDrawCallStart() {
464
+ // IF level is 4 or higher, log every frame.
465
+ const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;
466
+ if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {
467
+ return;
468
+ }
469
+ this._lastLogTime = Date.now();
470
+ this._logOpen = true;
471
+ log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, { collapsed: log.level <= 2 })();
472
+ }
473
+ _logDrawCallEnd() {
474
+ if (this._logOpen) {
475
+ const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id);
476
+ // log.table(logLevel, attributeTable)();
477
+ // log.table(logLevel, uniformTable)();
478
+ log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();
479
+ const uniformTable = this.shaderInputs.getDebugTable();
480
+ // Add any global uniforms
481
+ for (const [name, value] of Object.entries(this.uniforms)) {
482
+ uniformTable[name] = { value };
483
+ }
484
+ log.table(LOG_DRAW_PRIORITY, uniformTable)();
485
+ const attributeTable = this._getAttributeDebugTable();
486
+ log.table(LOG_DRAW_PRIORITY, this._attributeInfos)();
487
+ log.table(LOG_DRAW_PRIORITY, attributeTable)();
488
+ log.groupEnd(LOG_DRAW_PRIORITY)();
489
+ this._logOpen = false;
490
+ }
357
491
  }
358
- const framebuffer = renderPass.props.framebuffer;
359
- if (framebuffer) {
360
- debugFramebuffer(framebuffer, {
361
- id: framebuffer.id,
362
- minimap: true
363
- });
492
+ _drawCount = 0;
493
+ _logFramebuffer(renderPass) {
494
+ const debugFramebuffers = log.get('framebuffer');
495
+ this._drawCount++;
496
+ // Update first 3 frames and then every 60 frames
497
+ if (!debugFramebuffers || ((this._drawCount++ > 3) && (this._drawCount % 60))) {
498
+ return;
499
+ }
500
+ // TODO - display framebuffer output in debug window
501
+ const framebuffer = renderPass.props.framebuffer;
502
+ if (framebuffer) {
503
+ debugFramebuffer(framebuffer, { id: framebuffer.id, minimap: true });
504
+ // log.image({logLevel: LOG_DRAW_PRIORITY, message: `${framebuffer.id} %c sup?`, image})();
505
+ }
364
506
  }
365
- }
366
- _getAttributeDebugTable() {
367
- const table = {};
368
- for (const [name, attributeInfo] of Object.entries(this._attributeInfos)) {
369
- table[attributeInfo.location] = {
370
- name,
371
- type: attributeInfo.shaderType,
372
- values: this._getBufferOrConstantValues(this.vertexArray.attributes[attributeInfo.location], attributeInfo.bufferDataType)
373
- };
507
+ _getAttributeDebugTable() {
508
+ const table = {};
509
+ for (const [name, attributeInfo] of Object.entries(this._attributeInfos)) {
510
+ table[attributeInfo.location] = {
511
+ name,
512
+ type: attributeInfo.shaderType,
513
+ values: this._getBufferOrConstantValues(this.vertexArray.attributes[attributeInfo.location], attributeInfo.bufferDataType)
514
+ };
515
+ }
516
+ if (this.vertexArray.indexBuffer) {
517
+ const { indexBuffer } = this.vertexArray;
518
+ const values = indexBuffer.indexType === 'uint32'
519
+ ? new Uint32Array(indexBuffer.debugData)
520
+ : new Uint16Array(indexBuffer.debugData);
521
+ table.indices = {
522
+ name: 'indices',
523
+ type: indexBuffer.indexType,
524
+ values: values.toString()
525
+ };
526
+ }
527
+ return table;
374
528
  }
375
- if (this.vertexArray.indexBuffer) {
376
- const {
377
- indexBuffer
378
- } = this.vertexArray;
379
- const values = indexBuffer.indexType === 'uint32' ? new Uint32Array(indexBuffer.debugData) : new Uint16Array(indexBuffer.debugData);
380
- table.indices = {
381
- name: 'indices',
382
- type: indexBuffer.indexType,
383
- values: values.toString()
384
- };
529
+ // TODO - fix typing of luma data types
530
+ _getBufferOrConstantValues(attribute, dataType) {
531
+ const TypedArrayConstructor = getTypedArrayFromDataType(dataType);
532
+ const typedArray = attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;
533
+ return typedArray.toString();
385
534
  }
386
- return table;
387
- }
388
- _getBufferOrConstantValues(attribute, dataType) {
389
- const TypedArrayConstructor = getTypedArrayFromDataType(dataType);
390
- const typedArray = attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;
391
- return typedArray.toString();
392
- }
393
535
  }
394
- Model.defaultProps = {
395
- ...RenderPipeline.defaultProps,
396
- source: null,
397
- vs: null,
398
- fs: null,
399
- id: 'unnamed',
400
- handle: undefined,
401
- userData: {},
402
- defines: {},
403
- modules: [],
404
- moduleSettings: undefined,
405
- geometry: null,
406
- indexBuffer: null,
407
- attributes: {},
408
- constantAttributes: {},
409
- varyings: [],
410
- shaderInputs: undefined,
411
- pipelineFactory: undefined,
412
- transformFeedback: undefined,
413
- shaderAssembler: ShaderAssembler.getDefaultShaderAssembler()
414
- };
536
+ // HELPERS
537
+ /** TODO - move to core, document add tests */
415
538
  function mergeBufferLayouts(layouts1, layouts2) {
416
- const layouts = [...layouts1];
417
- for (const attribute of layouts2) {
418
- const index = layouts.findIndex(attribute2 => attribute2.name === attribute.name);
419
- if (index < 0) {
420
- layouts.push(attribute);
421
- } else {
422
- layouts[index] = attribute;
539
+ const layouts = [...layouts1];
540
+ for (const attribute of layouts2) {
541
+ const index = layouts.findIndex(attribute2 => attribute2.name === attribute.name);
542
+ if (index < 0) {
543
+ layouts.push(attribute);
544
+ }
545
+ else {
546
+ layouts[index] = attribute;
547
+ }
423
548
  }
424
- }
425
- return layouts;
549
+ return layouts;
426
550
  }
551
+ /** Create a shadertools platform info from the Device */
427
552
  export function getPlatformInfo(device) {
428
- return {
429
- type: device.info.type,
430
- shaderLanguage: device.info.shadingLanguage,
431
- shaderLanguageVersion: device.info.shadingLanguageVersion,
432
- gpu: device.info.gpu,
433
- features: device.features
434
- };
553
+ return {
554
+ type: device.info.type,
555
+ shaderLanguage: device.info.shadingLanguage,
556
+ shaderLanguageVersion: device.info.shadingLanguageVersion,
557
+ gpu: device.info.gpu,
558
+ features: device.features
559
+ };
435
560
  }
561
+ /** Get attribute names from a BufferLayout */
436
562
  function getAttributeNames(bufferLayout) {
437
- var _bufferLayout$attribu;
438
- return bufferLayout.attributes ? (_bufferLayout$attribu = bufferLayout.attributes) === null || _bufferLayout$attribu === void 0 ? void 0 : _bufferLayout$attribu.map(layout => layout.attribute) : [bufferLayout.name];
563
+ return bufferLayout.attributes
564
+ ? bufferLayout.attributes?.map(layout => layout.attribute)
565
+ : [bufferLayout.name];
439
566
  }
440
- //# sourceMappingURL=model.js.map