matrix-engine-wgpu 1.0.2 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/REFERENCE.md +3 -0
  2. package/app-worker.js +45 -0
  3. package/empty.js +12 -0
  4. package/examples/load-obj-file.js +48 -0
  5. package/examples/unlit-textures.js +27 -0
  6. package/examples.js +7 -0
  7. package/index.js +18 -5
  8. package/main.js +49 -23
  9. package/package.json +11 -2
  10. package/public/ammojs/ammo.js +957 -0
  11. package/public/ammojs/ammo.wasm.js +921 -0
  12. package/public/ammojs/ammo.wasm.wasm +0 -0
  13. package/public/app-worker.js +47 -0
  14. package/public/app.js +2640 -305
  15. package/public/css/style.css +1 -2
  16. package/public/empty.html +25 -0
  17. package/public/empty.js +9107 -0
  18. package/public/examples.html +25 -0
  19. package/public/examples.js +9180 -0
  20. package/public/index.html +1 -1
  21. package/public/res/meshes/blender/lopta.mtl +10 -0
  22. package/public/res/meshes/blender/lopta.obj +3402 -0
  23. package/public/res/meshes/blender/piramyd.blend +0 -0
  24. package/public/res/meshes/blender/piramyd.blend1 +0 -0
  25. package/public/res/meshes/blender/piramyd.js +42 -0
  26. package/public/res/meshes/blender/piramyd.mtl +10 -0
  27. package/public/res/meshes/blender/piramyd.obj +18696 -0
  28. package/public/res/meshes/blender/piramyd1.js +42 -0
  29. package/public/res/meshes/blender/welcomeTextblend.blend +0 -0
  30. package/public/res/meshes/dragon/stanfordDragonData.js +5 -0
  31. package/public/res/meshes/obj/armor.obj +319 -0
  32. package/public/res/meshes/obj/armor.png +0 -0
  33. package/public/worker.html +25 -0
  34. package/readme.md +130 -48
  35. package/src/engine/ball.js +26 -10
  36. package/src/engine/cube.js +100 -81
  37. package/src/engine/engine.js +466 -4
  38. package/src/engine/final/adaptJSON1.js +53 -0
  39. package/src/engine/final/utils2.js +63 -0
  40. package/src/engine/loader-obj.js +469 -0
  41. package/src/engine/matrix-class.js +5 -4
  42. package/src/engine/matrix-mesh.js +49 -0
  43. package/src/engine/mesh-obj.js +534 -0
  44. package/src/engine/utils.js +300 -45
  45. package/src/physics/matrix-ammo.js +119 -0
  46. package/src/shaders/fragment.wgsl.js +48 -0
  47. package/src/shaders/shaders.js +4 -124
  48. package/src/shaders/vertex.wgsl.js +49 -0
  49. package/src/shaders/vertexShadow.wgsl.js +20 -0
  50. package/src/world.js +246 -0
  51. package/src/meWGPU.js +0 -173
package/public/app.js CHANGED
@@ -1,53 +1,97 @@
1
1
  (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2
2
  "use strict";
3
3
 
4
- var _meWGPU = _interopRequireDefault(require("./src/meWGPU"));
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.application = void 0;
8
+ var _world = _interopRequireDefault(require("./src/world.js"));
9
+ var _loaderObj = require("./src/engine/loader-obj.js");
5
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
6
- let application = new _meWGPU.default({
7
- useSingleRenderPass: false
11
+ let application = exports.application = new _world.default({
12
+ canvasSize: 'fullscreen',
13
+ mainCameraParams: {
14
+ type: 'WASD',
15
+ responseCoef: 1000
16
+ }
8
17
  }, () => {
9
- let c = {
10
- position: {
11
- x: -3,
12
- y: 0,
13
- z: -5
14
- },
15
- rotation: {
16
- x: 0,
17
- y: 45,
18
- z: 0
19
- },
20
- rotationSpeed: {
21
- x: 0,
22
- y: 0,
23
- z: 0
24
- },
25
- texturesPaths: ['./res/textures/rust.jpg']
26
- };
27
- let o = {
28
- position: {
29
- x: 3,
30
- y: 0,
31
- z: -10
32
- },
33
- rotation: {
34
- x: 0,
35
- y: 45,
36
- z: 0
37
- },
38
- rotationSpeed: {
39
- x: 0,
40
- y: 10,
41
- z: 0
42
- },
43
- texturesPaths: ['./res/textures/rust.jpg']
44
- };
45
- application.addBall(o);
46
- application.addCube(c);
18
+ addEventListener('AmmoReady', () => {
19
+ (0, _loaderObj.downloadMeshes)({
20
+ welcomeText: "./res/meshes/blender/piramyd.obj",
21
+ armor: "./res/meshes/obj/armor.obj",
22
+ lopta: "./res/meshes/blender/lopta.obj"
23
+ }, onLoadObj);
24
+ });
25
+ function onLoadObj(m) {
26
+ // console.log('Loaded objs:', m);
27
+ application.addMeshObj({
28
+ position: {
29
+ x: -3,
30
+ y: 0,
31
+ z: -5
32
+ },
33
+ rotation: {
34
+ x: 0,
35
+ y: 0,
36
+ z: 0
37
+ },
38
+ rotationSpeed: {
39
+ x: 0,
40
+ y: 10,
41
+ z: 0
42
+ },
43
+ texturesPaths: ['./res/meshes/obj/armor.png'],
44
+ name: 'Armor',
45
+ mesh: m.armor
46
+ });
47
+ application.addMeshObj({
48
+ position: {
49
+ x: 1,
50
+ y: 0,
51
+ z: -5
52
+ },
53
+ rotation: {
54
+ x: -90,
55
+ y: 0,
56
+ z: 0
57
+ },
58
+ rotationSpeed: {
59
+ x: 0,
60
+ y: 0,
61
+ z: 0
62
+ },
63
+ texturesPaths: ['./res/meshes/obj/armor.png'],
64
+ name: 'MyText',
65
+ mesh: m.welcomeText
66
+ });
67
+ application.addMeshObj({
68
+ position: {
69
+ x: 1,
70
+ y: 0,
71
+ z: -15
72
+ },
73
+ rotation: {
74
+ x: -90,
75
+ y: 0,
76
+ z: 0
77
+ },
78
+ rotationSpeed: {
79
+ x: 0,
80
+ y: 10,
81
+ z: 0
82
+ },
83
+ texturesPaths: ['./res/meshes/obj/armor.png'],
84
+ name: 'Lopta-Fizika',
85
+ mesh: m.lopta,
86
+ physics: {
87
+ enabled: true
88
+ }
89
+ });
90
+ }
47
91
  });
48
92
  window.app = application;
49
93
 
50
- },{"./src/meWGPU":6}],2:[function(require,module,exports){
94
+ },{"./src/engine/loader-obj.js":6,"./src/world.js":15}],2:[function(require,module,exports){
51
95
  "use strict";
52
96
 
53
97
  Object.defineProperty(exports, "__esModule", {
@@ -5404,10 +5448,23 @@ exports.default = void 0;
5404
5448
  var _shaders = require("../shaders/shaders");
5405
5449
  var _wgpuMatrix = require("wgpu-matrix");
5406
5450
  var _matrixClass = require("./matrix-class");
5451
+ var _engine = require("./engine");
5407
5452
  class MEBall {
5408
5453
  constructor(canvas, device, context, o) {
5409
5454
  this.context = context;
5410
5455
  this.device = device;
5456
+
5457
+ // The input handler
5458
+ this.inputHandler = (0, _engine.createInputHandler)(window, canvas);
5459
+ this.cameras = o.cameras;
5460
+ this.scale = o.scale;
5461
+ console.log('passed : o.mainCameraParams.responseCoef ', o.mainCameraParams.responseCoef);
5462
+ this.mainCameraParams = {
5463
+ type: o.mainCameraParams.type,
5464
+ responseCoef: o.mainCameraParams.responseCoef
5465
+ }; // | WASD 'arcball' };
5466
+
5467
+ this.lastFrameMS = 0;
5411
5468
  this.entityArgPass = o.entityArgPass;
5412
5469
  this.SphereLayout = {
5413
5470
  vertexStride: 8 * 4,
@@ -5425,7 +5482,7 @@ class MEBall {
5425
5482
  this.rotation.rotationSpeed.y = o.rotationSpeed.y;
5426
5483
  this.rotation.rotationSpeed.z = o.rotationSpeed.z;
5427
5484
  this.shaderModule = device.createShaderModule({
5428
- code: _shaders.BALL_SHADER
5485
+ code: _shaders.UNLIT_SHADER
5429
5486
  });
5430
5487
  this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
5431
5488
  this.pipeline = device.createRenderPipeline({
@@ -5495,7 +5552,6 @@ class MEBall {
5495
5552
  };
5496
5553
  this.loadTex0(this.texturesPaths, device).then(() => {
5497
5554
  this.loadTex1(device).then(() => {
5498
- console.log('NICE THIS', this);
5499
5555
  this.sampler = device.createSampler({
5500
5556
  magFilter: 'linear',
5501
5557
  minFilter: 'linear'
@@ -5504,9 +5560,9 @@ class MEBall {
5504
5560
  _wgpuMatrix.mat4.identity(this.transform);
5505
5561
 
5506
5562
  // Create one large central planet surrounded by a large ring of asteroids
5507
- this.planet = this.createSphereRenderable(1.0);
5563
+ this.planet = this.createGeometry(this.scale);
5508
5564
  this.planet.bindGroup = this.createSphereBindGroup(this.texture0, this.transform);
5509
- var asteroids = [this.createSphereRenderable(0.2, 8, 6, 0.15), this.createSphereRenderable(0.13, 8, 6, 0.15)];
5565
+ var asteroids = [this.createGeometry(12, 8, 6, 0.15)];
5510
5566
  this.renderables = [this.planet];
5511
5567
 
5512
5568
  // this.ensureEnoughAsteroids(asteroids, this.transform);
@@ -5585,7 +5641,7 @@ class MEBall {
5585
5641
  this.renderScene(renderBundleEncoder);
5586
5642
  this.renderBundle = renderBundleEncoder.finish();
5587
5643
  }
5588
- createSphereRenderable(radius, widthSegments = 8, heightSegments = 4, randomness = 0) {
5644
+ createGeometry(radius, widthSegments = 8, heightSegments = 4, randomness = 0) {
5589
5645
  const sphereMesh = this.createSphereMesh(radius, widthSegments, heightSegments, randomness);
5590
5646
  // Create a vertex buffer from the sphere data.
5591
5647
  const vertices = this.device.createBuffer({
@@ -5635,9 +5691,15 @@ class MEBall {
5635
5691
  return bindGroup;
5636
5692
  }
5637
5693
  getTransformationMatrix(pos) {
5638
- const viewMatrix = _wgpuMatrix.mat4.identity();
5694
+ // const viewMatrix = mat4.identity();
5695
+ const now = Date.now();
5696
+ const deltaTime = (now - this.lastFrameMS) / this.mainCameraParams.responseCoef;
5697
+ this.lastFrameMS = now;
5698
+
5699
+ // const viewMatrix = mat4.identity(); ORI
5700
+ const camera = this.cameras[this.mainCameraParams.type];
5701
+ const viewMatrix = camera.update(deltaTime, this.inputHandler());
5639
5702
  _wgpuMatrix.mat4.translate(viewMatrix, _wgpuMatrix.vec3.fromValues(pos.x, pos.y, pos.z), viewMatrix);
5640
- const now = Date.now() / 1000;
5641
5703
  _wgpuMatrix.mat4.rotateX(viewMatrix, Math.PI * this.rotation.getRotX(), viewMatrix);
5642
5704
  _wgpuMatrix.mat4.rotateY(viewMatrix, Math.PI * this.rotation.getRotY(), viewMatrix);
5643
5705
  _wgpuMatrix.mat4.rotateZ(viewMatrix, Math.PI * this.rotation.getRotZ(), viewMatrix);
@@ -5783,7 +5845,7 @@ class MEBall {
5783
5845
  }
5784
5846
  exports.default = MEBall;
5785
5847
 
5786
- },{"../shaders/shaders":7,"./matrix-class":5,"wgpu-matrix":2}],4:[function(require,module,exports){
5848
+ },{"../shaders/shaders":12,"./engine":5,"./matrix-class":7,"wgpu-matrix":2}],4:[function(require,module,exports){
5787
5849
  "use strict";
5788
5850
 
5789
5851
  Object.defineProperty(exports, "__esModule", {
@@ -5793,6 +5855,7 @@ exports.default = void 0;
5793
5855
  var _shaders = require("../shaders/shaders");
5794
5856
  var _wgpuMatrix = require("wgpu-matrix");
5795
5857
  var _matrixClass = require("./matrix-class");
5858
+ var _engine = require("./engine");
5796
5859
  var SphereLayout = {
5797
5860
  vertexStride: 8 * 4,
5798
5861
  positionsOffset: 0,
@@ -5804,9 +5867,17 @@ class MECube {
5804
5867
  this.device = device;
5805
5868
  this.context = context;
5806
5869
  this.entityArgPass = o.entityArgPass;
5807
- console.log('passed args', o.entityArgPass);
5870
+ this.inputHandler = (0, _engine.createInputHandler)(window, canvas);
5871
+ this.cameras = o.cameras;
5872
+ console.log('passed : o.mainCameraParams.responseCoef ', o.mainCameraParams.responseCoef);
5873
+ this.mainCameraParams = {
5874
+ type: o.mainCameraParams.type,
5875
+ responseCoef: o.mainCameraParams.responseCoef
5876
+ }; // | WASD 'arcball' };
5877
+
5878
+ this.lastFrameMS = 0;
5808
5879
  this.shaderModule = device.createShaderModule({
5809
- code: _shaders.BALL_SHADER
5880
+ code: _shaders.UNLIT_SHADER
5810
5881
  });
5811
5882
  this.texturesPaths = [];
5812
5883
  o.texturesPaths.forEach(t => {
@@ -5814,10 +5885,12 @@ class MECube {
5814
5885
  });
5815
5886
  this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
5816
5887
  this.position = new _matrixClass.Position(o.position.x, o.position.y, o.position.z);
5888
+ console.log('cube added on pos : ', this.position);
5817
5889
  this.rotation = new _matrixClass.Rotation(o.rotation.x, o.rotation.y, o.rotation.z);
5818
5890
  this.rotation.rotationSpeed.x = o.rotationSpeed.x;
5819
5891
  this.rotation.rotationSpeed.y = o.rotationSpeed.y;
5820
5892
  this.rotation.rotationSpeed.z = o.rotationSpeed.z;
5893
+ this.scale = o.scale;
5821
5894
  this.pipeline = device.createRenderPipeline({
5822
5895
  layout: 'auto',
5823
5896
  vertex: {
@@ -5896,9 +5969,16 @@ class MECube {
5896
5969
  _wgpuMatrix.mat4.identity(this.transform);
5897
5970
 
5898
5971
  // Create one large central planet surrounded by a large ring of asteroids
5899
- this.planet = this.createSphereRenderable(1.0);
5972
+ this.planet = this.createGeometry({
5973
+ scale: this.scale,
5974
+ useUVShema4x2: false
5975
+ });
5900
5976
  this.planet.bindGroup = this.createSphereBindGroup(this.texture0, this.transform);
5901
- var asteroids = [this.createSphereRenderable(0.2, 8, 6, 0.15), this.createSphereRenderable(0.13, 8, 6, 0.15)];
5977
+
5978
+ // can be used like instance draws
5979
+ var asteroids = [
5980
+ // this.createGeometry(0.2, 8, 6, 0.15),
5981
+ ];
5902
5982
  this.renderables = [this.planet];
5903
5983
  // this.ensureEnoughAsteroids(asteroids, this.transform);
5904
5984
  this.renderPassDescriptor = {
@@ -5921,7 +6001,7 @@ class MECube {
5921
6001
  }
5922
6002
  };
5923
6003
  const aspect = canvas.width / canvas.height;
5924
- this.projectionMatrix = _wgpuMatrix.mat4.perspective(2 * Math.PI / 5, aspect, 1, 100.0);
6004
+ this.projectionMatrix = _wgpuMatrix.mat4.perspective(2 * Math.PI / 5, aspect, 1, 1000.0);
5925
6005
  this.modelViewProjectionMatrix = _wgpuMatrix.mat4.create();
5926
6006
  this.frameBindGroup = device.createBindGroup({
5927
6007
  layout: this.pipeline.getBindGroupLayout(0),
@@ -5976,27 +6056,27 @@ class MECube {
5976
6056
  this.renderScene(renderBundleEncoder);
5977
6057
  this.renderBundle = renderBundleEncoder.finish();
5978
6058
  }
5979
- createSphereRenderable(radius, widthSegments = 32, heightSegments = 16, randomness = 0) {
5980
- const sphereMesh = this.createCubeVertices();
6059
+ createGeometry(options) {
6060
+ const mesh = this.createCubeVertices(options);
5981
6061
  // Create a vertex buffer from the sphere data.
5982
6062
  const vertices = this.device.createBuffer({
5983
- size: sphereMesh.vertices.byteLength,
6063
+ size: mesh.vertices.byteLength,
5984
6064
  usage: GPUBufferUsage.VERTEX,
5985
6065
  mappedAtCreation: true
5986
6066
  });
5987
- new Float32Array(vertices.getMappedRange()).set(sphereMesh.vertices);
6067
+ new Float32Array(vertices.getMappedRange()).set(mesh.vertices);
5988
6068
  vertices.unmap();
5989
6069
  const indices = this.device.createBuffer({
5990
- size: sphereMesh.indices.byteLength,
6070
+ size: mesh.indices.byteLength,
5991
6071
  usage: GPUBufferUsage.INDEX,
5992
6072
  mappedAtCreation: true
5993
6073
  });
5994
- new Uint16Array(indices.getMappedRange()).set(sphereMesh.indices);
6074
+ new Uint16Array(indices.getMappedRange()).set(mesh.indices);
5995
6075
  indices.unmap();
5996
6076
  return {
5997
6077
  vertices,
5998
6078
  indices,
5999
- indexCount: sphereMesh.indices.length
6079
+ indexCount: mesh.indices.length
6000
6080
  };
6001
6081
  }
6002
6082
  createSphereBindGroup(texture, transform) {
@@ -6026,9 +6106,13 @@ class MECube {
6026
6106
  return bindGroup;
6027
6107
  }
6028
6108
  getTransformationMatrix(pos) {
6029
- // const now = Date.now() / 1000;
6109
+ const now = Date.now();
6110
+ const deltaTime = (now - this.lastFrameMS) / this.mainCameraParams.responseCoef;
6111
+ this.lastFrameMS = now;
6030
6112
 
6031
- const viewMatrix = _wgpuMatrix.mat4.identity();
6113
+ // const viewMatrix = mat4.identity(); ORI
6114
+ const camera = this.cameras[this.mainCameraParams.type];
6115
+ const viewMatrix = camera.update(deltaTime, this.inputHandler());
6032
6116
  _wgpuMatrix.mat4.translate(viewMatrix, _wgpuMatrix.vec3.fromValues(pos.x, pos.y, pos.z), viewMatrix);
6033
6117
  _wgpuMatrix.mat4.rotateX(viewMatrix, Math.PI * this.rotation.getRotX(), viewMatrix);
6034
6118
  _wgpuMatrix.mat4.rotateY(viewMatrix, Math.PI * this.rotation.getRotY(), viewMatrix);
@@ -6073,6 +6157,9 @@ class MECube {
6073
6157
  resolve();
6074
6158
  });
6075
6159
  }
6160
+ draw = () => {};
6161
+ drawElements = () => {};
6162
+ drawShadows = () => {};
6076
6163
 
6077
6164
  // Render bundles function as partial, limited render passes, so we can use the
6078
6165
  // same code both to render the scene normally and to build the render bundle.
@@ -6105,6 +6192,7 @@ class MECube {
6105
6192
  useUVShema4x2: false
6106
6193
  };
6107
6194
  }
6195
+ if (typeof options.scale === 'undefined') options.scale = 1;
6108
6196
  let vertices;
6109
6197
  if (options.useUVShema4x2 == true) {
6110
6198
  vertices = new Float32Array([
@@ -6124,20 +6212,20 @@ class MECube {
6124
6212
  -1, 1, 1, 1, 0, 0, 0.5, 0.5, 1, 1, 1, 1, 0, 0, 0.75, 0.5, -1, 1, -1, 1, 0, 0, 0.5, 1, 1, 1, -1, 1, 0, 0, 0.75, 1]);
6125
6213
  } else {
6126
6214
  vertices = new Float32Array([
6127
- // position | texture coordinate
6128
- //-------------+----------------------
6215
+ // position | texture coordinate
6216
+ //------------- +----------------------
6129
6217
  // front face select the top left image 1, 0.5,
6130
- -1, 1, 1, 1, 0, 0, 0, 0, -1, -1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, -1, 1, 1, 0, 0, 1, 1,
6218
+ -1 * options.scale, 1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 0, -1 * options.scale, -1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 1, 1 * options.scale, 1 * options.scale, 1 * options.scale, 1, 0, 0, 1, 0, 1 * options.scale, -1 * options.scale, 1 * options.scale, 1, 0, 0, 1, 1,
6131
6219
  // right face select the top middle image
6132
- 1, 1, -1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, -1, -1, 1, 0, 0, 1, 0, 1, -1, 1, 1, 0, 0, 1, 1,
6220
+ 1 * options.scale, 1 * options.scale, -1 * options.scale, 1, 0, 0, 0, 0, 1 * options.scale, 1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 1, 1 * options.scale, -1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 0, 1 * options.scale, -1 * options.scale, 1 * options.scale, 1, 0, 0, 1, 1,
6133
6221
  // back face select to top right image
6134
- 1, 1, -1, 1, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 1, -1, 1, -1, 1, 0, 0, 1, 0, -1, -1, -1, 1, 0, 0, 1, 1,
6222
+ 1 * options.scale, 1 * options.scale, -1 * options.scale, 1, 0, 0, 0, 0, 1 * options.scale, -1 * options.scale, -1 * options.scale, 1, 0, 0, 0, 1, -1 * options.scale, 1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 0, -1 * options.scale, -1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 1,
6135
6223
  // left face select the bottom left image
6136
- -1, 1, 1, 1, 0, 0, 0, 0, -1, 1, -1, 1, 0, 0, 0, 1, -1, -1, 1, 1, 0, 0, 1, 0, -1, -1, -1, 1, 0, 0, 1, 1,
6224
+ -1 * options.scale, 1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 0, -1 * options.scale, 1 * options.scale, -1 * options.scale, 1, 0, 0, 0, 1, -1 * options.scale, -1 * options.scale, 1 * options.scale, 1, 0, 0, 1, 0, -1 * options.scale, -1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 1,
6137
6225
  // bottom face select the bottom middle image
6138
- 1, -1, 1, 1, 0, 0, 0, 0, -1, -1, 1, 1, 0, 0, 0, 1, 1, -1, -1, 1, 0, 0, 1, 0, -1, -1, -1, 1, 0, 0, 1, 1,
6226
+ 1 * options.scale, -1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 0, -1 * options.scale, -1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 1, 1 * options.scale, -1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 0, -1 * options.scale, -1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 1,
6139
6227
  // top face select the bottom right image
6140
- -1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, -1, 1, -1, 1, 0, 0, 1, 0, 1, 1, -1, 1, 0, 0, 1, 1]);
6228
+ -1 * options.scale, 1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 0, 1 * options.scale, 1 * options.scale, 1 * options.scale, 1, 0, 0, 0, 1, -1 * options.scale, 1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 0, 1 * options.scale, 1 * options.scale, -1 * options.scale, 1, 0, 0, 1, 1]);
6141
6229
  }
6142
6230
  const indices = new Uint16Array([0, 1, 2, 2, 1, 3,
6143
6231
  // front
@@ -6169,15 +6257,942 @@ class MECube {
6169
6257
  }
6170
6258
  exports.default = MECube;
6171
6259
 
6172
- },{"../shaders/shaders":7,"./matrix-class":5,"wgpu-matrix":2}],5:[function(require,module,exports){
6260
+ },{"../shaders/shaders":12,"./engine":5,"./matrix-class":7,"wgpu-matrix":2}],5:[function(require,module,exports){
6261
+ "use strict";
6262
+
6263
+ Object.defineProperty(exports, "__esModule", {
6264
+ value: true
6265
+ });
6266
+ exports.WASDCamera = exports.ArcballCamera = void 0;
6267
+ exports.createInputHandler = createInputHandler;
6268
+ var _wgpuMatrix = require("wgpu-matrix");
6269
+ // Note: The code in this file does not use the 'dst' output parameter of functions in the
6270
+ // 'wgpu-matrix' library, so produces many temporary vectors and matrices.
6271
+ // This is intentional, as this sample prefers readability over performance.
6272
+
6273
+ // import Input from './input';
6274
+
6275
+ // // Common interface for camera implementations
6276
+ // export default interface Camera {
6277
+ // // update updates the camera using the user-input and returns the view matrix.
6278
+ // update(delta_time: number, input: Input): Mat4;
6279
+
6280
+ // // The camera matrix.
6281
+ // // This is the inverse of the view matrix.
6282
+ // matrix: Mat4;
6283
+ // // Alias to column vector 0 of the camera matrix.
6284
+ // right: Vec4;
6285
+ // // Alias to column vector 1 of the camera matrix.
6286
+ // up: Vec4;
6287
+ // // Alias to column vector 2 of the camera matrix.
6288
+ // back: Vec4;
6289
+ // // Alias to column vector 3 of the camera matrix.
6290
+ // position: Vec4;
6291
+ // }
6292
+
6293
+ // The common functionality between camera implementations
6294
+ class CameraBase {
6295
+ // The camera matrix
6296
+ matrix_ = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
6297
+
6298
+ // The calculated view matrix readonly
6299
+ view_ = _wgpuMatrix.mat4.create();
6300
+
6301
+ // Aliases to column vectors of the matrix
6302
+ right_ = new Float32Array(this.matrix_.buffer, 4 * 0, 4);
6303
+ up_ = new Float32Array(this.matrix_.buffer, 4 * 4, 4);
6304
+ back_ = new Float32Array(this.matrix_.buffer, 4 * 8, 4);
6305
+ position_ = new Float32Array(this.matrix_.buffer, 4 * 12, 4);
6306
+
6307
+ // Returns the camera matrix
6308
+ get matrix() {
6309
+ return this.matrix_;
6310
+ }
6311
+ // Assigns `mat` to the camera matrix
6312
+ set matrix(mat) {
6313
+ _wgpuMatrix.mat4.copy(mat, this.matrix_);
6314
+ }
6315
+
6316
+ // Returns the camera view matrix
6317
+ get view() {
6318
+ return this.view_;
6319
+ }
6320
+ // Assigns `mat` to the camera view
6321
+ set view(mat) {
6322
+ _wgpuMatrix.mat4.copy(mat, this.view_);
6323
+ }
6324
+
6325
+ // Returns column vector 0 of the camera matrix
6326
+ get right() {
6327
+ return this.right_;
6328
+ }
6329
+ // Assigns `vec` to the first 3 elements of column vector 0 of the camera matrix
6330
+ set right(vec) {
6331
+ _wgpuMatrix.vec3.copy(vec, this.right_);
6332
+ }
6333
+
6334
+ // Returns column vector 1 of the camera matrix
6335
+ get up() {
6336
+ return this.up_;
6337
+ }
6338
+ // Assigns `vec` to the first 3 elements of column vector 1 of the camera matrix \ Vec3
6339
+ set up(vec) {
6340
+ _wgpuMatrix.vec3.copy(vec, this.up_);
6341
+ }
6342
+
6343
+ // Returns column vector 2 of the camera matrix
6344
+ get back() {
6345
+ return this.back_;
6346
+ }
6347
+ // Assigns `vec` to the first 3 elements of column vector 2 of the camera matrix
6348
+ set back(vec) {
6349
+ _wgpuMatrix.vec3.copy(vec, this.back_);
6350
+ }
6351
+
6352
+ // Returns column vector 3 of the camera matrix
6353
+ get position() {
6354
+ return this.position_;
6355
+ }
6356
+ // Assigns `vec` to the first 3 elements of column vector 3 of the camera matrix
6357
+ set position(vec) {
6358
+ _wgpuMatrix.vec3.copy(vec, this.position_);
6359
+ }
6360
+ }
6361
+
6362
+ // WASDCamera is a camera implementation that behaves similar to first-person-shooter PC games.
6363
+ class WASDCamera extends CameraBase {
6364
+ // The camera absolute pitch angle
6365
+ pitch = 0;
6366
+ // The camera absolute yaw angle
6367
+ yaw = 0;
6368
+
6369
+ // The movement veloicty readonly
6370
+ velocity_ = _wgpuMatrix.vec3.create();
6371
+
6372
+ // Speed multiplier for camera movement
6373
+ movementSpeed = 10;
6374
+
6375
+ // Speed multiplier for camera rotation
6376
+ rotationSpeed = 1;
6377
+
6378
+ // Movement velocity drag coeffient [0 .. 1]
6379
+ // 0: Continues forever
6380
+ // 1: Instantly stops moving
6381
+ frictionCoefficient = 0.99;
6382
+
6383
+ // Returns velocity vector
6384
+ get velocity() {
6385
+ return this.velocity_;
6386
+ }
6387
+ // Assigns `vec` to the velocity vector
6388
+ set velocity(vec) {
6389
+ _wgpuMatrix.vec3.copy(vec, this.velocity_);
6390
+ }
6391
+
6392
+ // Construtor
6393
+ constructor(options) {
6394
+ super();
6395
+ if (options && (options.position || options.target)) {
6396
+ const position = options.position ?? _wgpuMatrix.vec3.create(0, 0, 0);
6397
+ const target = options.target ?? _wgpuMatrix.vec3.create(0, 0, 0);
6398
+ const forward = _wgpuMatrix.vec3.normalize(_wgpuMatrix.vec3.sub(target, position));
6399
+ this.recalculateAngles(forward);
6400
+ this.position = position;
6401
+ console.log('camera postion:', position);
6402
+ }
6403
+ }
6404
+
6405
+ // Returns the camera matrix
6406
+ get matrix() {
6407
+ return super.matrix;
6408
+ }
6409
+
6410
+ // Assigns `mat` to the camera matrix, and recalcuates the camera angles
6411
+ set matrix(mat) {
6412
+ super.matrix = mat;
6413
+ this.recalculateAngles(this.back);
6414
+ }
6415
+ update(deltaTime, input) {
6416
+ const sign = (positive, negative) => (positive ? 1 : 0) - (negative ? 1 : 0);
6417
+
6418
+ // Apply the delta rotation to the pitch and yaw angles
6419
+ this.yaw -= input.analog.x * deltaTime * this.rotationSpeed;
6420
+ this.pitch -= input.analog.y * deltaTime * this.rotationSpeed;
6421
+
6422
+ // Wrap yaw between [0° .. 360°], just to prevent large accumulation.
6423
+ this.yaw = mod(this.yaw, Math.PI * 2);
6424
+ // Clamp pitch between [-90° .. +90°] to prevent somersaults.
6425
+ this.pitch = clamp(this.pitch, -Math.PI / 2, Math.PI / 2);
6426
+
6427
+ // Save the current position, as we're about to rebuild the camera matrix.
6428
+ const position = _wgpuMatrix.vec3.copy(this.position);
6429
+
6430
+ // Reconstruct the camera's rotation, and store into the camera matrix.
6431
+ super.matrix = _wgpuMatrix.mat4.rotateX(_wgpuMatrix.mat4.rotationY(this.yaw), this.pitch);
6432
+
6433
+ // Calculate the new target velocity
6434
+ const digital = input.digital;
6435
+ const deltaRight = sign(digital.right, digital.left);
6436
+ const deltaUp = sign(digital.up, digital.down);
6437
+ const targetVelocity = _wgpuMatrix.vec3.create();
6438
+ const deltaBack = sign(digital.backward, digital.forward);
6439
+ _wgpuMatrix.vec3.addScaled(targetVelocity, this.right, deltaRight, targetVelocity);
6440
+ _wgpuMatrix.vec3.addScaled(targetVelocity, this.up, deltaUp, targetVelocity);
6441
+ _wgpuMatrix.vec3.addScaled(targetVelocity, this.back, deltaBack, targetVelocity);
6442
+ _wgpuMatrix.vec3.normalize(targetVelocity, targetVelocity);
6443
+ _wgpuMatrix.vec3.mulScalar(targetVelocity, this.movementSpeed, targetVelocity);
6444
+
6445
+ // Mix new target velocity
6446
+ this.velocity = lerp(targetVelocity, this.velocity, Math.pow(1 - this.frictionCoefficient, deltaTime));
6447
+
6448
+ // Integrate velocity to calculate new position
6449
+ this.position = _wgpuMatrix.vec3.addScaled(position, this.velocity, deltaTime);
6450
+
6451
+ // Invert the camera matrix to build the view matrix
6452
+ this.view = _wgpuMatrix.mat4.invert(this.matrix);
6453
+ return this.view;
6454
+ }
6455
+
6456
+ // Recalculates the yaw and pitch values from a directional vector
6457
+ recalculateAngles(dir) {
6458
+ this.yaw = Math.atan2(dir[0], dir[2]);
6459
+ this.pitch = -Math.asin(dir[1]);
6460
+ }
6461
+ }
6462
+
6463
+ // ArcballCamera implements a basic orbiting camera around the world origin
6464
+ exports.WASDCamera = WASDCamera;
6465
+ class ArcballCamera extends CameraBase {
6466
+ // The camera distance from the target
6467
+ distance = 0;
6468
+
6469
+ // The current angular velocity
6470
+ angularVelocity = 0;
6471
+
6472
+ // The current rotation axis
6473
+ axis_ = _wgpuMatrix.vec3.create();
6474
+
6475
+ // Returns the rotation axis
6476
+ get axis() {
6477
+ return this.axis_;
6478
+ }
6479
+ // Assigns `vec` to the rotation axis
6480
+ set axis(vec) {
6481
+ _wgpuMatrix.vec3.copy(vec, this.axis_);
6482
+ }
6483
+
6484
+ // Speed multiplier for camera rotation
6485
+ rotationSpeed = 1;
6486
+
6487
+ // Speed multiplier for camera zoom
6488
+ zoomSpeed = 0.1;
6489
+
6490
+ // Rotation velocity drag coeffient [0 .. 1]
6491
+ // 0: Spins forever
6492
+ // 1: Instantly stops spinning
6493
+ frictionCoefficient = 0.999;
6494
+
6495
+ // Construtor
6496
+ constructor(options) {
6497
+ super();
6498
+ if (options && options.position) {
6499
+ this.position = options.position;
6500
+ this.distance = _wgpuMatrix.vec3.len(this.position);
6501
+ this.back = _wgpuMatrix.vec3.normalize(this.position);
6502
+ this.recalcuateRight();
6503
+ this.recalcuateUp();
6504
+ }
6505
+ }
6506
+
6507
+ // Returns the camera matrix
6508
+ get matrix() {
6509
+ return super.matrix;
6510
+ }
6511
+
6512
+ // Assigns `mat` to the camera matrix, and recalcuates the distance
6513
+ set matrix(mat) {
6514
+ super.matrix = mat;
6515
+ this.distance = _wgpuMatrix.vec3.len(this.position);
6516
+ }
6517
+ update(deltaTime, input) {
6518
+ const epsilon = 0.0000001;
6519
+ if (input.analog.touching) {
6520
+ // Currently being dragged.
6521
+ this.angularVelocity = 0;
6522
+ } else {
6523
+ // Dampen any existing angular velocity
6524
+ this.angularVelocity *= Math.pow(1 - this.frictionCoefficient, deltaTime);
6525
+ }
6526
+
6527
+ // Calculate the movement vector
6528
+ const movement = _wgpuMatrix.vec3.create();
6529
+ _wgpuMatrix.vec3.addScaled(movement, this.right, input.analog.x, movement);
6530
+ _wgpuMatrix.vec3.addScaled(movement, this.up, -input.analog.y, movement);
6531
+
6532
+ // Cross the movement vector with the view direction to calculate the rotation axis x magnitude
6533
+ const crossProduct = _wgpuMatrix.vec3.cross(movement, this.back);
6534
+
6535
+ // Calculate the magnitude of the drag
6536
+ const magnitude = _wgpuMatrix.vec3.len(crossProduct);
6537
+ if (magnitude > epsilon) {
6538
+ // Normalize the crossProduct to get the rotation axis
6539
+ this.axis = _wgpuMatrix.vec3.scale(crossProduct, 1 / magnitude);
6540
+
6541
+ // Remember the current angular velocity. This is used when the touch is released for a fling.
6542
+ this.angularVelocity = magnitude * this.rotationSpeed;
6543
+ }
6544
+
6545
+ // The rotation around this.axis to apply to the camera matrix this update
6546
+ const rotationAngle = this.angularVelocity * deltaTime;
6547
+ if (rotationAngle > epsilon) {
6548
+ // Rotate the matrix around axis
6549
+ // Note: The rotation is not done as a matrix-matrix multiply as the repeated multiplications
6550
+ // will quickly introduce substantial error into the matrix.
6551
+ this.back = _wgpuMatrix.vec3.normalize(rotate(this.back, this.axis, rotationAngle));
6552
+ this.recalcuateRight();
6553
+ this.recalcuateUp();
6554
+ }
6555
+
6556
+ // recalculate `this.position` from `this.back` considering zoom
6557
+ if (input.analog.zoom !== 0) {
6558
+ this.distance *= 1 + input.analog.zoom * this.zoomSpeed;
6559
+ }
6560
+ this.position = _wgpuMatrix.vec3.scale(this.back, this.distance);
6561
+
6562
+ // Invert the camera matrix to build the view matrix
6563
+ this.view = _wgpuMatrix.mat4.invert(this.matrix);
6564
+ return this.view;
6565
+ }
6566
+
6567
+ // Assigns `this.right` with the cross product of `this.up` and `this.back`
6568
+ recalcuateRight() {
6569
+ this.right = _wgpuMatrix.vec3.normalize(_wgpuMatrix.vec3.cross(this.up, this.back));
6570
+ }
6571
+
6572
+ // Assigns `this.up` with the cross product of `this.back` and `this.right`
6573
+ recalcuateUp() {
6574
+ this.up = _wgpuMatrix.vec3.normalize(_wgpuMatrix.vec3.cross(this.back, this.right));
6575
+ }
6576
+ }
6577
+
6578
+ // Returns `x` clamped between [`min` .. `max`]
6579
+ exports.ArcballCamera = ArcballCamera;
6580
+ function clamp(x, min, max) {
6581
+ return Math.min(Math.max(x, min), max);
6582
+ }
6583
+
6584
+ // Returns `x` float-modulo `div`
6585
+ function mod(x, div) {
6586
+ return x - Math.floor(Math.abs(x) / div) * div * Math.sign(x);
6587
+ }
6588
+
6589
+ // Returns `vec` rotated `angle` radians around `axis`
6590
+ function rotate(vec, axis, angle) {
6591
+ return _wgpuMatrix.vec3.transformMat4Upper3x3(vec, _wgpuMatrix.mat4.rotation(axis, angle));
6592
+ }
6593
+
6594
+ // Returns the linear interpolation between 'a' and 'b' using 's'
6595
+ function lerp(a, b, s) {
6596
+ return _wgpuMatrix.vec3.addScaled(a, _wgpuMatrix.vec3.sub(b, a), s);
6597
+ }
6598
+
6599
+ // IMPUT
6600
+
6601
+ // // Input holds as snapshot of input state
6602
+ // export default interface Input {
6603
+ // // Digital input (e.g keyboard state)
6604
+ // readonly digital: {
6605
+ // readonly forward: boolean;
6606
+ // readonly backward: boolean;
6607
+ // readonly left: boolean;
6608
+ // readonly right: boolean;
6609
+ // readonly up: boolean;
6610
+ // readonly down: boolean;
6611
+ // };
6612
+ // // Analog input (e.g mouse, touchscreen)
6613
+ // readonly analog: {
6614
+ // readonly x: number;
6615
+ // readonly y: number;
6616
+ // readonly zoom: number;
6617
+ // readonly touching: boolean;
6618
+ // };
6619
+ // }
6620
+
6621
+ // InputHandler is a function that when called, returns the current Input state.
6622
+ // export type InputHandler = () => Input;
6623
+
6624
+ // createInputHandler returns an InputHandler by attaching event handlers to the window and canvas.
6625
+ function createInputHandler(window, canvas) {
6626
+ let digital = {
6627
+ forward: false,
6628
+ backward: false,
6629
+ left: false,
6630
+ right: false,
6631
+ up: false,
6632
+ down: false
6633
+ };
6634
+ let analog = {
6635
+ x: 0,
6636
+ y: 0,
6637
+ zoom: 0
6638
+ };
6639
+ let mouseDown = false;
6640
+ const setDigital = (e, value) => {
6641
+ switch (e.code) {
6642
+ case 'KeyW':
6643
+ digital.forward = value;
6644
+ e.preventDefault();
6645
+ e.stopPropagation();
6646
+ break;
6647
+ case 'KeyS':
6648
+ digital.backward = value;
6649
+ e.preventDefault();
6650
+ e.stopPropagation();
6651
+ break;
6652
+ case 'KeyA':
6653
+ digital.left = value;
6654
+ e.preventDefault();
6655
+ e.stopPropagation();
6656
+ break;
6657
+ case 'KeyD':
6658
+ digital.right = value;
6659
+ e.preventDefault();
6660
+ e.stopPropagation();
6661
+ break;
6662
+ case 'Space':
6663
+ digital.up = value;
6664
+ e.preventDefault();
6665
+ e.stopPropagation();
6666
+ break;
6667
+ case 'ShiftLeft':
6668
+ case 'ControlLeft':
6669
+ case 'KeyC':
6670
+ digital.down = value;
6671
+ e.preventDefault();
6672
+ e.stopPropagation();
6673
+ break;
6674
+ }
6675
+ };
6676
+ window.addEventListener('keydown', e => setDigital(e, true));
6677
+ window.addEventListener('keyup', e => setDigital(e, false));
6678
+ canvas.style.touchAction = 'pinch-zoom';
6679
+ canvas.addEventListener('pointerdown', () => {
6680
+ mouseDown = true;
6681
+ });
6682
+ canvas.addEventListener('pointerup', () => {
6683
+ mouseDown = false;
6684
+ });
6685
+ canvas.addEventListener('pointermove', e => {
6686
+ mouseDown = e.pointerType == 'mouse' ? (e.buttons & 1) !== 0 : true;
6687
+ if (mouseDown) {
6688
+ // console.log('TEST ', analog)
6689
+ analog.x += e.movementX / 10;
6690
+ analog.y += e.movementY / 10;
6691
+ }
6692
+ });
6693
+ canvas.addEventListener('wheel', e => {
6694
+ mouseDown = (e.buttons & 1) !== 0;
6695
+ if (mouseDown) {
6696
+ // The scroll value varies substantially between user agents / browsers.
6697
+ // Just use the sign.
6698
+ analog.zoom += Math.sign(e.deltaY);
6699
+ e.preventDefault();
6700
+ e.stopPropagation();
6701
+ }
6702
+ }, {
6703
+ passive: false
6704
+ });
6705
+ return () => {
6706
+ const out = {
6707
+ digital,
6708
+ analog: {
6709
+ x: analog.x,
6710
+ y: analog.y,
6711
+ zoom: analog.zoom,
6712
+ touching: mouseDown
6713
+ }
6714
+ };
6715
+ // Clear the analog values, as these accumulate.
6716
+ analog.x = 0;
6717
+ analog.y = 0;
6718
+ analog.zoom = 0;
6719
+ return out;
6720
+ };
6721
+ }
6722
+
6723
+ },{"wgpu-matrix":2}],6:[function(require,module,exports){
6724
+ "use strict";
6725
+
6726
+ Object.defineProperty(exports, "__esModule", {
6727
+ value: true
6728
+ });
6729
+ exports.makeObjSeqArg = exports.initMeshBuffers = exports.downloadMeshes = exports.constructMesh = void 0;
6730
+ exports.play = play;
6731
+ /**
6732
+ * The main Mesh class. The constructor will parse through the OBJ file data
6733
+ * and collect the vertex, vertex normal, texture, and face information. This
6734
+ * information can then be used later on when creating your VBOs. See
6735
+ * OBJ.initMeshBuffers for an example of how to use the newly created Mesh
6736
+ *
6737
+ * @class Mesh
6738
+ * @constructor
6739
+ *
6740
+ * @param {String} objectData a string representation of an OBJ file with newlines preserved.
6741
+ */
6742
+
6743
+ class constructMesh {
6744
+ constructor(objectData, inputArg) {
6745
+ this.inputArg = inputArg;
6746
+ this.objectData = objectData;
6747
+ this.create(objectData, inputArg);
6748
+ this.setScale = s => {
6749
+ this.inputArg.scale = s;
6750
+ this.create(this.objectData, this.inputArg);
6751
+ };
6752
+ this.updateBuffers = () => {
6753
+ this.inputArg.scale = 1;
6754
+ this.create(this.objectData, this.inputArg);
6755
+ };
6756
+ }
6757
+ create = (objectData, inputArg, callback) => {
6758
+ if (typeof callback === 'undefined') callback = function () {};
6759
+ let initOrientation = [0, 1, 2];
6760
+ /*
6761
+ The OBJ file format does a sort of compression when saving a model in a
6762
+ program like Blender. There are at least 3 sections (4 including textures)
6763
+ within the file. Each line in a section begins with the same string:
6764
+ * 'v': indicates vertex section
6765
+ * 'vn': indicates vertex normal section
6766
+ * 'f': indicates the faces section
6767
+ * 'vt': indicates vertex texture section (if textures were used on the model)
6768
+ Each of the above sections (except for the faces section) is a list/set of
6769
+ unique vertices.
6770
+ Each line of the faces section contains a list of
6771
+ (vertex, [texture], normal) groups
6772
+ Some examples:
6773
+ // the texture index is optional, both formats are possible for models
6774
+ // without a texture applied
6775
+ f 1/25 18/46 12/31
6776
+ f 1//25 18//46 12//31
6777
+ // A 3 vertex face with texture indices
6778
+ f 16/92/11 14/101/22 1/69/1
6779
+ // A 4 vertex face
6780
+ f 16/92/11 40/109/40 38/114/38 14/101/22
6781
+ The first two lines are examples of a 3 vertex face without a texture applied.
6782
+ The second is an example of a 3 vertex face with a texture applied.
6783
+ The third is an example of a 4 vertex face. Note: a face can contain N
6784
+ number of vertices.
6785
+ Each number that appears in one of the groups is a 1-based index
6786
+ corresponding to an item from the other sections (meaning that indexing
6787
+ starts at one and *not* zero).
6788
+ For example:
6789
+ `f 16/92/11` is saying to
6790
+ - take the 16th element from the [v] vertex array
6791
+ - take the 92nd element from the [vt] texture array
6792
+ - take the 11th element from the [vn] normal array
6793
+ and together they make a unique vertex.
6794
+ Using all 3+ unique Vertices from the face line will produce a polygon.
6795
+ Now, you could just go through the OBJ file and create a new vertex for
6796
+ each face line and WebGL will draw what appears to be the same model.
6797
+ However, vertices will be overlapped and duplicated all over the place.
6798
+ Consider a cube in 3D space centered about the origin and each side is
6799
+ 2 units long. The front face (with the positive Z-axis pointing towards
6800
+ you) would have a Top Right vertex (looking orthogonal to its normal)
6801
+ mapped at (1,1,1) The right face would have a Top Left vertex (looking
6802
+ orthogonal to its normal) at (1,1,1) and the top face would have a Bottom
6803
+ Right vertex (looking orthogonal to its normal) at (1,1,1). Each face
6804
+ has a vertex at the same coordinates, however, three distinct vertices
6805
+ will be drawn at the same spot.
6806
+ To solve the issue of duplicate Vertices (the `(vertex, [texture], normal)`
6807
+ groups), while iterating through the face lines, when a group is encountered
6808
+ the whole group string ('16/92/11') is checked to see if it exists in the
6809
+ packed.hashindices object, and if it doesn't, the indices it specifies
6810
+ are used to look up each attribute in the corresponding attribute arrays
6811
+ already created. The values are then copied to the corresponding unpacked
6812
+ array (flattened to play nice with WebGL's ELEMENT_ARRAY_BUFFER indexing),
6813
+ the group string is added to the hashindices set and the current unpacked
6814
+ index is used as this hashindices value so that the group of elements can
6815
+ be reused. The unpacked index is incremented. If the group string already
6816
+ exists in the hashindices object, its corresponding value is the index of
6817
+ that group and is appended to the unpacked indices array.
6818
+ */
6819
+ var verts = [],
6820
+ vertNormals = [],
6821
+ textures = [],
6822
+ unpacked = {};
6823
+ // unpacking stuff
6824
+ unpacked.verts = [];
6825
+ unpacked.norms = [];
6826
+ unpacked.textures = [];
6827
+ unpacked.hashindices = {};
6828
+ unpacked.indices = [];
6829
+ unpacked.index = 0;
6830
+ // array of lines separated by the newline
6831
+ var lines = objectData.split('\n');
6832
+
6833
+ // update swap orientation
6834
+ if (inputArg.swap[0] !== null) {
6835
+ swap(inputArg.swap[0], inputArg.swap[1], initOrientation);
6836
+ }
6837
+ var VERTEX_RE = /^v\s/;
6838
+ var NORMAL_RE = /^vn\s/;
6839
+ var TEXTURE_RE = /^vt\s/;
6840
+ var FACE_RE = /^f\s/;
6841
+ var WHITESPACE_RE = /\s+/;
6842
+ for (var i = 0; i < lines.length; i++) {
6843
+ var line = lines[i].trim();
6844
+ var elements = line.split(WHITESPACE_RE);
6845
+ elements.shift();
6846
+ if (VERTEX_RE.test(line)) {
6847
+ // if this is a vertex
6848
+ verts.push.apply(verts, elements);
6849
+ } else if (NORMAL_RE.test(line)) {
6850
+ // if this is a vertex normal
6851
+ vertNormals.push.apply(vertNormals, elements);
6852
+ } else if (TEXTURE_RE.test(line)) {
6853
+ // if this is a texture
6854
+ textures.push.apply(textures, elements);
6855
+ } else if (FACE_RE.test(line)) {
6856
+ // if this is a face
6857
+ /*
6858
+ split this face into an array of vertex groups
6859
+ for example:
6860
+ f 16/92/11 14/101/22 1/69/1
6861
+ becomes:
6862
+ ['16/92/11', '14/101/22', '1/69/1'];
6863
+ */
6864
+ var quad = false;
6865
+ for (var j = 0, eleLen = elements.length; j < eleLen; j++) {
6866
+ // Triangulating quads
6867
+ // quad: 'f v0/t0/vn0 v1/t1/vn1 v2/t2/vn2 v3/t3/vn3/'
6868
+ // corresponding triangles:
6869
+ // 'f v0/t0/vn0 v1/t1/vn1 v2/t2/vn2'
6870
+ // 'f v2/t2/vn2 v3/t3/vn3 v0/t0/vn0'
6871
+ if (j === 3 && !quad) {
6872
+ // add v2/t2/vn2 in again before continuing to 3
6873
+ j = 2;
6874
+ quad = true;
6875
+ }
6876
+ if (elements[j] in unpacked.hashindices) {
6877
+ unpacked.indices.push(unpacked.hashindices[elements[j]]);
6878
+ } else {
6879
+ /*
6880
+ Each element of the face line array is a vertex which has its
6881
+ attributes delimited by a forward slash. This will separate
6882
+ each attribute into another array:
6883
+ '19/92/11'
6884
+ becomes:
6885
+ vertex = ['19', '92', '11'];
6886
+ where
6887
+ vertex[0] is the vertex index
6888
+ vertex[1] is the texture index
6889
+ vertex[2] is the normal index
6890
+ Think of faces having Vertices which are comprised of the
6891
+ attributes location (v), texture (vt), and normal (vn).
6892
+ */
6893
+ var vertex = elements[j].split('/');
6894
+ /*
6895
+ The verts, textures, and vertNormals arrays each contain a
6896
+ flattend array of coordinates.
6897
+ Because it gets confusing by referring to vertex and then
6898
+ vertex (both are different in my descriptions) I will explain
6899
+ what's going on using the vertexNormals array:
6900
+ vertex[2] will contain the one-based index of the vertexNormals
6901
+ section (vn). One is subtracted from this index number to play
6902
+ nice with javascript's zero-based array indexing.
6903
+ Because vertexNormal is a flattened array of x, y, z values,
6904
+ simple pointer arithmetic is used to skip to the start of the
6905
+ vertexNormal, then the offset is added to get the correct
6906
+ component: +0 is x, +1 is y, +2 is z.
6907
+ This same process is repeated for verts and textures.
6908
+ */
6909
+ // vertex position
6910
+ unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + initOrientation[0]] * inputArg.scale);
6911
+ unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + initOrientation[1]] * inputArg.scale);
6912
+ unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + initOrientation[2]] * inputArg.scale);
6913
+
6914
+ // vertex textures
6915
+ if (textures.length) {
6916
+ unpacked.textures.push(+textures[(vertex[1] - 1) * 2 + 0]);
6917
+ unpacked.textures.push(+textures[(vertex[1] - 1) * 2 + 1]);
6918
+ }
6919
+ // vertex normals
6920
+ unpacked.norms.push(+vertNormals[(vertex[2] - 1) * 3 + 0]);
6921
+ unpacked.norms.push(+vertNormals[(vertex[2] - 1) * 3 + 1]);
6922
+ unpacked.norms.push(+vertNormals[(vertex[2] - 1) * 3 + 2]);
6923
+ // add the newly created vertex to the list of indices
6924
+ unpacked.hashindices[elements[j]] = unpacked.index;
6925
+ unpacked.indices.push(unpacked.index);
6926
+ // increment the counter
6927
+ unpacked.index += 1;
6928
+ }
6929
+ if (j === 3 && quad) {
6930
+ // add v0/t0/vn0 onto the second triangle
6931
+ unpacked.indices.push(unpacked.hashindices[elements[0]]);
6932
+ }
6933
+ }
6934
+ }
6935
+ }
6936
+ this.vertices = unpacked.verts;
6937
+ this.vertexNormals = unpacked.norms;
6938
+ this.textures = unpacked.textures;
6939
+ this.indices = unpacked.indices;
6940
+ callback();
6941
+ return this;
6942
+ };
6943
+ }
6944
+ exports.constructMesh = constructMesh;
6945
+ var Ajax = function () {
6946
+ // this is just a helper class to ease ajax calls
6947
+ var _this = this;
6948
+ this.xmlhttp = new XMLHttpRequest();
6949
+ this.get = function (url, callback) {
6950
+ _this.xmlhttp.onreadystatechange = function () {
6951
+ if (_this.xmlhttp.readyState === 4) {
6952
+ callback(_this.xmlhttp.responseText, _this.xmlhttp.status);
6953
+ }
6954
+ };
6955
+ _this.xmlhttp.open('GET', url, true);
6956
+ _this.xmlhttp.send();
6957
+ };
6958
+ };
6959
+
6960
+ /**
6961
+ * Takes in an object of `mesh_name`, `'/url/to/OBJ/file'` pairs and a callback
6962
+ * function. Each OBJ file will be ajaxed in and automatically converted to
6963
+ * an OBJ.Mesh. When all files have successfully downloaded the callback
6964
+ * function provided will be called and passed in an object containing
6965
+ * the newly created meshes.
6966
+ *
6967
+ * **Note:** In order to use this function as a way to download meshes, a
6968
+ * webserver of some sort must be used.
6969
+ *
6970
+ * @param {Object} nameAndURLs an object where the key is the name of the mesh and the value is the url to that mesh's OBJ file
6971
+ *
6972
+ * @param {Function} completionCallback should contain a function that will take one parameter: an object array where the keys will be the unique object name and the value will be a Mesh object
6973
+ *
6974
+ * @param {Object} meshes In case other meshes are loaded separately or if a previously declared variable is desired to be used, pass in a (possibly empty) json object of the pattern: { '<mesh_name>': OBJ.Mesh }
6975
+ *
6976
+ */
6977
+ var downloadMeshes = function (nameAndURLs, completionCallback, inputArg) {
6978
+ // the total number of meshes. this is used to implement "blocking"
6979
+ var semaphore = Object.keys(nameAndURLs).length;
6980
+ // if error is true, an alert will given
6981
+ var error = false;
6982
+ // this is used to check if all meshes have been downloaded
6983
+ // if meshes is supplied, then it will be populated, otherwise
6984
+ // a new object is created. this will be passed into the completionCallback
6985
+ if (typeof inputArg === 'undefined') {
6986
+ var inputArg = {
6987
+ scale: 1,
6988
+ swap: [null]
6989
+ };
6990
+ }
6991
+ if (typeof inputArg.scale === 'undefined') inputArg.scale = 0.1;
6992
+ if (typeof inputArg.swap === 'undefined') inputArg.swap = [null];
6993
+ var meshes = {};
6994
+
6995
+ // loop over the mesh_name,url key,value pairs
6996
+ for (var mesh_name in nameAndURLs) {
6997
+ if (nameAndURLs.hasOwnProperty(mesh_name)) {
6998
+ new Ajax().get(nameAndURLs[mesh_name], function (name) {
6999
+ return function (data, status) {
7000
+ if (status === 200) {
7001
+ meshes[name] = new constructMesh(data, inputArg);
7002
+ } else {
7003
+ error = true;
7004
+ console.error('An error has occurred and the mesh "' + name + '" could not be downloaded.');
7005
+ }
7006
+ // the request has finished, decrement the counter
7007
+ semaphore--;
7008
+ if (semaphore === 0) {
7009
+ if (error) {
7010
+ // if an error has occurred, the user is notified here and the
7011
+ // callback is not called
7012
+ console.error('An error has occurred and one or meshes has not been ' + 'downloaded. The execution of the script has terminated.');
7013
+ throw '';
7014
+ }
7015
+ // there haven't been any errors in retrieving the meshes
7016
+ // call the callback
7017
+ completionCallback(meshes);
7018
+ }
7019
+ };
7020
+ }(mesh_name));
7021
+ }
7022
+ }
7023
+ };
7024
+
7025
+ /**
7026
+ * Takes in the WebGL context and a Mesh, then creates and appends the buffers
7027
+ * to the mesh object as attributes.
7028
+ *
7029
+ * @param {WebGLRenderingContext} gl the `canvas.getContext('webgl')` context instance
7030
+ * @param {Mesh} mesh a single `OBJ.Mesh` instance
7031
+ *
7032
+ * The newly created mesh attributes are:
7033
+ *
7034
+ * Attrbute | Description
7035
+ * :--- | ---
7036
+ * **normalBuffer** |contains the model&#39;s Vertex Normals
7037
+ * normalBuffer.itemSize |set to 3 items
7038
+ * normalBuffer.numItems |the total number of vertex normals
7039
+ * |
7040
+ * **textureBuffer** |contains the model&#39;s Texture Coordinates
7041
+ * textureBuffer.itemSize |set to 2 items
7042
+ * textureBuffer.numItems |the number of texture coordinates
7043
+ * |
7044
+ * **vertexBuffer** |contains the model&#39;s Vertex Position Coordinates (does not include w)
7045
+ * vertexBuffer.itemSize |set to 3 items
7046
+ * vertexBuffer.numItems |the total number of vertices
7047
+ * |
7048
+ * **indexBuffer** |contains the indices of the faces
7049
+ * indexBuffer.itemSize |is set to 1
7050
+ * indexBuffer.numItems |the total number of indices
7051
+ *
7052
+ * A simple example (a lot of steps are missing, so don't copy and paste):
7053
+ *
7054
+ * var gl = canvas.getContext('webgl'),
7055
+ * mesh = OBJ.Mesh(obj_file_data);
7056
+ * // compile the shaders and create a shader program
7057
+ * var shaderProgram = gl.createProgram();
7058
+ * // compilation stuff here
7059
+ * ...
7060
+ * // make sure you have vertex, vertex normal, and texture coordinate
7061
+ * // attributes located in your shaders and attach them to the shader program
7062
+ * shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
7063
+ * gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
7064
+ *
7065
+ * shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
7066
+ * gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);
7067
+ *
7068
+ * shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
7069
+ * gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
7070
+ *
7071
+ * // create and initialize the vertex, vertex normal, and texture coordinate buffers
7072
+ * // and save on to the mesh object
7073
+ * OBJ.initMeshBuffers(gl, mesh);
7074
+ *
7075
+ * // now to render the mesh
7076
+ * gl.bindBuffer(gl.ARRAY_BUFFER, mesh.vertexBuffer);
7077
+ * gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, mesh.vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
7078
+ * // it's possible that the mesh doesn't contain
7079
+ * // any texture coordinates (e.g. suzanne.obj in the development branch).
7080
+ * // in this case, the texture vertexAttribArray will need to be disabled
7081
+ * // before the call to drawElements
7082
+ * if(!mesh.textures.length){
7083
+ * gl.disableVertexAttribArray(shaderProgram.textureCoordAttribute);
7084
+ * }
7085
+ * else{
7086
+ * // if the texture vertexAttribArray has been previously
7087
+ * // disabled, then it needs to be re-enabled
7088
+ * gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
7089
+ * gl.bindBuffer(gl.ARRAY_BUFFER, mesh.textureBuffer);
7090
+ * gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, mesh.textureBuffer.itemSize, gl.FLOAT, false, 0, 0);
7091
+ * }
7092
+ *
7093
+ * gl.bindBuffer(gl.ARRAY_BUFFER, mesh.normalBuffer);
7094
+ * gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, mesh.normalBuffer.itemSize, gl.FLOAT, false, 0, 0);
7095
+ *
7096
+ * gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.mesh.indexBuffer);
7097
+ * gl.drawElements(gl.TRIANGLES, model.mesh.indexBuffer.numItems, gl.UNSIGNED_SHORT, 0);
7098
+ */
7099
+ exports.downloadMeshes = downloadMeshes;
7100
+ var initMeshBuffers = function (gl, mesh) {
7101
+ // mesh.vertexNormals
7102
+ // mesh.textures
7103
+ // mesh.vertices
7104
+ // mesh.indices
7105
+ };
7106
+
7107
+ /**
7108
+ * @description
7109
+ * Construct sequence list argument for downloadMeshes.
7110
+ * This is adaptation for blender obj animation export.
7111
+ * For example:
7112
+ * matrixEngine.objLoader.downloadMeshes(
7113
+ matrixEngine.objLoader.makeObjSeqArg(
7114
+ {
7115
+ id: objName,
7116
+ joinMultiPahts: [
7117
+ {
7118
+ path: "res/bvh-skeletal-base/swat-guy/seq-walk/low/swat",
7119
+ id: objName,
7120
+ from: 1, to: 34
7121
+ },
7122
+ {
7123
+ path: "res/bvh-skeletal-base/swat-guy/seq-walk-pistol/low/swat-walk-pistol",
7124
+ id: objName,
7125
+ from: 35, to: 54
7126
+ }
7127
+ ]
7128
+ }),
7129
+ onLoadObj
7130
+ );
7131
+ */
7132
+ exports.initMeshBuffers = initMeshBuffers;
7133
+ const makeObjSeqArg = arg => {
7134
+ // Adaptation for blender (animation) obj exporter.
7135
+ var local = {};
7136
+ function localCalc(arg, noInitial = false) {
7137
+ var zeros = '00000';
7138
+ var l = {};
7139
+ var helper = arg.from;
7140
+ for (let j = arg.from, z = 1; j <= arg.to; j++) {
7141
+ if (z > 9 && z < 99) {
7142
+ zeros = '0000';
7143
+ } else if (z > 99 && z < 999) {
7144
+ zeros = '000';
7145
+ } // no need more then 999
7146
+
7147
+ if (helper == arg.from && noInitial === false) {
7148
+ l[arg.id] = arg.path + '_' + zeros + z + '.obj';
7149
+ } else {
7150
+ l[arg.id + (helper - 1)] = arg.path + '_' + zeros + z + '.obj';
7151
+ }
7152
+ helper++;
7153
+ z++;
7154
+ }
7155
+ return l;
7156
+ }
7157
+ if (typeof arg.path === 'string') {
7158
+ local = localCalc(arg);
7159
+ } else if (typeof arg.path === 'undefined') {
7160
+ if (typeof arg.joinMultiPahts !== 'undefined') {
7161
+ console.log("ITS joinMultiPahts!");
7162
+ var localFinal = {};
7163
+ arg.joinMultiPahts.forEach((arg, index) => {
7164
+ if (index === 0) {
7165
+ localFinal = Object.assign(local, localCalc(arg));
7166
+ } else {
7167
+ localFinal = Object.assign(local, localCalc(arg, true));
7168
+ }
7169
+ });
7170
+ console.log("joinMultiPahts LOCAL => ", localFinal);
7171
+ return localFinal;
7172
+ }
7173
+ }
7174
+ return local;
7175
+ };
7176
+
7177
+ /**
7178
+ * @description
7179
+ * Switching obj seq animations frames range.
7180
+ */
7181
+ exports.makeObjSeqArg = makeObjSeqArg;
7182
+ function play(nameAni) {
7183
+ this.animation.anims.active = nameAni;
7184
+ this.animation.currentAni = this.animation.anims[this.animation.anims.active].from;
7185
+ }
7186
+
7187
+ },{}],7:[function(require,module,exports){
6173
7188
  "use strict";
6174
7189
 
6175
7190
  Object.defineProperty(exports, "__esModule", {
6176
7191
  value: true
6177
7192
  });
6178
7193
  exports.Rotation = exports.Position = void 0;
7194
+ var _utils = require("./utils");
6179
7195
  // Sub classes for matrix-wgpu
6180
-
6181
7196
  /**
6182
7197
  * @description Base class
6183
7198
  * Position { x, y, z }
@@ -6344,7 +7359,7 @@ class Rotation {
6344
7359
  }
6345
7360
  getRotX() {
6346
7361
  if (this.rotationSpeed.x == 0) {
6347
- return this.x;
7362
+ return (0, _utils.degToRad)(this.x);
6348
7363
  } else {
6349
7364
  this.x = this.x + this.rotationSpeed.x * 0.001;
6350
7365
  return this.x;
@@ -6352,7 +7367,7 @@ class Rotation {
6352
7367
  }
6353
7368
  getRotY() {
6354
7369
  if (this.rotationSpeed.y == 0) {
6355
- return this.y;
7370
+ return (0, _utils.degToRad)(this.y);
6356
7371
  } else {
6357
7372
  this.y = this.y + this.rotationSpeed.y * 0.001;
6358
7373
  return this.y;
@@ -6360,7 +7375,7 @@ class Rotation {
6360
7375
  }
6361
7376
  getRotZ() {
6362
7377
  if (this.rotationSpeed.z == 0) {
6363
- return this.z;
7378
+ return (0, _utils.degToRad)(this.z);
6364
7379
  } else {
6365
7380
  this.z = this.z + this.rotationSpeed.z * 0.001;
6366
7381
  return this.z;
@@ -6369,40 +7384,1462 @@ class Rotation {
6369
7384
  }
6370
7385
  exports.Rotation = Rotation;
6371
7386
 
6372
- },{}],6:[function(require,module,exports){
7387
+ },{"./utils":9}],8:[function(require,module,exports){
6373
7388
  "use strict";
6374
7389
 
6375
7390
  Object.defineProperty(exports, "__esModule", {
6376
7391
  value: true
6377
7392
  });
6378
7393
  exports.default = void 0;
6379
- var _ball = _interopRequireDefault(require("./engine/ball.js"));
6380
- var _cube = _interopRequireDefault(require("./engine/cube.js"));
6381
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
6382
- class MatrixEngineWGPU {
6383
- mainRenderBundle = [];
6384
- rbContainer = [];
6385
- frame = () => {};
6386
- entityArgPass = {
6387
- loadOp: 'clear',
6388
- storeOp: 'store',
6389
- depthLoadOp: 'clear',
6390
- depthStoreOp: 'store'
6391
- };
6392
- constructor(options, callback) {
6393
- console.log('typeof options ', typeof options);
6394
- console.log('typeof options ', options);
6395
- if (typeof options == 'undefined' || typeof options == "function") {
6396
- this.options = {
6397
- useSingleRenderPass: true
6398
- };
6399
- callback = options;
7394
+ var _wgpuMatrix = require("wgpu-matrix");
7395
+ var _matrixClass = require("./matrix-class");
7396
+ var _engine = require("./engine");
7397
+ var _vertexShadow = require("../shaders/vertexShadow.wgsl");
7398
+ var _fragment = require("../shaders/fragment.wgsl");
7399
+ var _vertex = require("../shaders/vertex.wgsl");
7400
+ class MEMeshObj {
7401
+ constructor(canvas, device, context, o) {
7402
+ this.done = false;
7403
+ this.device = device;
7404
+ this.context = context;
7405
+ this.entityArgPass = o.entityArgPass;
7406
+
7407
+ // Mesh stuff
7408
+ this.mesh = o.mesh;
7409
+ this.mesh.uvs = this.mesh.textures;
7410
+ console.log('mesh obj: ', this.mesh);
7411
+ this.inputHandler = (0, _engine.createInputHandler)(window, canvas);
7412
+ this.cameras = o.cameras;
7413
+ this.mainCameraParams = {
7414
+ type: o.mainCameraParams.type,
7415
+ responseCoef: o.mainCameraParams.responseCoef
7416
+ };
7417
+ this.lastFrameMS = 0;
7418
+ this.texturesPaths = [];
7419
+ o.texturesPaths.forEach(t => {
7420
+ this.texturesPaths.push(t);
7421
+ });
7422
+ this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
7423
+ this.position = new _matrixClass.Position(o.position.x, o.position.y, o.position.z);
7424
+ this.rotation = new _matrixClass.Rotation(o.rotation.x, o.rotation.y, o.rotation.z);
7425
+ this.rotation.rotationSpeed.x = o.rotationSpeed.x;
7426
+ this.rotation.rotationSpeed.y = o.rotationSpeed.y;
7427
+ this.rotation.rotationSpeed.z = o.rotationSpeed.z;
7428
+ this.scale = o.scale;
7429
+ this.runProgram = () => {
7430
+ return new Promise(async resolve => {
7431
+ this.shadowDepthTextureSize = 1024;
7432
+ const aspect = canvas.width / canvas.height;
7433
+ this.projectionMatrix = _wgpuMatrix.mat4.perspective(2 * Math.PI / 5, aspect, 1, 2000.0);
7434
+ this.modelViewProjectionMatrix = _wgpuMatrix.mat4.create();
7435
+ // console.log('cube added texturesPaths: ', this.texturesPaths)
7436
+ this.loadTex0(this.texturesPaths, device).then(() => {
7437
+ // console.log('loaded tex buffer for mesh:', this.texture0)
7438
+ resolve();
7439
+ });
7440
+ });
7441
+ };
7442
+ this.runProgram().then(() => {
7443
+ const aspect = canvas.width / canvas.height;
7444
+ const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
7445
+ this.context.configure({
7446
+ device: this.device,
7447
+ format: presentationFormat,
7448
+ alphaMode: 'premultiplied'
7449
+ });
7450
+
7451
+ // Create the model vertex buffer.
7452
+ this.vertexBuffer = this.device.createBuffer({
7453
+ size: this.mesh.vertices.length * Float32Array.BYTES_PER_ELEMENT,
7454
+ usage: GPUBufferUsage.VERTEX,
7455
+ mappedAtCreation: true
7456
+ });
7457
+ {
7458
+ // const mapping = new Float32Array(this.vertexBuffer.getMappedRange());
7459
+ // // for(let i = 0;i < this.mesh.vertices.length;++i) {
7460
+ // // mapping.set(this.mesh.vertices[i], 6 * i);
7461
+ // // mapping.set(this.mesh.normals[i], 6 * i + 3);
7462
+ // // }
7463
+ // this.vertexBuffer.unmap();
7464
+ new Float32Array(this.vertexBuffer.getMappedRange()).set(this.mesh.vertices);
7465
+ this.vertexBuffer.unmap();
7466
+ }
7467
+
7468
+ // NIDZA TEST SECOUND BUFFER
7469
+ // Create the model vertex buffer.
7470
+ this.vertexNormalsBuffer = this.device.createBuffer({
7471
+ size: this.mesh.vertexNormals.length * Float32Array.BYTES_PER_ELEMENT,
7472
+ usage: GPUBufferUsage.VERTEX,
7473
+ mappedAtCreation: true
7474
+ });
7475
+ {
7476
+ new Float32Array(this.vertexNormalsBuffer.getMappedRange()).set(this.mesh.vertexNormals);
7477
+ this.vertexNormalsBuffer.unmap();
7478
+ }
7479
+ this.vertexTexCoordsBuffer = this.device.createBuffer({
7480
+ size: this.mesh.textures.length * Float32Array.BYTES_PER_ELEMENT,
7481
+ usage: GPUBufferUsage.VERTEX,
7482
+ mappedAtCreation: true
7483
+ });
7484
+ {
7485
+ new Float32Array(this.vertexTexCoordsBuffer.getMappedRange()).set(this.mesh.textures);
7486
+ this.vertexTexCoordsBuffer.unmap();
7487
+ }
7488
+
7489
+ // Create the model index buffer.
7490
+ this.indexCount = this.mesh.indices.length;
7491
+ this.indexBuffer = this.device.createBuffer({
7492
+ size: this.indexCount * Uint16Array.BYTES_PER_ELEMENT,
7493
+ usage: GPUBufferUsage.INDEX,
7494
+ mappedAtCreation: true
7495
+ });
7496
+ {
7497
+ // const mapping = new Uint16Array(this.indexBuffer.getMappedRange());
7498
+ // for(let i = 0;i < this.mesh.indices.length;++i) {
7499
+ // mapping.set(this.mesh.indices[i], i);
7500
+ // }
7501
+ new Uint16Array(this.indexBuffer.getMappedRange()).set(this.mesh.indices);
7502
+ this.indexBuffer.unmap();
7503
+ }
7504
+
7505
+ // Create the depth texture for rendering/sampling the shadow map.
7506
+ this.shadowDepthTexture = this.device.createTexture({
7507
+ size: [this.shadowDepthTextureSize, this.shadowDepthTextureSize, 1],
7508
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
7509
+ format: 'depth32float'
7510
+ });
7511
+ this.shadowDepthTextureView = this.shadowDepthTexture.createView();
7512
+
7513
+ // Create some common descriptors used for both the shadow pipeline
7514
+ // and the color rendering pipeline.
7515
+ this.vertexBuffers = [{
7516
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
7517
+ attributes: [{
7518
+ // position
7519
+ shaderLocation: 0,
7520
+ offset: 0,
7521
+ format: "float32x3"
7522
+ }]
7523
+ }, {
7524
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
7525
+ attributes: [{
7526
+ // normal
7527
+ shaderLocation: 1,
7528
+ offset: 0,
7529
+ format: "float32x3"
7530
+ }]
7531
+ }, {
7532
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 2,
7533
+ attributes: [{
7534
+ // uvs
7535
+ shaderLocation: 2,
7536
+ offset: 0,
7537
+ format: "float32x2"
7538
+ }]
7539
+ }];
7540
+ const primitive = {
7541
+ topology: 'triangle-list',
7542
+ cullMode: 'back'
7543
+ };
7544
+ this.uniformBufferBindGroupLayout = this.device.createBindGroupLayout({
7545
+ entries: [{
7546
+ binding: 0,
7547
+ visibility: GPUShaderStage.VERTEX,
7548
+ buffer: {
7549
+ type: 'uniform'
7550
+ }
7551
+ }]
7552
+ });
7553
+ this.shadowPipeline = this.device.createRenderPipeline({
7554
+ layout: this.device.createPipelineLayout({
7555
+ bindGroupLayouts: [this.uniformBufferBindGroupLayout, this.uniformBufferBindGroupLayout]
7556
+ }),
7557
+ vertex: {
7558
+ module: this.device.createShaderModule({
7559
+ code: _vertexShadow.vertexShadowWGSL
7560
+ }),
7561
+ buffers: this.vertexBuffers
7562
+ },
7563
+ depthStencil: {
7564
+ depthWriteEnabled: true,
7565
+ depthCompare: 'less',
7566
+ format: 'depth32float'
7567
+ },
7568
+ primitive
7569
+ });
7570
+
7571
+ // Create a bind group layout which holds the scene uniforms and
7572
+ // the texture+sampler for depth. We create it manually because the WebPU
7573
+ // implementation doesn't infer this from the shader (yet).
7574
+ this.bglForRender = this.device.createBindGroupLayout({
7575
+ entries: [{
7576
+ binding: 0,
7577
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
7578
+ buffer: {
7579
+ type: 'uniform'
7580
+ }
7581
+ }, {
7582
+ binding: 1,
7583
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
7584
+ texture: {
7585
+ sampleType: 'depth'
7586
+ }
7587
+ }, {
7588
+ binding: 2,
7589
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
7590
+ sampler: {
7591
+ type: 'comparison'
7592
+ }
7593
+ }, {
7594
+ binding: 3,
7595
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
7596
+ texture: {
7597
+ sampleType: 'float'
7598
+ }
7599
+ }, {
7600
+ binding: 4,
7601
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
7602
+ sampler: {
7603
+ type: 'filtering'
7604
+ }
7605
+ }]
7606
+ });
7607
+ this.pipeline = this.device.createRenderPipeline({
7608
+ layout: this.device.createPipelineLayout({
7609
+ bindGroupLayouts: [this.bglForRender, this.uniformBufferBindGroupLayout]
7610
+ }),
7611
+ vertex: {
7612
+ module: this.device.createShaderModule({
7613
+ code: _vertex.vertexWGSL
7614
+ }),
7615
+ buffers: this.vertexBuffers
7616
+ },
7617
+ fragment: {
7618
+ module: this.device.createShaderModule({
7619
+ code: _fragment.fragmentWGSL
7620
+ }),
7621
+ targets: [{
7622
+ format: presentationFormat
7623
+ }],
7624
+ constants: {
7625
+ shadowDepthTextureSize: this.shadowDepthTextureSize
7626
+ }
7627
+ },
7628
+ depthStencil: {
7629
+ depthWriteEnabled: true,
7630
+ depthCompare: 'less',
7631
+ format: 'depth24plus-stencil8'
7632
+ },
7633
+ primitive
7634
+ });
7635
+ const depthTexture = this.device.createTexture({
7636
+ size: [canvas.width, canvas.height],
7637
+ format: 'depth24plus-stencil8',
7638
+ usage: GPUTextureUsage.RENDER_ATTACHMENT
7639
+ });
7640
+ this.renderPassDescriptor = {
7641
+ colorAttachments: [{
7642
+ // view is acquired and set in render loop.
7643
+ view: undefined,
7644
+ clearValue: {
7645
+ r: 0.5,
7646
+ g: 0.5,
7647
+ b: 0.5,
7648
+ a: 1.0
7649
+ },
7650
+ loadOp: 'load',
7651
+ storeOp: 'store'
7652
+ }],
7653
+ depthStencilAttachment: {
7654
+ view: depthTexture.createView(),
7655
+ depthClearValue: 1.0,
7656
+ depthLoadOp: 'clear',
7657
+ depthStoreOp: 'store',
7658
+ stencilClearValue: 0,
7659
+ stencilLoadOp: 'clear',
7660
+ stencilStoreOp: 'store'
7661
+ }
7662
+ };
7663
+ this.modelUniformBuffer = this.device.createBuffer({
7664
+ size: 4 * 16,
7665
+ // 4x4 matrix
7666
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
7667
+ });
7668
+ this.sceneUniformBuffer = this.device.createBuffer({
7669
+ // Two 4x4 viewProj matrices,
7670
+ // one for the camera and one for the light.
7671
+ // Then a vec3 for the light position.
7672
+ // Rounded to the nearest multiple of 16.
7673
+ size: 2 * 4 * 16 + 4 * 4,
7674
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
7675
+ });
7676
+ this.sceneBindGroupForShadow = this.device.createBindGroup({
7677
+ layout: this.uniformBufferBindGroupLayout,
7678
+ entries: [{
7679
+ binding: 0,
7680
+ resource: {
7681
+ buffer: this.sceneUniformBuffer
7682
+ }
7683
+ }]
7684
+ });
7685
+ this.sceneBindGroupForRender = this.device.createBindGroup({
7686
+ layout: this.bglForRender,
7687
+ entries: [{
7688
+ binding: 0,
7689
+ resource: {
7690
+ buffer: this.sceneUniformBuffer
7691
+ }
7692
+ }, {
7693
+ binding: 1,
7694
+ resource: this.shadowDepthTextureView
7695
+ }, {
7696
+ binding: 2,
7697
+ resource: this.device.createSampler({
7698
+ compare: 'less'
7699
+ })
7700
+ }, {
7701
+ binding: 3,
7702
+ resource: this.texture0.createView()
7703
+ }, {
7704
+ binding: 4,
7705
+ resource: this.sampler
7706
+ }]
7707
+ });
7708
+ this.modelBindGroup = this.device.createBindGroup({
7709
+ layout: this.uniformBufferBindGroupLayout,
7710
+ entries: [{
7711
+ binding: 0,
7712
+ resource: {
7713
+ buffer: this.modelUniformBuffer
7714
+ }
7715
+ }]
7716
+ });
7717
+
7718
+ // Rotates the camera around the origin based on time.
7719
+ this.getTransformationMatrix = pos => {
7720
+ const now = Date.now();
7721
+ const deltaTime = (now - this.lastFrameMS) / this.mainCameraParams.responseCoef;
7722
+ this.lastFrameMS = now;
7723
+
7724
+ // const this.viewMatrix = mat4.identity()
7725
+ const camera = this.cameras[this.mainCameraParams.type];
7726
+ this.viewMatrix = camera.update(deltaTime, this.inputHandler());
7727
+ _wgpuMatrix.mat4.translate(this.viewMatrix, _wgpuMatrix.vec3.fromValues(pos.x, pos.y, pos.z), this.viewMatrix);
7728
+ _wgpuMatrix.mat4.rotateX(this.viewMatrix, Math.PI * this.rotation.getRotX(), this.viewMatrix);
7729
+ _wgpuMatrix.mat4.rotateY(this.viewMatrix, Math.PI * this.rotation.getRotY(), this.viewMatrix);
7730
+ _wgpuMatrix.mat4.rotateZ(this.viewMatrix, Math.PI * this.rotation.getRotZ(), this.viewMatrix);
7731
+ _wgpuMatrix.mat4.multiply(this.projectionMatrix, this.viewMatrix, this.modelViewProjectionMatrix);
7732
+ return this.modelViewProjectionMatrix;
7733
+ };
7734
+ this.upVector = _wgpuMatrix.vec3.fromValues(0, 1, 0);
7735
+ this.origin = _wgpuMatrix.vec3.fromValues(0, 0, 0);
7736
+ const lightPosition = _wgpuMatrix.vec3.fromValues(50, 100, -100);
7737
+ const lightViewMatrix = _wgpuMatrix.mat4.lookAt(lightPosition, this.origin, this.upVector);
7738
+ const lightProjectionMatrix = _wgpuMatrix.mat4.create();
7739
+ {
7740
+ const left = -80;
7741
+ const right = 80;
7742
+ const bottom = -80;
7743
+ const top = 80;
7744
+ const near = -200;
7745
+ const far = 300;
7746
+ _wgpuMatrix.mat4.ortho(left, right, bottom, top, near, far, lightProjectionMatrix);
7747
+ }
7748
+ const lightViewProjMatrix = _wgpuMatrix.mat4.multiply(lightProjectionMatrix, lightViewMatrix);
7749
+
7750
+ // looks like affect on transformations for now const 0
7751
+ const modelMatrix = _wgpuMatrix.mat4.translation([0, 0, 0]);
7752
+ // The camera/light aren't moving, so write them into buffers now.
7753
+ {
7754
+ const lightMatrixData = lightViewProjMatrix; // as Float32Array;
7755
+ this.device.queue.writeBuffer(this.sceneUniformBuffer, 0, lightMatrixData.buffer, lightMatrixData.byteOffset, lightMatrixData.byteLength);
7756
+ const lightData = lightPosition;
7757
+ this.device.queue.writeBuffer(this.sceneUniformBuffer, 128, lightData.buffer, lightData.byteOffset, lightData.byteLength);
7758
+ const modelData = modelMatrix;
7759
+ this.device.queue.writeBuffer(this.modelUniformBuffer, 0, modelData.buffer, modelData.byteOffset, modelData.byteLength);
7760
+ }
7761
+ this.shadowPassDescriptor = {
7762
+ colorAttachments: [],
7763
+ depthStencilAttachment: {
7764
+ view: this.shadowDepthTextureView,
7765
+ depthClearValue: 1.0,
7766
+ depthLoadOp: 'clear',
7767
+ depthStoreOp: 'store'
7768
+ }
7769
+ };
7770
+ this.done = true;
7771
+ });
7772
+ }
7773
+ async loadTex0(texturesPaths, device) {
7774
+ this.sampler = device.createSampler({
7775
+ magFilter: 'linear',
7776
+ minFilter: 'linear'
7777
+ });
7778
+ return new Promise(async resolve => {
7779
+ const response = await fetch(texturesPaths[0]);
7780
+ const imageBitmap = await createImageBitmap(await response.blob());
7781
+ this.texture0 = device.createTexture({
7782
+ size: [imageBitmap.width, imageBitmap.height, 1],
7783
+ format: 'rgba8unorm',
7784
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
7785
+ });
7786
+ device.queue.copyExternalImageToTexture({
7787
+ source: imageBitmap
7788
+ }, {
7789
+ texture: this.texture0
7790
+ }, [imageBitmap.width, imageBitmap.height]);
7791
+ resolve();
7792
+ });
7793
+ }
7794
+ draw = commandEncoder => {
7795
+ if (this.done == false) return;
7796
+ const transformationMatrix = this.getTransformationMatrix(this.position);
7797
+ this.device.queue.writeBuffer(this.sceneUniformBuffer, 64, transformationMatrix.buffer, transformationMatrix.byteOffset, transformationMatrix.byteLength);
7798
+ this.renderPassDescriptor.colorAttachments[0].view = this.context.getCurrentTexture().createView();
7799
+ // {
7800
+ // const shadowPass = commandEncoder.beginRenderPass(this.shadowPassDescriptor);
7801
+ // shadowPass.setPipeline(this.shadowPipeline);
7802
+
7803
+ // shadowPass.end();
7804
+ // }
7805
+ // {
7806
+ // const renderPass = commandEncoder.beginRenderPass(this.renderPassDescriptor);
7807
+ // renderPass.setPipeline(this.pipeline);
7808
+
7809
+ // renderPass.end();
7810
+ // }
7811
+ };
7812
+ drawElements = renderPass => {
7813
+ renderPass.setBindGroup(0, this.sceneBindGroupForRender);
7814
+ renderPass.setBindGroup(1, this.modelBindGroup);
7815
+ renderPass.setVertexBuffer(0, this.vertexBuffer);
7816
+ renderPass.setVertexBuffer(1, this.vertexNormalsBuffer);
7817
+ renderPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
7818
+ renderPass.setIndexBuffer(this.indexBuffer, 'uint16');
7819
+ renderPass.drawIndexed(this.indexCount);
7820
+ };
7821
+ drawShadows = shadowPass => {
7822
+ shadowPass.setBindGroup(0, this.sceneBindGroupForShadow);
7823
+ shadowPass.setBindGroup(1, this.modelBindGroup);
7824
+ shadowPass.setVertexBuffer(0, this.vertexBuffer);
7825
+ shadowPass.setVertexBuffer(1, this.vertexNormalsBuffer);
7826
+ shadowPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
7827
+ shadowPass.setIndexBuffer(this.indexBuffer, 'uint16');
7828
+ shadowPass.drawIndexed(this.indexCount);
7829
+ };
7830
+ }
7831
+ exports.default = MEMeshObj;
7832
+
7833
+ },{"../shaders/fragment.wgsl":11,"../shaders/vertex.wgsl":13,"../shaders/vertexShadow.wgsl":14,"./engine":5,"./matrix-class":7,"wgpu-matrix":2}],9:[function(require,module,exports){
7834
+ "use strict";
7835
+
7836
+ Object.defineProperty(exports, "__esModule", {
7837
+ value: true
7838
+ });
7839
+ exports.ORBIT = ORBIT;
7840
+ exports.ORBIT_FROM_ARRAY = ORBIT_FROM_ARRAY;
7841
+ exports.OSCILLATOR = OSCILLATOR;
7842
+ exports.QueryString = void 0;
7843
+ exports.SWITCHER = SWITCHER;
7844
+ exports.byId = void 0;
7845
+ exports.createAppEvent = createAppEvent;
7846
+ exports.degToRad = degToRad;
7847
+ exports.getAxisRot = getAxisRot;
7848
+ exports.mat4 = void 0;
7849
+ exports.quaternion_rotation_matrix = quaternion_rotation_matrix;
7850
+ exports.radToDeg = radToDeg;
7851
+ exports.randomFloatFromTo = randomFloatFromTo;
7852
+ exports.randomIntFromTo = randomIntFromTo;
7853
+ exports.vec3 = exports.scriptManager = void 0;
7854
+ const vec3 = exports.vec3 = {
7855
+ cross(a, b, dst) {
7856
+ dst = dst || new Float32Array(3);
7857
+ const t0 = a[1] * b[2] - a[2] * b[1];
7858
+ const t1 = a[2] * b[0] - a[0] * b[2];
7859
+ const t2 = a[0] * b[1] - a[1] * b[0];
7860
+ dst[0] = t0;
7861
+ dst[1] = t1;
7862
+ dst[2] = t2;
7863
+ return dst;
7864
+ },
7865
+ subtract(a, b, dst) {
7866
+ dst = dst || new Float32Array(3);
7867
+ dst[0] = a[0] - b[0];
7868
+ dst[1] = a[1] - b[1];
7869
+ dst[2] = a[2] - b[2];
7870
+ return dst;
7871
+ },
7872
+ normalize(v, dst) {
7873
+ dst = dst || new Float32Array(3);
7874
+ const length = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
7875
+ // make sure we don't divide by 0.
7876
+ if (length > 0.00001) {
7877
+ dst[0] = v[0] / length;
7878
+ dst[1] = v[1] / length;
7879
+ dst[2] = v[2] / length;
7880
+ } else {
7881
+ dst[0] = 0;
7882
+ dst[1] = 0;
7883
+ dst[2] = 0;
7884
+ }
7885
+ return dst;
7886
+ }
7887
+ };
7888
+ const mat4 = exports.mat4 = {
7889
+ projection(width, height, depth, dst) {
7890
+ // Note: This matrix flips the Y axis so that 0 is at the top.
7891
+ return mat4.ortho(0, width, height, 0, depth, -depth, dst);
7892
+ },
7893
+ perspective(fieldOfViewYInRadians, aspect, zNear, zFar, dst) {
7894
+ dst = dst || new Float32Array(16);
7895
+ const f = Math.tan(Math.PI * 0.5 - 0.5 * fieldOfViewYInRadians);
7896
+ const rangeInv = 1 / (zNear - zFar);
7897
+ dst[0] = f / aspect;
7898
+ dst[1] = 0;
7899
+ dst[2] = 0;
7900
+ dst[3] = 0;
7901
+ dst[4] = 0;
7902
+ dst[5] = f;
7903
+ dst[6] = 0;
7904
+ dst[7] = 0;
7905
+ dst[8] = 0;
7906
+ dst[9] = 0;
7907
+ dst[10] = zFar * rangeInv;
7908
+ dst[11] = -1;
7909
+ dst[12] = 0;
7910
+ dst[13] = 0;
7911
+ dst[14] = zNear * zFar * rangeInv;
7912
+ dst[15] = 0;
7913
+ return dst;
7914
+ },
7915
+ ortho(left, right, bottom, top, near, far, dst) {
7916
+ dst = dst || new Float32Array(16);
7917
+ dst[0] = 2 / (right - left);
7918
+ dst[1] = 0;
7919
+ dst[2] = 0;
7920
+ dst[3] = 0;
7921
+ dst[4] = 0;
7922
+ dst[5] = 2 / (top - bottom);
7923
+ dst[6] = 0;
7924
+ dst[7] = 0;
7925
+ dst[8] = 0;
7926
+ dst[9] = 0;
7927
+ dst[10] = 1 / (near - far);
7928
+ dst[11] = 0;
7929
+ dst[12] = (right + left) / (left - right);
7930
+ dst[13] = (top + bottom) / (bottom - top);
7931
+ dst[14] = near / (near - far);
7932
+ dst[15] = 1;
7933
+ return dst;
7934
+ },
7935
+ identity(dst) {
7936
+ dst = dst || new Float32Array(16);
7937
+ dst[0] = 1;
7938
+ dst[1] = 0;
7939
+ dst[2] = 0;
7940
+ dst[3] = 0;
7941
+ dst[4] = 0;
7942
+ dst[5] = 1;
7943
+ dst[6] = 0;
7944
+ dst[7] = 0;
7945
+ dst[8] = 0;
7946
+ dst[9] = 0;
7947
+ dst[10] = 1;
7948
+ dst[11] = 0;
7949
+ dst[12] = 0;
7950
+ dst[13] = 0;
7951
+ dst[14] = 0;
7952
+ dst[15] = 1;
7953
+ return dst;
7954
+ },
7955
+ multiply(a, b, dst) {
7956
+ dst = dst || new Float32Array(16);
7957
+ const b00 = b[0 * 4 + 0];
7958
+ const b01 = b[0 * 4 + 1];
7959
+ const b02 = b[0 * 4 + 2];
7960
+ const b03 = b[0 * 4 + 3];
7961
+ const b10 = b[1 * 4 + 0];
7962
+ const b11 = b[1 * 4 + 1];
7963
+ const b12 = b[1 * 4 + 2];
7964
+ const b13 = b[1 * 4 + 3];
7965
+ const b20 = b[2 * 4 + 0];
7966
+ const b21 = b[2 * 4 + 1];
7967
+ const b22 = b[2 * 4 + 2];
7968
+ const b23 = b[2 * 4 + 3];
7969
+ const b30 = b[3 * 4 + 0];
7970
+ const b31 = b[3 * 4 + 1];
7971
+ const b32 = b[3 * 4 + 2];
7972
+ const b33 = b[3 * 4 + 3];
7973
+ const a00 = a[0 * 4 + 0];
7974
+ const a01 = a[0 * 4 + 1];
7975
+ const a02 = a[0 * 4 + 2];
7976
+ const a03 = a[0 * 4 + 3];
7977
+ const a10 = a[1 * 4 + 0];
7978
+ const a11 = a[1 * 4 + 1];
7979
+ const a12 = a[1 * 4 + 2];
7980
+ const a13 = a[1 * 4 + 3];
7981
+ const a20 = a[2 * 4 + 0];
7982
+ const a21 = a[2 * 4 + 1];
7983
+ const a22 = a[2 * 4 + 2];
7984
+ const a23 = a[2 * 4 + 3];
7985
+ const a30 = a[3 * 4 + 0];
7986
+ const a31 = a[3 * 4 + 1];
7987
+ const a32 = a[3 * 4 + 2];
7988
+ const a33 = a[3 * 4 + 3];
7989
+ dst[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30;
7990
+ dst[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31;
7991
+ dst[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32;
7992
+ dst[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33;
7993
+ dst[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30;
7994
+ dst[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31;
7995
+ dst[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32;
7996
+ dst[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33;
7997
+ dst[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30;
7998
+ dst[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31;
7999
+ dst[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32;
8000
+ dst[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33;
8001
+ dst[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30;
8002
+ dst[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31;
8003
+ dst[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32;
8004
+ dst[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33;
8005
+ return dst;
8006
+ },
8007
+ cameraAim(eye, target, up, dst) {
8008
+ dst = dst || new Float32Array(16);
8009
+ const zAxis = vec3.normalize(vec3.subtract(eye, target));
8010
+ const xAxis = vec3.normalize(vec3.cross(up, zAxis));
8011
+ const yAxis = vec3.normalize(vec3.cross(zAxis, xAxis));
8012
+ dst[0] = xAxis[0];
8013
+ dst[1] = xAxis[1];
8014
+ dst[2] = xAxis[2];
8015
+ dst[3] = 0;
8016
+ dst[4] = yAxis[0];
8017
+ dst[5] = yAxis[1];
8018
+ dst[6] = yAxis[2];
8019
+ dst[7] = 0;
8020
+ dst[8] = zAxis[0];
8021
+ dst[9] = zAxis[1];
8022
+ dst[10] = zAxis[2];
8023
+ dst[11] = 0;
8024
+ dst[12] = eye[0];
8025
+ dst[13] = eye[1];
8026
+ dst[14] = eye[2];
8027
+ dst[15] = 1;
8028
+ return dst;
8029
+ },
8030
+ inverse(m, dst) {
8031
+ dst = dst || new Float32Array(16);
8032
+ const m00 = m[0 * 4 + 0];
8033
+ const m01 = m[0 * 4 + 1];
8034
+ const m02 = m[0 * 4 + 2];
8035
+ const m03 = m[0 * 4 + 3];
8036
+ const m10 = m[1 * 4 + 0];
8037
+ const m11 = m[1 * 4 + 1];
8038
+ const m12 = m[1 * 4 + 2];
8039
+ const m13 = m[1 * 4 + 3];
8040
+ const m20 = m[2 * 4 + 0];
8041
+ const m21 = m[2 * 4 + 1];
8042
+ const m22 = m[2 * 4 + 2];
8043
+ const m23 = m[2 * 4 + 3];
8044
+ const m30 = m[3 * 4 + 0];
8045
+ const m31 = m[3 * 4 + 1];
8046
+ const m32 = m[3 * 4 + 2];
8047
+ const m33 = m[3 * 4 + 3];
8048
+ const tmp0 = m22 * m33;
8049
+ const tmp1 = m32 * m23;
8050
+ const tmp2 = m12 * m33;
8051
+ const tmp3 = m32 * m13;
8052
+ const tmp4 = m12 * m23;
8053
+ const tmp5 = m22 * m13;
8054
+ const tmp6 = m02 * m33;
8055
+ const tmp7 = m32 * m03;
8056
+ const tmp8 = m02 * m23;
8057
+ const tmp9 = m22 * m03;
8058
+ const tmp10 = m02 * m13;
8059
+ const tmp11 = m12 * m03;
8060
+ const tmp12 = m20 * m31;
8061
+ const tmp13 = m30 * m21;
8062
+ const tmp14 = m10 * m31;
8063
+ const tmp15 = m30 * m11;
8064
+ const tmp16 = m10 * m21;
8065
+ const tmp17 = m20 * m11;
8066
+ const tmp18 = m00 * m31;
8067
+ const tmp19 = m30 * m01;
8068
+ const tmp20 = m00 * m21;
8069
+ const tmp21 = m20 * m01;
8070
+ const tmp22 = m00 * m11;
8071
+ const tmp23 = m10 * m01;
8072
+ const t0 = tmp0 * m11 + tmp3 * m21 + tmp4 * m31 - (tmp1 * m11 + tmp2 * m21 + tmp5 * m31);
8073
+ const t1 = tmp1 * m01 + tmp6 * m21 + tmp9 * m31 - (tmp0 * m01 + tmp7 * m21 + tmp8 * m31);
8074
+ const t2 = tmp2 * m01 + tmp7 * m11 + tmp10 * m31 - (tmp3 * m01 + tmp6 * m11 + tmp11 * m31);
8075
+ const t3 = tmp5 * m01 + tmp8 * m11 + tmp11 * m21 - (tmp4 * m01 + tmp9 * m11 + tmp10 * m21);
8076
+ const d = 1 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);
8077
+ dst[0] = d * t0;
8078
+ dst[1] = d * t1;
8079
+ dst[2] = d * t2;
8080
+ dst[3] = d * t3;
8081
+ dst[4] = d * (tmp1 * m10 + tmp2 * m20 + tmp5 * m30 - (tmp0 * m10 + tmp3 * m20 + tmp4 * m30));
8082
+ dst[5] = d * (tmp0 * m00 + tmp7 * m20 + tmp8 * m30 - (tmp1 * m00 + tmp6 * m20 + tmp9 * m30));
8083
+ dst[6] = d * (tmp3 * m00 + tmp6 * m10 + tmp11 * m30 - (tmp2 * m00 + tmp7 * m10 + tmp10 * m30));
8084
+ dst[7] = d * (tmp4 * m00 + tmp9 * m10 + tmp10 * m20 - (tmp5 * m00 + tmp8 * m10 + tmp11 * m20));
8085
+ dst[8] = d * (tmp12 * m13 + tmp15 * m23 + tmp16 * m33 - (tmp13 * m13 + tmp14 * m23 + tmp17 * m33));
8086
+ dst[9] = d * (tmp13 * m03 + tmp18 * m23 + tmp21 * m33 - (tmp12 * m03 + tmp19 * m23 + tmp20 * m33));
8087
+ dst[10] = d * (tmp14 * m03 + tmp19 * m13 + tmp22 * m33 - (tmp15 * m03 + tmp18 * m13 + tmp23 * m33));
8088
+ dst[11] = d * (tmp17 * m03 + tmp20 * m13 + tmp23 * m23 - (tmp16 * m03 + tmp21 * m13 + tmp22 * m23));
8089
+ dst[12] = d * (tmp14 * m22 + tmp17 * m32 + tmp13 * m12 - (tmp16 * m32 + tmp12 * m12 + tmp15 * m22));
8090
+ dst[13] = d * (tmp20 * m32 + tmp12 * m02 + tmp19 * m22 - (tmp18 * m22 + tmp21 * m32 + tmp13 * m02));
8091
+ dst[14] = d * (tmp18 * m12 + tmp23 * m32 + tmp15 * m02 - (tmp22 * m32 + tmp14 * m02 + tmp19 * m12));
8092
+ dst[15] = d * (tmp22 * m22 + tmp16 * m02 + tmp21 * m12 - (tmp20 * m12 + tmp23 * m22 + tmp17 * m02));
8093
+ return dst;
8094
+ },
8095
+ lookAt(eye, target, up, dst) {
8096
+ return mat4.inverse(mat4.cameraAim(eye, target, up, dst), dst);
8097
+ },
8098
+ translation([tx, ty, tz], dst) {
8099
+ dst = dst || new Float32Array(16);
8100
+ dst[0] = 1;
8101
+ dst[1] = 0;
8102
+ dst[2] = 0;
8103
+ dst[3] = 0;
8104
+ dst[4] = 0;
8105
+ dst[5] = 1;
8106
+ dst[6] = 0;
8107
+ dst[7] = 0;
8108
+ dst[8] = 0;
8109
+ dst[9] = 0;
8110
+ dst[10] = 1;
8111
+ dst[11] = 0;
8112
+ dst[12] = tx;
8113
+ dst[13] = ty;
8114
+ dst[14] = tz;
8115
+ dst[15] = 1;
8116
+ return dst;
8117
+ },
8118
+ rotationX(angleInRadians, dst) {
8119
+ const c = Math.cos(angleInRadians);
8120
+ const s = Math.sin(angleInRadians);
8121
+ dst = dst || new Float32Array(16);
8122
+ dst[0] = 1;
8123
+ dst[1] = 0;
8124
+ dst[2] = 0;
8125
+ dst[3] = 0;
8126
+ dst[4] = 0;
8127
+ dst[5] = c;
8128
+ dst[6] = s;
8129
+ dst[7] = 0;
8130
+ dst[8] = 0;
8131
+ dst[9] = -s;
8132
+ dst[10] = c;
8133
+ dst[11] = 0;
8134
+ dst[12] = 0;
8135
+ dst[13] = 0;
8136
+ dst[14] = 0;
8137
+ dst[15] = 1;
8138
+ return dst;
8139
+ },
8140
+ rotationY(angleInRadians, dst) {
8141
+ const c = Math.cos(angleInRadians);
8142
+ const s = Math.sin(angleInRadians);
8143
+ dst = dst || new Float32Array(16);
8144
+ dst[0] = c;
8145
+ dst[1] = 0;
8146
+ dst[2] = -s;
8147
+ dst[3] = 0;
8148
+ dst[4] = 0;
8149
+ dst[5] = 1;
8150
+ dst[6] = 0;
8151
+ dst[7] = 0;
8152
+ dst[8] = s;
8153
+ dst[9] = 0;
8154
+ dst[10] = c;
8155
+ dst[11] = 0;
8156
+ dst[12] = 0;
8157
+ dst[13] = 0;
8158
+ dst[14] = 0;
8159
+ dst[15] = 1;
8160
+ return dst;
8161
+ },
8162
+ rotationZ(angleInRadians, dst) {
8163
+ const c = Math.cos(angleInRadians);
8164
+ const s = Math.sin(angleInRadians);
8165
+ dst = dst || new Float32Array(16);
8166
+ dst[0] = c;
8167
+ dst[1] = s;
8168
+ dst[2] = 0;
8169
+ dst[3] = 0;
8170
+ dst[4] = -s;
8171
+ dst[5] = c;
8172
+ dst[6] = 0;
8173
+ dst[7] = 0;
8174
+ dst[8] = 0;
8175
+ dst[9] = 0;
8176
+ dst[10] = 1;
8177
+ dst[11] = 0;
8178
+ dst[12] = 0;
8179
+ dst[13] = 0;
8180
+ dst[14] = 0;
8181
+ dst[15] = 1;
8182
+ return dst;
8183
+ },
8184
+ scaling([sx, sy, sz], dst) {
8185
+ dst = dst || new Float32Array(16);
8186
+ dst[0] = sx;
8187
+ dst[1] = 0;
8188
+ dst[2] = 0;
8189
+ dst[3] = 0;
8190
+ dst[4] = 0;
8191
+ dst[5] = sy;
8192
+ dst[6] = 0;
8193
+ dst[7] = 0;
8194
+ dst[8] = 0;
8195
+ dst[9] = 0;
8196
+ dst[10] = sz;
8197
+ dst[11] = 0;
8198
+ dst[12] = 0;
8199
+ dst[13] = 0;
8200
+ dst[14] = 0;
8201
+ dst[15] = 1;
8202
+ return dst;
8203
+ },
8204
+ translate(m, translation, dst) {
8205
+ return mat4.multiply(m, mat4.translation(translation), dst);
8206
+ },
8207
+ rotateX(m, angleInRadians, dst) {
8208
+ return mat4.multiply(m, mat4.rotationX(angleInRadians), dst);
8209
+ },
8210
+ rotateY(m, angleInRadians, dst) {
8211
+ return mat4.multiply(m, mat4.rotationY(angleInRadians), dst);
8212
+ },
8213
+ rotateZ(m, angleInRadians, dst) {
8214
+ return mat4.multiply(m, mat4.rotationZ(angleInRadians), dst);
8215
+ },
8216
+ scale(m, scale, dst) {
8217
+ return mat4.multiply(m, mat4.scaling(scale), dst);
8218
+ }
8219
+ };
8220
+ function degToRad(degrees) {
8221
+ return degrees * Math.PI / 180;
8222
+ }
8223
+ ;
8224
+ function radToDeg(r) {
8225
+ var pi = Math.PI;
8226
+ return r * (180 / pi);
8227
+ }
8228
+ ;
8229
+ function createAppEvent(name, myDetails) {
8230
+ return new CustomEvent(name, {
8231
+ detail: {
8232
+ eventName: name,
8233
+ data: myDetails
8234
+ },
8235
+ bubbles: true
8236
+ });
8237
+ }
8238
+
8239
+ /**
8240
+ * @description
8241
+ * Load script in runtime.
8242
+ */
8243
+ var scriptManager = exports.scriptManager = {
8244
+ SCRIPT_ID: 0,
8245
+ LOAD: function addScript(src, id, type, parent, callback) {
8246
+ var s = document.createElement('script');
8247
+ s.onload = function () {
8248
+ // console.log('Script id loaded [src]: ' + this.src);
8249
+ if (typeof callback != 'undefined') callback();
8250
+ };
8251
+ if (typeof type !== 'undefined') {
8252
+ s.setAttribute('type', type);
8253
+ s.innerHTML = src;
8254
+ } else {
8255
+ s.setAttribute('src', src);
8256
+ }
8257
+ if (typeof id !== 'undefined') {
8258
+ s.setAttribute('id', id);
8259
+ }
8260
+ if (typeof parent !== 'undefined') {
8261
+ document.getElementById(parent).appendChild(s);
8262
+ if (typeof callback != 'undefined') callback();
8263
+ } else {
8264
+ document.body.appendChild(s);
8265
+ }
8266
+ },
8267
+ loadModule: function addScript(src, id, type, parent) {
8268
+ console.log('Script id load called ');
8269
+ var s = document.createElement('script');
8270
+ s.onload = function () {
8271
+ scriptManager.SCRIPT_ID++;
8272
+ };
8273
+ if (typeof type === 'undefined') {
8274
+ s.setAttribute('type', 'module');
8275
+ s.setAttribute('src', src);
8276
+ } else {
8277
+ s.setAttribute('type', type);
8278
+ s.innerHTML = src;
8279
+ }
8280
+ s.setAttribute('src', src);
8281
+ if (typeof id !== 'undefined') {
8282
+ s.setAttribute('id', id);
8283
+ }
8284
+ if (typeof parent !== 'undefined') {
8285
+ document.getElementById(parent).appendChild(s);
8286
+ } else {
8287
+ document.body.appendChild(s);
8288
+ }
8289
+ },
8290
+ loadGLSL: function (src) {
8291
+ return new Promise(resolve => {
8292
+ fetch(src).then(data => {
8293
+ resolve(data.text());
8294
+ });
8295
+ });
8296
+ }
8297
+ };
8298
+
8299
+ // GET PULSE VALUES IN REAL TIME
8300
+ function OSCILLATOR(min, max, step) {
8301
+ if ((typeof min === 'string' || typeof min === 'number') && (typeof max === 'string' || typeof max === 'number') && (typeof step === 'string' || typeof step === 'number')) {
8302
+ var ROOT = this;
8303
+ this.min = parseFloat(min);
8304
+ this.max = parseFloat(max);
8305
+ this.step = parseFloat(step);
8306
+ this.value_ = parseFloat(min);
8307
+ this.status = 0;
8308
+ this.on_maximum_value = function () {};
8309
+ this.on_minimum_value = function () {};
8310
+ this.UPDATE = function (STATUS_) {
8311
+ if (STATUS_ === undefined) {
8312
+ if (this.status == 0 && this.value_ < this.max) {
8313
+ this.value_ = this.value_ + this.step;
8314
+ if (this.value_ >= this.max) {
8315
+ this.value_ = this.max;
8316
+ this.status = 1;
8317
+ ROOT.on_maximum_value();
8318
+ }
8319
+ return this.value_;
8320
+ } else if (this.status == 1 && this.value_ > this.min) {
8321
+ this.value_ = this.value_ - this.step;
8322
+ if (this.value_ <= this.min) {
8323
+ this.value_ = this.min;
8324
+ this.status = 0;
8325
+ ROOT.on_minimum_value();
8326
+ }
8327
+ return this.value_;
8328
+ }
8329
+ } else {
8330
+ return this.value_;
8331
+ }
8332
+ };
8333
+ } else {
8334
+ console.log("SYS : warning for procedure 'SYS.MATH.OSCILLATOR' Desciption : Replace object with string or number, min >> " + typeof min + ' and max >>' + typeof max + ' and step >>' + typeof step + ' << must be string or number.');
8335
+ }
8336
+ }
8337
+
8338
+ // this is class not func ecma5
8339
+ function SWITCHER() {
8340
+ var ROOT = this;
8341
+ ROOT.VALUE = 1;
8342
+ ROOT.GET = function () {
8343
+ ROOT.VALUE = ROOT.VALUE * -1;
8344
+ return ROOT.VALUE;
8345
+ };
8346
+ }
8347
+ function ORBIT(cx, cy, angle, p) {
8348
+ var s = Math.sin(angle);
8349
+ var c = Math.cos(angle);
8350
+ p.x -= cx;
8351
+ p.y -= cy;
8352
+ var xnew = p.x * c - p.y * s;
8353
+ var ynew = p.x * s + p.y * c;
8354
+ p.x = xnew + cx;
8355
+ p.y = ynew + cy;
8356
+ return p;
8357
+ }
8358
+ function ORBIT_FROM_ARRAY(cx, cy, angle, p, byIndexs) {
8359
+ var s = Math.sin(angle);
8360
+ var c = Math.cos(angle);
8361
+ p[byIndexs[0]] -= cx;
8362
+ p[byIndexs[1]] -= cy;
8363
+ var xnew = p[byIndexs[0]] * c - p[byIndexs[1]] * s;
8364
+ var ynew = p[byIndexs[0]] * s + p[byIndexs[1]] * c;
8365
+ p[byIndexs[0]] = xnew + cx;
8366
+ p[byIndexs[1]] = ynew + cy;
8367
+ return p;
8368
+ }
8369
+ var byId = function (id) {
8370
+ return document.getElementById(id);
8371
+ };
8372
+ exports.byId = byId;
8373
+ function randomFloatFromTo(min, max) {
8374
+ return Math.random() * (max - min) + min;
8375
+ }
8376
+ function randomIntFromTo(min, max) {
8377
+ if (typeof min === 'object' || typeof max === 'object') {
8378
+ console.log("SYS : warning Desciption : Replace object with string , this >> " + typeof min + ' and ' + typeof min + ' << must be string or number.');
8379
+ } else if (typeof min === 'undefined' || typeof max === 'undefined') {
8380
+ console.log("SYS : warning Desciption : arguments (min, max) cant be undefined , this >> " + typeof min + ' and ' + typeof min + ' << must be string or number.');
8381
+ } else {
8382
+ return Math.floor(Math.random() * (max - min + 1) + min);
8383
+ }
8384
+ }
8385
+ var QueryString = exports.QueryString = function () {
8386
+ var query_string = {};
8387
+ var query = window.location.search.substring(1);
8388
+ var vars = query.split('&');
8389
+ for (var i = 0; i < vars.length; i++) {
8390
+ var pair = vars[i].split('=');
8391
+ if (typeof query_string[pair[0]] === 'undefined') {
8392
+ query_string[pair[0]] = decodeURIComponent(pair[1]);
8393
+ } else if (typeof query_string[pair[0]] === 'string') {
8394
+ var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
8395
+ query_string[pair[0]] = arr;
8396
+ } else {
8397
+ query_string[pair[0]].push(decodeURIComponent(pair[1]));
8398
+ }
8399
+ }
8400
+ return query_string;
8401
+ }();
8402
+ function getAxisRot(q1) {
8403
+ var x, y, z;
8404
+
8405
+ // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
8406
+ if (q1.w > 1) q1.normalise();
8407
+ var angle = 2 * Math.acos(q1.w);
8408
+ // assuming quaternion normalised then w is less than 1, so term always positive.
8409
+ var s = Math.sqrt(1 - q1.w * q1.w);
8410
+ // test to avoid divide by zero, s is always positive due to sqrt
8411
+ if (s < 0.001) {
8412
+ // if s close to zero then direction of axis not important
8413
+ // if it is important that axis is normalised then replace with x=1; y=z=0;
8414
+ x = q1.x;
8415
+ y = q1.y;
8416
+ z = q1.z;
8417
+ } else {
8418
+ x = q1.x / s; // normalise axis
8419
+ y = q1.y / s;
8420
+ z = q1.z / s;
8421
+ }
8422
+ return [radToDeg(x), radToDeg(y), radToDeg(z)];
8423
+ }
8424
+
8425
+ // NTO TESTED
8426
+ function quaternion_rotation_matrix(Q) {
8427
+ // Covert a quaternion into a full three-dimensional rotation matrix.
8428
+
8429
+ // Input
8430
+ // :param Q: A 4 element array representing the quaternion (q0,q1,q2,q3)
8431
+
8432
+ // Output
8433
+ // :return: A 3x3 element matrix representing the full 3D rotation matrix.
8434
+ // This rotation matrix converts a point in the local reference
8435
+ // frame to a point in the global reference frame.
8436
+ // """
8437
+ // # Extract the values from Q
8438
+ var q0 = Q[0];
8439
+ var q1 = Q[1];
8440
+ var q2 = Q[2];
8441
+ var q3 = Q[3];
8442
+
8443
+ // # First row of the rotation matrix
8444
+ var r00 = 2 * (q0 * q0 + q1 * q1) - 1;
8445
+ var r01 = 2 * (q1 * q2 - q0 * q3);
8446
+ var r02 = 2 * (q1 * q3 + q0 * q2);
8447
+
8448
+ // # Second row of the rotation matrix
8449
+ var r10 = 2 * (q1 * q2 + q0 * q3);
8450
+ var r11 = 2 * (q0 * q0 + q2 * q2) - 1;
8451
+ var r12 = 2 * (q2 * q3 - q0 * q1);
8452
+
8453
+ // # Third row of the rotation matrix
8454
+ var r20 = 2 * (q1 * q3 - q0 * q2);
8455
+ var r21 = 2 * (q2 * q3 + q0 * q1);
8456
+ var r22 = 2 * (q0 * q0 + q3 * q3) - 1;
8457
+
8458
+ // # 3x3 rotation matrix
8459
+ var rot_matrix = [[r00, r01, r02], [r10, r11, r12], [r20, r21, r22]];
8460
+ return rot_matrix;
8461
+ }
8462
+
8463
+ },{}],10:[function(require,module,exports){
8464
+ "use strict";
8465
+
8466
+ Object.defineProperty(exports, "__esModule", {
8467
+ value: true
8468
+ });
8469
+ exports.default = void 0;
8470
+ var _wgpuMatrix = require("wgpu-matrix");
8471
+ var _utils = require("../engine/utils");
8472
+ class MatrixAmmo {
8473
+ constructor() {
8474
+ // THIS PATH IS PATH FROM PUBLIC FINAL FOLDER
8475
+ _utils.scriptManager.LOAD("./ammojs/ammo.js", "ammojs", undefined, undefined, this.init);
8476
+ }
8477
+ init = () => {
8478
+ // start
8479
+ Ammo().then(Ammo => {
8480
+ // Physics variables
8481
+ this.dynamicsWorld = null;
8482
+ this.rigidBodies = [];
8483
+ this.Ammo = Ammo;
8484
+ this.lastUpdate = 0;
8485
+ console.log("Ammo core loaded.");
8486
+ this.initPhysics();
8487
+ dispatchEvent(new CustomEvent('AmmoReady', {}));
8488
+ });
8489
+ };
8490
+ initPhysics() {
8491
+ let Ammo = this.Ammo;
8492
+
8493
+ // Physics configuration
8494
+ var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration(),
8495
+ dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration),
8496
+ overlappingPairCache = new Ammo.btDbvtBroadphase(),
8497
+ solver = new Ammo.btSequentialImpulseConstraintSolver();
8498
+ this.dynamicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);
8499
+ this.dynamicsWorld.setGravity(new Ammo.btVector3(0, -10, 0));
8500
+ var groundShape = new Ammo.btBoxShape(new Ammo.btVector3(50, 2, 50)),
8501
+ groundTransform = new Ammo.btTransform();
8502
+ groundTransform.setIdentity();
8503
+ groundTransform.setOrigin(new Ammo.btVector3(0, -1, 0));
8504
+ var mass = 0,
8505
+ isDynamic = mass !== 0,
8506
+ localInertia = new Ammo.btVector3(0, 0, 0);
8507
+ if (isDynamic) groundShape.calculateLocalInertia(mass, localInertia);
8508
+ var myMotionState = new Ammo.btDefaultMotionState(groundTransform),
8509
+ rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, myMotionState, groundShape, localInertia),
8510
+ body = new Ammo.btRigidBody(rbInfo);
8511
+ this.dynamicsWorld.addRigidBody(body);
8512
+ // this.rigidBodies.push(body);
8513
+ }
8514
+ addPhysics(MEObject, pOptions) {
8515
+ if (pOptions.geometry == "Sphere") {
8516
+ this.addPhysicsSphere(MEObject, pOptions);
8517
+ } else if (pOptions.geometry == "Cube") {
8518
+ //
8519
+ }
8520
+ }
8521
+ addPhysicsSphere(MEObject, pOptions) {
8522
+ let Ammo = this.Ammo;
8523
+ var colShape = new Ammo.btSphereShape(1),
8524
+ startTransform = new Ammo.btTransform();
8525
+ startTransform.setIdentity();
8526
+ var mass = 1;
8527
+ var localInertia = new Ammo.btVector3(0, 0, 0);
8528
+ colShape.calculateLocalInertia(mass, localInertia);
8529
+ startTransform.setOrigin(new Ammo.btVector3(0, 15, -10));
8530
+ var myMotionState = new Ammo.btDefaultMotionState(startTransform),
8531
+ rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia),
8532
+ body = new Ammo.btRigidBody(rbInfo);
8533
+ body.MEObject = MEObject;
8534
+ this.dynamicsWorld.addRigidBody(body);
8535
+ this.rigidBodies.push(body);
8536
+ return body;
8537
+ }
8538
+ updatePhysics() {
8539
+ // Step world
8540
+ this.dynamicsWorld.stepSimulation(1 / 60, 10);
8541
+ // Update rigid bodies
8542
+ var trans = new Ammo.btTransform();
8543
+ this.rigidBodies.forEach(function (body) {
8544
+ if (body.getMotionState()) {
8545
+ body.getMotionState().getWorldTransform(trans);
8546
+ var _x = trans.getOrigin().x().toFixed(2);
8547
+ var _y = trans.getOrigin().y().toFixed(2);
8548
+ var _z = trans.getOrigin().z().toFixed(2);
8549
+ body.MEObject.position.setPosition(_x, _y, _z);
8550
+ var test = trans.getRotation();
8551
+ // var testAxis = test.getAxis();
8552
+ // var testAngle = test.getAngle()
8553
+ // testAxis.x()
8554
+ // console.log("world axis X = " + testAxis.x());
8555
+ console.log("world axis X = " + test.x());
8556
+ console.log("world axis Y = " + test.y());
8557
+ console.log("world axis Z = " + test.z());
8558
+ console.log("world axis W = " + test.w());
8559
+ var bug = (0, _utils.getAxisRot)({
8560
+ x: test.x(),
8561
+ y: test.y(),
8562
+ z: test.z(),
8563
+ w: test.w()
8564
+ });
8565
+ console.log('bug:', bug);
8566
+ // transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w));
8567
+ }
8568
+ });
8569
+ }
8570
+ }
8571
+ exports.default = MatrixAmmo;
8572
+
8573
+ },{"../engine/utils":9,"wgpu-matrix":2}],11:[function(require,module,exports){
8574
+ "use strict";
8575
+
8576
+ Object.defineProperty(exports, "__esModule", {
8577
+ value: true
8578
+ });
8579
+ exports.fragmentWGSL = void 0;
8580
+ let fragmentWGSL = exports.fragmentWGSL = `override shadowDepthTextureSize: f32 = 1024.0;
8581
+
8582
+ struct Scene {
8583
+ lightViewProjMatrix : mat4x4f,
8584
+ cameraViewProjMatrix : mat4x4f,
8585
+ lightPos : vec3f,
8586
+ }
8587
+
8588
+ @group(0) @binding(0) var<uniform> scene : Scene;
8589
+ @group(0) @binding(1) var shadowMap: texture_depth_2d;
8590
+ @group(0) @binding(2) var shadowSampler: sampler_comparison;
8591
+ @group(0) @binding(3) var meshTexture: texture_2d<f32>;
8592
+ @group(0) @binding(4) var meshSampler: sampler;
8593
+
8594
+ struct FragmentInput {
8595
+ @location(0) shadowPos : vec3f,
8596
+ @location(1) fragPos : vec3f,
8597
+ @location(2) fragNorm : vec3f,
8598
+ @location(3) uv : vec2f,
8599
+ }
8600
+
8601
+ const albedo = vec3f(0.9);
8602
+ const ambientFactor = 0.2;
8603
+
8604
+ @fragment
8605
+ fn main(input : FragmentInput) -> @location(0) vec4f {
8606
+ // Percentage-closer filtering. Sample texels in the region
8607
+ // to smooth the result.
8608
+ var visibility = 0.0;
8609
+ let oneOverShadowDepthTextureSize = 1.0 / shadowDepthTextureSize;
8610
+ for (var y = -1; y <= 1; y++) {
8611
+ for (var x = -1; x <= 1; x++) {
8612
+ let offset = vec2f(vec2(x, y)) * oneOverShadowDepthTextureSize;
8613
+
8614
+ visibility += textureSampleCompare(
8615
+ shadowMap, shadowSampler,
8616
+ input.shadowPos.xy + offset, input.shadowPos.z - 0.007
8617
+ );
8618
+ }
8619
+ }
8620
+ visibility /= 9.0;
8621
+
8622
+ let lambertFactor = max(dot(normalize(scene.lightPos - input.fragPos), normalize(input.fragNorm)), 0.0);
8623
+ let lightingFactor = min(ambientFactor + visibility * lambertFactor, 1.0);
8624
+ let textureColor = textureSample(meshTexture, meshSampler, input.uv);
8625
+
8626
+ return vec4(textureColor.rgb * lightingFactor * albedo, 1.0);
8627
+ }`;
8628
+
8629
+ },{}],12:[function(require,module,exports){
8630
+ "use strict";
8631
+
8632
+ Object.defineProperty(exports, "__esModule", {
8633
+ value: true
8634
+ });
8635
+ exports.UNLIT_SHADER = void 0;
8636
+ /**
8637
+ * @description
8638
+ * UNIT Texures -
8639
+ * Good for performance
8640
+ */
8641
+ const UNLIT_SHADER = exports.UNLIT_SHADER = `struct Uniforms {
8642
+ viewProjectionMatrix : mat4x4f
8643
+ }
8644
+ @group(0) @binding(0) var<uniform> uniforms : Uniforms;
8645
+
8646
+ @group(1) @binding(0) var<uniform> modelMatrix : mat4x4f;
8647
+
8648
+ struct VertexInput {
8649
+ @location(0) position : vec4f,
8650
+ @location(1) normal : vec3f,
8651
+ @location(2) uv : vec2f
8652
+ }
8653
+
8654
+ struct VertexOutput {
8655
+ @builtin(position) position : vec4f,
8656
+ @location(0) normal: vec3f,
8657
+ @location(1) uv : vec2f,
8658
+ }
8659
+
8660
+ @vertex
8661
+ fn vertexMain(input: VertexInput) -> VertexOutput {
8662
+ var output : VertexOutput;
8663
+ output.position = uniforms.viewProjectionMatrix * modelMatrix * input.position;
8664
+ output.normal = normalize((modelMatrix * vec4(input.normal, 0)).xyz);
8665
+ output.uv = input.uv;
8666
+ return output;
8667
+ }
8668
+
8669
+ @group(1) @binding(1) var meshSampler: sampler;
8670
+ @group(1) @binding(2) var meshTexture: texture_2d<f32>;
8671
+
8672
+ // Static directional lighting
8673
+ const lightDir = vec3f(1, 1, 1);
8674
+ const dirColor = vec3(1);
8675
+ const ambientColor = vec3f(0.05);
8676
+
8677
+ @fragment
8678
+ fn fragmentMain(input: VertexOutput) -> @location(0) vec4f {
8679
+ let textureColor = textureSample(meshTexture, meshSampler, input.uv);
8680
+
8681
+ // Very simplified lighting algorithm.
8682
+ let lightColor = saturate(ambientColor + max(dot(input.normal, lightDir), 0.0) * dirColor);
8683
+
8684
+ return vec4f(textureColor.rgb * lightColor, textureColor.a);
8685
+ }`;
8686
+
8687
+ },{}],13:[function(require,module,exports){
8688
+ "use strict";
8689
+
8690
+ Object.defineProperty(exports, "__esModule", {
8691
+ value: true
8692
+ });
8693
+ exports.vertexWGSL = void 0;
8694
+ let vertexWGSL = exports.vertexWGSL = `struct Scene {
8695
+ lightViewProjMatrix: mat4x4f,
8696
+ cameraViewProjMatrix: mat4x4f,
8697
+ lightPos: vec3f,
8698
+ }
8699
+
8700
+ struct Model {
8701
+ modelMatrix: mat4x4f,
8702
+ }
8703
+
8704
+ @group(0) @binding(0) var<uniform> scene : Scene;
8705
+ @group(1) @binding(0) var<uniform> model : Model;
8706
+
8707
+ struct VertexOutput {
8708
+ @location(0) shadowPos: vec3f,
8709
+ @location(1) fragPos: vec3f,
8710
+ @location(2) fragNorm: vec3f,
8711
+ @location(3) uv : vec2f,
8712
+
8713
+ @builtin(position) Position: vec4f,
8714
+ }
8715
+
8716
+ @vertex
8717
+ fn main(
8718
+ @location(0) position: vec3f,
8719
+ @location(1) normal: vec3f,
8720
+ @location(2) uv : vec2f
8721
+ ) -> VertexOutput {
8722
+ var output : VertexOutput;
8723
+
8724
+ // XY is in (-1, 1) space, Z is in (0, 1) space
8725
+ let posFromLight = scene.lightViewProjMatrix * model.modelMatrix * vec4(position, 1.0);
8726
+
8727
+ // Convert XY to (0, 1)
8728
+ // Y is flipped because texture coords are Y-down.
8729
+ output.shadowPos = vec3(
8730
+ posFromLight.xy * vec2(0.5, -0.5) + vec2(0.5),
8731
+ posFromLight.z
8732
+ );
8733
+
8734
+ output.Position = scene.cameraViewProjMatrix * model.modelMatrix * vec4(position, 1.0);
8735
+ output.fragPos = output.Position.xyz;
8736
+ output.fragNorm = normal;
8737
+ // nidza
8738
+ output.uv = uv;
8739
+
8740
+ return output;
8741
+ }
8742
+ `;
8743
+
8744
+ },{}],14:[function(require,module,exports){
8745
+ "use strict";
8746
+
8747
+ Object.defineProperty(exports, "__esModule", {
8748
+ value: true
8749
+ });
8750
+ exports.vertexShadowWGSL = void 0;
8751
+ let vertexShadowWGSL = exports.vertexShadowWGSL = `struct Scene {
8752
+ lightViewProjMatrix: mat4x4f,
8753
+ cameraViewProjMatrix: mat4x4f,
8754
+ lightPos: vec3f,
8755
+ }
8756
+
8757
+ struct Model {
8758
+ modelMatrix: mat4x4f,
8759
+ }
8760
+
8761
+ @group(0) @binding(0) var<uniform> scene : Scene;
8762
+ @group(1) @binding(0) var<uniform> model : Model;
8763
+
8764
+ @vertex
8765
+ fn main(
8766
+ @location(0) position: vec3f
8767
+ ) -> @builtin(position) vec4f {
8768
+ return scene.lightViewProjMatrix * model.modelMatrix * vec4(position, 1.0);
8769
+ }
8770
+ `;
8771
+
8772
+ },{}],15:[function(require,module,exports){
8773
+ "use strict";
8774
+
8775
+ Object.defineProperty(exports, "__esModule", {
8776
+ value: true
8777
+ });
8778
+ exports.default = void 0;
8779
+ var _wgpuMatrix = require("wgpu-matrix");
8780
+ var _ball = _interopRequireDefault(require("./engine/ball.js"));
8781
+ var _cube = _interopRequireDefault(require("./engine/cube.js"));
8782
+ var _engine = require("./engine/engine.js");
8783
+ var _meshObj = _interopRequireDefault(require("./engine/mesh-obj.js"));
8784
+ var _matrixAmmo = _interopRequireDefault(require("./physics/matrix-ammo.js"));
8785
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
8786
+ // import {scriptManager} from "./engine/utils.js";
8787
+
8788
+ class MatrixEngineWGPU {
8789
+ mainRenderBundle = [];
8790
+ rbContainer = [];
8791
+ frame = () => {};
8792
+ entityHolder = [];
8793
+ entityArgPass = {
8794
+ loadOp: 'clear',
8795
+ storeOp: 'store',
8796
+ depthLoadOp: 'clear',
8797
+ depthStoreOp: 'store'
8798
+ };
8799
+ matrixAmmo = new _matrixAmmo.default();
8800
+ constructor(options, callback) {
8801
+ // console.log('typeof options ', typeof options )
8802
+ if (typeof options == 'undefined' || typeof options == "function") {
8803
+ this.options = {
8804
+ useSingleRenderPass: true,
8805
+ canvasSize: 'fullscreen',
8806
+ mainCameraParams: {
8807
+ type: 'WASD',
8808
+ responseCoef: 2000
8809
+ }
8810
+ };
8811
+ callback = options;
8812
+ }
8813
+ if (typeof options.mainCameraParams === 'undefined') {
8814
+ options.mainCameraParams = {
8815
+ type: 'WASD',
8816
+ responseCoef: 2000
8817
+ };
6400
8818
  }
6401
8819
  this.options = options;
8820
+ this.mainCameraParams = options.mainCameraParams;
6402
8821
  var canvas = document.createElement('canvas');
6403
- canvas.width = window.innerWidth;
6404
- canvas.height = window.innerHeight;
8822
+ if (this.options.canvasSize == 'fullscreen') {
8823
+ canvas.width = window.innerWidth;
8824
+ canvas.height = window.innerHeight;
8825
+ } else {
8826
+ canvas.width = this.options.canvasSize.w;
8827
+ canvas.height = this.options.canvasSize.h;
8828
+ }
6405
8829
  document.body.append(canvas);
8830
+ const initialCameraPosition = _wgpuMatrix.vec3.create(0, 0, 0);
8831
+ this.mainCameraParams = {
8832
+ type: this.options.mainCameraParams.type,
8833
+ responseCoef: this.options.mainCameraParams.responseCoef
8834
+ };
8835
+ this.cameras = {
8836
+ arcball: new _engine.ArcballCamera({
8837
+ position: initialCameraPosition
8838
+ }),
8839
+ WASD: new _engine.WASDCamera({
8840
+ position: initialCameraPosition
8841
+ })
8842
+ };
6406
8843
  this.init({
6407
8844
  canvas,
6408
8845
  callback
@@ -6430,7 +8867,7 @@ class MatrixEngineWGPU {
6430
8867
  this.frame = this.frameSinglePass;
6431
8868
  } else {
6432
8869
  // must be
6433
- this.frame = this.framePassPerObject;
8870
+ this.frame = this.frameSinglePass;
6434
8871
  }
6435
8872
  this.run(callback);
6436
8873
  };
@@ -6463,6 +8900,7 @@ class MatrixEngineWGPU {
6463
8900
  addCube = o => {
6464
8901
  if (typeof o === 'undefined') {
6465
8902
  var o = {
8903
+ scale: 1,
6466
8904
  position: {
6467
8905
  x: 0,
6468
8906
  y: 0,
@@ -6479,7 +8917,9 @@ class MatrixEngineWGPU {
6479
8917
  y: 0,
6480
8918
  z: 0
6481
8919
  },
6482
- entityArgPass: this.entityArgPass
8920
+ entityArgPass: this.entityArgPass,
8921
+ cameras: this.cameras,
8922
+ mainCameraParams: this.mainCameraParams
6483
8923
  };
6484
8924
  } else {
6485
8925
  if (typeof o.position === 'undefined') {
@@ -6506,7 +8946,14 @@ class MatrixEngineWGPU {
6506
8946
  if (typeof o.texturesPaths === 'undefined') {
6507
8947
  o.texturesPaths = ['./res/textures/default.png'];
6508
8948
  }
8949
+ if (typeof o.scale === 'undefined') {
8950
+ o.scale = 1;
8951
+ }
8952
+ if (typeof o.mainCameraParams === 'undefined') {
8953
+ o.mainCameraParams = this.mainCameraParams;
8954
+ }
6509
8955
  o.entityArgPass = this.entityArgPass;
8956
+ o.cameras = this.cameras;
6510
8957
  }
6511
8958
  let myCube1 = new _cube.default(this.canvas, this.device, this.context, o);
6512
8959
  this.mainRenderBundle.push(myCube1);
@@ -6514,6 +8961,7 @@ class MatrixEngineWGPU {
6514
8961
  addBall = o => {
6515
8962
  if (typeof o === 'undefined') {
6516
8963
  var o = {
8964
+ scale: 1,
6517
8965
  position: {
6518
8966
  x: 0,
6519
8967
  y: 0,
@@ -6530,7 +8978,9 @@ class MatrixEngineWGPU {
6530
8978
  y: 0,
6531
8979
  z: 0
6532
8980
  },
6533
- entityArgPass: this.entityArgPass
8981
+ entityArgPass: this.entityArgPass,
8982
+ cameras: this.cameras,
8983
+ mainCameraParams: this.mainCameraParams
6534
8984
  };
6535
8985
  } else {
6536
8986
  if (typeof o.position === 'undefined') {
@@ -6557,227 +9007,112 @@ class MatrixEngineWGPU {
6557
9007
  if (typeof o.texturesPaths === 'undefined') {
6558
9008
  o.texturesPaths = ['./res/textures/default.png'];
6559
9009
  }
9010
+ if (typeof o.mainCameraParams === 'undefined') {
9011
+ o.mainCameraParams = this.mainCameraParams;
9012
+ }
9013
+ if (typeof o.scale === 'undefined') {
9014
+ o.scale = 1;
9015
+ }
6560
9016
  o.entityArgPass = this.entityArgPass;
9017
+ o.cameras = this.cameras;
6561
9018
  }
6562
9019
  let myBall1 = new _ball.default(this.canvas, this.device, this.context, o);
6563
9020
  this.mainRenderBundle.push(myBall1);
6564
9021
  };
9022
+ addMeshObj = o => {
9023
+ if (typeof o.position === 'undefined') {
9024
+ o.position = {
9025
+ x: 0,
9026
+ y: 0,
9027
+ z: -4
9028
+ };
9029
+ }
9030
+ if (typeof o.rotation === 'undefined') {
9031
+ o.rotation = {
9032
+ x: 0,
9033
+ y: 0,
9034
+ z: 0
9035
+ };
9036
+ }
9037
+ if (typeof o.rotationSpeed === 'undefined') {
9038
+ o.rotationSpeed = {
9039
+ x: 0,
9040
+ y: 0,
9041
+ z: 0
9042
+ };
9043
+ }
9044
+ if (typeof o.texturesPaths === 'undefined') {
9045
+ o.texturesPaths = ['./res/textures/default.png'];
9046
+ }
9047
+ if (typeof o.mainCameraParams === 'undefined') {
9048
+ o.mainCameraParams = this.mainCameraParams;
9049
+ }
9050
+ if (typeof o.scale === 'undefined') {
9051
+ o.scale = 1;
9052
+ }
9053
+ o.entityArgPass = this.entityArgPass;
9054
+ o.cameras = this.cameras;
9055
+ if (typeof o.name === 'undefined') {
9056
+ o.name = 'random' + Math.random();
9057
+ }
9058
+ if (typeof o.mesh === 'undefined') {
9059
+ throw console.error('arg mesh is empty...');
9060
+ return;
9061
+ }
9062
+ if (typeof o.physics === 'undefined') {
9063
+ o.physics = {
9064
+ enabled: false,
9065
+ geometry: "Sphere"
9066
+ };
9067
+ }
9068
+ if (typeof o.physics.enabled === 'undefined') {
9069
+ o.physics.enabled = false;
9070
+ }
9071
+ if (typeof o.physics.geometry === 'undefined') {
9072
+ o.physics.geometry = "Sphere";
9073
+ }
9074
+ // console.log('Mesh procedure', o)
9075
+ let myMesh1 = new _meshObj.default(this.canvas, this.device, this.context, o);
9076
+ if (o.physics.enabled == true) {
9077
+ this.matrixAmmo.addPhysics(myMesh1, o.physics);
9078
+ }
9079
+ this.mainRenderBundle.push(myMesh1);
9080
+ };
6565
9081
  run(callback) {
6566
9082
  setTimeout(() => {
6567
9083
  requestAnimationFrame(this.frame);
6568
- }, 1000);
9084
+ }, 30);
6569
9085
  setTimeout(() => {
6570
9086
  callback();
6571
- }, 10);
9087
+ }, 20);
6572
9088
  }
6573
9089
  frameSinglePass = () => {
6574
- console.log('single');
9090
+ if (typeof this.mainRenderBundle == 'undefined') return;
9091
+ let shadowPass = null;
9092
+ let renderPass;
6575
9093
  let commandEncoder = this.device.createCommandEncoder();
6576
- this.rbContainer = [];
6577
- let passEncoder;
6578
9094
  this.mainRenderBundle.forEach((meItem, index) => {
6579
- meItem.draw();
6580
- this.rbContainer.push(meItem.renderBundle);
6581
- // if(index == 0) passEncoder = commandEncoder.beginRenderPass(meItem.renderPassDescriptor);
9095
+ meItem.position.update();
9096
+ });
9097
+ this.mainRenderBundle.forEach((meItem, index) => {
9098
+ meItem.draw(commandEncoder);
9099
+ shadowPass = commandEncoder.beginRenderPass(meItem.shadowPassDescriptor);
9100
+ shadowPass.setPipeline(meItem.shadowPipeline);
9101
+ meItem.drawShadows(shadowPass);
9102
+ shadowPass.end();
9103
+ });
9104
+ this.mainRenderBundle.forEach((meItem, index) => {
9105
+ if (index == 0) renderPass = commandEncoder.beginRenderPass(meItem.renderPassDescriptor);
9106
+ if (index == 1) renderPass.setPipeline(meItem.pipeline);
6582
9107
  });
6583
- this.renderPassDescriptor.colorAttachments[0].view = this.context.getCurrentTexture().createView();
6584
- passEncoder = commandEncoder.beginRenderPass(this.renderPassDescriptor);
6585
- passEncoder.executeBundles(this.rbContainer);
6586
- passEncoder.end();
6587
- this.device.queue.submit([commandEncoder.finish()]);
6588
- requestAnimationFrame(this.frame);
6589
- };
6590
- framePassPerObject = () => {
6591
- console.log('framePassPerObject');
6592
- let commandEncoder = this.device.createCommandEncoder();
6593
- this.rbContainer = [];
6594
- let passEncoder;
6595
9108
  this.mainRenderBundle.forEach((meItem, index) => {
6596
- meItem.draw();
6597
- this.rbContainer.push(meItem.renderBundle);
6598
- passEncoder = commandEncoder.beginRenderPass(meItem.renderPassDescriptor);
6599
- passEncoder.executeBundles(this.rbContainer);
6600
- passEncoder.end();
9109
+ meItem.drawElements(renderPass);
6601
9110
  });
9111
+ renderPass.end();
6602
9112
  this.device.queue.submit([commandEncoder.finish()]);
6603
9113
  requestAnimationFrame(this.frame);
6604
9114
  };
6605
9115
  }
6606
9116
  exports.default = MatrixEngineWGPU;
6607
9117
 
6608
- },{"./engine/ball.js":3,"./engine/cube.js":4}],7:[function(require,module,exports){
6609
- "use strict";
6610
-
6611
- Object.defineProperty(exports, "__esModule", {
6612
- value: true
6613
- });
6614
- exports.vertexPositionColorWGSL = exports.shaderSrc = exports.cubeTexShader = exports.basicVertWGSL = exports.basicFragWGSL = exports.BALL_SHADER = void 0;
6615
- /**
6616
- * @description
6617
- * For microdraw pixel cube texture
6618
- */
6619
- const shaderSrc = exports.shaderSrc = `struct VSUniforms {
6620
- worldViewProjection: mat4x4f,
6621
- worldInverseTranspose: mat4x4f,
6622
- };
6623
- @group(0) @binding(0) var<uniform> vsUniforms: VSUniforms;
6624
-
6625
- struct MyVSInput {
6626
- @location(0) position: vec4f,
6627
- @location(1) normal: vec3f,
6628
- @location(2) texcoord: vec2f,
6629
- };
6630
-
6631
- struct MyVSOutput {
6632
- @builtin(position) position: vec4f,
6633
- @location(0) normal: vec3f,
6634
- @location(1) texcoord: vec2f,
6635
- };
6636
-
6637
- @vertex
6638
- fn myVSMain(v: MyVSInput) -> MyVSOutput {
6639
- var vsOut: MyVSOutput;
6640
- vsOut.position = vsUniforms.worldViewProjection * v.position;
6641
- vsOut.normal = (vsUniforms.worldInverseTranspose * vec4f(v.normal, 0.0)).xyz;
6642
- vsOut.texcoord = v.texcoord;
6643
- return vsOut;
6644
- }
6645
-
6646
- struct FSUniforms {
6647
- lightDirection: vec3f,
6648
- };
6649
-
6650
- @group(0) @binding(1) var<uniform> fsUniforms: FSUniforms;
6651
- @group(0) @binding(2) var diffuseSampler: sampler;
6652
- @group(0) @binding(3) var diffuseTexture: texture_2d<f32>;
6653
-
6654
- @fragment
6655
- fn myFSMain(v: MyVSOutput) -> @location(0) vec4f {
6656
- var diffuseColor = textureSample(diffuseTexture, diffuseSampler, v.texcoord);
6657
- var a_normal = normalize(v.normal);
6658
- var l = dot(a_normal, fsUniforms.lightDirection) * 0.5 + 0.5;
6659
- return vec4f(diffuseColor.rgb * l, diffuseColor.a);
6660
- }
6661
- `;
6662
-
6663
- /**
6664
- * @description
6665
- * For Cube with images
6666
- */
6667
- const cubeTexShader = exports.cubeTexShader = `struct Uniforms {
6668
- matrix: mat4x4f,
6669
- };
6670
-
6671
- struct Vertex {
6672
- @location(0) position: vec4f,
6673
- @location(1) texcoord: vec2f,
6674
- };
6675
-
6676
- struct VSOutput {
6677
- @builtin(position) position: vec4f,
6678
- @location(0) texcoord: vec2f,
6679
- };
6680
-
6681
- @group(0) @binding(0) var<uniform> uni: Uniforms;
6682
- @group(0) @binding(1) var ourSampler: sampler;
6683
- @group(0) @binding(2) var ourTexture: texture_2d<f32>;
6684
-
6685
- @vertex fn vs(vert: Vertex) -> VSOutput {
6686
- var vsOut: VSOutput;
6687
- vsOut.position = uni.matrix * vert.position;
6688
- vsOut.texcoord = vert.texcoord;
6689
- return vsOut;
6690
- }
6691
-
6692
- @fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
6693
- return textureSample(ourTexture, ourSampler, vsOut.texcoord);
6694
- }
6695
- `;
6696
- const basicVertWGSL = exports.basicVertWGSL = `struct Uniforms {
6697
- modelViewProjectionMatrix : mat4x4<f32>,
6698
- }
6699
- @binding(0) @group(0) var<uniform> uniforms : Uniforms;
6700
-
6701
- struct VertexOutput {
6702
- @builtin(position) Position : vec4<f32>,
6703
- @location(0) fragUV : vec2<f32>,
6704
- @location(1) fragPosition: vec4<f32>,
6705
- }
6706
-
6707
- @vertex
6708
- fn main(
6709
- @location(0) position : vec4<f32>,
6710
- @location(1) uv : vec2<f32>
6711
- ) -> VertexOutput {
6712
- var output : VertexOutput;
6713
- output.Position = uniforms.modelViewProjectionMatrix * position;
6714
- output.fragUV = uv;
6715
- output.fragPosition = 0.5 * (position + vec4(1.0, 1.0, 1.0, 1.0));
6716
- return output;
6717
- }
6718
- `;
6719
- const basicFragWGSL = exports.basicFragWGSL = `@group(0) @binding(1) var mySampler: sampler;
6720
- @group(0) @binding(2) var myTexture: texture_2d<f32>;
6721
-
6722
- @fragment
6723
- fn main(
6724
- @location(0) fragUV: vec2<f32>,
6725
- @location(1) fragPosition: vec4<f32>
6726
- ) -> @location(0) vec4<f32> {
6727
- return textureSample(myTexture, mySampler, fragUV) * fragPosition;
6728
- }
6729
- `;
6730
- const vertexPositionColorWGSL = exports.vertexPositionColorWGSL = `@fragment
6731
- fn main(
6732
- @location(0) fragUV: vec2<f32>,
6733
- @location(1) fragPosition: vec4<f32>
6734
- ) -> @location(0) vec4<f32> {
6735
- return fragPosition;
6736
- }`;
6737
- const BALL_SHADER = exports.BALL_SHADER = `struct Uniforms {
6738
- viewProjectionMatrix : mat4x4f
6739
- }
6740
- @group(0) @binding(0) var<uniform> uniforms : Uniforms;
6741
-
6742
- @group(1) @binding(0) var<uniform> modelMatrix : mat4x4f;
6743
-
6744
- struct VertexInput {
6745
- @location(0) position : vec4f,
6746
- @location(1) normal : vec3f,
6747
- @location(2) uv : vec2f
6748
- }
6749
-
6750
- struct VertexOutput {
6751
- @builtin(position) position : vec4f,
6752
- @location(0) normal: vec3f,
6753
- @location(1) uv : vec2f,
6754
- }
6755
-
6756
- @vertex
6757
- fn vertexMain(input: VertexInput) -> VertexOutput {
6758
- var output : VertexOutput;
6759
- output.position = uniforms.viewProjectionMatrix * modelMatrix * input.position;
6760
- output.normal = normalize((modelMatrix * vec4(input.normal, 0)).xyz);
6761
- output.uv = input.uv;
6762
- return output;
6763
- }
6764
-
6765
- @group(1) @binding(1) var meshSampler: sampler;
6766
- @group(1) @binding(2) var meshTexture: texture_2d<f32>;
6767
-
6768
- // Static directional lighting
6769
- const lightDir = vec3f(1, 1, 1);
6770
- const dirColor = vec3(1);
6771
- const ambientColor = vec3f(0.05);
6772
-
6773
- @fragment
6774
- fn fragmentMain(input: VertexOutput) -> @location(0) vec4f {
6775
- let textureColor = textureSample(meshTexture, meshSampler, input.uv);
6776
-
6777
- // Very simplified lighting algorithm.
6778
- let lightColor = saturate(ambientColor + max(dot(input.normal, lightDir), 0.0) * dirColor);
6779
-
6780
- return vec4f(textureColor.rgb * lightColor, textureColor.a);
6781
- }`;
6782
-
6783
- },{}]},{},[1]);
9118
+ },{"./engine/ball.js":3,"./engine/cube.js":4,"./engine/engine.js":5,"./engine/mesh-obj.js":8,"./physics/matrix-ammo.js":10,"wgpu-matrix":2}]},{},[1]);