matrix-engine-wgpu 1.0.6 → 1.1.1

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 (71) hide show
  1. package/.codesandbox/tasks.json +46 -0
  2. package/.devcontainer/devcontainer.json +22 -0
  3. package/.github/dependabot.yml +12 -0
  4. package/REFERENCE.md +3 -5
  5. package/dev.md +460 -0
  6. package/empty.js +7 -6
  7. package/examples/games/jamb/jamb.js +1133 -0
  8. package/examples/load-obj-file.js +65 -28
  9. package/examples/unlit-textures.js +26 -23
  10. package/examples.js +35 -3
  11. package/index.js +8 -2
  12. package/main.js +454 -48
  13. package/non-project-files/dev.txt +21 -0
  14. package/non-project-files/image1.png +0 -0
  15. package/non-project-files/image6.png +0 -0
  16. package/package.json +31 -13
  17. package/public/app.js +2234 -114
  18. package/public/css/style.css +371 -110
  19. package/public/empty.html +1 -1
  20. package/public/empty.js +9887 -9264
  21. package/public/examples.html +10 -8
  22. package/public/examples.js +2035 -247
  23. package/public/index.html +3 -5
  24. package/public/manifest copy.web +35 -0
  25. package/public/res/audios/block.mp3 +0 -0
  26. package/public/res/audios/dice1.mp3 +0 -0
  27. package/public/res/audios/dice2.mp3 +0 -0
  28. package/public/res/audios/start.mp3 +0 -0
  29. package/public/res/meshes/jamb/bg.blend +0 -0
  30. package/public/res/meshes/jamb/bg.blend1 +0 -0
  31. package/public/res/meshes/jamb/bg.mtl +12 -0
  32. package/public/res/meshes/jamb/bg.obj +17 -0
  33. package/public/res/meshes/jamb/bg.png +0 -0
  34. package/public/res/meshes/jamb/dice-default.png +0 -0
  35. package/public/res/meshes/jamb/dice-mark.png +0 -0
  36. package/public/res/meshes/jamb/dice.mtl +12 -0
  37. package/public/res/meshes/jamb/dice.obj +40 -0
  38. package/public/res/meshes/jamb/dice.png +0 -0
  39. package/public/res/meshes/jamb/jamb-title.mtl +12 -0
  40. package/public/res/meshes/jamb/jamb-title.obj +26008 -0
  41. package/public/res/meshes/jamb/jamb.blend +0 -0
  42. package/public/res/meshes/jamb/jamb.blend1 +0 -0
  43. package/public/res/meshes/jamb/logo.png +0 -0
  44. package/public/res/meshes/jamb/nidzaDice.blend +0 -0
  45. package/public/res/meshes/jamb/nidzaDice.blend1 +0 -0
  46. package/public/res/meshes/jamb/pile.blend +0 -0
  47. package/public/res/meshes/jamb/simpleCube.blend +0 -0
  48. package/public/res/meshes/jamb/simpleCube.blend1 +0 -0
  49. package/public/res/meshes/jamb/sounds/roll1.wav +0 -0
  50. package/public/res/meshes/jamb/text.png +0 -0
  51. package/public/res/multilang/en.json +27 -0
  52. package/public/res/multilang/sr.json +27 -0
  53. package/public/test.html +636 -0
  54. package/public/three-test.js +165 -0
  55. package/public/worker.html +1 -1
  56. package/readme.md +193 -115
  57. package/src/engine/ball.js +477 -468
  58. package/src/engine/cube.js +486 -468
  59. package/src/engine/engine.js +4 -6
  60. package/src/engine/loader-obj.js +9 -6
  61. package/src/engine/matrix-class.js +237 -204
  62. package/src/engine/mesh-obj.js +603 -515
  63. package/src/engine/raycast.js +101 -0
  64. package/src/engine/utils.js +69 -3
  65. package/src/multilang/lang.js +35 -0
  66. package/src/physics/matrix-ammo.js +168 -15
  67. package/src/shaders/fragment.wgsl.js +4 -2
  68. package/src/shaders/shaders.js +1 -1
  69. package/src/shaders/vertexShadow.wgsl.js +1 -1
  70. package/src/sounds/sounds.js +47 -0
  71. package/src/world.js +311 -248
@@ -4,521 +4,609 @@ import {createInputHandler} from "./engine";
4
4
  import {vertexShadowWGSL} from '../shaders/vertexShadow.wgsl';
5
5
  import {fragmentWGSL} from '../shaders/fragment.wgsl';
6
6
  import {vertexWGSL} from '../shaders/vertex.wgsl';
7
- import {degToRad, LOG_INFO} from './utils';
7
+ import {degToRad, genName, LOG_FUNNY, LOG_FUNNY_SMALL, LOG_INFO} from './utils';
8
+ import {checkingProcedure, checkingRay, touchCoordinate} from './raycast';
8
9
 
9
10
  export default class MEMeshObj {
10
-
11
- constructor(canvas, device, context, o) {
12
-
13
- this.done = false;
14
- this.device = device;
15
- this.context = context;
16
- this.entityArgPass = o.entityArgPass;
17
-
18
- // Mesh stuff
19
- this.mesh = o.mesh;
20
- this.mesh.uvs = this.mesh.textures;
21
- console.log(`%c Mesh loaded: ${o.name}`, LOG_INFO);
22
-
23
- this.inputHandler = createInputHandler(window, canvas);
24
- this.cameras = o.cameras;
25
-
26
- this.mainCameraParams = {
27
- type: o.mainCameraParams.type,
28
- responseCoef: o.mainCameraParams.responseCoef
29
- }
30
-
31
- this.lastFrameMS = 0;
32
- this.texturesPaths = [];
33
- o.texturesPaths.forEach((t) => {this.texturesPaths.push(t)})
34
-
35
- this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
36
-
37
- this.position = new Position(o.position.x, o.position.y, o.position.z);
38
- this.rotation = new Rotation(o.rotation.x, o.rotation.y, o.rotation.z);
39
- this.rotation.rotationSpeed.x = o.rotationSpeed.x;
40
- this.rotation.rotationSpeed.y = o.rotationSpeed.y;
41
- this.rotation.rotationSpeed.z = o.rotationSpeed.z;
42
- this.scale = o.scale;
43
-
44
- this.runProgram = () => {
45
- return new Promise(async (resolve) => {
46
- this.shadowDepthTextureSize = 1024;
47
- const aspect = canvas.width / canvas.height;
48
- this.projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 1, 2000.0);
49
- this.modelViewProjectionMatrix = mat4.create();
50
- // console.log('cube added texturesPaths: ', this.texturesPaths)
51
- this.loadTex0(this.texturesPaths, device).then(() => {
52
- // console.log('loaded tex buffer for mesh:', this.texture0)
53
- resolve()
54
- })
55
- })
56
- }
57
-
58
- this.runProgram().then(() => {
59
- const aspect = canvas.width / canvas.height;
60
- const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
61
- this.context.configure({
62
- device: this.device,
63
- format: presentationFormat,
64
- alphaMode: 'premultiplied',
65
- });
66
-
67
- // Create the model vertex buffer.
68
- this.vertexBuffer = this.device.createBuffer({
69
- size: this.mesh.vertices.length * Float32Array.BYTES_PER_ELEMENT,
70
- usage: GPUBufferUsage.VERTEX,
71
- mappedAtCreation: true,
72
- });
73
- {
74
- // const mapping = new Float32Array(this.vertexBuffer.getMappedRange());
75
- // // for(let i = 0;i < this.mesh.vertices.length;++i) {
76
- // // mapping.set(this.mesh.vertices[i], 6 * i);
77
- // // mapping.set(this.mesh.normals[i], 6 * i + 3);
78
- // // }
79
- // this.vertexBuffer.unmap();
80
- new Float32Array(this.vertexBuffer.getMappedRange()).set(this.mesh.vertices);
81
- this.vertexBuffer.unmap();
82
- }
83
-
84
- // NIDZA TEST SECOUND BUFFER
85
- // Create the model vertex buffer.
86
- this.vertexNormalsBuffer = this.device.createBuffer({
87
- size: this.mesh.vertexNormals.length * Float32Array.BYTES_PER_ELEMENT,
88
- usage: GPUBufferUsage.VERTEX,
89
- mappedAtCreation: true,
90
- });
91
- {
92
- new Float32Array(this.vertexNormalsBuffer.getMappedRange()).set(this.mesh.vertexNormals);
93
- this.vertexNormalsBuffer.unmap();
94
- }
95
-
96
- this.vertexTexCoordsBuffer = this.device.createBuffer({
97
- size: this.mesh.textures.length * Float32Array.BYTES_PER_ELEMENT,
98
- usage: GPUBufferUsage.VERTEX,
99
- mappedAtCreation: true,
100
- });
101
- {
102
- new Float32Array(this.vertexTexCoordsBuffer.getMappedRange()).set(this.mesh.textures);
103
- this.vertexTexCoordsBuffer.unmap();
104
- }
105
-
106
- // Create the model index buffer.
107
- this.indexCount = this.mesh.indices.length;
108
- this.indexBuffer = this.device.createBuffer({
109
- size: this.indexCount * Uint16Array.BYTES_PER_ELEMENT,
110
- usage: GPUBufferUsage.INDEX,
111
- mappedAtCreation: true,
112
- });
113
- {
114
- // const mapping = new Uint16Array(this.indexBuffer.getMappedRange());
115
- // for(let i = 0;i < this.mesh.indices.length;++i) {
116
- // mapping.set(this.mesh.indices[i], i);
117
- // }
118
- new Uint16Array(this.indexBuffer.getMappedRange()).set(this.mesh.indices);
119
- this.indexBuffer.unmap();
120
- }
121
-
122
- // Create the depth texture for rendering/sampling the shadow map.
123
- this.shadowDepthTexture = this.device.createTexture({
124
- size: [this.shadowDepthTextureSize, this.shadowDepthTextureSize, 1],
125
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
126
- format: 'depth32float',
127
- });
128
- this.shadowDepthTextureView = this.shadowDepthTexture.createView();
129
-
130
- // Create some common descriptors used for both the shadow pipeline
131
- // and the color rendering pipeline.
132
- this.vertexBuffers = [
133
- {
134
- arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
135
- attributes: [
136
- {
137
- // position
138
- shaderLocation: 0,
139
- offset: 0,
140
- format: "float32x3",
141
- }
142
- ],
143
- },
144
- {
145
- arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
146
- attributes: [
147
- {
148
- // normal
149
- shaderLocation: 1,
150
- offset: 0,
151
- format: "float32x3",
152
- },
153
- ],
154
- },
155
- {
156
- arrayStride: Float32Array.BYTES_PER_ELEMENT * 2,
157
- attributes: [
158
- {
159
- // uvs
160
- shaderLocation: 2,
161
- offset: 0,
162
- format: "float32x2",
163
- },
164
- ],
165
- },
166
- ];
167
-
168
- const primitive = {
169
- topology: 'triangle-list',
170
- cullMode: 'back',
171
- };
172
-
173
- this.uniformBufferBindGroupLayout = this.device.createBindGroupLayout({
174
- entries: [
175
- {
176
- binding: 0,
177
- visibility: GPUShaderStage.VERTEX,
178
- buffer: {
179
- type: 'uniform',
180
- },
181
- },
182
- ],
183
- });
184
-
185
- this.shadowPipeline = this.device.createRenderPipeline({
186
- layout: this.device.createPipelineLayout({
187
- bindGroupLayouts: [
188
- this.uniformBufferBindGroupLayout,
189
- this.uniformBufferBindGroupLayout,
190
- ],
191
- }),
192
- vertex: {
193
- module: this.device.createShaderModule({
194
- code: vertexShadowWGSL,
195
- }),
196
- buffers: this.vertexBuffers,
197
- },
198
- depthStencil: {
199
- depthWriteEnabled: true,
200
- depthCompare: 'less',
201
- format: 'depth32float',
202
- },
203
- primitive,
204
- });
205
-
206
- // Create a bind group layout which holds the scene uniforms and
207
- // the texture+sampler for depth. We create it manually because the WebPU
208
- // implementation doesn't infer this from the shader (yet).
209
- this.bglForRender = this.device.createBindGroupLayout({
210
- entries: [
211
- {
212
- binding: 0,
213
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
214
- buffer: {
215
- type: 'uniform',
216
- },
217
- },
218
- {
219
- binding: 1,
220
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
221
- texture: {
222
- sampleType: 'depth',
223
- },
224
- },
225
- {
226
- binding: 2,
227
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
228
- sampler: {
229
- type: 'comparison',
230
- },
231
- },
232
- {
233
- binding: 3,
234
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
235
- texture: {
236
- sampleType: 'float',
237
- }
238
- },
239
- {
240
- binding: 4,
241
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
242
- sampler: {
243
- type: 'filtering',
244
- }
245
- }
246
- ]
247
- });
248
-
249
- this.pipeline = this.device.createRenderPipeline({
250
- layout: this.device.createPipelineLayout({
251
- bindGroupLayouts: [this.bglForRender, this.uniformBufferBindGroupLayout],
252
- }),
253
- vertex: {
254
- module: this.device.createShaderModule({
255
- code: vertexWGSL,
256
- }),
257
- buffers: this.vertexBuffers,
258
- },
259
- fragment: {
260
- module: this.device.createShaderModule({
261
- code: fragmentWGSL,
262
- }),
263
- targets: [
264
- {
265
- format: presentationFormat,
266
- },
267
- ],
268
- constants: {
269
- shadowDepthTextureSize: this.shadowDepthTextureSize,
270
- },
271
- },
272
- depthStencil: {
273
- depthWriteEnabled: true,
274
- depthCompare: 'less',
275
- format: 'depth24plus-stencil8',
276
- },
277
- primitive,
278
- });
279
-
280
- const depthTexture = this.device.createTexture({
281
- size: [canvas.width, canvas.height],
282
- format: 'depth24plus-stencil8',
283
- usage: GPUTextureUsage.RENDER_ATTACHMENT,
284
- });
285
-
286
- this.renderPassDescriptor = {
287
- colorAttachments: [
288
- {
289
- // view is acquired and set in render loop.
290
- view: undefined,
291
- clearValue: {r: 0.5, g: 0.5, b: 0.5, a: 1.0},
292
- loadOp: 'load',
293
- storeOp: 'store',
294
- },
295
- ],
296
- depthStencilAttachment: {
297
- view: depthTexture.createView(),
298
- depthClearValue: 1.0,
299
- depthLoadOp: 'clear',
300
- depthStoreOp: 'store',
301
- stencilClearValue: 0,
302
- stencilLoadOp: 'clear',
303
- stencilStoreOp: 'store',
304
- },
305
- };
306
-
307
- this.modelUniformBuffer = this.device.createBuffer({
308
- size: 4 * 16, // 4x4 matrix
309
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
310
- });
311
-
312
- this.sceneUniformBuffer = this.device.createBuffer({
313
- // Two 4x4 viewProj matrices,
314
- // one for the camera and one for the light.
315
- // Then a vec3 for the light position.
316
- // Rounded to the nearest multiple of 16.
317
- size: 2 * 4 * 16 + 4 * 4,
318
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
319
- });
320
-
321
- this.sceneBindGroupForShadow = this.device.createBindGroup({
322
- layout: this.uniformBufferBindGroupLayout,
323
- entries: [
324
- {
325
- binding: 0,
326
- resource: {
327
- buffer: this.sceneUniformBuffer,
328
- },
329
- },
330
- ],
331
- });
332
-
333
- this.sceneBindGroupForRender = this.device.createBindGroup({
334
- layout: this.bglForRender,
335
- entries: [
336
- {
337
- binding: 0,
338
- resource: {
339
- buffer: this.sceneUniformBuffer,
340
- },
341
- },
342
- {
343
- binding: 1,
344
- resource: this.shadowDepthTextureView,
345
- },
346
- {
347
- binding: 2,
348
- resource: this.device.createSampler({
349
- compare: 'less',
350
- }),
351
- },
352
- {
353
- binding: 3,
354
- resource: this.texture0.createView(),
355
- },
356
- {
357
- binding: 4,
358
- resource: this.sampler,
359
- },
360
- ],
361
- });
362
-
363
- this.modelBindGroup = this.device.createBindGroup({
364
- layout: this.uniformBufferBindGroupLayout,
365
- entries: [
366
- {
367
- binding: 0,
368
- resource: {
369
- buffer: this.modelUniformBuffer,
370
- },
371
- },
372
- ],
373
- });
374
-
375
- // Rotates the camera around the origin based on time.
376
- this.getTransformationMatrix = (pos) => {
377
- const now = Date.now();
378
- const deltaTime = (now - this.lastFrameMS) / this.mainCameraParams.responseCoef;
379
- this.lastFrameMS = now;
380
- // const this.viewMatrix = mat4.identity()
381
- const camera = this.cameras[this.mainCameraParams.type];
382
- this.viewMatrix = camera.update(deltaTime, this.inputHandler());
383
- mat4.translate(this.viewMatrix, vec3.fromValues(pos.x, pos.y, pos.z), this.viewMatrix);
384
- mat4.rotate(
385
- this.viewMatrix,
386
- vec3.fromValues(this.rotation.axis.x, this.rotation.axis.y, this.rotation.axis.z),
387
- degToRad(this.rotation.angle), this.viewMatrix)
388
- // mat4.rotateX(this.viewMatrix, this.rotation.getRotX(), this.viewMatrix);
389
- // mat4.rotateY(this.viewMatrix, this.rotation.getRotY(), this.viewMatrix);
390
- // mat4.rotateZ(this.viewMatrix, this.rotation.getRotZ(), this.viewMatrix);
391
- mat4.multiply(this.projectionMatrix, this.viewMatrix, this.modelViewProjectionMatrix);
392
- return this.modelViewProjectionMatrix;
393
- }
394
-
395
- this.upVector = vec3.fromValues(0, 1, 0);
396
- this.origin = vec3.fromValues(0, 0, 0);
397
-
398
- const lightPosition = vec3.fromValues(50, 100, -100);
399
- const lightViewMatrix = mat4.lookAt(lightPosition, this.origin, this.upVector);
400
- const lightProjectionMatrix = mat4.create();
401
- {
402
- const left = -80;
403
- const right = 80;
404
- const bottom = -80;
405
- const top = 80;
406
- const near = -200;
407
- const far = 300;
408
- mat4.ortho(left, right, bottom, top, near, far, lightProjectionMatrix);
409
- }
410
-
411
- const lightViewProjMatrix = mat4.multiply(
412
- lightProjectionMatrix,
413
- lightViewMatrix
414
- );
415
-
416
- // looks like affect on transformations for now const 0
417
- const modelMatrix = mat4.translation([0, 0, 0]);
418
- // The camera/light aren't moving, so write them into buffers now.
419
- {
420
- const lightMatrixData = lightViewProjMatrix; // as Float32Array;
421
- this.device.queue.writeBuffer(
422
- this.sceneUniformBuffer,
423
- 0,
424
- lightMatrixData.buffer,
425
- lightMatrixData.byteOffset,
426
- lightMatrixData.byteLength
427
- );
428
-
429
- const lightData = lightPosition;
430
- this.device.queue.writeBuffer(
431
- this.sceneUniformBuffer,
432
- 128,
433
- lightData.buffer,
434
- lightData.byteOffset,
435
- lightData.byteLength
436
- );
437
-
438
- const modelData = modelMatrix;
439
- this.device.queue.writeBuffer(
440
- this.modelUniformBuffer,
441
- 0,
442
- modelData.buffer,
443
- modelData.byteOffset,
444
- modelData.byteLength
445
- );
446
- }
447
-
448
- this.shadowPassDescriptor = {
449
- colorAttachments: [],
450
- depthStencilAttachment: {
451
- view: this.shadowDepthTextureView,
452
- depthClearValue: 1.0,
453
- depthLoadOp: 'clear',
454
- depthStoreOp: 'store',
455
- },
456
- };
457
-
458
- this.done = true;
459
- })
460
- }
461
-
462
- async loadTex0(texturesPaths, device) {
463
-
464
- this.sampler = device.createSampler({
465
- magFilter: 'linear',
466
- minFilter: 'linear',
467
- });
468
-
469
- return new Promise(async (resolve) => {
470
- const response = await fetch(texturesPaths[0]);
471
- const imageBitmap = await createImageBitmap(await response.blob());
472
- this.texture0 = device.createTexture({
473
- size: [imageBitmap.width, imageBitmap.height, 1],
474
- format: 'rgba8unorm',
475
- usage:
476
- GPUTextureUsage.TEXTURE_BINDING |
477
- GPUTextureUsage.COPY_DST |
478
- GPUTextureUsage.RENDER_ATTACHMENT,
479
- });
480
-
481
- device.queue.copyExternalImageToTexture(
482
- {source: imageBitmap},
483
- {texture: this.texture0},
484
- [imageBitmap.width, imageBitmap.height]
485
- );
486
- resolve()
487
- })
488
- }
489
-
490
- draw = (commandEncoder) => {
491
- if(this.done == false) return;
492
- const transformationMatrix = this.getTransformationMatrix(this.position);
493
- this.device.queue.writeBuffer(
494
- this.sceneUniformBuffer,
495
- 64,
496
- transformationMatrix.buffer,
497
- transformationMatrix.byteOffset,
498
- transformationMatrix.byteLength
499
- );
500
- this.renderPassDescriptor.colorAttachments[0].view = this.context
501
- .getCurrentTexture()
502
- .createView();
503
- }
504
-
505
- drawElements = (renderPass) => {
506
- renderPass.setBindGroup(0, this.sceneBindGroupForRender);
507
- renderPass.setBindGroup(1, this.modelBindGroup);
508
- renderPass.setVertexBuffer(0, this.vertexBuffer);
509
- renderPass.setVertexBuffer(1, this.vertexNormalsBuffer);
510
- renderPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
511
- renderPass.setIndexBuffer(this.indexBuffer, 'uint16');
512
- renderPass.drawIndexed(this.indexCount);
513
- }
514
-
515
- drawShadows = (shadowPass) => {
516
- shadowPass.setBindGroup(0, this.sceneBindGroupForShadow);
517
- shadowPass.setBindGroup(1, this.modelBindGroup);
518
- shadowPass.setVertexBuffer(0, this.vertexBuffer);
519
- shadowPass.setVertexBuffer(1, this.vertexNormalsBuffer);
520
- shadowPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
521
- shadowPass.setIndexBuffer(this.indexBuffer, 'uint16');
522
- shadowPass.drawIndexed(this.indexCount);
523
- }
11
+ constructor(canvas, device, context, o) {
12
+ if(typeof o.name === 'undefined') o.name = genName(9);
13
+ if(typeof o.raycast === 'undefined') {
14
+ this.raycast = {
15
+ enabled: false,
16
+ radius: 2
17
+ };
18
+ } else {
19
+ this.raycast = o.raycast;
20
+ }
21
+
22
+ this.name = o.name;
23
+ this.done = false;
24
+ this.device = device;
25
+ this.context = context;
26
+ this.entityArgPass = o.entityArgPass;
27
+
28
+ // Mesh stuff
29
+ this.mesh = o.mesh;
30
+ this.mesh.uvs = this.mesh.textures;
31
+ console.log(`%c Mesh loaded: ${o.name}`, LOG_FUNNY_SMALL);
32
+
33
+ this.inputHandler = createInputHandler(window, canvas);
34
+ this.cameras = o.cameras;
35
+
36
+ this.mainCameraParams = {
37
+ type: o.mainCameraParams.type,
38
+ responseCoef: o.mainCameraParams.responseCoef
39
+ }
40
+
41
+ // touchCoordinate.enabled = true;
42
+
43
+ this.lastFrameMS = 0;
44
+ this.texturesPaths = [];
45
+ o.texturesPaths.forEach((t) => {this.texturesPaths.push(t)})
46
+
47
+ this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
48
+
49
+ this.position = new Position(o.position.x, o.position.y, o.position.z);
50
+ this.rotation = new Rotation(o.rotation.x, o.rotation.y, o.rotation.z);
51
+ this.rotation.rotationSpeed.x = o.rotationSpeed.x;
52
+ this.rotation.rotationSpeed.y = o.rotationSpeed.y;
53
+ this.rotation.rotationSpeed.z = o.rotationSpeed.z;
54
+ this.scale = o.scale;
55
+
56
+ this.runProgram = () => {
57
+ return new Promise(async (resolve) => {
58
+ this.shadowDepthTextureSize = 1024;
59
+ const aspect = canvas.width / canvas.height;
60
+ this.projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 1, 2000.0);
61
+ this.modelViewProjectionMatrix = mat4.create();
62
+ // console.log('cube added texturesPaths: ', this.texturesPaths)
63
+ this.loadTex0(this.texturesPaths, device).then(() => {
64
+ // console.log('loaded tex buffer for mesh:', this.texture0)
65
+ resolve()
66
+ })
67
+ })
68
+ }
69
+
70
+ this.runProgram().then(() => {
71
+ const aspect = canvas.width / canvas.height;
72
+ const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
73
+ this.context.configure({
74
+ device: this.device,
75
+ format: presentationFormat,
76
+ alphaMode: 'premultiplied',
77
+ });
78
+
79
+ // Create the model vertex buffer.
80
+ this.vertexBuffer = this.device.createBuffer({
81
+ size: this.mesh.vertices.length * Float32Array.BYTES_PER_ELEMENT,
82
+ usage: GPUBufferUsage.VERTEX,
83
+ mappedAtCreation: true,
84
+ });
85
+ {
86
+ // const mapping = new Float32Array(this.vertexBuffer.getMappedRange());
87
+ // // for(let i = 0;i < this.mesh.vertices.length;++i) {
88
+ // // mapping.set(this.mesh.vertices[i], 6 * i);
89
+ // // mapping.set(this.mesh.normals[i], 6 * i + 3);
90
+ // // }
91
+ // this.vertexBuffer.unmap();
92
+ new Float32Array(this.vertexBuffer.getMappedRange()).set(this.mesh.vertices);
93
+ this.vertexBuffer.unmap();
94
+ }
95
+
96
+ // NIDZA TEST SECOUND BUFFER
97
+ // Create the model vertex buffer.
98
+ this.vertexNormalsBuffer = this.device.createBuffer({
99
+ size: this.mesh.vertexNormals.length * Float32Array.BYTES_PER_ELEMENT,
100
+ usage: GPUBufferUsage.VERTEX,
101
+ mappedAtCreation: true,
102
+ });
103
+ {
104
+ new Float32Array(this.vertexNormalsBuffer.getMappedRange()).set(this.mesh.vertexNormals);
105
+ this.vertexNormalsBuffer.unmap();
106
+ }
107
+
108
+ this.vertexTexCoordsBuffer = this.device.createBuffer({
109
+ size: this.mesh.textures.length * Float32Array.BYTES_PER_ELEMENT,
110
+ usage: GPUBufferUsage.VERTEX,
111
+ mappedAtCreation: true,
112
+ });
113
+ {
114
+ new Float32Array(this.vertexTexCoordsBuffer.getMappedRange()).set(this.mesh.textures);
115
+ this.vertexTexCoordsBuffer.unmap();
116
+ }
117
+
118
+ // Create the model index buffer.
119
+ this.indexCount = this.mesh.indices.length;
120
+ this.indexBuffer = this.device.createBuffer({
121
+ size: this.indexCount * Uint16Array.BYTES_PER_ELEMENT,
122
+ usage: GPUBufferUsage.INDEX,
123
+ mappedAtCreation: true,
124
+ });
125
+ {
126
+ // const mapping = new Uint16Array(this.indexBuffer.getMappedRange());
127
+ // for(let i = 0;i < this.mesh.indices.length;++i) {
128
+ // mapping.set(this.mesh.indices[i], i);
129
+ // }
130
+ new Uint16Array(this.indexBuffer.getMappedRange()).set(this.mesh.indices);
131
+ this.indexBuffer.unmap();
132
+ }
133
+
134
+ // Create the depth texture for rendering/sampling the shadow map.
135
+ this.shadowDepthTexture = this.device.createTexture({
136
+ size: [this.shadowDepthTextureSize, this.shadowDepthTextureSize, 1],
137
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
138
+ format: 'depth32float',
139
+ });
140
+ this.shadowDepthTextureView = this.shadowDepthTexture.createView();
141
+
142
+ // Create some common descriptors used for both the shadow pipeline
143
+ // and the color rendering pipeline.
144
+ this.vertexBuffers = [
145
+ {
146
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
147
+ attributes: [
148
+ {
149
+ // position
150
+ shaderLocation: 0,
151
+ offset: 0,
152
+ format: "float32x3",
153
+ }
154
+ ],
155
+ },
156
+ {
157
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
158
+ attributes: [
159
+ {
160
+ // normal
161
+ shaderLocation: 1,
162
+ offset: 0,
163
+ format: "float32x3",
164
+ },
165
+ ],
166
+ },
167
+ {
168
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 2,
169
+ attributes: [
170
+ {
171
+ // uvs
172
+ shaderLocation: 2,
173
+ offset: 0,
174
+ format: "float32x2",
175
+ },
176
+ ],
177
+ },
178
+ ];
179
+
180
+ const primitive = {
181
+ topology: 'triangle-list',
182
+ cullMode: 'back',
183
+ };
184
+
185
+ this.uniformBufferBindGroupLayout = this.device.createBindGroupLayout({
186
+ entries: [
187
+ {
188
+ binding: 0,
189
+ visibility: GPUShaderStage.VERTEX,
190
+ buffer: {
191
+ type: 'uniform',
192
+ },
193
+ },
194
+ ],
195
+ });
196
+
197
+ this.shadowPipeline = this.device.createRenderPipeline({
198
+ layout: this.device.createPipelineLayout({
199
+ bindGroupLayouts: [
200
+ this.uniformBufferBindGroupLayout,
201
+ this.uniformBufferBindGroupLayout,
202
+ ],
203
+ }),
204
+ vertex: {
205
+ module: this.device.createShaderModule({
206
+ code: vertexShadowWGSL,
207
+ }),
208
+ buffers: this.vertexBuffers,
209
+ },
210
+ depthStencil: {
211
+ depthWriteEnabled: true,
212
+ depthCompare: 'less',
213
+ format: 'depth32float',
214
+ },
215
+ primitive,
216
+ });
217
+
218
+ // Create a bind group layout which holds the scene uniforms and
219
+ // the texture+sampler for depth. We create it manually because the WebPU
220
+ // implementation doesn't infer this from the shader (yet).
221
+ this.bglForRender = this.device.createBindGroupLayout({
222
+ entries: [
223
+ {
224
+ binding: 0,
225
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
226
+ buffer: {
227
+ type: 'uniform',
228
+ },
229
+ },
230
+ {
231
+ binding: 1,
232
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
233
+ texture: {
234
+ sampleType: 'depth',
235
+ },
236
+ },
237
+ {
238
+ binding: 2,
239
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
240
+ sampler: {
241
+ type: 'comparison',
242
+ },
243
+ },
244
+ {
245
+ binding: 3,
246
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
247
+ texture: {
248
+ sampleType: 'float',
249
+ }
250
+ },
251
+ {
252
+ binding: 4,
253
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
254
+ sampler: {
255
+ type: 'filtering',
256
+ }
257
+ }
258
+ ]
259
+ });
260
+
261
+ this.pipeline = this.device.createRenderPipeline({
262
+ layout: this.device.createPipelineLayout({
263
+ bindGroupLayouts: [this.bglForRender, this.uniformBufferBindGroupLayout],
264
+ }),
265
+ vertex: {
266
+ module: this.device.createShaderModule({
267
+ code: vertexWGSL,
268
+ }),
269
+ buffers: this.vertexBuffers,
270
+ },
271
+ fragment: {
272
+ module: this.device.createShaderModule({
273
+ code: fragmentWGSL,
274
+ }),
275
+ targets: [
276
+ {
277
+ format: presentationFormat,
278
+ },
279
+ ],
280
+ constants: {
281
+ shadowDepthTextureSize: this.shadowDepthTextureSize,
282
+ },
283
+ },
284
+ depthStencil: {
285
+ depthWriteEnabled: true,
286
+ depthCompare: 'less',
287
+ format: 'depth24plus-stencil8',
288
+ },
289
+ primitive,
290
+ });
291
+
292
+ const depthTexture = this.device.createTexture({
293
+ size: [canvas.width, canvas.height],
294
+ format: 'depth24plus-stencil8',
295
+ usage: GPUTextureUsage.RENDER_ATTACHMENT,
296
+ });
297
+
298
+ this.renderPassDescriptor = {
299
+ colorAttachments: [
300
+ {
301
+ // view is acquired and set in render loop.
302
+ view: undefined,
303
+ clearValue: {r: 0.5, g: 0.5, b: 0.5, a: 1.0},
304
+ loadOp: 'load',
305
+ storeOp: 'store',
306
+ },
307
+ ],
308
+ depthStencilAttachment: {
309
+ view: depthTexture.createView(),
310
+ depthClearValue: 1.0,
311
+ depthLoadOp: 'clear',
312
+ depthStoreOp: 'store',
313
+ stencilClearValue: 0,
314
+ stencilLoadOp: 'clear',
315
+ stencilStoreOp: 'store',
316
+ },
317
+ };
318
+
319
+ this.modelUniformBuffer = this.device.createBuffer({
320
+ size: 4 * 16, // 4x4 matrix
321
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
322
+ });
323
+
324
+ this.sceneUniformBuffer = this.device.createBuffer({
325
+ // Two 4x4 viewProj matrices,
326
+ // one for the camera and one for the light.
327
+ // Then a vec3 for the light position.
328
+ // Rounded to the nearest multiple of 16.
329
+ size: 2 * 4 * 16 + 4 * 4,
330
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
331
+ });
332
+
333
+ this.sceneBindGroupForShadow = this.device.createBindGroup({
334
+ layout: this.uniformBufferBindGroupLayout,
335
+ entries: [
336
+ {
337
+ binding: 0,
338
+ resource: {
339
+ buffer: this.sceneUniformBuffer,
340
+ },
341
+ },
342
+ ],
343
+ });
344
+
345
+ this.sceneBindGroupForRender = this.device.createBindGroup({
346
+ layout: this.bglForRender,
347
+ entries: [
348
+ {
349
+ binding: 0,
350
+ resource: {
351
+ buffer: this.sceneUniformBuffer,
352
+ },
353
+ },
354
+ {
355
+ binding: 1,
356
+ resource: this.shadowDepthTextureView,
357
+ },
358
+ {
359
+ binding: 2,
360
+ resource: this.device.createSampler({
361
+ compare: 'less',
362
+ }),
363
+ },
364
+ {
365
+ binding: 3,
366
+ resource: this.texture0.createView(),
367
+ },
368
+ {
369
+ binding: 4,
370
+ resource: this.sampler,
371
+ },
372
+ ],
373
+ });
374
+
375
+ this.modelBindGroup = this.device.createBindGroup({
376
+ layout: this.uniformBufferBindGroupLayout,
377
+ entries: [
378
+ {
379
+ binding: 0,
380
+ resource: {
381
+ buffer: this.modelUniformBuffer,
382
+ },
383
+ },
384
+ ],
385
+ });
386
+
387
+ // Rotates the camera around the origin based on time.
388
+ this.getTransformationMatrix = (pos) => {
389
+ const now = Date.now();
390
+ const deltaTime = (now - this.lastFrameMS) / this.mainCameraParams.responseCoef;
391
+ this.lastFrameMS = now;
392
+ // const this.viewMatrix = mat4.identity()
393
+ const camera = this.cameras[this.mainCameraParams.type];
394
+ this.viewMatrix = camera.update(deltaTime, this.inputHandler());
395
+ mat4.translate(this.viewMatrix, vec3.fromValues(pos.x, pos.y, pos.z), this.viewMatrix);
396
+ mat4.rotate(
397
+ this.viewMatrix,
398
+ vec3.fromValues(this.rotation.axis.x, this.rotation.axis.y, this.rotation.axis.z),
399
+ degToRad(this.rotation.angle), this.viewMatrix)
400
+
401
+ // console.info('angle: ', this.rotation.angle, ' axis ' , this.rotation.axis.x, ' , ', this.rotation.axis.y, ' , ', this.rotation.axis.z)
402
+ mat4.multiply(this.projectionMatrix, this.viewMatrix, this.modelViewProjectionMatrix);
403
+ return this.modelViewProjectionMatrix;
404
+ }
405
+
406
+ this.upVector = vec3.fromValues(0, 1, 0);
407
+ this.origin = vec3.fromValues(0, 0, 0);
408
+
409
+ this.lightPosition = vec3.fromValues(0, 0, 0);
410
+ this.lightViewMatrix = mat4.lookAt(this.lightPosition, this.origin, this.upVector);
411
+ const lightProjectionMatrix = mat4.create();
412
+
413
+ var myLMargin = 100;
414
+ {
415
+ const left = -myLMargin;
416
+ const right = myLMargin;
417
+ const bottom = -myLMargin;
418
+ const top = myLMargin;
419
+ const near = -200;
420
+ const far = 300;
421
+ mat4.ortho(left, right, bottom, top, near, far, lightProjectionMatrix);
422
+ // test
423
+ // mat4.ortho(right, left, top, bottom, near, far, lightProjectionMatrix);
424
+ }
425
+
426
+ this.lightViewProjMatrix = mat4.multiply(
427
+ lightProjectionMatrix,
428
+ this.lightViewMatrix
429
+ );
430
+
431
+ // looks like affect on transformations for now const 0
432
+ const modelMatrix = mat4.translation([0, 0, 0]);
433
+ // The camera/light aren't moving, so write them into buffers now.
434
+ {
435
+ const lightMatrixData = this.lightViewProjMatrix; // as Float32Array;
436
+ this.device.queue.writeBuffer(
437
+ this.sceneUniformBuffer,
438
+ 0,
439
+ lightMatrixData.buffer,
440
+ lightMatrixData.byteOffset,
441
+ lightMatrixData.byteLength
442
+ );
443
+
444
+ const lightData = this.lightPosition;
445
+ this.device.queue.writeBuffer(
446
+ this.sceneUniformBuffer,
447
+ 128,
448
+ lightData.buffer,
449
+ lightData.byteOffset,
450
+ lightData.byteLength
451
+ );
452
+
453
+ const modelData = modelMatrix;
454
+ this.device.queue.writeBuffer(
455
+ this.modelUniformBuffer,
456
+ 0,
457
+ modelData.buffer,
458
+ modelData.byteOffset,
459
+ modelData.byteLength
460
+ );
461
+ }
462
+
463
+ this.shadowPassDescriptor = {
464
+ colorAttachments: [],
465
+ depthStencilAttachment: {
466
+ view: this.shadowDepthTextureView,
467
+ depthClearValue: 1.0,
468
+ depthLoadOp: 'clear',
469
+ depthStoreOp: 'store',
470
+ },
471
+ };
472
+
473
+ this.done = true;
474
+ })
475
+ }
476
+
477
+ updateLightsTest = (position) => {
478
+ console.log('Update light position.', position)
479
+ this.lightPosition = vec3.fromValues(position[0], position[1], position[2]);
480
+ this.lightViewMatrix = mat4.lookAt(this.lightPosition, this.origin, this.upVector);
481
+
482
+ const lightProjectionMatrix = mat4.create();
483
+ {
484
+ const left = -80;
485
+ const right = 80;
486
+ const bottom = -80;
487
+ const top = 80;
488
+ const near = -200;
489
+ const far = 300;
490
+ mat4.ortho(left, right, bottom, top, near, far, lightProjectionMatrix);
491
+ }
492
+
493
+ this.lightViewProjMatrix = mat4.multiply(
494
+ lightProjectionMatrix,
495
+ this.lightViewMatrix
496
+ );
497
+
498
+ // looks like affect on transformations for now const 0
499
+ const modelMatrix = mat4.translation([0, 0, 0]);
500
+ // The camera/light aren't moving, so write them into buffers now.
501
+ {
502
+ const lightMatrixData = this.lightViewProjMatrix; // as Float32Array;
503
+ this.device.queue.writeBuffer(
504
+ this.sceneUniformBuffer,
505
+ 0, // 0 ori
506
+ lightMatrixData.buffer,
507
+ lightMatrixData.byteOffset,
508
+ lightMatrixData.byteLength
509
+ );
510
+
511
+ const lightData = this.lightPosition;
512
+ this.device.queue.writeBuffer(
513
+ this.sceneUniformBuffer,
514
+ 256,
515
+ lightData.buffer,
516
+ lightData.byteOffset,
517
+ lightData.byteLength
518
+ );
519
+
520
+ const modelData = modelMatrix;
521
+ this.device.queue.writeBuffer(
522
+ this.modelUniformBuffer,
523
+ 0,
524
+ modelData.buffer,
525
+ modelData.byteOffset,
526
+ modelData.byteLength
527
+ );
528
+ }
529
+
530
+ this.shadowPassDescriptor = {
531
+ colorAttachments: [],
532
+ depthStencilAttachment: {
533
+ view: this.shadowDepthTextureView,
534
+ depthClearValue: 1.0, // ori 1.0
535
+ depthLoadOp: 'clear',
536
+ depthStoreOp: 'store',
537
+ },
538
+ };
539
+
540
+ ///////////////////////
541
+ }
542
+
543
+ async loadTex0(texturesPaths, device) {
544
+
545
+ this.sampler = device.createSampler({
546
+ magFilter: 'linear',
547
+ minFilter: 'linear',
548
+ });
549
+
550
+ return new Promise(async (resolve) => {
551
+ const response = await fetch(texturesPaths[0]);
552
+ const imageBitmap = await createImageBitmap(await response.blob());
553
+ this.texture0 = device.createTexture({
554
+ size: [imageBitmap.width, imageBitmap.height, 1],
555
+ format: 'rgba8unorm',
556
+ usage:
557
+ GPUTextureUsage.TEXTURE_BINDING |
558
+ GPUTextureUsage.COPY_DST |
559
+ GPUTextureUsage.RENDER_ATTACHMENT,
560
+ });
561
+
562
+ device.queue.copyExternalImageToTexture(
563
+ {source: imageBitmap},
564
+ {texture: this.texture0},
565
+ [imageBitmap.width, imageBitmap.height]
566
+ );
567
+ resolve()
568
+ })
569
+ }
570
+
571
+ draw = (commandEncoder) => {
572
+ if(this.done == false) return;
573
+ const transformationMatrix = this.getTransformationMatrix(this.position);
574
+ this.device.queue.writeBuffer(
575
+ this.sceneUniformBuffer,
576
+ 64,
577
+ transformationMatrix.buffer,
578
+ transformationMatrix.byteOffset,
579
+ transformationMatrix.byteLength
580
+ );
581
+ this.renderPassDescriptor.colorAttachments[0].view = this.context
582
+ .getCurrentTexture()
583
+ .createView();
584
+ }
585
+
586
+ drawElements = (renderPass) => {
587
+ renderPass.setBindGroup(0, this.sceneBindGroupForRender);
588
+ renderPass.setBindGroup(1, this.modelBindGroup);
589
+ renderPass.setVertexBuffer(0, this.vertexBuffer);
590
+ renderPass.setVertexBuffer(1, this.vertexNormalsBuffer);
591
+ renderPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
592
+ renderPass.setIndexBuffer(this.indexBuffer, 'uint16');
593
+ renderPass.drawIndexed(this.indexCount);
594
+
595
+ // test ray
596
+
597
+ // try{ OLD
598
+ // if(this.raycast.enabled == true) checkingRay(this)
599
+ // } catch(e) {}
600
+
601
+ }
602
+
603
+ drawShadows = (shadowPass) => {
604
+ shadowPass.setBindGroup(0, this.sceneBindGroupForShadow);
605
+ shadowPass.setBindGroup(1, this.modelBindGroup);
606
+ shadowPass.setVertexBuffer(0, this.vertexBuffer);
607
+ shadowPass.setVertexBuffer(1, this.vertexNormalsBuffer);
608
+ shadowPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
609
+ shadowPass.setIndexBuffer(this.indexBuffer, 'uint16');
610
+ shadowPass.drawIndexed(this.indexCount);
611
+ }
524
612
  }