@xeokit/xeokit-sdk 2.6.91 → 2.6.93

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 (184) hide show
  1. package/dist/xeokit-sdk.cjs.js +13128 -44669
  2. package/dist/xeokit-sdk.es.js +13129 -44668
  3. package/dist/xeokit-sdk.es5.js +1414 -3498
  4. package/dist/xeokit-sdk.min.cjs.js +8 -8
  5. package/dist/xeokit-sdk.min.es.js +8 -8
  6. package/dist/xeokit-sdk.min.es5.js +7 -7
  7. package/package.json +1 -1
  8. package/src/plugins/AngleMeasurementsPlugin/AngleMeasurement.js +21 -1
  9. package/src/plugins/DistanceMeasurementsPlugin/DistanceMeasurement.js +32 -6
  10. package/src/viewer/Viewer.js +55 -103
  11. package/src/viewer/scene/canvas/Canvas.js +3 -43
  12. package/src/viewer/scene/geometry/ReadableGeometry.js +0 -25
  13. package/src/viewer/scene/lights/CubeTexture.js +0 -13
  14. package/src/viewer/scene/lights/DirLight.js +2 -1
  15. package/src/viewer/scene/lights/PointLight.js +2 -1
  16. package/src/viewer/scene/materials/Texture.js +0 -9
  17. package/src/viewer/scene/math/rtcCoords.js +1 -38
  18. package/src/viewer/scene/mesh/Mesh.js +454 -212
  19. package/src/viewer/scene/mesh/draw/DrawShaderSource.js +305 -1504
  20. package/src/viewer/scene/mesh/draw/LambertShaderSource.js +35 -0
  21. package/src/viewer/scene/mesh/emphasis/EmphasisShaderSource.js +34 -0
  22. package/src/viewer/scene/mesh/occlusion/OcclusionShaderSource.js +9 -158
  23. package/src/viewer/scene/mesh/pick/PickMeshShaderSource.js +21 -151
  24. package/src/viewer/scene/mesh/pick/PickTriangleShaderSource.js +12 -124
  25. package/src/viewer/scene/mesh/shadow/ShadowShaderSource.js +22 -97
  26. package/src/viewer/scene/model/SceneModel.js +248 -852
  27. package/src/viewer/scene/model/SceneModelEntity.js +4 -4
  28. package/src/viewer/scene/model/SceneModelMesh.js +3 -3
  29. package/src/viewer/scene/model/layer/DTXLayer.js +940 -0
  30. package/src/viewer/scene/model/layer/Layer.js +788 -0
  31. package/src/viewer/scene/model/layer/VBOLayer.js +1019 -0
  32. package/src/viewer/scene/model/layer/programs/ColorProgram.js +35 -0
  33. package/src/viewer/scene/model/layer/programs/ColorTextureProgram.js +46 -0
  34. package/src/viewer/scene/model/layer/programs/DepthProgram.js +11 -0
  35. package/src/viewer/scene/model/layer/programs/EdgesProgram.js +12 -0
  36. package/src/viewer/scene/model/layer/programs/FlatColorProgram.js +24 -0
  37. package/src/viewer/scene/model/layer/programs/OcclusionProgram.js +12 -0
  38. package/src/viewer/scene/model/layer/programs/PBRProgram.js +180 -0
  39. package/src/viewer/scene/model/layer/programs/PickDepthProgram.js +30 -0
  40. package/src/viewer/scene/model/layer/programs/PickMeshProgram.js +12 -0
  41. package/src/viewer/scene/model/layer/programs/PickNormalsProgram.js +18 -0
  42. package/src/viewer/scene/model/layer/programs/ShadowProgram.js +23 -0
  43. package/src/viewer/scene/model/layer/programs/SilhouetteProgram.js +15 -0
  44. package/src/viewer/scene/model/layer/programs/SnapProgram.js +29 -0
  45. package/src/viewer/scene/scene/Scene.js +21 -38
  46. package/src/viewer/scene/webgl/ArrayBuf.js +5 -20
  47. package/src/viewer/scene/webgl/FrameContext.js +14 -86
  48. package/src/viewer/scene/webgl/RenderBuffer.js +62 -262
  49. package/src/viewer/scene/webgl/Renderer.js +880 -843
  50. package/src/viewer/scene/webgl/WebGLRenderer.js +612 -0
  51. package/src/viewer/scene/webgl/occlusion/OcclusionLayer.js +60 -132
  52. package/src/viewer/scene/webgl/occlusion/OcclusionTester.js +167 -328
  53. package/src/viewer/scene/mesh/draw/DrawRenderer.js +0 -998
  54. package/src/viewer/scene/mesh/emphasis/EmphasisEdgesRenderer.js +0 -259
  55. package/src/viewer/scene/mesh/emphasis/EmphasisEdgesShaderSource.js +0 -160
  56. package/src/viewer/scene/mesh/emphasis/EmphasisFillRenderer.js +0 -286
  57. package/src/viewer/scene/mesh/emphasis/EmphasisFillShaderSource.js +0 -263
  58. package/src/viewer/scene/mesh/occlusion/OcclusionRenderer.js +0 -221
  59. package/src/viewer/scene/mesh/pick/PickMeshRenderer.js +0 -223
  60. package/src/viewer/scene/mesh/pick/PickTriangleRenderer.js +0 -200
  61. package/src/viewer/scene/mesh/shadow/ShadowRenderer.js +0 -214
  62. package/src/viewer/scene/model/RENDER_PASSES.js +0 -34
  63. package/src/viewer/scene/model/dtx/BindableDataTexture.js +0 -31
  64. package/src/viewer/scene/model/dtx/lines/DTXLinesBuffer.js +0 -27
  65. package/src/viewer/scene/model/dtx/lines/DTXLinesLayer.js +0 -897
  66. package/src/viewer/scene/model/dtx/lines/DTXLinesState.js +0 -46
  67. package/src/viewer/scene/model/dtx/lines/DTXLinesTextureFactory.js +0 -411
  68. package/src/viewer/scene/model/dtx/lines/dataTextureRamStats.js +0 -49
  69. package/src/viewer/scene/model/dtx/lines/rebucketPositions.js +0 -208
  70. package/src/viewer/scene/model/dtx/lines/renderers/DTXLinesColorRenderer.js +0 -389
  71. package/src/viewer/scene/model/dtx/lines/renderers/DTXLinesRenderers.js +0 -65
  72. package/src/viewer/scene/model/dtx/triangles/DTXTrianglesLayer.js +0 -1399
  73. package/src/viewer/scene/model/dtx/triangles/lib/DTXTrianglesBuffer.js +0 -46
  74. package/src/viewer/scene/model/dtx/triangles/lib/DTXTrianglesState.js +0 -250
  75. package/src/viewer/scene/model/dtx/triangles/lib/DTXTrianglesTextureFactory.js +0 -518
  76. package/src/viewer/scene/model/dtx/triangles/lib/dataTextureRamStats.js +0 -54
  77. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesColorRenderer.js +0 -639
  78. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesDepthRenderer.js +0 -464
  79. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesEdgesColorRenderer.js +0 -423
  80. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesEdgesRenderer.js +0 -431
  81. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesNormalsRenderer.js +0 -345
  82. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesOcclusionRenderer.js +0 -436
  83. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesPickDepthRenderer.js +0 -466
  84. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesPickMeshRenderer.js +0 -437
  85. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesPickNormalsFlatRenderer.js +0 -460
  86. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesPickNormalsRenderer.js +0 -437
  87. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesRenderers.js +0 -307
  88. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesSilhouetteRenderer.js +0 -472
  89. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesSnapInitRenderer.js +0 -474
  90. package/src/viewer/scene/model/dtx/triangles/renderers/DTXTrianglesSnapRenderer.js +0 -435
  91. package/src/viewer/scene/model/vbo/ScratchMemory.js +0 -63
  92. package/src/viewer/scene/model/vbo/VBORenderer.js +0 -664
  93. package/src/viewer/scene/model/vbo/batching/lines/VBOBatchingLinesLayer.js +0 -704
  94. package/src/viewer/scene/model/vbo/batching/lines/lib/VBOBatchingLinesBuffer.js +0 -19
  95. package/src/viewer/scene/model/vbo/batching/lines/renderers/VBOBatchingLineSnapInitRenderer.js +0 -318
  96. package/src/viewer/scene/model/vbo/batching/lines/renderers/VBOBatchingLinesColorRenderer.js +0 -114
  97. package/src/viewer/scene/model/vbo/batching/lines/renderers/VBOBatchingLinesRenderers.js +0 -99
  98. package/src/viewer/scene/model/vbo/batching/lines/renderers/VBOBatchingLinesSilhouetteRenderer.js +0 -124
  99. package/src/viewer/scene/model/vbo/batching/lines/renderers/VBOBatchingLinesSnapInitRenderer.js +0 -313
  100. package/src/viewer/scene/model/vbo/batching/lines/renderers/VBOBatchingLinesSnapRenderer.js +0 -311
  101. package/src/viewer/scene/model/vbo/batching/lines/renderers/VBOSceneModelLineBatchingRenderer.js +0 -24
  102. package/src/viewer/scene/model/vbo/batching/points/VBOBatchingPointsLayer.js +0 -688
  103. package/src/viewer/scene/model/vbo/batching/points/VBOBatchingPointsRenderer.js +0 -24
  104. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsColorRenderer.js +0 -168
  105. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsOcclusionRenderer.js +0 -136
  106. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsPickDepthRenderer.js +0 -156
  107. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsPickMeshRenderer.js +0 -148
  108. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsRenderers.js +0 -144
  109. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsShadowRenderer.js +0 -107
  110. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsSilhouetteRenderer.js +0 -146
  111. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsSnapInitRenderer.js +0 -315
  112. package/src/viewer/scene/model/vbo/batching/points/renderers/VBOBatchingPointsSnapRenderer.js +0 -305
  113. package/src/viewer/scene/model/vbo/batching/triangles/VBOBatchingTrianglesBuffer.js +0 -24
  114. package/src/viewer/scene/model/vbo/batching/triangles/VBOBatchingTrianglesLayer.js +0 -1346
  115. package/src/viewer/scene/model/vbo/batching/triangles/renderers/EdgesColorRenderer.js +0 -131
  116. package/src/viewer/scene/model/vbo/batching/triangles/renderers/EdgesEmphasisRenderer.js +0 -135
  117. package/src/viewer/scene/model/vbo/batching/triangles/renderers/EdgesRenderer.js +0 -12
  118. package/src/viewer/scene/model/vbo/batching/triangles/renderers/Renderers.js +0 -403
  119. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesBatchingRenderer.js +0 -35
  120. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesColorRenderer.js +0 -252
  121. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesColorTextureRenderer.js +0 -294
  122. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesDepthRenderer.js +0 -115
  123. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesFlatColorRenderer.js +0 -246
  124. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesNormalsRenderer.js +0 -139
  125. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesOcclusionRenderer.js +0 -125
  126. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesPBRRenderer.js +0 -561
  127. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesPickDepthRenderer.js +0 -144
  128. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesPickMeshRenderer.js +0 -130
  129. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesPickNormalsFlatRenderer.js +0 -121
  130. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesPickNormalsRenderer.js +0 -131
  131. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesShadowRenderer.js +0 -107
  132. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesSilhouetteRenderer.js +0 -144
  133. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesSnapInitRenderer.js +0 -313
  134. package/src/viewer/scene/model/vbo/batching/triangles/renderers/TrianglesSnapRenderer.js +0 -312
  135. package/src/viewer/scene/model/vbo/float16.js +0 -760
  136. package/src/viewer/scene/model/vbo/instancing/lines/VBOInstancingLinesLayer.js +0 -711
  137. package/src/viewer/scene/model/vbo/instancing/lines/renderers/VBOInstancingLinesColorRenderer.js +0 -148
  138. package/src/viewer/scene/model/vbo/instancing/lines/renderers/VBOInstancingLinesRenderer.js +0 -26
  139. package/src/viewer/scene/model/vbo/instancing/lines/renderers/VBOInstancingLinesRenderers.js +0 -139
  140. package/src/viewer/scene/model/vbo/instancing/lines/renderers/VBOInstancingLinesSilhouetteRenderer.js +0 -127
  141. package/src/viewer/scene/model/vbo/instancing/lines/renderers/VBOInstancingLinesSnapInitRenderer.js +0 -308
  142. package/src/viewer/scene/model/vbo/instancing/lines/renderers/VBOInstancingLinesSnapRenderer.js +0 -299
  143. package/src/viewer/scene/model/vbo/instancing/points/VBOInstancingPointsLayer.js +0 -733
  144. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsColorRenderer.js +0 -174
  145. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsDepthRenderer.js +0 -156
  146. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsOcclusionRenderer.js +0 -149
  147. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsPickDepthRenderer.js +0 -170
  148. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsPickMeshRenderer.js +0 -152
  149. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsRenderer.js +0 -26
  150. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsRenderers.js +0 -174
  151. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsShadowRenderer.js +0 -119
  152. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsSilhouetteRenderer.js +0 -154
  153. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsSnapInitRenderer.js +0 -307
  154. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingPointsSnapRenderer.js +0 -293
  155. package/src/viewer/scene/model/vbo/instancing/points/renderers/VBOInstancingTrianglesRenderer.js +0 -150
  156. package/src/viewer/scene/model/vbo/instancing/triangles/VBOInstancingTrianglesLayer.js +0 -1289
  157. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/EdgesColorRenderer.js +0 -135
  158. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/EdgesEmphasisRenderer.js +0 -137
  159. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/EdgesRenderer.js +0 -12
  160. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/Renderers.js +0 -403
  161. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesColorRenderer.js +0 -267
  162. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesColorTextureRenderer.js +0 -299
  163. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesDepthRenderer.js +0 -126
  164. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesFlatColorRenderer.js +0 -255
  165. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesFlatNormalsRenderer.js +0 -130
  166. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesInstancingRenderer.js +0 -32
  167. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesNormalsRenderer.js +0 -138
  168. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesOcclusionRenderer.js +0 -128
  169. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesPBRRenderer.js +0 -561
  170. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesPickDepthRenderer.js +0 -149
  171. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesPickMeshRenderer.js +0 -136
  172. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesPickNormalsFlatRenderer.js +0 -130
  173. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesPickNormalsRenderer.js +0 -145
  174. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesShadowRenderer.js +0 -113
  175. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesSilhouetteRenderer.js +0 -148
  176. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesSnapInitRenderer.js +0 -319
  177. package/src/viewer/scene/model/vbo/instancing/triangles/renderers/TrianglesSnapRenderer.js +0 -310
  178. package/src/viewer/scene/webgl/Attribute.js +0 -23
  179. package/src/viewer/scene/webgl/Program.js +0 -181
  180. package/src/viewer/scene/webgl/RenderBufferManager.js +0 -34
  181. package/src/viewer/scene/webgl/Sampler.js +0 -18
  182. package/src/viewer/scene/webgl/Shader.js +0 -49
  183. package/src/viewer/scene/webgl/sao/SAODepthLimitedBlurRenderer.js +0 -324
  184. package/src/viewer/scene/webgl/sao/SAOOcclusionRenderer.js +0 -384
@@ -0,0 +1,1019 @@
1
+ import {ENTITY_FLAGS} from "../ENTITY_FLAGS.js";
2
+ import {getColSilhEdgePickFlags, getRenderers, Layer} from "./Layer.js";
3
+
4
+ import {math} from "../../math/math.js";
5
+ import {quantizePositions, transformAndOctEncodeNormals} from "../compression.js";
6
+ import {geometryCompressionUtils} from "../../math/geometryCompressionUtils.js";
7
+
8
+ const tempFloat32 = new Float32Array(1);
9
+ const tempFloat32Vec4 = new Float32Array(4);
10
+ const tempVec3fa = new Float32Array(3);
11
+ const tempMat4 = math.mat4();
12
+ const tempVec4a = math.vec4([0, 0, 0, 1]);
13
+ const tempVec4b = math.vec4();
14
+
15
+ const tempVec3a = math.vec3();
16
+ const tempVec3b = math.vec3();
17
+ const tempVec3c = math.vec3();
18
+ const tempVec3d = math.vec3();
19
+ const tempVec3e = math.vec3();
20
+ const tempVec3f = math.vec3();
21
+ const tempVec3g = math.vec3();
22
+
23
+ const tempUint8Array4 = new Uint8Array(4);
24
+ const matricesUniformBlockBufferData = new Float32Array(4 * 4 * 6); // there is 6 mat4
25
+
26
+ const iota = function(n) {
27
+ const ret = [ ];
28
+ for (let i = 0; i < n; ++i) ret.push(i);
29
+ return ret;
30
+ };
31
+
32
+ // fills the whole dst array with src copies
33
+ const fillArray = function(dst, src) {
34
+ dst.set(src);
35
+ let soFar = src.length;
36
+ const allDataLen = dst.length;
37
+ while (soFar < allDataLen) {
38
+ const toCopy = Math.min(soFar, allDataLen - soFar);
39
+ dst.set(dst.subarray(0, toCopy), soFar);
40
+ soFar += toCopy;
41
+ }
42
+ };
43
+
44
+ const scratchMemory = (function() {
45
+ /**
46
+ * Provides scratch memory for methods like TrianglesBatchingLayer setFlags() and setColors(),
47
+ * so they don't need to allocate temporary arrays that need garbage collection.
48
+ */
49
+ let cnt = 0;
50
+ const arrays = new Map();
51
+ return {
52
+ acquire: () => cnt++,
53
+ release: () => {
54
+ cnt--;
55
+ if (cnt === 0) {
56
+ arrays.clear();
57
+ }
58
+ },
59
+ getTypeArray: function(type, len) {
60
+ if (! arrays.has(type)) {
61
+ arrays.set(type, { });
62
+ }
63
+ const typeArrays = arrays.get(type);
64
+ if (! (len in typeArrays)) {
65
+ typeArrays[len] = new type(len);
66
+ }
67
+ return typeArrays[len];
68
+ }
69
+ };
70
+ })();
71
+
72
+ /**
73
+ * @private
74
+ */
75
+ export class VBOLayer extends Layer {
76
+
77
+ /**
78
+ * @param model
79
+ * @param primitive
80
+ * @param origin
81
+ *
82
+ * @param cfg
83
+ * @param cfg.textureSet
84
+ *
85
+ * batching:
86
+ * @param cfg.positionsDecodeMatrix
87
+ * @param cfg.uvDecodeMatrix
88
+ * @param cfg.maxGeometryBatchSize
89
+ *
90
+ * instancing:
91
+ * @param cfg.geometry
92
+ */
93
+ constructor(model, primitive, origin, cfg) {
94
+
95
+ super(model, primitive, origin);
96
+
97
+ const instancing = !! cfg.geometry;
98
+
99
+ this._maxVerts = cfg.maxGeometryBatchSize;
100
+
101
+ const positionsDecodeMatrix = instancing ? cfg.geometry.positionsDecodeMatrix : cfg.positionsDecodeMatrix;
102
+ this._positionsDecodeMatrix = positionsDecodeMatrix && math.mat4(positionsDecodeMatrix);
103
+
104
+ this._cfgUvDecodeMatrix = cfg.uvDecodeMatrix && math.mat3(cfg.uvDecodeMatrix);
105
+ this._instancedGeometry = cfg.geometry;
106
+ this._textureSet = cfg.textureSet;
107
+
108
+ this._modelAABB = (! instancing) && math.collapseAABB3(); // Model-space AABB
109
+ this._portions = [ ];
110
+
111
+ const attribute = function() {
112
+ let length = 0;
113
+ const portions = [ ];
114
+
115
+ return {
116
+ length: () => length,
117
+ append: function(data, times = 1, denormalizeScale = 1.0, increment = 0.0) {
118
+ length += times * data.length;
119
+ portions.push({ data: data, times: times, denormalizeScale: denormalizeScale, increment: increment });
120
+ },
121
+ compileBuffer: function(type) {
122
+ let len = 0;
123
+ portions.forEach(p => { len += p.times * p.data.length; });
124
+ const buf = new type(len);
125
+
126
+ let begin = 0;
127
+ portions.forEach(p => {
128
+ const data = p.data;
129
+ const dScale = p.denormalizeScale;
130
+ const increment = p.increment;
131
+ const subBuf = buf.subarray(begin);
132
+
133
+ if ((dScale === 1.0) && (increment === 0.0)) {
134
+ subBuf.set(data);
135
+ } else {
136
+ for (let i = 0; i < data.length; ++i) {
137
+ subBuf[i] = increment + data[i] * dScale;
138
+ }
139
+ }
140
+
141
+ let soFar = data.length;
142
+ const allDataLen = p.times * data.length;
143
+ while (soFar < allDataLen) {
144
+ const toCopy = Math.min(soFar, allDataLen - soFar);
145
+ subBuf.set(subBuf.subarray(0, toCopy), soFar);
146
+ soFar += toCopy;
147
+ }
148
+
149
+ begin += soFar;
150
+ });
151
+
152
+ return buf;
153
+ }
154
+ };
155
+ };
156
+
157
+ this._buffer = {
158
+ colors: attribute(), // in instancing used only for non-points
159
+ metallicRoughness: attribute(), // used for triangulated
160
+ pickColors: attribute(), // used for non-lines
161
+ ...(instancing
162
+ ? {
163
+ // Modeling matrix per instance, array for each column
164
+ modelMatrixCol: [ attribute(), attribute(), attribute() ],
165
+ modelNormalMatrixCol: [ attribute(), attribute(), attribute() ]
166
+ }
167
+ : {
168
+ positions: attribute(),
169
+ indices: attribute(), // used for non-points
170
+ uv: attribute(), // used for triangulated
171
+ normals: attribute(), // used for triangulated
172
+ edgeIndices: attribute(), // used for triangulated
173
+ })
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Tests if there is room for another portion in this Layer.
179
+ *
180
+ * @param lenPositions Number of positions we'd like to create in the portion.
181
+ * @param lenIndices Number of indices we'd like to create in this portion.
182
+ * @returns {Boolean} True if OK to create another portion.
183
+ */
184
+ canCreatePortion(lenPositions, lenIndices) {
185
+ return this._instancedGeometry || (((this._buffer.positions.length() + lenPositions) <= (this._maxVerts * 3)) && ((this._buffer.indices.length() + lenIndices) <= (this._maxVerts * 3)));
186
+ }
187
+
188
+ /**
189
+ * Creates a new portion within this Layer, returns the new portion ID.
190
+ *
191
+ * @param mesh The SceneModelMesh that owns the portion
192
+ * @param cfg Portion params
193
+ * @param cfg.metallic Metalness factor [0..255] (triangulated)
194
+ * @param cfg.roughness Roughness factor [0..255] (triangulated)
195
+ * @param cfg.pickColor Quantized pick color (non-lines)
196
+ * @param cfg.meshMatrix Flat float 4x4 matrix (optional in batching)
197
+ * batching:
198
+ * @param cfg.positionsCompressed Flat quantized positions array - decompressed with positionsDecodeMatrix
199
+ * @param cfg.positions Flat float Local-space positions array.
200
+ * @param cfg.indices Flat int indices array.
201
+ * @param [cfg.normalsCompressed]
202
+ * @param [cfg.normals] Flat float normals array (triangulated)
203
+ * @param [cfg.colors] Flat float colors array (non-lines)
204
+ * @param [cfg.colorsCompressed] Quantized RGB colors [0..255,0..255,0..255,0..255] (non-lines)
205
+ * @param cfg.color Float RGB color [0..1,0..1,0..1] (points) or Quantized RGB color [0..255,0..255,0..255,0..255] (non-points)
206
+ * @param cfg.opacity Opacity [0..255] (non-points)
207
+ * @param [cfg.uv] Flat UVs array (triangulated)
208
+ * @param [cfg.uvCompressed] (triangulated)
209
+ * @param [cfg.edgeIndices] Flat int edges indices array (triangulated)
210
+ * @param cfg.aabb Flat float AABB World-space AABB
211
+ * instancing:
212
+ * @param cfg.color Color [0..255,0..255,0..255]
213
+ * @param cfg.opacity Opacity [0..255].
214
+ * @returns {number} Portion ID
215
+ */
216
+ createPortion(mesh, cfg) {
217
+ const buffer = this._buffer;
218
+ const instancedGeometry = this._instancedGeometry;
219
+ const model = this.model;
220
+ const portionId = this._portions.length;
221
+ const primitive = this.primitive;
222
+ const useCompressed = !! this._positionsDecodeMatrix;
223
+ const scene = model.scene;
224
+ const meshMatrix = cfg.meshMatrix;
225
+
226
+ const appendPortion = (portionBase, portionSize, indices, quantizedPositions, meshMatrix) => {
227
+ const prevPortion = (this._portions.length > 0) && this._portions[this._portions.length - 1];
228
+ const portion = {
229
+ indicesBaseIndex: prevPortion ? (prevPortion.indicesBaseIndex + prevPortion.numIndices) : 0,
230
+ numIndices: indices ? indices.length : 0,
231
+ portionBase: portionBase,
232
+ portionSize: portionSize,
233
+ retainedGeometry: scene.readableGeometryEnabled && (primitive !== "points") && (primitive !== "lines") && {
234
+ indices: indices,
235
+ quantizedPositions: quantizedPositions,
236
+ offset: scene.entityOffsetsEnabled && math.vec3(),
237
+ matrix: meshMatrix && meshMatrix.slice(),
238
+ inverseMatrix: null, // Lazy-computed for instancing in precisionRayPickSurface
239
+ normalMatrix: null, // Lazy-computed for instancing in precisionRayPickSurface
240
+ }
241
+ };
242
+
243
+ if ((primitive !== "points") && (primitive !== "lines")) {
244
+ buffer.metallicRoughness.append([ cfg.metallic ?? 0, cfg.roughness ?? 255 ], portionSize);
245
+ }
246
+
247
+ if (primitive !== "lines") {
248
+ buffer.pickColors.append(cfg.pickColor.slice(0, 4), portionSize);
249
+ }
250
+
251
+ this._portions.push(portion);
252
+ model.numPortions++;
253
+ this._meshes.push(mesh);
254
+ return portionId;
255
+ };
256
+
257
+ if (instancedGeometry) {
258
+ buffer.modelMatrixCol.forEach((b, i) => b.append([ meshMatrix[i+0], meshMatrix[i+4], meshMatrix[i+8], meshMatrix[i+12] ]));
259
+
260
+ if (primitive !== "points") {
261
+ const color = cfg.color; // Color is pre-quantized by SceneModel
262
+ buffer.colors.append([ color[0], color[1], color[2], cfg.opacity ?? 255 ]);
263
+ }
264
+
265
+ if ((primitive !== "points") && (primitive !== "lines")) {
266
+ if (instancedGeometry.normals) {
267
+ // Note: order of inverse and transpose doesn't matter
268
+ const normalMatrix = math.inverseMat4(math.transposeMat4(meshMatrix, math.mat4()));
269
+ buffer.modelNormalMatrixCol.forEach((b, i) => b.append([ normalMatrix[i+0], normalMatrix[i+4], normalMatrix[i+8], normalMatrix[i+12] ]));
270
+ }
271
+ }
272
+
273
+ return appendPortion(portionId, 1, instancedGeometry.indices, instancedGeometry.positionsCompressed, meshMatrix);
274
+ } else {
275
+ const vertsBaseIndex = buffer.positions.length() / 3;
276
+
277
+ const positions = useCompressed ? cfg.positionsCompressed : cfg.positions;
278
+ if (! positions) {
279
+ throw ((useCompressed ? "positionsCompressed" : "positions") + " expected");
280
+ }
281
+
282
+ buffer.positions.append(positions);
283
+
284
+ const numVerts = positions.length / 3;
285
+
286
+ const indices = cfg.indices;
287
+ if (indices) {
288
+ buffer.indices.append(indices, 1, 1.0, vertsBaseIndex);
289
+ }
290
+
291
+ const normalsCompressed = cfg.normalsCompressed;
292
+ const normals = cfg.normals;
293
+ if (normalsCompressed && normalsCompressed.length > 0) {
294
+ buffer.normals.append(normalsCompressed);
295
+ } else if (normals && normals.length > 0) {
296
+ const worldNormalMatrix = tempMat4;
297
+ if (meshMatrix) {
298
+ math.transposeMat4(meshMatrix, worldNormalMatrix);
299
+ math.inverseMat4(worldNormalMatrix, worldNormalMatrix); // Note: order of inverse and transpose doesn't matter
300
+ } else {
301
+ math.identityMat4(worldNormalMatrix);
302
+ }
303
+ const normalsData = [ ];
304
+ transformAndOctEncodeNormals(worldNormalMatrix, normals, normals.length, normalsData, 0);
305
+ buffer.normals.append(normalsData);
306
+ }
307
+
308
+ const colors = cfg.colors;
309
+ const colorsCompressed = cfg.colorsCompressed;
310
+ const color = cfg.color;
311
+ if (colors) {
312
+ if (primitive === "points") {
313
+ buffer.colors.append(colors, 1, 255.0);
314
+ } else { // triangulated
315
+ const colorsData = [ ];
316
+ for (let i = 0, len = colors.length; i < len; i += 3) {
317
+ colorsData.push(colors[i] * 255);
318
+ colorsData.push(colors[i + 1] * 255);
319
+ colorsData.push(colors[i + 2] * 255);
320
+ colorsData.push(255);
321
+ }
322
+ buffer.colors.append(colorsData);
323
+ }
324
+ } else if (colorsCompressed) {
325
+ if (primitive === "points") {
326
+ buffer.colors.append(colorsCompressed);
327
+ } else { // triangulated
328
+ const colorsData = [ ];
329
+ for (let i = 0, len = colorsCompressed.length; i < len; i += 3) {
330
+ colorsData.push(colorsCompressed[i]);
331
+ colorsData.push(colorsCompressed[i + 1]);
332
+ colorsData.push(colorsCompressed[i + 2]);
333
+ colorsData.push(255);
334
+ }
335
+ buffer.colors.append(colorsData);
336
+ }
337
+ } else if (color) {
338
+ // Color is pre-quantized by VBOSceneModel
339
+ buffer.colors.append([ color[0], color[1], color[2], (primitive === "points") ? 1.0 : cfg.opacity ], numVerts);
340
+ }
341
+
342
+ const nonEmpty = v => v && (v.length > 0) && v;
343
+ const uv = nonEmpty(cfg.uv) || nonEmpty(cfg.uvCompressed);
344
+ if (uv) {
345
+ buffer.uv.append(uv);
346
+ }
347
+
348
+ const edgeIndices = cfg.edgeIndices;
349
+ if (edgeIndices) {
350
+ buffer.edgeIndices.append(edgeIndices, 1, 1.0, vertsBaseIndex);
351
+ }
352
+
353
+ math.expandAABB3(this._modelAABB, cfg.aabb);
354
+
355
+ // quantizedPositions are initialized in finalize()
356
+ return appendPortion(vertsBaseIndex, numVerts, indices);
357
+ }
358
+ }
359
+
360
+ compilePortions() {
361
+ const buffer = this._buffer;
362
+ const instancedGeometry = this._instancedGeometry;
363
+ const model = this.model;
364
+ const modelAABB = this._modelAABB;
365
+ const origin = this.origin;
366
+ const portions = this._portions;
367
+ const primitive = this.primitive;
368
+ const textureSet = this._textureSet;
369
+ let positionsDecodeMatrix = this._positionsDecodeMatrix;
370
+ const cfgUvDecodeMatrix = this._cfgUvDecodeMatrix;
371
+
372
+ const scene = model.scene;
373
+ const gl = scene.canvas.gl;
374
+ const instancing = !! instancedGeometry;
375
+
376
+ const cleanups = [ ];
377
+
378
+ const createGlBuffer = (target, srcData, size, usage) => {
379
+ if (srcData.length > 0) {
380
+ const srcDataConstructor = srcData.constructor;
381
+ const [byteSize, type] = ({
382
+ [Uint8Array]: [1, gl.UNSIGNED_BYTE],
383
+ [Int8Array]: [1, gl.BYTE],
384
+ [Uint16Array]: [2, gl.UNSIGNED_SHORT],
385
+ [Int16Array]: [2, gl.SHORT],
386
+ [Uint32Array]: [4, gl.UNSIGNED_INT],
387
+ [Int32Array]: [4, gl.INT],
388
+ [Float32Array]: [4, gl.FLOAT]
389
+ })[srcDataConstructor];
390
+
391
+ const buffer = gl.createBuffer();
392
+ cleanups.push(() => gl.deleteBuffer(buffer));
393
+
394
+ const bindBuffer = () => gl.bindBuffer(target, buffer);
395
+ const setData = data => {
396
+ bindBuffer();
397
+ gl.bufferData(target, data, usage);
398
+ };
399
+ setData(srcData);
400
+
401
+ const bytesPerElement = srcData.BYTES_PER_ELEMENT;
402
+ const numItems = srcData.length / size;
403
+ return {
404
+ bindBuffer: bindBuffer,
405
+ getData: (baseIndex = 0, length = numItems - baseIndex) => {
406
+ bindBuffer();
407
+ const array = new srcDataConstructor(length * size);
408
+ gl.getBufferSubData(target, baseIndex * byteSize * size, array, 0, length * size);
409
+ return array;
410
+ },
411
+ numItems: numItems,
412
+ setData: setData,
413
+ setSubData: (data, offset) => {
414
+ bindBuffer();
415
+ gl.bufferSubData(target, offset * bytesPerElement, data);
416
+ },
417
+ type: type
418
+ };
419
+ } else {
420
+ return null;
421
+ }
422
+ };
423
+
424
+ const maybeCreateBuffer = (srcData, size, usage, setDivisor = false, normalized = false) => {
425
+ const buf = createGlBuffer(gl.ARRAY_BUFFER, srcData, size, usage);
426
+ return buf && {
427
+ getData: buf.getData,
428
+ numItems: buf.numItems,
429
+ setData: buf.setData,
430
+ setSubData: buf.setSubData,
431
+ attributeDivisor: setDivisor && 1,
432
+ bindAtLocation: location => {
433
+ buf.bindBuffer();
434
+ gl.vertexAttribPointer(location, size, buf.type, !!normalized, 0, 0);
435
+ }
436
+ };
437
+ };
438
+
439
+ const maybeCreateIndicesBuffer = srcData => {
440
+ const buf = createGlBuffer(gl.ELEMENT_ARRAY_BUFFER, srcData, 1, gl.STATIC_DRAW);
441
+ return buf && {
442
+ getData: buf.getData,
443
+ bindIndicesBuffer: buf.bindBuffer,
444
+ indicesCount: srcData.length,
445
+ indicesType: buf.type
446
+ };
447
+ };
448
+
449
+ const attributesCnt = portions.reduce((acc,p) => acc + p.portionSize, 0);
450
+
451
+ const flagsBuf = maybeCreateBuffer(new Float32Array(attributesCnt), 1, gl.DYNAMIC_DRAW, instancing);
452
+
453
+ const createColorsBuf = (srcData, usage) => maybeCreateBuffer(srcData, 4, usage, instancing && (primitive !== "points"), true);
454
+ const colorsBuf = ((instancing && instancedGeometry.colorsCompressed)
455
+ ? createColorsBuf(new Uint8Array(instancedGeometry.colorsCompressed), gl.STATIC_DRAW)
456
+ : createColorsBuf(buffer.colors.compileBuffer(Uint8Array), gl.DYNAMIC_DRAW));
457
+
458
+ const offsetsBuf = scene.entityOffsetsEnabled && maybeCreateBuffer(new Float32Array(attributesCnt * 3), 3, gl.DYNAMIC_DRAW, instancing);
459
+
460
+ const metallicRoughnessBuf = maybeCreateBuffer(buffer.metallicRoughness.compileBuffer(Uint8Array), 2, gl.STATIC_DRAW, instancing);
461
+
462
+ const pickColorsBuf = maybeCreateBuffer(buffer.pickColors.compileBuffer(Uint8Array), 4, gl.STATIC_DRAW, instancing);
463
+
464
+ const edgeIndicesBuf = maybeCreateIndicesBuffer(instancing
465
+ ? new Uint32Array(instancedGeometry.edgeIndices)
466
+ : buffer.edgeIndices.compileBuffer(Uint32Array));
467
+
468
+ const indices = (instancing
469
+ ? ((primitive !== "points") && instancedGeometry.indices && new Uint32Array(instancedGeometry.indices))
470
+ : buffer.indices.compileBuffer(Uint32Array));
471
+ const indicesBuf = indices && maybeCreateIndicesBuffer(indices);
472
+
473
+ const positions = (instancing
474
+ ? instancedGeometry.positionsCompressed
475
+ : (positionsDecodeMatrix
476
+ ? buffer.positions.compileBuffer(Uint16Array)
477
+ : (quantizePositions(buffer.positions.compileBuffer(Float64Array), modelAABB, positionsDecodeMatrix = math.mat4()))));
478
+ const positionsBuf = positions && maybeCreateBuffer(positions, 3, gl.STATIC_DRAW);
479
+ if (! instancing) {
480
+ portions.forEach(portion => {
481
+ if (portion.retainedGeometry) {
482
+ const start = 3 * portion.portionBase;
483
+ portion.retainedGeometry.quantizedPositions = positions.subarray(start, start + 3 * portion.portionSize);
484
+ }
485
+ });
486
+ }
487
+
488
+ const modelMatrixColBufs = instancing && buffer.modelMatrixCol.map(b => maybeCreateBuffer(b.compileBuffer(Float32Array), 4, gl.STATIC_DRAW, true));
489
+
490
+ const normals = (instancing
491
+ ? false // (primitive !== "points") && (primitive !== "lines") && instancedGeometry.normalsCompressed
492
+ : buffer.normals.compileBuffer(Int8Array));
493
+ // Normals are already oct-encoded, so `normalized = true` for oct encoded UInts
494
+ const normalsBuf = normals && maybeCreateBuffer(normals, 3, gl.STATIC_DRAW, false, true);
495
+
496
+ // WARNING: modelMatrixColBufs and normalsBuf are never simultaneously defined at the moment (when instancing=true)
497
+ const modelNormalMatrixColBufs = modelMatrixColBufs && normalsBuf && buffer.modelNormalMatrixCol.map(b => maybeCreateBuffer(b.compileBuffer(Float32Array), 4, gl.STATIC_DRAW, true));
498
+
499
+ const uvSetup = (instancing
500
+ ? ((primitive !== "points") && (primitive !== "lines") && instancedGeometry.uvCompressed && {
501
+ buf: maybeCreateBuffer(instancedGeometry.uvCompressed, 2, gl.STATIC_DRAW),
502
+ mat: instancedGeometry.uvDecodeMatrix
503
+ })
504
+ : (function() {
505
+ const uvs = buffer.uv.compileBuffer(Float32Array);
506
+ if (uvs.length === 0) {
507
+ return null;
508
+ } else if (cfgUvDecodeMatrix) {
509
+ return {
510
+ buf: maybeCreateBuffer(uvs, 2, gl.STATIC_DRAW),
511
+ mat: cfgUvDecodeMatrix
512
+ };
513
+ } else {
514
+ const bounds = geometryCompressionUtils.getUVBounds(uvs);
515
+ const result = geometryCompressionUtils.compressUVs(uvs, bounds.min, bounds.max);
516
+ return {
517
+ buf: maybeCreateBuffer(result.quantized, 2, gl.STATIC_DRAW),
518
+ mat: math.mat3(result.decodeMatrix)
519
+ };
520
+ }
521
+ })());
522
+
523
+ // Free up memory
524
+ this._buffer = null;
525
+
526
+ scratchMemory.acquire();
527
+ cleanups.push(() => scratchMemory.release());
528
+
529
+ let deferredFlagValues = null;
530
+
531
+ /**
532
+ * flags are 4bits values encoded on a 32bit base. color flag on the first 4 bits, silhouette flag on the next 4 bits and so on for edge, pick and clippable.
533
+ */
534
+ const setFlags = (portionId, flags, transparent, deferred = false) => {
535
+ getColSilhEdgePickFlags(flags, transparent, (primitive !== "points") && (primitive !== "lines"), scene, tempUint8Array4);
536
+
537
+ const clippableFlag = !!(flags & ENTITY_FLAGS.CLIPPABLE) ? 1 : 0;
538
+
539
+ let vertFlag = 0;
540
+ vertFlag |= tempUint8Array4[0];
541
+ vertFlag |= tempUint8Array4[1] << 4;
542
+ vertFlag |= tempUint8Array4[2] << 8;
543
+ vertFlag |= tempUint8Array4[3] << 12;
544
+ vertFlag |= clippableFlag << 16;
545
+
546
+ tempFloat32[0] = vertFlag;
547
+
548
+ const portion = portions[portionId];
549
+ const firstFlag = portion.portionBase;
550
+ const lenFlags = portion.portionSize;
551
+
552
+ if (deferred && (! instancedGeometry)) {
553
+ // Avoid zillions of individual WebGL bufferSubData calls - buffer them to apply in one shot
554
+ if (!deferredFlagValues) {
555
+ deferredFlagValues = new Float32Array(attributesCnt);
556
+ }
557
+ fillArray(deferredFlagValues.subarray(firstFlag, firstFlag + lenFlags), tempFloat32);
558
+ } else if (flagsBuf) {
559
+ const tempArray = scratchMemory.getTypeArray(Float32Array, lenFlags);
560
+ fillArray(tempArray, tempFloat32);
561
+ flagsBuf.setSubData(tempArray, firstFlag);
562
+ }
563
+ };
564
+
565
+ const solid = (primitive === "solid");
566
+ return {
567
+ edgesColorOpaqueAllowed: () => true,
568
+ solid: solid,
569
+ sortId: (((primitive === "points") ? "Points" : ((primitive === "lines") ? "Lines" : "Triangles"))
570
+ + (instancing ? "Instancing" : "Batching") + "Layer" +
571
+ (((primitive !== "points") && (primitive !== "lines"))
572
+ ? ((solid ? "-solid" : "-surface")
573
+ + "-autoNormals"
574
+ + (instancing
575
+ ? ""
576
+ // TODO: These two parts need to be IDs (ie. unique):
577
+ : ((textureSet && textureSet.colorTexture ? "-colorTexture" : "")
578
+ +
579
+ (textureSet && textureSet.metallicRoughnessTexture ? "-metallicRoughnessTexture" : ""))))
580
+ : "")),
581
+ setClippableFlags: setFlags,
582
+ setFlags: setFlags,
583
+ setFlags2: (portionId, flags, deferred) => { },
584
+ setDeferredFlags: () => {
585
+ if (deferredFlagValues) {
586
+ flagsBuf.setData(deferredFlagValues);
587
+ deferredFlagValues = null;
588
+ }
589
+ },
590
+
591
+ setColor: (portionId, color) => { // RGBA color is normalized as ints
592
+ if (colorsBuf) {
593
+ const portion = portions[portionId];
594
+ const tempArray = scratchMemory.getTypeArray(Uint8Array, portion.portionSize * 4);
595
+ // alpha used to be unset for points, so effectively random (from last use)
596
+ fillArray(tempArray, color.slice(0, 4));
597
+ colorsBuf.setSubData(tempArray, portion.portionBase * 4);
598
+ }
599
+ },
600
+ setMatrix: (portionId, matrix) => {
601
+ if (modelMatrixColBufs) {
602
+ modelMatrixColBufs.forEach((b, i) => {
603
+ tempFloat32Vec4[0] = matrix[i+0];
604
+ tempFloat32Vec4[1] = matrix[i+4];
605
+ tempFloat32Vec4[2] = matrix[i+8];
606
+ tempFloat32Vec4[3] = matrix[i+12];
607
+ b.setSubData(tempFloat32Vec4, portionId * 4);
608
+ });
609
+ }
610
+ },
611
+ setOffset: (portionId, offset) => {
612
+ if (!scene.entityOffsetsEnabled) {
613
+ model.error("Entity#offset not enabled for this Viewer"); // See Viewer entityOffsetsEnabled
614
+ } else {
615
+ const portion = portions[portionId];
616
+ if (offsetsBuf) {
617
+ tempVec3fa.set(offset);
618
+ const tempArray = scratchMemory.getTypeArray(Float32Array, portion.portionSize * 3);
619
+ fillArray(tempArray, tempVec3fa);
620
+ offsetsBuf.setSubData(tempArray, portion.portionBase * 3);
621
+ }
622
+ if (portion.retainedGeometry) {
623
+ portion.retainedGeometry.offset.set(offset);
624
+ }
625
+ }
626
+ },
627
+
628
+ getEachIndex: (portionId, callback) => {
629
+ const retainedGeometry = portions[portionId].retainedGeometry;
630
+ if (retainedGeometry) {
631
+ retainedGeometry.indices.forEach(i => callback(i));
632
+ }
633
+ },
634
+ getEachVertex: (portionId, callback) => {
635
+ const retainedGeometry = portions[portionId].retainedGeometry;
636
+ if (retainedGeometry) {
637
+ const origVec = tempVec4b;
638
+ if (origin) {
639
+ origVec.set(origin, 0);
640
+ } else {
641
+ origVec[0] = origVec[1] = origVec[2] = 0;
642
+ }
643
+ origVec[3] = 1;
644
+ const sceneModelMatrix = model.matrix;
645
+ math.mulMat4v4(sceneModelMatrix, origVec, origVec);
646
+ const positions = retainedGeometry.quantizedPositions;
647
+ const worldPos = tempVec4a;
648
+ for (let i = 0, len = positions.length; i < len; i += 3) {
649
+ worldPos[0] = positions[i];
650
+ worldPos[1] = positions[i + 1];
651
+ worldPos[2] = positions[i + 2];
652
+ math.decompressPosition(worldPos, positionsDecodeMatrix);
653
+ if (retainedGeometry.matrix) {
654
+ math.transformPoint3(retainedGeometry.matrix, worldPos, worldPos);
655
+ }
656
+ worldPos[3] = 1;
657
+ math.mulMat4v4(sceneModelMatrix, worldPos, worldPos);
658
+ math.addVec3(origVec, worldPos, worldPos);
659
+ callback(worldPos);
660
+ }
661
+ }
662
+ },
663
+ readGeometryData: (primitive !== "points") && (primitive !== "lines") && ((portionId) => {
664
+ const portion = (! instancing) && portions[portionId];
665
+ const indices = (portion
666
+ ? indicesBuf.getData(portion.indicesBaseIndex, portion.numIndices).map(i => i - portion.portionBase)
667
+ : indicesBuf.getData());
668
+
669
+ const sceneModelMatrix = model.matrix;
670
+
671
+ const origin4 = math.vec4();
672
+ origin4.set(origin, 0); origin4[3] = 1;
673
+ math.mulMat4v4(sceneModelMatrix, origin4, origin4);
674
+
675
+ const instanceMatrix = modelMatrixColBufs && math.mat4();
676
+ if (instanceMatrix) {
677
+ const col0 = modelMatrixColBufs[0].getData(portionId, 1);
678
+ const col1 = modelMatrixColBufs[1].getData(portionId, 1);
679
+ const col2 = modelMatrixColBufs[2].getData(portionId, 1);
680
+ instanceMatrix.set([
681
+ col0[0], col1[0], col2[0], 0,
682
+ col0[1], col1[1], col2[1], 0,
683
+ col0[2], col1[2], col2[2], 0,
684
+ col0[3], col1[3], col2[3], 1,
685
+ ]);
686
+ }
687
+
688
+ const matrix = math.mat4();
689
+ math.mulMat4(sceneModelMatrix, instanceMatrix ? math.mulMat4(instanceMatrix, positionsDecodeMatrix, matrix) : positionsDecodeMatrix, matrix);
690
+
691
+ matrix[12] += origin4[0];
692
+ matrix[13] += origin4[1];
693
+ matrix[14] += origin4[2];
694
+
695
+ const positionsQuantized = portion ? positionsBuf.getData(portion.portionBase, portion.portionSize) : positionsBuf.getData();
696
+
697
+ const positions = math.transformPositions3(
698
+ matrix,
699
+ positionsQuantized,
700
+ new Float64Array(positionsQuantized.length));
701
+
702
+ return { indices, positions };
703
+ }),
704
+ precisionRayPickSurface: (portionId, worldRayOrigin, worldRayDir, worldSurfacePos, worldNormal) => {
705
+ const retainedGeometry = portions[portionId].retainedGeometry;
706
+ if (! retainedGeometry) {
707
+ return false;
708
+ } else {
709
+ if (retainedGeometry.matrix && (! retainedGeometry.inverseMatrix)) {
710
+ retainedGeometry.inverseMatrix = math.inverseMat4(retainedGeometry.matrix, math.mat4());
711
+ }
712
+
713
+ if (worldNormal && retainedGeometry.inverseMatrix && (! retainedGeometry.normalMatrix)) {
714
+ retainedGeometry.normalMatrix = math.transposeMat4(retainedGeometry.inverseMatrix, math.mat4());
715
+ }
716
+
717
+ const positions = retainedGeometry.quantizedPositions;
718
+ const indices = retainedGeometry.indices;
719
+ const offset = retainedGeometry.offset;
720
+
721
+ const rtcRayOrigin = tempVec3a;
722
+ const rtcRayDir = tempVec3b;
723
+
724
+ rtcRayOrigin.set(origin ? math.subVec3(worldRayOrigin, origin, tempVec3c) : worldRayOrigin); // World -> RTC
725
+ rtcRayDir.set(worldRayDir);
726
+
727
+ if (offset) {
728
+ math.subVec3(rtcRayOrigin, offset);
729
+ }
730
+
731
+ math.transformRay(model.worldNormalMatrix, rtcRayOrigin, rtcRayDir, rtcRayOrigin, rtcRayDir); // RTC -> local
732
+
733
+ if (retainedGeometry.inverseMatrix) {
734
+ math.transformRay(retainedGeometry.inverseMatrix, rtcRayOrigin, rtcRayDir, rtcRayOrigin, rtcRayDir);
735
+ }
736
+
737
+ const a = tempVec3d;
738
+ const b = tempVec3e;
739
+ const c = tempVec3f;
740
+
741
+ let gotIntersect = false;
742
+ let closestDist = 0;
743
+ const closestIntersectPos = tempVec3g;
744
+
745
+ for (let i = 0, len = indices.length; i < len; i += 3) {
746
+
747
+ const ia = indices[i] * 3;
748
+ const ib = indices[i + 1] * 3;
749
+ const ic = indices[i + 2] * 3;
750
+
751
+ a[0] = positions[ia];
752
+ a[1] = positions[ia + 1];
753
+ a[2] = positions[ia + 2];
754
+
755
+ b[0] = positions[ib];
756
+ b[1] = positions[ib + 1];
757
+ b[2] = positions[ib + 2];
758
+
759
+ c[0] = positions[ic];
760
+ c[1] = positions[ic + 1];
761
+ c[2] = positions[ic + 2];
762
+
763
+ math.decompressPosition(a, positionsDecodeMatrix);
764
+ math.decompressPosition(b, positionsDecodeMatrix);
765
+ math.decompressPosition(c, positionsDecodeMatrix);
766
+
767
+ if (math.rayTriangleIntersect(rtcRayOrigin, rtcRayDir, a, b, c, closestIntersectPos)) {
768
+
769
+ if (retainedGeometry.matrix) {
770
+ math.transformPoint3(retainedGeometry.matrix, closestIntersectPos, closestIntersectPos);
771
+ }
772
+
773
+ math.transformPoint3(model.worldMatrix, closestIntersectPos, closestIntersectPos);
774
+
775
+ if (offset) {
776
+ math.addVec3(closestIntersectPos, offset);
777
+ }
778
+
779
+ if (origin) {
780
+ math.addVec3(closestIntersectPos, origin);
781
+ }
782
+
783
+ const dist = Math.abs(math.lenVec3(math.subVec3(closestIntersectPos, worldRayOrigin, [])));
784
+
785
+ if (!gotIntersect || dist > closestDist) {
786
+ closestDist = dist;
787
+ worldSurfacePos.set(closestIntersectPos);
788
+ if (worldNormal) { // Not that wasteful to eagerly compute - unlikely to hit >2 surfaces on most geometry
789
+ math.triangleNormal(a, b, c, worldNormal);
790
+ }
791
+ gotIntersect = true;
792
+ }
793
+ }
794
+ }
795
+
796
+ if (gotIntersect && worldNormal) {
797
+ if (retainedGeometry.normalMatrix) {
798
+ math.transformVec3(retainedGeometry.normalMatrix, worldNormal, worldNormal);
799
+ }
800
+ math.transformVec3(model.worldNormalMatrix, worldNormal, worldNormal);
801
+ math.normalizeVec3(worldNormal);
802
+ }
803
+
804
+ return gotIntersect;
805
+ }
806
+ },
807
+
808
+ layerTextureSet: textureSet,
809
+
810
+ renderers: getRenderers(scene, instancing ? "instancing" : "batching", primitive,
811
+ model.saoEnabled,
812
+ model.pbrEnabled && uvSetup && textureSet && textureSet.colorTexture && normalsBuf && metallicRoughnessBuf && textureSet.metallicRoughnessTexture,
813
+ model.colorTextureEnabled && uvSetup && textureSet && textureSet.colorTexture,
814
+ !!normalsBuf,
815
+ (programVariables) => makeVBORenderingAttributes(programVariables, instancing && { hasModelNormalMat: !!modelNormalMatrixColBufs }, scene.entityOffsetsEnabled)),
816
+ drawCalls: (function() {
817
+ const drawCallCache = { };
818
+ const makeDrawer = (subGeometry) => (attributesHash, layerTypeInputs, viewState) => {
819
+ let offset = 0;
820
+ const mat4Size = 4 * 4;
821
+ matricesUniformBlockBufferData.set(model.rotationMatrix, 0);
822
+ matricesUniformBlockBufferData.set(viewState.viewMatrix, offset += mat4Size);
823
+ matricesUniformBlockBufferData.set(viewState.projMatrix, offset += mat4Size);
824
+ matricesUniformBlockBufferData.set(positionsDecodeMatrix, offset += mat4Size);
825
+ if (layerTypeInputs.needNormal()) {
826
+ matricesUniformBlockBufferData.set(model.worldNormalMatrix, offset += mat4Size);
827
+ matricesUniformBlockBufferData.set(viewState.viewNormalMatrix, offset += mat4Size);
828
+ }
829
+ layerTypeInputs.matrices.setInputValue(matricesUniformBlockBufferData);
830
+
831
+ layerTypeInputs.uvDecodeMatrix.setInputValue && layerTypeInputs.uvDecodeMatrix.setInputValue(uvSetup.mat);
832
+
833
+ if (! (attributesHash in drawCallCache)) {
834
+ drawCallCache[attributesHash] = [ null, null, null ];
835
+ }
836
+ const inputsCache = drawCallCache[attributesHash];
837
+ const cacheKey = subGeometry ? (subGeometry.vertices ? 0 : 1) : 2;
838
+ if (! inputsCache[cacheKey]) {
839
+ const vao = gl.createVertexArray();
840
+ gl.bindVertexArray(vao);
841
+
842
+ const setAttr = (a, b) => { if (a && a.setInputValue && b) { a.setInputValue(b); } };
843
+ const attrs = layerTypeInputs.attributes;
844
+ setAttr(attrs.position, positionsBuf);
845
+ setAttr(attrs.normal, normalsBuf);
846
+ setAttr(attrs.color, colorsBuf);
847
+ setAttr(attrs.pickColor, pickColorsBuf);
848
+ setAttr(attrs.uV, uvSetup && uvSetup.buf);
849
+ setAttr(attrs.metallicRoughness, metallicRoughnessBuf);
850
+ setAttr(attrs.flags, flagsBuf);
851
+ setAttr(attrs.offset, offsetsBuf);
852
+ attrs.modelMatrixCol && attrs.modelMatrixCol.forEach((a, i) => setAttr(a, modelMatrixColBufs[i]));
853
+ attrs.modelNormalMatrixCol && attrs.modelNormalMatrixCol.forEach((a, i) => setAttr(a, modelNormalMatrixColBufs[i]));
854
+
855
+ const drawer = (function() {
856
+ // TODO: Use drawElements count and offset to draw only one entity
857
+
858
+ const drawPoints = () => {
859
+ if (instancing) {
860
+ gl.drawArraysInstanced(gl.POINTS, 0, positionsBuf.numItems, portions.length);
861
+ } else {
862
+ gl.drawArrays(gl.POINTS, 0, positionsBuf.numItems);
863
+ }
864
+ };
865
+
866
+ const elementsDrawer = (mode, indicesBuf) => {
867
+ indicesBuf.bindIndicesBuffer();
868
+ const count = indicesBuf.indicesCount;
869
+ const type = indicesBuf.indicesType;
870
+ return () => {
871
+ if (instancing) {
872
+ gl.drawElementsInstanced(mode, count, type, 0, portions.length);
873
+ } else {
874
+ gl.drawElements(mode, count, type, 0);
875
+ }
876
+ };
877
+ };
878
+
879
+ if (primitive === "points") {
880
+ return drawPoints;
881
+ } else if (primitive === "lines") {
882
+ if (subGeometry && subGeometry.vertices) {
883
+ return drawPoints;
884
+ } else {
885
+ return elementsDrawer(gl.LINES, indicesBuf);
886
+ }
887
+ } else { // triangles
888
+ if (subGeometry && subGeometry.vertices) {
889
+ return drawPoints;
890
+ } else if (subGeometry && edgeIndicesBuf) {
891
+ return elementsDrawer(gl.LINES, edgeIndicesBuf);
892
+ } else {
893
+ return elementsDrawer(gl.TRIANGLES, indicesBuf);
894
+ }
895
+ }
896
+ })();
897
+
898
+ gl.bindVertexArray(null);
899
+
900
+ cleanups.push(() => gl.deleteVertexArray(vao));
901
+
902
+ inputsCache[cacheKey] = () => {
903
+ gl.bindVertexArray(vao);
904
+ drawer();
905
+ gl.bindVertexArray(null);
906
+ };
907
+ }
908
+
909
+ inputsCache[cacheKey]();
910
+ };
911
+
912
+ return {
913
+ drawVertices: makeDrawer({ vertices: true }),
914
+ drawEdges: makeDrawer({ }),
915
+ drawSurface: makeDrawer(null)
916
+ };
917
+ })(),
918
+
919
+ destroy: () => {
920
+ cleanups.forEach(c => c());
921
+ cleanups.length = 0;
922
+ }
923
+ };
924
+ }
925
+ }
926
+
927
+ const lazyShaderVariable = function(name) {
928
+ const variable = {
929
+ toString: () => {
930
+ variable.needed = true;
931
+ return name;
932
+ }
933
+ };
934
+ return variable;
935
+ };
936
+
937
+ const makeVBORenderingAttributes = function(programVariables, instancing, entityOffsetsEnabled) {
938
+ const createAttribute = programVariables.createAttribute;
939
+
940
+ const attributes = {
941
+ position: createAttribute("vec3", "positionA"),
942
+ normal: createAttribute("vec3", "normalA"),
943
+ color: createAttribute("vec4", "colorA"),
944
+ pickColor: createAttribute("vec4", "pickColor"),
945
+ uV: createAttribute("vec2", "uvApremul"),
946
+ metallicRoughness: createAttribute("vec2", "metallicRoughness"),
947
+ flags: createAttribute("float", "flagsA"),
948
+ offset: entityOffsetsEnabled && createAttribute("vec3", "offset"),
949
+ modelMatrixCol: instancing && iota(3).map(i => createAttribute("vec4", "modelMatrixCol" + i)),
950
+ modelNormalMatrixCol: instancing && instancing.hasModelNormalMat && iota(3).map(i => createAttribute("vec4", "modelNormalMatrixCol" + i))
951
+ };
952
+
953
+ const uvA = lazyShaderVariable("aUv");
954
+ const viewNormal = lazyShaderVariable("viewNormal");
955
+ const worldNormal = lazyShaderVariable("worldNormal");
956
+ const uvDecodeMatrix = programVariables.createUniform("mat3", "uvDecodeMatrix");
957
+
958
+ const needNormal = () => (viewNormal.needed || worldNormal.needed);
959
+ const matrices = programVariables.createUniformBlock(
960
+ "Matrices",
961
+ {
962
+ worldMatrix: "mat4",
963
+ viewMatrix: "mat4",
964
+ projMatrix: "mat4",
965
+ positionsDecodeMatrix: "mat4",
966
+ worldNormalMatrix: "mat4",
967
+ viewNormalMatrix: "mat4"
968
+ });
969
+
970
+ return {
971
+ dontCullOnAlphaZero: true,
972
+
973
+ geometryParameters: {
974
+ attributes: {
975
+ clippable: `((int(${attributes.flags}) >> 16 & 0xF) == 1)`,
976
+ color: attributes.color,
977
+ flags: iota(4).map(i => ({ toString: () => `(int(${attributes.flags}) >> ${i * 4} & 0xF)` })),
978
+ metallicRoughness: attributes.metallicRoughness,
979
+ normal: {
980
+ view: viewNormal,
981
+ world: worldNormal
982
+ },
983
+ pickColor: attributes.pickColor,
984
+ position: {
985
+ clip: "gl_Position",
986
+ view: "viewPosition",
987
+ world: "worldPosition"
988
+ },
989
+ uv: uvA
990
+ },
991
+ projMatrix: matrices.projMatrix,
992
+ viewMatrix: matrices.viewMatrix
993
+ },
994
+
995
+ appendVertexData: (src) => {
996
+ uvA.needed && src.push(`vec2 ${uvA} = (${uvDecodeMatrix} * vec3(${attributes.uV}, 1.0)).xy;`);
997
+
998
+ const modelMatrixTransposed = attributes.modelMatrixCol && `mat4(${attributes.modelMatrixCol[0]}, ${attributes.modelMatrixCol[1]}, ${attributes.modelMatrixCol[2]}, vec4(0.0,0.0,0.0,1.0))`;
999
+ src.push(`vec4 worldPosition = ${matrices.worldMatrix} * (${matrices.positionsDecodeMatrix} * vec4(${attributes.position}, 1.0)${modelMatrixTransposed ? (" * " + modelMatrixTransposed) : ""});`);
1000
+ attributes.offset && src.push(`worldPosition.xyz = worldPosition.xyz + ${attributes.offset};`);
1001
+
1002
+ if (needNormal()) {
1003
+ const timesModelNormalMatrixT = attributes.modelNormalMatrixCol && `* mat4(${attributes.modelNormalMatrixCol[0]}, ${attributes.modelNormalMatrixCol[1]}, ${attributes.modelNormalMatrixCol[2]}, vec4(0.0,0.0,0.0,1.0))`;
1004
+ src.push(`vec4 modelNormal = vec4(${programVariables.commonLibrary.octDecode}(${attributes.normal}.xy), 0.0)${timesModelNormalMatrixT || ""};`);
1005
+ src.push(`vec3 ${worldNormal} = (${matrices.worldNormalMatrix} * modelNormal).xyz;`);
1006
+ if (viewNormal.needed) {
1007
+ src.push(`vec3 ${viewNormal} = normalize((${matrices.viewNormalMatrix} * vec4(${worldNormal}, 0.0)).xyz);`);
1008
+ }
1009
+ }
1010
+ },
1011
+
1012
+ layerTypeInputs: {
1013
+ attributes: attributes,
1014
+ matrices: matrices,
1015
+ uvDecodeMatrix: uvDecodeMatrix,
1016
+ needNormal: needNormal
1017
+ }
1018
+ };
1019
+ };