-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrapidSDK.py
2181 lines (1807 loc) · 80.7 KB
/
rapidSDK.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
"""
rapidSDK
Copyright (C) 2022, Ingo Clemens, brave rabbit, www.braverabbit.com
GNU GENERAL PUBLIC LICENSE Version 3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.
If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------
Description:
Rapid SDK provides a simple one-button workflow to quickly set up
driving relationships between one or more properties. It's aimed to help
simplify the steps needed to adjust relative ranges or even non-linear
behavior.
Obviously a one-button solution has limitations such as defining more
complex driving setups (multiple driving objects) or evaluating certain
properties such as colors or strings. But this is beyond the scope of
this add-on.
------------------------------------------------------------------------
Usage:
The Rapid SDK menu item is located in:
Object Mode: Main Menu > Object > Animation > Rapid SDK
Pose Mode: Main Menu > Pose > Animation > Rapid SDK
Rapid SDK is designed to be used on two modes: Creating a driving
relationship and editing an existing driver.
The current selection defines which mode is being used.
Create Mode:
1. Select two or more objects. The last and currently active object acts
as the driver. The state of the selected objects defines the starting
point of the relationship.
2. Run Rapid SDK. This stores the current values. All properties which
are not already driven or animated but change over the course of the
setup will be part of the relationship.
3. Select the driver and modify it to define the end range of the
relationship.
4. Select the driven object or objects and adjust these accordingly.
5. Run Rapid SDK again to finally setup the driver.
Edit Mode:
In contrast to the create mode only one driven object can be edited at a
time. This is a current limitation due to the one-button design of the
add-on.
1. Go to the position where the driven object needs adjustment.
2. Run Rapid SDK. This temporarily disables the drivers so that the
object can be manipulated.
3. Adjust the properties of the driven object.
4. Run Rapid SDK again. This either creates a new keyframe on the
driving curve in case the driving value has changed as well or
existing keyframes on the driver curve will be updated. Also, the driver
curves will get activated again.
If the selection changes while in Edit mode and Rapid SDK is run the
driver curves of the previous object will be activated and the new
object will be put into edit mode.
------------------------------------------------------------------------
Manual command:
from rapidSDK import rapidSDK
rapidSDK.execute()
------------------------------------------------------------------------
Changelog:
0.11.0 - 2023-10-17
- Added compatibility with Blender 4.0.
0.10.0 - 2023-04-23
- Fixed that driving armature properties are not correctly respected
when updating a relationship.
0.9.0 - 2022-05-11
- Added support for object modifiers.
- Added a colored frame to clearly identify create or edit mode.
- Improvements to object/bone selections in object mode.
- Fixed that adding keys outside the defined range are created with
in-between curve handles.
- Fixed that multiple recorded properties create the same number of
drivers per property.
- Fixed that driver indices weren't correctly passed which leads to keys
not getting created.
0.8.1 - 2022-04-05
- Fixed an issue with IDPropertyGroups.
0.8.0 - 2022-04-05
- Switched the stored objects to string representations because of a
bone related undo bug which invalidates the object data and leads to
a hard crash.
0.7.0 - 2022-04-05
- Improvement to the selection detection so that an object can be the
driver for a bone in object mode.
- Fixed an error because custom string properties are not filtered.
- Fixed that already driven shape keys are edited when creating new
drivers.
- Fixed a typo regarding custom properties.
- Fixed an issue where custom properties weren't able to be driven.
0.6.0 - 2022-03-31
- Added an on-screen message which displays the names of the currently
affected objects in create mode.
- The on-screen messages are now scaling correctly depending on the
pixel-size of the display.
- Fixed that the driven object's properties are left muted when leaving
edit mode with nothing selected.
0.5.1 - 2022-03-30
- Fixed an issue where a wrong object/armature/bone selection combo
doesn't throw a warning.
- Fixed that edit mode can be entered without any driven properties
present.
0.5.0 - 2022-03-30
- Added a separate preference setting for intermediate key handles.
- Added a preference setting for choosing the position of the on-screen
message.
0.4.0 - 2022-03-29
- Added an on-screen message for create and edit mode.
- Improved selection detection of hidden bones.
- Possible bugfixes which can lead to random crashes (to be watched)
0.3.0 - 2022-03-29
- Added shape keys on mesh and curve objects to be driven.
- Added a menu item to the Object and Pose Animation submenu.
- Added preferences for the extrapolation, tangent type and tolerance.
0.2.0 - 2022-03-26
- Redesign to allow multiple objects to be driven in creation mode.
0.1.0 - 2022-03-24
------------------------------------------------------------------------
"""
bl_info = {"name": "Rapid SDK",
"author": "Ingo Clemens",
"version": (0, 11, 0),
"blender": (2, 93, 0),
"category": "Animation",
"location": "Main Menu > Object/Pose > Animation > Rapid SDK",
"description": "Quickly create driving relationships between properties",
"warning": "",
"doc_url": "https://github.com/IngoClemens/blender/wiki/Rapid-SDK",
"tracker_url": ""}
import blf
import bpy
import gpu
from gpu_extras.batch import batch_for_shader
import idprop
import copy
import math
from mathutils import Euler, Quaternion, Vector
import re
NAME = "rapidSDK"
EXTRAPOLATION = False
RANGE_KEY_HANDLES = 'VECTOR'
MID_KEY_HANDLES = 'AUTO_CLAMPED'
TOLERANCE = 0.000001
MESSAGE_POSITION = 'TOP'
MESSAGE_COLOR = (0.263, 0.723, 0.0) # (0.545, 0.863, 0.0)
BORDER_WIDTH = 2
SEPARATOR = "::"
POSEBONE = "POSEBONE"
OBJECT = "OBJECT"
SHAPEKEY = "SHAPEKEY"
DEFAULT_PROPS = ["location", "rotation_euler", "rotation_quaternion", "rotation_axis_angle", "scale", "key_blocks", "modifiers"]
ANN_OUTSIDE = "Enable the extrapolation for the generated driver curves"
ANN_RANGE_HANDLES = "The default handle type for the driver's start and end keyframe points"
ANN_MID_HANDLES = "The default handle type for the driver's intermediate keyframe points"
ANN_TOLERANCE = "The minimum difference a value needs to be captured as a driver key. Default: {}".format(TOLERANCE)
ANN_MESSAGE_POSITION = "The position of the on-screen message when in create or edit mode"
ANN_MESSAGE_COLOR = "Display color for the on-screen message when in create or edit mode (not gamma corrected)"
ANN_BORDER_WIDTH = "The width of the colored frame when in create or edit mode."
# Version specific vars.
SHADER_TYPE = 'UNIFORM_COLOR'
if bpy.app.version < (3, 4, 0):
SHADER_TYPE = '2D_UNIFORM_COLOR'
def getViewSize():
"""Return the size of the 3d view exclusive the header area.
:return: The size of the 3d view in pixels.
:rtype: tuple(int, int)
"""
size = None
header = 0
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for region in area.regions:
if region.type == 'WINDOW':
size = (region.width, region.height)
elif region.type == 'HEADER':
header += region.height
elif region.type == 'TOOL_HEADER':
header += region.height
return size[0], size[1]-header
class DrawInfo3D(object):
"""Class for drawing the status info during create and edit.
"""
def __init__(self):
"""Variable initialization.
"""
self.msg = ""
self.handle = None
self.driver = None
self.driven = None
def drawCallback(self, context):
"""Callback for drawing the info message.
:param context: The current context.
:type context: bpy.context
"""
fontId = 0
# The font size and positioning depends on the system's pixel
# size.
pixelSize = bpy.context.preferences.system.pixel_size
# Get the size of the 3d view to be able to place the text
# correctly.
viewWidth, viewHeight = getViewSize()
color = getPreferences().message_color_value
# Gamma-correct the color.
color = [pow(c, 0.454) for c in color]
pos = getPreferences().message_position_value
textPos = viewHeight
if pos == 'TOP':
textPos = textPos - 20 * pixelSize
else:
textPos = 18 * pixelSize
fontSize = 11 * pixelSize
textWidth, textHeight = blf.dimensions(fontId, self.msg)
# Draw the message in the center at the top or bottom of the
# screen.
blf.position(fontId, viewWidth / 2 - textWidth / 2, textPos, 0)
blf.size(fontId, int(fontSize))
blf.color(fontId, color[0], color[1], color[2], 1.0)
blf.draw(fontId, self.msg)
# Draw the name of the objects in the lower left corner of the
# screen.
if len(self.driven):
lines = ["Driver:", self.driver, "", "Driven:"]
lines.extend(self.driven)
lineHeight = fontSize * 1.45
xPos = 20 * pixelSize
yPos = 20 * pixelSize
for i in reversed(range(len(lines))):
blf.position(fontId, xPos, yPos, 0)
blf.draw(fontId, lines[i])
yPos += lineHeight
# Draw the frame.
# https://docs.blender.org/api/blender2.8/gpu.html?highlight=gpu#module-gpu
border = getPreferences().border_width_value * pixelSize
viewWidth -= 20 * pixelSize
vertices = ((1, 1), (viewWidth, 1), (viewWidth, 1+border), (1, 1+border),
(viewWidth, viewHeight), (viewWidth-border, viewHeight), (viewWidth-border, 1),
(1, viewHeight), (1, viewHeight-border), (viewWidth, viewHeight-border),
(1+border, 1), (1+border, viewHeight))
indices = ((0, 1, 2), (0, 2, 3),
(1, 4, 5), (1, 5, 6),
(4, 7, 8), (4, 8, 9),
(7, 0, 10), (7, 10, 11))
shader = gpu.shader.from_builtin(SHADER_TYPE)
batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices)
shader.bind()
shader.uniform_float("color", (color[0], color[1], color[2], 1.0))
batch.draw(shader)
def add(self, message="", driver="", driven=None):
"""Add the message to the 3d view and store the handler for
later removal.
:param message: The message to display on screen.
:type message: str
:param driver: The name of the driver to display.
:type driver: str
:param driven: The list of object names for the driven to
display.
:type driven: str
"""
if driven is None:
driven = []
self.msg = message
self.driver = driver
self.driven = driven
self.handle = bpy.types.SpaceView3D.draw_handler_add(self.drawCallback,
(bpy.context,),
'WINDOW',
'POST_PIXEL')
self.updateView()
def remove(self):
"""Remove the message from the 3d view.
"""
if self.handle:
bpy.types.SpaceView3D.draw_handler_remove(self.handle, 'WINDOW')
self.handle = None
self.updateView()
def updateView(self):
"""Force a redraw of the current 3d view.
"""
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for region in area.regions:
if region.type == 'WINDOW':
region.tag_redraw()
# Global instance.
drawInfo3d = DrawInfo3D()
class RapidSDK(object):
"""Class managing the set driven key creation.
"""
def __init__(self):
"""Variable initialization.
"""
self.driver = None
self.driven = None
self.driverBase = {}
self.driverCurrent = {}
self.drivenBase = {}
self.drivenCurrent = {}
self.createMode = False
self.editMode = False
def execute(self):
"""Store the state of the current selection or create the driver
setup based on the number of selected objects.
"""
# Get the current selection.
objects = objectToString(selectedObjects())
active = objectToString(selectedObjects(active=True))
if len(objects) and not active:
drawInfo3d.remove()
return {'WARNING'}, "No driving object selected"
# --------------------------------------------------------------
# Initiate
# --------------------------------------------------------------
# With two or more objects selected a new process gets started.
if len(objects) > 1 and not self.createMode:
self.createMode = True
# Remove the active object from the list, which then only
# contains driven objects.
objects.remove(active)
self.driver = active
self.driven = objects
# Get and store the current values as the driving base.
self.driverBase = getCurrentValues(self.driver)[self.driver]
self.drivenBase = getCurrentValues(self.driven)
# ----------------------------------------------------------
# Messages
# ----------------------------------------------------------
drivenMsg = ""
if len(self.driven) > 1:
drivenMsg = " (+ {} more)".format(len(self.driven)-1)
driverName = stringToObject(self.driver).name
drivenNames = [d.name for d in stringToObject(self.driven)]
drawInfo3d.add("Record SDK", driverName, drivenNames)
return {'INFO'}, "Starting driver setup: {} -> {}{}".format(driverName,
drivenNames[0],
drivenMsg)
# --------------------------------------------------------------
# Create the driver
# --------------------------------------------------------------
# If only one object is selected setup the driver.
elif self.createMode:
self.createMode = False
drawInfo3d.remove()
# Get the modified values to compare with the original.
self.driverCurrent = getCurrentValues(self.driver)[self.driver]
self.drivenCurrent = getCurrentValues(self.driven)
# Get the properties for the driver and driven object which
# have been modified.
driverData = self.getDrivingProperty()
drivenData = self.getDrivenProperty(create=True)
# Check what can be used for the driver setup.
if not len(driverData):
return {'WARNING'}, "No driving properties changed or are already driving the target"
if not len(drivenData):
return {'WARNING'}, "No driven properties changed or are already been driven by the target"
# Create the driving relationship.
setupDriver(stringToObject(self.driver), driverData, drivenData)
msg = "object" if len(self.driven) == 1 else "objects"
return {'INFO'}, "Created driver for {} {}".format(len(self.driven), msg)
# --------------------------------------------------------------
# Edit mode
# --------------------------------------------------------------
elif len(objects) == 1 and not self.createMode:
# A special case of selection which mostly happens with mesh
# and bone selections in object mode.
# For example, the driving bone can be selected in the
# outliner but it's icon is not highlighted. Though the
# armature is selected and the icon highlighted.
# As a result of the selection filter there's only the mesh
# in the list of selected objects but the active selection
# is the armature.
# But when editing the driver the selection and active
# object needs to match.
if active not in objects:
return {'WARNING'}, "Selection inconclusive. Please check your selection"
# ----------------------------------------------------------
# Enter edit
# ----------------------------------------------------------
if not self.editMode:
message = self.initEdit(active)
if not message:
name = active.split(SEPARATOR)[-1]
drawInfo3d.add("Edit SDK: {}".format(name))
return {'INFO'}, "Editing driver for {}".format(name)
else:
return message
# ----------------------------------------------------------
# Exit edit
# ----------------------------------------------------------
elif self.editMode:
drawInfo3d.remove()
# Even if there's only one driven object in edit mode
# the driven is still a list for consistency.
if active == self.driven[0]:
self.editMode = False
# Get the modified values to compare with the
# original.
self.drivenCurrent = getCurrentValues(self.driven)
# Get the properties which have been modified.
drivenData = self.getDrivenProperty(create=False)
if drivenData:
insertKey(self.driven[0], drivenData[self.driven[0]])
obj = stringToObject(self.driven[0])
message = {'INFO'}, "Updating driver curves for {}".format(obj.name)
else:
message = {'INFO'}, "Editing cancelled without any changes"
# Enable the driver animation curves.
setAnimationCurvesState(stringToObject(self.driven[0]), True)
return message
# If the current object is not the last edited driven
# object reset the last driven and start a new edit.
else:
return self.resetDriverState(self.driven)
# --------------------------------------------------------------
# Reset the last driven objects
# --------------------------------------------------------------
# If nothing is selected reset the muted driver state for the
# last driven object.
elif not len(objects):
drawInfo3d.remove()
if self.driven:
return self.resetDriverState(self.driven)
else:
return {'WARNING'}, "No driven objects selected"
def getDrivingProperty(self):
"""Find which properties have been changed for the driver and
filter all which cannot be used because they are already driving
other properties of the same object.
:return: A list with a list of values which can be used for
driving. Each item contains a list with the property,
the index and a tuple with the start and end values.
:rtype: list(list(str, int, tuple(float, float)))
"""
result = []
# Compare which values have been changed.
for key in self.driverCurrent.keys():
value = self.driverCurrent[key]
# In case of list-type properties the values need to be
# extracted individually.
if isinstance(value, (Euler, Quaternion, Vector, list, tuple,
idprop.types.IDPropertyArray)):
for i in range(len(value)):
baseValue = self.driverBase[key][i]
if not isClose(value[i], baseValue):
result.append([key, i, (baseValue, value[i])])
# Skip the rotation mode key.
elif isinstance(value, str):
pass
# Single-value properties.
elif key not in ["shapeKeys", "modifiers"]:
baseValue = self.driverBase[key]
if not isClose(value, baseValue):
result.append([key, -1, (baseValue, value)])
# Shape keys.
# Example:
# {'shapeKeys': {'Key': {'Basis': 0.0, 'smile': 0.0}}}
elif key == "shapeKeys" and value is not None:
name = list(value.keys())[0]
for k in value[name].keys():
val = value[name][k]
baseValue = self.driverBase["shapeKeys"][name][k]
if not isClose(val, baseValue):
keyId = bpy.data.shape_keys[name]
src = {"shapeKeys": {"keyId": keyId, "name": k, "prop": "value"}}
result.append([src, -1, (baseValue, val)])
# Modifiers
# Example:
# {'GeometryNodes': {'Input_3': 0.1, 'Input_4': 180.0}}
elif key == "modifiers" and value is not None:
for mod in value.keys():
for attr in value[mod].keys():
val = value[mod][attr]
baseValue = self.driverBase["modifiers"][mod][attr]
if isinstance(val, (idprop.types.IDPropertyArray, list)):
for i in range(len(val)):
if not isClose(val[i], baseValue[i]):
src = {"modifier": {"name": mod, "prop": attr}}
result.append([src, i, (baseValue[i], val[i])])
else:
if not isClose(val, baseValue):
src = {"modifier": {"name": mod, "prop": attr}}
result.append([src, -1, (baseValue, val)])
return result
def getDrivenProperty(self, create=True):
"""Find which properties have been changed for the driven and
filter all which cannot be used because they are already driven
or have animation.
:param create: True, if a new driver setup should be created and
therefore existing driven properties should be
excluded.
False, to include driven properties when editing.
:type create: bool
:return: A list with a list of values which can be used for
being driven. Each item contains a list with the
property, the index and a tuple with the start and end
values.
The list is stored as the value with the object as the
key.
:rtype: dict(list(list(str, int, tuple(float, float))))
"""
result = {}
for obj in self.driven:
result[obj] = self.getDrivenPropertyForObject(obj, create)
return result
def getDrivenPropertyForObject(self, obj, create):
"""Find which properties have been changed for the driven and
filter all which cannot be used because they are already driven
or have animation.
:param obj: The name of the object to query.
:type obj: str
:param create: True, if a new driver setup should be created and
therefore existing driven properties should be
excluded.
False, to include driven properties when editing.
:type create: bool
:return: A list with a list of values which can be used for
being driven. Each item contains a list with the
property, the index and a tuple with the start and end
values.
:rtype: list(list(str, int, tuple(float, float)))
"""
drivenData = getDriver(obj)
props = []
# Compare which values have been changed.
for key in self.drivenCurrent[obj].keys():
value = self.drivenCurrent[obj][key]
# In case of list-type properties the values need to be
# extracted individually.
if isinstance(value, (Euler, Quaternion, Vector, list, tuple,
idprop.types.IDPropertyArray)):
for i in range(len(value)):
baseValue = self.drivenBase[obj][key][i]
if not isClose(value[i], baseValue):
# Check, if the current value is already the
# target of a driving relationship.
if propertyIsAvailable(obj, drivenData, key, i, create):
props.append([key, i, (baseValue, value[i])])
# Single-value properties.
elif key not in ["shapeKeys", "modifiers"]:
baseValue = self.drivenBase[obj][key]
if not isClose(value, baseValue):
# Check, if the current value is already the target
# of a driving relationship.
if propertyIsAvailable(obj, drivenData, key, -1, create):
props.append([key, -1, (baseValue, value)])
# Shape keys.
# Example:
# {'shapeKeys': {'Key': {'Basis': 0.0, 'smile': 0.0}}}
elif key == "shapeKeys" and value is not None:
name = list(value.keys())[0]
for k in value[name].keys():
val = value[name][k]
baseValue = self.drivenBase[obj]["shapeKeys"][name][k]
if not isClose(val, baseValue):
# To query the availability of a shape key the
# shape key data block needs to be passed as the
# object.
if propertyIsAvailable(bpy.data.shape_keys[name],
drivenData,
k,
-1,
create):
keyId = bpy.data.shape_keys[name]
tgt = {"shapeKeys": {"keyId": keyId, "name": k, "prop": "value"}}
props.append([tgt, -1, (baseValue, val)])
# Modifiers
# Example:
# {'GeometryNodes': {'Input_3': 0.1, 'Input_4': 180.0}}
elif key == "modifiers" and value is not None:
for mod in value.keys():
for attr in value[mod].keys():
val = value[mod][attr]
baseValue = self.drivenBase[obj]["modifiers"][mod][attr]
if isinstance(val, (idprop.types.IDPropertyArray, list)):
for i in range(len(val)):
if not isClose(val[i], baseValue[i]):
# Check, if the current value is
# already the target of a driving
# relationship.
if propertyIsAvailable(obj, drivenData, (mod, attr), i, create):
tgt = {"modifier": {"name": mod, "prop": attr}}
props.append([tgt, i, (baseValue[i], val[i])])
else:
if not isClose(val, baseValue):
if propertyIsAvailable(obj, drivenData, (mod, attr), -1, create):
tgt = {"modifier": {"name": mod, "prop": attr}}
props.append([tgt, -1, (baseValue, val)])
return props
def initEdit(self, obj):
"""Enter edit mode by disabling the driver curves and getting
the current values of the driven object.
:param obj: The name of the object to edit.
:type obj: str
:return: The info message about the reset.
:rtype: tuple(str, str)
"""
# Disable the driver animation curves.
objInst = stringToObject(obj)
if not setAnimationCurvesState(objInst, False):
return {'INFO'}, "No drivers to edit for {}".format(objInst.name)
self.editMode = True
# The active object is the driven.
self.driven = [obj]
# Get and store the current values as the driving base.
self.drivenBase = getCurrentValues(self.driven)
def resetDriverState(self, objects):
"""Enable the driver animation curves for the driven objects.
:param objects: The names of the objects to reset the driver
state for.
:type objects: list(bpy.types.Object)
:return: The info message about the reset.
:rtype: tuple(str, str)
"""
names = []
for obj in objects:
obj = stringToObject(obj)
setAnimationCurvesState(obj, True)
names.append(obj.name)
self.driven = None
self.editMode = False
return {'INFO'}, "Reset driver curves for {}".format(", ".join(names))
# Global instance.
rapidSDK = RapidSDK()
def selectedObjects(active=False):
"""Return the currently selected objects. In case of an armature
return the selected bones when in edit or pose mode.
:param active: Return only the currently active object.
:type active: bool
:return: The list of selected objects.
:rtype: bpy.data.objects
"""
sel = []
for obj in bpy.context.selected_objects:
if obj.type == 'ARMATURE':
if bpy.context.object.mode == 'POSE':
if active:
activeBone = bpy.context.active_pose_bone
if not activeBone:
bones = selectedBones(obj)
poseBones = bpy.context.selected_pose_bones
for b in bones:
if b not in poseBones:
return b
else:
return bpy.context.active_pose_bone
else:
sel.extend(selectedBones(obj))
elif bpy.context.object.mode == 'EDIT':
if active:
return bpy.context.active_bone
else:
sel.extend(bpy.context.selected_bones)
else:
bones = selectedBones(obj)
if active:
if bpy.context.active_object == obj:
if len(bones) and bpy.context.active_object == obj:
return bones[0]
else:
return obj
else:
if len(bones):
sel.extend(selectedBones(obj))
else:
sel.append(obj)
else:
if active and obj == bpy.context.active_object:
return obj
else:
sel.append(obj)
return sel
def selectedBones(armature):
"""Get a list of all selected pose bones from the given armature
object even if they are hidden.
:param armature: The armature object.
:type armature: bpy.types.Object
:return: A list with all selected bones.
:rtype: list(bpy.types.PoseBone)
"""
sel = []
for bone in getArmatureData(armature).bones:
if bone.select:
sel.append(armature.pose.bones[bone.name])
return sel
def objectToString(objects):
"""Convert the given object or list of objects to a name string.
In case of a pose bone it's a delimited string of the armature name
and the bone name.
:param objects: The object or list of objects to convert.
:type objects: bpy.types.Object or list(bpy.types.Object)
:return: The name or list of names.
:rtype: str or list(str)
"""
isArray = True
if not isinstance(objects, list):
isArray = False
objects = [objects]
items = []
for obj in objects:
if isinstance(obj, bpy.types.PoseBone):
items.append(SEPARATOR.join([POSEBONE, obj.id_data.name, obj.name]))
elif isinstance(obj, bpy.types.Key):
items.append(SEPARATOR.join([SHAPEKEY, obj.name]))
else:
items.append(SEPARATOR.join([OBJECT, obj.name]))
if not isArray and len(items):
return items[0]
return items
def stringToObject(names):
"""Return the given name or list of names to objects.
:param names: The name or list of object names.
:type names: str or list(str)
:return: The object or list of objects.
:rtype: bpy.types.Object or list(bpy.types.Object)
"""
isArray = True
if not isinstance(names, list):
isArray = False
names = [names]
items = []
for name in names:
elements = name.split(SEPARATOR)
if len(elements):
if len(elements) > 2:
items.append(bpy.data.objects[elements[1]].pose.bones[elements[2]])
else:
if elements[0] == OBJECT:
items.append(bpy.data.objects[elements[1]])
elif elements[0] == SHAPEKEY:
items.append(obj.data.shape_keys[elements[1]])
if not isArray and len(items):
return items[0]
return items
def getArmatureData(obj):
"""Return the armature data block which is used by the given
armature object.
:param obj: The armature object.
:type obj: bpy.types.Object
:return: The armature data block.
:rtype: bpy.data.Armature
"""
for i in range(len(bpy.data.armatures)):
if obj.user_of_id(bpy.data.armatures[i]):
return bpy.data.armatures[i]
def getCurrentValues(objects):
"""Return a dictionary with all properties and their current values
of the given object, wrapped in a dictionary with the object as the
key and the data as its value.
:param objects: The object names to get the data from.
:type objects: str or list(str)
:return: A dictionary with all properties as keys and their values
for each object.
:rtype: dict(dict())
"""
if not isinstance(objects, list):
objects = [objects]
allData = {}
for i in range(len(objects)):
# Convert the name to an object.
obj = stringToObject(objects[i])
data = {}
# --------------------------------------------------------------
# bpy.types.Object
# --------------------------------------------------------------
if not isinstance(obj, bpy.types.Key):
data["location"] = obj.location
if obj.rotation_mode == 'AXIS_ANGLE':
values = obj.rotation_axis_angle
data["rotation_axis_angle"] = (values[0], values[1], values[2], values[3])
elif obj.rotation_mode == 'QUATERNION':
data["rotation_quaternion"] = obj.rotation_quaternion
else:
data["rotation_euler"] = obj.rotation_euler
data["scale"] = obj.scale
# Get the custom properties.
for prop in customProperties(obj):
value = obj.get(prop)
if isinstance(value, idprop.types.IDPropertyArray):
data[prop] = [i for i in value]
else:
data[prop] = value
# Get the shape keys for meshes and curves.
data["shapeKeys"] = getShapeKeys(obj)
# Get the modifiers.
data["modifiers"] = getModifierProperties(obj)[obj]
# --------------------------------------------------------------
# bpy.types.Key
# --------------------------------------------------------------
# If the given object is a shapes key only the shapes and their
# values are of importance. This is only the case when querying
# the current driver values for inserting a new key. Therefore
# the result is different from getting the values upon
# initializing.
else:
for block in obj.key_blocks:
data[block.name] = block.value
# The key for the data set is not the object but the string
# representation.
allData[objects[i]] = copy.deepcopy(data)
return allData
def customProperties(obj):
"""Return a list with the custom properties of the given object.
:param obj: The object to get the properties from.
:type obj: bpy.types.Object
:return: The list with the custom properties.
:rtype: list(str)
"""
props = []
for prop in obj.keys():
if prop not in '_RNA_UI' and isinstance(obj[prop], (int, float, list)):
props.append(prop)
return props
def hasShapeKeys(obj):
"""Return, if the given object has shape keys.
:param obj: The object to query.
:type obj: bpy.types.Object
:return: True, if the object has shape keys.
:rtype: bool
"""
if obj.id_data.type in ['MESH', 'CURVE']:
return True if obj.data.shape_keys else False
else:
return False
def shapeKeyName(obj):
"""Return the name of the shape key data block if the object has
shape keys.