-
Notifications
You must be signed in to change notification settings - Fork 316
/
exporter.py
3299 lines (2824 loc) · 136 KB
/
exporter.py
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
"""
Armory Scene Exporter
https://armory3d.org/
Based on Open Game Engine Exchange
https://opengex.org/
Export plugin for Blender by Eric Lengyel
Copyright 2015, Terathon Software LLC
This software is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License:
https://creativecommons.org/licenses/by-sa/3.0/deed.en_US
"""
from enum import Enum, unique
import math
import os
import time
from typing import Any, Dict, List, Tuple, Union, Optional
import numpy as np
import bpy
from mathutils import Matrix, Vector
import bmesh
import arm.utils
import arm.profiler
from arm import assets, exporter_opt, log, make_renderpath
from arm.material import cycles, make as make_material, mat_batch
if arm.is_reload(__name__):
assets = arm.reload_module(assets)
exporter_opt = arm.reload_module(exporter_opt)
log = arm.reload_module(log)
make_renderpath = arm.reload_module(make_renderpath)
cycles = arm.reload_module(cycles)
make_material = arm.reload_module(make_material)
mat_batch = arm.reload_module(mat_batch)
arm.utils = arm.reload_module(arm.utils)
arm.profiler = arm.reload_module(arm.profiler)
else:
arm.enable_reload(__name__)
@unique
class NodeType(Enum):
"""Represents the type of an object."""
EMPTY = 0
BONE = 1
MESH = 2
LIGHT = 3
CAMERA = 4
SPEAKER = 5
DECAL = 6
PROBE = 7
@classmethod
def get_bobject_type(cls, bobject: bpy.types.Object) -> "NodeType":
"""Returns the NodeType enum member belonging to the type of
the given blender object."""
if bobject.type == "MESH":
if bobject.data.polygons:
return cls.MESH
elif bobject.type in ('FONT', 'META'):
return cls.MESH
elif bobject.type == "LIGHT":
return cls.LIGHT
elif bobject.type == "CAMERA":
return cls.CAMERA
elif bobject.type == "SPEAKER":
return cls.SPEAKER
elif bobject.type == "LIGHT_PROBE":
return cls.PROBE
return cls.EMPTY
STRUCT_IDENTIFIER = ("object", "bone_object", "mesh_object",
"light_object", "camera_object", "speaker_object",
"decal_object", "probe_object")
# Internal target names for single FCurve data paths
FCURVE_TARGET_NAMES = {
"location": ("xloc", "yloc", "zloc"),
"rotation_euler": ("xrot", "yrot", "zrot"),
"rotation_quaternion": ("qwrot", "qxrot", "qyrot", "qzrot"),
"scale": ("xscl", "yscl", "zscl"),
"delta_location": ("dxloc", "dyloc", "dzloc"),
"delta_rotation_euler": ("dxrot", "dyrot", "dzrot"),
"delta_rotation_quaternion": ("dqwrot", "dqxrot", "dqyrot", "dqzrot"),
"delta_scale": ("dxscl", "dyscl", "dzscl"),
}
current_output = None
class ArmoryExporter:
"""Export to Armory format.
Some common naming patterns:
- out_[]: Variables starting with "out_" represent data that is
exported to Iron
- bobject: A Blender object (bpy.types.Object). Used because
`object` is a reserved Python keyword
"""
compress_enabled = False
export_all_flag = True
# Indicates whether rigid body is exported
export_physics = False
optimize_enabled = False
option_mesh_only = False
# Class names of referenced traits
import_traits: List[str] = []
def __init__(self, context: bpy.types.Context, filepath: str, scene: bpy.types.Scene = None, depsgraph: bpy.types.Depsgraph = None):
global current_output
self.filepath = filepath
self.scene = context.scene if scene is None else scene
self.depsgraph = context.evaluated_depsgraph_get() if depsgraph is None else depsgraph
# The output dict contains all data that is later exported to Iron format
self.output: Dict[str, Any] = {'frame_time': 1.0 / (self.scene.render.fps / self.scene.render.fps_base)}
current_output = self.output
# Stores the object type ("objectType") and the asset name
# ("structName") in a dict for each object
self.bobject_array: Dict[bpy.types.Object, Dict[str, Union[NodeType, str]]] = {}
self.bobject_bone_array = {}
self.mesh_array = {}
self.light_array = {}
self.probe_array = {}
self.camera_array = {}
self.speaker_array = {}
self.material_array = []
self.world_array = []
self.particle_system_array = {}
self.referenced_collections: list[bpy.types.Collection] = []
"""Collections referenced by collection instances"""
self.has_spawning_camera = False
"""Whether there is at least one camera in the scene that spawns by default"""
self.material_to_object_dict = {}
# If no material is assigned, provide default to mimic cycles
self.default_material_objects = []
self.default_skin_material_objects = []
self.default_part_material_objects = []
self.material_to_arm_object_dict = {}
# Stores the link between a blender object and its
# corresponding export data (arm object)
self.object_to_arm_object_dict: Dict[bpy.types.Object, Dict] = {}
self.bone_tracks = []
ArmoryExporter.preprocess()
@classmethod
def export_scene(cls, context: bpy.types.Context, filepath: str, scene: bpy.types.Scene = None, depsgraph: bpy.types.Depsgraph = None) -> None:
"""Exports the given scene to the given file path. This is the
function that is called in make.py and the entry point of the
exporter."""
with arm.profiler.Profile('profile_exporter.prof', arm.utils.get_pref_or_default('profile_exporter', False)):
cls(context, filepath, scene, depsgraph).execute()
@classmethod
def preprocess(cls):
wrd = bpy.data.worlds['Arm']
if wrd.arm_physics == 'Enabled':
cls.export_physics = True
cls.export_navigation = False
if wrd.arm_navigation == 'Enabled':
cls.export_navigation = True
cls.export_ui = False
cls.export_network = False
if wrd.arm_network == 'Enabled':
cls.export_network = True
@staticmethod
def write_matrix(matrix):
return [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],
matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]]
def get_meshes_file_path(self, object_id: str, compressed=False) -> str:
index = self.filepath.rfind('/')
mesh_fp = self.filepath[:(index + 1)] + 'meshes/'
if not os.path.exists(mesh_fp):
os.makedirs(mesh_fp)
ext = '.lz4' if compressed else '.arm'
return mesh_fp + object_id + ext
@staticmethod
def get_shape_keys(mesh):
rpdat = arm.utils.get_rp()
if rpdat.arm_morph_target != 'On':
return False
# Metaball
if not hasattr(mesh, 'shape_keys'):
return False
shape_keys = mesh.shape_keys
if not shape_keys:
return False
if len(shape_keys.key_blocks) < 2:
return False
for shape_key in shape_keys.key_blocks[1:]:
if not shape_key.mute:
return True
return False
@staticmethod
def get_morph_uv_index(mesh):
i = 0
for uv_layer in mesh.uv_layers:
if uv_layer.name == 'UVMap_shape_key':
return i
i +=1
def find_bone(self, name: str) -> Optional[Tuple[bpy.types.Bone, Dict]]:
"""Finds the bone reference (a tuple containing the bone object
and its data) by the given name and returns it."""
for bone_ref in self.bobject_bone_array.items():
if bone_ref[0].name == name:
return bone_ref
return None
@staticmethod
def collect_bone_animation(armature: bpy.types.Object, name: str) -> List[bpy.types.FCurve]:
path = f"pose.bones[\"{name}\"]."
if armature.animation_data:
action = armature.animation_data.action
if action:
return [fcurve for fcurve in action.fcurves if fcurve.data_path.startswith(path)]
return []
def export_bone(self, armature, bone: bpy.types.Bone, o, action: bpy.types.Action):
rpdat = arm.utils.get_rp()
bobject_ref = self.bobject_bone_array.get(bone)
if rpdat.arm_use_armature_deform_only:
if not bone.use_deform:
return
if bobject_ref:
o['type'] = STRUCT_IDENTIFIER[bobject_ref["objectType"].value]
o['name'] = bobject_ref["structName"]
self.export_bone_transform(armature, bone, o, action)
o['children'] = []
for sub_bobject in bone.children:
so = {}
self.export_bone(armature, sub_bobject, so, action)
o['children'].append(so)
@staticmethod
def export_pose_markers(oanim, action):
if action.pose_markers is None or len(action.pose_markers) == 0:
return
oanim['marker_frames'] = []
oanim['marker_names'] = []
for pos_marker in action.pose_markers:
oanim['marker_frames'].append(int(pos_marker.frame))
oanim['marker_names'].append(pos_marker.name)
@staticmethod
def calculate_anim_frame_range(action: bpy.types.Action) -> Tuple[int, int]:
"""Calculates the required frame range of the given action by
also taking fcurve modifiers into account.
Modifiers that are not range-restricted are ignored in this
calculation.
"""
start = action.frame_range[0]
end = action.frame_range[1]
# Take FCurve modifiers into account if they have a restricted
# frame range
for fcurve in action.fcurves:
for modifier in fcurve.modifiers:
if not modifier.use_restricted_range:
continue
if modifier.frame_start < start:
start = modifier.frame_start
if modifier.frame_end > end:
end = modifier.frame_end
return int(start), int(end)
@staticmethod
def export_animation_track(fcurve: bpy.types.FCurve, frame_range: Tuple[int, int], target: str) -> Dict:
"""This function exports a single animation track."""
out_track = {'target': target, 'frames': [], 'values': []}
start = frame_range[0]
end = frame_range[1]
for frame in range(start, end + 1):
out_track['frames'].append(frame)
out_track['values'].append(fcurve.evaluate(frame))
return out_track
def export_object_transform(self, bobject: bpy.types.Object, o):
wrd = bpy.data.worlds['Arm']
# Static transform
o['transform'] = {'values': ArmoryExporter.write_matrix(bobject.matrix_local)}
# Animated transform
if bobject.animation_data is not None and bobject.type != "ARMATURE":
action = bobject.animation_data.action
if action is not None:
action_name = arm.utils.safestr(arm.utils.asset_name(action))
fp = self.get_meshes_file_path('action_' + action_name, compressed=ArmoryExporter.compress_enabled)
assets.add(fp)
ext = '.lz4' if ArmoryExporter.compress_enabled else ''
if ext == '' and not wrd.arm_minimize:
ext = '.json'
if 'object_actions' not in o:
o['object_actions'] = []
o['object_actions'].append('action_' + action_name + ext)
frame_range = self.calculate_anim_frame_range(action)
out_anim = {
'begin': frame_range[0],
'end': frame_range[1],
'tracks': []
}
self.export_pose_markers(out_anim, action)
unresolved_data_paths = set()
for fcurve in action.fcurves:
data_path = fcurve.data_path
try:
out_track = self.export_animation_track(fcurve, frame_range, FCURVE_TARGET_NAMES[data_path][fcurve.array_index])
except KeyError:
if data_path not in FCURVE_TARGET_NAMES:
# This can happen if the target is simply not
# supported or the action shares both bone
# and object transform data (FCURVE_TARGET_NAMES
# only contains object transform targets)
unresolved_data_paths.add(data_path)
continue
# Missing target entry for array_index or something else
raise
if data_path.startswith('delta_'):
out_anim['has_delta'] = True
out_anim['tracks'].append(out_track)
if len(unresolved_data_paths) > 0:
warning = (
f'The action "{action_name}" has fcurve channels with data paths that could not be resolved.'
' This can be caused by the following things:\n'
' - The data paths are not supported.\n'
' - The action exists on both armature and non-armature objects or has both bone and object transform data.'
)
if wrd.arm_verbose_output:
warning += f'\n Unresolved data paths: {unresolved_data_paths}'
else:
warning += '\n To see the list of unresolved data paths please recompile with Armory Project > Verbose Output enabled.'
log.warn(warning)
if True: # not action.arm_cached or not os.path.exists(fp):
if wrd.arm_verbose_output:
print('Exporting object action ' + action_name)
out_object_action = {
'name': action_name,
'anim': out_anim,
'type': 'object',
'data_ref': '',
'transform': None
}
action_file = {'objects': [out_object_action]}
arm.utils.write_arm(fp, action_file)
def process_bone(self, bone: bpy.types.Bone) -> None:
if ArmoryExporter.export_all_flag or bone.select:
self.bobject_bone_array[bone] = {
"objectType": NodeType.BONE,
"structName": bone.name
}
for subbobject in bone.children:
self.process_bone(subbobject)
def process_bobject(self, bobject: bpy.types.Object) -> None:
"""Stores some basic information about the given object (its
name and type).
If the given object is an armature, its bones are also
processed.
"""
if ArmoryExporter.export_all_flag or bobject.select_get():
btype: NodeType = NodeType.get_bobject_type(bobject)
if btype is not NodeType.MESH and ArmoryExporter.option_mesh_only:
return
self.bobject_array[bobject] = {
"objectType": btype,
"structName": arm.utils.asset_name(bobject)
}
if bobject.type == "ARMATURE":
armature: bpy.types.Armature = bobject.data
if armature:
for bone in armature.bones:
if not bone.parent:
self.process_bone(bone)
if bobject.arm_instanced == 'Off':
for subbobject in bobject.children:
self.process_bobject(subbobject)
def process_skinned_meshes(self):
"""Iterates through all objects that are exported and ensures
that bones are actually stored as bones."""
for bobject_ref in self.bobject_array.items():
if bobject_ref[1]["objectType"] is NodeType.MESH:
armature = bobject_ref[0].find_armature()
if armature is not None:
for bone in armature.data.bones:
bone_ref = self.find_bone(bone.name)
if bone_ref is not None:
# If an object is used as a bone, then we
# force its type to be a bone
bone_ref[1]["objectType"] = NodeType.BONE
def export_bone_transform(self, armature: bpy.types.Object, bone: bpy.types.Bone, o, action: bpy.types.Action):
pose_bone = armature.pose.bones.get(bone.name)
# if pose_bone is not None:
# transform = pose_bone.matrix.copy()
# if pose_bone.parent is not None:
# transform = pose_bone.parent.matrix.inverted_safe() * transform
# else:
transform = bone.matrix_local.copy()
if bone.parent is not None:
transform = (bone.parent.matrix_local.inverted_safe() @ transform)
o['transform'] = {'values': ArmoryExporter.write_matrix(transform)}
fcurve_list = self.collect_bone_animation(armature, bone.name)
if fcurve_list and pose_bone:
begin_frame, end_frame = int(action.frame_range[0]), int(action.frame_range[1])
out_track = {'target': "transform", 'frames': [], 'values': []}
o['anim'] = {'tracks': [out_track]}
for i in range(begin_frame, end_frame + 1):
out_track['frames'].append(i - begin_frame)
self.bone_tracks.append((out_track['values'], pose_bone))
def use_default_material(self, bobject: bpy.types.Object, o):
if arm.utils.export_bone_data(bobject):
o['material_refs'].append('armdefaultskin')
self.default_skin_material_objects.append(bobject)
else:
o['material_refs'].append('armdefault')
self.default_material_objects.append(bobject)
def use_default_material_part(self):
"""Select the particle material variant for all particle system
instance objects that use the armdefault material.
"""
for ps in bpy.data.particles:
if ps.render_type != 'OBJECT' or ps.instance_object is None or not ps.instance_object.arm_export:
continue
po = ps.instance_object
if po not in self.object_to_arm_object_dict:
self.process_bobject(po)
self.export_object(po)
o = self.object_to_arm_object_dict[po]
# Check if the instance object uses the armdefault material
if len(o['material_refs']) > 0 and o['material_refs'][0] == 'armdefault' and po not in self.default_part_material_objects:
self.default_part_material_objects.append(po)
o['material_refs'] = ['armdefaultpart'] # Replace armdefault
def export_material_ref(self, bobject: bpy.types.Object, material, index, o):
if material is None: # Use default for empty mat slots
self.use_default_material(bobject, o)
return
if material not in self.material_array:
self.material_array.append(material)
o['material_refs'].append(arm.utils.asset_name(material))
def export_particle_system_ref(self, psys: bpy.types.ParticleSystem, out_object):
if psys.settings.instance_object is None or psys.settings.render_type != 'OBJECT' or not psys.settings.instance_object.arm_export:
return
self.particle_system_array[psys.settings] = {"structName": psys.settings.name}
pref = {
'name': psys.name,
'seed': psys.seed,
'particle': psys.settings.name
}
out_object['particle_refs'].append(pref)
@staticmethod
def get_view3d_area() -> Optional[bpy.types.Area]:
screen = bpy.context.window.screen
for area in screen.areas:
if area.type == 'VIEW_3D':
return area
return None
@staticmethod
def get_viewport_view_matrix() -> Optional[Matrix]:
play_area = ArmoryExporter.get_view3d_area()
if play_area is None:
return None
for space in play_area.spaces:
if space.type == 'VIEW_3D':
return space.region_3d.view_matrix
return None
@staticmethod
def get_viewport_projection_matrix() -> Tuple[Optional[Matrix], bool]:
play_area = ArmoryExporter.get_view3d_area()
if play_area is None:
return None, False
for space in play_area.spaces:
if space.type == 'VIEW_3D':
# return space.region_3d.perspective_matrix # pesp = window * view
return space.region_3d.window_matrix, space.region_3d.is_perspective
return None, False
def write_bone_matrices(self, scene, action):
# profile_time = time.time()
begin_frame, end_frame = int(action.frame_range[0]), int(action.frame_range[1])
if len(self.bone_tracks) > 0:
for i in range(begin_frame, end_frame + 1):
scene.frame_set(i)
for track in self.bone_tracks:
values, pose_bone = track[0], track[1]
parent = pose_bone.parent
if parent:
values += ArmoryExporter.write_matrix((parent.matrix.inverted_safe() @ pose_bone.matrix))
else:
values += ArmoryExporter.write_matrix(pose_bone.matrix)
# print('Bone matrices exported in ' + str(time.time() - profile_time))
@staticmethod
def has_baked_material(bobject, materials):
for mat in materials:
if mat is None:
continue
baked_mat = mat.name + '_' + bobject.name + '_baked'
if baked_mat in bpy.data.materials:
return True
return False
@staticmethod
def create_material_variants(scene: bpy.types.Scene) -> Tuple[List[bpy.types.Material], List[bpy.types.MaterialSlot]]:
"""Creates unique material variants for skinning, tilesheets and
particles."""
matvars: List[bpy.types.Material] = []
matslots: List[bpy.types.MaterialSlot] = []
bobject: bpy.types.Object
for bobject in scene.collection.all_objects.values():
variant_suffix = ''
# Skinning
if arm.utils.export_bone_data(bobject):
variant_suffix = '_armskin'
# Tilesheets
elif bobject.arm_tilesheet != '':
if not bobject.arm_use_custom_tilesheet_node:
variant_suffix = '_armtile'
elif arm.utils.export_morph_targets(bobject):
variant_suffix = '_armskey'
if variant_suffix == '':
continue
for slot in bobject.material_slots:
if slot.material is None or slot.material.library is not None:
continue
if slot.material.name.endswith(variant_suffix):
continue
matslots.append(slot)
mat_name = slot.material.name + variant_suffix
mat = bpy.data.materials.get(mat_name)
# Create material variant
if mat is None:
mat = slot.material.copy()
mat.name = mat_name
if variant_suffix == '_armtile':
mat.arm_tilesheet_flag = True
matvars.append(mat)
slot.material = mat
# Particle and non-particle objects can not share material
particle_sys: bpy.types.ParticleSettings
for particle_sys in bpy.data.particles:
bobject = particle_sys.instance_object
if bobject is None or particle_sys.render_type != 'OBJECT' or not bobject.arm_export:
continue
for slot in bobject.material_slots:
if slot.material is None or slot.material.library is not None:
continue
if slot.material.name.endswith('_armpart'):
continue
matslots.append(slot)
mat_name = slot.material.name + '_armpart'
mat = bpy.data.materials.get(mat_name)
if mat is None:
mat = slot.material.copy()
mat.name = mat_name
mat.arm_particle_flag = True
matvars.append(mat)
slot.material = mat
return matvars, matslots
@staticmethod
def slot_to_material(bobject: bpy.types.Object, slot: bpy.types.MaterialSlot):
mat = slot.material
# Pick up backed material if present
if mat is not None:
baked_mat = mat.name + '_' + bobject.name + '_baked'
if baked_mat in bpy.data.materials:
mat = bpy.data.materials[baked_mat]
return mat
# def ExportMorphWeights(self, node, shapeKeys, scene):
# action = None
# curveArray = []
# indexArray = []
# if (shapeKeys.animation_data):
# action = shapeKeys.animation_data.action
# if (action):
# for fcurve in action.fcurves:
# if ((fcurve.data_path.startswith("key_blocks[")) and (fcurve.data_path.endswith("].value"))):
# keyName = fcurve.data_path.strip("abcdehklopstuvy[]_.")
# if ((keyName[0] == "\"") or (keyName[0] == "'")):
# index = shapeKeys.key_blocks.find(keyName.strip("\"'"))
# if (index >= 0):
# curveArray.append(fcurve)
# indexArray.append(index)
# else:
# curveArray.append(fcurve)
# indexArray.append(int(keyName))
# if ((not action) and (node.animation_data)):
# action = node.animation_data.action
# if (action):
# for fcurve in action.fcurves:
# if ((fcurve.data_path.startswith("data.shape_keys.key_blocks[")) and (fcurve.data_path.endswith("].value"))):
# keyName = fcurve.data_path.strip("abcdehklopstuvy[]_.")
# if ((keyName[0] == "\"") or (keyName[0] == "'")):
# index = shapeKeys.key_blocks.find(keyName.strip("\"'"))
# if (index >= 0):
# curveArray.append(fcurve)
# indexArray.append(index)
# else:
# curveArray.append(fcurve)
# indexArray.append(int(keyName))
# animated = (len(curveArray) != 0)
# referenceName = shapeKeys.reference_key.name if (shapeKeys.use_relative) else ""
# for k in range(len(shapeKeys.key_blocks)):
# self.IndentWrite(B"MorphWeight", 0, (k == 0))
# if (animated):
# self.Write(B" %mw")
# self.WriteInt(k)
# self.Write(B" (index = ")
# self.WriteInt(k)
# self.Write(B") {float {")
# block = shapeKeys.key_blocks[k]
# self.WriteFloat(block.value if (block.name != referenceName) else 1.0)
# self.Write(B"}}\n")
# if (animated):
# self.IndentWrite(B"Animation (begin = ", 0, True)
# self.WriteFloat((action.frame_range[0]) * self.frameTime)
# self.Write(B", end = ")
# self.WriteFloat((action.frame_range[1]) * self.frameTime)
# self.Write(B")\n")
# self.IndentWrite(B"{\n")
# self.indentLevel += 1
# structFlag = False
# for a in range(len(curveArray)):
# k = indexArray[a]
# target = bytes("mw" + str(k), "UTF-8")
# fcurve = curveArray[a]
# kind = OpenGexExporter.ClassifyAnimationCurve(fcurve)
# if ((kind != kAnimationSampled) and (not self.sampleAnimationFlag)):
# self.ExportAnimationTrack(fcurve, kind, target, structFlag)
# else:
# self.ExportMorphWeightSampledAnimationTrack(shapeKeys.key_blocks[k], target, scene, structFlag)
# structFlag = True
# self.indentLevel -= 1
# self.IndentWrite(B"}\n")
def export_object(self, bobject: bpy.types.Object, out_parent: Dict = None) -> None:
"""This function exports a single object in the scene and
includes its name, object reference, material references (for
meshes), and transform.
Subobjects are then exported recursively.
"""
if not bobject.arm_export:
return
bobject_ref = self.bobject_array.get(bobject)
if bobject_ref is not None:
object_type = bobject_ref["objectType"]
# Linked object, not present in scene
if bobject not in self.object_to_arm_object_dict:
out_object = {
'traits': [],
'spawn': False
}
self.object_to_arm_object_dict[bobject] = out_object
out_object = self.object_to_arm_object_dict[bobject]
out_object['type'] = STRUCT_IDENTIFIER[object_type.value]
out_object['name'] = bobject_ref["structName"]
if bobject.parent_type == "BONE":
out_object['parent_bone'] = bobject.parent_bone
if bobject.hide_render or not bobject.arm_visible:
out_object['visible'] = False
if bpy.app.version < (3, 0, 0):
if not bobject.cycles_visibility:
out_object['visible_mesh'] = False
out_object['visible_shadow'] = False
else:
if not bobject.visible_camera:
out_object['visible_mesh'] = False
if not bobject.visible_shadow:
out_object['visible_shadow'] = False
if not bobject.arm_spawn:
out_object['spawn'] = False
out_object['mobile'] = bobject.arm_mobile
if bobject.instance_type == 'COLLECTION' and bobject.instance_collection is not None:
out_object['group_ref'] = bobject.instance_collection.name
self.referenced_collections.append(bobject.instance_collection)
if bobject.arm_tilesheet != '':
out_object['tilesheet_ref'] = bobject.arm_tilesheet
out_object['tilesheet_action_ref'] = bobject.arm_tilesheet_action
if len(bobject.arm_propertylist) > 0:
out_object['properties'] = []
for proplist_item in bobject.arm_propertylist:
# Check if the property is a collection (array type).
if proplist_item.type_prop == 'array':
# Convert the collection to a list.
array_type = proplist_item.array_item_type
collection_value = getattr(proplist_item, 'array_prop')
property_name = array_type + '_prop'
value = [str(getattr(item, property_name)) for item in collection_value]
else:
# Handle other types of properties.
value = getattr(proplist_item, proplist_item.type_prop + '_prop')
out_property = {
'name': proplist_item.name_prop,
'value': value
}
out_object['properties'].append(out_property)
# Export the object reference and material references
objref = bobject.data
if objref is not None:
objname = arm.utils.asset_name(objref)
# LOD
if bobject.type == 'MESH' and hasattr(objref, 'arm_lodlist') and len(objref.arm_lodlist) > 0:
out_object['lods'] = []
for lodlist_item in objref.arm_lodlist:
if not lodlist_item.enabled_prop:
continue
out_lod = {
'object_ref': lodlist_item.name,
'screen_size': lodlist_item.screen_size_prop
}
out_object['lods'].append(out_lod)
if objref.arm_lod_material:
out_object['lod_material'] = True
if object_type is NodeType.MESH:
if objref not in self.mesh_array:
self.mesh_array[objref] = {"structName": objname, "objectTable": [bobject]}
else:
self.mesh_array[objref]["objectTable"].append(bobject)
oid = arm.utils.safestr(self.mesh_array[objref]["structName"])
wrd = bpy.data.worlds['Arm']
if wrd.arm_single_data_file:
out_object['data_ref'] = oid
else:
ext = '' if not ArmoryExporter.compress_enabled else '.lz4'
if ext == '' and not bpy.data.worlds['Arm'].arm_minimize:
ext = '.json'
out_object['data_ref'] = 'mesh_' + oid + ext + '/' + oid
out_object['material_refs'] = []
for i in range(len(bobject.material_slots)):
mat = self.slot_to_material(bobject, bobject.material_slots[i])
# Export ref
self.export_material_ref(bobject, mat, i, out_object)
# Decal flag
if mat is not None and mat.arm_decal:
out_object['type'] = 'decal_object'
# No material, mimic cycles and assign default
if len(out_object['material_refs']) == 0:
self.use_default_material(bobject, out_object)
num_psys = len(bobject.particle_systems)
if num_psys > 0:
out_object['particle_refs'] = []
out_object['render_emitter'] = bobject.show_instancer_for_render
for i in range(num_psys):
self.export_particle_system_ref(bobject.particle_systems[i], out_object)
aabb = bobject.data.arm_aabb
if aabb[0] == 0 and aabb[1] == 0 and aabb[2] == 0:
self.calc_aabb(bobject)
out_object['dimensions'] = [aabb[0], aabb[1], aabb[2]]
# shapeKeys = ArmoryExporter.get_shape_keys(objref)
# if shapeKeys:
# self.ExportMorphWeights(bobject, shapeKeys, scene, out_object)
elif object_type is NodeType.LIGHT:
if objref not in self.light_array:
self.light_array[objref] = {"structName" : objname, "objectTable" : [bobject]}
else:
self.light_array[objref]["objectTable"].append(bobject)
out_object['data_ref'] = self.light_array[objref]["structName"]
elif object_type is NodeType.PROBE:
if objref not in self.probe_array:
self.probe_array[objref] = {"structName" : objname, "objectTable" : [bobject]}
else:
self.probe_array[objref]["objectTable"].append(bobject)
dist = bobject.data.influence_distance
if objref.type == "PLANAR":
out_object['dimensions'] = [1.0, 1.0, dist]
# GRID, CUBEMAP
else:
out_object['dimensions'] = [dist, dist, dist]
out_object['data_ref'] = self.probe_array[objref]["structName"]
elif object_type is NodeType.CAMERA:
if out_object.get('spawn', True): # Also spawn object if 'spawn' attr doesn't exist
self.has_spawning_camera = True
if objref not in self.camera_array:
self.camera_array[objref] = {"structName" : objname, "objectTable" : [bobject]}
else:
self.camera_array[objref]["objectTable"].append(bobject)
out_object['data_ref'] = self.camera_array[objref]["structName"]
elif object_type is NodeType.SPEAKER:
if objref not in self.speaker_array:
self.speaker_array[objref] = {"structName" : objname, "objectTable" : [bobject]}
else:
self.speaker_array[objref]["objectTable"].append(bobject)
out_object['data_ref'] = self.speaker_array[objref]["structName"]
# Export the transform. If object is animated, then animation tracks are exported here
if bobject.type != 'ARMATURE' and bobject.animation_data is not None:
action = bobject.animation_data.action
export_actions = [action]
for track in bobject.animation_data.nla_tracks:
if track.strips is None:
continue
for strip in track.strips:
if strip.action is None or strip.action in export_actions:
continue
export_actions.append(strip.action)
orig_action = action
for a in export_actions:
bobject.animation_data.action = a
self.export_object_transform(bobject, out_object)
if len(export_actions) >= 2 and export_actions[0] is None: # No action assigned
out_object['object_actions'].insert(0, 'null')
bobject.animation_data.action = orig_action
else:
self.export_object_transform(bobject, out_object)
# If the object is parented to a bone and is not relative, then undo the bone's transform
if bobject.parent_type == "BONE":
armature = bobject.parent.data
bone = armature.bones[bobject.parent_bone]
# if not bone.use_relative_parent:
out_object['parent_bone_connected'] = bone.use_connect
if bone.use_connect:
bone_translation = Vector((0, bone.length, 0)) + bone.head
out_object['parent_bone_tail'] = [bone_translation[0], bone_translation[1], bone_translation[2]]
else:
bone_translation = bone.tail - bone.head
out_object['parent_bone_tail'] = [bone_translation[0], bone_translation[1], bone_translation[2]]
pose_bone = bobject.parent.pose.bones[bobject.parent_bone]
bone_translation_pose = pose_bone.tail - pose_bone.head
out_object['parent_bone_tail_pose'] = [bone_translation_pose[0], bone_translation_pose[1], bone_translation_pose[2]]
if bobject.type == 'ARMATURE' and bobject.data is not None:
# Armature data
bdata = bobject.data
# Reference start action
action = None
adata = bobject.animation_data
# Active action
if adata is not None:
action = adata.action
if action is None:
log.warn('Object ' + bobject.name + ' - No action assigned, setting to pose')
bobject.animation_data_create()
actions = bpy.data.actions
action = actions.get('armorypose')
if action is None:
action = actions.new(name='armorypose')
# Export actions
export_actions = [action]
# hasattr - armature modifier may reference non-parent
# armature object to deform with
if hasattr(adata, 'nla_tracks') and adata.nla_tracks is not None:
for track in adata.nla_tracks:
if track.strips is None:
continue
for strip in track.strips:
if strip.action is None:
continue
if strip.action.name == action.name:
continue
export_actions.append(strip.action)
armatureid = arm.utils.safestr(arm.utils.asset_name(bdata))
ext = '.lz4' if ArmoryExporter.compress_enabled else ''
if ext == '' and not bpy.data.worlds['Arm'].arm_minimize:
ext = '.json'
out_object['bone_actions'] = []
for action in export_actions:
aname = arm.utils.safestr(arm.utils.asset_name(action))
out_object['bone_actions'].append('action_' + armatureid + '_' + aname + ext)
clear_op = set()
skelobj = bobject
baked_actions = []
orig_action = bobject.animation_data.action
if bdata.arm_autobake and bobject.name not in bpy.context.collection.all_objects:
clear_op.add('unlink')
# Clone bobject and put it in the current scene so
# the bake operator can run