-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathgaussianSplattingMesh.ts
1607 lines (1468 loc) · 60.4 KB
/
gaussianSplattingMesh.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Scene } from "core/scene";
import type { Nullable } from "core/types";
import type { BaseTexture } from "core/Materials/Textures/baseTexture";
import { SubMesh } from "../subMesh";
import type { AbstractMesh } from "../abstractMesh";
import { Mesh } from "../mesh";
import { VertexData } from "../mesh.vertexData";
import { Matrix, TmpVectors, Vector2, Vector3 } from "core/Maths/math.vector";
import type { Quaternion } from "core/Maths/math.vector";
import { Logger } from "core/Misc/logger";
import { GaussianSplattingMaterial } from "core/Materials/GaussianSplatting/gaussianSplattingMaterial";
import { RawTexture } from "core/Materials/Textures/rawTexture";
import { Constants } from "core/Engines/constants";
import { Tools } from "core/Misc/tools";
import "core/Meshes/thinInstanceMesh";
import type { ThinEngine } from "core/Engines/thinEngine";
import { ToHalfFloat } from "core/Misc/textureTools";
import type { Material } from "core/Materials/material";
import { Scalar } from "core/Maths/math.scalar";
import { runCoroutineSync, runCoroutineAsync, createYieldingScheduler, type Coroutine } from "core/Misc/coroutine";
import { EngineStore } from "core/Engines/engineStore";
interface DelayedTextureUpdate {
covA: Uint16Array;
covB: Uint16Array;
colors: Uint8Array;
centers: Float32Array;
sh?: Uint8Array[];
}
// @internal
const unpackUnorm = (value: number, bits: number) => {
const t = (1 << bits) - 1;
return (value & t) / t;
};
// @internal
const unpack111011 = (value: number, result: Vector3) => {
result.x = unpackUnorm(value >>> 21, 11);
result.y = unpackUnorm(value >>> 11, 10);
result.z = unpackUnorm(value, 11);
};
// @internal
const unpack8888 = (value: number, result: Uint8ClampedArray) => {
result[0] = unpackUnorm(value >>> 24, 8) * 255;
result[1] = unpackUnorm(value >>> 16, 8) * 255;
result[2] = unpackUnorm(value >>> 8, 8) * 255;
result[3] = unpackUnorm(value, 8) * 255;
};
// @internal
// unpack quaternion with 2,10,10,10 format (largest element, 3x10bit element)
const unpackRot = (value: number, result: Quaternion) => {
const norm = 1.0 / (Math.sqrt(2) * 0.5);
const a = (unpackUnorm(value >>> 20, 10) - 0.5) * norm;
const b = (unpackUnorm(value >>> 10, 10) - 0.5) * norm;
const c = (unpackUnorm(value, 10) - 0.5) * norm;
const m = Math.sqrt(1.0 - (a * a + b * b + c * c));
switch (value >>> 30) {
case 0:
result.set(m, a, b, c);
break;
case 1:
result.set(a, m, b, c);
break;
case 2:
result.set(a, b, m, c);
break;
case 3:
result.set(a, b, c, m);
break;
}
};
// @internal
interface CompressedPLYChunk {
min: Vector3;
max: Vector3;
minScale: Vector3;
maxScale: Vector3;
minColor: Vector3;
maxColor: Vector3;
}
// @internal
interface PLYConversionBuffers {
buffer: ArrayBuffer;
sh?: [];
}
/**
* Representation of the types
*/
const enum PLYType {
FLOAT,
INT,
UINT,
DOUBLE,
UCHAR,
UNDEFINED,
}
/**
* Usage types of the PLY values
*/
const enum PLYValue {
MIN_X,
MIN_Y,
MIN_Z,
MAX_X,
MAX_Y,
MAX_Z,
MIN_SCALE_X,
MIN_SCALE_Y,
MIN_SCALE_Z,
MAX_SCALE_X,
MAX_SCALE_Y,
MAX_SCALE_Z,
PACKED_POSITION,
PACKED_ROTATION,
PACKED_SCALE,
PACKED_COLOR,
X,
Y,
Z,
SCALE_0,
SCALE_1,
SCALE_2,
DIFFUSE_RED,
DIFFUSE_GREEN,
DIFFUSE_BLUE,
OPACITY,
F_DC_0,
F_DC_1,
F_DC_2,
F_DC_3,
ROT_0,
ROT_1,
ROT_2,
ROT_3,
MIN_COLOR_R,
MIN_COLOR_G,
MIN_COLOR_B,
MAX_COLOR_R,
MAX_COLOR_G,
MAX_COLOR_B,
SH_0,
SH_1,
SH_2,
SH_3,
SH_4,
SH_5,
SH_6,
SH_7,
SH_8,
SH_9,
SH_10,
SH_11,
SH_12,
SH_13,
SH_14,
SH_15,
SH_16,
SH_17,
SH_18,
SH_19,
SH_20,
SH_21,
SH_22,
SH_23,
SH_24,
SH_25,
SH_26,
SH_27,
SH_28,
SH_29,
SH_30,
SH_31,
SH_32,
SH_33,
SH_34,
SH_35,
SH_36,
SH_37,
SH_38,
SH_39,
SH_40,
SH_41,
SH_42,
SH_43,
SH_44,
UNDEFINED,
}
/**
* Property field found in PLY header
*/
export type PlyProperty = {
/**
* Value usage
*/
value: PLYValue;
/**
* Value type
*/
type: PLYType;
/**
* offset in byte from te beginning of the splat
*/
offset: number;
};
/**
* meta info on Splat file
*/
export interface PLYHeader {
/**
* number of splats
*/
vertexCount: number;
/**
* number of spatial chunks for compressed ply
*/
chunkCount: number;
/**
* length in bytes of the vertex info
*/
rowVertexLength: number;
/**
* length in bytes of the chunk
*/
rowChunkLength: number;
/**
* array listing properties per vertex
*/
vertexProperties: PlyProperty[];
/**
* array listing properties per chunk
*/
chunkProperties: PlyProperty[];
/**
* data view for parsing chunks and vertices
*/
dataView: DataView;
/**
* buffer for the data view
*/
buffer: ArrayBuffer;
/**
* degree of SH coefficients
*/
shDegree: number;
/**
* number of coefficient per splat
*/
shCoefficientCount: number;
/**
* buffer for SH coefficients
*/
shBuffer: ArrayBuffer | null;
}
/**
* Class used to render a gaussian splatting mesh
*/
export class GaussianSplattingMesh extends Mesh {
private _vertexCount = 0;
private _worker: Nullable<Worker> = null;
private _frameIdLastUpdate = -1;
private _modelViewMatrix = Matrix.Identity();
private _depthMix: BigInt64Array;
private _canPostToWorker = true;
private _readyToDisplay = false;
private _covariancesATexture: Nullable<BaseTexture> = null;
private _covariancesBTexture: Nullable<BaseTexture> = null;
private _centersTexture: Nullable<BaseTexture> = null;
private _colorsTexture: Nullable<BaseTexture> = null;
private _splatPositions: Nullable<Float32Array> = null;
private _splatIndex: Nullable<Float32Array> = null;
private _shTextures: Nullable<BaseTexture[]> = null;
private _splatsData: Nullable<ArrayBuffer> = null;
private _sh: Nullable<Uint8Array[]> = null;
private readonly _keepInRam: boolean = false;
private _delayedTextureUpdate: Nullable<DelayedTextureUpdate> = null;
private _oldDirection = new Vector3();
private _useRGBACovariants = false;
private _material: Nullable<Material> = null;
private _tmpCovariances = [0, 0, 0, 0, 0, 0];
private _sortIsDirty = false;
private static _RowOutputLength = 3 * 4 + 3 * 4 + 4 + 4; // Vector3 position, Vector3 scale, 1 u8 quaternion, 1 color with alpha
private static _SH_C0 = 0.28209479177387814;
// batch size between 2 yield calls. This value is a tradeoff between updates overhead and framerate hiccups
// This step is faster the PLY conversion. So batch size can be bigger
private static _SplatBatchSize = 327680;
// batch size between 2 yield calls during the PLY to splat conversion.
private static _PlyConversionBatchSize = 32768;
private _shDegree = 0;
/**
* SH degree. 0 = no sh (default). 1 = 3 parameters. 2 = 8 parameters. 3 = 15 parameters.
*/
public get shDegree() {
return this._shDegree;
}
/**
* returns the splats data array buffer that contains in order : postions (3 floats), size (3 floats), color (4 bytes), orientation quaternion (4 bytes)
*/
public get splatsData() {
return this._splatsData;
}
/**
* Set the number of batch (a batch is 16384 splats) after which a display update is performed
* A value of 0 (default) means display update will not happens before splat is ready.
*/
public static ProgressiveUpdateAmount = 0;
/**
* Gets the covariancesA texture
*/
public get covariancesATexture() {
return this._covariancesATexture;
}
/**
* Gets the covariancesB texture
*/
public get covariancesBTexture() {
return this._covariancesBTexture;
}
/**
* Gets the centers texture
*/
public get centersTexture() {
return this._centersTexture;
}
/**
* Gets the colors texture
*/
public get colorsTexture() {
return this._colorsTexture;
}
/**
* Gets the SH textures
*/
public get shTextures() {
return this._shTextures;
}
/**
* set rendering material
*/
public override set material(value: Material) {
this._material = value;
this._material.backFaceCulling = true;
this._material.cullBackFaces = false;
value.resetDrawCache();
}
/**
* get rendering material
*/
public override get material(): Nullable<Material> {
return this._material;
}
/**
* Creates a new gaussian splatting mesh
* @param name defines the name of the mesh
* @param url defines the url to load from (optional)
* @param scene defines the hosting scene (optional)
* @param keepInRam keep datas in ram for editing purpose
*/
constructor(name: string, url: Nullable<string> = null, scene: Nullable<Scene> = null, keepInRam: boolean = false) {
super(name, scene);
const vertexData = new VertexData();
// Use an intanced quad or triangle. Triangle might be a bit faster because of less shader invocation but I didn't see any difference.
// Keeping both and use triangle for now.
// for quad, use following lines
//vertexData.positions = [-2, -2, 0, 2, -2, 0, 2, 2, 0, -2, 2, 0];
//vertexData.indices = [0, 1, 2, 0, 2, 3];
vertexData.positions = [-3, -2, 0, 3, -2, 0, 0, 4, 0];
vertexData.indices = [0, 1, 2];
vertexData.applyToMesh(this);
this.subMeshes = [];
// for quad, use following line
//new SubMesh(0, 0, 4, 0, 6, this);
new SubMesh(0, 0, 3, 0, 3, this);
this.setEnabled(false);
// webGL2 and webGPU support for RG texture with float16 is fine. not webGL1
this._useRGBACovariants = !this.getEngine().isWebGPU && this.getEngine().version === 1.0;
this._keepInRam = keepInRam;
if (url) {
this.loadFileAsync(url);
}
this._material = new GaussianSplattingMaterial(this.name + "_material", this._scene);
}
/**
* Returns the class name
* @returns "GaussianSplattingMesh"
*/
public override getClassName(): string {
return "GaussianSplattingMesh";
}
/**
* Returns the total number of vertices (splats) within the mesh
* @returns the total number of vertices
*/
public override getTotalVertices(): number {
return this._vertexCount;
}
/**
* Is this node ready to be used/rendered
* @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
* @returns true when ready
*/
public override isReady(completeCheck = false): boolean {
if (!super.isReady(completeCheck, true)) {
return false;
}
if (!this._readyToDisplay) {
// mesh is ready when worker has done at least 1 sorting
this._postToWorker(true);
return false;
}
return true;
}
/** @internal */
public _postToWorker(forced = false): void {
const frameId = this.getScene().getFrameId();
if ((forced || frameId !== this._frameIdLastUpdate) && this._worker && this._scene.activeCamera && this._canPostToWorker) {
const cameraMatrix = this._scene.activeCamera.getViewMatrix();
this.getWorldMatrix().multiplyToRef(cameraMatrix, this._modelViewMatrix);
cameraMatrix.invertToRef(TmpVectors.Matrix[0]);
this.getWorldMatrix().multiplyToRef(TmpVectors.Matrix[0], TmpVectors.Matrix[1]);
Vector3.TransformNormalToRef(Vector3.Forward(this._scene.useRightHandedSystem), TmpVectors.Matrix[1], TmpVectors.Vector3[2]);
TmpVectors.Vector3[2].normalize();
const dot = Vector3.Dot(TmpVectors.Vector3[2], this._oldDirection);
if (forced || Math.abs(dot - 1) >= 0.01) {
this._oldDirection.copyFrom(TmpVectors.Vector3[2]);
this._frameIdLastUpdate = frameId;
this._canPostToWorker = false;
this._worker.postMessage({ view: this._modelViewMatrix.m, depthMix: this._depthMix, useRightHandedSystem: this._scene.useRightHandedSystem }, [
this._depthMix.buffer,
]);
}
}
}
/**
* Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
* @param subMesh defines the subMesh to render
* @param enableAlphaMode defines if alpha mode can be changed
* @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering
* @returns the current mesh
*/
public override render(subMesh: SubMesh, enableAlphaMode: boolean, effectiveMeshReplacement?: AbstractMesh): Mesh {
this._postToWorker();
return super.render(subMesh, enableAlphaMode, effectiveMeshReplacement);
}
private static _TypeNameToEnum(name: string): PLYType {
switch (name) {
case "float":
return PLYType.FLOAT;
case "int":
return PLYType.INT;
break;
case "uint":
return PLYType.UINT;
case "double":
return PLYType.DOUBLE;
case "uchar":
return PLYType.UCHAR;
}
return PLYType.UNDEFINED;
}
private static _ValueNameToEnum(name: string): PLYValue {
switch (name) {
case "min_x":
return PLYValue.MIN_X;
case "min_y":
return PLYValue.MIN_Y;
case "min_z":
return PLYValue.MIN_Z;
case "max_x":
return PLYValue.MAX_X;
case "max_y":
return PLYValue.MAX_Y;
case "max_z":
return PLYValue.MAX_Z;
case "min_scale_x":
return PLYValue.MIN_SCALE_X;
case "min_scale_y":
return PLYValue.MIN_SCALE_Y;
case "min_scale_z":
return PLYValue.MIN_SCALE_Z;
case "max_scale_x":
return PLYValue.MAX_SCALE_X;
case "max_scale_y":
return PLYValue.MAX_SCALE_Y;
case "max_scale_z":
return PLYValue.MAX_SCALE_Z;
case "packed_position":
return PLYValue.PACKED_POSITION;
case "packed_rotation":
return PLYValue.PACKED_ROTATION;
case "packed_scale":
return PLYValue.PACKED_SCALE;
case "packed_color":
return PLYValue.PACKED_COLOR;
case "x":
return PLYValue.X;
case "y":
return PLYValue.Y;
case "z":
return PLYValue.Z;
case "scale_0":
return PLYValue.SCALE_0;
case "scale_1":
return PLYValue.SCALE_1;
case "scale_2":
return PLYValue.SCALE_2;
case "diffuse_red":
case "red":
return PLYValue.DIFFUSE_RED;
case "diffuse_green":
case "green":
return PLYValue.DIFFUSE_GREEN;
case "diffuse_blue":
case "blue":
return PLYValue.DIFFUSE_BLUE;
case "f_dc_0":
return PLYValue.F_DC_0;
case "f_dc_1":
return PLYValue.F_DC_1;
case "f_dc_2":
return PLYValue.F_DC_2;
case "f_dc_3":
return PLYValue.F_DC_3;
case "opacity":
return PLYValue.OPACITY;
case "rot_0":
return PLYValue.ROT_0;
case "rot_1":
return PLYValue.ROT_1;
case "rot_2":
return PLYValue.ROT_2;
case "rot_3":
return PLYValue.ROT_3;
case "min_r":
return PLYValue.MIN_COLOR_R;
case "min_g":
return PLYValue.MIN_COLOR_G;
case "min_b":
return PLYValue.MIN_COLOR_B;
case "max_r":
return PLYValue.MAX_COLOR_R;
case "max_g":
return PLYValue.MAX_COLOR_G;
case "max_b":
return PLYValue.MAX_COLOR_B;
case "f_rest_0":
return PLYValue.SH_0;
case "f_rest_1":
return PLYValue.SH_1;
case "f_rest_2":
return PLYValue.SH_2;
case "f_rest_3":
return PLYValue.SH_3;
case "f_rest_4":
return PLYValue.SH_4;
case "f_rest_5":
return PLYValue.SH_5;
case "f_rest_6":
return PLYValue.SH_6;
case "f_rest_7":
return PLYValue.SH_7;
case "f_rest_8":
return PLYValue.SH_8;
case "f_rest_9":
return PLYValue.SH_9;
case "f_rest_10":
return PLYValue.SH_10;
case "f_rest_11":
return PLYValue.SH_11;
case "f_rest_12":
return PLYValue.SH_12;
case "f_rest_13":
return PLYValue.SH_13;
case "f_rest_14":
return PLYValue.SH_14;
case "f_rest_15":
return PLYValue.SH_15;
case "f_rest_16":
return PLYValue.SH_16;
case "f_rest_17":
return PLYValue.SH_17;
case "f_rest_18":
return PLYValue.SH_18;
case "f_rest_19":
return PLYValue.SH_19;
case "f_rest_20":
return PLYValue.SH_20;
case "f_rest_21":
return PLYValue.SH_21;
case "f_rest_22":
return PLYValue.SH_22;
case "f_rest_23":
return PLYValue.SH_23;
case "f_rest_24":
return PLYValue.SH_24;
case "f_rest_25":
return PLYValue.SH_25;
case "f_rest_26":
return PLYValue.SH_26;
case "f_rest_27":
return PLYValue.SH_27;
case "f_rest_28":
return PLYValue.SH_28;
case "f_rest_29":
return PLYValue.SH_29;
case "f_rest_30":
return PLYValue.SH_30;
case "f_rest_31":
return PLYValue.SH_31;
case "f_rest_32":
return PLYValue.SH_32;
case "f_rest_33":
return PLYValue.SH_33;
case "f_rest_34":
return PLYValue.SH_34;
case "f_rest_35":
return PLYValue.SH_35;
case "f_rest_36":
return PLYValue.SH_36;
case "f_rest_37":
return PLYValue.SH_37;
case "f_rest_38":
return PLYValue.SH_38;
case "f_rest_39":
return PLYValue.SH_39;
case "f_rest_40":
return PLYValue.SH_40;
case "f_rest_41":
return PLYValue.SH_41;
case "f_rest_42":
return PLYValue.SH_42;
case "f_rest_43":
return PLYValue.SH_43;
case "f_rest_44":
return PLYValue.SH_44;
}
return PLYValue.UNDEFINED;
}
/**
* Parse a PLY file header and returns metas infos on splats and chunks
* @param data the loaded buffer
* @returns a PLYHeader
*/
static ParseHeader(data: ArrayBuffer): PLYHeader | null {
const ubuf = new Uint8Array(data);
const header = new TextDecoder().decode(ubuf.slice(0, 1024 * 10));
const headerEnd = "end_header\n";
const headerEndIndex = header.indexOf(headerEnd);
if (headerEndIndex < 0 || !header) {
// standard splat
return null;
}
const vertexCount = parseInt(/element vertex (\d+)\n/.exec(header)![1]);
const chunkElement = /element chunk (\d+)\n/.exec(header);
let chunkCount = 0;
if (chunkElement) {
chunkCount = parseInt(chunkElement[1]);
}
let rowVertexOffset = 0;
let rowChunkOffset = 0;
const offsets: Record<string, number> = {
double: 8,
int: 4,
uint: 4,
float: 4,
short: 2,
ushort: 2,
uchar: 1,
list: 0,
};
const enum ElementMode {
Vertex = 0,
Chunk = 1,
}
let chunkMode = ElementMode.Chunk;
const vertexProperties: PlyProperty[] = [];
const chunkProperties: PlyProperty[] = [];
const filtered = header.slice(0, headerEndIndex).split("\n");
let shDegree = 0;
for (const prop of filtered) {
if (prop.startsWith("property ")) {
const [, typeName, name] = prop.split(" ");
const value = GaussianSplattingMesh._ValueNameToEnum(name);
// SH degree 1,2 or 3 for 9, 24 or 45 values
if (value >= PLYValue.SH_44) {
shDegree = 3;
} else if (value >= PLYValue.SH_24) {
shDegree = 2;
} else if (value >= PLYValue.SH_8) {
shDegree = 1;
}
const type = GaussianSplattingMesh._TypeNameToEnum(typeName);
if (chunkMode == ElementMode.Chunk) {
chunkProperties.push({ value, type, offset: rowChunkOffset });
rowChunkOffset += offsets[typeName];
} else if (chunkMode == ElementMode.Vertex) {
vertexProperties.push({ value, type, offset: rowVertexOffset });
rowVertexOffset += offsets[typeName];
}
if (!offsets[typeName]) {
Logger.Warn(`Unsupported property type: ${typeName}.`);
}
} else if (prop.startsWith("element ")) {
const [, type] = prop.split(" ");
if (type == "chunk") {
chunkMode = ElementMode.Chunk;
} else if (type == "vertex") {
chunkMode = ElementMode.Vertex;
}
}
}
const dataView = new DataView(data, headerEndIndex + headerEnd.length);
const buffer = new ArrayBuffer(GaussianSplattingMesh._RowOutputLength * vertexCount);
let shBuffer = null;
let shCoefficientCount = 0;
if (shDegree) {
const shVectorCount = (shDegree + 1) * (shDegree + 1) - 1;
shCoefficientCount = shVectorCount * 3;
shBuffer = new ArrayBuffer(shCoefficientCount * vertexCount);
}
return {
vertexCount: vertexCount,
chunkCount: chunkCount,
rowVertexLength: rowVertexOffset,
rowChunkLength: rowChunkOffset,
vertexProperties: vertexProperties,
chunkProperties: chunkProperties,
dataView: dataView,
buffer: buffer,
shDegree: shDegree,
shCoefficientCount: shCoefficientCount,
shBuffer: shBuffer,
};
}
private static _GetCompressedChunks(header: PLYHeader, offset: { value: number }): Array<CompressedPLYChunk> | null {
if (!header.chunkCount) {
return null;
}
const dataView = header.dataView;
const compressedChunks = new Array<CompressedPLYChunk>(header.chunkCount);
for (let i = 0; i < header.chunkCount; i++) {
const currentChunk = {
min: new Vector3(),
max: new Vector3(),
minScale: new Vector3(),
maxScale: new Vector3(),
minColor: new Vector3(0, 0, 0),
maxColor: new Vector3(1, 1, 1),
};
compressedChunks[i] = currentChunk;
for (let propertyIndex = 0; propertyIndex < header.chunkProperties.length; propertyIndex++) {
const property = header.chunkProperties[propertyIndex];
let value;
switch (property.type) {
case PLYType.FLOAT:
value = dataView.getFloat32(property.offset + offset.value, true);
break;
default:
continue;
}
switch (property.value) {
case PLYValue.MIN_X:
currentChunk.min.x = value;
break;
case PLYValue.MIN_Y:
currentChunk.min.y = value;
break;
case PLYValue.MIN_Z:
currentChunk.min.z = value;
break;
case PLYValue.MAX_X:
currentChunk.max.x = value;
break;
case PLYValue.MAX_Y:
currentChunk.max.y = value;
break;
case PLYValue.MAX_Z:
currentChunk.max.z = value;
break;
case PLYValue.MIN_SCALE_X:
currentChunk.minScale.x = value;
break;
case PLYValue.MIN_SCALE_Y:
currentChunk.minScale.y = value;
break;
case PLYValue.MIN_SCALE_Z:
currentChunk.minScale.z = value;
break;
case PLYValue.MAX_SCALE_X:
currentChunk.maxScale.x = value;
break;
case PLYValue.MAX_SCALE_Y:
currentChunk.maxScale.y = value;
break;
case PLYValue.MAX_SCALE_Z:
currentChunk.maxScale.z = value;
break;
case PLYValue.MIN_COLOR_R:
currentChunk.minColor.x = value;
break;
case PLYValue.MIN_COLOR_G:
currentChunk.minColor.y = value;
break;
case PLYValue.MIN_COLOR_B:
currentChunk.minColor.z = value;
break;
case PLYValue.MAX_COLOR_R:
currentChunk.maxColor.x = value;
break;
case PLYValue.MAX_COLOR_G:
currentChunk.maxColor.y = value;
break;
case PLYValue.MAX_COLOR_B:
currentChunk.maxColor.z = value;
break;
}
}
offset.value += header.rowChunkLength;
}
return compressedChunks;
}
private static _GetSplat(header: PLYHeader, index: number, compressedChunks: Array<CompressedPLYChunk> | null, offset: { value: number }): void {
const q = TmpVectors.Quaternion[0];
const temp3 = TmpVectors.Vector3[0];
const rowOutputLength = GaussianSplattingMesh._RowOutputLength;
const buffer = header.buffer;
const dataView = header.dataView;
const position = new Float32Array(buffer, index * rowOutputLength, 3);
const scale = new Float32Array(buffer, index * rowOutputLength + 12, 3);
const rgba = new Uint8ClampedArray(buffer, index * rowOutputLength + 24, 4);
const rot = new Uint8ClampedArray(buffer, index * rowOutputLength + 28, 4);
let sh = null;
if (header.shBuffer) {
sh = new Uint8ClampedArray(header.shBuffer, index * header.shCoefficientCount, header.shCoefficientCount);
}
const chunkIndex = index >> 8;
let r0: number = 255;
let r1: number = 0;
let r2: number = 0;
let r3: number = 0;
for (let propertyIndex = 0; propertyIndex < header.vertexProperties.length; propertyIndex++) {
const property = header.vertexProperties[propertyIndex];
let value;
switch (property.type) {
case PLYType.FLOAT:
value = dataView.getFloat32(offset.value + property.offset, true);
break;
case PLYType.INT:
value = dataView.getInt32(offset.value + property.offset, true);
break;
case PLYType.UINT:
value = dataView.getUint32(offset.value + property.offset, true);
break;
case PLYType.DOUBLE:
value = dataView.getFloat64(offset.value + property.offset, true);
break;
case PLYType.UCHAR:
value = dataView.getUint8(offset.value + property.offset);
break;
default:
continue;
}
switch (property.value) {
case PLYValue.PACKED_POSITION:
{
const compressedChunk = compressedChunks![chunkIndex];
unpack111011(value, temp3);
position[0] = Scalar.Lerp(compressedChunk.min.x, compressedChunk.max.x, temp3.x);
position[1] = Scalar.Lerp(compressedChunk.min.y, compressedChunk.max.y, temp3.y);
position[2] = Scalar.Lerp(compressedChunk.min.z, compressedChunk.max.z, temp3.z);
}
break;
case PLYValue.PACKED_ROTATION:
{
unpackRot(value, q);
r0 = q.w;
r1 = -q.z;
r2 = q.y;
r3 = -q.x;
}
break;
case PLYValue.PACKED_SCALE:
{
const compressedChunk = compressedChunks![chunkIndex];
unpack111011(value, temp3);
scale[0] = Math.exp(Scalar.Lerp(compressedChunk.minScale.x, compressedChunk.maxScale.x, temp3.x));
scale[1] = Math.exp(Scalar.Lerp(compressedChunk.minScale.y, compressedChunk.maxScale.y, temp3.y));
scale[2] = Math.exp(Scalar.Lerp(compressedChunk.minScale.z, compressedChunk.maxScale.z, temp3.z));
}
break;
case PLYValue.PACKED_COLOR:
{
const compressedChunk = compressedChunks![chunkIndex];
unpack8888(value, rgba);
rgba[0] = Scalar.Lerp(compressedChunk.minColor.x, compressedChunk.maxColor.x, rgba[0] / 255) * 255;
rgba[1] = Scalar.Lerp(compressedChunk.minColor.y, compressedChunk.maxColor.y, rgba[1] / 255) * 255;
rgba[2] = Scalar.Lerp(compressedChunk.minColor.z, compressedChunk.maxColor.z, rgba[2] / 255) * 255;
}
break;
case PLYValue.X:
position[0] = value;
break;
case PLYValue.Y:
position[1] = value;
break;
case PLYValue.Z:
position[2] = value;
break;
case PLYValue.SCALE_0:
scale[0] = Math.exp(value);
break;
case PLYValue.SCALE_1:
scale[1] = Math.exp(value);
break;
case PLYValue.SCALE_2:
scale[2] = Math.exp(value);
break;
case PLYValue.DIFFUSE_RED:
rgba[0] = value;
break;
case PLYValue.DIFFUSE_GREEN:
rgba[1] = value;
break;
case PLYValue.DIFFUSE_BLUE:
rgba[2] = value;
break;
case PLYValue.F_DC_0:
rgba[0] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
break;
case PLYValue.F_DC_1:
rgba[1] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
break;
case PLYValue.F_DC_2:
rgba[2] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
break;
case PLYValue.F_DC_3:
rgba[3] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
break;
case PLYValue.OPACITY:
rgba[3] = (1 / (1 + Math.exp(-value))) * 255;
break;
case PLYValue.ROT_0:
r0 = value;