dsh-3d-viewer 0.1.0 → 0.2.0

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 (47) hide show
  1. package/README.md +180 -107
  2. package/README.zh.md +180 -107
  3. package/THIRD_PARTY_NOTICES.md +54 -52
  4. package/assets/hdri/LICENSE.md +17 -16
  5. package/dist/client.fbx.js +14 -0
  6. package/dist/client.gltf.js +14 -0
  7. package/dist/client.js +4472 -0
  8. package/dist/client.obj.js +19 -0
  9. package/dist/client.stl.js +14 -0
  10. package/dist/client.tex-exr.js +14 -0
  11. package/dist/client.tex-hdr.js +18 -0
  12. package/dist/client.tex-tga.js +14 -0
  13. package/index.js +167 -7
  14. package/package.json +72 -48
  15. package/assets/preview.png +0 -0
  16. package/build.mjs +0 -49
  17. package/client.js +0 -4462
  18. package/scripts/embed-hdri.mjs +0 -70
  19. package/src/bytes.js +0 -158
  20. package/src/client.js +0 -57
  21. package/src/formats.js +0 -100
  22. package/src/generated/hdri-data.js +0 -8
  23. package/src/loaders/gltf.js +0 -251
  24. package/src/loaders/model-loader.js +0 -232
  25. package/src/loaders/workspace.js +0 -295
  26. package/src/model.js +0 -417
  27. package/src/scene/animation.js +0 -149
  28. package/src/scene/blue-noise.js +0 -48
  29. package/src/scene/camera.js +0 -83
  30. package/src/scene/createSceneView.js +0 -375
  31. package/src/scene/environment.js +0 -187
  32. package/src/scene/ground.js +0 -286
  33. package/src/scene/lighting.js +0 -41
  34. package/src/scene/materials.js +0 -263
  35. package/src/scene/postprocessing.js +0 -155
  36. package/src/scene/render-loop.js +0 -98
  37. package/src/scene/viewer-error.js +0 -16
  38. package/src/ui/AnimationBar.js +0 -95
  39. package/src/ui/ModelViewer.js +0 -278
  40. package/src/ui/ViewerSurface.js +0 -87
  41. package/src/ui/chrome.js +0 -220
  42. package/src/ui/dictionaries.js +0 -99
  43. package/src/ui/icons.js +0 -88
  44. package/src/ui/options.js +0 -23
  45. package/src/ui/primitives.js +0 -88
  46. package/src/ui/styles.js +0 -89
  47. package/src/vendor/FBXLoaderPbr.js +0 -4772
@@ -1,4772 +0,0 @@
1
- /**
2
- * Three.js FBXLoader (r187), vendored so custom material properties survive
3
- * parsing. Based on three/examples/jsm/loaders/FBXLoader.js (MIT).
4
- * The only behavioral addition is extracting scalar metalness/roughness from
5
- * material nodes into userData.fbxMetalness/fbxRoughness for the viewer's PBR
6
- * conversion.
7
- */
8
-
9
- import {
10
- AmbientLight,
11
- AnimationClip,
12
- Bone,
13
- BufferGeometry,
14
- ClampToEdgeWrapping,
15
- Color,
16
- ColorManagement,
17
- DirectionalLight,
18
- EquirectangularReflectionMapping,
19
- Euler,
20
- FileLoader,
21
- Float32BufferAttribute,
22
- Group,
23
- Line,
24
- LineBasicMaterial,
25
- Loader,
26
- LoaderUtils,
27
- MathUtils,
28
- Matrix3,
29
- Matrix4,
30
- Mesh,
31
- MeshLambertMaterial,
32
- MeshPhongMaterial,
33
- NumberKeyframeTrack,
34
- Object3D,
35
- PerspectiveCamera,
36
- PointLight,
37
- PropertyBinding,
38
- Quaternion,
39
- QuaternionKeyframeTrack,
40
- RepeatWrapping,
41
- SRGBColorSpace,
42
- ShapeUtils,
43
- Skeleton,
44
- SkinnedMesh,
45
- SpotLight,
46
- Texture,
47
- TextureLoader,
48
- Uint16BufferAttribute,
49
- Vector2,
50
- Vector3,
51
- Vector4,
52
- VectorKeyframeTrack
53
- } from 'three';
54
-
55
- import { unzlibSync } from 'three/addons/libs/fflate.module.js';
56
- import { NURBSCurve } from 'three/addons/curves/NURBSCurve.js';
57
-
58
- /**
59
- * Read a scalar custom property from a parsed FBX material node.
60
- *
61
- * FBX's classic Lambert/Phong materials have no standard metallic-roughness
62
- * channels. PBR-aware exporters instead add custom properties with names such
63
- * as Metalness, Roughness, or vendor-prefixed variants. Only scalar values are
64
- * read; texture-driven properties fall back to the caller's default.
65
- *
66
- * @param {object} materialNode Parsed FBX material node.
67
- * @param {string[]} preferred Normalized property names in priority order.
68
- * @returns {number | undefined} Clamped scalar in [0, 1], or undefined.
69
- */
70
- function extractFbxScalar( materialNode, preferred ) {
71
-
72
- if ( materialNode === null || typeof materialNode !== 'object' ) return undefined;
73
-
74
- const readScalar = ( value ) => {
75
-
76
- if ( typeof value === 'number' ) return Number.isFinite( value ) ? value : undefined;
77
- if ( typeof value === 'string' && value.trim() !== '' ) {
78
-
79
- const parsed = Number( value );
80
- return Number.isFinite( parsed ) ? parsed : undefined;
81
-
82
- }
83
- if ( Array.isArray( value ) ) return readScalar( value[ 0 ] );
84
- if ( value !== null && typeof value === 'object' && Object.prototype.hasOwnProperty.call( value, 'value' ) ) {
85
-
86
- return readScalar( value.value );
87
-
88
- }
89
- return undefined;
90
-
91
- };
92
-
93
- const found = new Map();
94
-
95
- const consider = ( key, value ) => {
96
-
97
- if ( typeof key !== 'string' ) return;
98
- const normalized = key.split( '|' ).pop().toLowerCase().replace( /[^a-z0-9]/g, '' );
99
- if ( preferred.includes( normalized ) === false || found.has( normalized ) ) return;
100
-
101
- const scalar = readScalar( value );
102
- if ( scalar !== undefined ) found.set( normalized, Math.min( 1, Math.max( 0, scalar ) ) );
103
-
104
- };
105
-
106
- for ( const [ key, value ] of Object.entries( materialNode ) ) consider( key, value );
107
-
108
- const properties = materialNode.Properties70 ?? materialNode.properties70;
109
- if ( properties !== null && typeof properties === 'object' && Array.isArray( properties ) === false ) {
110
-
111
- for ( const [ key, value ] of Object.entries( properties ) ) consider( key, value );
112
-
113
- }
114
-
115
- for ( const name of preferred ) {
116
-
117
- if ( found.has( name ) ) return found.get( name );
118
-
119
- }
120
- return undefined;
121
-
122
- }
123
-
124
- /**
125
- * Read scalar metalness from an FBX material node.
126
- *
127
- * @param {object} materialNode Parsed FBX material node.
128
- * @returns {number | undefined} Metalness in [0, 1], or undefined.
129
- */
130
- export function extractFbxMetalness( materialNode ) {
131
-
132
- return extractFbxScalar( materialNode, [ 'metalness', 'metalnessfactor', 'metallic', 'metallicfactor' ] );
133
-
134
- }
135
-
136
- /**
137
- * Read scalar roughness from an FBX material node.
138
- *
139
- * @param {object} materialNode Parsed FBX material node.
140
- * @returns {number | undefined} Roughness in [0, 1], or undefined.
141
- */
142
- export function extractFbxRoughness( materialNode ) {
143
-
144
- return extractFbxScalar( materialNode, [ 'roughness', 'roughnessfactor' ] );
145
-
146
- }
147
-
148
- let fbxTree;
149
- let connections;
150
- let sceneGraph;
151
-
152
- /**
153
- * A loader for the FBX format.
154
- *
155
- * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format.
156
- * Versions lower than this may load but will probably have errors.
157
- *
158
- * Needs Support:
159
- * - Morph normals / blend shape normals
160
- *
161
- * FBX format references:
162
- * - [C++ SDK reference](https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html)
163
- *
164
- * Binary format specification:
165
- * - [FBX binary file format specification](https://code.blender.org/2013/08/fbx-binary-file-format-specification/)
166
- *
167
- * ```js
168
- * const loader = new FBXLoader();
169
- * const object = await loader.loadAsync( 'models/fbx/stanford-bunny.fbx' );
170
- * scene.add( object );
171
- * ```
172
- *
173
- * @augments Loader
174
- * @three_import import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';
175
- */
176
- class FBXLoader extends Loader {
177
-
178
- /**
179
- * Constructs a new FBX loader.
180
- *
181
- * @param {LoadingManager} [manager] - The loading manager.
182
- */
183
- constructor( manager ) {
184
-
185
- super( manager );
186
-
187
- /**
188
- * Whether to trim animation clips to the time range of their
189
- * animation stacks and shift them to start at time zero. Useful
190
- * for assets that define multiple clips on a single timeline.
191
- *
192
- * @type {boolean}
193
- * @default false
194
- */
195
- this.trimAnimationClips = false;
196
-
197
- }
198
-
199
- /**
200
- * Starts loading from the given URL and passes the loaded FBX asset
201
- * to the `onLoad()` callback.
202
- *
203
- * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
204
- * @param {function(Group)} onLoad - Executed when the loading process has been finished.
205
- * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
206
- * @param {onErrorCallback} onError - Executed when errors occur.
207
- */
208
- load( url, onLoad, onProgress, onError ) {
209
-
210
- const scope = this;
211
-
212
- const path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path;
213
-
214
- const loader = new FileLoader( this.manager );
215
- loader.setPriority( this.priority );
216
- loader.setCache( this.cache );
217
- loader.setPath( scope.path );
218
- loader.setResponseType( 'arraybuffer' );
219
- loader.setRequestHeader( scope.requestHeader );
220
- loader.setWithCredentials( scope.withCredentials );
221
-
222
- loader.load( url, function ( buffer ) {
223
-
224
- try {
225
-
226
- onLoad( scope.parse( buffer, path ) );
227
-
228
- } catch ( e ) {
229
-
230
- if ( onError ) {
231
-
232
- onError( e );
233
-
234
- } else {
235
-
236
- console.error( e );
237
-
238
- }
239
-
240
- scope.manager.itemError( url );
241
-
242
- }
243
-
244
- }, onProgress, onError );
245
-
246
- }
247
-
248
- /**
249
- * Parses the given FBX data and returns the resulting group.
250
- *
251
- * @param {ArrayBuffer} FBXBuffer - The raw FBX data as an array buffer.
252
- * @param {string} path - The URL base path.
253
- * @return {Group} An object representing the parsed asset.
254
- */
255
- parse( FBXBuffer, path ) {
256
-
257
- if ( isFbxFormatBinary( FBXBuffer ) ) {
258
-
259
- fbxTree = new BinaryParser().parse( FBXBuffer );
260
-
261
- } else {
262
-
263
- const FBXText = convertArrayBufferToString( FBXBuffer );
264
-
265
- if ( ! isFbxFormatASCII( FBXText ) ) {
266
-
267
- throw new Error( 'THREE.FBXLoader: Unknown format.' );
268
-
269
- }
270
-
271
- if ( getFbxVersion( FBXText ) < 7000 ) {
272
-
273
- throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
274
-
275
- }
276
-
277
- fbxTree = new TextParser().parse( FBXText );
278
-
279
- }
280
-
281
- // console.log( fbxTree );
282
-
283
- const textureLoader = new TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
284
- textureLoader.setPriority( this.priority );
285
- textureLoader.setCache( this.cache );
286
-
287
- return new FBXTreeParser( textureLoader, this.manager, this.trimAnimationClips ).parse( fbxTree );
288
-
289
- }
290
-
291
- }
292
-
293
- // Parse the FBXTree object returned by the BinaryParser or TextParser and return a Group
294
- class FBXTreeParser {
295
-
296
- constructor( textureLoader, manager, trimAnimationClips ) {
297
-
298
- this.textureLoader = textureLoader;
299
- this.manager = manager;
300
- this.trimAnimationClips = trimAnimationClips;
301
-
302
- }
303
-
304
- parse() {
305
-
306
- connections = this.parseConnections();
307
-
308
- const images = this.parseImages();
309
- const textures = this.parseTextures( images );
310
- const materials = this.parseMaterials( textures );
311
- const deformers = this.parseDeformers();
312
- const geometryMap = new GeometryParser().parse( deformers );
313
-
314
- this.parseScene( deformers, geometryMap, materials );
315
-
316
- return sceneGraph;
317
-
318
- }
319
-
320
- // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
321
- // and details the connection type
322
- parseConnections() {
323
-
324
- const connectionMap = new Map();
325
-
326
- if ( 'Connections' in fbxTree ) {
327
-
328
- const rawConnections = fbxTree.Connections.connections;
329
-
330
- rawConnections.forEach( function ( rawConnection ) {
331
-
332
- const fromID = rawConnection[ 0 ];
333
- const toID = rawConnection[ 1 ];
334
- const relationship = rawConnection[ 2 ];
335
-
336
- if ( ! connectionMap.has( fromID ) ) {
337
-
338
- connectionMap.set( fromID, {
339
- parents: [],
340
- children: []
341
- } );
342
-
343
- }
344
-
345
- const parentRelationship = { ID: toID, relationship: relationship };
346
- connectionMap.get( fromID ).parents.push( parentRelationship );
347
-
348
- if ( ! connectionMap.has( toID ) ) {
349
-
350
- connectionMap.set( toID, {
351
- parents: [],
352
- children: []
353
- } );
354
-
355
- }
356
-
357
- const childRelationship = { ID: fromID, relationship: relationship };
358
- connectionMap.get( toID ).children.push( childRelationship );
359
-
360
- } );
361
-
362
- }
363
-
364
- return connectionMap;
365
-
366
- }
367
-
368
- // Parse FBXTree.Objects.Video for embedded image data
369
- // These images are connected to textures in FBXTree.Objects.Textures
370
- // via FBXTree.Connections.
371
- parseImages() {
372
-
373
- const images = {};
374
- const blobs = {};
375
-
376
- if ( 'Video' in fbxTree.Objects ) {
377
-
378
- const videoNodes = fbxTree.Objects.Video;
379
-
380
- for ( const nodeID in videoNodes ) {
381
-
382
- const videoNode = videoNodes[ nodeID ];
383
-
384
- const id = parseInt( nodeID );
385
-
386
- images[ id ] = videoNode.RelativeFilename || videoNode.Filename;
387
-
388
- // raw image data is in videoNode.Content
389
- if ( 'Content' in videoNode ) {
390
-
391
- const arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
392
- const base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );
393
-
394
- if ( arrayBufferContent || base64Content ) {
395
-
396
- const image = this.parseImage( videoNodes[ nodeID ] );
397
-
398
- blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;
399
-
400
- }
401
-
402
- }
403
-
404
- }
405
-
406
- }
407
-
408
- for ( const id in images ) {
409
-
410
- const filename = images[ id ];
411
-
412
- if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
413
- else images[ id ] = images[ id ].split( '\\' ).pop();
414
-
415
- }
416
-
417
- return images;
418
-
419
- }
420
-
421
- // Parse embedded image data in FBXTree.Video.Content
422
- parseImage( videoNode ) {
423
-
424
- const content = videoNode.Content;
425
- const fileName = videoNode.RelativeFilename || videoNode.Filename;
426
- const extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
427
-
428
- let type;
429
-
430
- switch ( extension ) {
431
-
432
- case 'bmp':
433
-
434
- type = 'image/bmp';
435
- break;
436
-
437
- case 'jpg':
438
- case 'jpeg':
439
-
440
- type = 'image/jpeg';
441
- break;
442
-
443
- case 'png':
444
-
445
- type = 'image/png';
446
- break;
447
-
448
- case 'tif':
449
-
450
- type = 'image/tiff';
451
- break;
452
-
453
- case 'tga':
454
-
455
- if ( this.manager.getHandler( '.tga' ) === null ) {
456
-
457
- console.warn( 'FBXLoader: TGA loader not found, skipping ', fileName );
458
-
459
- }
460
-
461
- type = 'image/tga';
462
- break;
463
-
464
- case 'webp':
465
-
466
- type = 'image/webp';
467
- break;
468
-
469
- default:
470
-
471
- console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
472
- return;
473
-
474
- }
475
-
476
- if ( typeof content === 'string' ) { // ASCII format
477
-
478
- return 'data:' + type + ';base64,' + content;
479
-
480
- } else { // Binary Format
481
-
482
- const array = new Uint8Array( content );
483
- return URL.createObjectURL( new Blob( [ array ], { type: type } ) );
484
-
485
- }
486
-
487
- }
488
-
489
- // Parse nodes in FBXTree.Objects.Texture
490
- // These contain details such as UV scaling, cropping, rotation etc and are connected
491
- // to images in FBXTree.Objects.Video
492
- parseTextures( images ) {
493
-
494
- const textureMap = new Map();
495
-
496
- if ( 'Texture' in fbxTree.Objects ) {
497
-
498
- const textureNodes = fbxTree.Objects.Texture;
499
- for ( const nodeID in textureNodes ) {
500
-
501
- const texture = this.parseTexture( textureNodes[ nodeID ], images );
502
- textureMap.set( parseInt( nodeID ), texture );
503
-
504
- }
505
-
506
- }
507
-
508
- return textureMap;
509
-
510
- }
511
-
512
- // Parse individual node in FBXTree.Objects.Texture
513
- parseTexture( textureNode, images ) {
514
-
515
- const texture = this.loadTexture( textureNode, images );
516
-
517
- texture.ID = textureNode.id;
518
-
519
- texture.name = textureNode.attrName;
520
-
521
- const wrapModeU = textureNode.WrapModeU;
522
- const wrapModeV = textureNode.WrapModeV;
523
-
524
- const valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
525
- const valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
526
-
527
- // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
528
- // 0: repeat(default), 1: clamp
529
-
530
- texture.wrapS = valueU === 0 ? RepeatWrapping : ClampToEdgeWrapping;
531
- texture.wrapT = valueV === 0 ? RepeatWrapping : ClampToEdgeWrapping;
532
-
533
- if ( 'Scaling' in textureNode ) {
534
-
535
- const values = textureNode.Scaling.value;
536
-
537
- texture.repeat.x = values[ 0 ];
538
- texture.repeat.y = values[ 1 ];
539
-
540
- }
541
-
542
- if ( 'Translation' in textureNode ) {
543
-
544
- const values = textureNode.Translation.value;
545
-
546
- texture.offset.x = values[ 0 ];
547
- texture.offset.y = values[ 1 ];
548
-
549
- }
550
-
551
- return texture;
552
-
553
- }
554
-
555
- // load a texture specified as a blob or data URI, or via an external URL using TextureLoader
556
- loadTexture( textureNode, images ) {
557
-
558
- const extension = textureNode.FileName.split( '.' ).pop().toLowerCase();
559
-
560
- let loader = this.manager.getHandler( `.${extension}` );
561
- if ( loader === null ) loader = this.textureLoader;
562
-
563
- const loaderPath = loader.path;
564
-
565
- if ( ! loaderPath ) {
566
-
567
- loader.setPath( this.textureLoader.path );
568
-
569
- }
570
-
571
- const children = connections.get( textureNode.id ).children;
572
-
573
- let fileName;
574
-
575
- if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) {
576
-
577
- fileName = images[ children[ 0 ].ID ];
578
-
579
- if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
580
-
581
- loader.setPath( undefined );
582
-
583
- }
584
-
585
- }
586
-
587
- if ( fileName === undefined ) {
588
-
589
- console.warn( 'FBXLoader: Undefined filename, creating placeholder texture.' );
590
- return new Texture();
591
-
592
- }
593
-
594
- const texture = loader.load( fileName );
595
-
596
- // revert to initial path
597
- loader.setPath( loaderPath );
598
-
599
- return texture;
600
-
601
- }
602
-
603
- // Parse nodes in FBXTree.Objects.Material
604
- parseMaterials( textureMap ) {
605
-
606
- const materialMap = new Map();
607
-
608
- if ( 'Material' in fbxTree.Objects ) {
609
-
610
- const materialNodes = fbxTree.Objects.Material;
611
-
612
- for ( const nodeID in materialNodes ) {
613
-
614
- const material = this.parseMaterial( materialNodes[ nodeID ], textureMap );
615
-
616
- if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
617
-
618
- }
619
-
620
- }
621
-
622
- return materialMap;
623
-
624
- }
625
-
626
- // Parse single node in FBXTree.Objects.Material
627
- // Materials are connected to texture maps in FBXTree.Objects.Textures
628
- // FBX format currently only supports Lambert and Phong shading models
629
- parseMaterial( materialNode, textureMap ) {
630
-
631
- const ID = materialNode.id;
632
- const name = materialNode.attrName;
633
- let type = materialNode.ShadingModel;
634
-
635
- // Case where FBX wraps shading model in property object.
636
- if ( typeof type === 'object' ) {
637
-
638
- type = type.value;
639
-
640
- }
641
-
642
- // Ignore unused materials which don't have any connections.
643
- if ( ! connections.has( ID ) ) return null;
644
-
645
- const parameters = this.parseParameters( materialNode, textureMap, ID );
646
-
647
- let material;
648
-
649
- switch ( type.toLowerCase() ) {
650
-
651
- case 'phong':
652
- material = new MeshPhongMaterial();
653
- break;
654
- case 'lambert':
655
- material = new MeshLambertMaterial();
656
- break;
657
- default:
658
- console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
659
- material = new MeshPhongMaterial();
660
- break;
661
-
662
- }
663
-
664
- material.setValues( parameters );
665
- material.name = name;
666
-
667
- const metalness = extractFbxMetalness( materialNode );
668
- if ( metalness !== undefined ) {
669
-
670
- material.userData.fbxMetalness = metalness;
671
-
672
- }
673
-
674
- const roughness = extractFbxRoughness( materialNode );
675
- if ( roughness !== undefined ) {
676
-
677
- material.userData.fbxRoughness = roughness;
678
-
679
- }
680
-
681
- return material;
682
-
683
- }
684
-
685
- // Parse FBX material and return parameters suitable for a three.js material
686
- // Also parse the texture map and return any textures associated with the material
687
- parseParameters( materialNode, textureMap, ID ) {
688
-
689
- const parameters = {};
690
-
691
- if ( materialNode.BumpFactor ) {
692
-
693
- parameters.bumpScale = materialNode.BumpFactor.value;
694
-
695
- }
696
-
697
- if ( materialNode.Diffuse ) {
698
-
699
- parameters.color = ColorManagement.colorSpaceToWorking( new Color().fromArray( materialNode.Diffuse.value ), SRGBColorSpace );
700
-
701
- } else if ( materialNode.DiffuseColor && ( materialNode.DiffuseColor.type === 'Color' || materialNode.DiffuseColor.type === 'ColorRGB' ) ) {
702
-
703
- // The blender exporter exports diffuse here instead of in materialNode.Diffuse
704
- parameters.color = ColorManagement.colorSpaceToWorking( new Color().fromArray( materialNode.DiffuseColor.value ), SRGBColorSpace );
705
-
706
- }
707
-
708
- if ( materialNode.DisplacementFactor ) {
709
-
710
- parameters.displacementScale = materialNode.DisplacementFactor.value;
711
-
712
- }
713
-
714
- if ( materialNode.Emissive ) {
715
-
716
- parameters.emissive = ColorManagement.colorSpaceToWorking( new Color().fromArray( materialNode.Emissive.value ), SRGBColorSpace );
717
-
718
- } else if ( materialNode.EmissiveColor && ( materialNode.EmissiveColor.type === 'Color' || materialNode.EmissiveColor.type === 'ColorRGB' ) ) {
719
-
720
- // The blender exporter exports emissive color here instead of in materialNode.Emissive
721
- parameters.emissive = ColorManagement.colorSpaceToWorking( new Color().fromArray( materialNode.EmissiveColor.value ), SRGBColorSpace );
722
-
723
- }
724
-
725
- if ( materialNode.EmissiveFactor ) {
726
-
727
- parameters.emissiveIntensity = parseFloat( materialNode.EmissiveFactor.value );
728
-
729
- }
730
-
731
- // the transparency handling is implemented based on Blender's approach:
732
- // https://github.com/blender/blender/blob/main/scripts/addons_core/io_scene_fbx/import_fbx.py
733
-
734
- parameters.opacity = 1 - ( materialNode.TransparencyFactor ? parseFloat( materialNode.TransparencyFactor.value ) : 0 );
735
-
736
- if ( parameters.opacity === 1 || parameters.opacity === 0 ) {
737
-
738
- parameters.opacity = ( materialNode.Opacity ? parseFloat( materialNode.Opacity.value ) : null );
739
-
740
- if ( parameters.opacity === null ) {
741
-
742
- // Default to opaque. Some exporters (e.g. 3ds Max) define TransparentColor
743
- // as white (1,1,1) without intending transparency, which makes the Unity-style
744
- // fallback of `1 - TransparentColor.r` produce incorrect zero opacity.
745
- parameters.opacity = 1;
746
-
747
- }
748
-
749
- }
750
-
751
- if ( parameters.opacity < 1.0 ) {
752
-
753
- parameters.transparent = true;
754
-
755
- }
756
-
757
- if ( materialNode.ReflectionFactor ) {
758
-
759
- parameters.reflectivity = materialNode.ReflectionFactor.value;
760
-
761
- }
762
-
763
- if ( materialNode.Shininess ) {
764
-
765
- parameters.shininess = materialNode.Shininess.value;
766
-
767
- }
768
-
769
- if ( materialNode.Specular ) {
770
-
771
- parameters.specular = ColorManagement.colorSpaceToWorking( new Color().fromArray( materialNode.Specular.value ), SRGBColorSpace );
772
-
773
- } else if ( materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color' ) {
774
-
775
- // The blender exporter exports specular color here instead of in materialNode.Specular
776
- parameters.specular = ColorManagement.colorSpaceToWorking( new Color().fromArray( materialNode.SpecularColor.value ), SRGBColorSpace );
777
-
778
- }
779
-
780
- const scope = this;
781
- connections.get( ID ).children.forEach( function ( child ) {
782
-
783
- const type = child.relationship;
784
-
785
- switch ( type ) {
786
-
787
- case 'Bump':
788
- parameters.bumpMap = scope.getTexture( textureMap, child.ID );
789
- break;
790
-
791
- case 'Maya|TEX_ao_map':
792
- parameters.aoMap = scope.getTexture( textureMap, child.ID );
793
- break;
794
-
795
- case 'DiffuseColor':
796
- case 'Maya|TEX_color_map':
797
- parameters.map = scope.getTexture( textureMap, child.ID );
798
- if ( parameters.map !== undefined ) {
799
-
800
- parameters.map.colorSpace = SRGBColorSpace;
801
-
802
- }
803
-
804
- break;
805
-
806
- case 'DisplacementColor':
807
- parameters.displacementMap = scope.getTexture( textureMap, child.ID );
808
- break;
809
-
810
- case 'EmissiveColor':
811
- parameters.emissiveMap = scope.getTexture( textureMap, child.ID );
812
- if ( parameters.emissiveMap !== undefined ) {
813
-
814
- parameters.emissiveMap.colorSpace = SRGBColorSpace;
815
-
816
- }
817
-
818
- break;
819
-
820
- case 'NormalMap':
821
- case 'Maya|TEX_normal_map':
822
- parameters.normalMap = scope.getTexture( textureMap, child.ID );
823
- break;
824
-
825
- case 'ReflectionColor':
826
- parameters.envMap = scope.getTexture( textureMap, child.ID );
827
- if ( parameters.envMap !== undefined ) {
828
-
829
- parameters.envMap.mapping = EquirectangularReflectionMapping;
830
- parameters.envMap.colorSpace = SRGBColorSpace;
831
-
832
- }
833
-
834
- break;
835
-
836
- case 'SpecularColor':
837
- parameters.specularMap = scope.getTexture( textureMap, child.ID );
838
- if ( parameters.specularMap !== undefined ) {
839
-
840
- parameters.specularMap.colorSpace = SRGBColorSpace;
841
-
842
- }
843
-
844
- break;
845
-
846
- case 'TransparentColor':
847
- case 'TransparencyFactor':
848
- parameters.alphaMap = scope.getTexture( textureMap, child.ID );
849
- parameters.transparent = true;
850
- break;
851
-
852
- case 'AmbientColor':
853
- case 'ShininessExponent': // AKA glossiness map
854
- case 'SpecularFactor': // AKA specularLevel
855
- case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
856
- default:
857
- console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
858
- break;
859
-
860
- }
861
-
862
- } );
863
-
864
- return parameters;
865
-
866
- }
867
-
868
- // get a texture from the textureMap for use by a material.
869
- getTexture( textureMap, id ) {
870
-
871
- // if the texture is a layered texture, just use the first layer and issue a warning
872
- if ( 'LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture ) {
873
-
874
- console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' );
875
- id = connections.get( id ).children[ 0 ].ID;
876
-
877
- }
878
-
879
- return textureMap.get( id );
880
-
881
- }
882
-
883
- // Parse nodes in FBXTree.Objects.Deformer
884
- // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
885
- // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
886
- parseDeformers() {
887
-
888
- const skeletons = {};
889
- const morphTargets = {};
890
-
891
- if ( 'Deformer' in fbxTree.Objects ) {
892
-
893
- const DeformerNodes = fbxTree.Objects.Deformer;
894
-
895
- for ( const nodeID in DeformerNodes ) {
896
-
897
- const deformerNode = DeformerNodes[ nodeID ];
898
-
899
- const relationships = connections.get( parseInt( nodeID ) );
900
-
901
- if ( deformerNode.attrType === 'Skin' ) {
902
-
903
- const skeleton = this.parseSkeleton( relationships, DeformerNodes );
904
- skeleton.ID = nodeID;
905
-
906
- if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: skeleton attached to more than one geometry is not supported.' );
907
- skeleton.geometryID = relationships.parents[ 0 ].ID;
908
-
909
- skeletons[ nodeID ] = skeleton;
910
-
911
- } else if ( deformerNode.attrType === 'BlendShape' ) {
912
-
913
- const morphTarget = {
914
- id: nodeID,
915
- };
916
-
917
- morphTarget.rawTargets = this.parseMorphTargets( relationships, DeformerNodes );
918
- morphTarget.id = nodeID;
919
-
920
- if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: morph target attached to more than one geometry is not supported.' );
921
-
922
- morphTargets[ nodeID ] = morphTarget;
923
-
924
- }
925
-
926
- }
927
-
928
- }
929
-
930
- return {
931
-
932
- skeletons: skeletons,
933
- morphTargets: morphTargets,
934
-
935
- };
936
-
937
- }
938
-
939
- // Parse single nodes in FBXTree.Objects.Deformer
940
- // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
941
- // Each skin node represents a skeleton and each cluster node represents a bone
942
- parseSkeleton( relationships, deformerNodes ) {
943
-
944
- const rawBones = [];
945
-
946
- relationships.children.forEach( function ( child ) {
947
-
948
- const boneNode = deformerNodes[ child.ID ];
949
-
950
- if ( boneNode.attrType !== 'Cluster' ) return;
951
-
952
- const rawBone = {
953
-
954
- ID: child.ID,
955
- indices: [],
956
- weights: [],
957
- transformLink: new Matrix4().fromArray( boneNode.TransformLink.a ),
958
-
959
- };
960
-
961
- if ( 'Indexes' in boneNode ) {
962
-
963
- rawBone.indices = boneNode.Indexes.a;
964
- rawBone.weights = boneNode.Weights.a;
965
-
966
- }
967
-
968
- rawBones.push( rawBone );
969
-
970
- } );
971
-
972
- return {
973
-
974
- rawBones: rawBones,
975
- bones: []
976
-
977
- };
978
-
979
- }
980
-
981
- // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
982
- parseMorphTargets( relationships, deformerNodes ) {
983
-
984
- const rawMorphTargets = [];
985
-
986
- for ( let i = 0; i < relationships.children.length; i ++ ) {
987
-
988
- const child = relationships.children[ i ];
989
-
990
- const morphTargetNode = deformerNodes[ child.ID ];
991
-
992
- const rawMorphTarget = {
993
-
994
- name: morphTargetNode.attrName,
995
- initialWeight: morphTargetNode.DeformPercent,
996
- id: morphTargetNode.id,
997
- fullWeights: morphTargetNode.FullWeights.a
998
-
999
- };
1000
-
1001
- if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return;
1002
-
1003
- rawMorphTarget.geoID = connections.get( parseInt( child.ID ) ).children.filter( function ( child ) {
1004
-
1005
- return child.relationship === undefined;
1006
-
1007
- } )[ 0 ].ID;
1008
-
1009
- rawMorphTargets.push( rawMorphTarget );
1010
-
1011
- }
1012
-
1013
- return rawMorphTargets;
1014
-
1015
- }
1016
-
1017
- // create the main Group() to be returned by the loader
1018
- parseScene( deformers, geometryMap, materialMap ) {
1019
-
1020
- sceneGraph = new Group();
1021
-
1022
- const modelMap = this.parseModels( deformers.skeletons, geometryMap, materialMap );
1023
-
1024
- const modelNodes = fbxTree.Objects.Model;
1025
-
1026
- const scope = this;
1027
- modelMap.forEach( function ( model ) {
1028
-
1029
- const modelNode = modelNodes[ model.ID ];
1030
- scope.setLookAtProperties( model, modelNode );
1031
-
1032
- const parentConnections = connections.get( model.ID ).parents;
1033
-
1034
- parentConnections.forEach( function ( connection ) {
1035
-
1036
- const parent = modelMap.get( connection.ID );
1037
- if ( parent !== undefined ) parent.add( model );
1038
-
1039
- } );
1040
-
1041
- if ( model.parent === null ) {
1042
-
1043
- sceneGraph.add( model );
1044
-
1045
- }
1046
-
1047
-
1048
- } );
1049
-
1050
- this.addGlobalSceneSettings();
1051
-
1052
- sceneGraph.traverse( function ( node ) {
1053
-
1054
- if ( node.userData.transformData ) {
1055
-
1056
- if ( node.parent ) {
1057
-
1058
- node.userData.transformData.parentMatrix = node.parent.matrix;
1059
- node.userData.transformData.parentMatrixWorld = node.parent.matrixWorld;
1060
-
1061
- }
1062
-
1063
- const transform = generateTransform( node.userData.transformData );
1064
-
1065
- node.applyMatrix4( transform );
1066
- node.updateWorldMatrix();
1067
-
1068
- }
1069
-
1070
- } );
1071
-
1072
- // Like Blender's FBX importer, use the BindPose section to set the
1073
- // rest pose for bones that are not part of a skin cluster. The BindPose
1074
- // provides a more authoritative rest pose than the Lcl properties which
1075
- // may represent an animation frame rather than the true rest state.
1076
- // Bones WITH clusters will get their bind pose from TransformLink
1077
- // (set via bindSkeleton below), which takes priority.
1078
- const bindPoseMatrices = this.parsePoseNodes();
1079
- const clusterBoneIDs = new Set();
1080
-
1081
- for ( const ID in deformers.skeletons ) {
1082
-
1083
- deformers.skeletons[ ID ].rawBones.forEach( function ( _, i ) {
1084
-
1085
- const bone = deformers.skeletons[ ID ].bones[ i ];
1086
- if ( bone ) clusterBoneIDs.add( bone.ID );
1087
-
1088
- } );
1089
-
1090
- }
1091
-
1092
- const tempMatrix = new Matrix4();
1093
-
1094
- sceneGraph.traverse( function ( node ) {
1095
-
1096
- if ( node.isBone && node.ID !== undefined && ! clusterBoneIDs.has( node.ID ) ) {
1097
-
1098
- const bindPose = bindPoseMatrices[ node.ID ];
1099
-
1100
- if ( bindPose !== undefined ) {
1101
-
1102
- if ( node.parent ) {
1103
-
1104
- tempMatrix.copy( node.parent.matrixWorld ).invert();
1105
- tempMatrix.multiply( bindPose );
1106
-
1107
- } else {
1108
-
1109
- tempMatrix.copy( bindPose );
1110
-
1111
- }
1112
-
1113
- tempMatrix.decompose( node.position, node.quaternion, node.scale );
1114
- node.updateMatrix();
1115
- node.matrixWorld.copy( bindPose );
1116
-
1117
- }
1118
-
1119
- }
1120
-
1121
- } );
1122
-
1123
- // Bind skeletons after transforms are applied so that bind matrices
1124
- // are computed from the final scene state. This ensures the rest pose
1125
- // is correct even when the FBX file's Cluster TransformLink matrices
1126
- // differ from the reconstructed bone transforms (common in files
1127
- // without a BindPose section).
1128
- this.bindSkeleton( deformers.skeletons, geometryMap, modelMap );
1129
-
1130
- const animations = new AnimationParser( this.trimAnimationClips ).parse();
1131
-
1132
- // if all the models where already combined in a single group, just return that
1133
- if ( sceneGraph.children.length === 1 && sceneGraph.children[ 0 ].isGroup ) {
1134
-
1135
- sceneGraph.children[ 0 ].animations = animations;
1136
- Object.assign( sceneGraph.children[ 0 ].userData, sceneGraph.userData );
1137
- sceneGraph = sceneGraph.children[ 0 ];
1138
-
1139
- }
1140
-
1141
- sceneGraph.animations = animations;
1142
-
1143
- // Apply coordinate system correction. FBX files can use different
1144
- // up-axis conventions (Y-up or Z-up). Three.js uses Y-up, so rotate
1145
- // the scene when the file uses Z-up (UpAxis === 2).
1146
-
1147
- if ( 'GlobalSettings' in fbxTree && 'UpAxis' in fbxTree.GlobalSettings ) {
1148
-
1149
- const upAxis = fbxTree.GlobalSettings.UpAxis.value;
1150
-
1151
- if ( upAxis === 2 ) {
1152
-
1153
- console.warn( 'THREE.FBXLoader: You are loading an asset with a Z-UP coordinate system. The loader just rotates the asset to transform it into Y-UP. The vertex data are not converted.' );
1154
-
1155
- sceneGraph.rotation.set( - Math.PI / 2, 0, 0 );
1156
-
1157
- }
1158
-
1159
- }
1160
-
1161
- }
1162
-
1163
- // parse nodes in FBXTree.Objects.Model
1164
- parseModels( skeletons, geometryMap, materialMap ) {
1165
-
1166
- const modelMap = new Map();
1167
- const modelNodes = fbxTree.Objects.Model;
1168
-
1169
- for ( const nodeID in modelNodes ) {
1170
-
1171
- const id = parseInt( nodeID );
1172
- const node = modelNodes[ nodeID ];
1173
- const relationships = connections.get( id );
1174
-
1175
- let model = this.buildSkeleton( relationships, skeletons, id, node.attrName );
1176
-
1177
- if ( ! model ) {
1178
-
1179
- switch ( node.attrType ) {
1180
-
1181
- case 'Camera':
1182
- model = this.createCamera( relationships );
1183
- break;
1184
- case 'Light':
1185
- model = this.createLight( relationships );
1186
- break;
1187
- case 'Mesh':
1188
- model = this.createMesh( relationships, geometryMap, materialMap );
1189
- break;
1190
- case 'NurbsCurve':
1191
- model = this.createCurve( relationships, geometryMap );
1192
- break;
1193
- case 'LimbNode':
1194
- case 'Root':
1195
- model = new Bone();
1196
- break;
1197
- case 'Null':
1198
- default:
1199
- model = new Group();
1200
- break;
1201
-
1202
- }
1203
-
1204
- model.name = node.attrName ? PropertyBinding.sanitizeNodeName( node.attrName ) : '';
1205
- model.userData.originalName = node.attrName;
1206
-
1207
- model.ID = id;
1208
-
1209
- }
1210
-
1211
- this.getTransformData( model, node );
1212
- modelMap.set( id, model );
1213
-
1214
- }
1215
-
1216
- return modelMap;
1217
-
1218
- }
1219
-
1220
- buildSkeleton( relationships, skeletons, id, name ) {
1221
-
1222
- let bone = null;
1223
-
1224
- relationships.parents.forEach( function ( parent ) {
1225
-
1226
- for ( const ID in skeletons ) {
1227
-
1228
- const skeleton = skeletons[ ID ];
1229
-
1230
- skeleton.rawBones.forEach( function ( rawBone, i ) {
1231
-
1232
- if ( rawBone.ID === parent.ID ) {
1233
-
1234
- const subBone = bone;
1235
- bone = new Bone();
1236
-
1237
- bone.matrixWorld.copy( rawBone.transformLink );
1238
-
1239
- // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
1240
-
1241
- bone.name = name ? PropertyBinding.sanitizeNodeName( name ) : '';
1242
- bone.userData.originalName = name;
1243
- bone.ID = id;
1244
-
1245
- skeleton.bones[ i ] = bone;
1246
-
1247
- // In cases where a bone is shared between multiple meshes
1248
- // duplicate the bone here and add it as a child of the first bone
1249
- if ( subBone !== null ) {
1250
-
1251
- bone.add( subBone );
1252
-
1253
- }
1254
-
1255
- }
1256
-
1257
- } );
1258
-
1259
- }
1260
-
1261
- } );
1262
-
1263
- return bone;
1264
-
1265
- }
1266
-
1267
- // create a PerspectiveCamera or OrthographicCamera
1268
- createCamera( relationships ) {
1269
-
1270
- let model;
1271
- let cameraAttribute;
1272
-
1273
- relationships.children.forEach( function ( child ) {
1274
-
1275
- const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
1276
-
1277
- if ( attr !== undefined ) {
1278
-
1279
- cameraAttribute = attr;
1280
-
1281
- }
1282
-
1283
- } );
1284
-
1285
- if ( cameraAttribute === undefined ) {
1286
-
1287
- model = new Object3D();
1288
-
1289
- } else {
1290
-
1291
- let type = 0;
1292
- if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
1293
-
1294
- type = 1;
1295
-
1296
- }
1297
-
1298
- let nearClippingPlane = 1;
1299
- if ( cameraAttribute.NearPlane !== undefined ) {
1300
-
1301
- nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
1302
-
1303
- }
1304
-
1305
- let farClippingPlane = 1000;
1306
- if ( cameraAttribute.FarPlane !== undefined ) {
1307
-
1308
- farClippingPlane = cameraAttribute.FarPlane.value / 1000;
1309
-
1310
- }
1311
-
1312
-
1313
- let width = window.innerWidth;
1314
- let height = window.innerHeight;
1315
-
1316
- if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
1317
-
1318
- width = cameraAttribute.AspectWidth.value;
1319
- height = cameraAttribute.AspectHeight.value;
1320
-
1321
- }
1322
-
1323
- const aspect = width / height;
1324
-
1325
- let fov = 45;
1326
- if ( cameraAttribute.FieldOfView !== undefined ) {
1327
-
1328
- fov = cameraAttribute.FieldOfView.value;
1329
-
1330
- }
1331
-
1332
- const focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
1333
-
1334
- switch ( type ) {
1335
-
1336
- case 0: // Perspective
1337
- model = new PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
1338
- if ( focalLength !== null ) model.setFocalLength( focalLength );
1339
- break;
1340
-
1341
- case 1: // Orthographic
1342
- console.warn( 'THREE.FBXLoader: Orthographic cameras not supported yet.' );
1343
- model = new Object3D();
1344
- break;
1345
-
1346
- default:
1347
- console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
1348
- model = new Object3D();
1349
- break;
1350
-
1351
- }
1352
-
1353
- }
1354
-
1355
- return model;
1356
-
1357
- }
1358
-
1359
- // Create a DirectionalLight, PointLight or SpotLight
1360
- createLight( relationships ) {
1361
-
1362
- let model;
1363
- let lightAttribute;
1364
-
1365
- relationships.children.forEach( function ( child ) {
1366
-
1367
- const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
1368
-
1369
- if ( attr !== undefined ) {
1370
-
1371
- lightAttribute = attr;
1372
-
1373
- }
1374
-
1375
- } );
1376
-
1377
- if ( lightAttribute === undefined ) {
1378
-
1379
- model = new Object3D();
1380
-
1381
- } else {
1382
-
1383
- let type;
1384
-
1385
- // LightType can be undefined for Point lights
1386
- if ( lightAttribute.LightType === undefined ) {
1387
-
1388
- type = 0;
1389
-
1390
- } else {
1391
-
1392
- type = lightAttribute.LightType.value;
1393
-
1394
- }
1395
-
1396
- let color = 0xffffff;
1397
-
1398
- if ( lightAttribute.Color !== undefined ) {
1399
-
1400
- color = ColorManagement.colorSpaceToWorking( new Color().fromArray( lightAttribute.Color.value ), SRGBColorSpace );
1401
-
1402
- }
1403
-
1404
- let intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
1405
-
1406
- // light disabled
1407
- if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
1408
-
1409
- intensity = 0;
1410
-
1411
- }
1412
-
1413
- let distance = 0;
1414
- if ( lightAttribute.FarAttenuationEnd !== undefined ) {
1415
-
1416
- if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
1417
-
1418
- distance = 0;
1419
-
1420
- } else {
1421
-
1422
- distance = lightAttribute.FarAttenuationEnd.value;
1423
-
1424
- }
1425
-
1426
- }
1427
-
1428
- // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
1429
- const decay = 1;
1430
-
1431
- switch ( type ) {
1432
-
1433
- case 0: // Point
1434
- model = new PointLight( color, intensity, distance, decay );
1435
- break;
1436
-
1437
- case 1: // Directional
1438
- model = new DirectionalLight( color, intensity );
1439
- break;
1440
-
1441
- case 2: // Spot
1442
- let angle = Math.PI / 3;
1443
- let penumbra = 0;
1444
-
1445
- if ( lightAttribute.OuterAngle !== undefined ) {
1446
-
1447
- angle = MathUtils.degToRad( lightAttribute.OuterAngle.value );
1448
-
1449
- if ( lightAttribute.InnerAngle !== undefined ) {
1450
-
1451
- penumbra = 1 - ( lightAttribute.InnerAngle.value / lightAttribute.OuterAngle.value );
1452
- penumbra = Math.max( 0, penumbra ); // penumbra must be in the range [0,1]
1453
-
1454
- }
1455
-
1456
- } else if ( lightAttribute.InnerAngle !== undefined ) {
1457
-
1458
- // fallback if only InnerAngle is defined
1459
-
1460
- angle = MathUtils.degToRad( lightAttribute.InnerAngle.value );
1461
-
1462
- }
1463
-
1464
- model = new SpotLight( color, intensity, distance, angle, penumbra, decay );
1465
- break;
1466
-
1467
- default:
1468
- console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a PointLight.' );
1469
- model = new PointLight( color, intensity );
1470
- break;
1471
-
1472
- }
1473
-
1474
- if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
1475
-
1476
- model.castShadow = true;
1477
-
1478
- }
1479
-
1480
- }
1481
-
1482
- return model;
1483
-
1484
- }
1485
-
1486
- createMesh( relationships, geometryMap, materialMap ) {
1487
-
1488
- let model;
1489
- let geometry = null;
1490
- let material = null;
1491
- const materials = [];
1492
-
1493
- // get geometry and materials(s) from connections
1494
- relationships.children.forEach( function ( child ) {
1495
-
1496
- if ( geometryMap.has( child.ID ) ) {
1497
-
1498
- geometry = geometryMap.get( child.ID );
1499
-
1500
- }
1501
-
1502
- if ( materialMap.has( child.ID ) ) {
1503
-
1504
- materials.push( materialMap.get( child.ID ) );
1505
-
1506
- }
1507
-
1508
- } );
1509
-
1510
- if ( materials.length > 1 ) {
1511
-
1512
- material = materials;
1513
-
1514
- } else if ( materials.length > 0 ) {
1515
-
1516
- material = materials[ 0 ];
1517
-
1518
- } else {
1519
-
1520
- material = new MeshPhongMaterial( {
1521
- name: Loader.DEFAULT_MATERIAL_NAME,
1522
- color: 0xcccccc
1523
- } );
1524
- materials.push( material );
1525
-
1526
- }
1527
-
1528
- if ( 'color' in geometry.attributes ) {
1529
-
1530
- materials.forEach( function ( material ) {
1531
-
1532
- material.vertexColors = true;
1533
-
1534
- } );
1535
-
1536
- }
1537
-
1538
- // Sanitization: If geometry has groups, then it must match the provided material array.
1539
- // If not, we need to clean up the `group.materialIndex` properties inside the groups and point at a (new) default material.
1540
- // This isn't well defined; Unity creates default material, while Blender implicitly uses the previous material in the list.
1541
- if ( geometry.groups.length > 0 ) {
1542
-
1543
- let needsDefaultMaterial = false;
1544
-
1545
- for ( let i = 0, il = geometry.groups.length; i < il; i ++ ) {
1546
-
1547
- const group = geometry.groups[ i ];
1548
-
1549
- if ( group.materialIndex < 0 || group.materialIndex >= materials.length ) {
1550
-
1551
- group.materialIndex = materials.length;
1552
- needsDefaultMaterial = true;
1553
-
1554
- }
1555
-
1556
- }
1557
-
1558
- if ( needsDefaultMaterial ) {
1559
-
1560
- const defaultMaterial = new MeshPhongMaterial();
1561
- materials.push( defaultMaterial );
1562
-
1563
- }
1564
-
1565
- }
1566
-
1567
- if ( geometry.FBX_Deformer ) {
1568
-
1569
- model = new SkinnedMesh( geometry, material );
1570
- model.normalizeSkinWeights();
1571
-
1572
- } else {
1573
-
1574
- model = new Mesh( geometry, material );
1575
-
1576
- }
1577
-
1578
- return model;
1579
-
1580
- }
1581
-
1582
- createCurve( relationships, geometryMap ) {
1583
-
1584
- const geometry = relationships.children.reduce( function ( geo, child ) {
1585
-
1586
- if ( geometryMap.has( child.ID ) ) geo = geometryMap.get( child.ID );
1587
-
1588
- return geo;
1589
-
1590
- }, null );
1591
-
1592
- // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
1593
- const material = new LineBasicMaterial( {
1594
- name: Loader.DEFAULT_MATERIAL_NAME,
1595
- color: 0x3300ff,
1596
- linewidth: 1
1597
- } );
1598
- return new Line( geometry, material );
1599
-
1600
- }
1601
-
1602
- // parse the model node for transform data
1603
- getTransformData( model, modelNode ) {
1604
-
1605
- const transformData = {};
1606
-
1607
- if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
1608
-
1609
- if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
1610
- else transformData.eulerOrder = getEulerOrder( 0 );
1611
-
1612
- if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value;
1613
-
1614
- if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value;
1615
- if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value;
1616
- if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value;
1617
-
1618
- if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value;
1619
-
1620
- if ( 'ScalingOffset' in modelNode ) transformData.scalingOffset = modelNode.ScalingOffset.value;
1621
- if ( 'ScalingPivot' in modelNode ) transformData.scalingPivot = modelNode.ScalingPivot.value;
1622
-
1623
- if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value;
1624
- if ( 'RotationPivot' in modelNode ) transformData.rotationPivot = modelNode.RotationPivot.value;
1625
-
1626
- model.userData.transformData = transformData;
1627
-
1628
- }
1629
-
1630
- setLookAtProperties( model, modelNode ) {
1631
-
1632
- if ( 'LookAtProperty' in modelNode ) {
1633
-
1634
- const children = connections.get( model.ID ).children;
1635
-
1636
- children.forEach( function ( child ) {
1637
-
1638
- if ( child.relationship === 'LookAtProperty' ) {
1639
-
1640
- const lookAtTarget = fbxTree.Objects.Model[ child.ID ];
1641
-
1642
- if ( 'Lcl_Translation' in lookAtTarget ) {
1643
-
1644
- const pos = lookAtTarget.Lcl_Translation.value;
1645
-
1646
- // DirectionalLight, SpotLight
1647
- if ( model.target !== undefined ) {
1648
-
1649
- model.target.position.fromArray( pos );
1650
- sceneGraph.add( model.target );
1651
-
1652
- } else { // Cameras and other Object3Ds
1653
-
1654
- model.lookAt( new Vector3().fromArray( pos ) );
1655
-
1656
- }
1657
-
1658
- }
1659
-
1660
- }
1661
-
1662
- } );
1663
-
1664
- }
1665
-
1666
- }
1667
-
1668
- bindSkeleton( skeletons, geometryMap, modelMap ) {
1669
-
1670
- for ( const ID in skeletons ) {
1671
-
1672
- const skeleton = skeletons[ ID ];
1673
-
1674
- // Compute bone inverses from TransformLink rather than from the
1675
- // bones' current matrixWorld. The TransformLink matrices represent
1676
- // each bone's global transform at the time the skin weights were
1677
- // painted, which may differ from the scene-reconstructed transforms.
1678
- const boneInverses = [];
1679
-
1680
- for ( let i = 0, l = skeleton.bones.length; i < l; i ++ ) {
1681
-
1682
- const inverse = new Matrix4();
1683
-
1684
- if ( skeleton.bones[ i ] && skeleton.rawBones[ i ] ) {
1685
-
1686
- inverse.copy( skeleton.rawBones[ i ].transformLink ).invert();
1687
-
1688
- }
1689
-
1690
- boneInverses.push( inverse );
1691
-
1692
- }
1693
-
1694
- const parents = connections.get( parseInt( skeleton.ID ) ).parents;
1695
-
1696
- parents.forEach( function ( parent ) {
1697
-
1698
- if ( geometryMap.has( parent.ID ) ) {
1699
-
1700
- const geoID = parent.ID;
1701
- const geoRelationships = connections.get( geoID );
1702
-
1703
- geoRelationships.parents.forEach( function ( geoConnParent ) {
1704
-
1705
- if ( modelMap.has( geoConnParent.ID ) ) {
1706
-
1707
- const model = modelMap.get( geoConnParent.ID );
1708
-
1709
- // Use the mesh's current matrixWorld as bind matrix.
1710
- // The BindPose section is intentionally not used here
1711
- // since it may contain scale/rotation from the model
1712
- // hierarchy that is inconsistent with the TransformLink-
1713
- // based bone inverses. Always provide a bind matrix to
1714
- // prevent bind() from calling calculateInverses() which
1715
- // would overwrite the bone inverses computed above.
1716
- model.updateMatrixWorld( true );
1717
-
1718
- model.bind( new Skeleton( skeleton.bones, boneInverses ), model.matrixWorld );
1719
-
1720
- }
1721
-
1722
- } );
1723
-
1724
- }
1725
-
1726
- } );
1727
-
1728
- }
1729
-
1730
- }
1731
-
1732
- // Parse BindPose nodes and return a map of node ID to bind matrix.
1733
- parsePoseNodes() {
1734
-
1735
- const bindMatrices = {};
1736
-
1737
- if ( 'Pose' in fbxTree.Objects ) {
1738
-
1739
- const BindPoseNode = fbxTree.Objects.Pose;
1740
-
1741
- for ( const nodeID in BindPoseNode ) {
1742
-
1743
- if ( BindPoseNode[ nodeID ].attrType === 'BindPose' && BindPoseNode[ nodeID ].NbPoseNodes > 0 ) {
1744
-
1745
- const poseNodes = BindPoseNode[ nodeID ].PoseNode;
1746
-
1747
- if ( Array.isArray( poseNodes ) ) {
1748
-
1749
- poseNodes.forEach( function ( poseNode ) {
1750
-
1751
- bindMatrices[ poseNode.Node ] = new Matrix4().fromArray( poseNode.Matrix.a );
1752
-
1753
- } );
1754
-
1755
- } else {
1756
-
1757
- bindMatrices[ poseNodes.Node ] = new Matrix4().fromArray( poseNodes.Matrix.a );
1758
-
1759
- }
1760
-
1761
- }
1762
-
1763
- }
1764
-
1765
- }
1766
-
1767
- return bindMatrices;
1768
-
1769
- }
1770
-
1771
- addGlobalSceneSettings() {
1772
-
1773
- if ( 'GlobalSettings' in fbxTree ) {
1774
-
1775
- if ( 'AmbientColor' in fbxTree.GlobalSettings ) {
1776
-
1777
- // Parse ambient color - if it's not set to black (default), create an ambient light
1778
-
1779
- const ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
1780
- const r = ambientColor[ 0 ];
1781
- const g = ambientColor[ 1 ];
1782
- const b = ambientColor[ 2 ];
1783
-
1784
- if ( r !== 0 || g !== 0 || b !== 0 ) {
1785
-
1786
- const color = new Color().setRGB( r, g, b, SRGBColorSpace );
1787
- sceneGraph.add( new AmbientLight( color, 1 ) );
1788
-
1789
- }
1790
-
1791
- }
1792
-
1793
- if ( 'UnitScaleFactor' in fbxTree.GlobalSettings ) {
1794
-
1795
- sceneGraph.userData.unitScaleFactor = fbxTree.GlobalSettings.UnitScaleFactor.value;
1796
-
1797
- }
1798
-
1799
- }
1800
-
1801
- }
1802
-
1803
- }
1804
-
1805
- // parse Geometry data from FBXTree and return map of BufferGeometries
1806
- class GeometryParser {
1807
-
1808
- constructor() {
1809
-
1810
- this.negativeMaterialIndices = false;
1811
-
1812
- }
1813
-
1814
- // Parse nodes in FBXTree.Objects.Geometry
1815
- parse( deformers ) {
1816
-
1817
- const geometryMap = new Map();
1818
-
1819
- if ( 'Geometry' in fbxTree.Objects ) {
1820
-
1821
- const geoNodes = fbxTree.Objects.Geometry;
1822
-
1823
- for ( const nodeID in geoNodes ) {
1824
-
1825
- const relationships = connections.get( parseInt( nodeID ) );
1826
- const geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers );
1827
-
1828
- geometryMap.set( parseInt( nodeID ), geo );
1829
-
1830
- }
1831
-
1832
- }
1833
-
1834
- // report warnings
1835
-
1836
- if ( this.negativeMaterialIndices === true ) {
1837
-
1838
- console.warn( 'THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected.' );
1839
-
1840
- }
1841
-
1842
- return geometryMap;
1843
-
1844
- }
1845
-
1846
- // Parse single node in FBXTree.Objects.Geometry
1847
- parseGeometry( relationships, geoNode, deformers ) {
1848
-
1849
- switch ( geoNode.attrType ) {
1850
-
1851
- case 'Mesh':
1852
- return this.parseMeshGeometry( relationships, geoNode, deformers );
1853
-
1854
- case 'NurbsCurve':
1855
- return this.parseNurbsGeometry( geoNode );
1856
-
1857
- }
1858
-
1859
- }
1860
-
1861
- // Parse single node mesh geometry in FBXTree.Objects.Geometry
1862
- parseMeshGeometry( relationships, geoNode, deformers ) {
1863
-
1864
- const skeletons = deformers.skeletons;
1865
- const morphTargets = [];
1866
-
1867
- const modelNodes = relationships.parents.map( function ( parent ) {
1868
-
1869
- return fbxTree.Objects.Model[ parent.ID ];
1870
-
1871
- } );
1872
-
1873
- // don't create geometry if it is not associated with any models
1874
- if ( modelNodes.length === 0 ) return;
1875
-
1876
- const skeleton = relationships.children.reduce( function ( skeleton, child ) {
1877
-
1878
- if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
1879
-
1880
- return skeleton;
1881
-
1882
- }, null );
1883
-
1884
- relationships.children.forEach( function ( child ) {
1885
-
1886
- if ( deformers.morphTargets[ child.ID ] !== undefined ) {
1887
-
1888
- morphTargets.push( deformers.morphTargets[ child.ID ] );
1889
-
1890
- }
1891
-
1892
- } );
1893
-
1894
- // Assume one model and get the preRotation from that
1895
- // if there is more than one model associated with the geometry this may cause problems
1896
- const modelNode = modelNodes[ 0 ];
1897
-
1898
- const transformData = {};
1899
-
1900
- if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
1901
- if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
1902
-
1903
- if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value;
1904
- if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value;
1905
- if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value;
1906
-
1907
- const transform = generateTransform( transformData );
1908
-
1909
- return this.genGeometry( geoNode, skeleton, morphTargets, transform );
1910
-
1911
- }
1912
-
1913
- // Generate a BufferGeometry from a node in FBXTree.Objects.Geometry
1914
- genGeometry( geoNode, skeleton, morphTargets, preTransform ) {
1915
-
1916
- const geo = new BufferGeometry();
1917
- if ( geoNode.attrName ) geo.name = geoNode.attrName;
1918
-
1919
- const geoInfo = this.parseGeoNode( geoNode, skeleton );
1920
- const buffers = this.genBuffers( geoInfo );
1921
-
1922
- const positionAttribute = new Float32BufferAttribute( buffers.vertex, 3 );
1923
-
1924
- positionAttribute.applyMatrix4( preTransform );
1925
-
1926
- geo.setAttribute( 'position', positionAttribute );
1927
-
1928
- if ( buffers.colors.length > 0 ) {
1929
-
1930
- geo.setAttribute( 'color', new Float32BufferAttribute( buffers.colors, 3 ) );
1931
-
1932
- }
1933
-
1934
- if ( skeleton ) {
1935
-
1936
- geo.setAttribute( 'skinIndex', new Uint16BufferAttribute( buffers.weightsIndices, 4 ) );
1937
-
1938
- geo.setAttribute( 'skinWeight', new Float32BufferAttribute( buffers.vertexWeights, 4 ) );
1939
-
1940
- // used later to bind the skeleton to the model
1941
- geo.FBX_Deformer = skeleton;
1942
-
1943
- }
1944
-
1945
- if ( buffers.normal.length > 0 ) {
1946
-
1947
- const normalMatrix = new Matrix3().getNormalMatrix( preTransform );
1948
-
1949
- const normalAttribute = new Float32BufferAttribute( buffers.normal, 3 );
1950
- normalAttribute.applyNormalMatrix( normalMatrix );
1951
-
1952
- geo.setAttribute( 'normal', normalAttribute );
1953
-
1954
- }
1955
-
1956
- buffers.uvs.forEach( function ( uvBuffer, i ) {
1957
-
1958
- const name = i === 0 ? 'uv' : `uv${ i }`;
1959
-
1960
- geo.setAttribute( name, new Float32BufferAttribute( buffers.uvs[ i ], 2 ) );
1961
-
1962
- } );
1963
-
1964
- if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
1965
-
1966
- // Convert the material indices of each vertex into rendering groups on the geometry.
1967
- let prevMaterialIndex = buffers.materialIndex[ 0 ];
1968
- let startIndex = 0;
1969
-
1970
- buffers.materialIndex.forEach( function ( currentIndex, i ) {
1971
-
1972
- if ( currentIndex !== prevMaterialIndex ) {
1973
-
1974
- geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
1975
-
1976
- prevMaterialIndex = currentIndex;
1977
- startIndex = i;
1978
-
1979
- }
1980
-
1981
- } );
1982
-
1983
- // the loop above doesn't add the last group, do that here.
1984
- if ( geo.groups.length > 0 ) {
1985
-
1986
- const lastGroup = geo.groups[ geo.groups.length - 1 ];
1987
- const lastIndex = lastGroup.start + lastGroup.count;
1988
-
1989
- if ( lastIndex !== buffers.materialIndex.length ) {
1990
-
1991
- geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex );
1992
-
1993
- }
1994
-
1995
- }
1996
-
1997
- // case where there are multiple materials but the whole geometry is only
1998
- // using one of them
1999
- if ( geo.groups.length === 0 ) {
2000
-
2001
- geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] );
2002
-
2003
- }
2004
-
2005
- }
2006
-
2007
- this.addMorphTargets( geo, geoNode, morphTargets, preTransform );
2008
-
2009
- return geo;
2010
-
2011
- }
2012
-
2013
- parseGeoNode( geoNode, skeleton ) {
2014
-
2015
- const geoInfo = {};
2016
-
2017
- geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : [];
2018
- geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : [];
2019
-
2020
- if ( geoNode.LayerElementColor && geoNode.LayerElementColor[ 0 ].Colors ) {
2021
-
2022
- geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] );
2023
-
2024
- }
2025
-
2026
- if ( geoNode.LayerElementMaterial ) {
2027
-
2028
- geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] );
2029
-
2030
- }
2031
-
2032
- if ( geoNode.LayerElementNormal ) {
2033
-
2034
- geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] );
2035
-
2036
- }
2037
-
2038
- if ( geoNode.LayerElementUV ) {
2039
-
2040
- geoInfo.uv = [];
2041
-
2042
- let i = 0;
2043
- while ( geoNode.LayerElementUV[ i ] ) {
2044
-
2045
- if ( geoNode.LayerElementUV[ i ].UV ) {
2046
-
2047
- geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) );
2048
-
2049
- }
2050
-
2051
- i ++;
2052
-
2053
- }
2054
-
2055
- }
2056
-
2057
- geoInfo.weightTable = {};
2058
-
2059
- if ( skeleton !== null ) {
2060
-
2061
- geoInfo.skeleton = skeleton;
2062
-
2063
- skeleton.rawBones.forEach( function ( rawBone, i ) {
2064
-
2065
- // loop over the bone's vertex indices and weights
2066
- rawBone.indices.forEach( function ( index, j ) {
2067
-
2068
- if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = [];
2069
-
2070
- geoInfo.weightTable[ index ].push( {
2071
-
2072
- id: i,
2073
- weight: rawBone.weights[ j ],
2074
-
2075
- } );
2076
-
2077
- } );
2078
-
2079
- } );
2080
-
2081
- }
2082
-
2083
- return geoInfo;
2084
-
2085
- }
2086
-
2087
- genBuffers( geoInfo ) {
2088
-
2089
- const buffers = {
2090
- vertex: [],
2091
- normal: [],
2092
- colors: [],
2093
- uvs: [],
2094
- materialIndex: [],
2095
- vertexWeights: [],
2096
- weightsIndices: [],
2097
- };
2098
-
2099
- let polygonIndex = 0;
2100
- let faceLength = 0;
2101
- let displayedWeightsWarning = false;
2102
-
2103
- // these will hold data for a single face
2104
- let facePositionIndexes = [];
2105
- let faceNormals = [];
2106
- let faceColors = [];
2107
- let faceUVs = [];
2108
- let faceWeights = [];
2109
- let faceWeightIndices = [];
2110
-
2111
- const scope = this;
2112
- geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
2113
-
2114
- let materialIndex;
2115
- let endOfFace = false;
2116
-
2117
- // Face index and vertex index arrays are combined in a single array
2118
- // A cube with quad faces looks like this:
2119
- // PolygonVertexIndex: *24 {
2120
- // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
2121
- // }
2122
- // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
2123
- // to find index of last vertex bit shift the index: ^ - 1
2124
- if ( vertexIndex < 0 ) {
2125
-
2126
- vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
2127
- endOfFace = true;
2128
-
2129
- }
2130
-
2131
- let weightIndices = [];
2132
- let weights = [];
2133
-
2134
- facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
2135
-
2136
- if ( geoInfo.color ) {
2137
-
2138
- const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color );
2139
-
2140
- faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
2141
-
2142
- }
2143
-
2144
- if ( geoInfo.skeleton ) {
2145
-
2146
- if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) {
2147
-
2148
- geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) {
2149
-
2150
- weights.push( wt.weight );
2151
- weightIndices.push( wt.id );
2152
-
2153
- } );
2154
-
2155
-
2156
- }
2157
-
2158
- if ( weights.length > 4 ) {
2159
-
2160
- if ( ! displayedWeightsWarning ) {
2161
-
2162
- console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
2163
- displayedWeightsWarning = true;
2164
-
2165
- }
2166
-
2167
- const wIndex = [ 0, 0, 0, 0 ];
2168
- const Weight = [ 0, 0, 0, 0 ];
2169
-
2170
- weights.forEach( function ( weight, weightIndex ) {
2171
-
2172
- let currentWeight = weight;
2173
- let currentIndex = weightIndices[ weightIndex ];
2174
-
2175
- Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
2176
-
2177
- if ( currentWeight > comparedWeight ) {
2178
-
2179
- comparedWeightArray[ comparedWeightIndex ] = currentWeight;
2180
- currentWeight = comparedWeight;
2181
-
2182
- const tmp = wIndex[ comparedWeightIndex ];
2183
- wIndex[ comparedWeightIndex ] = currentIndex;
2184
- currentIndex = tmp;
2185
-
2186
- }
2187
-
2188
- } );
2189
-
2190
- } );
2191
-
2192
- weightIndices = wIndex;
2193
- weights = Weight;
2194
-
2195
- }
2196
-
2197
- // if the weight array is shorter than 4 pad with 0s
2198
- while ( weights.length < 4 ) {
2199
-
2200
- weights.push( 0 );
2201
- weightIndices.push( 0 );
2202
-
2203
- }
2204
-
2205
- for ( let i = 0; i < 4; ++ i ) {
2206
-
2207
- faceWeights.push( weights[ i ] );
2208
- faceWeightIndices.push( weightIndices[ i ] );
2209
-
2210
- }
2211
-
2212
- }
2213
-
2214
- if ( geoInfo.normal ) {
2215
-
2216
- const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal );
2217
-
2218
- faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
2219
-
2220
- }
2221
-
2222
- if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
2223
-
2224
- materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ];
2225
-
2226
- if ( materialIndex < 0 ) {
2227
-
2228
- scope.negativeMaterialIndices = true;
2229
- materialIndex = 0; // fallback
2230
-
2231
- }
2232
-
2233
- }
2234
-
2235
- if ( geoInfo.uv ) {
2236
-
2237
- geoInfo.uv.forEach( function ( uv, i ) {
2238
-
2239
- const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
2240
-
2241
- if ( faceUVs[ i ] === undefined ) {
2242
-
2243
- faceUVs[ i ] = [];
2244
-
2245
- }
2246
-
2247
- faceUVs[ i ].push( data[ 0 ] );
2248
- faceUVs[ i ].push( data[ 1 ] );
2249
-
2250
- } );
2251
-
2252
- }
2253
-
2254
- faceLength ++;
2255
-
2256
- if ( endOfFace ) {
2257
-
2258
- scope.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength );
2259
-
2260
- polygonIndex ++;
2261
- faceLength = 0;
2262
-
2263
- // reset arrays for the next face
2264
- facePositionIndexes = [];
2265
- faceNormals = [];
2266
- faceColors = [];
2267
- faceUVs = [];
2268
- faceWeights = [];
2269
- faceWeightIndices = [];
2270
-
2271
- }
2272
-
2273
- } );
2274
-
2275
- return buffers;
2276
-
2277
- }
2278
-
2279
- // See https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal
2280
- getNormalNewell( vertices ) {
2281
-
2282
- const normal = new Vector3( 0.0, 0.0, 0.0 );
2283
-
2284
- for ( let i = 0; i < vertices.length; i ++ ) {
2285
-
2286
- const current = vertices[ i ];
2287
- const next = vertices[ ( i + 1 ) % vertices.length ];
2288
-
2289
- normal.x += ( current.y - next.y ) * ( current.z + next.z );
2290
- normal.y += ( current.z - next.z ) * ( current.x + next.x );
2291
- normal.z += ( current.x - next.x ) * ( current.y + next.y );
2292
-
2293
- }
2294
-
2295
- normal.normalize();
2296
-
2297
- return normal;
2298
-
2299
- }
2300
-
2301
- getNormalTangentAndBitangent( vertices ) {
2302
-
2303
- const normalVector = this.getNormalNewell( vertices );
2304
- // Avoid up being equal or almost equal to normalVector
2305
- const up = Math.abs( normalVector.z ) > 0.5 ? new Vector3( 0.0, 1.0, 0.0 ) : new Vector3( 0.0, 0.0, 1.0 );
2306
- const tangent = up.cross( normalVector ).normalize();
2307
- const bitangent = normalVector.clone().cross( tangent ).normalize();
2308
-
2309
- return {
2310
- normal: normalVector,
2311
- tangent: tangent,
2312
- bitangent: bitangent
2313
- };
2314
-
2315
- }
2316
-
2317
- flattenVertex( vertex, normalTangent, normalBitangent ) {
2318
-
2319
- return new Vector2(
2320
- vertex.dot( normalTangent ),
2321
- vertex.dot( normalBitangent )
2322
- );
2323
-
2324
- }
2325
-
2326
- // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
2327
- genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {
2328
-
2329
- let triangles;
2330
-
2331
- if ( faceLength > 3 ) {
2332
-
2333
- // Triangulate n-gon using earcut
2334
-
2335
- const vertices = [];
2336
- // in morphing scenario vertexPositions represent morphPositions
2337
- // while baseVertexPositions represent the original geometry's positions
2338
- const positions = geoInfo.baseVertexPositions || geoInfo.vertexPositions;
2339
- for ( let i = 0; i < facePositionIndexes.length; i += 3 ) {
2340
-
2341
- vertices.push(
2342
- new Vector3(
2343
- positions[ facePositionIndexes[ i ] ],
2344
- positions[ facePositionIndexes[ i + 1 ] ],
2345
- positions[ facePositionIndexes[ i + 2 ] ]
2346
- )
2347
- );
2348
-
2349
- }
2350
-
2351
- const { tangent, bitangent } = this.getNormalTangentAndBitangent( vertices );
2352
- const triangulationInput = [];
2353
-
2354
- for ( const vertex of vertices ) {
2355
-
2356
- triangulationInput.push( this.flattenVertex( vertex, tangent, bitangent ) );
2357
-
2358
- }
2359
-
2360
- // When vertices is an array of [0,0,0] elements (which is the case for vertices not participating in morph)
2361
- // the triangulationInput will be an array of [0,0] elements
2362
- // resulting in an array of 0 triangles being returned from ShapeUtils.triangulateShape
2363
- // leading to not pushing into buffers.vertex the redundant vertices (the vertices that are not morphed).
2364
- // That's why, in order to support morphing scenario, "positions" is looking first for baseVertexPositions,
2365
- // so that we don't end up with an array of 0 triangles for the faces not participating in morph.
2366
- triangles = ShapeUtils.triangulateShape( triangulationInput, [] );
2367
-
2368
- } else {
2369
-
2370
- // Regular triangle, skip earcut triangulation step
2371
- triangles = [[ 0, 1, 2 ]];
2372
-
2373
- }
2374
-
2375
- for ( const [ i0, i1, i2 ] of triangles ) {
2376
-
2377
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i0 * 3 ] ] );
2378
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i0 * 3 + 1 ] ] );
2379
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i0 * 3 + 2 ] ] );
2380
-
2381
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i1 * 3 ] ] );
2382
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i1 * 3 + 1 ] ] );
2383
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i1 * 3 + 2 ] ] );
2384
-
2385
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i2 * 3 ] ] );
2386
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i2 * 3 + 1 ] ] );
2387
- buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i2 * 3 + 2 ] ] );
2388
-
2389
- if ( geoInfo.skeleton ) {
2390
-
2391
- buffers.vertexWeights.push( faceWeights[ i0 * 4 ] );
2392
- buffers.vertexWeights.push( faceWeights[ i0 * 4 + 1 ] );
2393
- buffers.vertexWeights.push( faceWeights[ i0 * 4 + 2 ] );
2394
- buffers.vertexWeights.push( faceWeights[ i0 * 4 + 3 ] );
2395
-
2396
- buffers.vertexWeights.push( faceWeights[ i1 * 4 ] );
2397
- buffers.vertexWeights.push( faceWeights[ i1 * 4 + 1 ] );
2398
- buffers.vertexWeights.push( faceWeights[ i1 * 4 + 2 ] );
2399
- buffers.vertexWeights.push( faceWeights[ i1 * 4 + 3 ] );
2400
-
2401
- buffers.vertexWeights.push( faceWeights[ i2 * 4 ] );
2402
- buffers.vertexWeights.push( faceWeights[ i2 * 4 + 1 ] );
2403
- buffers.vertexWeights.push( faceWeights[ i2 * 4 + 2 ] );
2404
- buffers.vertexWeights.push( faceWeights[ i2 * 4 + 3 ] );
2405
-
2406
- buffers.weightsIndices.push( faceWeightIndices[ i0 * 4 ] );
2407
- buffers.weightsIndices.push( faceWeightIndices[ i0 * 4 + 1 ] );
2408
- buffers.weightsIndices.push( faceWeightIndices[ i0 * 4 + 2 ] );
2409
- buffers.weightsIndices.push( faceWeightIndices[ i0 * 4 + 3 ] );
2410
-
2411
- buffers.weightsIndices.push( faceWeightIndices[ i1 * 4 ] );
2412
- buffers.weightsIndices.push( faceWeightIndices[ i1 * 4 + 1 ] );
2413
- buffers.weightsIndices.push( faceWeightIndices[ i1 * 4 + 2 ] );
2414
- buffers.weightsIndices.push( faceWeightIndices[ i1 * 4 + 3 ] );
2415
-
2416
- buffers.weightsIndices.push( faceWeightIndices[ i2 * 4 ] );
2417
- buffers.weightsIndices.push( faceWeightIndices[ i2 * 4 + 1 ] );
2418
- buffers.weightsIndices.push( faceWeightIndices[ i2 * 4 + 2 ] );
2419
- buffers.weightsIndices.push( faceWeightIndices[ i2 * 4 + 3 ] );
2420
-
2421
- }
2422
-
2423
- if ( geoInfo.color ) {
2424
-
2425
- buffers.colors.push( faceColors[ i0 * 3 ] );
2426
- buffers.colors.push( faceColors[ i0 * 3 + 1 ] );
2427
- buffers.colors.push( faceColors[ i0 * 3 + 2 ] );
2428
-
2429
- buffers.colors.push( faceColors[ i1 * 3 ] );
2430
- buffers.colors.push( faceColors[ i1 * 3 + 1 ] );
2431
- buffers.colors.push( faceColors[ i1 * 3 + 2 ] );
2432
-
2433
- buffers.colors.push( faceColors[ i2 * 3 ] );
2434
- buffers.colors.push( faceColors[ i2 * 3 + 1 ] );
2435
- buffers.colors.push( faceColors[ i2 * 3 + 2 ] );
2436
-
2437
- }
2438
-
2439
- if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
2440
-
2441
- buffers.materialIndex.push( materialIndex );
2442
- buffers.materialIndex.push( materialIndex );
2443
- buffers.materialIndex.push( materialIndex );
2444
-
2445
- }
2446
-
2447
- if ( geoInfo.normal ) {
2448
-
2449
- buffers.normal.push( faceNormals[ i0 * 3 ] );
2450
- buffers.normal.push( faceNormals[ i0 * 3 + 1 ] );
2451
- buffers.normal.push( faceNormals[ i0 * 3 + 2 ] );
2452
-
2453
- buffers.normal.push( faceNormals[ i1 * 3 ] );
2454
- buffers.normal.push( faceNormals[ i1 * 3 + 1 ] );
2455
- buffers.normal.push( faceNormals[ i1 * 3 + 2 ] );
2456
-
2457
- buffers.normal.push( faceNormals[ i2 * 3 ] );
2458
- buffers.normal.push( faceNormals[ i2 * 3 + 1 ] );
2459
- buffers.normal.push( faceNormals[ i2 * 3 + 2 ] );
2460
-
2461
- }
2462
-
2463
- if ( geoInfo.uv ) {
2464
-
2465
- geoInfo.uv.forEach( function ( uv, j ) {
2466
-
2467
- if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];
2468
-
2469
- buffers.uvs[ j ].push( faceUVs[ j ][ i0 * 2 ] );
2470
- buffers.uvs[ j ].push( faceUVs[ j ][ i0 * 2 + 1 ] );
2471
-
2472
- buffers.uvs[ j ].push( faceUVs[ j ][ i1 * 2 ] );
2473
- buffers.uvs[ j ].push( faceUVs[ j ][ i1 * 2 + 1 ] );
2474
-
2475
- buffers.uvs[ j ].push( faceUVs[ j ][ i2 * 2 ] );
2476
- buffers.uvs[ j ].push( faceUVs[ j ][ i2 * 2 + 1 ] );
2477
-
2478
- } );
2479
-
2480
- }
2481
-
2482
- }
2483
-
2484
- }
2485
-
2486
- addMorphTargets( parentGeo, parentGeoNode, morphTargets, preTransform ) {
2487
-
2488
- if ( morphTargets.length === 0 ) return;
2489
-
2490
- parentGeo.morphTargetsRelative = true;
2491
-
2492
- parentGeo.morphAttributes.position = [];
2493
- // parentGeo.morphAttributes.normal = []; // not implemented
2494
-
2495
- // Morph attribute positions are stored as deltas (morphTargetsRelative = true), so the
2496
- // translation component of the geometric transform must not be applied to them — only the
2497
- // rotation/scale part. Otherwise every delta gets the geometric translation added, which
2498
- // shifts morphed vertices away from their intended position by `weight * translation` as
2499
- // the influence increases.
2500
- const morphPreTransform = preTransform.clone().setPosition( 0, 0, 0 );
2501
-
2502
- const scope = this;
2503
- morphTargets.forEach( function ( morphTarget ) {
2504
-
2505
- morphTarget.rawTargets.forEach( function ( rawTarget ) {
2506
-
2507
- const morphGeoNode = fbxTree.Objects.Geometry[ rawTarget.geoID ];
2508
-
2509
- if ( morphGeoNode !== undefined ) {
2510
-
2511
- scope.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, morphPreTransform, rawTarget.name );
2512
-
2513
- }
2514
-
2515
- } );
2516
-
2517
- } );
2518
-
2519
- }
2520
-
2521
- // a morph geometry node is similar to a standard node, and the node is also contained
2522
- // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
2523
- // and a special attribute Index defining which vertices of the original geometry are affected
2524
- // Normal and position attributes only have data for the vertices that are affected by the morph
2525
- genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, name ) {
2526
-
2527
- const basePositions = parentGeoNode.Vertices !== undefined ? parentGeoNode.Vertices.a : [];
2528
- const baseIndices = parentGeoNode.PolygonVertexIndex !== undefined ? parentGeoNode.PolygonVertexIndex.a : [];
2529
-
2530
- const morphPositionsSparse = morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
2531
- const morphIndices = morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
2532
-
2533
- const length = parentGeo.attributes.position.count * 3;
2534
- const morphPositions = new Float32Array( length );
2535
-
2536
- for ( let i = 0; i < morphIndices.length; i ++ ) {
2537
-
2538
- const morphIndex = morphIndices[ i ] * 3;
2539
-
2540
- morphPositions[ morphIndex ] = morphPositionsSparse[ i * 3 ];
2541
- morphPositions[ morphIndex + 1 ] = morphPositionsSparse[ i * 3 + 1 ];
2542
- morphPositions[ morphIndex + 2 ] = morphPositionsSparse[ i * 3 + 2 ];
2543
-
2544
- }
2545
-
2546
- // TODO: add morph normal support
2547
- const morphGeoInfo = {
2548
- vertexIndices: baseIndices,
2549
- vertexPositions: morphPositions,
2550
- baseVertexPositions: basePositions
2551
- };
2552
-
2553
- const morphBuffers = this.genBuffers( morphGeoInfo );
2554
-
2555
- const positionAttribute = new Float32BufferAttribute( morphBuffers.vertex, 3 );
2556
- positionAttribute.name = name || morphGeoNode.attrName;
2557
-
2558
- positionAttribute.applyMatrix4( preTransform );
2559
-
2560
- parentGeo.morphAttributes.position.push( positionAttribute );
2561
-
2562
- }
2563
-
2564
- // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
2565
- parseNormals( NormalNode ) {
2566
-
2567
- const mappingType = NormalNode.MappingInformationType;
2568
- const referenceType = NormalNode.ReferenceInformationType;
2569
- const buffer = NormalNode.Normals.a;
2570
- let indexBuffer = [];
2571
- if ( referenceType === 'IndexToDirect' ) {
2572
-
2573
- if ( 'NormalIndex' in NormalNode ) {
2574
-
2575
- indexBuffer = NormalNode.NormalIndex.a;
2576
-
2577
- } else if ( 'NormalsIndex' in NormalNode ) {
2578
-
2579
- indexBuffer = NormalNode.NormalsIndex.a;
2580
-
2581
- }
2582
-
2583
- }
2584
-
2585
- return {
2586
- dataSize: 3,
2587
- buffer: buffer,
2588
- indices: indexBuffer,
2589
- mappingType: mappingType,
2590
- referenceType: referenceType
2591
- };
2592
-
2593
- }
2594
-
2595
- // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
2596
- parseUVs( UVNode ) {
2597
-
2598
- const mappingType = UVNode.MappingInformationType;
2599
- const referenceType = UVNode.ReferenceInformationType;
2600
- const buffer = UVNode.UV.a;
2601
- let indexBuffer = [];
2602
- if ( referenceType === 'IndexToDirect' ) {
2603
-
2604
- indexBuffer = UVNode.UVIndex.a;
2605
-
2606
- }
2607
-
2608
- return {
2609
- dataSize: 2,
2610
- buffer: buffer,
2611
- indices: indexBuffer,
2612
- mappingType: mappingType,
2613
- referenceType: referenceType
2614
- };
2615
-
2616
- }
2617
-
2618
- // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
2619
- parseVertexColors( ColorNode ) {
2620
-
2621
- const mappingType = ColorNode.MappingInformationType;
2622
- const referenceType = ColorNode.ReferenceInformationType;
2623
- const buffer = ColorNode.Colors.a;
2624
- let indexBuffer = [];
2625
- if ( referenceType === 'IndexToDirect' ) {
2626
-
2627
- indexBuffer = ColorNode.ColorIndex.a;
2628
-
2629
- }
2630
-
2631
- for ( let i = 0, c = new Color(); i < buffer.length; i += 4 ) {
2632
-
2633
- c.fromArray( buffer, i );
2634
- ColorManagement.colorSpaceToWorking( c, SRGBColorSpace );
2635
- c.toArray( buffer, i );
2636
-
2637
- }
2638
-
2639
- return {
2640
- dataSize: 4,
2641
- buffer: buffer,
2642
- indices: indexBuffer,
2643
- mappingType: mappingType,
2644
- referenceType: referenceType
2645
- };
2646
-
2647
- }
2648
-
2649
- // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
2650
- parseMaterialIndices( MaterialNode ) {
2651
-
2652
- const mappingType = MaterialNode.MappingInformationType;
2653
- const referenceType = MaterialNode.ReferenceInformationType;
2654
-
2655
- if ( mappingType === 'NoMappingInformation' ) {
2656
-
2657
- return {
2658
- dataSize: 1,
2659
- buffer: [ 0 ],
2660
- indices: [ 0 ],
2661
- mappingType: 'AllSame',
2662
- referenceType: referenceType
2663
- };
2664
-
2665
- }
2666
-
2667
- const materialIndexBuffer = MaterialNode.Materials.a;
2668
-
2669
- // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
2670
- // we expect.So we create an intermediate buffer that points to the index in the buffer,
2671
- // for conforming with the other functions we've written for other data.
2672
- const materialIndices = [];
2673
-
2674
- for ( let i = 0; i < materialIndexBuffer.length; ++ i ) {
2675
-
2676
- materialIndices.push( i );
2677
-
2678
- }
2679
-
2680
- return {
2681
- dataSize: 1,
2682
- buffer: materialIndexBuffer,
2683
- indices: materialIndices,
2684
- mappingType: mappingType,
2685
- referenceType: referenceType
2686
- };
2687
-
2688
- }
2689
-
2690
- // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
2691
- parseNurbsGeometry( geoNode ) {
2692
-
2693
- const order = parseInt( geoNode.Order );
2694
-
2695
- if ( isNaN( order ) ) {
2696
-
2697
- console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id );
2698
- return new BufferGeometry();
2699
-
2700
- }
2701
-
2702
- const degree = order - 1;
2703
-
2704
- const knots = geoNode.KnotVector.a;
2705
- const controlPoints = [];
2706
- const pointsValues = geoNode.Points.a;
2707
-
2708
- for ( let i = 0, l = pointsValues.length; i < l; i += 4 ) {
2709
-
2710
- controlPoints.push( new Vector4().fromArray( pointsValues, i ) );
2711
-
2712
- }
2713
-
2714
- let startKnot, endKnot;
2715
-
2716
- if ( geoNode.Form === 'Closed' ) {
2717
-
2718
- controlPoints.push( controlPoints[ 0 ] );
2719
-
2720
- } else if ( geoNode.Form === 'Periodic' ) {
2721
-
2722
- startKnot = degree;
2723
- endKnot = knots.length - 1 - startKnot;
2724
-
2725
- for ( let i = 0; i < degree; ++ i ) {
2726
-
2727
- controlPoints.push( controlPoints[ i ] );
2728
-
2729
- }
2730
-
2731
- }
2732
-
2733
- const curve = new NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
2734
- const points = curve.getPoints( controlPoints.length * 12 );
2735
-
2736
- return new BufferGeometry().setFromPoints( points );
2737
-
2738
- }
2739
-
2740
- }
2741
-
2742
- // parse animation data from FBXTree
2743
- class AnimationParser {
2744
-
2745
- constructor( trimAnimationClips ) {
2746
-
2747
- this.trimAnimationClips = trimAnimationClips;
2748
-
2749
- }
2750
-
2751
- // take raw animation clips and turn them into three.js animation clips
2752
- parse() {
2753
-
2754
- const animationClips = [];
2755
-
2756
- const rawClips = this.parseClips();
2757
-
2758
- if ( rawClips !== undefined ) {
2759
-
2760
- for ( const key in rawClips ) {
2761
-
2762
- const rawClip = rawClips[ key ];
2763
-
2764
- const clip = this.addClip( rawClip );
2765
-
2766
- animationClips.push( clip );
2767
-
2768
- }
2769
-
2770
- }
2771
-
2772
- return animationClips;
2773
-
2774
- }
2775
-
2776
- parseClips() {
2777
-
2778
- // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
2779
- // if this is undefined we can safely assume there are no animations
2780
- if ( fbxTree.Objects.AnimationCurve === undefined ) return undefined;
2781
-
2782
- const curveNodesMap = this.parseAnimationCurveNodes();
2783
-
2784
- this.parseAnimationCurves( curveNodesMap );
2785
-
2786
- const layersMap = this.parseAnimationLayers( curveNodesMap );
2787
- const rawClips = this.parseAnimStacks( layersMap );
2788
-
2789
- return rawClips;
2790
-
2791
- }
2792
-
2793
- // parse nodes in FBXTree.Objects.AnimationCurveNode
2794
- // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
2795
- // and is referenced by an AnimationLayer
2796
- parseAnimationCurveNodes() {
2797
-
2798
- const rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
2799
-
2800
- const curveNodesMap = new Map();
2801
-
2802
- for ( const nodeID in rawCurveNodes ) {
2803
-
2804
- const rawCurveNode = rawCurveNodes[ nodeID ];
2805
-
2806
- if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) {
2807
-
2808
- const curveNode = {
2809
-
2810
- id: rawCurveNode.id,
2811
- attr: rawCurveNode.attrName,
2812
- curves: {},
2813
-
2814
- };
2815
-
2816
- curveNodesMap.set( curveNode.id, curveNode );
2817
-
2818
- }
2819
-
2820
- }
2821
-
2822
- return curveNodesMap;
2823
-
2824
- }
2825
-
2826
- // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
2827
- // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
2828
- // axis ( e.g. times and values of x rotation)
2829
- parseAnimationCurves( curveNodesMap ) {
2830
-
2831
- const rawCurves = fbxTree.Objects.AnimationCurve;
2832
-
2833
- // TODO: Many values are identical up to roundoff error, but won't be optimised
2834
- // e.g. position times: [0, 0.4, 0. 8]
2835
- // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
2836
- // clearly, this should be optimised to
2837
- // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
2838
- // this shows up in nearly every FBX file, and generally time array is length > 100
2839
-
2840
- for ( const nodeID in rawCurves ) {
2841
-
2842
- const animationCurve = {
2843
-
2844
- id: rawCurves[ nodeID ].id,
2845
- times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ),
2846
- values: rawCurves[ nodeID ].KeyValueFloat.a,
2847
-
2848
- };
2849
-
2850
- const relationships = connections.get( animationCurve.id );
2851
-
2852
- if ( relationships !== undefined ) {
2853
-
2854
- const animationCurveID = relationships.parents[ 0 ].ID;
2855
- const animationCurveRelationship = relationships.parents[ 0 ].relationship;
2856
-
2857
- if ( animationCurveRelationship.match( /X/ ) ) {
2858
-
2859
- curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve;
2860
-
2861
- } else if ( animationCurveRelationship.match( /Y/ ) ) {
2862
-
2863
- curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve;
2864
-
2865
- } else if ( animationCurveRelationship.match( /Z/ ) ) {
2866
-
2867
- curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve;
2868
-
2869
- } else if ( animationCurveRelationship.match( /DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) {
2870
-
2871
- curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve;
2872
-
2873
- }
2874
-
2875
- }
2876
-
2877
- }
2878
-
2879
- }
2880
-
2881
- // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
2882
- // to various AnimationCurveNodes and is referenced by an AnimationStack node
2883
- // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
2884
- parseAnimationLayers( curveNodesMap ) {
2885
-
2886
- const rawLayers = fbxTree.Objects.AnimationLayer;
2887
-
2888
- const layersMap = new Map();
2889
-
2890
- for ( const nodeID in rawLayers ) {
2891
-
2892
- const layerCurveNodes = [];
2893
-
2894
- const connection = connections.get( parseInt( nodeID ) );
2895
-
2896
- if ( connection !== undefined ) {
2897
-
2898
- // all the animationCurveNodes used in the layer
2899
- const children = connection.children;
2900
-
2901
- children.forEach( function ( child, i ) {
2902
-
2903
- if ( curveNodesMap.has( child.ID ) ) {
2904
-
2905
- const curveNode = curveNodesMap.get( child.ID );
2906
-
2907
- // check that the curves are defined for at least one axis, otherwise ignore the curveNode
2908
- if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) {
2909
-
2910
- if ( layerCurveNodes[ i ] === undefined ) {
2911
-
2912
- const filteredParents = connections.get( child.ID ).parents.filter( function ( parent ) {
2913
-
2914
- return parent.relationship !== undefined;
2915
-
2916
- } );
2917
-
2918
- if ( filteredParents.length === 0 ) return;
2919
-
2920
- const modelID = filteredParents[ 0 ].ID;
2921
-
2922
- if ( modelID !== undefined ) {
2923
-
2924
- const rawModel = fbxTree.Objects.Model[ modelID.toString() ];
2925
-
2926
- if ( rawModel === undefined ) {
2927
-
2928
- console.warn( 'THREE.FBXLoader: Encountered a unused curve.', child );
2929
- return;
2930
-
2931
- }
2932
-
2933
- const node = {
2934
-
2935
- modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
2936
- ID: rawModel.id,
2937
- initialPosition: [ 0, 0, 0 ],
2938
- initialRotation: [ 0, 0, 0 ],
2939
- initialScale: [ 1, 1, 1 ],
2940
-
2941
- };
2942
-
2943
- sceneGraph.traverse( function ( child ) {
2944
-
2945
- if ( child.ID === rawModel.id ) {
2946
-
2947
- node.transform = child.matrix;
2948
-
2949
- if ( child.userData.transformData ) {
2950
-
2951
- node.eulerOrder = child.userData.transformData.eulerOrder;
2952
-
2953
- if ( child.userData.transformData.rotation ) node.initialRotation = child.userData.transformData.rotation;
2954
-
2955
- }
2956
-
2957
- }
2958
-
2959
- } );
2960
-
2961
- if ( ! node.transform ) node.transform = new Matrix4();
2962
-
2963
- // if the animated model is pre rotated, we'll have to apply the pre rotations to every
2964
- // animation value as well
2965
- if ( 'PreRotation' in rawModel ) node.preRotation = rawModel.PreRotation.value;
2966
- if ( 'PostRotation' in rawModel ) node.postRotation = rawModel.PostRotation.value;
2967
-
2968
- layerCurveNodes[ i ] = node;
2969
-
2970
- }
2971
-
2972
- }
2973
-
2974
- if ( layerCurveNodes[ i ] ) layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
2975
-
2976
- } else if ( curveNode.curves.morph !== undefined ) {
2977
-
2978
- if ( layerCurveNodes[ i ] === undefined ) {
2979
-
2980
- const filteredParents = connections.get( child.ID ).parents.filter( function ( parent ) {
2981
-
2982
- return parent.relationship !== undefined;
2983
-
2984
- } );
2985
-
2986
- if ( filteredParents.length === 0 ) return;
2987
-
2988
- const deformerID = filteredParents[ 0 ].ID;
2989
-
2990
- const morpherID = connections.get( deformerID ).parents[ 0 ].ID;
2991
- const geoID = connections.get( morpherID ).parents[ 0 ].ID;
2992
-
2993
- // assuming geometry is not used in more than one model
2994
- const modelID = connections.get( geoID ).parents[ 0 ].ID;
2995
-
2996
- const rawModel = fbxTree.Objects.Model[ modelID ];
2997
-
2998
- const node = {
2999
-
3000
- modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
3001
- morphName: fbxTree.Objects.Deformer[ deformerID ].attrName,
3002
-
3003
- };
3004
-
3005
- layerCurveNodes[ i ] = node;
3006
-
3007
- }
3008
-
3009
- layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
3010
-
3011
- }
3012
-
3013
- }
3014
-
3015
- } );
3016
-
3017
- layersMap.set( parseInt( nodeID ), layerCurveNodes );
3018
-
3019
- }
3020
-
3021
- }
3022
-
3023
- return layersMap;
3024
-
3025
- }
3026
-
3027
- // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
3028
- // hierarchy. Each Stack node will be used to create an AnimationClip
3029
- parseAnimStacks( layersMap ) {
3030
-
3031
- const rawStacks = fbxTree.Objects.AnimationStack;
3032
-
3033
- // connect the stacks (clips) up to the layers
3034
- const rawClips = {};
3035
-
3036
- for ( const nodeID in rawStacks ) {
3037
-
3038
- const children = connections.get( parseInt( nodeID ) ).children;
3039
-
3040
- if ( children.length > 1 ) {
3041
-
3042
- // it seems like stacks will always be associated with a single layer. But just in case there are files
3043
- // where there are multiple layers per stack, we'll display a warning
3044
- console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
3045
-
3046
- }
3047
-
3048
- const layer = layersMap.get( children[ 0 ].ID );
3049
- const rawStack = rawStacks[ nodeID ];
3050
-
3051
- rawClips[ nodeID ] = {
3052
-
3053
- name: rawStack.attrName,
3054
- layer: layer,
3055
- localStart: rawStack.LocalStart !== undefined ? convertFBXTimeToSeconds( Number( rawStack.LocalStart.value ) ) : 0,
3056
- localStop: rawStack.LocalStop !== undefined ? convertFBXTimeToSeconds( Number( rawStack.LocalStop.value ) ) : 0,
3057
-
3058
- };
3059
-
3060
- }
3061
-
3062
- return rawClips;
3063
-
3064
- }
3065
-
3066
- addClip( rawClip ) {
3067
-
3068
- let tracks = [];
3069
-
3070
- const scope = this;
3071
- rawClip.layer.forEach( function ( rawTracks ) {
3072
-
3073
- tracks = tracks.concat( scope.generateTracks( rawTracks ) );
3074
-
3075
- } );
3076
-
3077
- if ( this.trimAnimationClips === true && rawClip.localStop > rawClip.localStart ) {
3078
-
3079
- tracks = this.trimTracks( tracks, rawClip.localStart, rawClip.localStop );
3080
-
3081
- }
3082
-
3083
- return new AnimationClip( rawClip.name, - 1, tracks );
3084
-
3085
- }
3086
-
3087
- // trims the given tracks to the time range [ startTime, endTime ] and shifts
3088
- // them so they start at time zero. tracks without keyframes in the range are discarded
3089
- trimTracks( tracks, startTime, endTime ) {
3090
-
3091
- // track times are stored as float32 so compare against float32 boundaries
3092
- // to keep keyframes lying exactly on the range limits
3093
-
3094
- const start = Math.fround( startTime );
3095
- const end = Math.fround( endTime );
3096
-
3097
- const trimmedTracks = [];
3098
-
3099
- for ( let i = 0; i < tracks.length; i ++ ) {
3100
-
3101
- const track = tracks[ i ];
3102
- const stride = track.getValueSize();
3103
-
3104
- const times = [];
3105
- const values = [];
3106
-
3107
- for ( let j = 0; j < track.times.length; j ++ ) {
3108
-
3109
- const time = track.times[ j ];
3110
-
3111
- if ( time < start || time > end ) continue;
3112
-
3113
- times.push( time - start );
3114
-
3115
- for ( let k = 0; k < stride; k ++ ) {
3116
-
3117
- values.push( track.values[ j * stride + k ] );
3118
-
3119
- }
3120
-
3121
- }
3122
-
3123
- if ( times.length === 0 ) continue;
3124
-
3125
- track.times = new Float32Array( times );
3126
- track.values = new Float32Array( values );
3127
-
3128
- trimmedTracks.push( track );
3129
-
3130
- }
3131
-
3132
- return trimmedTracks;
3133
-
3134
- }
3135
-
3136
- generateTracks( rawTracks ) {
3137
-
3138
- const tracks = [];
3139
-
3140
- let initialPosition = new Vector3();
3141
- let initialScale = new Vector3();
3142
-
3143
- if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, new Quaternion(), initialScale );
3144
-
3145
- initialPosition = initialPosition.toArray();
3146
- initialScale = initialScale.toArray();
3147
-
3148
- if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) {
3149
-
3150
- const positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' );
3151
- if ( positionTrack !== undefined ) tracks.push( positionTrack );
3152
-
3153
- }
3154
-
3155
- if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) {
3156
-
3157
- const rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, rawTracks.preRotation, rawTracks.postRotation, rawTracks.eulerOrder, rawTracks.initialRotation );
3158
- if ( rotationTrack !== undefined ) tracks.push( rotationTrack );
3159
-
3160
- }
3161
-
3162
- if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) {
3163
-
3164
- const scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' );
3165
- if ( scaleTrack !== undefined ) tracks.push( scaleTrack );
3166
-
3167
- }
3168
-
3169
- if ( rawTracks.DeformPercent !== undefined ) {
3170
-
3171
- const morphTrack = this.generateMorphTrack( rawTracks );
3172
- if ( morphTrack !== undefined ) tracks.push( morphTrack );
3173
-
3174
- }
3175
-
3176
- return tracks;
3177
-
3178
- }
3179
-
3180
- generateVectorTrack( modelName, curves, initialValue, type ) {
3181
-
3182
- const times = this.getTimesForAllAxes( curves );
3183
- const values = this.getKeyframeTrackValues( times, curves, initialValue );
3184
-
3185
- return new VectorKeyframeTrack( modelName + '.' + type, times, values );
3186
-
3187
- }
3188
-
3189
- generateRotationTrack( modelName, curves, preRotation, postRotation, eulerOrder, initialRotation ) {
3190
-
3191
- let times;
3192
- let values;
3193
-
3194
- if ( curves.x !== undefined || curves.y !== undefined || curves.z !== undefined ) {
3195
-
3196
- // Get merged, sorted, unique times from all available curves
3197
- const mergedTimes = this.getTimesForAllAxes( curves );
3198
-
3199
- if ( mergedTimes.length > 0 ) {
3200
-
3201
- const initialRot = initialRotation || [ 0, 0, 0 ];
3202
-
3203
- // Synchronize all curves to the merged time array.
3204
- // Missing axes are filled with constant values from the initial rotation (Lcl Rotation).
3205
- // Existing curves at different times are linearly interpolated.
3206
- const syncX = this.synchronizeCurve( curves.x, mergedTimes, initialRot[ 0 ] );
3207
- const syncY = this.synchronizeCurve( curves.y, mergedTimes, initialRot[ 1 ] );
3208
- const syncZ = this.synchronizeCurve( curves.z, mergedTimes, initialRot[ 2 ] );
3209
-
3210
- const result = this.interpolateRotations( syncX, syncY, syncZ, eulerOrder );
3211
-
3212
- times = result[ 0 ];
3213
- values = result[ 1 ];
3214
-
3215
- }
3216
-
3217
- }
3218
-
3219
- // For Maya models using "Joint Orient", Euler order only applies to rotation, not pre/post-rotations
3220
- const defaultEulerOrder = getEulerOrder( 0 );
3221
-
3222
- if ( preRotation !== undefined ) {
3223
-
3224
- preRotation = preRotation.map( MathUtils.degToRad );
3225
- preRotation.push( defaultEulerOrder );
3226
-
3227
- preRotation = new Euler().fromArray( preRotation );
3228
- preRotation = new Quaternion().setFromEuler( preRotation );
3229
-
3230
- }
3231
-
3232
- if ( postRotation !== undefined ) {
3233
-
3234
- postRotation = postRotation.map( MathUtils.degToRad );
3235
- postRotation.push( defaultEulerOrder );
3236
-
3237
- postRotation = new Euler().fromArray( postRotation );
3238
- postRotation = new Quaternion().setFromEuler( postRotation ).invert();
3239
-
3240
- }
3241
-
3242
- const quaternion = new Quaternion();
3243
- const euler = new Euler();
3244
-
3245
- const quaternionValues = [];
3246
-
3247
- if ( ! values || ! times ) return undefined;
3248
-
3249
- for ( let i = 0; i < values.length; i += 3 ) {
3250
-
3251
- euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], eulerOrder );
3252
- quaternion.setFromEuler( euler );
3253
-
3254
- if ( preRotation !== undefined ) quaternion.premultiply( preRotation );
3255
- if ( postRotation !== undefined ) quaternion.multiply( postRotation );
3256
-
3257
- // Check unroll
3258
- if ( i > 2 ) {
3259
-
3260
- const prevQuat = new Quaternion().fromArray(
3261
- quaternionValues,
3262
- ( ( i - 3 ) / 3 ) * 4
3263
- );
3264
-
3265
- if ( prevQuat.dot( quaternion ) < 0 ) {
3266
-
3267
- quaternion.set( - quaternion.x, - quaternion.y, - quaternion.z, - quaternion.w );
3268
-
3269
- }
3270
-
3271
- }
3272
-
3273
- quaternion.toArray( quaternionValues, ( i / 3 ) * 4 );
3274
-
3275
- }
3276
-
3277
- return new QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues );
3278
-
3279
- }
3280
-
3281
- generateMorphTrack( rawTracks ) {
3282
-
3283
- const curves = rawTracks.DeformPercent.curves.morph;
3284
- const values = curves.values.map( function ( val ) {
3285
-
3286
- return val / 100;
3287
-
3288
- } );
3289
-
3290
- const morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ];
3291
-
3292
- return new NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values );
3293
-
3294
- }
3295
-
3296
- // For all animated objects, times are defined separately for each axis
3297
- // Here we'll combine the times into one sorted array without duplicates
3298
- getTimesForAllAxes( curves ) {
3299
-
3300
- let times = [];
3301
-
3302
- // first join together the times for each axis, if defined
3303
- if ( curves.x !== undefined ) times = times.concat( curves.x.times );
3304
- if ( curves.y !== undefined ) times = times.concat( curves.y.times );
3305
- if ( curves.z !== undefined ) times = times.concat( curves.z.times );
3306
-
3307
- // then sort them
3308
- times = times.sort( function ( a, b ) {
3309
-
3310
- return a - b;
3311
-
3312
- } );
3313
-
3314
- // and remove duplicates
3315
- if ( times.length > 1 ) {
3316
-
3317
- let targetIndex = 1;
3318
- let lastValue = times[ 0 ];
3319
- for ( let i = 1; i < times.length; i ++ ) {
3320
-
3321
- const currentValue = times[ i ];
3322
- if ( currentValue !== lastValue ) {
3323
-
3324
- times[ targetIndex ] = currentValue;
3325
- lastValue = currentValue;
3326
- targetIndex ++;
3327
-
3328
- }
3329
-
3330
- }
3331
-
3332
- times = times.slice( 0, targetIndex );
3333
-
3334
- }
3335
-
3336
- return times;
3337
-
3338
- }
3339
-
3340
- getKeyframeTrackValues( times, curves, initialValue ) {
3341
-
3342
- const prevValue = initialValue;
3343
-
3344
- const values = [];
3345
-
3346
- let xIndex = - 1;
3347
- let yIndex = - 1;
3348
- let zIndex = - 1;
3349
-
3350
- times.forEach( function ( time ) {
3351
-
3352
- if ( curves.x ) xIndex = curves.x.times.indexOf( time );
3353
- if ( curves.y ) yIndex = curves.y.times.indexOf( time );
3354
- if ( curves.z ) zIndex = curves.z.times.indexOf( time );
3355
-
3356
- // if there is an x value defined for this frame, use that
3357
- if ( xIndex !== - 1 ) {
3358
-
3359
- const xValue = curves.x.values[ xIndex ];
3360
- values.push( xValue );
3361
- prevValue[ 0 ] = xValue;
3362
-
3363
- } else {
3364
-
3365
- // otherwise use the x value from the previous frame
3366
- values.push( prevValue[ 0 ] );
3367
-
3368
- }
3369
-
3370
- if ( yIndex !== - 1 ) {
3371
-
3372
- const yValue = curves.y.values[ yIndex ];
3373
- values.push( yValue );
3374
- prevValue[ 1 ] = yValue;
3375
-
3376
- } else {
3377
-
3378
- values.push( prevValue[ 1 ] );
3379
-
3380
- }
3381
-
3382
- if ( zIndex !== - 1 ) {
3383
-
3384
- const zValue = curves.z.values[ zIndex ];
3385
- values.push( zValue );
3386
- prevValue[ 2 ] = zValue;
3387
-
3388
- } else {
3389
-
3390
- values.push( prevValue[ 2 ] );
3391
-
3392
- }
3393
-
3394
- } );
3395
-
3396
- return values;
3397
-
3398
- }
3399
-
3400
- // Synchronize a curve to a target time array using linear interpolation.
3401
- // If the curve is undefined (axis not animated), returns constant values from initialValue.
3402
- synchronizeCurve( curve, targetTimes, initialValue ) {
3403
-
3404
- if ( curve === undefined ) {
3405
-
3406
- return { times: targetTimes, values: targetTimes.map( () => initialValue ) };
3407
-
3408
- }
3409
-
3410
- // If the curve already has the same number of keyframes as the target, assume times match
3411
- if ( curve.times.length === targetTimes.length ) return curve;
3412
-
3413
- // Linearly interpolate curve values at each target time
3414
- const values = [];
3415
-
3416
- for ( let i = 0; i < targetTimes.length; i ++ ) {
3417
-
3418
- values.push( this.sampleCurveValue( curve, targetTimes[ i ], initialValue ) );
3419
-
3420
- }
3421
-
3422
- return { times: targetTimes, values: values };
3423
-
3424
- }
3425
-
3426
- // Sample a single value from a curve at a given time using linear interpolation
3427
- sampleCurveValue( curve, time, initialValue ) {
3428
-
3429
- const times = curve.times;
3430
- const values = curve.values;
3431
-
3432
- // Before first keyframe
3433
- if ( time <= times[ 0 ] ) return values[ 0 ];
3434
-
3435
- // After last keyframe
3436
- if ( time >= times[ times.length - 1 ] ) return values[ values.length - 1 ];
3437
-
3438
- // Find surrounding keyframes and linearly interpolate
3439
- for ( let i = 0; i < times.length - 1; i ++ ) {
3440
-
3441
- if ( time >= times[ i ] && time <= times[ i + 1 ] ) {
3442
-
3443
- if ( times[ i ] === time ) return values[ i ];
3444
-
3445
- const alpha = ( time - times[ i ] ) / ( times[ i + 1 ] - times[ i ] );
3446
- return values[ i ] * ( 1 - alpha ) + values[ i + 1 ] * alpha;
3447
-
3448
- }
3449
-
3450
- }
3451
-
3452
- return initialValue;
3453
-
3454
- }
3455
-
3456
- // Rotations are defined as Euler angles which can have values of any size
3457
- // These will be converted to quaternions which don't support values greater than
3458
- // PI, so we'll interpolate large rotations
3459
- interpolateRotations( curvex, curvey, curvez, eulerOrder ) {
3460
-
3461
- const times = [];
3462
- const values = [];
3463
-
3464
- // Add first frame
3465
- times.push( curvex.times[ 0 ] );
3466
- values.push( MathUtils.degToRad( curvex.values[ 0 ] ) );
3467
- values.push( MathUtils.degToRad( curvey.values[ 0 ] ) );
3468
- values.push( MathUtils.degToRad( curvez.values[ 0 ] ) );
3469
-
3470
- for ( let i = 1; i < curvex.values.length; i ++ ) {
3471
-
3472
- const initialValue = [
3473
- curvex.values[ i - 1 ],
3474
- curvey.values[ i - 1 ],
3475
- curvez.values[ i - 1 ],
3476
- ];
3477
-
3478
- if ( isNaN( initialValue[ 0 ] ) || isNaN( initialValue[ 1 ] ) || isNaN( initialValue[ 2 ] ) ) {
3479
-
3480
- continue;
3481
-
3482
- }
3483
-
3484
- const initialValueRad = initialValue.map( MathUtils.degToRad );
3485
-
3486
- const currentValue = [
3487
- curvex.values[ i ],
3488
- curvey.values[ i ],
3489
- curvez.values[ i ],
3490
- ];
3491
-
3492
- if ( isNaN( currentValue[ 0 ] ) || isNaN( currentValue[ 1 ] ) || isNaN( currentValue[ 2 ] ) ) {
3493
-
3494
- continue;
3495
-
3496
- }
3497
-
3498
- const currentValueRad = currentValue.map( MathUtils.degToRad );
3499
-
3500
- const valuesSpan = [
3501
- currentValue[ 0 ] - initialValue[ 0 ],
3502
- currentValue[ 1 ] - initialValue[ 1 ],
3503
- currentValue[ 2 ] - initialValue[ 2 ],
3504
- ];
3505
-
3506
- const absoluteSpan = [
3507
- Math.abs( valuesSpan[ 0 ] ),
3508
- Math.abs( valuesSpan[ 1 ] ),
3509
- Math.abs( valuesSpan[ 2 ] ),
3510
- ];
3511
-
3512
- if ( absoluteSpan[ 0 ] >= 180 || absoluteSpan[ 1 ] >= 180 || absoluteSpan[ 2 ] >= 180 ) {
3513
-
3514
- const maxAbsSpan = Math.max( ...absoluteSpan );
3515
-
3516
- const numSubIntervals = maxAbsSpan / 180;
3517
-
3518
- const E1 = new Euler( ...initialValueRad, eulerOrder );
3519
- const E2 = new Euler( ...currentValueRad, eulerOrder );
3520
-
3521
- const Q1 = new Quaternion().setFromEuler( E1 );
3522
- const Q2 = new Quaternion().setFromEuler( E2 );
3523
-
3524
- // Check unroll
3525
- if ( Q1.dot( Q2 ) < 0 ) {
3526
-
3527
- Q2.set( - Q2.x, - Q2.y, - Q2.z, - Q2.w );
3528
-
3529
- }
3530
-
3531
- // Interpolate
3532
- const initialTime = curvex.times[ i - 1 ];
3533
- const timeSpan = curvex.times[ i ] - initialTime;
3534
-
3535
- const Q = new Quaternion();
3536
- const E = new Euler();
3537
- for ( let t = 0; t < 1; t += 1 / numSubIntervals ) {
3538
-
3539
- Q.copy( Q1.clone().slerp( Q2.clone(), t ) );
3540
-
3541
- times.push( initialTime + t * timeSpan );
3542
- E.setFromQuaternion( Q, eulerOrder );
3543
-
3544
- values.push( E.x );
3545
- values.push( E.y );
3546
- values.push( E.z );
3547
-
3548
- }
3549
-
3550
- } else {
3551
-
3552
- times.push( curvex.times[ i ] );
3553
- values.push( MathUtils.degToRad( curvex.values[ i ] ) );
3554
- values.push( MathUtils.degToRad( curvey.values[ i ] ) );
3555
- values.push( MathUtils.degToRad( curvez.values[ i ] ) );
3556
-
3557
- }
3558
-
3559
- }
3560
-
3561
- return [ times, values ];
3562
-
3563
- }
3564
-
3565
- }
3566
-
3567
- // parse an FBX file in ASCII format
3568
- class TextParser {
3569
-
3570
- getPrevNode() {
3571
-
3572
- return this.nodeStack[ this.currentIndent - 2 ];
3573
-
3574
- }
3575
-
3576
- getCurrentNode() {
3577
-
3578
- return this.nodeStack[ this.currentIndent - 1 ];
3579
-
3580
- }
3581
-
3582
- getCurrentProp() {
3583
-
3584
- return this.currentProp;
3585
-
3586
- }
3587
-
3588
- pushStack( node ) {
3589
-
3590
- this.nodeStack.push( node );
3591
- this.currentIndent += 1;
3592
-
3593
- }
3594
-
3595
- popStack() {
3596
-
3597
- this.nodeStack.pop();
3598
- this.currentIndent -= 1;
3599
-
3600
- }
3601
-
3602
- setCurrentProp( val, name ) {
3603
-
3604
- this.currentProp = val;
3605
- this.currentPropName = name;
3606
-
3607
- }
3608
-
3609
- parse( text ) {
3610
-
3611
- this.currentIndent = 0;
3612
-
3613
- this.allNodes = new FBXTree();
3614
- this.nodeStack = [];
3615
- this.currentProp = [];
3616
- this.currentPropName = '';
3617
-
3618
- const scope = this;
3619
-
3620
- const split = text.split( /[\r\n]+/ );
3621
-
3622
- split.forEach( function ( line, i ) {
3623
-
3624
- const matchComment = line.match( /^[\s\t]*;/ );
3625
- const matchEmpty = line.match( /^[\s\t]*$/ );
3626
-
3627
- if ( matchComment || matchEmpty ) return;
3628
-
3629
- const matchBeginning = line.match( '^\\t{' + scope.currentIndent + '}(\\w+):(.*){', '' );
3630
- const matchProperty = line.match( '^\\t{' + ( scope.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
3631
- const matchEnd = line.match( '^\\t{' + ( scope.currentIndent - 1 ) + '}}' );
3632
-
3633
- if ( matchBeginning ) {
3634
-
3635
- scope.parseNodeBegin( line, matchBeginning );
3636
-
3637
- } else if ( matchProperty ) {
3638
-
3639
- scope.parseNodeProperty( line, matchProperty, split[ ++ i ] );
3640
-
3641
- } else if ( matchEnd ) {
3642
-
3643
- scope.popStack();
3644
-
3645
- } else if ( line.match( /^[^\s\t}]/ ) ) {
3646
-
3647
- // large arrays are split over multiple lines terminated with a ',' character
3648
- // if this is encountered the line needs to be joined to the previous line
3649
- scope.parseNodePropertyContinued( line );
3650
-
3651
- }
3652
-
3653
- } );
3654
-
3655
- return this.allNodes;
3656
-
3657
- }
3658
-
3659
- parseNodeBegin( line, property ) {
3660
-
3661
- const nodeName = property[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
3662
-
3663
- const nodeAttrs = property[ 2 ].split( ',' ).map( function ( attr ) {
3664
-
3665
- return attr.trim().replace( /^"/, '' ).replace( /"$/, '' );
3666
-
3667
- } );
3668
-
3669
- const node = { name: nodeName };
3670
- const attrs = this.parseNodeAttr( nodeAttrs );
3671
-
3672
- const currentNode = this.getCurrentNode();
3673
-
3674
- // a top node
3675
- if ( this.currentIndent === 0 ) {
3676
-
3677
- this.allNodes.add( nodeName, node );
3678
-
3679
- } else { // a subnode
3680
-
3681
- // if the subnode already exists, append it
3682
- if ( nodeName in currentNode ) {
3683
-
3684
- // special case Pose needs PoseNodes as an array
3685
- if ( nodeName === 'PoseNode' ) {
3686
-
3687
- currentNode.PoseNode.push( node );
3688
-
3689
- } else if ( currentNode[ nodeName ].id !== undefined ) {
3690
-
3691
- currentNode[ nodeName ] = {};
3692
- currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
3693
-
3694
- }
3695
-
3696
- if ( attrs.id !== '' ) currentNode[ nodeName ][ attrs.id ] = node;
3697
-
3698
- } else if ( typeof attrs.id === 'number' ) {
3699
-
3700
- currentNode[ nodeName ] = {};
3701
- currentNode[ nodeName ][ attrs.id ] = node;
3702
-
3703
- } else if ( nodeName !== 'Properties70' ) {
3704
-
3705
- if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ];
3706
- else currentNode[ nodeName ] = node;
3707
-
3708
- }
3709
-
3710
- }
3711
-
3712
- if ( typeof attrs.id === 'number' ) node.id = attrs.id;
3713
- if ( attrs.name !== '' ) node.attrName = attrs.name;
3714
- if ( attrs.type !== '' ) node.attrType = attrs.type;
3715
-
3716
- this.pushStack( node );
3717
-
3718
- }
3719
-
3720
- parseNodeAttr( attrs ) {
3721
-
3722
- let id = attrs[ 0 ];
3723
-
3724
- if ( attrs[ 0 ] !== '' ) {
3725
-
3726
- id = parseInt( attrs[ 0 ] );
3727
-
3728
- if ( isNaN( id ) ) {
3729
-
3730
- id = attrs[ 0 ];
3731
-
3732
- }
3733
-
3734
- }
3735
-
3736
- let name = '', type = '';
3737
-
3738
- if ( attrs.length > 1 ) {
3739
-
3740
- name = attrs[ 1 ].replace( /^(\w+)::/, '' );
3741
- type = attrs[ 2 ];
3742
-
3743
- }
3744
-
3745
- return { id: id, name: name, type: type };
3746
-
3747
- }
3748
-
3749
- parseNodeProperty( line, property, contentLine ) {
3750
-
3751
- let propName = property[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
3752
- let propValue = property[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
3753
-
3754
- // for special case: base64 image data follows "Content: ," line
3755
- // Content: ,
3756
- // "/9j/4RDaRXhpZgAATU0A..."
3757
- if ( propName === 'Content' && propValue === ',' ) {
3758
-
3759
- propValue = contentLine.replace( /"/g, '' ).replace( /,$/, '' ).trim();
3760
-
3761
- }
3762
-
3763
- const currentNode = this.getCurrentNode();
3764
- const parentName = currentNode.name;
3765
-
3766
- if ( parentName === 'Properties70' ) {
3767
-
3768
- this.parseNodeSpecialProperty( line, propName, propValue );
3769
- return;
3770
-
3771
- }
3772
-
3773
- // Connections
3774
- if ( propName === 'C' ) {
3775
-
3776
- const connProps = propValue.split( ',' ).slice( 1 );
3777
- const from = parseInt( connProps[ 0 ] );
3778
- const to = parseInt( connProps[ 1 ] );
3779
-
3780
- let rest = propValue.split( ',' ).slice( 3 );
3781
-
3782
- rest = rest.map( function ( elem ) {
3783
-
3784
- return elem.trim().replace( /^"/, '' );
3785
-
3786
- } );
3787
-
3788
- propName = 'connections';
3789
- propValue = [ from, to ];
3790
- append( propValue, rest );
3791
-
3792
- if ( currentNode[ propName ] === undefined ) {
3793
-
3794
- currentNode[ propName ] = [];
3795
-
3796
- }
3797
-
3798
- }
3799
-
3800
- // Node
3801
- if ( propName === 'Node' ) currentNode.id = propValue;
3802
-
3803
- // connections
3804
- if ( propName in currentNode && Array.isArray( currentNode[ propName ] ) ) {
3805
-
3806
- currentNode[ propName ].push( propValue );
3807
-
3808
- } else {
3809
-
3810
- if ( propName !== 'a' ) currentNode[ propName ] = propValue;
3811
- else currentNode.a = propValue;
3812
-
3813
- }
3814
-
3815
- this.setCurrentProp( currentNode, propName );
3816
-
3817
- // convert string to array, unless it ends in ',' in which case more will be added to it
3818
- if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
3819
-
3820
- currentNode.a = parseNumberArray( propValue );
3821
-
3822
- }
3823
-
3824
- }
3825
-
3826
- parseNodePropertyContinued( line ) {
3827
-
3828
- const currentNode = this.getCurrentNode();
3829
-
3830
- currentNode.a += line;
3831
-
3832
- // if the line doesn't end in ',' we have reached the end of the property value
3833
- // so convert the string to an array
3834
- if ( line.slice( - 1 ) !== ',' ) {
3835
-
3836
- currentNode.a = parseNumberArray( currentNode.a );
3837
-
3838
- }
3839
-
3840
- }
3841
-
3842
- // parse "Property70"
3843
- parseNodeSpecialProperty( line, propName, propValue ) {
3844
-
3845
- // split this
3846
- // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
3847
- // into array like below
3848
- // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
3849
- const props = propValue.split( '",' ).map( function ( prop ) {
3850
-
3851
- return prop.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
3852
-
3853
- } );
3854
-
3855
- const innerPropName = props[ 0 ];
3856
- const innerPropType1 = props[ 1 ];
3857
- const innerPropType2 = props[ 2 ];
3858
- const innerPropFlag = props[ 3 ];
3859
- let innerPropValue = props[ 4 ];
3860
-
3861
- // cast values where needed, otherwise leave as strings
3862
- switch ( innerPropType1 ) {
3863
-
3864
- case 'int':
3865
- case 'enum':
3866
- case 'bool':
3867
- case 'ULongLong':
3868
- case 'double':
3869
- case 'Number':
3870
- case 'FieldOfView':
3871
- innerPropValue = parseFloat( innerPropValue );
3872
- break;
3873
-
3874
- case 'Color':
3875
- case 'ColorRGB':
3876
- case 'Vector3D':
3877
- case 'Lcl_Translation':
3878
- case 'Lcl_Rotation':
3879
- case 'Lcl_Scaling':
3880
- innerPropValue = parseNumberArray( innerPropValue );
3881
- break;
3882
-
3883
- }
3884
-
3885
- // CAUTION: these props must append to parent's parent
3886
- this.getPrevNode()[ innerPropName ] = {
3887
-
3888
- 'type': innerPropType1,
3889
- 'type2': innerPropType2,
3890
- 'flag': innerPropFlag,
3891
- 'value': innerPropValue
3892
-
3893
- };
3894
-
3895
- this.setCurrentProp( this.getPrevNode(), innerPropName );
3896
-
3897
- }
3898
-
3899
- }
3900
-
3901
- // Parse an FBX file in Binary format
3902
- class BinaryParser {
3903
-
3904
- parse( buffer ) {
3905
-
3906
- const reader = new BinaryReader( buffer );
3907
- reader.skip( 23 ); // skip magic 23 bytes
3908
-
3909
- const version = reader.getUint32();
3910
-
3911
- if ( version < 6400 ) {
3912
-
3913
- throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + version );
3914
-
3915
- }
3916
-
3917
- const allNodes = new FBXTree();
3918
-
3919
- while ( ! this.endOfContent( reader ) ) {
3920
-
3921
- const node = this.parseNode( reader, version );
3922
- if ( node !== null ) allNodes.add( node.name, node );
3923
-
3924
- }
3925
-
3926
- return allNodes;
3927
-
3928
- }
3929
-
3930
- // Check if reader has reached the end of content.
3931
- endOfContent( reader ) {
3932
-
3933
- // footer size: 160bytes + 16-byte alignment padding
3934
- // - 16bytes: magic
3935
- // - padding til 16-byte alignment (at least 1byte?)
3936
- // (seems like some exporters embed fixed 15 or 16bytes?)
3937
- // - 4bytes: magic
3938
- // - 4bytes: version
3939
- // - 120bytes: zero
3940
- // - 16bytes: magic
3941
- if ( reader.size() % 16 === 0 ) {
3942
-
3943
- return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
3944
-
3945
- } else {
3946
-
3947
- return reader.getOffset() + 160 + 16 >= reader.size();
3948
-
3949
- }
3950
-
3951
- }
3952
-
3953
- // recursively parse nodes until the end of the file is reached
3954
- parseNode( reader, version ) {
3955
-
3956
- const node = {};
3957
-
3958
- // The first three data sizes depends on version.
3959
- const endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
3960
- const numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
3961
-
3962
- ( version >= 7500 ) ? reader.getUint64() : reader.getUint32(); // the returned propertyListLen is not used
3963
-
3964
- const nameLen = reader.getUint8();
3965
- const name = reader.getString( nameLen );
3966
-
3967
- // Regards this node as NULL-record if endOffset is zero
3968
- if ( endOffset === 0 ) return null;
3969
-
3970
- const propertyList = [];
3971
-
3972
- for ( let i = 0; i < numProperties; i ++ ) {
3973
-
3974
- propertyList.push( this.parseProperty( reader ) );
3975
-
3976
- }
3977
-
3978
- // Regards the first three elements in propertyList as id, attrName, and attrType
3979
- const id = propertyList.length > 0 ? propertyList[ 0 ] : '';
3980
- const attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
3981
- const attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
3982
-
3983
- // check if this node represents just a single property
3984
- // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
3985
- node.singleProperty = ( numProperties === 1 && reader.getOffset() === endOffset ) ? true : false;
3986
-
3987
- while ( endOffset > reader.getOffset() ) {
3988
-
3989
- const subNode = this.parseNode( reader, version );
3990
-
3991
- if ( subNode !== null ) this.parseSubNode( name, node, subNode );
3992
-
3993
- }
3994
-
3995
- node.propertyList = propertyList; // raw property list used by parent
3996
-
3997
- if ( typeof id === 'number' ) node.id = id;
3998
- if ( attrName !== '' ) node.attrName = attrName;
3999
- if ( attrType !== '' ) node.attrType = attrType;
4000
- if ( name !== '' ) node.name = name;
4001
-
4002
- return node;
4003
-
4004
- }
4005
-
4006
- parseSubNode( name, node, subNode ) {
4007
-
4008
- // special case: child node is single property
4009
- if ( subNode.singleProperty === true ) {
4010
-
4011
- const value = subNode.propertyList[ 0 ];
4012
-
4013
- if ( Array.isArray( value ) ) {
4014
-
4015
- node[ subNode.name ] = subNode;
4016
-
4017
- subNode.a = value;
4018
-
4019
- } else {
4020
-
4021
- node[ subNode.name ] = value;
4022
-
4023
- }
4024
-
4025
- } else if ( name === 'Connections' && subNode.name === 'C' ) {
4026
-
4027
- const array = [];
4028
-
4029
- subNode.propertyList.forEach( function ( property, i ) {
4030
-
4031
- // first Connection is FBX type (OO, OP, etc.). We'll discard these
4032
- if ( i !== 0 ) array.push( property );
4033
-
4034
- } );
4035
-
4036
- if ( node.connections === undefined ) {
4037
-
4038
- node.connections = [];
4039
-
4040
- }
4041
-
4042
- node.connections.push( array );
4043
-
4044
- } else if ( subNode.name === 'Properties70' ) {
4045
-
4046
- const keys = Object.keys( subNode );
4047
-
4048
- keys.forEach( function ( key ) {
4049
-
4050
- node[ key ] = subNode[ key ];
4051
-
4052
- } );
4053
-
4054
- } else if ( name === 'Properties70' && subNode.name === 'P' ) {
4055
-
4056
- let innerPropName = subNode.propertyList[ 0 ];
4057
- let innerPropType1 = subNode.propertyList[ 1 ];
4058
- const innerPropType2 = subNode.propertyList[ 2 ];
4059
- const innerPropFlag = subNode.propertyList[ 3 ];
4060
- let innerPropValue;
4061
-
4062
- if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
4063
- if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
4064
-
4065
- if ( innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
4066
-
4067
- innerPropValue = [
4068
- subNode.propertyList[ 4 ],
4069
- subNode.propertyList[ 5 ],
4070
- subNode.propertyList[ 6 ]
4071
- ];
4072
-
4073
- } else {
4074
-
4075
- innerPropValue = subNode.propertyList[ 4 ];
4076
-
4077
- }
4078
-
4079
- // this will be copied to parent, see above
4080
- node[ innerPropName ] = {
4081
-
4082
- 'type': innerPropType1,
4083
- 'type2': innerPropType2,
4084
- 'flag': innerPropFlag,
4085
- 'value': innerPropValue
4086
-
4087
- };
4088
-
4089
- } else if ( node[ subNode.name ] === undefined ) {
4090
-
4091
- if ( typeof subNode.id === 'number' ) {
4092
-
4093
- node[ subNode.name ] = {};
4094
- node[ subNode.name ][ subNode.id ] = subNode;
4095
-
4096
- } else {
4097
-
4098
- node[ subNode.name ] = subNode;
4099
-
4100
- }
4101
-
4102
- } else {
4103
-
4104
- if ( subNode.name === 'PoseNode' ) {
4105
-
4106
- if ( ! Array.isArray( node[ subNode.name ] ) ) {
4107
-
4108
- node[ subNode.name ] = [ node[ subNode.name ] ];
4109
-
4110
- }
4111
-
4112
- node[ subNode.name ].push( subNode );
4113
-
4114
- } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
4115
-
4116
- node[ subNode.name ][ subNode.id ] = subNode;
4117
-
4118
- }
4119
-
4120
- }
4121
-
4122
- }
4123
-
4124
- parseProperty( reader ) {
4125
-
4126
- const type = reader.getString( 1 );
4127
- let length;
4128
-
4129
- switch ( type ) {
4130
-
4131
- case 'C':
4132
- return reader.getBoolean();
4133
-
4134
- case 'D':
4135
- return reader.getFloat64();
4136
-
4137
- case 'F':
4138
- return reader.getFloat32();
4139
-
4140
- case 'I':
4141
- return reader.getInt32();
4142
-
4143
- case 'L':
4144
- return reader.getInt64();
4145
-
4146
- case 'R':
4147
- length = reader.getUint32();
4148
- return reader.getArrayBuffer( length );
4149
-
4150
- case 'S':
4151
- length = reader.getUint32();
4152
- return reader.getString( length );
4153
-
4154
- case 'Y':
4155
- return reader.getInt16();
4156
-
4157
- case 'b':
4158
- case 'c':
4159
- case 'd':
4160
- case 'f':
4161
- case 'i':
4162
- case 'l':
4163
-
4164
- const arrayLength = reader.getUint32();
4165
- const encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
4166
- const compressedLength = reader.getUint32();
4167
-
4168
- if ( encoding === 0 ) {
4169
-
4170
- switch ( type ) {
4171
-
4172
- case 'b':
4173
- case 'c':
4174
- return reader.getBooleanArray( arrayLength );
4175
-
4176
- case 'd':
4177
- return reader.getFloat64Array( arrayLength );
4178
-
4179
- case 'f':
4180
- return reader.getFloat32Array( arrayLength );
4181
-
4182
- case 'i':
4183
- return reader.getInt32Array( arrayLength );
4184
-
4185
- case 'l':
4186
- return reader.getInt64Array( arrayLength );
4187
-
4188
- }
4189
-
4190
- }
4191
-
4192
- const data = unzlibSync( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) );
4193
- const reader2 = new BinaryReader( data.buffer );
4194
-
4195
- switch ( type ) {
4196
-
4197
- case 'b':
4198
- case 'c':
4199
- return reader2.getBooleanArray( arrayLength );
4200
-
4201
- case 'd':
4202
- return reader2.getFloat64Array( arrayLength );
4203
-
4204
- case 'f':
4205
- return reader2.getFloat32Array( arrayLength );
4206
-
4207
- case 'i':
4208
- return reader2.getInt32Array( arrayLength );
4209
-
4210
- case 'l':
4211
- return reader2.getInt64Array( arrayLength );
4212
-
4213
- }
4214
-
4215
- break; // cannot happen but is required by the DeepScan
4216
-
4217
- default:
4218
- throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
4219
-
4220
- }
4221
-
4222
- }
4223
-
4224
- }
4225
-
4226
- class BinaryReader {
4227
-
4228
- constructor( buffer, littleEndian ) {
4229
-
4230
- this.dv = new DataView( buffer );
4231
- this.offset = 0;
4232
- this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
4233
- this._textDecoder = new TextDecoder();
4234
-
4235
- }
4236
-
4237
- getOffset() {
4238
-
4239
- return this.offset;
4240
-
4241
- }
4242
-
4243
- size() {
4244
-
4245
- return this.dv.buffer.byteLength;
4246
-
4247
- }
4248
-
4249
- skip( length ) {
4250
-
4251
- this.offset += length;
4252
-
4253
- }
4254
-
4255
- // seems like true/false representation depends on exporter.
4256
- // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
4257
- // then sees LSB.
4258
- getBoolean() {
4259
-
4260
- return ( this.getUint8() & 1 ) === 1;
4261
-
4262
- }
4263
-
4264
- getBooleanArray( size ) {
4265
-
4266
- const a = [];
4267
-
4268
- for ( let i = 0; i < size; i ++ ) {
4269
-
4270
- a.push( this.getBoolean() );
4271
-
4272
- }
4273
-
4274
- return a;
4275
-
4276
- }
4277
-
4278
- getUint8() {
4279
-
4280
- const value = this.dv.getUint8( this.offset );
4281
- this.offset += 1;
4282
- return value;
4283
-
4284
- }
4285
-
4286
- getInt16() {
4287
-
4288
- const value = this.dv.getInt16( this.offset, this.littleEndian );
4289
- this.offset += 2;
4290
- return value;
4291
-
4292
- }
4293
-
4294
- getInt32() {
4295
-
4296
- const value = this.dv.getInt32( this.offset, this.littleEndian );
4297
- this.offset += 4;
4298
- return value;
4299
-
4300
- }
4301
-
4302
- getInt32Array( size ) {
4303
-
4304
- const a = [];
4305
-
4306
- for ( let i = 0; i < size; i ++ ) {
4307
-
4308
- a.push( this.getInt32() );
4309
-
4310
- }
4311
-
4312
- return a;
4313
-
4314
- }
4315
-
4316
- getUint32() {
4317
-
4318
- const value = this.dv.getUint32( this.offset, this.littleEndian );
4319
- this.offset += 4;
4320
- return value;
4321
-
4322
- }
4323
-
4324
- // JavaScript doesn't support 64-bit integer so calculate this here
4325
- // 1 << 32 will return 1 so using multiply operation instead here.
4326
- // There's a possibility that this method returns wrong value if the value
4327
- // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
4328
- // TODO: safely handle 64-bit integer
4329
- getInt64() {
4330
-
4331
- let low, high;
4332
-
4333
- if ( this.littleEndian ) {
4334
-
4335
- low = this.getUint32();
4336
- high = this.getUint32();
4337
-
4338
- } else {
4339
-
4340
- high = this.getUint32();
4341
- low = this.getUint32();
4342
-
4343
- }
4344
-
4345
- // calculate negative value
4346
- if ( high & 0x80000000 ) {
4347
-
4348
- high = ~ high & 0xFFFFFFFF;
4349
- low = ~ low & 0xFFFFFFFF;
4350
-
4351
- if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
4352
-
4353
- low = ( low + 1 ) & 0xFFFFFFFF;
4354
-
4355
- return - ( high * 0x100000000 + low );
4356
-
4357
- }
4358
-
4359
- return high * 0x100000000 + low;
4360
-
4361
- }
4362
-
4363
- getInt64Array( size ) {
4364
-
4365
- const a = [];
4366
-
4367
- for ( let i = 0; i < size; i ++ ) {
4368
-
4369
- a.push( this.getInt64() );
4370
-
4371
- }
4372
-
4373
- return a;
4374
-
4375
- }
4376
-
4377
- // Note: see getInt64() comment
4378
- getUint64() {
4379
-
4380
- let low, high;
4381
-
4382
- if ( this.littleEndian ) {
4383
-
4384
- low = this.getUint32();
4385
- high = this.getUint32();
4386
-
4387
- } else {
4388
-
4389
- high = this.getUint32();
4390
- low = this.getUint32();
4391
-
4392
- }
4393
-
4394
- return high * 0x100000000 + low;
4395
-
4396
- }
4397
-
4398
- getFloat32() {
4399
-
4400
- const value = this.dv.getFloat32( this.offset, this.littleEndian );
4401
- this.offset += 4;
4402
- return value;
4403
-
4404
- }
4405
-
4406
- getFloat32Array( size ) {
4407
-
4408
- const a = [];
4409
-
4410
- for ( let i = 0; i < size; i ++ ) {
4411
-
4412
- a.push( this.getFloat32() );
4413
-
4414
- }
4415
-
4416
- return a;
4417
-
4418
- }
4419
-
4420
- getFloat64() {
4421
-
4422
- const value = this.dv.getFloat64( this.offset, this.littleEndian );
4423
- this.offset += 8;
4424
- return value;
4425
-
4426
- }
4427
-
4428
- getFloat64Array( size ) {
4429
-
4430
- const a = [];
4431
-
4432
- for ( let i = 0; i < size; i ++ ) {
4433
-
4434
- a.push( this.getFloat64() );
4435
-
4436
- }
4437
-
4438
- return a;
4439
-
4440
- }
4441
-
4442
- getArrayBuffer( size ) {
4443
-
4444
- const value = this.dv.buffer.slice( this.offset, this.offset + size );
4445
- this.offset += size;
4446
- return value;
4447
-
4448
- }
4449
-
4450
- getString( size ) {
4451
-
4452
- const start = this.offset;
4453
- let a = new Uint8Array( this.dv.buffer, start, size );
4454
-
4455
- this.skip( size );
4456
-
4457
- const nullByte = a.indexOf( 0 );
4458
- if ( nullByte >= 0 ) a = new Uint8Array( this.dv.buffer, start, nullByte );
4459
-
4460
- return this._textDecoder.decode( a );
4461
-
4462
- }
4463
-
4464
- }
4465
-
4466
- // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
4467
- // and BinaryParser( FBX Binary format)
4468
- class FBXTree {
4469
-
4470
- add( key, val ) {
4471
-
4472
- this[ key ] = val;
4473
-
4474
- }
4475
-
4476
- }
4477
-
4478
- // ************** UTILITY FUNCTIONS **************
4479
-
4480
- function isFbxFormatBinary( buffer ) {
4481
-
4482
- const CORRECT = 'Kaydara\u0020FBX\u0020Binary\u0020\u0020\0';
4483
-
4484
- return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
4485
-
4486
- }
4487
-
4488
- function isFbxFormatASCII( text ) {
4489
-
4490
- const CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
4491
-
4492
- let cursor = 0;
4493
-
4494
- function read( offset ) {
4495
-
4496
- const result = text[ offset - 1 ];
4497
- text = text.slice( cursor + offset );
4498
- cursor ++;
4499
- return result;
4500
-
4501
- }
4502
-
4503
- for ( let i = 0; i < CORRECT.length; ++ i ) {
4504
-
4505
- const num = read( 1 );
4506
- if ( num === CORRECT[ i ] ) {
4507
-
4508
- return false;
4509
-
4510
- }
4511
-
4512
- }
4513
-
4514
- return true;
4515
-
4516
- }
4517
-
4518
- function getFbxVersion( text ) {
4519
-
4520
- const versionRegExp = /FBXVersion: (\d+)/;
4521
- const match = text.match( versionRegExp );
4522
-
4523
- if ( match ) {
4524
-
4525
- const version = parseInt( match[ 1 ] );
4526
- return version;
4527
-
4528
- }
4529
-
4530
- throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
4531
-
4532
- }
4533
-
4534
- // Converts FBX ticks into real time seconds.
4535
- function convertFBXTimeToSeconds( time ) {
4536
-
4537
- return time / 46186158000;
4538
-
4539
- }
4540
-
4541
- const dataArray = [];
4542
-
4543
- // extracts the data from the correct position in the FBX array based on indexing type
4544
- function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
4545
-
4546
- let index;
4547
-
4548
- switch ( infoObject.mappingType ) {
4549
-
4550
- case 'ByPolygonVertex' :
4551
- index = polygonVertexIndex;
4552
- break;
4553
- case 'ByPolygon' :
4554
- index = polygonIndex;
4555
- break;
4556
- case 'ByVertice' :
4557
- index = vertexIndex;
4558
- break;
4559
- case 'AllSame' :
4560
- index = infoObject.indices[ 0 ];
4561
- break;
4562
- default :
4563
- console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
4564
-
4565
- }
4566
-
4567
- if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
4568
-
4569
- const from = index * infoObject.dataSize;
4570
- const to = from + infoObject.dataSize;
4571
-
4572
- return slice( dataArray, infoObject.buffer, from, to );
4573
-
4574
- }
4575
-
4576
- const tempEuler = new Euler();
4577
- const tempVec = new Vector3();
4578
-
4579
- // generate transformation from FBX transform data
4580
- // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
4581
- // ref: http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/_transformations_2main_8cxx-example.html,topicNumber=cpp_ref__transformations_2main_8cxx_example_htmlfc10a1e1-b18d-4e72-9dc0-70d0f1959f5e
4582
- function generateTransform( transformData ) {
4583
-
4584
- const lTranslationM = new Matrix4();
4585
- const lPreRotationM = new Matrix4();
4586
- const lRotationM = new Matrix4();
4587
- const lPostRotationM = new Matrix4();
4588
-
4589
- const lScalingM = new Matrix4();
4590
- const lScalingPivotM = new Matrix4();
4591
- const lScalingOffsetM = new Matrix4();
4592
- const lRotationOffsetM = new Matrix4();
4593
- const lRotationPivotM = new Matrix4();
4594
-
4595
- const lParentGX = new Matrix4();
4596
- const lParentLX = new Matrix4();
4597
- const lGlobalT = new Matrix4();
4598
-
4599
- const inheritType = ( transformData.inheritType ) ? transformData.inheritType : 0;
4600
-
4601
- if ( transformData.translation ) lTranslationM.setPosition( tempVec.fromArray( transformData.translation ) );
4602
-
4603
- // For Maya models using "Joint Orient", Euler order only applies to rotation, not pre/post-rotations
4604
- const defaultEulerOrder = getEulerOrder( 0 );
4605
-
4606
- if ( transformData.preRotation ) {
4607
-
4608
- const array = transformData.preRotation.map( MathUtils.degToRad );
4609
- array.push( defaultEulerOrder );
4610
- lPreRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
4611
-
4612
- }
4613
-
4614
- if ( transformData.rotation ) {
4615
-
4616
- const array = transformData.rotation.map( MathUtils.degToRad );
4617
- array.push( transformData.eulerOrder || defaultEulerOrder );
4618
- lRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
4619
-
4620
- }
4621
-
4622
- if ( transformData.postRotation ) {
4623
-
4624
- const array = transformData.postRotation.map( MathUtils.degToRad );
4625
- array.push( defaultEulerOrder );
4626
- lPostRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
4627
- lPostRotationM.invert();
4628
-
4629
- }
4630
-
4631
- if ( transformData.scale ) lScalingM.scale( tempVec.fromArray( transformData.scale ) );
4632
-
4633
- // Pivots and offsets
4634
- if ( transformData.scalingOffset ) lScalingOffsetM.setPosition( tempVec.fromArray( transformData.scalingOffset ) );
4635
- if ( transformData.scalingPivot ) lScalingPivotM.setPosition( tempVec.fromArray( transformData.scalingPivot ) );
4636
- if ( transformData.rotationOffset ) lRotationOffsetM.setPosition( tempVec.fromArray( transformData.rotationOffset ) );
4637
- if ( transformData.rotationPivot ) lRotationPivotM.setPosition( tempVec.fromArray( transformData.rotationPivot ) );
4638
-
4639
- // parent transform
4640
- if ( transformData.parentMatrixWorld ) {
4641
-
4642
- lParentLX.copy( transformData.parentMatrix );
4643
- lParentGX.copy( transformData.parentMatrixWorld );
4644
-
4645
- }
4646
-
4647
- const lLRM = lPreRotationM.clone().multiply( lRotationM ).multiply( lPostRotationM );
4648
- // Global Rotation
4649
- const lParentGRM = new Matrix4();
4650
- lParentGRM.extractRotation( lParentGX );
4651
-
4652
- // Global Shear*Scaling
4653
- const lParentTM = new Matrix4();
4654
- lParentTM.copyPosition( lParentGX );
4655
-
4656
- const lParentGRSM = lParentTM.clone().invert().multiply( lParentGX );
4657
- const lParentGSM = lParentGRM.clone().invert().multiply( lParentGRSM );
4658
- const lLSM = lScalingM;
4659
-
4660
- const lGlobalRS = new Matrix4();
4661
-
4662
- if ( inheritType === 0 ) {
4663
-
4664
- lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM ).multiply( lLSM );
4665
-
4666
- } else if ( inheritType === 1 ) {
4667
-
4668
- lGlobalRS.copy( lParentGRM ).multiply( lParentGSM ).multiply( lLRM ).multiply( lLSM );
4669
-
4670
- } else {
4671
-
4672
- const lParentLSM = new Matrix4().scale( new Vector3().setFromMatrixScale( lParentLX ) );
4673
- const lParentLSM_inv = lParentLSM.clone().invert();
4674
- const lParentGSM_noLocal = lParentGSM.clone().multiply( lParentLSM_inv );
4675
-
4676
- lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM_noLocal ).multiply( lLSM );
4677
-
4678
- }
4679
-
4680
- const lRotationPivotM_inv = lRotationPivotM.clone().invert();
4681
- const lScalingPivotM_inv = lScalingPivotM.clone().invert();
4682
- // Calculate the local transform matrix
4683
- let lTransform = lTranslationM.clone().multiply( lRotationOffsetM ).multiply( lRotationPivotM ).multiply( lPreRotationM ).multiply( lRotationM ).multiply( lPostRotationM ).multiply( lRotationPivotM_inv ).multiply( lScalingOffsetM ).multiply( lScalingPivotM ).multiply( lScalingM ).multiply( lScalingPivotM_inv );
4684
-
4685
- const lLocalTWithAllPivotAndOffsetInfo = new Matrix4().copyPosition( lTransform );
4686
-
4687
- const lGlobalTranslation = lParentGX.clone().multiply( lLocalTWithAllPivotAndOffsetInfo );
4688
- lGlobalT.copyPosition( lGlobalTranslation );
4689
-
4690
- lTransform = lGlobalT.clone().multiply( lGlobalRS );
4691
-
4692
- // from global to local
4693
- lTransform.premultiply( lParentGX.invert() );
4694
-
4695
- return lTransform;
4696
-
4697
- }
4698
-
4699
- // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
4700
- // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
4701
- function getEulerOrder( order ) {
4702
-
4703
- order = order || 0;
4704
-
4705
- const enums = [
4706
- 'ZYX', // -> XYZ extrinsic
4707
- 'YZX', // -> XZY extrinsic
4708
- 'XZY', // -> YZX extrinsic
4709
- 'ZXY', // -> YXZ extrinsic
4710
- 'YXZ', // -> ZXY extrinsic
4711
- 'XYZ', // -> ZYX extrinsic
4712
- //'SphericXYZ', // not possible to support
4713
- ];
4714
-
4715
- if ( order === 6 ) {
4716
-
4717
- console.warn( 'THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.' );
4718
- return enums[ 0 ];
4719
-
4720
- }
4721
-
4722
- return enums[ order ];
4723
-
4724
- }
4725
-
4726
- // Parses comma separated list of numbers and returns them an array.
4727
- // Used internally by the TextParser
4728
- function parseNumberArray( value ) {
4729
-
4730
- const array = value.split( ',' ).map( function ( val ) {
4731
-
4732
- return parseFloat( val );
4733
-
4734
- } );
4735
-
4736
- return array;
4737
-
4738
- }
4739
-
4740
- function convertArrayBufferToString( buffer, from, to ) {
4741
-
4742
- if ( from === undefined ) from = 0;
4743
- if ( to === undefined ) to = buffer.byteLength;
4744
-
4745
- return new TextDecoder().decode( new Uint8Array( buffer, from, to ) );
4746
-
4747
- }
4748
-
4749
- function append( a, b ) {
4750
-
4751
- for ( let i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
4752
-
4753
- a[ j ] = b[ i ];
4754
-
4755
- }
4756
-
4757
- }
4758
-
4759
- function slice( a, b, from, to ) {
4760
-
4761
- for ( let i = from, j = 0; i < to; i ++, j ++ ) {
4762
-
4763
- a[ j ] = b[ i ];
4764
-
4765
- }
4766
-
4767
- return a;
4768
-
4769
- }
4770
-
4771
-
4772
- export { FBXLoader };