/
webgpuEngine.ts
3933 lines (3331 loc) · 176 KB
/
webgpuEngine.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 { Logger } from "../Misc/logger";
import { Nullable, DataArray, IndicesArray, FloatArray, Immutable } from "../types";
import { Color4 } from "../Maths/math";
import { Engine } from "../Engines/engine";
import { InstancingAttributeInfo } from "../Engines/instancingAttributeInfo";
import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
import { IEffectCreationOptions, Effect } from "../Materials/effect";
import { EffectFallbacks } from "../Materials/effectFallbacks";
import { _TimeToken } from "../Instrumentation/timeToken";
import { Constants } from "./constants";
import * as WebGPUConstants from './WebGPU/webgpuConstants';
import { VertexBuffer } from "../Meshes/buffer";
import { WebGPUPipelineContext, IWebGPURenderPipelineStageDescriptor, WebGPUBindGroupCacheNode } from './WebGPU/webgpuPipelineContext';
import { IPipelineContext } from './IPipelineContext';
import { DataBuffer } from '../Meshes/dataBuffer';
import { WebGPUDataBuffer } from '../Meshes/WebGPU/webgpuDataBuffer';
import { BaseTexture } from "../Materials/Textures/baseTexture";
import { IShaderProcessor } from "./Processors/iShaderProcessor";
import { WebGPUShaderProcessor } from "./WebGPU/webgpuShaderProcessors";
import { ShaderProcessingContext } from "./Processors/shaderProcessingOptions";
import { WebGPUShaderProcessingContext } from "./WebGPU/webgpuShaderProcessingContext";
import { Tools } from "../Misc/tools";
import { WebGPUTextureHelper } from './WebGPU/webgpuTextureHelper';
import { ISceneLike } from './thinEngine';
import { Scene } from '../scene';
import { WebGPUBufferManager } from './WebGPU/webgpuBufferManager';
import { DepthTextureCreationOptions } from './depthTextureCreationOptions';
import { HardwareTextureWrapper } from '../Materials/Textures/hardwareTextureWrapper';
import { WebGPUHardwareTexture } from './WebGPU/webgpuHardwareTexture';
import { IColor4Like } from '../Maths/math.like';
import { IWebRequest } from '../Misc/interfaces/iWebRequest';
import { UniformBuffer } from '../Materials/uniformBuffer';
import { WebGPURenderPassWrapper } from './WebGPU/webgpuRenderPassWrapper';
import { IMultiRenderTargetOptions } from '../Materials/Textures/multiRenderTarget';
import { WebGPUCacheSampler } from "./WebGPU/webgpuCacheSampler";
import { WebGPUShaderManager } from "./WebGPU/webgpuShaderManager";
import { WebGPUCacheRenderPipeline } from "./WebGPU/webgpuCacheRenderPipeline";
import { WebGPUCacheRenderPipelineTree } from "./WebGPU/webgpuCacheRenderPipelineTree";
import { WebGPUStencilState } from "./WebGPU/webgpuStencilState";
import { WebGPUDepthCullingState } from "./WebGPU/webgpuDepthCullingState";
import "../Shaders/clearQuad.vertex";
import "../Shaders/clearQuad.fragment";
declare type VideoTexture = import("../Materials/Textures/videoTexture").VideoTexture;
declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
// TODO WEBGPU remove when not needed anymore
function assert(condition: any, msg?: string): asserts condition {
if (!condition) {
throw new Error(msg);
}
}
/**
* Options to load the associated Glslang library
*/
export interface GlslangOptions {
/**
* Defines an existing instance of Glslang (useful in modules who do not access the global instance).
*/
glslang?: any;
/**
* Defines the URL of the glslang JS File.
*/
jsPath?: string;
/**
* Defines the URL of the glslang WASM File.
*/
wasmPath?: string;
}
/**
* Options to create the WebGPU engine
*/
export interface WebGPUEngineOptions extends GPURequestAdapterOptions {
/**
* If delta time between frames should be constant
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
*/
deterministicLockstep?: boolean;
/**
* Maximum about of steps between frames (Default: 4)
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
*/
lockstepMaxSteps?: number;
/**
* Defines the seconds between each deterministic lock step
*/
timeStep?: number;
/**
* Defines that engine should ignore modifying touch action attribute and style
* If not handle, you might need to set it up on your side for expected touch devices behavior.
*/
doNotHandleTouchAction?: boolean;
/**
* Defines if webaudio should be initialized as well
* @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
*/
audioEngine?: boolean;
/**
* Defines the category of adapter to use.
* Is it the discrete or integrated device.
*/
powerPreference?: GPUPowerPreference;
/**
* Defines the device descriptor used to create a device.
*/
deviceDescriptor?: GPUDeviceDescriptor;
/**
* Defines the requested Swap Chain Format.
*/
swapChainFormat?: GPUTextureFormat;
/**
* Defines whether MSAA is enabled on the canvas.
*/
antialiasing?: boolean;
/**
* Defines whether the stencil buffer should be enabled.
*/
stencil?: boolean;
/**
* Defines whether we should generate debug markers in the gpu command lists (can be seen with PIX for eg)
*/
enableGPUDebugMarkers?: boolean;
/**
* Options to load the associated Glslang library
*/
glslangOptions?: GlslangOptions;
}
/**
* The web GPU engine class provides support for WebGPU version of babylon.js.
*/
export class WebGPUEngine extends Engine {
// Default glslang options.
private static readonly _glslangDefaultOptions: GlslangOptions = {
jsPath: "https://preview.babylonjs.com/glslang/glslang.js",
wasmPath: "https://preview.babylonjs.com/glslang/glslang.wasm"
};
// Page Life cycle and constants
private readonly _uploadEncoderDescriptor = { label: "upload" };
private readonly _renderEncoderDescriptor = { label: "render" };
private readonly _renderTargetEncoderDescriptor = { label: "renderTarget" };
private readonly _clearDepthValue = 1;
private readonly _clearReverseDepthValue = 0;
private readonly _clearStencilValue = 0;
private readonly _defaultSampleCount = 4; // Only supported value for now.
// Engine Life Cycle
private _canvas: HTMLCanvasElement;
private _options: WebGPUEngineOptions;
private _glslang: any = null;
private _adapter: GPUAdapter;
private _adapterSupportedExtensions: GPUExtensionName[];
private _device: GPUDevice;
private _deviceEnabledExtensions: GPUExtensionName[];
private _context: GPUCanvasContext;
private _swapChain: GPUSwapChain;
private _swapChainTexture: GPUTexture;
private _mainPassSampleCount: number;
private _textureHelper: WebGPUTextureHelper;
private _bufferManager: WebGPUBufferManager;
private _shaderManager: WebGPUShaderManager;
private _cacheSampler: WebGPUCacheSampler;
private _cacheRenderPipeline: WebGPUCacheRenderPipeline;
private _emptyVertexBuffer: VertexBuffer;
private _lastCachedWrapU: number;
private _lastCachedWrapV: number;
private _lastCachedWrapR: number;
private _mrtAttachments: number[];
private _counters: {
numBindGroupsCreation: number;
} = {
numBindGroupsCreation: 0,
};
// Some of the internal state might change during the render pass.
// This happens mainly during clear for the state
// And when the frame starts to swap the target texture from the swap chain
private _mainTexture: GPUTexture;
private _depthTexture: GPUTexture;
private _mainTextureExtends: GPUExtent3D;
private _depthTextureFormat: GPUTextureFormat | undefined;
private _colorFormat: GPUTextureFormat;
// Frame Life Cycle (recreated each frame)
private _uploadEncoder: GPUCommandEncoder;
private _renderEncoder: GPUCommandEncoder;
private _renderTargetEncoder: GPUCommandEncoder;
private _commandBuffers: GPUCommandBuffer[] = [null as any, null as any, null as any];
// Frame Buffer Life Cycle (recreated for each render target pass)
private _currentRenderPass: Nullable<GPURenderPassEncoder> = null;
private _mainRenderPassWrapper: WebGPURenderPassWrapper = new WebGPURenderPassWrapper();
private _rttRenderPassWrapper: WebGPURenderPassWrapper = new WebGPURenderPassWrapper();
private _pendingDebugCommands: Array<[string, Nullable<string>]> = [];
// DrawCall Life Cycle
// Effect is on the parent class
// protected _currentEffect: Nullable<Effect> = null;
private _currentVertexBuffers: Nullable<{ [key: string]: Nullable<VertexBuffer> }> = null;
private _currentOverrideVertexBuffers: Nullable<{ [key: string]: Nullable<VertexBuffer> }> = null;
private _currentIndexBuffer: Nullable<DataBuffer> = null;
private __colorWrite = true;
private _uniformsBuffers: { [name: string]: WebGPUDataBuffer } = {};
private _forceEnableEffect = false;
// TODO WEBGPU remove those variables when code stabilized
/** @hidden */
public dbgShowShaderCode = false;
/** @hidden */
public dbgSanityChecks = false;
/** @hidden */
public dbgGenerateLogs = false;
/** @hidden */
public dbgVerboseLogsForFirstFrames = false;
/** @hidden */
public dbgVerboseLogsNumFrames = 10;
/** @hidden */
public dbgShowWarningsNotImplemented = false;
/**
* Sets this to true to disable the cache for the samplers. You should do it only for testing purpose!
*/
public get disableCacheSamplers(): boolean {
return this._cacheSampler ? this._cacheSampler.disabled : false;
}
public set disableCacheSamplers(disable: boolean) {
if (this._cacheSampler) {
this._cacheSampler.disabled = disable;
}
}
/**
* Sets this to true to disable the cache for the render pipelines. You should do it only for testing purpose!
*/
public get disableCacheRenderPipelines(): boolean {
return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : false;
}
public set disableCacheRenderPipelines(disable: boolean) {
if (this._cacheRenderPipeline) {
this._cacheRenderPipeline.disabled = disable;
}
}
/**
* Gets a boolean indicating if the engine can be instantiated (ie. if a WebGPU context can be found)
* @returns true if the engine can be created
*/
public static get IsSupported(): boolean {
return !!navigator.gpu;
}
/**
* Gets a boolean indicating that the engine supports uniform buffers
*/
public get supportsUniformBuffers(): boolean {
return true;
}
/** Gets the supported extensions by the WebGPU adapter */
public get supportedExtensions(): Immutable<GPUExtensionName[]> {
return this._adapterSupportedExtensions;
}
/** Gets the currently enabled extensions on the WebGPU device */
public get enabledExtensions(): Immutable<GPUExtensionName[]> {
return this._deviceEnabledExtensions;
}
/**
* Returns the name of the engine
*/
public get name(): string {
return "WebGPU";
}
/**
* Returns a string describing the current engine
*/
public get description(): string {
let description = this.name + this.version;
return description;
}
/**
* Returns the version of the engine
*/
public get version(): number {
return 1;
}
/**
* Create a new instance of the gpu engine asynchronously
* @param canvas Defines the canvas to use to display the result
* @param options Defines the options passed to the engine to create the GPU context dependencies
* @returns a promise that resolves with the created engine
*/
public static CreateAsync(canvas: HTMLCanvasElement, options: WebGPUEngineOptions = {}): Promise<WebGPUEngine> {
const engine = new WebGPUEngine(canvas, options);
return new Promise((resolve) => {
engine.initAsync(options.glslangOptions).then(() => resolve(engine));
});
}
/**
* Create a new instance of the gpu engine.
* @param canvas Defines the canvas to use to display the result
* @param options Defines the options passed to the engine to create the GPU context dependencies
*/
public constructor(canvas: HTMLCanvasElement, options: WebGPUEngineOptions = {}) {
super(null);
options.deviceDescriptor = options.deviceDescriptor || { };
options.swapChainFormat = options.swapChainFormat || WebGPUConstants.TextureFormat.BGRA8Unorm;
options.antialiasing = options.antialiasing === undefined ? true : options.antialiasing;
options.stencil = options.stencil ?? true;
options.enableGPUDebugMarkers = options.enableGPUDebugMarkers ?? false;
Logger.Log(`Babylon.js v${Engine.Version} - ${this.description} engine`);
if (!navigator.gpu) {
Logger.Error("WebGPU is not supported by your browser.");
return;
}
this._isWebGPU = true;
this._shaderPlatformName = "WEBGPU";
if (options.deterministicLockstep === undefined) {
options.deterministicLockstep = false;
}
if (options.lockstepMaxSteps === undefined) {
options.lockstepMaxSteps = 4;
}
if (options.audioEngine === undefined) {
options.audioEngine = true;
}
this._deterministicLockstep = options.deterministicLockstep;
this._lockstepMaxSteps = options.lockstepMaxSteps;
this._timeStep = options.timeStep || 1 / 60;
this._doNotHandleContextLost = false;
this._canvas = canvas;
this._options = options;
this.premultipliedAlpha = false;
this._hardwareScalingLevel = 1;
this._mainPassSampleCount = options.antialiasing ? this._defaultSampleCount : 1;
this._isStencilEnable = options.stencil;
this._sharedInit(canvas, !!options.doNotHandleTouchAction, options.audioEngine);
this._shaderProcessor = this._getShaderProcessor();
// TODO. WEBGPU. Use real way to do it.
this._canvas.style.transform = "scaleY(-1)";
}
//------------------------------------------------------------------------------
// Initialization
//------------------------------------------------------------------------------
/**
* Initializes the WebGPU context and dependencies.
* @param glslangOptions Defines the GLSLang compiler options if necessary
* @returns a promise notifying the readiness of the engine.
*/
public initAsync(glslangOptions?: GlslangOptions): Promise<void> {
return this._initGlslang(glslangOptions ?? this._options?.glslangOptions)
.then((glslang: any) => {
this._glslang = glslang;
return navigator.gpu!.requestAdapter(this._options);
})
.then((adapter: GPUAdapter | null) => {
this._adapter = adapter!;
this._adapterSupportedExtensions = this._adapter.extensions.slice(0);
const deviceDescriptor = this._options.deviceDescriptor;
if (deviceDescriptor?.extensions) {
const requestedExtensions = deviceDescriptor.extensions;
const validExtensions = [];
const iterator = requestedExtensions[Symbol.iterator]();
while (true) {
const { done, value : extension } = iterator.next();
if (done) {
break;
}
if (this._adapterSupportedExtensions.indexOf(extension) >= 0) {
validExtensions.push(extension);
}
}
deviceDescriptor.extensions = validExtensions;
}
return this._adapter.requestDevice(this._options.deviceDescriptor);
})
.then((device: GPUDevice | null) => {
this._device = device!;
this._deviceEnabledExtensions = this._device.extensions.slice(0);
})
.then(() => {
this._bufferManager = new WebGPUBufferManager(this._device);
this._textureHelper = new WebGPUTextureHelper(this._device, this._glslang, this._bufferManager);
this._shaderManager = new WebGPUShaderManager(this._device);
this._cacheSampler = new WebGPUCacheSampler(this._device);
if (this.dbgVerboseLogsForFirstFrames) {
if ((this as any)._count === undefined) {
(this as any)._count = 0;
console.log("%c frame #" + (this as any)._count + " - begin", "background: #ffff00");
}
}
this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);
this._emptyVertexBuffer = new VertexBuffer(this, [0], "", false, false, 1, false, 0, 1);
this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, this._emptyVertexBuffer);
this._depthCullingState = new WebGPUDepthCullingState(this._cacheRenderPipeline);
this._stencilState = new WebGPUStencilState(this._cacheRenderPipeline);
this._depthCullingState.depthTest = true;
this._depthCullingState.depthFunc = Constants.LEQUAL;
this._depthCullingState.depthMask = true;
this._textureHelper.setCommandEncoder(this._uploadEncoder);
this._initializeLimits();
this._initializeContextAndSwapChain();
this._initializeMainAttachments();
this.resize();
})
.catch((e: any) => {
Logger.Error("Can not create WebGPU Device and/or context.");
Logger.Error(e);
if (console.trace) {
console.trace();
}
});
}
private _initGlslang(glslangOptions?: GlslangOptions): Promise<any> {
glslangOptions = glslangOptions || { };
glslangOptions = {
...WebGPUEngine._glslangDefaultOptions,
...glslangOptions
};
if (glslangOptions.glslang) {
return Promise.resolve(glslangOptions.glslang);
}
if ((window as any).glslang) {
return (window as any).glslang(glslangOptions!.wasmPath);
}
if (glslangOptions.jsPath && glslangOptions.wasmPath) {
return Tools.LoadScriptAsync(glslangOptions.jsPath)
.then(() => {
return (window as any).glslang(glslangOptions!.wasmPath);
});
}
return Promise.reject("gslang is not available.");
}
private _initializeLimits(): void {
// Init caps
// TODO WEBGPU Real Capability check once limits will be working.
this._caps = {
maxTexturesImageUnits: 16,
maxVertexTextureImageUnits: 16,
maxCombinedTexturesImageUnits: 32,
maxTextureSize: 2048,
maxCubemapTextureSize: 2048,
maxRenderTextureSize: 2048,
maxVertexAttribs: 16,
maxVaryingVectors: 16,
maxFragmentUniformVectors: 1024,
maxVertexUniformVectors: 1024,
standardDerivatives: true,
astc: null,
s3tc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.ExtensionName.TextureCompressionBC) >= 0 ? true : undefined) as any,
pvrtc: null,
etc1: null,
etc2: null,
bptc: this._deviceEnabledExtensions.indexOf(WebGPUConstants.ExtensionName.TextureCompressionBC) >= 0 ? true : undefined,
maxAnisotropy: 16, // TODO WEBGPU: Retrieve this smartly
uintIndices: true,
fragmentDepthSupported: true,
highPrecisionShaderSupported: true,
colorBufferFloat: true,
textureFloat: true,
textureFloatLinearFiltering: true,
textureFloatRender: true,
textureHalfFloat: true,
textureHalfFloatLinearFiltering: true,
textureHalfFloatRender: true,
textureLOD: true,
drawBuffersExtension: true,
depthTextureExtension: true,
vertexArrayObject: false,
instancedArrays: true,
timerQuery: undefined,
canUseTimestampForTimerQuery: false,
multiview: false,
oculusMultiview: false,
parallelShaderCompile: undefined,
blendMinMax: true,
maxMSAASamples: 4,
canUseGLInstanceID: true,
canUseGLVertexID: true
};
this._caps.parallelShaderCompile = null as any;
this._features = {
forceBitmapOverHTMLImageElement: true,
supportRenderAndCopyToLodForFloatTextures: true,
supportDepthStencilTexture: true,
supportShadowSamplers: true,
uniformBufferHardCheckMatrix: true,
allowTexturePrefiltering: true,
trackUbosInFrame: true,
supportCSM: true,
basisNeedsPOT: false,
support3DTextures: false, // TODO WEBGPU change to true when Chrome supports 3D textures
needTypeSuffixInShaderConstants: true,
supportMSAA: true,
supportSSAO2: true,
supportExtendedTextureFormats: true,
supportSwitchCaseInShader: true,
supportSyncTextureRead: false,
needsInvertingBitmap: false,
_collectUbosUpdatedInFrame: true,
};
}
private _initializeContextAndSwapChain(): void {
this._context = this._canvas.getContext('gpupresent') as unknown as GPUCanvasContext;
this._swapChain = this._context.configureSwapChain({
device: this._device,
format: this._options.swapChainFormat!,
usage: WebGPUConstants.TextureUsage.OutputAttachment | WebGPUConstants.TextureUsage.CopySrc,
});
this._colorFormat = this._options.swapChainFormat!;
this._mainRenderPassWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture()];
this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat;
if (this.dbgGenerateLogs) {
this._context.getSwapChainPreferredFormat(this._device).then((format) => {
console.log("Swap chain preferred format:", format);
});
}
}
// Set default values as WebGL with depth and stencil attachment for the broadest Compat.
private _initializeMainAttachments(): void {
this._mainTextureExtends = {
width: this.getRenderWidth(),
height: this.getRenderHeight(),
depth: 1
};
let mainColorAttachments: GPURenderPassColorAttachmentDescriptor[];
if (this._options.antialiasing) {
const mainTextureDescriptor: GPUTextureDescriptor = {
size: this._mainTextureExtends,
mipLevelCount: 1,
sampleCount: this._mainPassSampleCount,
dimension: WebGPUConstants.TextureDimension.E2d,
format: this._options.swapChainFormat!,
usage: WebGPUConstants.TextureUsage.OutputAttachment,
};
if (this._mainTexture) {
this._mainTexture.destroy();
}
this._mainTexture = this._device.createTexture(mainTextureDescriptor);
mainColorAttachments = [{
attachment: this._mainTexture.createView(),
loadValue: new Color4(0, 0, 0, 1),
storeOp: WebGPUConstants.StoreOp.Store
}];
}
else {
mainColorAttachments = [{
attachment: undefined as any,
loadValue: new Color4(0, 0, 0, 1),
storeOp: WebGPUConstants.StoreOp.Store
}];
}
this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? WebGPUConstants.TextureFormat.Depth24PlusStencil8 : WebGPUConstants.TextureFormat.Depth32Float;
this._setDepthTextureFormat(this._mainRenderPassWrapper);
const depthTextureDescriptor: GPUTextureDescriptor = {
size: this._mainTextureExtends,
mipLevelCount: 1,
sampleCount: this._mainPassSampleCount,
dimension: WebGPUConstants.TextureDimension.E2d,
format: this._mainRenderPassWrapper.depthTextureFormat,
usage: WebGPUConstants.TextureUsage.OutputAttachment
};
if (this._depthTexture) {
this._depthTexture.destroy();
}
this._depthTexture = this._device.createTexture(depthTextureDescriptor);
const mainDepthAttachment: GPURenderPassDepthStencilAttachmentDescriptor = {
attachment: this._depthTexture.createView(),
depthLoadValue: this._clearDepthValue,
depthStoreOp: WebGPUConstants.StoreOp.Store,
stencilLoadValue: this._clearStencilValue,
stencilStoreOp: WebGPUConstants.StoreOp.Store,
};
this._mainRenderPassWrapper.renderPassDescriptor = {
colorAttachments: mainColorAttachments,
depthStencilAttachment: mainDepthAttachment
};
if (this._mainRenderPassWrapper.renderPass !== null) {
this._endMainRenderPass();
}
}
/**
* Force a specific size of the canvas
* @param width defines the new canvas' width
* @param height defines the new canvas' height
* @param forceSetSize true to force setting the sizes of the underlying canvas
* @returns true if the size was changed
*/
public setSize(width: number, height: number, forceSetSize = false): boolean {
if (!super.setSize(width, height, forceSetSize)) {
return false;
}
if (this.dbgVerboseLogsForFirstFrames) {
if ((this as any)._count === undefined) { (this as any)._count = 0; }
if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
console.log("frame #" + (this as any)._count + " - setSize called -", width, height);
}
}
this._initializeMainAttachments();
return true;
}
/**
* Gets a shader processor implementation fitting with the current engine type.
* @returns The shader processor implementation.
*/
protected _getShaderProcessor(): Nullable<IShaderProcessor> {
return new WebGPUShaderProcessor();
}
/** @hidden */
public _getShaderProcessingContext(): Nullable<ShaderProcessingContext> {
return new WebGPUShaderProcessingContext();
}
//------------------------------------------------------------------------------
// Static Pipeline WebGPU States
//------------------------------------------------------------------------------
/**
* Force the entire cache to be cleared
* You should not have to use this function unless your engine needs to share the WebGPU context with another engine
* @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
*/
public wipeCaches(bruteForce?: boolean): void {
if (this.preventCacheWipeBetweenFrames && !bruteForce) {
return;
}
//this._currentEffect = null; // can't reset _currentEffect, else some crashes can occur (for eg in ProceduralTexture which calls bindFrameBuffer (which calls wipeCaches) after having called enableEffect and before drawing into the texture)
// _forceEnableEffect = true assumes the role of _currentEffect = null
this._forceEnableEffect = true;
this._currentIndexBuffer = null;
this._currentVertexBuffers = null;
this._currentOverrideVertexBuffers = null;
this._cacheRenderPipeline.setBuffers(null, null, null);
if (bruteForce) {
this._currentProgram = null;
this._stencilState.reset();
this._depthCullingState.reset();
this._depthCullingState.depthFunc = Constants.LEQUAL;
this._alphaState.reset();
this._alphaMode = Constants.ALPHA_ADD;
this._alphaEquation = Constants.ALPHA_DISABLE;
this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);
this._cacheRenderPipeline.setAlphaBlendEnabled(false);
this.setColorWrite(true);
}
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._cachedEffectForVertexBuffers = null;
}
/**
* Enable or disable color writing
* @param enable defines the state to set
*/
public setColorWrite(enable: boolean): void {
this.__colorWrite = enable;
this._cacheRenderPipeline.setWriteMask(enable ? 0xF : 0);
}
/**
* Gets a boolean indicating if color writing is enabled
* @returns the current color writing state
*/
public getColorWrite(): boolean {
return this.__colorWrite;
}
//------------------------------------------------------------------------------
// Dynamic WebGPU States
//------------------------------------------------------------------------------
private _viewportsCurrent: Array<{ x: number, y: number, w: number, h: number }> = [{ x: 0, y: 0, w: 0, h: 0 }, { x: 0, y: 0, w: 0, h: 0 }];
private _resetCurrentViewport(index: number) {
this._viewportsCurrent[index].x = 0;
this._viewportsCurrent[index].y = 0;
this._viewportsCurrent[index].w = 0;
this._viewportsCurrent[index].h = 0;
}
private _applyViewport(renderPass: GPURenderPassEncoder): void {
const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;
const x = this._viewportCached.x,
y = this._viewportCached.y,
w = this._viewportCached.z,
h = this._viewportCached.w;
if (this._viewportsCurrent[index].x !== x || this._viewportsCurrent[index].y !== y ||
this._viewportsCurrent[index].w !== w || this._viewportsCurrent[index].h !== h)
{
this._viewportsCurrent[index].x = x;
this._viewportsCurrent[index].y = y;
this._viewportsCurrent[index].w = w;
this._viewportsCurrent[index].h = h;
renderPass.setViewport(x, y, w, h, 0, 1);
if (this.dbgVerboseLogsForFirstFrames) {
if ((this as any)._count === undefined) { (this as any)._count = 0; }
if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
console.log("frame #" + (this as any)._count + " - viewport applied - (", x, y, w, h, ") current pass is main pass=" + (renderPass === this._mainRenderPassWrapper.renderPass));
}
}
}
}
/** @hidden */
public _viewport(x: number, y: number, width: number, height: number): void {
this._viewportCached.x = x;
this._viewportCached.y = y;
this._viewportCached.z = width;
this._viewportCached.w = height;
}
private _scissorsCurrent: Array<{ x: number, y: number, w: number, h: number }> = [{ x: 0, y: 0, w: 0, h: 0 }, { x: 0, y: 0, w: 0, h: 0 }];
protected _scissorCached = { x: 0, y: 0, z: 0, w: 0 };
private _resetCurrentScissor(index: number) {
this._scissorsCurrent[index].x = 0;
this._scissorsCurrent[index].y = 0;
this._scissorsCurrent[index].w = 0;
this._scissorsCurrent[index].h = 0;
}
private _applyScissor(renderPass: GPURenderPassEncoder): void {
const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;
const x = this._scissorCached.x,
y = this._scissorCached.y,
w = this._scissorCached.z,
h = this._scissorCached.w;
if (this._scissorsCurrent[index].x !== x || this._scissorsCurrent[index].y !== y ||
this._scissorsCurrent[index].w !== w || this._scissorsCurrent[index].h !== h)
{
this._scissorsCurrent[index].x = x;
this._scissorsCurrent[index].y = y;
this._scissorsCurrent[index].w = w;
this._scissorsCurrent[index].h = h;
renderPass.setScissorRect(x, y, w, h);
if (this.dbgVerboseLogsForFirstFrames) {
if ((this as any)._count === undefined) { (this as any)._count = 0; }
if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
console.log("frame #" + (this as any)._count + " - scissor applied - (", x, y, w, h, ") current pass is main pass=" + (renderPass === this._mainRenderPassWrapper.renderPass));
}
}
}
}
private _scissorIsActive() {
return this._scissorCached.x !== 0 ||
this._scissorCached.y !== 0 ||
(this._scissorCached.z !== this.getRenderWidth() && this._scissorCached.z !== 0) ||
(this._scissorCached.w !== this.getRenderHeight() && this._scissorCached.w !== 0);
}
public enableScissor(x: number, y: number, width: number, height: number): void {
this._scissorCached.x = x;
this._scissorCached.y = y;
this._scissorCached.z = width;
this._scissorCached.w = height;
}
public disableScissor() {
this._scissorCached.x = 0;
this._scissorCached.y = 0;
this._scissorCached.z = this.getRenderWidth();
this._scissorCached.w = this.getRenderHeight();
}
/**
* Clear the current render buffer or the current render target (if any is set up)
* @param color defines the color to use
* @param backBuffer defines if the back buffer must be cleared
* @param depth defines if the depth buffer must be cleared
* @param stencil defines if the stencil buffer must be cleared
*/
public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
// Some PGs are using color3...
if (color && color.a === undefined) {
color.a = 1;
}
if (this.dbgVerboseLogsForFirstFrames) {
if ((this as any)._count === undefined) { (this as any)._count = 0; }
if (!(this as any)._count || (this as any)._count < this.dbgVerboseLogsNumFrames) {
console.log("frame #" + (this as any)._count + " - clear called - backBuffer=", backBuffer, " depth=", depth, " stencil=", stencil);
}
}
// We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account
if (this._currentRenderTarget) {
if (this._currentRenderPass) {
this._endRenderTargetRenderPass();
}
this._startRenderTargetRenderPass(this._currentRenderTarget!, backBuffer ? color : null, backBuffer ? color : null, depth, stencil);
} else {
this._startMainRenderPass(true, backBuffer ? color : null, depth, stencil);
}
}
/**
* Clears a list of attachments
* @param attachments list of the attachments
* @param colorMain clear color for the main attachment (the first one)
* @param colorOthers clear color for the other attachments
* @param clearDepth true to clear the depth buffer. Used only for the first attachment
* @param clearStencil true to clear the stencil buffer. Used only for the first attachment
*/
public clearAttachments(attachments: number[], colorMain: Nullable<IColor4Like>, colorOthers: Nullable<IColor4Like>, clearDepth: boolean, clearStencil: boolean): void {
if (attachments.length === 0 || !this._currentRenderTarget) {
return;
}
if (this._currentRenderPass) {
this._endRenderTargetRenderPass();
}
this._startRenderTargetRenderPass(this._currentRenderTarget!, colorMain, colorOthers, clearDepth, clearStencil);
}
//------------------------------------------------------------------------------
// Vertex/Index Buffers
//------------------------------------------------------------------------------
/**
* Creates a vertex buffer
* @param data the data for the vertex buffer
* @returns the new buffer
*/
public createVertexBuffer(data: DataArray): DataBuffer {
let view: ArrayBufferView;
if (data instanceof Array) {
view = new Float32Array(data);
}
else if (data instanceof ArrayBuffer) {
view = new Uint8Array(data);
}
else {
view = data;
}
const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Vertex | WebGPUConstants.BufferUsage.CopyDst);
return dataBuffer;
}
/**
* Creates a vertex buffer
* @param data the data for the dynamic vertex buffer
* @returns the new buffer
*/
public createDynamicVertexBuffer(data: DataArray): DataBuffer {
return this.createVertexBuffer(data);
}
/**
* Updates a vertex buffer.
* @param vertexBuffer the vertex buffer to update
* @param data the data used to update the vertex buffer
* @param byteOffset the byte offset of the data
* @param byteLength the byte length of the data
*/
public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
const dataBuffer = vertexBuffer as WebGPUDataBuffer;
if (byteOffset === undefined) {
byteOffset = 0;
}
let view: ArrayBufferView;
if (byteLength === undefined) {
if (data instanceof Array) {
view = new Float32Array(data);
}
else if (data instanceof ArrayBuffer) {
view = new Uint8Array(data);
}
else {
view = data;
}
byteLength = view.byteLength;
} else {
if (data instanceof Array) {
view = new Float32Array(data);
}
else if (data instanceof ArrayBuffer) {
view = new Uint8Array(data);
}
else {
view = data;
}
}
this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength);
}
/**
* Creates a new index buffer
* @param indices defines the content of the index buffer
* @param updatable defines if the index buffer must be updatable - not used in WebGPU
* @returns a new buffer
*/
public createIndexBuffer(indices: IndicesArray, updatable?: boolean): DataBuffer {
let is32Bits = true;
let view: ArrayBufferView;
if (indices instanceof Uint32Array || indices instanceof Int32Array) {
view = indices;