zincjs 2.4.1-beta.2 → 2.4.1-beta.3

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.
@@ -1,2501 +0,0 @@
1
- import {
2
- BufferAttribute,
3
- BufferGeometry,
4
- ClampToEdgeWrapping,
5
- DoubleSide,
6
- InterpolateDiscrete,
7
- InterpolateLinear,
8
- LinearFilter,
9
- LinearMipmapLinearFilter,
10
- LinearMipmapNearestFilter,
11
- MathUtils,
12
- Matrix4,
13
- MirroredRepeatWrapping,
14
- NearestFilter,
15
- NearestMipmapLinearFilter,
16
- NearestMipmapNearestFilter,
17
- PropertyBinding,
18
- RGBAFormat,
19
- RGBFormat,
20
- RepeatWrapping,
21
- Scene,
22
- Vector3
23
- } from 'three/webgpu';
24
-
25
-
26
- class GLTFExporter {
27
-
28
- constructor() {
29
-
30
- this.pluginCallbacks = [];
31
-
32
- this.register( function ( writer ) {
33
-
34
- return new GLTFLightExtension( writer );
35
-
36
- } );
37
-
38
- this.register( function ( writer ) {
39
-
40
- return new GLTFMaterialsUnlitExtension( writer );
41
-
42
- } );
43
-
44
- this.register( function ( writer ) {
45
-
46
- return new GLTFMaterialsPBRSpecularGlossiness( writer );
47
-
48
- } );
49
-
50
- }
51
-
52
- register( callback ) {
53
-
54
- if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
55
-
56
- this.pluginCallbacks.push( callback );
57
-
58
- }
59
-
60
- return this;
61
-
62
- }
63
-
64
- unregister( callback ) {
65
-
66
- if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
67
-
68
- this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
69
-
70
- }
71
-
72
- return this;
73
-
74
- }
75
-
76
- /**
77
- * Parse scenes and generate GLTF output
78
- * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
79
- * @param {Function} onDone Callback on completed
80
- * @param {Object} options options
81
- */
82
- parse( input, onDone, options ) {
83
-
84
- const writer = new GLTFWriter();
85
- const plugins = [];
86
-
87
- for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) {
88
-
89
- plugins.push( this.pluginCallbacks[ i ]( writer ) );
90
-
91
- }
92
-
93
- writer.setPlugins( plugins );
94
- writer.write( input, onDone, options );
95
-
96
- }
97
-
98
- }
99
-
100
- //------------------------------------------------------------------------------
101
- // Constants
102
- //------------------------------------------------------------------------------
103
-
104
- const WEBGL_CONSTANTS = {
105
- POINTS: 0x0000,
106
- LINES: 0x0001,
107
- LINE_LOOP: 0x0002,
108
- LINE_STRIP: 0x0003,
109
- TRIANGLES: 0x0004,
110
- TRIANGLE_STRIP: 0x0005,
111
- TRIANGLE_FAN: 0x0006,
112
-
113
- UNSIGNED_BYTE: 0x1401,
114
- UNSIGNED_SHORT: 0x1403,
115
- FLOAT: 0x1406,
116
- UNSIGNED_INT: 0x1405,
117
- ARRAY_BUFFER: 0x8892,
118
- ELEMENT_ARRAY_BUFFER: 0x8893,
119
-
120
- NEAREST: 0x2600,
121
- LINEAR: 0x2601,
122
- NEAREST_MIPMAP_NEAREST: 0x2700,
123
- LINEAR_MIPMAP_NEAREST: 0x2701,
124
- NEAREST_MIPMAP_LINEAR: 0x2702,
125
- LINEAR_MIPMAP_LINEAR: 0x2703,
126
-
127
- CLAMP_TO_EDGE: 33071,
128
- MIRRORED_REPEAT: 33648,
129
- REPEAT: 10497
130
- };
131
-
132
- const THREE_TO_WEBGL = {};
133
-
134
- THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
135
- THREE_TO_WEBGL[ NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
136
- THREE_TO_WEBGL[ NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
137
- THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
138
- THREE_TO_WEBGL[ LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
139
- THREE_TO_WEBGL[ LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
140
-
141
- THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
142
- THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
143
- THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
144
-
145
- const PATH_PROPERTIES = {
146
- scale: 'scale',
147
- position: 'translation',
148
- quaternion: 'rotation',
149
- morphTargetInfluences: 'weights'
150
- };
151
-
152
- // GLB constants
153
- // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
154
-
155
- const GLB_HEADER_BYTES = 12;
156
- const GLB_HEADER_MAGIC = 0x46546C67;
157
- const GLB_VERSION = 2;
158
-
159
- const GLB_CHUNK_PREFIX_BYTES = 8;
160
- const GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
161
- const GLB_CHUNK_TYPE_BIN = 0x004E4942;
162
-
163
- //------------------------------------------------------------------------------
164
- // Utility functions
165
- //------------------------------------------------------------------------------
166
-
167
- /**
168
- * Compare two arrays
169
- * @param {Array} array1 Array 1 to compare
170
- * @param {Array} array2 Array 2 to compare
171
- * @return {Boolean} Returns true if both arrays are equal
172
- */
173
- function equalArray( array1, array2 ) {
174
-
175
- return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
176
-
177
- return element === array2[ index ];
178
-
179
- } );
180
-
181
- }
182
-
183
- /**
184
- * Converts a string to an ArrayBuffer.
185
- * @param {string} text
186
- * @return {ArrayBuffer}
187
- */
188
- function stringToArrayBuffer( text ) {
189
-
190
- if ( window.TextEncoder !== undefined ) {
191
-
192
- return new TextEncoder().encode( text ).buffer;
193
-
194
- }
195
-
196
- const array = new Uint8Array( new ArrayBuffer( text.length ) );
197
-
198
- for ( let i = 0, il = text.length; i < il; i ++ ) {
199
-
200
- const value = text.charCodeAt( i );
201
-
202
- // Replacing multi-byte character with space(0x20).
203
- array[ i ] = value > 0xFF ? 0x20 : value;
204
-
205
- }
206
-
207
- return array.buffer;
208
-
209
- }
210
-
211
- /**
212
- * Is identity matrix
213
- *
214
- * @param {Matrix4} matrix
215
- * @returns {Boolean} Returns true, if parameter is identity matrix
216
- */
217
- function isIdentityMatrix( matrix ) {
218
-
219
- return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] );
220
-
221
- }
222
-
223
- /**
224
- * Get the min and max vectors from the given attribute
225
- * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
226
- * @param {Integer} start
227
- * @param {Integer} count
228
- * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
229
- */
230
- function getMinMax( attribute, start, count ) {
231
-
232
- const output = {
233
-
234
- min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
235
- max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
236
-
237
- };
238
-
239
- for ( let i = start; i < start + count; i ++ ) {
240
-
241
- for ( let a = 0; a < attribute.itemSize; a ++ ) {
242
-
243
- let value;
244
-
245
- if ( attribute.itemSize > 4 ) {
246
-
247
- // no support for interleaved data for itemSize > 4
248
-
249
- value = attribute.array[ i * attribute.itemSize + a ];
250
-
251
- } else {
252
-
253
- if ( a === 0 ) value = attribute.getX( i );
254
- else if ( a === 1 ) value = attribute.getY( i );
255
- else if ( a === 2 ) value = attribute.getZ( i );
256
- else if ( a === 3 ) value = attribute.getW( i );
257
-
258
- }
259
-
260
- output.min[ a ] = Math.min( output.min[ a ], value );
261
- output.max[ a ] = Math.max( output.max[ a ], value );
262
-
263
- }
264
-
265
- }
266
-
267
- return output;
268
-
269
- }
270
-
271
- /**
272
- * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
273
- * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
274
- *
275
- * @param {Integer} bufferSize The size the original buffer.
276
- * @returns {Integer} new buffer size with required padding.
277
- *
278
- */
279
- function getPaddedBufferSize( bufferSize ) {
280
-
281
- return Math.ceil( bufferSize / 4 ) * 4;
282
-
283
- }
284
-
285
- /**
286
- * Returns a buffer aligned to 4-byte boundary.
287
- *
288
- * @param {ArrayBuffer} arrayBuffer Buffer to pad
289
- * @param {Integer} paddingByte (Optional)
290
- * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
291
- */
292
- function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) {
293
-
294
- const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
295
-
296
- if ( paddedLength !== arrayBuffer.byteLength ) {
297
-
298
- const array = new Uint8Array( paddedLength );
299
- array.set( new Uint8Array( arrayBuffer ) );
300
-
301
- if ( paddingByte !== 0 ) {
302
-
303
- for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
304
-
305
- array[ i ] = paddingByte;
306
-
307
- }
308
-
309
- }
310
-
311
- return array.buffer;
312
-
313
- }
314
-
315
- return arrayBuffer;
316
-
317
- }
318
-
319
- let cachedCanvas = null;
320
-
321
- /**
322
- * Writer
323
- */
324
- class GLTFWriter {
325
-
326
- constructor() {
327
-
328
- this.plugins = [];
329
-
330
- this.options = {};
331
- this.pending = [];
332
- this.buffers = [];
333
-
334
- this.byteOffset = 0;
335
- this.buffers = [];
336
- this.nodeMap = new Map();
337
- this.skins = [];
338
- this.extensionsUsed = {};
339
-
340
- this.uids = new Map();
341
- this.uid = 0;
342
-
343
- this.json = {
344
- asset: {
345
- version: '2.0',
346
- generator: 'THREE.GLTFExporter'
347
- }
348
- };
349
-
350
- this.cache = {
351
- meshes: new Map(),
352
- attributes: new Map(),
353
- attributesNormalized: new Map(),
354
- materials: new Map(),
355
- textures: new Map(),
356
- images: new Map()
357
- };
358
-
359
- }
360
-
361
- setPlugins( plugins ) {
362
-
363
- this.plugins = plugins;
364
-
365
- }
366
-
367
- /**
368
- * Parse scenes and generate GLTF output
369
- * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
370
- * @param {Function} onDone Callback on completed
371
- * @param {Object} options options
372
- */
373
- write( input, onDone, options ) {
374
-
375
- this.options = Object.assign( {}, {
376
- // default options
377
- binary: false,
378
- trs: false,
379
- onlyVisible: true,
380
- truncateDrawRange: true,
381
- embedImages: true,
382
- maxTextureSize: Infinity,
383
- animations: [],
384
- includeCustomExtensions: false
385
- }, options );
386
-
387
- if ( this.options.animations.length > 0 ) {
388
-
389
- // Only TRS properties, and not matrices, may be targeted by animation.
390
- this.options.trs = true;
391
-
392
- }
393
-
394
- this.processInput( input );
395
-
396
- const writer = this;
397
-
398
- Promise.all( this.pending ).then( function () {
399
-
400
- const buffers = writer.buffers;
401
- const json = writer.json;
402
- const options = writer.options;
403
- const extensionsUsed = writer.extensionsUsed;
404
-
405
- // Merge buffers.
406
- const blob = new Blob( buffers, { type: 'application/octet-stream' } );
407
-
408
- // Declare extensions.
409
- const extensionsUsedList = Object.keys( extensionsUsed );
410
-
411
- if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList;
412
-
413
- // Update bytelength of the single buffer.
414
- if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size;
415
-
416
- if ( options.binary === true ) {
417
-
418
- // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
419
-
420
- const reader = new window.FileReader();
421
- reader.readAsArrayBuffer( blob );
422
- reader.onloadend = function () {
423
-
424
- // Binary chunk.
425
- const binaryChunk = getPaddedArrayBuffer( reader.result );
426
- const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
427
- binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
428
- binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
429
-
430
- // JSON chunk.
431
- const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 );
432
- const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
433
- jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
434
- jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
435
-
436
- // GLB header.
437
- const header = new ArrayBuffer( GLB_HEADER_BYTES );
438
- const headerView = new DataView( header );
439
- headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
440
- headerView.setUint32( 4, GLB_VERSION, true );
441
- const totalByteLength = GLB_HEADER_BYTES
442
- + jsonChunkPrefix.byteLength + jsonChunk.byteLength
443
- + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
444
- headerView.setUint32( 8, totalByteLength, true );
445
-
446
- const glbBlob = new Blob( [
447
- header,
448
- jsonChunkPrefix,
449
- jsonChunk,
450
- binaryChunkPrefix,
451
- binaryChunk
452
- ], { type: 'application/octet-stream' } );
453
-
454
- const glbReader = new window.FileReader();
455
- glbReader.readAsArrayBuffer( glbBlob );
456
- glbReader.onloadend = function () {
457
-
458
- onDone( glbReader.result );
459
-
460
- };
461
-
462
- };
463
-
464
- } else {
465
-
466
- if ( json.buffers && json.buffers.length > 0 ) {
467
-
468
- const reader = new window.FileReader();
469
- reader.readAsDataURL( blob );
470
- reader.onloadend = function () {
471
-
472
- const base64data = reader.result;
473
- json.buffers[ 0 ].uri = base64data;
474
- onDone( json );
475
-
476
- };
477
-
478
- } else {
479
-
480
- onDone( json );
481
-
482
- }
483
-
484
- }
485
-
486
- } );
487
-
488
- }
489
-
490
- /**
491
- * Serializes a userData.
492
- *
493
- * @param {THREE.Object3D|THREE.Material} object
494
- * @param {Object} objectDef
495
- */
496
- serializeUserData( object, objectDef ) {
497
-
498
- if (object.userData && object.userData.isZincObject) return;
499
-
500
- if ( Object.keys( object.userData ).length === 0 ) return;
501
-
502
- const options = this.options;
503
- const extensionsUsed = this.extensionsUsed;
504
-
505
- try {
506
-
507
- const json = JSON.parse( JSON.stringify( object.userData ) );
508
-
509
- if ( options.includeCustomExtensions && json.gltfExtensions ) {
510
-
511
- if ( objectDef.extensions === undefined ) objectDef.extensions = {};
512
-
513
- for ( const extensionName in json.gltfExtensions ) {
514
-
515
- objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
516
- extensionsUsed[ extensionName ] = true;
517
-
518
- }
519
-
520
- delete json.gltfExtensions;
521
-
522
- }
523
-
524
- if ( Object.keys( json ).length > 0 ) objectDef.extras = json;
525
-
526
- } catch ( error ) {
527
-
528
- console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
529
- 'won\'t be serialized because of JSON.stringify error - ' + error.message );
530
-
531
- }
532
-
533
- }
534
-
535
- /**
536
- * Assign and return a temporal unique id for an object
537
- * especially which doesn't have .uuid
538
- * @param {Object} object
539
- * @return {Integer}
540
- */
541
- getUID( object ) {
542
-
543
- if ( ! this.uids.has( object ) ) this.uids.set( object, this.uid ++ );
544
-
545
- return this.uids.get( object );
546
-
547
- }
548
-
549
- /**
550
- * Checks if normal attribute values are normalized.
551
- *
552
- * @param {BufferAttribute} normal
553
- * @returns {Boolean}
554
- */
555
- isNormalizedNormalAttribute( normal ) {
556
-
557
- const cache = this.cache;
558
-
559
- if ( cache.attributesNormalized.has( normal ) ) return false;
560
-
561
- const v = new Vector3();
562
-
563
- for ( let i = 0, il = normal.count; i < il; i ++ ) {
564
-
565
- // 0.0005 is from glTF-validator
566
- if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
567
-
568
- }
569
-
570
- return true;
571
-
572
- }
573
-
574
- /**
575
- * Creates normalized normal buffer attribute.
576
- *
577
- * @param {BufferAttribute} normal
578
- * @returns {BufferAttribute}
579
- *
580
- */
581
- createNormalizedNormalAttribute( normal ) {
582
-
583
- const cache = this.cache;
584
-
585
- if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal );
586
-
587
- const attribute = normal.clone();
588
- const v = new Vector3();
589
-
590
- for ( let i = 0, il = attribute.count; i < il; i ++ ) {
591
-
592
- v.fromBufferAttribute( attribute, i );
593
-
594
- if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
595
-
596
- // if values can't be normalized set (1, 0, 0)
597
- v.setX( 1.0 );
598
-
599
- } else {
600
-
601
- v.normalize();
602
-
603
- }
604
-
605
- attribute.setXYZ( i, v.x, v.y, v.z );
606
-
607
- }
608
-
609
- cache.attributesNormalized.set( normal, attribute );
610
-
611
- return attribute;
612
-
613
- }
614
-
615
- /**
616
- * Applies a texture transform, if present, to the map definition. Requires
617
- * the KHR_texture_transform extension.
618
- *
619
- * @param {Object} mapDef
620
- * @param {THREE.Texture} texture
621
- */
622
- applyTextureTransform( mapDef, texture ) {
623
-
624
- let didTransform = false;
625
- const transformDef = {};
626
-
627
- if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
628
-
629
- transformDef.offset = texture.offset.toArray();
630
- didTransform = true;
631
-
632
- }
633
-
634
- if ( texture.rotation !== 0 ) {
635
-
636
- transformDef.rotation = texture.rotation;
637
- didTransform = true;
638
-
639
- }
640
-
641
- if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
642
-
643
- transformDef.scale = texture.repeat.toArray();
644
- didTransform = true;
645
-
646
- }
647
-
648
- if ( didTransform ) {
649
-
650
- mapDef.extensions = mapDef.extensions || {};
651
- mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
652
- this.extensionsUsed[ 'KHR_texture_transform' ] = true;
653
-
654
- }
655
-
656
- }
657
-
658
- /**
659
- * Process a buffer to append to the default one.
660
- * @param {ArrayBuffer} buffer
661
- * @return {Integer}
662
- */
663
- processBuffer( buffer ) {
664
-
665
- const json = this.json;
666
- const buffers = this.buffers;
667
-
668
- if ( ! json.buffers ) json.buffers = [ { byteLength: 0 } ];
669
-
670
- // All buffers are merged before export.
671
- buffers.push( buffer );
672
-
673
- return 0;
674
-
675
- }
676
-
677
- /**
678
- * Process and generate a BufferView
679
- * @param {BufferAttribute} attribute
680
- * @param {number} componentType
681
- * @param {number} start
682
- * @param {number} count
683
- * @param {number} target (Optional) Target usage of the BufferView
684
- * @return {Object}
685
- */
686
- processBufferView( attribute, componentType, start, count, target ) {
687
-
688
- const json = this.json;
689
-
690
- if ( ! json.bufferViews ) json.bufferViews = [];
691
-
692
- // Create a new dataview and dump the attribute's array into it
693
-
694
- let componentSize;
695
-
696
- if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
697
-
698
- componentSize = 1;
699
-
700
- } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
701
-
702
- componentSize = 2;
703
-
704
- } else {
705
-
706
- componentSize = 4;
707
-
708
- }
709
-
710
- const byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
711
- const dataView = new DataView( new ArrayBuffer( byteLength ) );
712
- let offset = 0;
713
-
714
- for ( let i = start; i < start + count; i ++ ) {
715
-
716
- for ( let a = 0; a < attribute.itemSize; a ++ ) {
717
-
718
- let value;
719
-
720
- if ( attribute.itemSize > 4 ) {
721
-
722
- // no support for interleaved data for itemSize > 4
723
-
724
- value = attribute.array[ i * attribute.itemSize + a ];
725
-
726
- } else {
727
-
728
- if ( a === 0 ) value = attribute.getX( i );
729
- else if ( a === 1 ) value = attribute.getY( i );
730
- else if ( a === 2 ) value = attribute.getZ( i );
731
- else if ( a === 3 ) value = attribute.getW( i );
732
-
733
- }
734
-
735
- if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
736
-
737
- dataView.setFloat32( offset, value, true );
738
-
739
- } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
740
-
741
- dataView.setUint32( offset, value, true );
742
-
743
- } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
744
-
745
- dataView.setUint16( offset, value, true );
746
-
747
- } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
748
-
749
- dataView.setUint8( offset, value );
750
-
751
- }
752
-
753
- offset += componentSize;
754
-
755
- }
756
-
757
- }
758
-
759
- const bufferViewDef = {
760
-
761
- buffer: this.processBuffer( dataView.buffer ),
762
- byteOffset: this.byteOffset,
763
- byteLength: byteLength
764
-
765
- };
766
-
767
- if ( target !== undefined ) bufferViewDef.target = target;
768
-
769
- if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
770
-
771
- // Only define byteStride for vertex attributes.
772
- bufferViewDef.byteStride = attribute.itemSize * componentSize;
773
-
774
- }
775
-
776
- this.byteOffset += byteLength;
777
-
778
- json.bufferViews.push( bufferViewDef );
779
-
780
- // @TODO Merge bufferViews where possible.
781
- const output = {
782
-
783
- id: json.bufferViews.length - 1,
784
- byteLength: 0
785
-
786
- };
787
-
788
- return output;
789
-
790
- }
791
-
792
- /**
793
- * Process and generate a BufferView from an image Blob.
794
- * @param {Blob} blob
795
- * @return {Promise<Integer>}
796
- */
797
- processBufferViewImage( blob ) {
798
-
799
- const writer = this;
800
- const json = writer.json;
801
-
802
- if ( ! json.bufferViews ) json.bufferViews = [];
803
-
804
- return new Promise( function ( resolve ) {
805
-
806
- const reader = new window.FileReader();
807
- reader.readAsArrayBuffer( blob );
808
- reader.onloadend = function () {
809
-
810
- const buffer = getPaddedArrayBuffer( reader.result );
811
-
812
- const bufferViewDef = {
813
- buffer: writer.processBuffer( buffer ),
814
- byteOffset: writer.byteOffset,
815
- byteLength: buffer.byteLength
816
- };
817
-
818
- writer.byteOffset += buffer.byteLength;
819
- resolve( json.bufferViews.push( bufferViewDef ) - 1 );
820
-
821
- };
822
-
823
- } );
824
-
825
- }
826
-
827
- /**
828
- * Process attribute to generate an accessor
829
- * @param {BufferAttribute} attribute Attribute to process
830
- * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
831
- * @param {Integer} start (Optional)
832
- * @param {Integer} count (Optional)
833
- * @return {Integer|null} Index of the processed accessor on the "accessors" array
834
- */
835
- processAccessor( attribute, geometry, start, count ) {
836
-
837
- const options = this.options;
838
- const json = this.json;
839
-
840
- const types = {
841
-
842
- 1: 'SCALAR',
843
- 2: 'VEC2',
844
- 3: 'VEC3',
845
- 4: 'VEC4',
846
- 16: 'MAT4'
847
-
848
- };
849
-
850
- let componentType;
851
-
852
- // Detect the component type of the attribute array (float, uint or ushort)
853
- if ( attribute.array.constructor === Float32Array ) {
854
-
855
- componentType = WEBGL_CONSTANTS.FLOAT;
856
-
857
- } else if ( attribute.array.constructor === Uint32Array ) {
858
-
859
- componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
860
-
861
- } else if ( attribute.array.constructor === Uint16Array ) {
862
-
863
- componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
864
-
865
- } else if ( attribute.array.constructor === Uint8Array ) {
866
-
867
- componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
868
-
869
- } else {
870
-
871
- throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
872
-
873
- }
874
-
875
- if ( start === undefined ) start = 0;
876
- if ( count === undefined ) count = attribute.count;
877
-
878
- // @TODO Indexed buffer geometry with drawRange not supported yet
879
- if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
880
-
881
- const end = start + count;
882
- const end2 = geometry.drawRange.count === Infinity
883
- ? attribute.count
884
- : geometry.drawRange.start + geometry.drawRange.count;
885
-
886
- start = Math.max( start, geometry.drawRange.start );
887
- count = Math.min( end, end2 ) - start;
888
-
889
- if ( count < 0 ) count = 0;
890
-
891
- }
892
-
893
- // Skip creating an accessor if the attribute doesn't have data to export
894
- if ( count === 0 ) return null;
895
-
896
- const minMax = getMinMax( attribute, start, count );
897
- let bufferViewTarget;
898
-
899
- // If geometry isn't provided, don't infer the target usage of the bufferView. For
900
- // animation samplers, target must not be set.
901
- if ( geometry !== undefined ) {
902
-
903
- bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
904
-
905
- }
906
-
907
- const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
908
-
909
- const accessorDef = {
910
-
911
- bufferView: bufferView.id,
912
- byteOffset: bufferView.byteOffset,
913
- componentType: componentType,
914
- count: count,
915
- max: minMax.max,
916
- min: minMax.min,
917
- type: types[ attribute.itemSize ]
918
-
919
- };
920
-
921
- if ( attribute.normalized === true ) accessorDef.normalized = true;
922
- if ( ! json.accessors ) json.accessors = [];
923
-
924
- return json.accessors.push( accessorDef ) - 1;
925
-
926
- }
927
-
928
- /**
929
- * Process image
930
- * @param {Image} image to process
931
- * @param {Integer} format of the image (e.g. RGBFormat, RGBAFormat etc)
932
- * @param {Boolean} flipY before writing out the image
933
- * @return {Integer} Index of the processed texture in the "images" array
934
- */
935
- processImage( image, format, flipY ) {
936
-
937
- const writer = this;
938
- const cache = writer.cache;
939
- const json = writer.json;
940
- const options = writer.options;
941
- const pending = writer.pending;
942
-
943
- if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
944
-
945
- const cachedImages = cache.images.get( image );
946
- const mimeType = format === RGBAFormat ? 'image/png' : 'image/jpeg';
947
- const key = mimeType + ':flipY/' + flipY.toString();
948
-
949
- if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
950
-
951
- if ( ! json.images ) json.images = [];
952
-
953
- const imageDef = { mimeType: mimeType };
954
-
955
- if ( options.embedImages ) {
956
-
957
- const canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
958
-
959
- canvas.width = Math.min( image.width, options.maxTextureSize );
960
- canvas.height = Math.min( image.height, options.maxTextureSize );
961
-
962
- const ctx = canvas.getContext( '2d' );
963
-
964
- if ( flipY === true ) {
965
-
966
- ctx.translate( 0, canvas.height );
967
- ctx.scale( 1, - 1 );
968
-
969
- }
970
-
971
- if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
972
- ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
973
- ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ||
974
- ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
975
-
976
- ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
977
-
978
- } else {
979
-
980
- if ( format !== RGBAFormat && format !== RGBFormat ) {
981
-
982
- console.error( 'GLTFExporter: Only RGB and RGBA formats are supported.' );
983
-
984
- }
985
-
986
- if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
987
-
988
- console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
989
-
990
- }
991
-
992
- const data = new Uint8ClampedArray( image.height * image.width * 4 );
993
-
994
- if ( format === RGBAFormat ) {
995
-
996
- for ( let i = 0; i < data.length; i += 4 ) {
997
-
998
- data[ i + 0 ] = image.data[ i + 0 ];
999
- data[ i + 1 ] = image.data[ i + 1 ];
1000
- data[ i + 2 ] = image.data[ i + 2 ];
1001
- data[ i + 3 ] = image.data[ i + 3 ];
1002
-
1003
- }
1004
-
1005
- } else {
1006
-
1007
- for ( let i = 0, j = 0; i < data.length; i += 4, j += 3 ) {
1008
-
1009
- data[ i + 0 ] = image.data[ j + 0 ];
1010
- data[ i + 1 ] = image.data[ j + 1 ];
1011
- data[ i + 2 ] = image.data[ j + 2 ];
1012
- data[ i + 3 ] = 255;
1013
-
1014
- }
1015
-
1016
- }
1017
-
1018
- ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
1019
-
1020
- }
1021
-
1022
- if ( options.binary === true ) {
1023
-
1024
- pending.push( new Promise( function ( resolve ) {
1025
-
1026
- canvas.toBlob( function ( blob ) {
1027
-
1028
- writer.processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
1029
-
1030
- imageDef.bufferView = bufferViewIndex;
1031
- resolve();
1032
-
1033
- } );
1034
-
1035
- }, mimeType );
1036
-
1037
- } ) );
1038
-
1039
- } else {
1040
-
1041
- imageDef.uri = canvas.toDataURL( mimeType );
1042
-
1043
- }
1044
-
1045
- } else {
1046
-
1047
- imageDef.uri = image.src;
1048
-
1049
- }
1050
-
1051
- const index = json.images.push( imageDef ) - 1;
1052
- cachedImages[ key ] = index;
1053
- return index;
1054
-
1055
- }
1056
-
1057
- /**
1058
- * Process sampler
1059
- * @param {Texture} map Texture to process
1060
- * @return {Integer} Index of the processed texture in the "samplers" array
1061
- */
1062
- processSampler( map ) {
1063
-
1064
- const json = this.json;
1065
-
1066
- if ( ! json.samplers ) json.samplers = [];
1067
-
1068
- const samplerDef = {
1069
- magFilter: THREE_TO_WEBGL[ map.magFilter ],
1070
- minFilter: THREE_TO_WEBGL[ map.minFilter ],
1071
- wrapS: THREE_TO_WEBGL[ map.wrapS ],
1072
- wrapT: THREE_TO_WEBGL[ map.wrapT ]
1073
- };
1074
-
1075
- return json.samplers.push( samplerDef ) - 1;
1076
-
1077
- }
1078
-
1079
- /**
1080
- * Process texture
1081
- * @param {Texture} map Map to process
1082
- * @return {Integer} Index of the processed texture in the "textures" array
1083
- */
1084
- processTexture( map ) {
1085
-
1086
- const cache = this.cache;
1087
- const json = this.json;
1088
-
1089
- if ( cache.textures.has( map ) ) return cache.textures.get( map );
1090
-
1091
- if ( ! json.textures ) json.textures = [];
1092
-
1093
- const textureDef = {
1094
- sampler: this.processSampler( map ),
1095
- source: this.processImage( map.image, map.format, map.flipY )
1096
- };
1097
-
1098
- if ( map.name ) textureDef.name = map.name;
1099
-
1100
- this._invokeAll( function ( ext ) {
1101
-
1102
- ext.writeTexture && ext.writeTexture( map, textureDef );
1103
-
1104
- } );
1105
-
1106
- const index = json.textures.push( textureDef ) - 1;
1107
- cache.textures.set( map, index );
1108
- return index;
1109
-
1110
- }
1111
-
1112
- /**
1113
- * Process material
1114
- * @param {THREE.Material} material Material to process
1115
- * @return {Integer|null} Index of the processed material in the "materials" array
1116
- */
1117
- processMaterial( material ) {
1118
-
1119
- const cache = this.cache;
1120
- const json = this.json;
1121
-
1122
- if ( cache.materials.has( material ) ) return cache.materials.get( material );
1123
-
1124
- if ( material.isShaderMaterial ) {
1125
-
1126
- console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
1127
- return null;
1128
-
1129
- }
1130
-
1131
- if ( ! json.materials ) json.materials = [];
1132
-
1133
- // @QUESTION Should we avoid including any attribute that has the default value?
1134
- const materialDef = { pbrMetallicRoughness: {} };
1135
-
1136
- if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
1137
-
1138
- console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
1139
-
1140
- }
1141
-
1142
- // pbrMetallicRoughness.baseColorFactor
1143
- const color = material.color.toArray().concat( [ material.opacity ] );
1144
-
1145
- if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
1146
-
1147
- materialDef.pbrMetallicRoughness.baseColorFactor = color;
1148
-
1149
- }
1150
-
1151
- if ( material.isMeshStandardMaterial ) {
1152
-
1153
- materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
1154
- materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
1155
-
1156
- } else {
1157
-
1158
- materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
1159
- materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
1160
-
1161
- }
1162
-
1163
- // pbrMetallicRoughness.metallicRoughnessTexture
1164
- if ( material.metalnessMap || material.roughnessMap ) {
1165
-
1166
- if ( material.metalnessMap === material.roughnessMap ) {
1167
-
1168
- const metalRoughMapDef = { index: this.processTexture( material.metalnessMap ) };
1169
- this.applyTextureTransform( metalRoughMapDef, material.metalnessMap );
1170
- materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
1171
-
1172
- } else {
1173
-
1174
- console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
1175
-
1176
- }
1177
-
1178
- }
1179
-
1180
- // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
1181
- if ( material.map ) {
1182
-
1183
- const baseColorMapDef = { index: this.processTexture( material.map ) };
1184
- this.applyTextureTransform( baseColorMapDef, material.map );
1185
- materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
1186
-
1187
- }
1188
-
1189
- if ( material.emissive ) {
1190
-
1191
- // note: emissive components are limited to stay within the 0 - 1 range to accommodate glTF spec. see #21849 and #22000.
1192
- const emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity );
1193
- const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
1194
-
1195
- if ( maxEmissiveComponent > 1 ) {
1196
-
1197
- emissive.multiplyScalar( 1 / maxEmissiveComponent );
1198
-
1199
- console.warn( 'THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited' );
1200
-
1201
- }
1202
-
1203
- if ( maxEmissiveComponent > 0 ) {
1204
-
1205
- materialDef.emissiveFactor = emissive.toArray();
1206
-
1207
- }
1208
-
1209
- // emissiveTexture
1210
- if ( material.emissiveMap ) {
1211
-
1212
- const emissiveMapDef = { index: this.processTexture( material.emissiveMap ) };
1213
- this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
1214
- materialDef.emissiveTexture = emissiveMapDef;
1215
-
1216
- }
1217
-
1218
- }
1219
-
1220
- // normalTexture
1221
- if ( material.normalMap ) {
1222
-
1223
- const normalMapDef = { index: this.processTexture( material.normalMap ) };
1224
-
1225
- if ( material.normalScale && material.normalScale.x !== - 1 ) {
1226
-
1227
- if ( material.normalScale.x !== material.normalScale.y ) {
1228
-
1229
- console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
1230
-
1231
- }
1232
-
1233
- normalMapDef.scale = material.normalScale.x;
1234
-
1235
- }
1236
-
1237
- this.applyTextureTransform( normalMapDef, material.normalMap );
1238
- materialDef.normalTexture = normalMapDef;
1239
-
1240
- }
1241
-
1242
- // occlusionTexture
1243
- if ( material.aoMap ) {
1244
-
1245
- const occlusionMapDef = {
1246
- index: this.processTexture( material.aoMap ),
1247
- texCoord: 1
1248
- };
1249
-
1250
- if ( material.aoMapIntensity !== 1.0 ) {
1251
-
1252
- occlusionMapDef.strength = material.aoMapIntensity;
1253
-
1254
- }
1255
-
1256
- this.applyTextureTransform( occlusionMapDef, material.aoMap );
1257
- materialDef.occlusionTexture = occlusionMapDef;
1258
-
1259
- }
1260
-
1261
- // alphaMode
1262
- if ( material.transparent ) {
1263
-
1264
- materialDef.alphaMode = 'BLEND';
1265
-
1266
- } else {
1267
-
1268
- if ( material.alphaTest > 0.0 ) {
1269
-
1270
- materialDef.alphaMode = 'MASK';
1271
- materialDef.alphaCutoff = material.alphaTest;
1272
-
1273
- }
1274
-
1275
- }
1276
-
1277
- // doubleSided
1278
- if ( material.side === DoubleSide ) materialDef.doubleSided = true;
1279
- if ( material.name !== '' ) materialDef.name = material.name;
1280
-
1281
- this.serializeUserData( material, materialDef );
1282
-
1283
- this._invokeAll( function ( ext ) {
1284
-
1285
- ext.writeMaterial && ext.writeMaterial( material, materialDef );
1286
-
1287
- } );
1288
-
1289
- const index = json.materials.push( materialDef ) - 1;
1290
- cache.materials.set( material, index );
1291
- return index;
1292
-
1293
- }
1294
-
1295
- /**
1296
- * A Pointset's {@link InstancedPoints} draws every point as an instance of a
1297
- * small camera facing quad - its `geometry` only carries that quad, the
1298
- * actual point positions/colours live in `pointPositions`/`instanceColor`.
1299
- * Temporarily substitute a plain points geometry built from that data (and
1300
- * flag the object as `isPoints`) so the regular POINTS export path below
1301
- * produces a correct round trip, then return a function that restores the
1302
- * object to its original state.
1303
- *
1304
- * @param {InstancedPoints} object Object to substitute the geometry of
1305
- * @return {Function} Restores `object` to its pre-substitution state
1306
- */
1307
- substituteInstancedPointsGeometry( object ) {
1308
-
1309
- const count = object.count;
1310
- const geometry = new BufferGeometry();
1311
- geometry.setAttribute( 'position',
1312
- new BufferAttribute( object.pointPositions.slice( 0, count * 3 ), 3 ) );
1313
-
1314
- if ( object.instanceColor ) {
1315
-
1316
- geometry.setAttribute( 'color',
1317
- new BufferAttribute( object.instanceColor.array.slice( 0, count * 3 ), 3 ) );
1318
-
1319
- }
1320
-
1321
- const originalGeometry = object.geometry;
1322
- const originalIsPoints = object.isPoints;
1323
-
1324
- object.geometry = geometry;
1325
- object.isPoints = true;
1326
-
1327
- return function () {
1328
-
1329
- object.geometry = originalGeometry;
1330
- object.isPoints = originalIsPoints;
1331
- geometry.dispose();
1332
-
1333
- };
1334
-
1335
- }
1336
-
1337
- /**
1338
- * Process mesh
1339
- * @param {THREE.Mesh} mesh Mesh to process
1340
- * @return {Integer|null} Index of the processed mesh in the "meshes" array
1341
- */
1342
- processMesh( mesh ) {
1343
-
1344
- const cache = this.cache;
1345
- const json = this.json;
1346
-
1347
- const meshCacheKeyParts = [ mesh.geometry.uuid ];
1348
-
1349
- if ( Array.isArray( mesh.material ) ) {
1350
-
1351
- for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
1352
-
1353
- meshCacheKeyParts.push( mesh.material[ i ].uuid );
1354
-
1355
- }
1356
-
1357
- } else {
1358
-
1359
- meshCacheKeyParts.push( mesh.material.uuid );
1360
-
1361
- }
1362
-
1363
- const meshCacheKey = meshCacheKeyParts.join( ':' );
1364
-
1365
- if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
1366
-
1367
- const geometry = mesh.geometry;
1368
- let mode;
1369
-
1370
- // Use the correct mode
1371
- if ( mesh.isLineSegments ) {
1372
-
1373
- mode = WEBGL_CONSTANTS.LINES;
1374
-
1375
- } else if ( mesh.isLineLoop ) {
1376
-
1377
- mode = WEBGL_CONSTANTS.LINE_LOOP;
1378
-
1379
- } else if ( mesh.isLine ) {
1380
-
1381
- mode = WEBGL_CONSTANTS.LINE_STRIP;
1382
-
1383
- } else if ( mesh.isPoints ) {
1384
-
1385
- mode = WEBGL_CONSTANTS.POINTS;
1386
-
1387
- } else {
1388
-
1389
- mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
1390
-
1391
- }
1392
-
1393
- if ( geometry.isBufferGeometry !== true ) {
1394
-
1395
- throw new Error( 'THREE.GLTFExporter: Geometry is not of type THREE.BufferGeometry.' );
1396
-
1397
- }
1398
-
1399
- const meshDef = {};
1400
- const attributes = {};
1401
- const primitives = [];
1402
- const targets = [];
1403
-
1404
- // Conversion between attributes names in threejs and gltf spec
1405
- const nameConversion = {
1406
- uv: 'TEXCOORD_0',
1407
- uv2: 'TEXCOORD_1',
1408
- color: 'COLOR_0',
1409
- skinWeight: 'WEIGHTS_0',
1410
- skinIndex: 'JOINTS_0'
1411
- };
1412
-
1413
- const originalNormal = geometry.getAttribute( 'normal' );
1414
-
1415
- if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
1416
-
1417
- console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
1418
-
1419
- geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
1420
-
1421
- }
1422
-
1423
- // @QUESTION Detect if .vertexColors = true?
1424
- // For every attribute create an accessor
1425
- let modifiedAttribute = null;
1426
-
1427
- for ( let attributeName in geometry.attributes ) {
1428
-
1429
- // Ignore morph target attributes, which are exported later.
1430
- if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
1431
-
1432
- const attribute = geometry.attributes[ attributeName ];
1433
- attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
1434
-
1435
- // Prefix all geometry attributes except the ones specifically
1436
- // listed in the spec; non-spec attributes are considered custom.
1437
- const validVertexAttributes =
1438
- /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
1439
-
1440
- if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
1441
-
1442
- if ( cache.attributes.has( this.getUID( attribute ) ) ) {
1443
-
1444
- attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
1445
- continue;
1446
-
1447
- }
1448
-
1449
- // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
1450
- modifiedAttribute = null;
1451
- const array = attribute.array;
1452
-
1453
- if ( attributeName === 'JOINTS_0' &&
1454
- ! ( array instanceof Uint16Array ) &&
1455
- ! ( array instanceof Uint8Array ) ) {
1456
-
1457
- console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
1458
- modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
1459
-
1460
- }
1461
-
1462
- const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
1463
-
1464
- if ( accessor !== null ) {
1465
-
1466
- attributes[ attributeName ] = accessor;
1467
- cache.attributes.set( this.getUID( attribute ), accessor );
1468
-
1469
- }
1470
-
1471
- }
1472
-
1473
- if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
1474
-
1475
- // Skip if no exportable attributes found
1476
- if ( Object.keys( attributes ).length === 0 ) return null;
1477
-
1478
- // Morph targets
1479
- if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
1480
-
1481
- const weights = [];
1482
- const targetNames = [];
1483
- const reverseDictionary = {};
1484
-
1485
- if ( mesh.morphTargetDictionary !== undefined ) {
1486
-
1487
- for ( const key in mesh.morphTargetDictionary ) {
1488
-
1489
- reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
1490
-
1491
- }
1492
-
1493
- }
1494
-
1495
- for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
1496
-
1497
- const target = {};
1498
- let warned = false;
1499
-
1500
- for ( const attributeName in geometry.morphAttributes ) {
1501
-
1502
-
1503
- // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
1504
- // Three.js doesn't support TANGENT yet.
1505
-
1506
- if ( attributeName !== 'position' && attributeName !== 'normal' && attributeName !== 'color' ) {
1507
-
1508
- if ( ! warned ) {
1509
-
1510
- console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
1511
- warned = true;
1512
-
1513
- }
1514
-
1515
- continue;
1516
-
1517
- }
1518
-
1519
- const attribute = geometry.morphAttributes[ attributeName ][ i ];
1520
- let gltfAttributeName = attributeName.toUpperCase();
1521
-
1522
- if ( nameConversion[ attributeName ] ) {
1523
-
1524
- gltfAttributeName = nameConversion[ attributeName ];
1525
-
1526
- }
1527
-
1528
- // Three.js morph attribute has absolute values while the one of glTF has relative values.
1529
- //
1530
- // glTF 2.0 Specification:
1531
- // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
1532
-
1533
- const baseAttribute = geometry.attributes[ attributeName ];
1534
-
1535
- if ( cache.attributes.has( this.getUID( attribute ) ) ) {
1536
-
1537
- target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute ) );
1538
- continue;
1539
-
1540
- }
1541
-
1542
- // Clones attribute not to override
1543
- const relativeAttribute = baseAttribute.clone();
1544
-
1545
- if ( ! geometry.morphTargetsRelative ) {
1546
-
1547
- if (baseAttribute) {
1548
-
1549
- for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
1550
-
1551
- if (baseAttribute.count > j) {
1552
-
1553
- relativeAttribute.setXYZ(
1554
- j,
1555
- attribute.getX( j ) - baseAttribute.getX( j ),
1556
- attribute.getY( j ) - baseAttribute.getY( j ),
1557
- attribute.getZ( j ) - baseAttribute.getZ( j )
1558
- );
1559
-
1560
- }
1561
-
1562
- }
1563
-
1564
- } else {
1565
-
1566
- for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
1567
-
1568
- relativeAttribute.setXYZ(
1569
- j,
1570
- 0,
1571
- 0,
1572
- 0
1573
- );
1574
-
1575
- }
1576
-
1577
- }
1578
-
1579
- }
1580
-
1581
- target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
1582
- cache.attributes.set( this.getUID( baseAttribute ), target[ gltfAttributeName ] );
1583
-
1584
- }
1585
-
1586
- targets.push( target );
1587
-
1588
- weights.push( mesh.morphTargetInfluences[ i ] );
1589
-
1590
- if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
1591
-
1592
- }
1593
-
1594
- meshDef.weights = weights;
1595
-
1596
- if ( targetNames.length > 0 ) {
1597
-
1598
- meshDef.extras = {};
1599
- meshDef.extras.targetNames = targetNames;
1600
-
1601
- }
1602
-
1603
- }
1604
-
1605
- const isMultiMaterial = Array.isArray( mesh.material );
1606
-
1607
- if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
1608
-
1609
- const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
1610
- const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
1611
-
1612
- for ( let i = 0, il = groups.length; i < il; i ++ ) {
1613
-
1614
- const primitive = {
1615
- mode: mode,
1616
- attributes: attributes,
1617
- };
1618
-
1619
- this.serializeUserData( geometry, primitive );
1620
-
1621
- if ( targets.length > 0 ) primitive.targets = targets;
1622
-
1623
- if ( geometry.index !== null ) {
1624
-
1625
- let cacheKey = this.getUID( geometry.index );
1626
-
1627
- if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
1628
-
1629
- cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
1630
-
1631
- }
1632
-
1633
- if ( cache.attributes.has( cacheKey ) ) {
1634
-
1635
- primitive.indices = cache.attributes.get( cacheKey );
1636
-
1637
- } else {
1638
-
1639
- primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
1640
- cache.attributes.set( cacheKey, primitive.indices );
1641
-
1642
- }
1643
-
1644
- if ( primitive.indices === null ) delete primitive.indices;
1645
-
1646
- }
1647
-
1648
- const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
1649
-
1650
- if ( material !== null ) primitive.material = material;
1651
-
1652
- primitives.push( primitive );
1653
-
1654
- }
1655
-
1656
- meshDef.primitives = primitives;
1657
-
1658
- if ( ! json.meshes ) json.meshes = [];
1659
-
1660
- this._invokeAll( function ( ext ) {
1661
-
1662
- ext.writeMesh && ext.writeMesh( mesh, meshDef );
1663
-
1664
- } );
1665
-
1666
- const index = json.meshes.push( meshDef ) - 1;
1667
- cache.meshes.set( meshCacheKey, index );
1668
- return index;
1669
-
1670
- }
1671
-
1672
- /**
1673
- * Process camera
1674
- * @param {THREE.Camera} camera Camera to process
1675
- * @return {Integer} Index of the processed mesh in the "camera" array
1676
- */
1677
- processCamera( camera ) {
1678
-
1679
- const json = this.json;
1680
-
1681
- if ( ! json.cameras ) json.cameras = [];
1682
-
1683
- const isOrtho = camera.isOrthographicCamera;
1684
-
1685
- const cameraDef = {
1686
- type: isOrtho ? 'orthographic' : 'perspective'
1687
- };
1688
-
1689
- if ( isOrtho ) {
1690
-
1691
- cameraDef.orthographic = {
1692
- xmag: camera.right * 2,
1693
- ymag: camera.top * 2,
1694
- zfar: camera.far <= 0 ? 0.001 : camera.far,
1695
- znear: camera.near < 0 ? 0 : camera.near
1696
- };
1697
-
1698
- } else {
1699
-
1700
- cameraDef.perspective = {
1701
- aspectRatio: camera.aspect,
1702
- yfov: MathUtils.degToRad( camera.fov ),
1703
- zfar: camera.far <= 0 ? 0.001 : camera.far,
1704
- znear: camera.near < 0 ? 0 : camera.near
1705
- };
1706
-
1707
- }
1708
-
1709
- // Question: Is saving "type" as name intentional?
1710
- if ( camera.name !== '' ) cameraDef.name = camera.type;
1711
-
1712
- return json.cameras.push( cameraDef ) - 1;
1713
-
1714
- }
1715
-
1716
- /**
1717
- * Creates glTF animation entry from AnimationClip object.
1718
- *
1719
- * Status:
1720
- * - Only properties listed in PATH_PROPERTIES may be animated.
1721
- *
1722
- * @param {THREE.AnimationClip} clip
1723
- * @param {THREE.Object3D} root
1724
- * @return {number|null}
1725
- */
1726
- processAnimation( clip, root ) {
1727
-
1728
- const json = this.json;
1729
- const nodeMap = this.nodeMap;
1730
-
1731
- if ( ! json.animations ) json.animations = [];
1732
-
1733
- clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
1734
-
1735
- const tracks = clip.tracks;
1736
- const channels = [];
1737
- const samplers = [];
1738
-
1739
- for ( let i = 0; i < tracks.length; ++ i ) {
1740
-
1741
- const track = tracks[ i ];
1742
- const trackBinding = PropertyBinding.parseTrackName( track.name );
1743
- let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
1744
- const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
1745
-
1746
- if ( trackBinding.objectName === 'bones' ) {
1747
-
1748
- if ( trackNode.isSkinnedMesh === true ) {
1749
-
1750
- trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
1751
-
1752
- } else {
1753
-
1754
- trackNode = undefined;
1755
-
1756
- }
1757
-
1758
- }
1759
-
1760
- if ( ! trackNode || ! trackProperty ) {
1761
-
1762
- console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
1763
- return null;
1764
-
1765
- }
1766
-
1767
- const inputItemSize = 1;
1768
- let outputItemSize = track.values.length / track.times.length;
1769
-
1770
- if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
1771
-
1772
- outputItemSize /= trackNode.morphTargetInfluences.length;
1773
-
1774
- }
1775
-
1776
- let interpolation;
1777
-
1778
- // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
1779
-
1780
- // Detecting glTF cubic spline interpolant by checking factory method's special property
1781
- // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
1782
- // valid value from .getInterpolation().
1783
- if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
1784
-
1785
- interpolation = 'CUBICSPLINE';
1786
-
1787
- // itemSize of CUBICSPLINE keyframe is 9
1788
- // (VEC3 * 3: inTangent, splineVertex, and outTangent)
1789
- // but needs to be stored as VEC3 so dividing by 3 here.
1790
- outputItemSize /= 3;
1791
-
1792
- } else if ( track.getInterpolation() === InterpolateDiscrete ) {
1793
-
1794
- interpolation = 'STEP';
1795
-
1796
- } else {
1797
-
1798
- interpolation = 'LINEAR';
1799
-
1800
- }
1801
-
1802
- samplers.push( {
1803
- input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
1804
- output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
1805
- interpolation: interpolation
1806
- } );
1807
-
1808
- channels.push( {
1809
- sampler: samplers.length - 1,
1810
- target: {
1811
- node: nodeMap.get( trackNode ),
1812
- path: trackProperty
1813
- }
1814
- } );
1815
-
1816
- }
1817
-
1818
- json.animations.push( {
1819
- name: clip.name || 'clip_' + json.animations.length,
1820
- samplers: samplers,
1821
- channels: channels
1822
- } );
1823
-
1824
- return json.animations.length - 1;
1825
-
1826
- }
1827
-
1828
- /**
1829
- * @param {THREE.Object3D} object
1830
- * @return {number|null}
1831
- */
1832
- processSkin( object ) {
1833
-
1834
- const json = this.json;
1835
- const nodeMap = this.nodeMap;
1836
-
1837
- const node = json.nodes[ nodeMap.get( object ) ];
1838
-
1839
- const skeleton = object.skeleton;
1840
-
1841
- if ( skeleton === undefined ) return null;
1842
-
1843
- const rootJoint = object.skeleton.bones[ 0 ];
1844
-
1845
- if ( rootJoint === undefined ) return null;
1846
-
1847
- const joints = [];
1848
- const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
1849
- const temporaryBoneInverse = new Matrix4();
1850
-
1851
- for ( let i = 0; i < skeleton.bones.length; ++ i ) {
1852
-
1853
- joints.push( nodeMap.get( skeleton.bones[ i ] ) );
1854
- temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
1855
- temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
1856
-
1857
- }
1858
-
1859
- if ( json.skins === undefined ) json.skins = [];
1860
-
1861
- json.skins.push( {
1862
- inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
1863
- joints: joints,
1864
- skeleton: nodeMap.get( rootJoint )
1865
- } );
1866
-
1867
- const skinIndex = node.skin = json.skins.length - 1;
1868
-
1869
- return skinIndex;
1870
-
1871
- }
1872
-
1873
- /**
1874
- * Process Object3D node
1875
- * @param {THREE.Object3D} node Object3D to processNode
1876
- * @return {Integer} Index of the node in the nodes list
1877
- */
1878
- processNode( object ) {
1879
-
1880
- const json = this.json;
1881
- const options = this.options;
1882
- const nodeMap = this.nodeMap;
1883
-
1884
- if ( ! json.nodes ) json.nodes = [];
1885
-
1886
- const nodeDef = {};
1887
-
1888
- if ( options.trs ) {
1889
-
1890
- const rotation = object.quaternion.toArray();
1891
- const position = object.position.toArray();
1892
- const scale = object.scale.toArray();
1893
-
1894
- if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
1895
-
1896
- nodeDef.rotation = rotation;
1897
-
1898
- }
1899
-
1900
- if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
1901
-
1902
- nodeDef.translation = position;
1903
-
1904
- }
1905
-
1906
- if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
1907
-
1908
- nodeDef.scale = scale;
1909
-
1910
- }
1911
-
1912
- } else {
1913
-
1914
- if ( object.matrixAutoUpdate ) {
1915
-
1916
- object.updateMatrix();
1917
-
1918
- }
1919
-
1920
- if ( isIdentityMatrix( object.matrix ) === false ) {
1921
-
1922
- nodeDef.matrix = object.matrix.elements;
1923
-
1924
- }
1925
-
1926
- }
1927
-
1928
- // We don't export empty strings name because it represents no-name in Three.js.
1929
- if ( object.name !== '' ) nodeDef.name = String( object.name );
1930
-
1931
- this.serializeUserData( object, nodeDef );
1932
-
1933
- if ( object.isMesh || object.isLine || object.isPoints || object.isInstancedPoints ) {
1934
-
1935
- let restoreInstancedPoints;
1936
-
1937
- if ( object.isInstancedPoints ) {
1938
-
1939
- restoreInstancedPoints = this.substituteInstancedPointsGeometry( object );
1940
-
1941
- }
1942
-
1943
- const meshIndex = this.processMesh( object );
1944
-
1945
- if ( restoreInstancedPoints ) restoreInstancedPoints();
1946
-
1947
- if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
1948
-
1949
- } else if ( object.isCamera ) {
1950
-
1951
- nodeDef.camera = this.processCamera( object );
1952
-
1953
- }
1954
-
1955
- if ( object.isSkinnedMesh ) this.skins.push( object );
1956
-
1957
- if ( object.children.length > 0 ) {
1958
-
1959
- const children = [];
1960
-
1961
- for ( let i = 0, l = object.children.length; i < l; i ++ ) {
1962
-
1963
- const child = object.children[ i ];
1964
-
1965
- if ( child.visible || options.onlyVisible === false ) {
1966
-
1967
- const nodeIndex = this.processNode( child );
1968
-
1969
- if ( nodeIndex !== null ) children.push( nodeIndex );
1970
-
1971
- }
1972
-
1973
- }
1974
-
1975
- if ( children.length > 0 ) nodeDef.children = children;
1976
-
1977
- }
1978
-
1979
- this._invokeAll( function ( ext ) {
1980
-
1981
- ext.writeNode && ext.writeNode( object, nodeDef );
1982
-
1983
- } );
1984
-
1985
- const nodeIndex = json.nodes.push( nodeDef ) - 1;
1986
- nodeMap.set( object, nodeIndex );
1987
- return nodeIndex;
1988
-
1989
- }
1990
-
1991
- /**
1992
- * Process Scene
1993
- * @param {Scene} node Scene to process
1994
- */
1995
- processScene( scene ) {
1996
-
1997
- const json = this.json;
1998
- const options = this.options;
1999
-
2000
- if ( ! json.scenes ) {
2001
-
2002
- json.scenes = [];
2003
- json.scene = 0;
2004
-
2005
- }
2006
-
2007
- const sceneDef = {};
2008
-
2009
- if ( scene.name !== '' ) sceneDef.name = scene.name;
2010
-
2011
- json.scenes.push( sceneDef );
2012
-
2013
- const nodes = [];
2014
-
2015
- for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
2016
-
2017
- const child = scene.children[ i ];
2018
-
2019
- if ( child.visible || options.onlyVisible === false ) {
2020
-
2021
- const nodeIndex = this.processNode( child );
2022
-
2023
- if ( nodeIndex !== null ) nodes.push( nodeIndex );
2024
-
2025
- }
2026
-
2027
- }
2028
-
2029
- if ( nodes.length > 0 ) sceneDef.nodes = nodes;
2030
-
2031
- this.serializeUserData( scene, sceneDef );
2032
-
2033
- }
2034
-
2035
- /**
2036
- * Creates a Scene to hold a list of objects and parse it
2037
- * @param {Array} objects List of objects to process
2038
- */
2039
- processObjects( objects ) {
2040
-
2041
- const scene = new Scene();
2042
- scene.name = 'AuxScene';
2043
-
2044
- for ( let i = 0; i < objects.length; i ++ ) {
2045
-
2046
- // We push directly to children instead of calling `add` to prevent
2047
- // modify the .parent and break its original scene and hierarchy
2048
- scene.children.push( objects[ i ] );
2049
-
2050
- }
2051
-
2052
- this.processScene( scene );
2053
-
2054
- }
2055
-
2056
- /**
2057
- * @param {THREE.Object3D|Array<THREE.Object3D>} input
2058
- */
2059
- processInput( input ) {
2060
-
2061
- const options = this.options;
2062
-
2063
- input = input instanceof Array ? input : [ input ];
2064
-
2065
- this._invokeAll( function ( ext ) {
2066
-
2067
- ext.beforeParse && ext.beforeParse( input );
2068
-
2069
- } );
2070
-
2071
- const objectsWithoutScene = [];
2072
-
2073
- for ( let i = 0; i < input.length; i ++ ) {
2074
-
2075
- if ( input[ i ] instanceof Scene ) {
2076
-
2077
- this.processScene( input[ i ] );
2078
-
2079
- } else {
2080
-
2081
- objectsWithoutScene.push( input[ i ] );
2082
-
2083
- }
2084
-
2085
- }
2086
-
2087
- if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
2088
-
2089
- for ( let i = 0; i < this.skins.length; ++ i ) {
2090
-
2091
- this.processSkin( this.skins[ i ] );
2092
-
2093
- }
2094
-
2095
- for ( let i = 0; i < options.animations.length; ++ i ) {
2096
-
2097
- this.processAnimation( options.animations[ i ].clip, options.animations[i].mesh);
2098
-
2099
- }
2100
-
2101
- this._invokeAll( function ( ext ) {
2102
-
2103
- ext.afterParse && ext.afterParse( input );
2104
-
2105
- } );
2106
-
2107
- }
2108
-
2109
- _invokeAll( func ) {
2110
-
2111
- for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
2112
-
2113
- func( this.plugins[ i ] );
2114
-
2115
- }
2116
-
2117
- }
2118
-
2119
- }
2120
-
2121
- /**
2122
- * Punctual Lights Extension
2123
- *
2124
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
2125
- */
2126
- class GLTFLightExtension {
2127
-
2128
- constructor( writer ) {
2129
-
2130
- this.writer = writer;
2131
- this.name = 'KHR_lights_punctual';
2132
-
2133
- }
2134
-
2135
- writeNode( light, nodeDef ) {
2136
-
2137
- if ( ! light.isLight ) return;
2138
-
2139
- if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
2140
-
2141
- console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
2142
- return;
2143
-
2144
- }
2145
-
2146
- const writer = this.writer;
2147
- const json = writer.json;
2148
- const extensionsUsed = writer.extensionsUsed;
2149
-
2150
- const lightDef = {};
2151
-
2152
- if ( light.name ) lightDef.name = light.name;
2153
-
2154
- lightDef.color = light.color.toArray();
2155
-
2156
- lightDef.intensity = light.intensity;
2157
-
2158
- if ( light.isDirectionalLight ) {
2159
-
2160
- lightDef.type = 'directional';
2161
-
2162
- } else if ( light.isPointLight ) {
2163
-
2164
- lightDef.type = 'point';
2165
-
2166
- if ( light.distance > 0 ) lightDef.range = light.distance;
2167
-
2168
- } else if ( light.isSpotLight ) {
2169
-
2170
- lightDef.type = 'spot';
2171
-
2172
- if ( light.distance > 0 ) lightDef.range = light.distance;
2173
-
2174
- lightDef.spot = {};
2175
- lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
2176
- lightDef.spot.outerConeAngle = light.angle;
2177
-
2178
- }
2179
-
2180
- if ( light.decay !== undefined && light.decay !== 2 ) {
2181
-
2182
- console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
2183
- + 'and expects light.decay=2.' );
2184
-
2185
- }
2186
-
2187
- if ( light.target
2188
- && ( light.target.parent !== light
2189
- || light.target.position.x !== 0
2190
- || light.target.position.y !== 0
2191
- || light.target.position.z !== - 1 ) ) {
2192
-
2193
- console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
2194
- + 'make light.target a child of the light with position 0,0,-1.' );
2195
-
2196
- }
2197
-
2198
- if ( ! extensionsUsed[ this.name ] ) {
2199
-
2200
- json.extensions = json.extensions || {};
2201
- json.extensions[ this.name ] = { lights: [] };
2202
- extensionsUsed[ this.name ] = true;
2203
-
2204
- }
2205
-
2206
- const lights = json.extensions[ this.name ].lights;
2207
- lights.push( lightDef );
2208
-
2209
- nodeDef.extensions = nodeDef.extensions || {};
2210
- nodeDef.extensions[ this.name ] = { light: lights.length - 1 };
2211
-
2212
- }
2213
-
2214
- }
2215
-
2216
- /**
2217
- * Unlit Materials Extension
2218
- *
2219
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
2220
- */
2221
- class GLTFMaterialsUnlitExtension {
2222
-
2223
- constructor( writer ) {
2224
-
2225
- this.writer = writer;
2226
- this.name = 'KHR_materials_unlit';
2227
-
2228
- }
2229
-
2230
- writeMaterial( material, materialDef ) {
2231
-
2232
- if ( ! material.isMeshBasicMaterial ) return;
2233
-
2234
- const writer = this.writer;
2235
- const extensionsUsed = writer.extensionsUsed;
2236
-
2237
- materialDef.extensions = materialDef.extensions || {};
2238
- materialDef.extensions[ this.name ] = {};
2239
-
2240
- extensionsUsed[ this.name ] = true;
2241
-
2242
- materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
2243
- materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
2244
-
2245
- }
2246
-
2247
- }
2248
-
2249
- /**
2250
- * Specular-Glossiness Extension
2251
- *
2252
- * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
2253
- */
2254
- class GLTFMaterialsPBRSpecularGlossiness {
2255
-
2256
- constructor( writer ) {
2257
-
2258
- this.writer = writer;
2259
- this.name = 'KHR_materials_pbrSpecularGlossiness';
2260
-
2261
- }
2262
-
2263
- writeMaterial( material, materialDef ) {
2264
-
2265
- if ( ! material.isGLTFSpecularGlossinessMaterial ) return;
2266
-
2267
- const writer = this.writer;
2268
- const extensionsUsed = writer.extensionsUsed;
2269
-
2270
- const extensionDef = {};
2271
-
2272
- if ( materialDef.pbrMetallicRoughness.baseColorFactor ) {
2273
-
2274
- extensionDef.diffuseFactor = materialDef.pbrMetallicRoughness.baseColorFactor;
2275
-
2276
- }
2277
-
2278
- const specularFactor = [ 1, 1, 1 ];
2279
- material.specular.toArray( specularFactor, 0 );
2280
- extensionDef.specularFactor = specularFactor;
2281
- extensionDef.glossinessFactor = material.glossiness;
2282
-
2283
- if ( materialDef.pbrMetallicRoughness.baseColorTexture ) {
2284
-
2285
- extensionDef.diffuseTexture = materialDef.pbrMetallicRoughness.baseColorTexture;
2286
-
2287
- }
2288
-
2289
- if ( material.specularMap ) {
2290
-
2291
- const specularMapDef = { index: writer.processTexture( material.specularMap ) };
2292
- writer.applyTextureTransform( specularMapDef, material.specularMap );
2293
- extensionDef.specularGlossinessTexture = specularMapDef;
2294
-
2295
- }
2296
-
2297
- materialDef.extensions = materialDef.extensions || {};
2298
- materialDef.extensions[ this.name ] = extensionDef;
2299
- extensionsUsed[ this.name ] = true;
2300
-
2301
- }
2302
-
2303
- }
2304
-
2305
- /**
2306
- * Static utility functions
2307
- */
2308
- GLTFExporter.Utils = {
2309
-
2310
- insertKeyframe: function ( track, time ) {
2311
-
2312
- const tolerance = 0.001; // 1ms
2313
- const valueSize = track.getValueSize();
2314
-
2315
- const times = new track.TimeBufferType( track.times.length + 1 );
2316
- const values = new track.ValueBufferType( track.values.length + valueSize );
2317
- const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
2318
-
2319
- let index;
2320
-
2321
- if ( track.times.length === 0 ) {
2322
-
2323
- times[ 0 ] = time;
2324
-
2325
- for ( let i = 0; i < valueSize; i ++ ) {
2326
-
2327
- values[ i ] = 0;
2328
-
2329
- }
2330
-
2331
- index = 0;
2332
-
2333
- } else if ( time < track.times[ 0 ] ) {
2334
-
2335
- if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
2336
-
2337
- times[ 0 ] = time;
2338
- times.set( track.times, 1 );
2339
-
2340
- values.set( interpolant.evaluate( time ), 0 );
2341
- values.set( track.values, valueSize );
2342
-
2343
- index = 0;
2344
-
2345
- } else if ( time > track.times[ track.times.length - 1 ] ) {
2346
-
2347
- if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
2348
-
2349
- return track.times.length - 1;
2350
-
2351
- }
2352
-
2353
- times[ times.length - 1 ] = time;
2354
- times.set( track.times, 0 );
2355
-
2356
- values.set( track.values, 0 );
2357
- values.set( interpolant.evaluate( time ), track.values.length );
2358
-
2359
- index = times.length - 1;
2360
-
2361
- } else {
2362
-
2363
- for ( let i = 0; i < track.times.length; i ++ ) {
2364
-
2365
- if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
2366
-
2367
- if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
2368
-
2369
- times.set( track.times.slice( 0, i + 1 ), 0 );
2370
- times[ i + 1 ] = time;
2371
- times.set( track.times.slice( i + 1 ), i + 2 );
2372
-
2373
- values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
2374
- values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
2375
- values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
2376
-
2377
- index = i + 1;
2378
-
2379
- break;
2380
-
2381
- }
2382
-
2383
- }
2384
-
2385
- }
2386
-
2387
- track.times = times;
2388
- track.values = values;
2389
-
2390
- return index;
2391
-
2392
- },
2393
-
2394
- mergeMorphTargetTracks: function ( clip, root ) {
2395
-
2396
- const tracks = [];
2397
- const mergedTracks = {};
2398
- const sourceTracks = clip.tracks;
2399
-
2400
- for ( let i = 0; i < sourceTracks.length; ++ i ) {
2401
-
2402
- let sourceTrack = sourceTracks[ i ];
2403
- const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
2404
- const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
2405
-
2406
- if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
2407
-
2408
- // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
2409
- tracks.push( sourceTrack );
2410
- continue;
2411
-
2412
- }
2413
-
2414
- if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
2415
- && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
2416
-
2417
- if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
2418
-
2419
- // This should never happen, because glTF morph target animations
2420
- // affect all targets already.
2421
- throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
2422
-
2423
- }
2424
-
2425
- console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
2426
-
2427
- sourceTrack = sourceTrack.clone();
2428
- sourceTrack.setInterpolation( InterpolateLinear );
2429
-
2430
- }
2431
-
2432
- const targetCount = sourceTrackNode.morphTargetInfluences.length;
2433
- const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
2434
-
2435
- if ( targetIndex === undefined ) {
2436
-
2437
- throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
2438
-
2439
- }
2440
-
2441
- let mergedTrack;
2442
-
2443
- // If this is the first time we've seen this object, create a new
2444
- // track to store merged keyframe data for each morph target.
2445
- if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
2446
-
2447
- mergedTrack = sourceTrack.clone();
2448
-
2449
- const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
2450
-
2451
- for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
2452
-
2453
- values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
2454
-
2455
- }
2456
-
2457
- // We need to take into consideration the intended target node
2458
- // of our original un-merged morphTarget animation.
2459
- mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
2460
- mergedTrack.values = values;
2461
-
2462
- mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
2463
- tracks.push( mergedTrack );
2464
-
2465
- continue;
2466
-
2467
- }
2468
-
2469
- const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
2470
-
2471
- mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
2472
-
2473
- // For every existing keyframe of the merged track, write a (possibly
2474
- // interpolated) value from the source track.
2475
- for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
2476
-
2477
- mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
2478
-
2479
- }
2480
-
2481
- // For every existing keyframe of the source track, write a (possibly
2482
- // new) keyframe to the merged track. Values from the previous loop may
2483
- // be written again, but keyframes are de-duplicated.
2484
- for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
2485
-
2486
- const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
2487
- mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
2488
-
2489
- }
2490
-
2491
- }
2492
-
2493
- clip.tracks = tracks;
2494
-
2495
- return clip;
2496
-
2497
- }
2498
-
2499
- };
2500
-
2501
- export { GLTFExporter };