1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
|
# Copyright 2018 The glTF-Blender-IO authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Imports
#
from mathutils import Vector, Quaternion
from mathutils.geometry import tessellate_polygon
from operator import attrgetter
from . import gltf2_blender_export_keys
from ...io.com.gltf2_io_debug import print_console
from ...io.com.gltf2_io_color_management import color_srgb_to_scene_linear
from io_scene_gltf2.blender.exp import gltf2_blender_gather_skins
#
# Globals
#
INDICES_ID = 'indices'
MATERIAL_ID = 'material'
ATTRIBUTES_ID = 'attributes'
COLOR_PREFIX = 'COLOR_'
MORPH_TANGENT_PREFIX = 'MORPH_TANGENT_'
MORPH_NORMAL_PREFIX = 'MORPH_NORMAL_'
MORPH_POSITION_PREFIX = 'MORPH_POSITION_'
TEXCOORD_PREFIX = 'TEXCOORD_'
WEIGHTS_PREFIX = 'WEIGHTS_'
JOINTS_PREFIX = 'JOINTS_'
TANGENT_ATTRIBUTE = 'TANGENT'
NORMAL_ATTRIBUTE = 'NORMAL'
POSITION_ATTRIBUTE = 'POSITION'
GLTF_MAX_COLORS = 2
#
# Classes
#
class ShapeKey:
def __init__(self, shape_key, vertex_normals, polygon_normals):
self.shape_key = shape_key
self.vertex_normals = vertex_normals
self.polygon_normals = polygon_normals
#
# Functions
#
def convert_swizzle_location(loc, export_settings):
"""Convert a location from Blender coordinate system to glTF coordinate system."""
if export_settings[gltf2_blender_export_keys.YUP]:
return Vector((loc[0], loc[2], -loc[1]))
else:
return Vector((loc[0], loc[1], loc[2]))
def convert_swizzle_tangent(tan, export_settings):
"""Convert a tangent from Blender coordinate system to glTF coordinate system."""
if tan[0] == 0.0 and tan[1] == 0.0 and tan[2] == 0.0:
print_console('WARNING', 'Tangent has zero length.')
if export_settings[gltf2_blender_export_keys.YUP]:
return Vector((tan[0], tan[2], -tan[1], 1.0))
else:
return Vector((tan[0], tan[1], tan[2], 1.0))
def convert_swizzle_rotation(rot, export_settings):
"""
Convert a quaternion rotation from Blender coordinate system to glTF coordinate system.
'w' is still at first position.
"""
if export_settings[gltf2_blender_export_keys.YUP]:
return Quaternion((rot[0], rot[1], rot[3], -rot[2]))
else:
return Quaternion((rot[0], rot[1], rot[2], rot[3]))
def convert_swizzle_scale(scale, export_settings):
"""Convert a scale from Blender coordinate system to glTF coordinate system."""
if export_settings[gltf2_blender_export_keys.YUP]:
return Vector((scale[0], scale[2], scale[1]))
else:
return Vector((scale[0], scale[1], scale[2]))
def decompose_transition(matrix, context, export_settings):
translation, rotation, scale = matrix.decompose()
"""Decompose a matrix depending if it is associated to a joint or node."""
if context == 'NODE':
translation = convert_swizzle_location(translation, export_settings)
rotation = convert_swizzle_rotation(rotation, export_settings)
scale = convert_swizzle_scale(scale, export_settings)
# Put w at the end.
rotation = Quaternion((rotation[1], rotation[2], rotation[3], rotation[0]))
return translation, rotation, scale
def extract_primitive_floor(a, indices, use_tangents):
"""Shift indices, that the first one starts with 0. It is assumed, that the indices are packed."""
attributes = {
POSITION_ATTRIBUTE: [],
NORMAL_ATTRIBUTE: []
}
if use_tangents:
attributes[TANGENT_ATTRIBUTE] = []
result_primitive = {
MATERIAL_ID: a[MATERIAL_ID],
INDICES_ID: [],
ATTRIBUTES_ID: attributes
}
source_attributes = a[ATTRIBUTES_ID]
#
tex_coord_index = 0
process_tex_coord = True
while process_tex_coord:
tex_coord_id = TEXCOORD_PREFIX + str(tex_coord_index)
if source_attributes.get(tex_coord_id) is not None:
attributes[tex_coord_id] = []
tex_coord_index += 1
else:
process_tex_coord = False
tex_coord_max = tex_coord_index
#
color_index = 0
process_color = True
while process_color:
color_id = COLOR_PREFIX + str(color_index)
if source_attributes.get(color_id) is not None:
attributes[color_id] = []
color_index += 1
else:
process_color = False
color_max = color_index
#
bone_index = 0
process_bone = True
while process_bone:
joint_id = JOINTS_PREFIX + str(bone_index)
weight_id = WEIGHTS_PREFIX + str(bone_index)
if source_attributes.get(joint_id) is not None:
attributes[joint_id] = []
attributes[weight_id] = []
bone_index += 1
else:
process_bone = False
bone_max = bone_index
#
morph_index = 0
process_morph = True
while process_morph:
morph_position_id = MORPH_POSITION_PREFIX + str(morph_index)
morph_normal_id = MORPH_NORMAL_PREFIX + str(morph_index)
morph_tangent_id = MORPH_TANGENT_PREFIX + str(morph_index)
if source_attributes.get(morph_position_id) is not None:
attributes[morph_position_id] = []
attributes[morph_normal_id] = []
if use_tangents:
attributes[morph_tangent_id] = []
morph_index += 1
else:
process_morph = False
morph_max = morph_index
#
min_index = min(indices)
max_index = max(indices)
for old_index in indices:
result_primitive[INDICES_ID].append(old_index - min_index)
for old_index in range(min_index, max_index + 1):
for vi in range(0, 3):
attributes[POSITION_ATTRIBUTE].append(source_attributes[POSITION_ATTRIBUTE][old_index * 3 + vi])
attributes[NORMAL_ATTRIBUTE].append(source_attributes[NORMAL_ATTRIBUTE][old_index * 3 + vi])
if use_tangents:
for vi in range(0, 4):
attributes[TANGENT_ATTRIBUTE].append(source_attributes[TANGENT_ATTRIBUTE][old_index * 4 + vi])
for tex_coord_index in range(0, tex_coord_max):
tex_coord_id = TEXCOORD_PREFIX + str(tex_coord_index)
for vi in range(0, 2):
attributes[tex_coord_id].append(source_attributes[tex_coord_id][old_index * 2 + vi])
for color_index in range(0, color_max):
color_id = COLOR_PREFIX + str(color_index)
for vi in range(0, 4):
attributes[color_id].append(source_attributes[color_id][old_index * 4 + vi])
for bone_index in range(0, bone_max):
joint_id = JOINTS_PREFIX + str(bone_index)
weight_id = WEIGHTS_PREFIX + str(bone_index)
for vi in range(0, 4):
attributes[joint_id].append(source_attributes[joint_id][old_index * 4 + vi])
attributes[weight_id].append(source_attributes[weight_id][old_index * 4 + vi])
for morph_index in range(0, morph_max):
morph_position_id = MORPH_POSITION_PREFIX + str(morph_index)
morph_normal_id = MORPH_NORMAL_PREFIX + str(morph_index)
morph_tangent_id = MORPH_TANGENT_PREFIX + str(morph_index)
for vi in range(0, 3):
attributes[morph_position_id].append(source_attributes[morph_position_id][old_index * 3 + vi])
attributes[morph_normal_id].append(source_attributes[morph_normal_id][old_index * 3 + vi])
if use_tangents:
for vi in range(0, 4):
attributes[morph_tangent_id].append(source_attributes[morph_tangent_id][old_index * 4 + vi])
return result_primitive
def extract_primitive_pack(a, indices, use_tangents):
"""Pack indices, that the first one starts with 0. Current indices can have gaps."""
attributes = {
POSITION_ATTRIBUTE: [],
NORMAL_ATTRIBUTE: []
}
if use_tangents:
attributes[TANGENT_ATTRIBUTE] = []
result_primitive = {
MATERIAL_ID: a[MATERIAL_ID],
INDICES_ID: [],
ATTRIBUTES_ID: attributes
}
source_attributes = a[ATTRIBUTES_ID]
#
tex_coord_index = 0
process_tex_coord = True
while process_tex_coord:
tex_coord_id = TEXCOORD_PREFIX + str(tex_coord_index)
if source_attributes.get(tex_coord_id) is not None:
attributes[tex_coord_id] = []
tex_coord_index += 1
else:
process_tex_coord = False
tex_coord_max = tex_coord_index
#
color_index = 0
process_color = True
while process_color:
color_id = COLOR_PREFIX + str(color_index)
if source_attributes.get(color_id) is not None:
attributes[color_id] = []
color_index += 1
else:
process_color = False
color_max = color_index
#
bone_index = 0
process_bone = True
while process_bone:
joint_id = JOINTS_PREFIX + str(bone_index)
weight_id = WEIGHTS_PREFIX + str(bone_index)
if source_attributes.get(joint_id) is not None:
attributes[joint_id] = []
attributes[weight_id] = []
bone_index += 1
else:
process_bone = False
bone_max = bone_index
#
morph_index = 0
process_morph = True
while process_morph:
morph_position_id = MORPH_POSITION_PREFIX + str(morph_index)
morph_normal_id = MORPH_NORMAL_PREFIX + str(morph_index)
morph_tangent_id = MORPH_TANGENT_PREFIX + str(morph_index)
if source_attributes.get(morph_position_id) is not None:
attributes[morph_position_id] = []
attributes[morph_normal_id] = []
if use_tangents:
attributes[morph_tangent_id] = []
morph_index += 1
else:
process_morph = False
morph_max = morph_index
#
old_to_new_indices = {}
new_to_old_indices = {}
new_index = 0
for old_index in indices:
if old_to_new_indices.get(old_index) is None:
old_to_new_indices[old_index] = new_index
new_to_old_indices[new_index] = old_index
new_index += 1
result_primitive[INDICES_ID].append(old_to_new_indices[old_index])
end_new_index = new_index
for new_index in range(0, end_new_index):
old_index = new_to_old_indices[new_index]
for vi in range(0, 3):
attributes[POSITION_ATTRIBUTE].append(source_attributes[POSITION_ATTRIBUTE][old_index * 3 + vi])
attributes[NORMAL_ATTRIBUTE].append(source_attributes[NORMAL_ATTRIBUTE][old_index * 3 + vi])
if use_tangents:
for vi in range(0, 4):
attributes[TANGENT_ATTRIBUTE].append(source_attributes[TANGENT_ATTRIBUTE][old_index * 4 + vi])
for tex_coord_index in range(0, tex_coord_max):
tex_coord_id = TEXCOORD_PREFIX + str(tex_coord_index)
for vi in range(0, 2):
attributes[tex_coord_id].append(source_attributes[tex_coord_id][old_index * 2 + vi])
for color_index in range(0, color_max):
color_id = COLOR_PREFIX + str(color_index)
for vi in range(0, 4):
attributes[color_id].append(source_attributes[color_id][old_index * 4 + vi])
for bone_index in range(0, bone_max):
joint_id = JOINTS_PREFIX + str(bone_index)
weight_id = WEIGHTS_PREFIX + str(bone_index)
for vi in range(0, 4):
attributes[joint_id].append(source_attributes[joint_id][old_index * 4 + vi])
attributes[weight_id].append(source_attributes[weight_id][old_index * 4 + vi])
for morph_index in range(0, morph_max):
morph_position_id = MORPH_POSITION_PREFIX + str(morph_index)
morph_normal_id = MORPH_NORMAL_PREFIX + str(morph_index)
morph_tangent_id = MORPH_TANGENT_PREFIX + str(morph_index)
for vi in range(0, 3):
attributes[morph_position_id].append(source_attributes[morph_position_id][old_index * 3 + vi])
attributes[morph_normal_id].append(source_attributes[morph_normal_id][old_index * 3 + vi])
if use_tangents:
for vi in range(0, 4):
attributes[morph_tangent_id].append(source_attributes[morph_tangent_id][old_index * 4 + vi])
return result_primitive
def extract_primitives(glTF, blender_mesh, blender_vertex_groups, modifiers, export_settings):
"""
Extract primitives from a mesh. Polygons are triangulated and sorted by material.
Furthermore, primitives are split up, if the indices range is exceeded.
Finally, triangles are also split up/duplicated, if face normals are used instead of vertex normals.
"""
print_console('INFO', 'Extracting primitive: ' + blender_mesh.name)
use_tangents = False
if blender_mesh.uv_layers.active and len(blender_mesh.uv_layers) > 0:
try:
blender_mesh.calc_tangents()
use_tangents = True
except Exception:
print_console('WARNING', 'Could not calculate tangents. Please try to triangulate the mesh first.')
#
material_map = {}
#
# Gathering position, normal and tex_coords.
#
no_material_attributes = {
POSITION_ATTRIBUTE: [],
NORMAL_ATTRIBUTE: []
}
if use_tangents:
no_material_attributes[TANGENT_ATTRIBUTE] = []
#
# Directory of materials with its primitive.
#
no_material_primitives = {
MATERIAL_ID: '',
INDICES_ID: [],
ATTRIBUTES_ID: no_material_attributes
}
material_name_to_primitives = {'': no_material_primitives}
#
vertex_index_to_new_indices = {}
material_map[''] = vertex_index_to_new_indices
#
# Create primitive for each material.
#
for blender_material in blender_mesh.materials:
if blender_material is None:
continue
attributes = {
POSITION_ATTRIBUTE: [],
NORMAL_ATTRIBUTE: []
}
if use_tangents:
attributes[TANGENT_ATTRIBUTE] = []
primitive = {
MATERIAL_ID: blender_material.name,
INDICES_ID: [],
ATTRIBUTES_ID: attributes
}
material_name_to_primitives[blender_material.name] = primitive
#
vertex_index_to_new_indices = {}
material_map[blender_material.name] = vertex_index_to_new_indices
tex_coord_max = 0
if blender_mesh.uv_layers.active:
tex_coord_max = len(blender_mesh.uv_layers)
#
vertex_colors = {}
color_index = 0
for vertex_color in blender_mesh.vertex_colors:
vertex_color_name = COLOR_PREFIX + str(color_index)
vertex_colors[vertex_color_name] = vertex_color
color_index += 1
if color_index >= GLTF_MAX_COLORS:
break
color_max = color_index
#
bone_max = 0
for blender_polygon in blender_mesh.polygons:
for loop_index in blender_polygon.loop_indices:
vertex_index = blender_mesh.loops[loop_index].vertex_index
bones_count = len(blender_mesh.vertices[vertex_index].groups)
if bones_count > 0:
if bones_count % 4 == 0:
bones_count -= 1
bone_max = max(bone_max, bones_count // 4 + 1)
#
morph_max = 0
blender_shape_keys = []
if blender_mesh.shape_keys is not None:
morph_max = len(blender_mesh.shape_keys.key_blocks) - 1
for blender_shape_key in blender_mesh.shape_keys.key_blocks:
if blender_shape_key != blender_shape_key.relative_key:
blender_shape_keys.append(ShapeKey(
blender_shape_key,
blender_shape_key.normals_vertex_get(), # calculate vertex normals for this shape key
blender_shape_key.normals_polygon_get())) # calculate polygon normals for this shape key
#
# Convert polygon to primitive indices and eliminate invalid ones. Assign to material.
#
for blender_polygon in blender_mesh.polygons:
export_color = True
#
if blender_polygon.material_index < 0 or blender_polygon.material_index >= len(blender_mesh.materials) or \
blender_mesh.materials[blender_polygon.material_index] is None:
primitive = material_name_to_primitives['']
vertex_index_to_new_indices = material_map['']
else:
primitive = material_name_to_primitives[blender_mesh.materials[blender_polygon.material_index].name]
vertex_index_to_new_indices = material_map[blender_mesh.materials[blender_polygon.material_index].name]
#
attributes = primitive[ATTRIBUTES_ID]
face_normal = blender_polygon.normal
face_tangent = Vector((0.0, 0.0, 0.0))
face_bitangent = Vector((0.0, 0.0, 0.0))
if use_tangents:
for loop_index in blender_polygon.loop_indices:
temp_vertex = blender_mesh.loops[loop_index]
face_tangent += temp_vertex.tangent
face_bitangent += temp_vertex.bitangent
face_tangent.normalize()
face_bitangent.normalize()
#
indices = primitive[INDICES_ID]
loop_index_list = []
if len(blender_polygon.loop_indices) == 3:
loop_index_list.extend(blender_polygon.loop_indices)
elif len(blender_polygon.loop_indices) > 3:
# Triangulation of polygon. Using internal function, as non-convex polygons could exist.
polyline = []
for loop_index in blender_polygon.loop_indices:
vertex_index = blender_mesh.loops[loop_index].vertex_index
v = blender_mesh.vertices[vertex_index].co
polyline.append(Vector((v[0], v[1], v[2])))
triangles = tessellate_polygon((polyline,))
for triangle in triangles:
loop_index_list.append(blender_polygon.loop_indices[triangle[0]])
loop_index_list.append(blender_polygon.loop_indices[triangle[2]])
loop_index_list.append(blender_polygon.loop_indices[triangle[1]])
else:
continue
for loop_index in loop_index_list:
vertex_index = blender_mesh.loops[loop_index].vertex_index
if vertex_index_to_new_indices.get(vertex_index) is None:
vertex_index_to_new_indices[vertex_index] = []
#
v = None
n = None
t = None
b = None
uvs = []
colors = []
joints = []
weights = []
target_positions = []
target_normals = []
target_tangents = []
vertex = blender_mesh.vertices[vertex_index]
v = convert_swizzle_location(vertex.co, export_settings)
if blender_polygon.use_smooth:
n = convert_swizzle_location(vertex.normal, export_settings)
if use_tangents:
t = convert_swizzle_tangent(blender_mesh.loops[loop_index].tangent, export_settings)
b = convert_swizzle_location(blender_mesh.loops[loop_index].bitangent, export_settings)
else:
n = convert_swizzle_location(face_normal, export_settings)
if use_tangents:
t = convert_swizzle_tangent(face_tangent, export_settings)
b = convert_swizzle_location(face_bitangent, export_settings)
if use_tangents:
tv = Vector((t[0], t[1], t[2]))
bv = Vector((b[0], b[1], b[2]))
nv = Vector((n[0], n[1], n[2]))
if (nv.cross(tv)).dot(bv) < 0.0:
t[3] = -1.0
if blender_mesh.uv_layers.active:
for tex_coord_index in range(0, tex_coord_max):
uv = blender_mesh.uv_layers[tex_coord_index].data[loop_index].uv
uvs.append([uv.x, 1.0 - uv.y])
#
if color_max > 0 and export_color:
for color_index in range(0, color_max):
color_name = COLOR_PREFIX + str(color_index)
color = vertex_colors[color_name].data[loop_index].color
colors.append([
color_srgb_to_scene_linear(color[0]),
color_srgb_to_scene_linear(color[1]),
color_srgb_to_scene_linear(color[2]),
1.0
])
#
bone_count = 0
if blender_vertex_groups is not None and vertex.groups is not None and len(vertex.groups) > 0 and export_settings[gltf2_blender_export_keys.SKINS]:
joint = []
weight = []
vertex_groups = vertex.groups
if not export_settings['gltf_all_vertex_influences']:
# sort groups by weight descending
vertex_groups = sorted(vertex.groups, key=attrgetter('weight'), reverse=True)
for group_element in vertex_groups:
if len(joint) == 4:
bone_count += 1
joints.append(joint)
weights.append(weight)
joint = []
weight = []
#
joint_weight = group_element.weight
if joint_weight <= 0.0:
continue
#
vertex_group_index = group_element.group
vertex_group_name = blender_vertex_groups[vertex_group_index].name
joint_index = None
if modifiers is not None:
modifiers_dict = {m.type: m for m in modifiers}
if "ARMATURE" in modifiers_dict:
armature = modifiers_dict["ARMATURE"].object
skin = gltf2_blender_gather_skins.gather_skin(armature, export_settings)
for index, j in enumerate(skin.joints):
if j.name == vertex_group_name:
joint_index = index
break
#
if joint_index is not None:
joint.append(joint_index)
weight.append(joint_weight)
if len(joint) > 0:
bone_count += 1
for fill in range(0, 4 - len(joint)):
joint.append(0)
weight.append(0.0)
joints.append(joint)
weights.append(weight)
for fill in range(0, bone_max - bone_count):
joints.append([0, 0, 0, 0])
weights.append([0.0, 0.0, 0.0, 0.0])
#
if morph_max > 0 and export_settings[gltf2_blender_export_keys.MORPH]:
for morph_index in range(0, morph_max):
blender_shape_key = blender_shape_keys[morph_index]
v_morph = convert_swizzle_location(blender_shape_key.shape_key.data[vertex_index].co,
export_settings)
# Store delta.
v_morph -= v
target_positions.append(v_morph)
#
n_morph = None
if blender_polygon.use_smooth:
temp_normals = blender_shape_key.vertex_normals
n_morph = (temp_normals[vertex_index * 3 + 0], temp_normals[vertex_index * 3 + 1],
temp_normals[vertex_index * 3 + 2])
else:
temp_normals = blender_shape_key.polygon_normals
n_morph = (
temp_normals[blender_polygon.index * 3 + 0], temp_normals[blender_polygon.index * 3 + 1],
temp_normals[blender_polygon.index * 3 + 2])
n_morph = convert_swizzle_location(n_morph, export_settings)
# Store delta.
n_morph -= n
target_normals.append(n_morph)
#
if use_tangents:
rotation = n_morph.rotation_difference(n)
t_morph = Vector((t[0], t[1], t[2]))
t_morph.rotate(rotation)
target_tangents.append(t_morph)
#
#
create = True
for current_new_index in vertex_index_to_new_indices[vertex_index]:
found = True
for i in range(0, 3):
if attributes[POSITION_ATTRIBUTE][current_new_index * 3 + i] != v[i]:
found = False
break
if attributes[NORMAL_ATTRIBUTE][current_new_index * 3 + i] != n[i]:
found = False
break
if use_tangents:
for i in range(0, 4):
if attributes[TANGENT_ATTRIBUTE][current_new_index * 4 + i] != t[i]:
found = False
break
if not found:
continue
for tex_coord_index in range(0, tex_coord_max):
uv = uvs[tex_coord_index]
tex_coord_id = TEXCOORD_PREFIX + str(tex_coord_index)
for i in range(0, 2):
if attributes[tex_coord_id][current_new_index * 2 + i] != uv[i]:
found = False
break
if export_color:
for color_index in range(0, color_max):
color = colors[color_index]
color_id = COLOR_PREFIX + str(color_index)
for i in range(0, 3):
# Alpha is always 1.0 - see above.
current_color = attributes[color_id][current_new_index * 4 + i]
if color_srgb_to_scene_linear(current_color) != color[i]:
found = False
break
if export_settings[gltf2_blender_export_keys.SKINS]:
for bone_index in range(0, bone_max):
joint = joints[bone_index]
weight = weights[bone_index]
joint_id = JOINTS_PREFIX + str(bone_index)
weight_id = WEIGHTS_PREFIX + str(bone_index)
for i in range(0, 4):
if attributes[joint_id][current_new_index * 4 + i] != joint[i]:
found = False
break
if attributes[weight_id][current_new_index * 4 + i] != weight[i]:
found = False
break
if export_settings[gltf2_blender_export_keys.MORPH]:
for morph_index in range(0, morph_max):
target_position = target_positions[morph_index]
target_normal = target_normals[morph_index]
if use_tangents:
target_tangent = target_tangents[morph_index]
target_position_id = MORPH_POSITION_PREFIX + str(morph_index)
target_normal_id = MORPH_NORMAL_PREFIX + str(morph_index)
target_tangent_id = MORPH_TANGENT_PREFIX + str(morph_index)
for i in range(0, 3):
if attributes[target_position_id][current_new_index * 3 + i] != target_position[i]:
found = False
break
if attributes[target_normal_id][current_new_index * 3 + i] != target_normal[i]:
found = False
break
if use_tangents:
if attributes[target_tangent_id][current_new_index * 3 + i] != target_tangent[i]:
found = False
break
if found:
indices.append(current_new_index)
create = False
break
if not create:
continue
new_index = 0
if primitive.get('max_index') is not None:
new_index = primitive['max_index'] + 1
primitive['max_index'] = new_index
vertex_index_to_new_indices[vertex_index].append(new_index)
#
#
indices.append(new_index)
#
attributes[POSITION_ATTRIBUTE].extend(v)
attributes[NORMAL_ATTRIBUTE].extend(n)
if use_tangents:
attributes[TANGENT_ATTRIBUTE].extend(t)
if blender_mesh.uv_layers.active:
for tex_coord_index in range(0, tex_coord_max):
tex_coord_id = TEXCOORD_PREFIX + str(tex_coord_index)
if attributes.get(tex_coord_id) is None:
attributes[tex_coord_id] = []
attributes[tex_coord_id].extend(uvs[tex_coord_index])
if export_color:
for color_index in range(0, color_max):
color_id = COLOR_PREFIX + str(color_index)
if attributes.get(color_id) is None:
attributes[color_id] = []
attributes[color_id].extend(colors[color_index])
if export_settings[gltf2_blender_export_keys.SKINS]:
for bone_index in range(0, bone_max):
joint_id = JOINTS_PREFIX + str(bone_index)
if attributes.get(joint_id) is None:
attributes[joint_id] = []
attributes[joint_id].extend(joints[bone_index])
weight_id = WEIGHTS_PREFIX + str(bone_index)
if attributes.get(weight_id) is None:
attributes[weight_id] = []
attributes[weight_id].extend(weights[bone_index])
if export_settings[gltf2_blender_export_keys.MORPH]:
for morph_index in range(0, morph_max):
target_position_id = MORPH_POSITION_PREFIX + str(morph_index)
if attributes.get(target_position_id) is None:
attributes[target_position_id] = []
attributes[target_position_id].extend(target_positions[morph_index])
target_normal_id = MORPH_NORMAL_PREFIX + str(morph_index)
if attributes.get(target_normal_id) is None:
attributes[target_normal_id] = []
attributes[target_normal_id].extend(target_normals[morph_index])
if use_tangents:
target_tangent_id = MORPH_TANGENT_PREFIX + str(morph_index)
if attributes.get(target_tangent_id) is None:
attributes[target_tangent_id] = []
attributes[target_tangent_id].extend(target_tangents[morph_index])
#
# Add primitive plus split them if needed.
#
result_primitives = []
for material_name, primitive in material_name_to_primitives.items():
export_color = True
#
indices = primitive[INDICES_ID]
if len(indices) == 0:
continue
position = primitive[ATTRIBUTES_ID][POSITION_ATTRIBUTE]
normal = primitive[ATTRIBUTES_ID][NORMAL_ATTRIBUTE]
if use_tangents:
tangent = primitive[ATTRIBUTES_ID][TANGENT_ATTRIBUTE]
tex_coords = []
for tex_coord_index in range(0, tex_coord_max):
tex_coords.append(primitive[ATTRIBUTES_ID][TEXCOORD_PREFIX + str(tex_coord_index)])
colors = []
if export_color:
for color_index in range(0, color_max):
tex_coords.append(primitive[ATTRIBUTES_ID][COLOR_PREFIX + str(color_index)])
joints = []
weights = []
if export_settings[gltf2_blender_export_keys.SKINS]:
for bone_index in range(0, bone_max):
joints.append(primitive[ATTRIBUTES_ID][JOINTS_PREFIX + str(bone_index)])
weights.append(primitive[ATTRIBUTES_ID][WEIGHTS_PREFIX + str(bone_index)])
target_positions = []
target_normals = []
target_tangents = []
if export_settings[gltf2_blender_export_keys.MORPH]:
for morph_index in range(0, morph_max):
target_positions.append(primitive[ATTRIBUTES_ID][MORPH_POSITION_PREFIX + str(morph_index)])
target_normals.append(primitive[ATTRIBUTES_ID][MORPH_NORMAL_PREFIX + str(morph_index)])
if use_tangents:
target_tangents.append(primitive[ATTRIBUTES_ID][MORPH_TANGENT_PREFIX + str(morph_index)])
#
count = len(indices)
if count == 0:
continue
max_index = max(indices)
#
# NOTE: Values used by some graphics APIs as "primitive restart" values are disallowed.
# Specifically, the value 65535 (in UINT16) cannot be used as a vertex index.
# https://github.com/KhronosGroup/glTF/issues/1142
# https://github.com/KhronosGroup/glTF/pull/1476/files
range_indices = 65535
#
if max_index >= range_indices:
#
# Splitting result_primitives.
#
# At start, all indices are pending.
pending_attributes = {
POSITION_ATTRIBUTE: [],
NORMAL_ATTRIBUTE: []
}
if use_tangents:
pending_attributes[TANGENT_ATTRIBUTE] = []
pending_primitive = {
MATERIAL_ID: material_name,
INDICES_ID: [],
ATTRIBUTES_ID: pending_attributes
}
pending_primitive[INDICES_ID].extend(indices)
pending_attributes[POSITION_ATTRIBUTE].extend(position)
pending_attributes[NORMAL_ATTRIBUTE].extend(normal)
if use_tangents:
pending_attributes[TANGENT_ATTRIBUTE].extend(tangent)
tex_coord_index = 0
for tex_coord in tex_coords:
pending_attributes[TEXCOORD_PREFIX + str(tex_coord_index)] = tex_coord
tex_coord_index += 1
if export_color:
color_index = 0
for color in colors:
pending_attributes[COLOR_PREFIX + str(color_index)] = color
color_index += 1
if export_settings[gltf2_blender_export_keys.SKINS]:
joint_index = 0
for joint in joints:
pending_attributes[JOINTS_PREFIX + str(joint_index)] = joint
joint_index += 1
weight_index = 0
for weight in weights:
pending_attributes[WEIGHTS_PREFIX + str(weight_index)] = weight
weight_index += 1
if export_settings[gltf2_blender_export_keys.MORPH]:
morph_index = 0
for target_position in target_positions:
pending_attributes[MORPH_POSITION_PREFIX + str(morph_index)] = target_position
morph_index += 1
morph_index = 0
for target_normal in target_normals:
pending_attributes[MORPH_NORMAL_PREFIX + str(morph_index)] = target_normal
morph_index += 1
if use_tangents:
morph_index = 0
for target_tangent in target_tangents:
pending_attributes[MORPH_TANGENT_PREFIX + str(morph_index)] = target_tangent
morph_index += 1
pending_indices = pending_primitive[INDICES_ID]
# Continue until all are processed.
while len(pending_indices) > 0:
process_indices = pending_primitive[INDICES_ID]
max_index = max(process_indices)
pending_indices = []
#
#
all_local_indices = []
for i in range(0, (max_index // range_indices) + 1):
all_local_indices.append([])
#
#
# For all faces ...
for face_index in range(0, len(process_indices), 3):
written = False
face_min_index = min(process_indices[face_index + 0], process_indices[face_index + 1],
process_indices[face_index + 2])
face_max_index = max(process_indices[face_index + 0], process_indices[face_index + 1],
process_indices[face_index + 2])
# ... check if it can be but in a range of maximum indices.
for i in range(0, (max_index // range_indices) + 1):
offset = i * range_indices
# Yes, so store the primitive with its indices.
if face_min_index >= offset and face_max_index < offset + range_indices:
all_local_indices[i].extend(
[process_indices[face_index + 0], process_indices[face_index + 1],
process_indices[face_index + 2]])
written = True
break
# If not written, the triangle face has indices from different ranges.
if not written:
pending_indices.extend([process_indices[face_index + 0], process_indices[face_index + 1],
process_indices[face_index + 2]])
# Only add result_primitives, which do have indices in it.
for local_indices in all_local_indices:
if len(local_indices) > 0:
current_primitive = extract_primitive_floor(pending_primitive, local_indices, use_tangents)
result_primitives.append(current_primitive)
print_console('DEBUG', 'Adding primitive with splitting. Indices: ' + str(
len(current_primitive[INDICES_ID])) + ' Vertices: ' + str(
len(current_primitive[ATTRIBUTES_ID][POSITION_ATTRIBUTE]) // 3))
# Process primitive faces having indices in several ranges.
if len(pending_indices) > 0:
pending_primitive = extract_primitive_pack(pending_primitive, pending_indices, use_tangents)
print_console('DEBUG', 'Creating temporary primitive for splitting')
else:
#
# No splitting needed.
#
result_primitives.append(primitive)
print_console('DEBUG', 'Adding primitive without splitting. Indices: ' + str(
len(primitive[INDICES_ID])) + ' Vertices: ' + str(
len(primitive[ATTRIBUTES_ID][POSITION_ATTRIBUTE]) // 3))
print_console('INFO', 'Primitives created: ' + str(len(result_primitives)))
return result_primitives
|