-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMeshBaseMixin.ts
1143 lines (970 loc) · 36.3 KB
/
MeshBaseMixin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { generateUUID, throwWarning } from '../../../utils/utils'
import { isRenderer, Renderer } from '../../renderers/utils'
import { RenderMaterial } from '../../materials/RenderMaterial'
import { Texture } from '../../textures/Texture'
import { Geometry } from '../../geometries/Geometry'
import { RenderTexture, RenderTextureParams } from '../../textures/RenderTexture'
import { ExternalTextureParams, TextureParams, TextureParent } from '../../../types/Textures'
import { RenderTarget } from '../../renderPasses/RenderTarget'
import { GPUCurtains } from '../../../curtains/GPUCurtains'
import { ProjectedMesh } from '../../renderers/GPURenderer'
import { Material } from '../../materials/Material'
import { DOMElementBoundingRect } from '../../DOM/DOMElement'
import { AllowedGeometries, RenderMaterialParams, ShaderOptions } from '../../../types/Materials'
import { ProjectedMeshBaseClass } from './ProjectedMeshBaseMixin'
import default_vsWgsl from '../../shaders/chunks/default_vs.wgsl'
import default_fsWgsl from '../../shaders/chunks/default_fs.wgsl'
import { RenderPass } from '../../renderPasses/RenderPass'
let meshIndex = 0
export interface MeshBaseRenderParams extends RenderMaterialParams {
/** Whether we should add this Mesh to our {@link core/scenes/Scene.Scene | Scene} to let it handle the rendering process automatically */
autoRender?: boolean
/** Flag indicating whether to draw this Mesh or not */
visible?: boolean
/** Controls the order in which this Mesh should be rendered by our {@link core/scenes/Scene.Scene | Scene} */
renderOrder?: number
/** Optional {@link RenderTarget} to render this Mesh to instead of the canvas context. */
outputTarget?: RenderTarget
/** Parameters used by this Mesh to create a {@link Texture} */
texturesOptions?: ExternalTextureParams
}
/**
* Base parameters used to create a Mesh
*/
export interface MeshBaseParams extends MeshBaseRenderParams {
/** Geometry to use */
geometry: AllowedGeometries
}
/**
* Base options used to create this Mesh
*/
export interface MeshBaseOptions {
/** The label of this Mesh, sent to various GPU objects for debugging purpose */
label?: MeshBaseParams['label']
/** Shaders to use by this Mesh {@link RenderMaterial} */
shaders?: MeshBaseParams['shaders']
/** Parameters used by this Mesh to create a {@link Texture} */
texturesOptions?: ExternalTextureParams
/** {@link RenderTarget} to render this Mesh to instead of the canvas context, if any. */
outputTarget?: RenderTarget | null
/** Whether we should add this Mesh to our {@link core/scenes/Scene.Scene | Scene} to let it handle the rendering process automatically */
autoRender?: boolean
/** Whether to compile this Mesh {@link RenderMaterial} {@link core/pipelines/RenderPipelineEntry.RenderPipelineEntry#pipeline | render pipeline} asynchronously or not */
useAsyncPipeline?: boolean
}
/** @const - Default Mesh parameters to merge with user defined parameters */
const defaultMeshBaseParams: MeshBaseParams = {
// geometry
geometry: new Geometry(),
// material
shaders: {},
autoRender: true,
useProjection: false,
useAsyncPipeline: true,
// rendering
cullMode: 'back',
depth: true,
depthWriteEnabled: true,
depthCompare: 'less',
depthFormat: 'depth24plus',
transparent: false,
visible: true,
renderOrder: 0,
// textures
texturesOptions: {},
}
// based on https://stackoverflow.com/a/75673107/13354068
// we declare first a class, and then the mixin with a return type
/**
* This class describes the properties and methods to set up a basic Mesh, implemented in the {@link MeshBaseMixin}:
* - Set and render the {@link Geometry} and {@link RenderMaterial}
* - Add helpers to create {@link Texture} and {@link RenderTexture}
* - Handle resizing, device lost/restoration and destroying the resources
*/
export declare class MeshBaseClass {
/** The type of the {@link MeshBaseClass} */
type: string
/** The universal unique id of the {@link MeshBaseClass} */
readonly uuid: string
/** Index of this {@link MeshBaseClass}, i.e. creation order */
readonly index: number
/** The {@link Renderer} used */
renderer: Renderer
/** Options used to create this {@link MeshBaseClass} */
options: MeshBaseOptions
/** {@link RenderMaterial} used by this {@link MeshBaseClass} */
material: RenderMaterial
/** {@link AllowedGeometries | Geometry} used by this {@link MeshBaseClass} */
geometry: MeshBaseParams['geometry']
/** {@link RenderTarget} to render this Mesh to instead of the canvas context, if any. */
outputTarget: null | RenderTarget
/** Controls the order in which this {@link MeshBaseClass} should be rendered by our {@link core/scenes/Scene.Scene | Scene} */
renderOrder: number
/** Whether this {@link MeshBaseClass} should be treated as transparent. Impacts the {@link core/pipelines/RenderPipelineEntry.RenderPipelineEntry#pipeline | render pipeline} blend properties */
transparent: boolean
/** Flag indicating whether to draw this {@link MeshBaseClass} or not */
visible: boolean
/** Flag indicating whether this {@link MeshBaseClass} is ready to be drawn */
_ready: boolean
/** Empty object to store any additional data or custom properties into your Mesh. */
userData: Record<string, unknown>
// callbacks
/** function assigned to the {@link onReady} callback */
_onReadyCallback: () => void
/** function assigned to the {@link onBeforeRender} callback */
_onBeforeRenderCallback: () => void
/** function assigned to the {@link onRender} callback */
_onRenderCallback: () => void
/** function assigned to the {@link onAfterRender} callback */
_onAfterRenderCallback: () => void
/** function assigned to the {@link onAfterResize} callback */
_onAfterResizeCallback: () => void
/**
* Assign a callback function to _onReadyCallback
* @param callback - callback to run when {@link MeshBaseClass} is ready
* @returns - our Mesh
*/
onReady: (callback: () => void) => MeshBaseClass | ProjectedMeshBaseClass
/**
* Assign a callback function to _onBeforeRenderCallback
* @param callback - callback to run just before {@link MeshBaseClass} will be rendered
* @returns - our Mesh
*/
onBeforeRender: (callback: () => void) => MeshBaseClass | ProjectedMeshBaseClass
/**
* Assign a callback function to _onRenderCallback
* @param callback - callback to run when {@link MeshBaseClass} is rendered
* @returns - our Mesh
*/
onRender: (callback: () => void) => MeshBaseClass | ProjectedMeshBaseClass
/**
* Assign a callback function to _onAfterRenderCallback
* @param callback - callback to run just after {@link MeshBaseClass} has been rendered
* @returns - our Mesh
*/
onAfterRender: (callback: () => void) => MeshBaseClass | ProjectedMeshBaseClass
/**
* Assign a callback function to _onBeforeRenderCallback
* @param callback - callback to run just after {@link MeshBaseClass} has been resized
* @returns - our Mesh
*/
onAfterResize: (callback: () => void) => MeshBaseClass | ProjectedMeshBaseClass
/**
* {@link MeshBaseClass} constructor
* @param renderer - our {@link Renderer} class object
* @param element - a DOM HTML Element that can be bound to a Mesh
* @param parameters - {@link MeshBaseParams | Mesh base parameters}
*/
constructor(renderer: Renderer, element: HTMLElement | null, parameters: MeshBaseParams)
/**
* Get private #autoRender value
* @readonly
*/
get autoRender(): boolean // allow to read value from child classes
/**
* Get/set whether a Mesh is ready or not
* @readonly
*/
get ready(): boolean
set ready(value: boolean)
/**
* Add a Mesh to the renderer and the {@link core/scenes/Scene.Scene | Scene}
*/
addToScene(): void
/**
* Remove a Mesh from the renderer and the {@link core/scenes/Scene.Scene | Scene}
*/
removeFromScene(): void
/**
* Set a new {@link Renderer} for this Mesh
* @param renderer - new {@link Renderer} to set
*/
setRenderer(renderer: Renderer | GPUCurtains): void
/**
* Called when the {@link core/renderers/GPUDeviceManager.GPUDeviceManager#device | device} has been lost to prepare everything for restoration.
* Basically set all the {@link GPUBuffer} to null so they will be reset next time we try to draw the Mesh
*/
loseContext(): void
/**
* Called when the {@link core/renderers/GPUDeviceManager.GPUDeviceManager#device | device} has been restored
*/
restoreContext(): void
/**
* Set default shaders if one or both of them are missing
*/
setShaders(): void
/**
* Compute the Mesh geometry if needed
*/
computeGeometry(): void
/**
* Create the Mesh Geometry vertex and index buffers if needed
*/
createGeometryBuffers(): void
/**
* Set our Mesh geometry: create buffers and add attributes to material
*/
setGeometry(): void
/**
* Set or update the {@link RenderMaterial} {@link types/Materials.RenderMaterialRenderingOptions | rendering options} to match the {@link RenderPass#descriptor | RenderPass descriptor} used to draw this Mesh.
* @param renderPass - {@link RenderPass | RenderPass} used to draw this Mesh, default to the {@link core/renderers/GPURenderer.GPURenderer#renderPass | renderer renderPass}.
*/
setRenderingOptionsForRenderPass(renderPass: RenderPass): void
/**
* Hook used to clean up parameters before sending them to the material.
* @param parameters - parameters to clean before sending them to the {@link RenderMaterial}
* @returns - cleaned parameters
*/
cleanupRenderMaterialParameters(parameters: MeshBaseRenderParams): MeshBaseRenderParams
/**
* Set a Mesh transparent property, then set its material
* @param meshParameters - {@link RenderMaterialParams | RenderMaterial parameters}
*/
setMaterial(meshParameters: RenderMaterialParams): void
/**
* Set Mesh material attributes
*/
setMaterialGeometryAttributes(): void
/**
* Get our {@link RenderMaterial#textures | RenderMaterial textures array}
* @readonly
*/
get textures(): Texture[]
/**
* Get our {@link RenderMaterial#renderTextures | RenderMaterial render textures array}
* @readonly
*/
get renderTextures(): RenderTexture[]
/**
* Create a new {@link Texture}
* @param options - {@link TextureParams | Texture parameters}
* @returns - newly created Texture
*/
createTexture(options: TextureParams): Texture
/**
* Add a {@link Texture}
* @param texture - {@link Texture} to add
*/
addTexture(texture: Texture)
/**
* Callback run when a new {@link Texture} has been created
* @param texture - newly created Texture
*/
onTextureAdded(texture: Texture): void
/**
* Create a new {@link RenderTexture}
* @param options - {@link RenderTextureParams | RenderTexture parameters}
* @returns - newly created RenderTexture
*/
createRenderTexture(options: RenderTextureParams): RenderTexture
/**
* Add a {@link RenderTexture}
* @param renderTexture - {@link RenderTexture} to add
*/
addRenderTexture(renderTexture: RenderTexture)
/**
* Assign or remove a {@link RenderTarget} to this Mesh
* Since this manipulates the {@link core/scenes/Scene.Scene | Scene} stacks, it can be used to remove a RenderTarget as well.
* @param outputTarget - the RenderTarget to assign or null if we want to remove the current RenderTarget
*/
setOutputTarget(outputTarget: RenderTarget | null): void
/**
* Get the current {@link RenderMaterial} uniforms
* @readonly
*/
get uniforms(): Material['uniforms']
/**
* Get the current {@link RenderMaterial} storages
* @readonly
*/
get storages(): Material['storages']
/**
* Resize the Mesh's textures
* @param boundingRect
*/
resize(boundingRect?: DOMElementBoundingRect): void
/**
* Called before rendering the Mesh
* Set the geometry if needed (create buffers and add attributes to the {@link RenderMaterial})
* Then executes {@link RenderMaterial#onBeforeRender}: create its bind groups and pipeline if needed and eventually update its struct
*/
onBeforeRenderPass(): void
/**
* Render our {@link MeshBaseClass} if the {@link RenderMaterial} is ready
* @param pass - current render pass encoder
*/
onRenderPass(pass: GPURenderPassEncoder): void
/**
* Called after having rendered the Mesh
*/
onAfterRenderPass(): void
/**
* Render our Mesh
* - Execute {@link onBeforeRenderPass}
* - Stop here if {@link Renderer} is not ready or Mesh is not {@link visible}
* - Execute super render call if it exists
* - {@link onRenderPass | render} our {@link material} and {@link geometry}
* - Execute {@link onAfterRenderPass}
* @param pass - current render pass encoder
*/
render(pass: GPURenderPassEncoder): void
/**
* Remove the Mesh from the {@link core/scenes/Scene.Scene | Scene} and destroy it
*/
remove(): void
/**
* Destroy the Mesh
*/
destroy(): void
}
/**
* To get started, we need a type which we'll use to extend
* other classes from. The main responsibility is to declare
* that the type being passed in is a class.
* We use a generic version which can apply a constraint on
* the class which this mixin is applied to
* @typeParam T - the base constructor
*/
export type MixinConstructor<T = {}> = new (...args: any[]) => T
/**
* Used to mix the basic Mesh properties and methods defined in {@link MeshBaseClass} (basically, set a {@link Geometry} and a {@link RenderMaterial} and render them, add helpers to create {@link Texture} and {@link RenderTexture}) with a given Base of type {@link core/objects3D/Object3D.Object3D | Object3D}, {@link core/objects3D/ProjectedObject3D.ProjectedObject3D | ProjectedObject3D}, {@link curtains/objects3D/DOMObject3D.DOMObject3D | DOMObject3D} or an empty class.
* @exports MeshBaseMixin
* @param Base - the class to mix onto
* @returns - the mixed classes, creating a basic Mesh.
*/
function MeshBaseMixin<TBase extends MixinConstructor>(Base: TBase): MixinConstructor<MeshBaseClass> & TBase {
/**
* MeshBase defines our base properties and methods
*/
return class MeshBase extends Base implements MeshBaseClass {
/** The type of the {@link MeshBase} */
type: string
/** The universal unique id of the {@link MeshBase} */
readonly uuid: string
/** Index of this {@link MeshBase}, i.e. creation order */
readonly index: number
/** The {@link Renderer} used */
renderer: Renderer
/** Options used to create this {@link MeshBase} */
options: MeshBaseOptions
/** {@link RenderMaterial} used by this {@link MeshBase} */
material: RenderMaterial
/** {@link AllowedGeometries | Geometry} used by this {@link MeshBase} */
geometry: MeshBaseParams['geometry']
/** {@link RenderTarget} to render this Mesh to, if any */
outputTarget: null | RenderTarget
/** Controls the order in which this {@link MeshBase} should be rendered by our {@link core/scenes/Scene.Scene | Scene} */
renderOrder: number
/** Whether this {@link MeshBase} should be treated as transparent. Impacts the {@link core/pipelines/RenderPipelineEntry.RenderPipelineEntry#pipeline | render pipeline} blend properties */
transparent: boolean
/** Flag indicating whether to draw this {@link MeshBase} or not */
visible: boolean
/** Flag indicating whether this {@link MeshBase} is ready to be drawn */
_ready: boolean
/** Empty object to store any additional data or custom properties into your {@link MeshBase}. */
userData: Record<string, unknown>
/** Whether we should add this {@link MeshBase} to our {@link core/scenes/Scene.Scene | Scene} to let it handle the rendering process automatically */
#autoRender = true
// callbacks / events
/** function assigned to the {@link onReady} callback */
_onReadyCallback: () => void = () => {
/* allow empty callback */
}
/** function assigned to the {@link onBeforeRender} callback */
_onBeforeRenderCallback: () => void = () => {
/* allow empty callback */
}
/** function assigned to the {@link onRender} callback */
_onRenderCallback: () => void = () => {
/* allow empty callback */
}
/** function assigned to the {@link onAfterRender} callback */
_onAfterRenderCallback: () => void = () => {
/* allow empty callback */
}
/** function assigned to the {@link onAfterResize} callback */
_onAfterResizeCallback: () => void = () => {
/* allow empty callback */
}
/**
* MeshBase constructor
*
* @typedef MeshBaseArrayParams
* @type {array}
* @property {(Renderer|GPUCurtains)} 0 - our {@link Renderer} class object
* @property {(string|HTMLElement|null)} 1 - a DOM HTML Element that can be bound to a Mesh
* @property {MeshBaseParams} 2 - {@link MeshBaseParams | Mesh base parameters}
*
* @param {MeshBaseArrayParams} params - our MeshBaseMixin parameters
*/
constructor(...params: any[]) {
super(
params[0] as Renderer | GPUCurtains,
params[1] as HTMLElement | string | null,
{ ...defaultMeshBaseParams, ...params[2] } as MeshBaseParams
)
let renderer = params[0]
const parameters = { ...defaultMeshBaseParams, ...params[2] }
this.type = 'MeshBase'
this.uuid = generateUUID()
Object.defineProperty(this as MeshBase, 'index', { value: meshIndex++ })
// we could pass our curtains object OR our curtains renderer object
renderer = (renderer && (renderer as GPUCurtains).renderer) || (renderer as Renderer)
isRenderer(renderer, parameters.label ? parameters.label + ' ' + this.type : this.type)
this.renderer = renderer
const {
label,
shaders,
geometry,
visible,
renderOrder,
outputTarget,
texturesOptions,
autoRender,
...meshParameters
} = parameters
this.outputTarget = outputTarget ?? null
// set default sample count
meshParameters.sampleCount = !!meshParameters.sampleCount
? meshParameters.sampleCount
: this.outputTarget
? this.outputTarget.renderPass.options.sampleCount
: this.renderer && this.renderer.renderPass
? this.renderer.renderPass.options.sampleCount
: 1
this.options = {
...(this.options ?? {}), // merge possible lower options?
label: label ?? 'Mesh ' + this.renderer.meshes.length,
shaders,
texturesOptions,
...(outputTarget !== undefined && { outputTarget }),
...(autoRender !== undefined && { autoRender }),
...meshParameters,
}
this.geometry = geometry
if (autoRender !== undefined) {
this.#autoRender = autoRender
}
this.visible = visible
this.renderOrder = renderOrder
this.ready = false
this.userData = {}
this.computeGeometry()
this.setMaterial({
...this.cleanupRenderMaterialParameters({ ...this.options }),
verticesOrder: geometry.verticesOrder,
topology: geometry.topology,
} as RenderMaterialParams)
this.addToScene()
}
/**
* Get private #autoRender value
* @readonly
*/
get autoRender(): boolean {
return this.#autoRender
}
/**
* Get/set whether a Mesh is ready or not
* @readonly
*/
get ready(): boolean {
return this._ready
}
set ready(value: boolean) {
if (value) {
this._onReadyCallback && this._onReadyCallback()
}
this._ready = value
}
/* SCENE */
/**
* Add a Mesh to the renderer and the {@link core/scenes/Scene.Scene | Scene}. Can patch the {@link RenderMaterial} render options to match the {@link RenderPass} used to draw this Mesh.
*/
addToScene() {
this.renderer.meshes.push(this as unknown as ProjectedMesh)
this.setRenderingOptionsForRenderPass(this.outputTarget ? this.outputTarget.renderPass : this.renderer.renderPass)
if (this.#autoRender) {
this.renderer.scene.addMesh(this as unknown as ProjectedMesh)
}
}
/**
* Remove a Mesh from the renderer and the {@link core/scenes/Scene.Scene | Scene}
*/
removeFromScene() {
if (this.#autoRender) {
this.renderer.scene.removeMesh(this as unknown as ProjectedMesh)
}
this.renderer.meshes = this.renderer.meshes.filter((m) => m.uuid !== this.uuid)
}
/**
* Set a new {@link Renderer} for this Mesh
* @param renderer - new {@link Renderer} to set
*/
setRenderer(renderer: Renderer | GPUCurtains) {
// we could pass our curtains object OR our curtains renderer object
renderer = (renderer && (renderer as GPUCurtains).renderer) || (renderer as Renderer)
if (
!renderer ||
!(
renderer.type === 'GPURenderer' ||
renderer.type === 'GPUCameraRenderer' ||
renderer.type === 'GPUCurtainsRenderer'
)
) {
throwWarning(
`${this.options.label}: Cannot set ${renderer} as a renderer because it is not of a valid Renderer type.`
)
return
}
const oldRenderer = this.renderer
this.removeFromScene()
this.renderer = renderer
this.addToScene()
// if old renderer does not contain any meshes any more
// clear it
if (!oldRenderer.meshes.length) {
oldRenderer.onBeforeRenderScene.add(
(commandEncoder) => {
oldRenderer.forceClear(commandEncoder)
},
{ once: true }
)
}
}
/**
* Assign or remove a {@link RenderTarget} to this Mesh
* Since this manipulates the {@link core/scenes/Scene.Scene | Scene} stacks, it can be used to remove a RenderTarget as well.
* @param outputTarget - the RenderTarget to assign or null if we want to remove the current RenderTarget
*/
setOutputTarget(outputTarget: RenderTarget | null) {
if (outputTarget && outputTarget.type !== 'RenderTarget') {
throwWarning(`${this.options.label ?? this.type}: outputTarget is not a RenderTarget: ${outputTarget}`)
return
}
// ensure the mesh is in the correct scene stack
this.removeFromScene()
this.outputTarget = outputTarget
this.addToScene()
}
/**
* Called when the {@link core/renderers/GPUDeviceManager.GPUDeviceManager#device | device} has been lost to prepare everything for restoration.
* Basically set all the {@link GPUBuffer} to null so they will be reset next time we try to draw the Mesh
*/
loseContext() {
// first the geometry
this.geometry.vertexBuffers.forEach((vertexBuffer) => {
vertexBuffer.buffer = null
})
if ('indexBuffer' in this.geometry) {
this.geometry.indexBuffer.buffer = null
}
// then the material
this.material.loseContext()
}
/**
* Called when the {@link core/renderers/GPUDeviceManager.GPUDeviceManager#device | device} has been restored
*/
restoreContext() {
this.material.restoreContext()
}
/* SHADERS */
/**
* Set default shaders if one or both of them are missing
*/
setShaders() {
let { shaders } = this.options
if (!shaders) {
shaders = {
vertex: {
code: default_vsWgsl,
entryPoint: 'main',
},
fragment: {
code: default_fsWgsl,
entryPoint: 'main',
},
}
} else {
if (!shaders.vertex || !shaders.vertex.code) {
shaders.vertex = {
code: default_vsWgsl,
entryPoint: 'main',
}
}
if (shaders.fragment === undefined || (shaders.fragment && !(shaders.fragment as ShaderOptions).code)) {
shaders.fragment = {
code: default_fsWgsl,
entryPoint: 'main',
}
}
}
}
/* GEOMETRY */
/**
* Compute the Mesh geometry if needed
*/
computeGeometry() {
if (this.geometry.shouldCompute) {
this.geometry.computeGeometry()
}
}
/**
* Create the Mesh Geometry vertex and index buffers if needed
*/
createGeometryBuffers() {
if (!this.geometry.ready) {
this.geometry.vertexBuffers.forEach((vertexBuffer) => {
if (!vertexBuffer.buffer) {
vertexBuffer.buffer = this.renderer.createBuffer({
label: this.options.label + ' geometry: ' + vertexBuffer.name + ' buffer',
size: vertexBuffer.array.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
})
this.renderer.queueWriteBuffer(vertexBuffer.buffer, 0, vertexBuffer.array)
}
})
// if it's an indexed geometry, create index GPUBuffer as well
if ('indexBuffer' in this.geometry && this.geometry.indexBuffer && !this.geometry.indexBuffer.buffer) {
this.geometry.indexBuffer.buffer = this.renderer.createBuffer({
label: this.options.label + ' geometry: index buffer',
size: this.geometry.indexBuffer.array.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
})
this.renderer.queueWriteBuffer(this.geometry.indexBuffer.buffer, 0, this.geometry.indexBuffer.array)
}
}
}
/**
* Set our Mesh geometry: create buffers and add attributes to material
*/
setGeometry() {
if (this.geometry && this.renderer.ready) {
this.createGeometryBuffers()
this.setMaterialGeometryAttributes()
}
}
/* MATERIAL */
/**
* Set or update the {@link RenderMaterial} {@link types/Materials.RenderMaterialRenderingOptions | rendering options} to match the {@link RenderPass#descriptor | RenderPass descriptor} used to draw this Mesh.
* @param renderPass - {@link RenderPass | RenderPass} used to draw this Mesh, default to the {@link core/renderers/GPURenderer.GPURenderer#renderPass | renderer renderPass}.
*/
setRenderingOptionsForRenderPass(renderPass: RenderPass) {
// a Mesh render material rendering options MUST match the render pass descriptor used to draw it!
const renderingOptions = {
sampleCount: renderPass.options.sampleCount,
// color attachments
...(renderPass.options.colorAttachments.length && {
targetFormat: renderPass.options.colorAttachments[0].targetFormat,
// multiple render targets?
...(renderPass.options.colorAttachments.length > 1 && {
additionalTargets: renderPass.options.colorAttachments
.filter((c, i) => i > 0)
.map((colorAttachment) => {
return {
format: colorAttachment.targetFormat,
}
}),
}),
}),
// depth
depth: renderPass.options.useDepth,
...(renderPass.options.useDepth && {
depthFormat: renderPass.options.depthFormat,
}),
}
this.material?.setRenderingOptions(renderingOptions)
}
/**
* Hook used to clean up parameters before sending them to the {@link RenderMaterial}.
* @param parameters - parameters to clean before sending them to the {@link RenderMaterial}
* @returns - cleaned parameters
*/
cleanupRenderMaterialParameters(parameters: MeshBaseRenderParams): MeshBaseRenderParams {
// patch and set options, return mesh parameters
delete parameters.texturesOptions
delete parameters.outputTarget
delete parameters.autoRender
return parameters
}
/**
* Set a Mesh transparent property, then set its material
* @param meshParameters - {@link RenderMaterialParams | RenderMaterial parameters}
*/
setMaterial(meshParameters: RenderMaterialParams) {
this.transparent = meshParameters.transparent
this.setShaders()
this.material = new RenderMaterial(this.renderer, meshParameters)
// add eventual textures passed as parameters
this.material.options.textures
?.filter((texture) => texture instanceof Texture)
.forEach((texture) => this.onTextureAdded(texture))
}
/**
* Set Mesh material attributes
*/
setMaterialGeometryAttributes() {
if (this.material && !this.material.attributes) {
this.material.setAttributesFromGeometry(this.geometry)
}
}
/* TEXTURES */
/**
* Get our {@link RenderMaterial#textures | RenderMaterial textures array}
* @readonly
*/
get textures(): Texture[] {
return this.material?.textures || []
}
/**
* Get our {@link RenderMaterial#renderTextures | RenderMaterial render textures array}
* @readonly
*/
get renderTextures(): RenderTexture[] {
return this.material?.renderTextures || []
}
/**
* Create a new {@link Texture}
* @param options - {@link TextureParams | Texture parameters}
* @returns - newly created {@link Texture}
*/
createTexture(options: TextureParams): Texture {
if (!options.name) {
options.name = 'texture' + this.textures.length
}
if (!options.label) {
options.label = this.options.label + ' ' + options.name
}
const texture = new Texture(this.renderer, { ...options, ...this.options.texturesOptions })
this.addTexture(texture)
return texture
}
/**
* Add a {@link Texture}
* @param texture - {@link Texture} to add
*/
addTexture(texture: Texture) {
this.material.addTexture(texture)
this.onTextureAdded(texture)
}
/**
* Callback run when a new {@link Texture} has been added
* @param texture - newly created Texture
*/
onTextureAdded(texture: Texture) {
texture.parentMesh = this as unknown as TextureParent
}
/**
* Create a new {@link RenderTexture}
* @param options - {@link RenderTextureParams | RenderTexture parameters}
* @returns - newly created {@link RenderTexture}
*/
createRenderTexture(options: RenderTextureParams): RenderTexture {
if (!options.name) {
options.name = 'renderTexture' + this.renderTextures.length
}
const renderTexture = new RenderTexture(this.renderer, options)
this.addRenderTexture(renderTexture)
return renderTexture
}
/**
* Add a {@link RenderTexture}
* @param renderTexture - {@link RenderTexture} to add
*/
addRenderTexture(renderTexture: RenderTexture) {
this.material.addTexture(renderTexture)
}
/* BINDINGS */
/**
* Get the current {@link RenderMaterial} uniforms
* @readonly
*/
get uniforms(): Material['uniforms'] {
return this.material?.uniforms
}
/**
* Get the current {@link RenderMaterial} storages
* @readonly
*/
get storages(): Material['storages'] {
return this.material?.storages
}
/* RESIZE */
/**
* Resize the Mesh's textures
* @param boundingRect
*/
resize(boundingRect?: DOMElementBoundingRect | null) {
// @ts-ignore
if (super.resize) {
// @ts-ignore
super.resize(boundingRect)
}
this.renderTextures?.forEach((renderTexture) => {
// copy from original textures again if needed
if (renderTexture.options.fromTexture) {
renderTexture.copy(renderTexture.options.fromTexture)
}
})
// resize textures
this.textures?.forEach((texture) => {
texture.resize()
})
this._onAfterResizeCallback && this._onAfterResizeCallback()
}
/* EVENTS */
/**
* Assign a callback function to _onReadyCallback
* @param callback - callback to run when {@link MeshBase} is ready
* @returns - our Mesh
*/
onReady(callback: () => void): MeshBase | ProjectedMeshBaseClass {
if (callback) {
this._onReadyCallback = callback
}
return this
}
/**
* Assign a callback function to _onBeforeRenderCallback
* @param callback - callback to run just before {@link MeshBase} will be rendered
* @returns - our Mesh
*/
onBeforeRender(callback: () => void): MeshBase | ProjectedMeshBaseClass {
if (callback) {
this._onBeforeRenderCallback = callback
}
return this
}
/**
* Assign a callback function to _onRenderCallback
* @param callback - callback to run when {@link MeshBase} is rendered
* @returns - our Mesh
*/
onRender(callback: () => void): MeshBase | ProjectedMeshBaseClass {
if (callback) {
this._onRenderCallback = callback
}
return this
}
/**
* Assign a callback function to _onAfterRenderCallback
* @param callback - callback to run just after {@link MeshBase} has been rendered
* @returns - our Mesh
*/
onAfterRender(callback: () => void): MeshBase | ProjectedMeshBaseClass {
if (callback) {
this._onAfterRenderCallback = callback