-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
2763 lines (2301 loc) · 136 KB
/
__init__.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
import bpy
import os
import time
import math
import importlib
import _s4animtools.bone_names
from _s4animtools.serialization.fnv import get_64bithash
from _s4animtools.rcol.rcol_wrapper import OT_S4ANIMTOOLS_ImportFootprint, OT_S4ANIMTOOLS_VisualizeFootprint, \
OT_S4ANIMTOOLS_ExportFootprint
from _s4animtools.rig.create_rig import Trackmask
from _s4animtools.rig_tools import ExportRig, SyncRigToMesh
from _s4animtools.events.events import SnapEvent, SoundEvent, ScriptEvent, ReactionEvent, VisibilityEvent, ParentEvent, \
PlayEffectEvent, FocusCompatibilityEvent, SuppressLipsyncEvent, StopEffectEvent
from _s4animtools.serialization.types.basic import Float32, UInt32
from _s4animtools.clip_processing.clip_header import ClipResource, bone_to_slot_offset_idx
from _s4animtools.ik_baker import s4animtool_OT_bakeik, get_ik_targets
from _s4animtools.asm.state_machine import ActorPanel, ActorProperties, LIST_OT_MoveActor, LIST_OT_NewActor, \
LIST_OT_DeleteActor
from _s4animtools.asm.states import StateProperties, LIST_OT_NewState, LIST_OT_DeleteState, LIST_OT_MoveState, \
StatePanel, ControllerProperties, LIST_OT_NewController, LIST_OT_RemoveController, LIST_OT_MoveControllerState, \
PostureProperties, PosturePanel, LIST_OT_NewPosture, LIST_OT_DeletePosture, LIST_OT_MovePosture, StateConnections, \
LIST_OT_NewStateConnection, LIST_OT_DeleteStateConnection, LIST_OT_MoveStateConnection
from _s4animtools.rig.create_rig import create_rig_with_context
import _s4animtools.clip_processing.clip_header
import _s4animtools.rig
import _s4animtools.channels.f1_normalized_channel
import _s4animtools.channels.translation_channel
import _s4animtools.channels.loco_channel
import _s4animtools.channels.palette_channel
import _s4animtools.channels.quaternion_channel
import _s4animtools.control_rig.basic_control_rig
import _s4animtools.frames.frame
from _s4animtools.control_rig.basic_control_rig import CopyLeftSideAnimationToRightSide, \
CopySelectedLeftSideToRightSide, CopyLeftSideAnimationToRightSideSim, CopyBakedAnimationToControlRig, FlipLeftSideAnimationToRightSideSim
from _s4animtools.ik_manager import BeginIKMarker, LIST_OT_NewIKTarget,LIST_OT_CreateIKTarget, LIST_OT_DeleteIKTarget, LIST_OT_MoveIKTarget, \
s4animtool_OT_removeIK, s4animtool_OT_mute_ik, s4animtool_OT_unmute_ik, LIST_OT_NewIKRange, LIST_OT_DeleteIKRange, \
LIST_OT_DeleteSpecificIKTarget, MAX_SUBROOTS, s4animtools_OT_guessTarget
import _s4animtools.animation_exporter.animation
from _s4animtools.animation_exporter.animation import AnimationExporter, AdditiveAnimationExporter
import _s4animtools.rig.create_rig
from _s4animtools.serialization.types.transforms import Vector3, Quaternion4
import _s4animtools.clip_processing.clip_body
import _s4animtools.clip_processing.f1_palette
from bpy_extras.io_utils import ImportHelper
from mathutils import Vector, Quaternion, Matrix
from bpy.props import IntProperty, CollectionProperty, FloatProperty
from bpy.types import PropertyGroup
from collections import defaultdict
JAW_ANIMATE_DURATION = 100000
CHAIN_STR_IDX = 2
bl_info = {"name": "_s4animtools", "category": "Object", "blender": (2, 80, 0)}
importlib.reload(_s4animtools.animation_exporter.animation)
importlib.reload(_s4animtools.clip_processing.f1_palette)
importlib.reload(_s4animtools.frames.frame)
importlib.reload(_s4animtools.clip_processing.clip_body)
importlib.reload(_s4animtools.channels.palette_channel)
# importlib.reload(_s4animtools.asm.state_machine)
# importlib.reload(_s4animtools.translation_channel)
# importlib.reload(_s4animtools.f1_normalized_channel)
# importlib.reload(_s4animtools.rig.create_rig)
importlib.reload(_s4animtools.clip_processing.clip_header)
importlib.reload(_s4animtools.control_rig.basic_control_rig)
importlib.reload(_s4animtools.ik_manager)
importlib.reload(_s4animtools.clip_processing.clip_body)
importlib.reload(_s4animtools.rcol.rcol_wrapper)
def determine_ik_slot_targets(rig):
all_constraints = defaultdict(list)
current_bone_idx = defaultdict(int)
for ik_target in get_ik_targets(rig):
target_bone = ik_target.target_bone
is_subroot_bone = False
subroot_suffix = 0
for subroot_suffix in range(MAX_SUBROOTS):
is_subroot_bone = ik_target.target_bone.endswith(f"_{subroot_suffix}")
if is_subroot_bone:
break
if is_subroot_bone:
target_bone = ik_target.target_bone.replace(f"_{subroot_suffix}", "_")
if ik_target.chain_idx == -1:
chain_idx = bone_to_slot_offset_idx[ik_target.chain_bone]
else:
chain_idx = ik_target.chain_idx
print(f"IK target {ik_target.target_obj} is on chain {ik_target.chain_bone}")
all_constraints[ik_target.chain_bone].append(SlotAssignmentBlender(source_rig=rig,
source_bone=ik_target.chain_bone,
target_rig=bpy.data.objects[ik_target.target_obj],
target_bone=target_bone,
chain_idx=chain_idx,
slot_assignment_idx=current_bone_idx[ik_target.chain_bone]))
current_bone_idx[ik_target.chain_bone] += 1
#print(",".join(all_constraints))
return all_constraints
def create_ik_weight_channels(bone_name, influences, sequence_count):
f1normalized_channel = _s4animtools.channels.f1_normalized_channel.F1Normalized(bone_name, 5, 14 + sequence_count)
min_value, max_value = min(influences.values()), max(influences.values())
offset = (min_value + max_value) / 2
scale = -((min_value - max_value) / 2)
if scale == 0:
scale = 1
f1normalized_channel.set_channel_data(offset=offset, scale=scale, individual_frames=influences)
return f1normalized_channel
def gather_ik_weights(obj, influences, bone_name, ik_weight_idx, start_frame, current_frame, last_frame_influence):
"""Record the IK weight of each IK constraint from the ik weight in Blender."""
# print(last_frame_influence - constraint.influence)
influence = getattr(obj.pose.bones[bone_name], f'ik_weight_{ik_weight_idx}')
if current_frame - start_frame == 0 or abs(last_frame_influence - influence) > 0.001:
influences[(bone_name, ik_weight_idx)][current_frame - start_frame] = influence
return influence
return last_frame_influence
def set_loco_world_ik(bone_name, clip_start, clip_end):
"""Record the IK weight of each IK constraint from the actual constraint in Blender."""
f1normalized_channel = _s4animtools.channels.f1_normalized_channel.F1Normalized(bone_name, 5, 14)
influences = {}
min_value, max_value = 1, 1
influences[0] = 1
influences[clip_end - clip_start] = 1
# print(min_value, max_value)
offset = (min_value + max_value) / 2
scale = -((min_value - max_value) / 2)
if scale == 0:
scale = 1
f1normalized_channel.set_channel_data(offset=offset, scale=scale, individual_frames=influences)
return f1normalized_channel
class Snapper(bpy.types.Operator):
bl_idname = "s4animtools.snap"
bl_label = "Snap IK Target"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
"""Does this thing actally still work?"""
active_pose_bone = bpy.context.active_pose_bone
x = bpy.data.objects["dude1"]
y = bpy.data.objects["rig.001"]
y_bones = y.pose.bones
y_scores = {}
y_translations = {}
for bone in y_bones:
if bone.name.endswith("slot"):
target_matrix_final = y.matrix_world @ bone.matrix
active_bone_matrix_final = x.matrix_world @ active_pose_bone.matrix
distance_of_bone = (active_bone_matrix_final.translation - target_matrix_final.translation).length
y_scores[bone.name] = distance_of_bone
y_translations[bone.name] = target_matrix_final.translation
top_y_bone = sorted(y_scores.items(), key=lambda x: x[1])[0][0]
context.scene.IK_bone_target = top_y_bone
bpy.data.objects["Cube"].location = y_translations[top_y_bone]
print(top_y_bone, y_scores[top_y_bone])
print(time.time())
def modal(self, context, event):
self.execute(context)
if event.type == 'ESC':
context.scene.watcher_running = False
print("Giving up.")
return {'FINISHED'}
print("pass through")
# all other events pass through to blender
return {'PASS_THROUGH'}
def invoke(self, context, event):
run_as_modal = True
print("Invoke me pls")
if run_as_modal:
self.timer = context.window_manager.event_timer_add(0.01, window=context.window)
# set the monitoring property to True
context.scene.watcher_running = True
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
# run self to spawn cubes
return {'FINISHED'}
class ClipExporter(bpy.types.Operator):
bl_idname = "s4animtools.export_clip"
bl_label = "Export Clip"
bl_options = {"REGISTER", "UNDO"}
def convert_into_value(self, value):
return str(value)
def get_distance(self, posA, posB):
distance = math.sqrt((posA.x - posB.x) ** 2 + (posA.y - posB.y) ** 2 + (posA.z - posB.z) ** 2)
# print(distance)
return distance
def get_keyframes(self, obj):
keyframes = []
anim = obj.animation_data
if anim is not None and anim.action is not None:
for fcu in anim.action.fcurves:
for keyframe in fcu.keyframe_points:
x, y = keyframe.co
if x not in keyframes:
keyframes.append((math.ceil(x)))
return keyframes
def setup_events(self, context, current_clip, start_frame, frame_count, additional_snap_frames):
"""
Shifts the timestamps of the clip events depending on the split.
So you can time it relative to the start of the blend file in blender,
and have it reflect relative to the clip file in the export.
"""
start_time = start_frame * (1 / 30)
frame_time = frame_count * (1 / 30)
variable_to_event = {context.object.parent_events_list: ParentEvent,
context.object.sound_events_list: SoundEvent,
context.object.snap_events_list: SnapEvent,
context.object.visibility_events_list: VisibilityEvent,
context.object.script_events_list: ScriptEvent,
context.object.reaction_events_list: ReactionEvent,
context.object.play_effect_events_list: PlayEffectEvent,
context.object.focus_compatibility_events_list: FocusCompatibilityEvent,
context.object.disable_lipsync_events_list: SuppressLipsyncEvent,
context.object.stop_effect_events_list: StopEffectEvent}
snap_frames = []
for parameter_fields, event in variable_to_event.items():
for event_instance in parameter_fields:
parameters = event_instance.info.split(",")
parameter_length = len(parameters)
if parameter_length == 1:
continue
if parameter_length < event.arg_count:
raise Exception(
f"Your event has incomplete parameters. Expected {event.arg_count} parameters. Got {parameter_length}")
try:
original_timestamp = parameters[0].strip()
original_timestamp, timeshifted_timestamp = self.create_timeshifted_timestamp(original_timestamp,
start_time)
if event == SnapEvent:
snap_frames.append(timeshifted_timestamp)
if event == FocusCompatibilityEvent:
if frame_time >= timeshifted_timestamp >= 0:
_, timeshifted_end_timestamp = self.create_timeshifted_timestamp(parameters[1].strip(),
start_time)
current_clip.add_event(
event(timeshifted_timestamp, timeshifted_end_timestamp, *parameters[2:]))
else:
if frame_time >= timeshifted_timestamp >= 0:
current_clip.add_event(event(timeshifted_timestamp, *parameters[1:]))
except Exception as e:
print(e)
#raise Exception("You're missing parameters for your event..")
if additional_snap_frames != "":
additional_snap_frames = additional_snap_frames.split(",")
for frame in additional_snap_frames:
original_frame = int(frame)
timeshifted_frame = original_frame - start_frame
if frame_count > timeshifted_frame >= 0:
snap_frames.append(timeshifted_frame)
return snap_frames
def create_timeshifted_timestamp(self, original_timestamp_str, start_time):
if original_timestamp_str.endswith("f") or original_timestamp_str.endswith("fr"):
original_timestamp = float(original_timestamp_str[:-1]) / 30
elif original_timestamp_str.endswith("e"):
original_timestamp = eval(original_timestamp_str[:-1])
else:
original_timestamp = float(original_timestamp_str)
# IF it ends with r (relative), then we don't need to shift from absolute to relative,
# because we're already in relative
if original_timestamp_str.endswith("r") and original_timestamp_str.endswith("rf"):
timeshifted_timestamp = original_timestamp
else:
timeshifted_timestamp = original_timestamp - start_time
return original_timestamp, timeshifted_timestamp
def execute(self, context):
t1 = time.time()
root_bone = list(bpy.context.active_object.pose.bones)[0]
world_root_bone, world_rig = self.determine_world_ik(context, root_bone)
ik_targets = determine_ik_slot_targets(bpy.context.active_object)
weight_channels = []
slot_assignments = defaultdict(list)
# add rigs namespaces
rigs_used = []
ik_bones = []
animated_bones = dict()
previous_recorded_frame = dict()
def setup_channel_data(bone):
default_bone_channels = {"Main Channel": {"TRANSLATION": {}, "ORIENTATION": {}, "SCALE": {}},
"IK World Channel": {"TRANSLATION": {}, "ORIENTATION": {}}}
animated_bones[bone.name] = default_bone_channels.copy()
default_previous_frame = {
"Main Channel": {"TRANSLATION": Vector((0, 0, 0)), "ORIENTATION": Quaternion((1, 0, 0, 0)),
"SCALE": Vector((1, 1, 1))},
"IK World Channel": {"TRANSLATION": Vector((0, 0, 0)), "ORIENTATION": Quaternion((1, 0, 0, 0))}}
previous_recorded_frame[bone.name] = default_previous_frame.copy()
for ik_chain in slot_assignments:
if ik_chain == bone.name:
for idx in range(len(slot_assignments[ik_chain])):
channel_name = "IK Target {} Channel".format(1 + idx)
animated_bones[bone.name][channel_name] = {"TRANSLATION": {}, "ORIENTATION": {}}
previous_recorded_frame[bone.name][channel_name] = {"TRANSLATION": Vector((0, 0, 0)),
"ORIENTATION": Quaternion((1, 0, 0, 0))}
for child in bone.children:
setup_channel_data(child)
snap_frames = None
# Todo why doesn't this use the Slot Assignment class?
for bone in constraints:
for idx, target in enumerate(constraints[bone]):
slot_assignments[bone].append(
(bone, target[0], target[1], idx, int(target[2].target.name.split(" ")[2])))
if bone not in ik_bones:
ik_bones.append(bone)
# Ik bones list
# Get blend name for source file name in clip file.
filepath = bpy.data.filepath
blend_name = filepath.split(os.sep)[-1]
clip_indices = [0, ]
clip_splits = context.scene.clip_splits.split(",")
if len(clip_splits) > 0:
for idx in range(len(clip_splits)):
clip_indices.append(int(clip_splits[idx]))
# clip_indices.append(bpy.context.scene.frame_end)
def finalize_channels(all_frame_data, channel_data, current_channel):
min, max = 9999, -9999
for idx, frame_data in channel_data.items():
all_frame_data[idx] = frame_data.copy()
for value in frame_data:
# print(value, max)
if max < value:
max = value
if min > value:
min = value
# TODO Uhhh does the below code even do what it's supposed to do?
# printfor ax_idx in range(len(frame_data)):
# frame_data[ax_idx] = number_format(frame_data[ax_idx])
offset = (min + max) / 2
scale = -((min - max) / 2)
current_channel.set_channel_data(offset=offset, scale=scale, individual_frames=all_frame_data,
snap_frames=snap_frames)
current_clip.clip_body.add_channel(current_channel)
def recursive_bone_animate(bone, idx, is_snap_frame):
if bone.parent and keyframed_bones[
bone.name] and bpy.context.scene.is_overlay or not bpy.context.scene.is_overlay and bone.parent:
# Animate relative to the world rig if the current bone is the b__ROOT_bind__ bone.
if bone.parent.name == "b__ROOT__":
animate_relative_to_bone(bone, world_root_bone, bpy.context.active_object, world_rig, idx,
"Main Channel", is_snap_frame)
else:
animate_relative_to_bone(bone, bone.parent, bpy.context.active_object, bpy.context.active_object,
idx, "Main Channel", is_snap_frame)
use_IK = True
if bone.name in ik_bones and use_IK:
current_ik_target = 0
animate_relative_to_bone(bone, world_root_bone, bpy.context.active_object, world_rig, idx,
"IK World Channel", is_snap_frame)
current_ik_target += 1
for bone_constraint_name in slot_assignments.keys():
if bone.name == bone_constraint_name:
for bone_constraint in slot_assignments[bone_constraint_name]:
channel_name = "IK Target {} Channel".format(current_ik_target)
current_ik_target += 1
animate_relative_to_bone(bone, bone_constraint[1].pose.bones[bone_constraint[2]],
bpy.context.active_object, bone_constraint[1], idx,
channel_name, is_snap_frame)
for child in bone.children:
# Don't animate slots.
if "slot" not in child.name:
recursive_bone_animate(child, idx, is_snap_frame)
def recursive_bone_finalize(bone):
current_sequence_count = 1 # This affects the actual IK translation and rotation offset data
for channel_name, channel_bundle in animated_bones[bone.name].items():
for channel_type, channel_data in channel_bundle.items():
# Don't need to save channel if nothing is in it
if len(channel_data) == 0:
continue
all_frame_data = {}
current_channel = None
if channel_type == "TRANSLATION":
current_channel = _s4animtools.channels.translation_channel.Vector3Channel(bone.name, 18, 1)
elif channel_type == "ORIENTATION":
current_channel = _s4animtools.channels.channel.QuaternionChannel(bone.name, 20, 2)
elif channel_type == "SCALE":
current_channel = _s4animtools.channels.translation_channel.Vector3Channel(bone.name, 18, 3)
if "IK" in channel_name:
if channel_type == "TRANSLATION":
current_channel = _s4animtools.channels.translation_channel.Vector3Channel(bone.name,
18, 23 + (
current_sequence_count * 2))
elif channel_type == "ORIENTATION":
current_channel = _s4animtools.channels.channel.QuaternionChannel(bone.name, 20,
(24 + current_sequence_count * 2))
finalize_channels(all_frame_data, channel_data, current_channel)
if "IK" in channel_name:
current_sequence_count += 1
for bone in bone.children:
recursive_bone_finalize(bone)
def animate_relative_to_bone(bone, parent_bone, source_rig, target_rig, idx, channel_name, is_snap_frame,
allow_fail_on_scale=True):
bp1 = source_rig.matrix_world @ bone.matrix
bp2 = target_rig.matrix_world @ parent_bone.matrix
matrix_data = bp2.inverted() @ bp1
rotation_data = matrix_data.to_quaternion()
translation_data = matrix_data.to_translation()
last_rotation_data = previous_recorded_frame[bone.name][channel_name]["ORIENTATION"]
last_translation_data = previous_recorded_frame[bone.name][channel_name]["TRANSLATION"]
# TODO quick hack for scale
try:
scale_data = bone.scale
last_scale_data = previous_recorded_frame[bone.name][channel_name]["SCALE"]
if abs(self.get_distance(last_scale_data, scale_data)) < 0.00001 and len(
animated_bones[bone.name][channel_name]["SCALE"].keys()) >= 1 and not is_snap_frame:
pass
else:
animated_bones[bone.name][channel_name]["SCALE"][idx] = [scale_data.x, scale_data.y,
scale_data.z]
previous_recorded_frame[bone.name][channel_name]["SCALE"] = scale_data.copy()
except Exception as e:
if allow_fail_on_scale:
pass
else:
raise e
if abs((last_rotation_data - rotation_data).magnitude) < 0.00001 and len(
animated_bones[bone.name][channel_name]["ORIENTATION"].keys()) >= 1 and not is_snap_frame:
pass
else:
animated_bones[bone.name][channel_name]["ORIENTATION"][idx] = [rotation_data.x, rotation_data.y,
rotation_data.z,
rotation_data.w]
previous_recorded_frame[bone.name][channel_name]["ORIENTATION"] = rotation_data
if abs(self.get_distance(last_translation_data, translation_data)) < 0.00001 and len(
animated_bones[bone.name][channel_name]["TRANSLATION"].keys()) >= 1 and not is_snap_frame:
pass
else:
animated_bones[bone.name][channel_name]["TRANSLATION"][idx] = [translation_data.x, translation_data.y,
translation_data.z]
previous_recorded_frame[bone.name][channel_name]["TRANSLATION"] = translation_data
def save_locomotion_data(clip_start, clip_end):
next_initial_translation_offset = ""
if "loco" in bpy.context.active_object.pose.bones:
loco_bone = bpy.context.active_object.pose.bones["loco"]
# current_clip.clip_body._f1PaletteData.append(float32(0))
for idx in range(clip_start, clip_end):
bpy.context.scene.frame_set(idx)
bp1 = bpy.context.active_object.matrix_world @ loco_bone.matrix
current_clip.clip_body._f1PaletteData.append(Float32(round(abs(bp1.to_translation().y), 6)))
if idx == clip_start:
next_initial_translation_offset = "0,0,{}".format(abs(bp1.to_translation().y))
current_clip.clip_body._f1PaletteSize = len(current_clip.clip_body._f1PaletteData)
loco_channel_pos = _s4animtools.channels.palette_channel.PaletteTranslationChannel("loco", 3, 1)
channel_frame_data = {}
for idx in range(clip_start, clip_end):
channel_frame_data[idx - clip_start] = (0, 0, idx - clip_start)
loco_channel_pos.set_channel_data(0, 1, channel_frame_data, snap_frames)
loco_channel_rot = _s4animtools.channels.channel.QuaternionChannel("loco", 17, 2)
loco_channel_rot.set_channel_data(0, 1, {}, snap_frames)
loco_channel_pos._target = UInt32(720414894)
loco_channel_rot._target = UInt32(720414894)
loco_channel_pos._frame_count = current_clip.clip_body._f1PaletteSize
current_clip.clip_body.add_channel(loco_channel_pos)
current_clip.clip_body.add_channel(loco_channel_rot)
return next_initial_translation_offset
def get_animated_bones():
rig = bpy.context.active_object.pose
keyframed_bones = defaultdict(bool)
for b in rig.bones:
for fcu in bpy.context.active_object.animation_data.action.fcurves:
if fcu.data_path.startswith('pose.bones["{}"]'.format(b.name)):
keyframed_bones[b.name] = True
break
return keyframed_bones
keyframed_bones = get_animated_bones()
clip_names = []
clip_input_names = context.scene.clip_name.split(",")
if len(clip_input_names) > 0:
for idx in range(len(clip_input_names)):
clip_names.append(clip_input_names[idx].strip())
reset_offset = []
if context.object.reset_initial_offset_t != "":
reset_initial_offset_t = context.object.reset_initial_offset_t.split(",")
if len(reset_initial_offset_t) > 0:
for idx in range(len(reset_initial_offset_t)):
reset_offset.append(reset_initial_offset_t[idx].strip() == "+")
else:
for clip_idx in range(len(clip_indices) - 1):
reset_offset.append(False)
initial_offset_t = context.object.initial_offset_t
initial_offset_q = context.object.initial_offset_q
# Set the initial offsets to the default if the user doesn't enter anything.
if initial_offset_t == "":
initial_offset_t = "0,0,0"
if initial_offset_q == "":
initial_offset_q = "0,0,0,1"
rig_name = context.object.rig_name
if rig_name == "":
context.object.rig_name = "x"
rig_name = context.object.rig_name
reference_namespace_hash = context.object.reference_namespace_hash
if reference_namespace_hash == "":
reference_namespace_hash = 0
else:
reference_namespace_hash = int(reference_namespace_hash, 16)
for clip_idx in range(len(clip_indices) - 1):
clip_frame_idx = clip_indices[clip_idx]
if context.scene.clip_name_prefix == "":
combined_clip_name = "{}".format(clip_names[clip_idx])
else:
combined_clip_name = "{}_{}".format(context.scene.clip_name_prefix, clip_names[clip_idx])
has_loco_bone = "loco" in context.object.pose.bones
current_clip = ClipResource(combined_clip_name, rig_name, slot_assignments,
context.object.explicit_namespaces,
reference_namespace_hash, Quaternion.from_str(initial_offset_q),
Vector3.from_str(initial_offset_t), blend_name, has_loco_bone,
context.object.disable_rig_suffix)
setup_channel_data(root_bone)
clip_start, clip_end = clip_frame_idx, clip_indices[clip_idx + 1]
snap_frames = self.setup_events(context, current_clip, clip_start, clip_end - clip_start,
context.object.additional_snap_frames)
for channel in weight_channels:
current_clip.clip_body.add_channel(channel)
last_frame_influences = defaultdict(int)
ik_weight_animation_data = defaultdict(dict)
for current_frame in range(clip_start, clip_end):
bpy.context.scene.frame_set(current_frame)
bpy.context.view_layer.update()
# Clip data needs to be offset when the clip actually starts is at zero.
recursive_bone_animate(root_bone, current_frame - clip_start, current_frame - clip_start in snap_frames)
for bone in constraints:
for idx, target in enumerate(constraints[bone]):
ik_weight = gather_ik_weights(ik_weight_animation_data, target[2], clip_start, current_frame,
last_frame_influences[target[2]])
last_frame_influences[target[2]] = ik_weight
for bone in constraints:
for idx, target in enumerate(constraints[bone]):
current_clip.clip_body.add_channel(
(create_ik_weight_channels(bone, ik_weight_animation_data[target[2]], idx + 1)))
next_initial_translation_offset = save_locomotion_data(clip_start, clip_end)
if next_initial_translation_offset != "":
# TODO Hack!! Fix this
current_clip._initialOffsetT = list(map(float, next_initial_translation_offset.split(",")))
if len(reset_offset) > clip_idx:
if reset_offset[clip_idx]:
initial_offset_t = "0,0,0"
initial_offset_q = "0,0,0,1"
loco_animation = False
root_bone = bpy.context.active_object.pose.bones["b__ROOT__"]
if loco_animation:
try:
for bone in self.IK_bones:
# todo don't play the animation each time for a bone!!
current_clip.clip_body.add_channel(set_loco_world_ik(bone, clip_start, clip_end))
except:
print("wtf")
recursive_bone_finalize(root_bone)
current_clip.clip_body.set_clip_length(clip_end - clip_start)
current_clip.update_duration(clip_end - clip_start)
current_clip.serialize()
current_clip = None
t2 = time.time()
print(f"Took {t2 - t1} seconds for clip export")
def determine_world_ik(self, context, root_bone):
if context.object.world_rig == "":
world_rig = bpy.context.active_object
world_root_bone = root_bone
else:
world_rig = bpy.data.objects[context.object.world_rig]
world_root_bone = world_rig.pose.bones[context.object.world_bone]
return world_root_bone, world_rig
def invoke(self, context, event):
self.execute(context)
return {'FINISHED'}
class ClipInfo:
def __init__(self, start_frame, end_frame, name, reference_namespace_hash, explicit_namespaces, initial_offset_q,
initial_offset_t, rig_name):
self.start_frame = start_frame
self.end_frame = end_frame
self.name = name
if reference_namespace_hash == "":
reference_namespace_hash = 0
else:
reference_namespace_hash = int(reference_namespace_hash, 16)
self.reference_namespace_hash = reference_namespace_hash
self.explicit_namespaces = explicit_namespaces
self.initial_offset_q = initial_offset_q
self.initial_offset_t = initial_offset_t
self.rig_name = rig_name
class SlotAssignmentBlender:
def __init__(self, source_rig, source_bone, target_rig, target_bone, slot_assignment_idx, chain_idx):
self.source_rig = source_rig
self.source_bone = source_bone
self.target_rig = target_rig
self.target_bone = target_bone
self.slot_assignment_idx = slot_assignment_idx
self.chain_idx = chain_idx
class NewClipExporter(bpy.types.Operator):
bl_idname = "s4animtools.new_export_clip"
bl_label = "New Export Clip"
bl_options = {"REGISTER", "UNDO"}
additive: bpy.props.BoolProperty(default=False)
def __init__(self):
self.context = None
self.clip_infos = []
def setup_events(self, context, current_clip, start_frame, frame_count, additional_snap_frames):
"""Shifts the timestamps of the clip events depending on the split.
So you can time it relative to the start of the blend file in blender,
and have it reflect relative to the clip file in the export.
"""
start_time = start_frame * (1 / 30)
frame_time = frame_count * (1 / 30)
variable_to_event = {context.object.parent_events_list: ParentEvent,
context.object.sound_events_list: SoundEvent,
context.object.snap_events_list: SnapEvent,
context.object.visibility_events_list: VisibilityEvent,
context.object.script_events_list: ScriptEvent,
context.object.reaction_events_list: ReactionEvent,
context.object.play_effect_events_list: PlayEffectEvent,
context.object.focus_compatibility_events_list: FocusCompatibilityEvent,
context.object.disable_lipsync_events_list: SuppressLipsyncEvent,
context.object.stop_effect_events_list: StopEffectEvent}
snap_frames = []
for parameter_fields, event in variable_to_event.items():
for event_instance in parameter_fields:
parameters = event_instance.info.split(",")
parameter_length = len(parameters)
if parameter_length == 1:
continue
if parameter_length < event.arg_count:
raise Exception(
f"Your event has incomplete parameters. Expected {event.arg_count} parameters. Got {parameter_length}")
original_timestamp = parameters[0].strip()
if original_timestamp.startswith("//"):
continue
original_timestamp, timeshifted_timestamp = self.create_timeshifted_timestamp(original_timestamp,
start_time)
if event == SnapEvent:
if frame_time >= timeshifted_timestamp >= 0:
snap_frames.append(timeshifted_timestamp)
current_clip.add_event(event(timeshifted_timestamp, *parameters[1:]))
elif event == FocusCompatibilityEvent:
if frame_time >= timeshifted_timestamp >= 0:
_, timeshifted_end_timestamp = self.create_timeshifted_timestamp(parameters[1].strip(),
start_time)
current_clip.add_event(
event(timeshifted_timestamp, timeshifted_end_timestamp, *parameters[2:]))
elif event == SuppressLipsyncEvent:
if frame_time >= timeshifted_timestamp >= 0:
_, timeshifted_end_timestamp = self.create_timeshifted_timestamp(parameters[1].strip(),
start_time)
current_clip.add_event(
event(timeshifted_timestamp, timeshifted_end_timestamp, *parameters[2:]))
else:
if frame_time >= timeshifted_timestamp >= 0:
current_clip.add_event(event(timeshifted_timestamp, *parameters[1:]))
if context.object.allow_jaw_animation_for_entire_animation:
current_clip.add_event(SuppressLipsyncEvent(0, JAW_ANIMATE_DURATION))
# raise Exception("You're missing parameters for your event..")
if additional_snap_frames != "":
additional_snap_frames = additional_snap_frames.split(",")
for frame in additional_snap_frames:
original_frame = int(frame)
timeshifted_frame = original_frame - start_frame
if frame_count > timeshifted_frame >= 0:
snap_frames.append(timeshifted_frame)
return snap_frames
def create_timeshifted_timestamp(self, original_timestamp_str, start_time):
if original_timestamp_str.endswith("f") or original_timestamp_str.endswith("fr"):
original_timestamp = float(original_timestamp_str[:-1]) / 30
elif original_timestamp_str.endswith("e"):
original_timestamp = eval(original_timestamp_str[:-1])
else:
original_timestamp = float(original_timestamp_str)
# IF it ends with r (relative), then we don't need to shift from absolute to relative,
# because we're already in relative
if original_timestamp_str.endswith("r") and original_timestamp_str.endswith("rf"):
timeshifted_timestamp = original_timestamp
else:
timeshifted_timestamp = original_timestamp - start_time
return original_timestamp, timeshifted_timestamp
def get_clip_names(self):
clip_names = []
clip_input_names = self.context.scene.clip_name.split(",")
if len(clip_input_names) > 0:
for clip_input_name in clip_input_names:
if self.context.scene.clip_name_prefix == "":
clip_names.append(clip_input_name)
else:
clip_names.append(f"{self.context.scene.clip_name_prefix}_{clip_input_name}")
return clip_names
def get_clip_splits(self):
clip_indices = [0, ]
clip_splits = self.context.scene.clip_splits.split(",")
if len(clip_splits) > 0:
for split in clip_splits:
clip_indices.append(int(split))
return clip_indices
def get_explicit_namespaces(self):
return self.context.object.explicit_namespaces
def get_reference_namespace_hash(self):
return self.context.object.reference_namespace_hash
def get_clip_infos(self):
rig_name = self.context.object.rig_name
if rig_name == "":
raise Exception("You need to specify a rig name")
return
initial_offset_t = self.context.object.initial_offset_t
initial_offset_q = self.context.object.initial_offset_q
# Set the initial offsets to the default if the user doesn't enter anything.
if initial_offset_t == "":
initial_offset_t = "0,0,0"
if initial_offset_q == "":
initial_offset_q = "0,0,0,1"
if len(self.clip_infos) == 0:
clip_infos = []
clip_names = self.get_clip_names()
clip_indices = self.get_clip_splits()
if len(clip_names) != len(clip_indices) - 1:
raise ValueError(
"Clip names doesn't match clip indices. Please check your splits and names are the same length.")
for clip_idx in range(len(clip_names)):
clip_infos.append(
ClipInfo(start_frame=clip_indices[clip_idx], end_frame=clip_indices[clip_idx + 1], name=clip_names[clip_idx],
explicit_namespaces=self.get_explicit_namespaces(),
reference_namespace_hash=self.get_reference_namespace_hash(),
initial_offset_q=Quaternion4.from_str(initial_offset_q),
initial_offset_t=Vector3.from_str(initial_offset_t), rig_name=rig_name))
self.clip_infos = clip_infos
return self.clip_infos
def execute(self, context):
t1 = time.time()
self.context = context
self.clip_infos = []
source_filename = bpy.data.filepath.split(os.sep)[-1]
ik_targets_to_bone = determine_ik_slot_targets(self.context.active_object)
self.clip_infos = self.get_clip_infos()
world_rig = self.context.object.world_rig
world_root = self.context.object.world_bone
if len(world_rig) == 0:
world_rig = self.context.object
else:
world_rig = bpy.data.objects[world_rig]
if len(world_root) == 0:
world_root = world_rig.pose.bones["b__ROOT__"]
else:
world_root = world_rig.pose.bones[world_root]
base_rig = self.context.object.base_rig
for idx, clip_info in enumerate(self.clip_infos):
current_clip = ClipResource(clip_info.name, clip_info.rig_name, ik_targets_to_bone,
clip_info.explicit_namespaces,
clip_info.reference_namespace_hash, clip_info.initial_offset_q,
clip_info.initial_offset_t, source_filename, False, context.object.disable_rig_suffix)
rig = self.context.object
snap_frames = self.setup_events(self.context, current_clip, clip_info.start_frame, clip_info.end_frame - clip_info.start_frame,
self.context.object.additional_snap_frames)
if self.additive:
exporter = AdditiveAnimationExporter(rig, snap_frames, world_rig=world_rig, world_root=world_root, use_full_precision=self.context.object.use_full_precision, base_rig=bpy.data.objects[base_rig])
else:
exporter = AnimationExporter(rig, snap_frames, world_rig=world_rig, world_root=world_root, use_full_precision=self.context.object.use_full_precision)
exporter.create_animation_data()
exporter.paletteHolder.try_add_palette_to_palette_values(0)
exporter.paletteHolder.try_add_palette_to_palette_values(1.0)
last_frame_influences = defaultdict(int)
ik_weight_animation_data = defaultdict(dict)
slot_assignment_source_bones = ik_targets_to_bone.keys()
for frame_idx in range(clip_info.start_frame, clip_info.end_frame):
bpy.context.scene.frame_set(frame_idx)
bpy.context.view_layer.update()
exporter.animate_recursively(frame_idx, start_frame=clip_info.start_frame, force=frame_idx == clip_info.start_frame
or frame_idx == clip_info.end_frame)
for source_bone_ik in slot_assignment_source_bones:
for ik_idx, slot_assignment_info in enumerate(ik_targets_to_bone[source_bone_ik]):
ik_weight = gather_ik_weights(rig, ik_weight_animation_data, slot_assignment_info.source_bone, ik_idx, clip_info.start_frame,
frame_idx, last_frame_influences[(slot_assignment_info.source_bone, ik_idx)])
last_frame_influences[(slot_assignment_info.source_bone, ik_idx)] = ik_weight
for source_bone_ik in slot_assignment_source_bones:
for ik_idx, slot_assignment_info in enumerate(ik_targets_to_bone[source_bone_ik]):
exporter.add_baked_animation_data_to_frame(slot_assignment_info.source_bone,
start_frame=clip_info.start_frame,
end_frame=clip_info.end_frame, ik_idx=ik_idx)
current_clip.clip_body.add_channel(
(create_ik_weight_channels(slot_assignment_info.source_bone,
ik_weight_animation_data[(slot_assignment_info.source_bone, ik_idx)],
ik_idx)))
for channel in exporter.export_to_channels():
current_clip.clip_body.add_channel(new_channel=channel)
current_clip.clip_body.set_palette_values(exporter.paletteHolder.palette_values)
current_clip.clip_body.set_clip_length(clip_info.end_frame - clip_info.start_frame)
current_clip.update_duration(clip_info.end_frame - clip_info.start_frame)
current_clip.serialize()
t2 = time.time()
print(f"Took {t2 - t1} seconds for clip export")
return {"FINISHED"}
class S4ANIMTOOLS_PT_MainPanel(bpy.types.Panel):
bl_idname = "S4ANIMTOOLS_PT_MainPanel"
bl_label = "S4AnimTools"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
# bl_category = "Tools"
bl_category = "S4AnimTools"
def draw_property_if_not_empty(self, obj, property_name, layout):
if getattr(obj, property_name, "") != "":
layout.prop(obj, property_name)
def draw_events(self, obj, events_list_name, x_scale, description, event_name, layout, parameters=None):
events_list = getattr(obj, events_list_name)
layout.label(
text=f"{event_name}: {len(events_list)} - {description}")
for idx, item in enumerate(events_list):
row = layout.row()
if item.info != "":
if parameters is not None:
concat_string = ""
parameter_list = list(zip(parameters, item.info.split(",")))
for key, value in parameter_list:
layout.row().label(text=f"{key}: {value}")
if len(parameters) > len(item.info.split(",")):
layout.row().label(text="Not enough parameters.")
if len(parameters) < len(item.info.split(",")):
layout.row().label(text="Too many parameters.")
# layout.row().label(text=concat_string[:-2])
row2 = row.row()
row.scale_x = x_scale
row2.prop(item, "info", text="")
row.operator('s4animtools.move_new_element', text='↑').args = f"{events_list_name},{idx},up"
row.operator('s4animtools.move_new_element', text='↓').args = f"{events_list_name},{idx},down"
row.operator('s4animtools.move_new_element', text='✖').args = f"{events_list_name},{idx},delete"
row.operator('s4animtools.move_new_element', text='+').args = f"{events_list_name},{idx},create"
def draw(self, context):
obj = context.object
#self.layout.operator("s4animtools.export_clip", icon='MESH_CUBE', text="Export Clip")
# self.layout.operator("s4animtools.sync_rig_to_mesh", icon='MESH_CUBE', text="Sync Rig To Mesh")
# self.layout.prop(context.scene, "IK_bone_target") # String for displaying current IK bone
row = self.layout.row()
# row.operator("s4animtools.beginikmarker", text="Add Left Hand").command = "LEFT,HAND,BEGIN"
# row.operator("s4animtools.beginikmarker", text="Remove Left Hand").command = "LEFT,HAND,END"
#
# row = self.layout.row()
# row.operator("s4animtools.beginikmarker", text="Add Right Hand").command = "RIGHT,HAND,BEGIN"
# row.operator("s4animtools.beginikmarker", text="Remove Right Hand").command = "RIGHT,HAND,END"
# row = self.layout.row()
# row.operator("s4animtools.beginikmarker", text="Add Left Foot").command = "LEFT,FOOT,BEGIN"
# row.operator("s4animtools.beginikmarker", text="Remove Left Foot").command = "LEFT,FOOT,END"
# row = self.layout.row()
# row.operator("s4animtools.beginikmarker", text="Add Right Foot").command = "RIGHT,FOOT,BEGIN"
# row.operator("s4animtools.beginikmarker", text="Remove Right Foot").command = "RIGHT,FOOT,END"
# row = self.layout.row()
#
# row.operator("s4animtools.beginikmarker", text="Add Root Bind").command = "SINGLE,BIND,BEGIN"
# row.operator("s4animtools.beginikmarker", text="Remove Root Bind").command = "SINGLE,BIND,END"
#
self.layout.operator("s4animtools.import_footprint", icon="MESH_CUBE", text="Import Footprint")
self.layout.operator("s4animtools.export_footprint", icon="MESH_CUBE", text="Export Footprint")
self.layout.operator("s4animtools.visualize_footprint", icon="MESH_CUBE", text="View Pathing Footprints").command="for_pathing"
self.layout.operator("s4animtools.visualize_footprint", icon="MESH_CUBE", text="View Placement Footprints").command="for_placement"
self.layout.operator("s4animtools.visualize_footprint", icon="MESH_CUBE", text="View Terrain Footprints").command="terrain"
self.layout.operator("s4animtools.visualize_footprint", icon="MESH_CUBE", text="View Floor Footprints").command="floor"
self.layout.operator("s4animtools.visualize_footprint", icon="MESH_CUBE", text="View Pool Footprints").command="pool"
self.layout.prop(context.scene, "footprint_name", text="Footprint Name Or Hash")
if obj is not None:
layout = self.layout
layout.prop(obj, "is_footprint", text = "Is Footprint Object")
if obj.is_footprint:
layout = self.layout.row()
self.layout.label(text="Footprint is in: ")
layout = self.layout.row()
layout.prop(obj, "slope", text = "Slope")
layout.prop(obj, "outside", text = "Outside")
layout.prop(obj, "inside", text = "Inside")
self.layout.label(text="Footprint is of Type: ")
layout = self.layout.row()
layout.prop(obj, "for_placement", text = "For Placement")
layout.prop(obj, "for_pathing", text = "For Pathing")
layout.prop(obj, "is_enabled", text = "Is Enabled")
layout = self.layout.row()
layout.prop(obj, "discouraged", text = "Discouraged")
layout.prop(obj, "landing_strip", text = "Landing Strip")
layout.prop(obj, "no_raycast", text = "No Raycast")
layout = self.layout.row()
layout.prop(obj, "placement_slotted", text = "Placement Slotted")