/
GltfReader.ts
2047 lines (1739 loc) · 80.5 KB
/
GltfReader.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Tiles
*/
import {
assert, ByteStream, compareBooleans, compareNumbers, compareStrings, Dictionary, JsonUtils, Logger, utf8ToString,
} from "@itwin/core-bentley";
import {
Angle, IndexedPolyface, Matrix3d, Point2d, Point3d, Point4d, Polyface, Range2d, Range3d, Transform, Vector3d,
} from "@itwin/core-geometry";
import {
AxisAlignedBox3d, BatchType, ColorDef, ElementAlignedBox3d, Feature, FeatureIndex, FeatureIndexType, FeatureTable, FillFlags, GlbHeader, ImageSource, LinePixels, MeshEdge,
MeshEdges, MeshPolyline, MeshPolylineList, OctEncodedNormal, PackedFeatureTable, QParams2d, QParams3d, QPoint2dList,
QPoint3dList, Quantization, RenderMaterial, RenderMode, RenderTexture, TextureMapping, TextureTransparency, TileFormat, TileReadStatus, ViewFlagOverrides,
} from "@itwin/core-common";
import { IModelConnection } from "../IModelConnection";
import { IModelApp } from "../IModelApp";
import { GraphicBranch } from "../render/GraphicBranch";
import { PickableGraphicOptions } from "../render/GraphicBuilder";
import { InstancedGraphicParams } from "../render/InstancedGraphicParams";
import { RealityMeshParams } from "../render/RealityMeshParams";
import { Mesh } from "../render/primitives/mesh/MeshPrimitives";
import { Triangle } from "../render/primitives/Primitives";
import { RenderGraphic } from "../render/RenderGraphic";
import { RenderSystem } from "../render/RenderSystem";
import { decodeMeshoptBuffer, RealityTileGeometry, TileContent } from "./internal";
import type { DracoLoader, DracoMesh } from "@loaders.gl/draco";
import { CreateRenderMaterialArgs } from "../render/CreateRenderMaterialArgs";
import { DisplayParams } from "../common/render/primitives/DisplayParams";
import { FrontendLoggerCategory } from "../common/FrontendLoggerCategory";
import { getImageSourceFormatForMimeType, imageBitmapFromImageSource, imageElementFromImageSource, tryImageElementFromUrl } from "../common/ImageUtil";
import { MeshPrimitiveType } from "../common/render/primitives/MeshPrimitive";
import { PointCloudArgs } from "../render/primitives/PointCloudPrimitive";
import { TextureImageSource } from "../common/render/TextureParams";
import {
DracoMeshCompression, getGltfNodeMeshIds, Gltf2Node, GltfAccessor, GltfBuffer, GltfBufferViewProps, GltfDataType, GltfDictionary, gltfDictionaryIterator, GltfDocument, GltfId,
GltfImage, GltfMaterial, GltfMesh, GltfMeshMode, GltfMeshPrimitive, GltfNode, GltfSampler, GltfScene, GltfTechniqueState, GltfTexture, GltfWrapMode, isGltf1Material, traverseGltfNodes,
} from "../common/gltf/GltfSchema";
/* eslint-disable no-restricted-syntax */
/** @internal */
export type GltfDataBuffer = Uint8Array | Uint16Array | Uint32Array | Float32Array;
/**
* A chunk of binary data exposed as a typed array.
* The count member indicates how many elements exist. This may be less than this.buffer.length due to padding added to the
* binary stream to ensure correct alignment.
* @internal
*/
export class GltfBufferData {
public readonly buffer: GltfDataBuffer;
public readonly count: number;
public constructor(buffer: GltfDataBuffer, count: number) {
this.buffer = buffer;
this.count = count;
}
/**
* Create a GltfBufferData of the desired type. The actual type may differ from the desired type - for example, small 32-bit integers
* may be represented as 8-bit or 16-bit integers instead.
* If the actual data type is not convertible to the desired type, this function returns undefined.
*/
public static create(bytes: Uint8Array, actualType: GltfDataType, expectedType: GltfDataType, count: number): GltfBufferData | undefined {
if (expectedType !== actualType) {
// Some data is stored in smaller data types to save space if no values exceed the maximum of the smaller type.
switch (expectedType) {
case GltfDataType.Float:
case GltfDataType.UnsignedByte:
return undefined;
case GltfDataType.UnsignedShort:
if (GltfDataType.UnsignedByte !== actualType)
return undefined;
break;
case GltfDataType.UInt32:
if (GltfDataType.UnsignedByte !== actualType && GltfDataType.UnsignedShort !== actualType)
return undefined;
break;
}
}
const data = this.createDataBuffer(bytes, actualType);
return undefined !== data ? new GltfBufferData(data, count) : undefined;
}
private static createDataBuffer(bytes: Uint8Array, actualType: GltfDataType): GltfDataBuffer | undefined {
// NB: Endianness of typed array data is determined by the 'platform byte order'. Actual data is always little-endian.
// We are assuming little-endian platform. If we find a big-endian platform, we'll need to use a DataView instead.
switch (actualType) {
case GltfDataType.UnsignedByte:
return bytes;
case GltfDataType.UnsignedShort:
return new Uint16Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 2);
case GltfDataType.UInt32:
return new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
case GltfDataType.Float:
return new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
default:
return undefined;
}
}
}
/**
* A view of a chunk of glTF binary data containing an array of elements of a specific data type.
* The count member indicates how many elements exist; this may be smaller than this.data.length.
* The count member may also indicate the number of elements of a type containing more than one value of the
* underlying type. For example, a buffer of 4 32-bit floating point 'vec2' elements will have a count of 4,
* but its data member will contain 8 32-bit floating point values (2 per vec2).
* The accessor member may contain additional JSON data specific to a particular buffer.
* @internal
*/
class GltfBufferView {
public readonly data: Uint8Array;
public readonly count: number;
public readonly type: GltfDataType;
public readonly accessor: GltfAccessor;
public readonly stride: number;
public get byteLength(): number { return this.data.length; }
public constructor(data: Uint8Array, count: number, type: GltfDataType, accessor: GltfAccessor, stride: number) {
this.data = data;
this.count = count;
this.type = type;
this.accessor = accessor;
this.stride = stride;
}
public toBufferData(desiredType: GltfDataType): GltfBufferData | undefined {
return GltfBufferData.create(this.data, this.type, desiredType, this.count);
}
}
/** The result of [[GltfReader.read]].
* @internal
*/
export interface GltfReaderResult extends TileContent {
readStatus: TileReadStatus;
range?: AxisAlignedBox3d;
}
/** Data required for creating a [[GltfReader]] capable of deserializing [glTF](https://www.khronos.org/gltf/).
* @internal
*/
export class GltfReaderProps {
public readonly version: number;
public readonly glTF: GltfDocument;
public readonly yAxisUp: boolean;
public readonly binaryData?: Uint8Array;
public readonly baseUrl?: URL;
private constructor(glTF: GltfDocument, version: number, yAxisUp: boolean, binaryData: Uint8Array | undefined, baseUrl?: URL | undefined) {
this.version = version;
this.glTF = glTF;
this.binaryData = binaryData;
this.yAxisUp = yAxisUp;
this.baseUrl = baseUrl;
}
/** Attempt to construct a new GltfReaderProps from the binary data beginning at the supplied stream's current read position. */
public static create(source: Uint8Array | GltfDocument, yAxisUp: boolean = false, baseUrl?: URL): GltfReaderProps | undefined {
let version: number;
let json: GltfDocument;
let binaryData: Uint8Array | undefined;
if (source instanceof Uint8Array) {
// It may be JSON - check for magic indicating glb.
const buffer = ByteStream.fromUint8Array(source);
if (TileFormat.Gltf !== buffer.readUint32()) {
try {
const utf8Json = utf8ToString(source);
if (!utf8Json)
return undefined;
json = JSON.parse(utf8Json);
version = 2;
} catch (_) {
return undefined;
}
} else {
buffer.reset();
const header = new GlbHeader(buffer);
if (!header.isValid)
return undefined;
version = header.version;
if (header.binaryChunk)
binaryData = new Uint8Array(source.buffer, source.byteOffset + header.binaryChunk.offset, header.binaryChunk.length);
try {
const jsonBytes = new Uint8Array(source.buffer, source.byteOffset + header.jsonChunk.offset, header.jsonChunk.length);
const jsonStr = utf8ToString(jsonBytes);
if (undefined === jsonStr)
return undefined;
json = JSON.parse(jsonStr);
} catch (_) {
return undefined;
}
}
} else {
version = 2; // ###TODO verify against source.asset?.version
json = source;
}
// asset is required in glTF 2, optional in glTF 1
const asset = JsonUtils.asObject(json.asset);
if (version === 2 && !asset)
return undefined;
const glTF: GltfDocument = {
asset,
scene: JsonUtils.asString(json.scene),
extensions: JsonUtils.asObject(json.extensions),
extensionsUsed: JsonUtils.asArray(json.extensionsUsed),
extensionsRequired: JsonUtils.asArray(json.extensionsRequired),
accessors: JsonUtils.asObject(json.accessors),
buffers: JsonUtils.asObject(json.buffers),
bufferViews: JsonUtils.asObject(json.bufferViews),
images: JsonUtils.asObject(json.images),
materials: JsonUtils.asObject(json.materials),
meshes: JsonUtils.asObject(json.meshes),
nodes: JsonUtils.asObject(json.nodes),
samplers: JsonUtils.asObject(json.samplers),
scenes: JsonUtils.asObject(json.scenes),
textures: JsonUtils.asObject(json.textures),
techniques: JsonUtils.asObject(json.techniques),
};
return glTF.meshes ? new GltfReaderProps(glTF, version, yAxisUp, binaryData, baseUrl) : undefined;
}
}
/** The GltfMeshData contains the raw GLTF mesh data. If the data is suitable to create a [[RealityMesh]] directly, basically in the quantized format produced by
* ContextCapture, then a RealityMesh is created directly from this data. Otherwise, the mesh primitive is populated from the raw data and a MeshPrimitive
* is generated. The MeshPrimitve path is much less efficient but should be rarely used.
*
* @internal
*/
export class GltfMeshData {
public primitive: Mesh; // Populated with vertex and indices only if the mesh cannot be represented as [[RealityMesh]]
public pointQParams?: QParams3d;
public points?: Uint16Array;
public pointRange?: Range3d;
public normals?: Uint16Array;
public uvQParams?: QParams2d;
public uvs?: Uint16Array;
public uvRange?: Range2d;
public indices?: Uint8Array | Uint16Array | Uint32Array;
public readonly type = "mesh" as const;
public constructor(props: Mesh) {
this.primitive = props;
}
}
interface GltfPointCloud extends PointCloudArgs {
readonly type: "pointcloud";
pointRange: Range3d;
}
type GltfPrimitiveData = GltfMeshData | GltfPointCloud;
/** A function that returns true if deserialization of the data supplied by the reader should abort.
* @internal
*/
export type ShouldAbortReadGltf = (reader: GltfReader) => boolean;
const emptyDict = { };
function colorFromJson(values: number[]): ColorDef {
return ColorDef.from(values[0] * 255, values[1] * 255, values[2] * 255, (1.0 - values[3]) * 255);
}
function colorFromMaterial(material: GltfMaterial, isTransparent: boolean): ColorDef {
let color = ColorDef.white;
if (isGltf1Material(material)) {
if (material.values?.color && Array.isArray(material.values.color))
color = colorFromJson(material.values.color);
} else if (material.extensions?.KHR_techniques_webgl?.values?.u_color) {
color = colorFromJson(material.extensions.KHR_techniques_webgl.values.u_color);
} else if (material.pbrMetallicRoughness?.baseColorFactor) {
color = colorFromJson(material.pbrMetallicRoughness.baseColorFactor);
}
// SPEC: Opaque materials ignore any alpha channel.
if (!isTransparent)
color = color.withTransparency(0);
return color;
}
function trsMatrix(translation: [number, number, number] | undefined, rotation: [number, number, number, number] | undefined, scale: [number, number, number] | undefined, result?: Transform): Transform {
// SPEC: To compose the local transformation matrix, TRS properties MUST be converted to matrices and postmultiplied in the T * R * S order;
// first the scale is applied to the vertices, then the rotation, and then the translation.
const scaleTf = Transform.createRefs(undefined, scale ? Matrix3d.createScale(scale[0], scale[1], scale[2]) : Matrix3d.identity);
const rotTf = Transform.createRefs(undefined, rotation ? Matrix3d.createFromQuaternion(Point4d.create(rotation[0], rotation[1], rotation[2], rotation[3])) : Matrix3d.identity);
rotTf.matrix.transposeInPlace(); // See comment on Matrix3d.createFromQuaternion
const transTf = Transform.createTranslation(translation ? new Point3d(translation[0], translation[1], translation[2]) : Point3d.createZero());
const tf = rotTf.multiplyTransformTransform(scaleTf, result);
transTf.multiplyTransformTransform(tf, tf);
return tf;
}
class TransformStack {
private readonly _stack: Array<Transform | undefined> = [];
public constructor(transform?: Transform) {
if (transform)
this._stack.push(transform);
}
public get transform(): Transform | undefined {
return this._stack.length > 0 ? this._stack[this._stack.length - 1] : undefined;
}
public get isEmpty(): boolean {
return 0 === this._stack.length;
}
public push(node: GltfNode): void {
let nodeTransform;
if (node.matrix) {
const origin = Point3d.create(node.matrix[12], node.matrix[13], node.matrix[14]);
const matrix = Matrix3d.createRowValues(
node.matrix[0], node.matrix[4], node.matrix[8],
node.matrix[1], node.matrix[5], node.matrix[9],
node.matrix[2], node.matrix[6], node.matrix[10],
);
nodeTransform = Transform.createOriginAndMatrix(origin, matrix);
} else if (node.rotation || node.scale || node.translation) {
nodeTransform = trsMatrix(node.translation, node.rotation, node.scale);
}
const top = this.transform;
if (!top)
this._stack.push(nodeTransform);
else
this._stack.push(nodeTransform ? top.multiplyTransformTransform(nodeTransform) : top);
}
public pop(): void {
assert(this._stack.length > 0);
this._stack.pop();
}
}
/** Arguments to [[GltfReader]] constructor.
* @internal
*/
export interface GltfReaderArgs {
/** Properties of the glTF source. */
props: GltfReaderProps;
/** The iModel with which the graphics are to be associated. */
iModel: IModelConnection;
/** If true, create 2d graphics. */
is2d?: boolean;
/** The render system that will produce the graphics. Defaults to [[IModelApp.renderSystem]]. */
system?: RenderSystem;
/** The type of batch to create. Defaults to [BatchType.Primary]($common).
* @see [[RenderSystem.createBatch]].
*/
type?: BatchType;
/** An optional function that, if supplied, is invoked periodically to determine if the process of producing graphics from the glTF should terminate early. */
shouldAbort?: ShouldAbortReadGltf;
/** If true, each vertex in the graphics should belong to exactly one triangle. This is less efficient than sharing vertices between adjoining triangles, but
* sometimes required - for example, for [ViewFlags.wiremesh]($common).
*/
deduplicateVertices?: boolean;
/** If true, the graphics produced will always use a [[VertexTable]]; otherwise, where possible a [[RealityMeshParams]] will be used instead.
* Reality meshes are simpler but do not support some features like lighting.
*/
vertexTableRequired?: boolean;
}
interface TextureKey {
readonly id: GltfId;
readonly isTransparent: boolean;
}
function compareTextureKeys(lhs: TextureKey, rhs: TextureKey): number {
const cmp = compareBooleans(lhs.isTransparent, rhs.isTransparent);
if (0 !== cmp)
return cmp;
assert(typeof lhs.id === typeof rhs.id);
if ("string" === typeof lhs.id) {
assert("string" === typeof rhs.id);
return compareStrings(lhs.id, rhs.id);
}
assert("number" === typeof lhs.id && "number" === typeof rhs.id);
return compareNumbers(lhs.id, rhs.id);
}
/** Deserializes [glTF](https://www.khronos.org/gltf/).
* @internal
*/
export abstract class GltfReader {
protected readonly _glTF: GltfDocument;
protected readonly _version: number;
protected readonly _iModel: IModelConnection;
protected readonly _is3d: boolean;
protected readonly _system: RenderSystem;
protected readonly _returnToCenter?: Point3d;
protected readonly _yAxisUp: boolean;
protected readonly _baseUrl?: URL;
protected readonly _type: BatchType;
protected readonly _deduplicateVertices: boolean;
protected readonly _vertexTableRequired: boolean;
private readonly _canceled?: ShouldAbortReadGltf;
protected readonly _sceneNodes: GltfId[];
protected _computedContentRange?: ElementAlignedBox3d;
private readonly _resolvedTextures = new Dictionary<TextureKey, RenderTexture | false>((lhs, rhs) => compareTextureKeys(lhs, rhs));
private readonly _dracoMeshes = new Map<DracoMeshCompression, DracoMesh>();
private _containsPointCloud = false;
protected get _nodes(): GltfDictionary<GltfNode> { return this._glTF.nodes ?? emptyDict; }
protected get _meshes(): GltfDictionary<GltfMesh> { return this._glTF.meshes ?? emptyDict; }
protected get _accessors(): GltfDictionary<GltfAccessor> { return this._glTF.accessors ?? emptyDict; }
protected get _bufferViews(): GltfDictionary<GltfBufferViewProps & { resolvedBuffer?: Uint8Array }> { return this._glTF.bufferViews ?? emptyDict; }
protected get _materials(): GltfDictionary<GltfMaterial> { return this._glTF.materials ?? emptyDict; }
protected get _samplers(): GltfDictionary<GltfSampler> { return this._glTF.samplers ?? emptyDict; }
protected get _textures(): GltfDictionary<GltfTexture> { return this._glTF.textures ?? emptyDict; }
protected get _images(): GltfDictionary<GltfImage & { resolvedImage?: TextureImageSource }> { return this._glTF.images ?? emptyDict; }
protected get _buffers(): GltfDictionary<GltfBuffer & { resolvedBuffer?: Uint8Array }> { return this._glTF.buffers ?? emptyDict; }
/** Asynchronously deserialize the tile data and return the result. */
public abstract read(): Promise<GltfReaderResult>;
protected get _isCanceled(): boolean { return undefined !== this._canceled && this._canceled(this); }
protected get _isVolumeClassifier(): boolean { return BatchType.VolumeClassifier === this._type; }
/** Traverse the nodes specified by their Ids, recursing into their child nodes.
* @param nodeIds The Ids of the nodes to traverse.
* @throws Error if a node appears more than once during traversal
*/
public traverseNodes(nodeIds: Iterable<GltfId>): Iterable<GltfNode> {
return traverseGltfNodes(nodeIds, this._nodes, new Set<GltfId>());
}
/** Traverse the nodes specified by their scene, recursing into their child nodes.
* @throws Error if a node appears more than once during traversal
*/
public traverseScene(): Iterable<GltfNode> {
return this.traverseNodes(this._sceneNodes);
}
protected get viewFlagOverrides(): ViewFlagOverrides | undefined {
return undefined;
}
private getTileTransform(transformToRoot?: Transform, pseudoRtcBias?: Vector3d): Transform | undefined {
let transform;
if (this._returnToCenter || pseudoRtcBias || this._yAxisUp || transformToRoot) {
if (this._returnToCenter)
transform = Transform.createTranslation(this._returnToCenter.clone());
else if (pseudoRtcBias)
transform = Transform.createTranslationXYZ(pseudoRtcBias.x, pseudoRtcBias.y, pseudoRtcBias.z);
else
transform = Transform.createIdentity();
if (this._yAxisUp)
transform = transform.multiplyTransformMatrix3d(Matrix3d.createRotationAroundVector(Vector3d.create(1.0, 0.0, 0.0), Angle.createRadians(Angle.piOver2Radians)) as Matrix3d);
if (transformToRoot)
transform = transformToRoot.multiplyTransformTransform(transform);
}
return transform;
}
protected readGltfAndCreateGraphics(isLeaf: boolean, featureTable: FeatureTable | undefined, contentRange: ElementAlignedBox3d | undefined, transformToRoot?: Transform, pseudoRtcBias?: Vector3d, instances?: InstancedGraphicParams): GltfReaderResult {
if (this._isCanceled)
return { readStatus: TileReadStatus.Canceled, isLeaf };
// If contentRange was not supplied, we will compute it as we read the meshes.
if (!contentRange)
this._computedContentRange = contentRange = Range3d.createNull();
else
this._computedContentRange = undefined;
// ###TODO this looks like a hack? Why does it assume the first node's transform is special, or that the transform will be specified as a matrix instead of translation+rot+scale?
if (this._returnToCenter || this._nodes[0]?.matrix || (pseudoRtcBias && pseudoRtcBias.magnitude() < 1.0E5))
pseudoRtcBias = undefined;
const transformStack = new TransformStack();
const renderGraphicList: RenderGraphic[] = [];
let readStatus: TileReadStatus = TileReadStatus.InvalidTileData;
for (const nodeKey of this._sceneNodes) {
assert(transformStack.isEmpty);
const node = this._nodes[nodeKey];
if (node && TileReadStatus.Success !== (readStatus = this.readNodeAndCreateGraphics(renderGraphicList, node, featureTable, transformStack, instances, pseudoRtcBias)))
return { readStatus, isLeaf };
}
if (0 === renderGraphicList.length)
return { readStatus: TileReadStatus.InvalidTileData, isLeaf };
let renderGraphic: RenderGraphic | undefined;
if (1 === renderGraphicList.length)
renderGraphic = renderGraphicList[0];
else
renderGraphic = this._system.createGraphicList(renderGraphicList);
const transform = this.getTileTransform(transformToRoot, pseudoRtcBias);
// Compute range in tileset/world space.
let range = contentRange;
const invTransform = transform?.inverse();
if (invTransform)
range = invTransform.multiplyRange(contentRange);
// The batch range needs to be in tile coordinate space.
// If we computed the content range ourselves, it's already in tile space.
// If the content range was supplied by the caller, it's in tileset space and needs to be transformed to tile space.
if (featureTable)
renderGraphic = this._system.createBatch(renderGraphic, PackedFeatureTable.pack(featureTable), this._computedContentRange ? contentRange : range);
const viewFlagOverrides = this.viewFlagOverrides;
if (transform || viewFlagOverrides) {
const branch = new GraphicBranch(true);
if (viewFlagOverrides)
branch.setViewFlagOverrides(viewFlagOverrides);
branch.add(renderGraphic);
renderGraphic = this._system.createBranch(branch, transform ?? Transform.createIdentity());
}
return {
readStatus,
isLeaf,
contentRange,
range,
graphic: renderGraphic,
containsPointCloud: this._containsPointCloud,
};
}
public readGltfAndCreateGeometry(transformToRoot?: Transform, needNormals = false, needParams = false): RealityTileGeometry {
const transformStack = new TransformStack(this.getTileTransform(transformToRoot));
const polyfaces: Polyface[] = [];
for (const nodeKey of this._sceneNodes) {
const node = this._nodes[nodeKey];
if (node)
this.readNodeAndCreatePolyfaces(polyfaces, node, transformStack, needNormals, needParams);
}
return { polyfaces };
}
private graphicFromMeshData(gltfMesh: GltfPrimitiveData, instances?: InstancedGraphicParams): RenderGraphic | undefined {
if ("pointcloud" === gltfMesh.type)
return this._system.createPointCloud(gltfMesh, this._iModel);
if (!gltfMesh.points || !gltfMesh.pointRange)
return gltfMesh.primitive.getGraphics(this._system, instances);
const realityMeshPrimitive = (this._vertexTableRequired || instances) ? undefined : RealityMeshParams.fromGltfMesh(gltfMesh);
if (realityMeshPrimitive) {
const realityMesh = this._system.createRealityMesh(realityMeshPrimitive);
if (realityMesh)
return realityMesh;
}
const mesh = gltfMesh.primitive;
const pointCount = gltfMesh.points.length / 3;
assert(mesh.points instanceof QPoint3dList);
mesh.points.fromTypedArray(gltfMesh.pointRange, gltfMesh.points);
if (mesh.triangles && gltfMesh.indices)
mesh.triangles.addFromTypedArray(gltfMesh.indices);
if (gltfMesh.uvs && gltfMesh.uvRange && gltfMesh.uvQParams) {
/** This is ugly and inefficient... unnecessary if Mesh stored uvs as QPoint2dList */
for (let i = 0, j = 0; i < pointCount; i++)
mesh.uvParams.push(gltfMesh.uvQParams.unquantize(gltfMesh.uvs[j++], gltfMesh.uvs[j++]));
}
if (gltfMesh.normals)
for (const normal of gltfMesh.normals)
mesh.normals.push(new OctEncodedNormal(normal));
return mesh.getGraphics(this._system, instances);
}
private readInstanceAttributes(node: Gltf2Node, featureTable: FeatureTable | undefined): InstancedGraphicParams | undefined {
const ext = node.extensions?.EXT_mesh_gpu_instancing;
if (!ext || !ext.attributes) {
return undefined;
}
const translationsView = this.getBufferView(ext.attributes, "TRANSLATION");
const translations = translationsView?.toBufferData(GltfDataType.Float);
const rotations = this.getBufferView(ext.attributes, "ROTATION")?.toBufferData(GltfDataType.Float);
const scales = this.getBufferView(ext.attributes, "SCALE")?.toBufferData(GltfDataType.Float);
// All attributes must specify the same count, count must be greater than zero, and at least one attribute must be specified.
const count = translations?.count ?? rotations?.count ?? scales?.count;
if (!count || (rotations && rotations.count !== count) || (scales && scales.count !== count)) {
return undefined;
}
const transformCenter = new Point3d();
const trMin = translationsView?.accessor.min;
const trMax = translationsView?.accessor.max;
if (trMin && trMax) {
const half = (idx: number): number => trMin[idx] + (trMax[idx] - trMin[idx]) / 2;
transformCenter.set(half(0), half(1), half(2));
}
const getTranslation = (index: number): [number, number, number] | undefined => {
if (!translations) {
return undefined;
}
index *= 3;
return [
translations.buffer[index + 0] - transformCenter.x,
translations.buffer[index + 1] - transformCenter.y,
translations.buffer[index + 2] - transformCenter.z,
];
};
const getRotation = (index: number): [number, number, number, number] | undefined => {
index *= 4;
return rotations ? [rotations.buffer[index], rotations.buffer[index + 1], rotations.buffer[index + 2], rotations.buffer[index + 3]] : undefined;
};
const getScale = (index: number): [number, number, number] | undefined => {
index *= 3;
return scales ? [scales.buffer[index], scales.buffer[index + 1], scales.buffer[index + 2]] : undefined;
};
const transforms = new Float32Array(3 * 4 * count);
const transform = Transform.createIdentity();
for (let i = 0; i < count; i++) {
const tf = trsMatrix(getTranslation(i), getRotation(i), getScale(i), transform);
const idx = i * 3 * 4;
transforms[idx + 0] = tf.matrix.coffs[0];
transforms[idx + 1] = tf.matrix.coffs[1];
transforms[idx + 2] = tf.matrix.coffs[2];
transforms[idx + 3] = tf.origin.x;
transforms[idx + 4] = tf.matrix.coffs[3];
transforms[idx + 5] = tf.matrix.coffs[4];
transforms[idx + 6] = tf.matrix.coffs[5];
transforms[idx + 7] = tf.origin.y;
transforms[idx + 8] = tf.matrix.coffs[6];
transforms[idx + 9] = tf.matrix.coffs[7];
transforms[idx + 10] = tf.matrix.coffs[8];
transforms[idx + 11] = tf.origin.z;
}
// ###TODO? The extension currently provides no way of specifying per-instance feature Ids.
// For now, assume that if the feature table contains exactly one feature, all the instances belong to that feature.
const featureIds = featureTable && featureTable.isUniform ? new Uint8Array(3 * count) : undefined;
return { count, transforms, transformCenter, featureIds };
}
private readNodeAndCreateGraphics(renderGraphicList: RenderGraphic[], node: GltfNode, featureTable: FeatureTable | undefined, transformStack: TransformStack, batchInstances?: InstancedGraphicParams, pseudoRtcBias?: Vector3d): TileReadStatus {
if (undefined === node)
return TileReadStatus.InvalidTileData;
// IMPORTANT: Do not return without popping this node from the stack.
transformStack.push(node);
const thisTransform = transformStack.transform;
const nodeInstances = !batchInstances && undefined !== node.mesh ? this.readInstanceAttributes(node, featureTable) : undefined;
/**
* This is a workaround for tiles generated by
* context capture which have a large offset from the tileset origin that exceeds the
* capacity of 32 bit integers. It is essentially an ad hoc RTC applied at read time only if the tile is far from the
* origin and there is no RTC supplied either with the B3DM of the GLTF.
* as the vertices are supplied in a quantized format, applying the RTC bias to
* quantization origin will make these tiles work correctly.
*/
let thisBias;
if (undefined !== pseudoRtcBias)
thisBias = (undefined === thisTransform) ? pseudoRtcBias : thisTransform.matrix.multiplyInverse(pseudoRtcBias);
for (const meshKey of getGltfNodeMeshIds(node)) {
const nodeMesh = this._meshes[meshKey];
if (nodeMesh?.primitives) {
const meshes = this.readMeshPrimitives(node, featureTable, thisTransform, thisBias, nodeInstances);
let renderGraphic: RenderGraphic | undefined;
if (0 !== meshes.length) {
if (1 === meshes.length) {
renderGraphic = this.graphicFromMeshData(meshes[0], batchInstances ?? nodeInstances);
} else {
const thisList: RenderGraphic[] = [];
for (const mesh of meshes) {
renderGraphic = this.graphicFromMeshData(mesh, batchInstances ?? nodeInstances);
if (undefined !== renderGraphic)
thisList.push(renderGraphic);
}
if (0 !== thisList.length)
renderGraphic = this._system.createGraphicList(thisList);
}
if (renderGraphic) {
if (thisTransform && !thisTransform.isIdentity) {
const branch = new GraphicBranch(true);
branch.add(renderGraphic);
renderGraphic = this._system.createBranch(branch, thisTransform);
}
renderGraphicList.push(renderGraphic);
}
}
}
}
if (node.children) {
for (const childId of node.children) {
const child = this._nodes[childId];
if (child)
this.readNodeAndCreateGraphics(renderGraphicList, child, featureTable, transformStack, batchInstances ?? nodeInstances);
}
}
transformStack.pop();
return TileReadStatus.Success;
}
private readNodeAndCreatePolyfaces(polyfaces: Polyface[], node: GltfNode, transformStack: TransformStack, needNormals: boolean, needParams: boolean): void {
// IMPORTANT: Do not return without popping this node from the stack.
transformStack.push(node);
const meshes = this.readMeshPrimitives(node);
for (const mesh of meshes) {
if (mesh.type === "mesh") {
const polyface = this.polyfaceFromGltfMesh(mesh, transformStack.transform, needNormals, needParams);
if (polyface)
polyfaces.push(polyface);
}
}
if (node.children) {
for (const childId of node.children) {
const child = this._nodes[childId];
if (child)
this.readNodeAndCreatePolyfaces(polyfaces, child, transformStack, needNormals, needParams);
}
}
}
private polyfaceFromGltfMesh(mesh: GltfMeshData, transform: Transform | undefined , needNormals: boolean, needParams: boolean): Polyface | undefined {
if (!mesh.pointQParams || !mesh.points || !mesh.indices)
return undefined;
const { points, pointQParams, normals, uvs, uvQParams, indices } = mesh;
const includeNormals = needNormals && undefined !== normals;
const includeParams = needParams && undefined !== uvQParams && undefined !== uvs;
const polyface = IndexedPolyface.create(includeNormals, includeParams);
for (let i = 0; i < points.length; ) {
const point = pointQParams.unquantize(points[i++], points[i++], points[i++]);
if (transform)
transform.multiplyPoint3d(point, point);
polyface.addPoint(point);
}
if (includeNormals && normals)
for (let i = 0; i < normals.length; )
polyface.addNormal(OctEncodedNormal.decodeValue(normals[i++]));
if (includeParams && uvs && uvQParams)
for (let i = 0; i < uvs.length; )
polyface.addParam(uvQParams.unquantize(uvs[i++], uvs[i++]));
let j = 0;
for (const index of indices) {
polyface.addPointIndex(index);
if (includeNormals)
polyface.addNormalIndex(index);
if (includeParams)
polyface.addParamIndex(index);
if (0 === (++j % 3))
polyface.terminateFacet();
}
return polyface;
}
// ###TODO what is the actual type of `json`?
public getBufferView(json: { [k: string]: any }, accessorName: string): GltfBufferView | undefined {
try {
const accessorValue = JsonUtils.asString(json[accessorName]);
const accessor = accessorValue ? this._accessors[accessorValue] : undefined;
if (!accessor)
return undefined;
const bufferViewAccessorValue = accessor.bufferView;
const bufferView = undefined !== bufferViewAccessorValue ? this._bufferViews[bufferViewAccessorValue] : undefined;
if (!bufferView)
return undefined;
let bufferData = bufferView.resolvedBuffer;
if (!bufferData) {
if (undefined === bufferView.buffer)
return undefined;
const buffer = this._buffers[bufferView.buffer];
bufferData = buffer?.resolvedBuffer;
}
if (!bufferData)
return undefined;
const type = accessor.componentType as GltfDataType;
let dataSize = 0;
switch (type) {
case GltfDataType.UnsignedByte:
dataSize = 1;
break;
case GltfDataType.UnsignedShort:
dataSize = 2;
break;
case GltfDataType.UInt32:
case GltfDataType.Float:
dataSize = 4;
break;
default:
return undefined;
}
let componentCount = 1;
switch (accessor.type) {
case "VEC4":
componentCount = 4;
break;
case "VEC3":
componentCount = 3;
break;
case "VEC2":
componentCount = 2;
break;
}
const byteStride = bufferView.byteStride ? bufferView.byteStride : componentCount * dataSize;
const offset = ((bufferView && bufferView.byteOffset) ? bufferView.byteOffset : 0) + (accessor.byteOffset ? accessor.byteOffset : 0);
const length = byteStride * accessor.count;
// If the data is misaligned (Scalable mesh tile publisher) use slice to copy -- else use subarray.
const aligned = 0 === (bufferData.byteOffset + offset) % dataSize;
const bytes = aligned ? bufferData.subarray(offset, offset + length) : bufferData.slice(offset, offset + length);
return new GltfBufferView(bytes, accessor.count, type, accessor, byteStride / dataSize);
} catch (e) {
return undefined;
}
}
public readBufferData32(json: { [k: string]: any }, accessorName: string): GltfBufferData | undefined { return this.readBufferData(json, accessorName, GltfDataType.UInt32); }
public readBufferData16(json: { [k: string]: any }, accessorName: string): GltfBufferData | undefined { return this.readBufferData(json, accessorName, GltfDataType.UnsignedShort); }
public readBufferData8(json: { [k: string]: any }, accessorName: string): GltfBufferData | undefined { return this.readBufferData(json, accessorName, GltfDataType.UnsignedByte); }
public readBufferDataFloat(json: { [k: string]: any }, accessorName: string): GltfBufferData | undefined { return this.readBufferData(json, accessorName, GltfDataType.Float); }
protected constructor(args: GltfReaderArgs) {
this._glTF = args.props.glTF;
this._version = args.props.version;
this._yAxisUp = args.props.yAxisUp;
this._baseUrl = args.props.baseUrl;
const rtcCenter = args.props.glTF.extensions?.CESIUM_RTC?.center;
if (rtcCenter && 3 === rtcCenter.length)
if (0 !== rtcCenter[0] || 0 !== rtcCenter[1] || 0 !== rtcCenter[2])
this._returnToCenter = Point3d.fromJSON(rtcCenter);
this._iModel = args.iModel;
this._is3d = true !== args.is2d;
this._system = args.system ?? IModelApp.renderSystem;
this._type = args.type ?? BatchType.Primary;
this._canceled = args.shouldAbort;
this._deduplicateVertices = args.deduplicateVertices ?? false;
this._vertexTableRequired = args.vertexTableRequired ?? false;
const binaryData = args.props.binaryData;
if (binaryData) {
const buffer = this._buffers[this._version === 2 ? 0 : "binary_glTF"];
if (buffer && undefined === buffer.uri)
buffer.resolvedBuffer = binaryData;
}
// The original implementation of GltfReader would process and produce graphics for every node in glTF.nodes.
// What it's *supposed* to do is process the nodes in glTF.scenes[glTF.scene].nodes
// Some nodes may not be referenced by the configured scene, or only indirectly via GltfNode.children.
// Perhaps some faulty tiles existed that didn't define their scenes properly?
let sceneNodes;
if (this._glTF.scenes && undefined !== this._glTF.scene)
sceneNodes = this._glTF.scenes[this._glTF.scene]?.nodes;
if (!sceneNodes)
sceneNodes = Object.keys(this._nodes);
this._sceneNodes = sceneNodes;
}
protected readBufferData(json: { [k: string]: any }, accessorName: string, type: GltfDataType): GltfBufferData | undefined {
const view = this.getBufferView(json, accessorName);
return undefined !== view ? view.toBufferData(type) : undefined;
}
protected readFeatureIndices(_json: any): number[] | undefined { return undefined; }
private extractId(value: any): string | undefined {
switch (typeof value) {
case "string":
return value;
case "number":
return value.toString();
default:
return undefined;
}
}
private extractTextureId(material: GltfMaterial): string | undefined {
if (typeof material !== "object")
return undefined;
// Bimium's shader value...almost certainly obsolete at this point.
if (isGltf1Material(material))
return material.diffuse ?? this.extractId(material.values?.tex);
// KHR_techniques_webgl extension
const techniques = this._glTF.extensions?.KHR_techniques_webgl?.techniques;
const ext = Array.isArray(techniques) ? material.extensions?.KHR_techniques_webgl : undefined;
if (techniques && undefined !== ext && typeof(ext.values) === "object") {
const uniforms = typeof ext.technique === "number" ? techniques[ext.technique].uniforms : undefined;
if (typeof uniforms === "object") {
for (const uniformName of Object.keys(uniforms)) {
const uniform = uniforms[uniformName];
if (typeof uniform === "object" && uniform.type === GltfDataType.Sampler2d)
return this.extractId((ext.values[uniformName] as any)?.index);
}
}
}
const id = this.extractId(material.pbrMetallicRoughness?.baseColorTexture?.index);
return id ?? this.extractId(material.emissiveTexture?.index);
}
private extractNormalMapId(material: GltfMaterial): string | undefined {
if (typeof material !== "object")
return undefined;
if (isGltf1Material(material))
return undefined;
return this.extractId(material.normalTexture?.index);
}
private isMaterialTransparent(material: GltfMaterial): boolean {
if (isGltf1Material(material)) {
if (this._glTF.techniques && undefined !== material.technique) {
const technique = this._glTF.techniques[material.technique];
if (technique?.states?.enable?.some((state: GltfTechniqueState) => state === GltfTechniqueState.Blend))
return true;
}
return false;
} else {
// Default: OPAQUE.
// ###TODO support MASK. For now treat as opaque.
return "BLEND" === material.alphaMode;
}
}
protected createDisplayParams(material: GltfMaterial, hasBakedLighting: boolean): DisplayParams | undefined {
const isTransparent = this.isMaterialTransparent(material);
const textureId = this.extractTextureId(material);
const normalMapId = this.extractNormalMapId(material);
let textureMapping = (undefined !== textureId || undefined !== normalMapId) ? this.findTextureMapping(textureId, isTransparent, normalMapId) : undefined;
const color = colorFromMaterial(material, isTransparent);
let renderMaterial: RenderMaterial | undefined;
if (undefined !== textureMapping && undefined !== textureMapping.normalMapParams) {
const args: CreateRenderMaterialArgs = { diffuse: { color }, specular: { color: ColorDef.white }, textureMapping };
renderMaterial = IModelApp.renderSystem.createRenderMaterial(args);
// DisplayParams doesn't want a separate texture mapping if the material already has one.
textureMapping = undefined;
}
return new DisplayParams(DisplayParams.Type.Mesh, color, color, 1, LinePixels.Solid, FillFlags.None, renderMaterial, undefined, hasBakedLighting, textureMapping);
}