2025-12-01

This commit is contained in:
2026-03-17 14:58:51 -06:00
parent 183e865f8b
commit 4b82b57113
6846 changed files with 954887 additions and 162606 deletions
+42 -19
View File
@@ -20,11 +20,10 @@
bl_info = {
"name": "Animation Layers",
"author": "Tal Hershkovich",
"version" : (2, 1, 8, 8),
"version" : (2, 3, 4),
"blender" : (3, 2, 0),
"location": "View3D - Properties - Animation Panel",
"description": "Simplifying the NLA editor into an animation layers UI and workflow",
#"warning": "New Branch of Animation Layers, Do not use below Blender v3.2",
"wiki_url": "",
"category": "Animation"}
@@ -66,7 +65,11 @@ class AnimLayersSceneSettings(bpy.types.PropertyGroup):
]
)
viewlayer_objects: bpy.props.IntProperty(name='View Layer Objects', description='checking if objects were turned on or off from the view Layers', default=0)
influence: bpy.props.FloatProperty(name="Layer Influence", description="Layer Influence", min = 0.0, options={'ANIMATABLE'}, max = 1.0, default = 1.0, precision = 3, update = anim_layers.influence_update)
influence_settings: bpy.props.BoolProperty(name="Influence Settings", description="Opens Influence settings menu", default=False)
influence_global: bpy.props.BoolProperty(name="Influence Global/Local", description="Influence options affect current layer or all layers", default=False)
edit_all_layers_op: bpy.props.BoolProperty(name="Edit All Layers Check Property", description="Operator to check if edit all layers is running", default=False)
class AnimLayersSettings(bpy.types.PropertyGroup):
turn_on: bpy.props.BoolProperty(name="Turn Animation Layers On", description="Turn on and start Animation Layers", default=False, options={'HIDDEN'}, update = anim_layers.turn_animlayers_on, override = {'LIBRARY_OVERRIDABLE'})
@@ -75,7 +78,7 @@ class AnimLayersSettings(bpy.types.PropertyGroup):
#Bake settings
smartbake: bpy.props.BoolProperty(name="Smart Bake", description="Stay with the same amount of keyframes after merging and baking", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
onlyselected: bpy.props.BoolProperty(name="Only selected Bones", description="Bake only selected Armature controls", default=True, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
onlyselected: bpy.props.BoolProperty(name="Only selected Bones", description="Bake only selected Armature controls", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
clearconstraints: bpy.props.BoolProperty(name="Clear constraints", description="Clear constraints during bake", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
mergefcurves: bpy.props.BoolProperty(name="Merge Cyclic & Fcurve modifiers", description="Include Fcurve modifiers in the bake", default = True, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
@@ -102,22 +105,27 @@ class AnimLayersSettings(bpy.types.PropertyGroup):
auto_blend: bpy.props.BoolProperty(name="Auto Blend", description="Apply blend type automatically based on scale and rotation values", default = False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
fcurves: bpy.props.IntProperty(name='fcurves', description='helper to check if fcurves are changed', default=0, override = {'LIBRARY_OVERRIDABLE'})
upper_stack : bpy.props.BoolProperty(name="Upper Stack Evaluation", description="Checks if tweak mode uses upper stack", default=False, override = {'LIBRARY_OVERRIDABLE'})
viewlayer : bpy.props.BoolProperty(name="View Layer Exclusion", description="Check if the object was added or removed from the view layer", default=True, override = {'LIBRARY_OVERRIDABLE'})
#tools
#Tools
inbetweener : bpy.props.FloatProperty(name='Inbetween Keyframe', description="Adds an inbetween Keyframe between the Layer's neighbor keyframes", soft_min = 0, soft_max = 1, default=0.5, options = set(), override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.add_inbetween_key)
share_layer_keys: bpy.props.EnumProperty(name = 'Share Layer Keys', description="Share keyframes positions between layers", items = anim_layers.share_layerkeys_items, override = {'LIBRARY_OVERRIDABLE'})
influence_hide: bpy.props.BoolProperty(name="Hide Influence", description="Hide Influence Fcurves", default=False, update = anim_layers.influence_hide_keyframes, override = {'LIBRARY_OVERRIDABLE'})
influence_lock: bpy.props.BoolProperty(name="Lock Influence", description="Lock Influence Fcurves", default=False, update = anim_layers.influence_lock_keyframes, override = {'LIBRARY_OVERRIDABLE'})
influence_mute: bpy.props.BoolProperty(name="Mute Influence", description="Mute Influence Fcurves", default=False, update = anim_layers.influence_mute_fcurves, override = {'LIBRARY_OVERRIDABLE'})
class AnimLayersItems(bpy.types.PropertyGroup):
name: bpy.props.StringProperty(name="AnimLayer", override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_name_update)
mute: bpy.props.BoolProperty(name="Mute", description="Mute Animation Layer", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_mute)
lock: bpy.props.BoolProperty(name="Lock", description="Lock Animation Layer", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_lock)
solo: bpy.props.BoolProperty(name="Solo", description="Solo Animation Layer", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_solo)
influence: bpy.props.FloatProperty(name="Layer Influence", description="Layer Influence", min = 0.0, options={'ANIMATABLE'}, max = 1.0, default = 1.0, precision = 3, update = anim_layers.influence_update, override = {'LIBRARY_OVERRIDABLE'})
influence_mute: bpy.props.BoolProperty(name="Animated Influence", description="Turn Animated influence On/Off", default=False, options={'HIDDEN'}, update = anim_layers.influence_mute_update, override = {'LIBRARY_OVERRIDABLE'})
#action_list: bpy.props.EnumProperty(name = 'Actions', description = "Select action", update = anim_layers.load_action, items = anim_layers.action_items, override = {'LIBRARY_OVERRIDABLE'})
influence: bpy.props.FloatProperty(name="Layer Influence", description="Layer Influence", min = 0.0, options={'ANIMATABLE'}, max = 1.0, default = 1.0, precision = 3, update = anim_layers.influence_update) #
action: bpy.props.PointerProperty(name = 'action', description = "Select action", type=bpy.types.Action, update = anim_layers.load_action, override = {'LIBRARY_OVERRIDABLE'})
action_range: bpy.props.FloatVectorProperty(name='action range', description="used to check if layer needs to update frame range", override = {'LIBRARY_OVERRIDABLE'}, size = 2)
frame_range: bpy.props.BoolProperty(name="Custom Frame Range", description="Use a custom frame range per layer instead of the scene frame range", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_frame_range)
custom_frame_range: bpy.props.BoolProperty(name="Custom Frame Range", description="Use a custom frame range per layer instead of the scene frame range", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_frame_range)
frame_start: bpy.props.FloatProperty(name='Action Start Frame', description="First frame of the layer's action",min = 0, default=0, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_frame_start)
frame_end: bpy.props.FloatProperty(name='Action End Frame', description="End frame of the layer's action", default=0, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_frame_end)
speed: bpy.props.FloatProperty(name='Speed of the action', description="Speed of the action strip", default = 1, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_speed)
@@ -129,12 +137,15 @@ class AnimLayersObjects(bpy.types.PropertyGroup):
object: bpy.props.PointerProperty(name = "object", description = "objects with animation layers turned on", type=bpy.types.Object, override = {'LIBRARY_OVERRIDABLE'})
# Add-ons Preferences Update Panel
# Define Panel classes for updating
panels = (anim_layers.ANIMLAYERS_PT_List, anim_layers.ANIMLAYERS_PT_Ops, anim_layers.ANIMLAYERS_PT_Tools, anim_layers.ANIMLAYERS_PT_Settings) #anim_layers.ANIMLAYERS_PT_Panel, anim_layers.ANIMLAYERS_PT_Multikey,
panels = anim_layers.panel_classes
def update_panel(self, context):
anim_layers.unregister_panels()
anim_layers.register_panels()
message = "AnimationLayers: Updating Panel locations has failed"
try:
for panel in panels:
@@ -165,6 +176,8 @@ class AnimLayersAddonPreferences(bpy.types.AddonPreferences):
items = [('ANIMLAYERS', 'Anim Layers Settings', 'Use Anim Layers properties to adjust custom frame range'),
('NLA', 'NLA Settings', 'Use the nla properties to adjust custom frame range')])
lock_nlatracks: bpy.props.BoolProperty(name="Automatically lock the nla tracks for safety measures", description="Automatically lock nla tracks when creating layers for safety", default = True)
#Property for ClearActiveAction
proceed: bpy.props.EnumProperty(name="Choose how to proceed", description="Select an option how to proceed with Anim Layers", override = {'LIBRARY_OVERRIDABLE'},
items = [
@@ -172,6 +185,15 @@ class AnimLayersAddonPreferences(bpy.types.AddonPreferences):
( 'REMOVE_ACTION', 'Remove current action and reload older Layers', 'Remove current action and continue with the previous layers', 1),
('ADD_ACTION', 'Add the current action as a new Layer', 'Keep previous Anim Layers and Add the active action as a new layer', 2),])
enabled_editors: bpy.props.EnumProperty(
name="Enabled Editors",
description="Select which editors should show animation layers panels",
items=[('VIEW_3D', "3D View", ""), ('GRAPH_EDITOR', "Graph Editor", ""), ('DOPESHEET_EDITOR', "Dope Sheet", ""),('NLA_EDITOR', "NLA Editor", ""),],
options={'ENUM_FLAG'},
default={'VIEW_3D', 'NLA_EDITOR', 'DOPESHEET_EDITOR', 'GRAPH_EDITOR'},
update=update_panel
)
category: bpy.props.StringProperty(
name="Tab Category",
description="Choose a name for the category of the panel",
@@ -183,7 +205,7 @@ class AnimLayersAddonPreferences(bpy.types.AddonPreferences):
auto_check_update: bpy.props.BoolProperty(
name = "Auto-check for Update",
description = "If enabled, auto-check for updates using an interval",
default = False,
default = True,
)
updater_interval_months: bpy.props.IntProperty(
@@ -222,14 +244,14 @@ class AnimLayersAddonPreferences(bpy.types.AddonPreferences):
col.label(text="Tab Category:")
col.prop(self, "category", text="")
row = layout.row()
row.prop(self, "enabled_editors")
col = layout.column()
col.separator(factor = 1)
col = col.box()
col.label(text="Defaults:")
#row = layout.row()
split = col.split(factor=0.5, align = True)
split.prop(self, "auto_rename")
#row.prop(self, "blend_type")
#split = row.split(factor=0.7, align = True)
split.label(text="Default Blend Type: ")
split.prop(self,'blend_type', text = '')
@@ -237,11 +259,12 @@ class AnimLayersAddonPreferences(bpy.types.AddonPreferences):
row = col.row()
row.label(text = "Custom Frame Range Settings")
row.prop(self, "frame_range_settings", text = '')
#row = layout.row(align = True)
#col = layout.row(bpy.context.scene.als,'blend_type', text = '')
col.prop(self, "lock_nlatracks")
classes = (AnimLayersSettings, AnimLayersSceneSettings, AnimLayersItems, AnimLayersObjects)
addon_keymaps = []
def register():
@@ -1374,9 +1374,9 @@ def register(bl_info):
# **WARNING** Depending on the engine, this token can act like a password!!
# Only provide a token if the project is *non-public*, see readme for
# other considerations and suggestions from a security standpoint
# updater.private_token = "kgsE5RsxTzDvQRs9P_Yg" # "tokenstring"
updater.private_token = "glpat-K6GjFFka_J6o3GTbe3JK"
# "tokenstring" Need read api and read repo permission
# updater.private_token = "glpat-K6GjFFka_J6o3GTbe3JK"
updater.private_token = "glpat-js__ikigVSQ_tKWgjVn1"
# choose your own username, must match website (not needed for GitLab)
updater.user = ""
@@ -1508,7 +1508,7 @@ def register(bl_info):
# max install (<) will install strictly anything lower
# updater.version_max_update = (9,9,9)
updater.version_max_update = (2,1,8,7) # set to None if not wanting to set max
updater.version_max_update = None # set to None if not wanting to set max
# Function defined above, customize as appropriate per repository
updater.skip_tag = skip_tag_function # min and max used in this function
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,5 @@
{
"last_check": "2025-05-28 13:56:15.908215",
"last_check": "2025-11-26 10:56:41.294043",
"backup_date": "",
"update_ready": false,
"ignore": false,
@@ -1,311 +0,0 @@
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# 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 2
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****
bl_info = {
"name": "Animation Layers",
"author": "Tal Hershkovich",
"version" : (2, 1, 9, 7),
"blender" : (3, 2, 0),
"location": "View3D - Properties - Animation Panel",
"description": "Simplifying the NLA editor into an animation layers UI and workflow",
"wiki_url": "",
"category": "Animation"}
if "bpy" in locals():
import importlib
if "bake_ops" in locals():
importlib.reload(bake_ops)
if "anim_layers" in locals():
print('reloading anim layers')
importlib.reload(anim_layers)
if "subscriptions" in locals():
importlib.reload(subscriptions)
if "multikey" in locals():
importlib.reload(multikey)
if "addon_updater_ops" in locals():
importlib.reload(addon_updater_ops)
import bpy
from . import addon_updater_ops
from . import anim_layers
from . import bake_ops
from . import subscriptions
from . import multikey
from bpy.utils import register_class
from bpy.utils import unregister_class
class AnimLayersSceneSettings(bpy.types.PropertyGroup):
bake_range_type: bpy.props.EnumProperty(name = 'Bake Range', description="Use either scene, actions length or custom frame range", default = 'SCENE', update = bake_ops.bake_range_type,
items = [('SCENE', 'Scene Range', 'Bake to the scene range'), ('KEYFRAMES', 'Keyframes Range', 'Bake all the keyframes in the layers'), ('CUSTOM', 'Custom', 'Enter a custom frame range')], override = {'LIBRARY_OVERRIDABLE'})
bake_range: bpy.props.IntVectorProperty(name='Frame Range', description='Bake to a custom frame range', size = 2)
handles_type: bpy.props.EnumProperty(name="Handle Types", description="Select handle type before recalculating the handle values", override = {'LIBRARY_OVERRIDABLE'}, default = 'FREE',
items = [
('PRESERVE', 'Preserve', 'Preserves previous Bezier handlers types before recalculation', 0),
( 'FREE', 'Free', 'Bezier handlers get Free handle types before recalculation', 1),
('ALIGNED', 'Aligned', 'Bezier handlers get Aligned handle types before recalculation', 2),
('VECTOR','Vector', 'Bezier handlers get Vector handle types', 3),
('AUTO', 'Auto', 'Bezier handlers get Auto handle types before recalculation',4),
('AUTO_CLAMPED', 'Auto Clamped', 'Bezier handlers get Free handle types before recalculation', 5)
]
)
class AnimLayersSettings(bpy.types.PropertyGroup):
turn_on: bpy.props.BoolProperty(name="Turn Animation Layers On", description="Turn on and start Animation Layers", default=False, options={'HIDDEN'}, update = anim_layers.turn_animlayers_on, override = {'LIBRARY_OVERRIDABLE'})
layer_index: bpy.props.IntProperty(update = anim_layers.update_layer_index, options={'LIBRARY_EDITABLE'}, default = 0, override = {'LIBRARY_OVERRIDABLE'})
linked: bpy.props.BoolProperty(name="Linked", description="Duplicate a layer with a linked action", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
#Bake settings
smartbake: bpy.props.BoolProperty(name="Smart Bake", description="Stay with the same amount of keyframes after merging and baking", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
onlyselected: bpy.props.BoolProperty(name="Only selected Bones", description="Bake only selected Armature controls", default=True, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
clearconstraints: bpy.props.BoolProperty(name="Clear constraints", description="Clear constraints during bake", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
mergefcurves: bpy.props.BoolProperty(name="Merge Cyclic & Fcurve modifiers", description="Include Fcurve modifiers in the bake", default = True, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
view_all_keyframes: bpy.props.BoolProperty(name="View", description="View keyframes from multiple layers, use lock and mute to exclude layers", default=False, update = anim_layers.view_all_keyframes, override = {'LIBRARY_OVERRIDABLE'})
edit_all_keyframes: bpy.props.BoolProperty(name="Edit", description="Edit keyframes from multiple layers", default=False, update = anim_layers.unlock_edit_keyframes, override = {'LIBRARY_OVERRIDABLE'})
only_selected_bones: bpy.props.BoolProperty(name="Only Selected Bones", description="Edit and view only selected bones", default=True, update = anim_layers.only_selected_bones, override = {'LIBRARY_OVERRIDABLE'})
view_all_type: bpy.props.EnumProperty(name="Type", description="Select visibiltiy type of keyframes", update = anim_layers.view_all_keyframes, override = {'LIBRARY_OVERRIDABLE'}, default = '2',
items = [
('0', 'Breakdown', 'select Breakdown visibility'),
('1', 'Jitter', 'select Jitter visibility'),
('2', 'Moving Hold', 'select Moving Hold visibility'),
('3', 'Extreme', 'select Extreme visibility'),
('4', 'Keyframe', 'select Keyframe visibility')
]
)
baketype : bpy.props.EnumProperty(name = '', description="Type of Bake", items = [('AL', 'Anim Layers','Use Animation Layers Bake',0), ('NLA', 'NLA Bake', 'Use Blender internal NLA Bake',1)], override = {'LIBRARY_OVERRIDABLE'})
direction: bpy.props.EnumProperty(name = '', description="Select direction of merge", items = [('UP', 'Up','Merge upwards','TRIA_UP',1), ('DOWN', 'Down', 'Merge downwards','TRIA_DOWN',0), ('ALL', 'All', 'Merge all layers')], override = {'LIBRARY_OVERRIDABLE'})
operator : bpy.props.EnumProperty(name = '', description="Type of bake", items = [('NEW', 'New Baked Layer','Bake into a New Layer','NLA',1), ('MERGE', 'Merge', 'Merge Layers','NLA_PUSHDOWN',0)], override = {'LIBRARY_OVERRIDABLE'})
blend_type : bpy.props.EnumProperty(name = 'Blend Type', description="Blend Type",
items = [('REPLACE', 'Replace', 'Use as a Base Layer'), ('ADD', 'Add', 'Use as an Additive Layer'), ('SUBTRACT', 'Subtract', 'Use as an Subtract Layer')], update = anim_layers.blend_type_update , override = {'LIBRARY_OVERRIDABLE'})
data_type : bpy.props.EnumProperty(name = 'Data Type', description="Select type of action data", default = 'OBJECT', update = anim_layers.data_type_update,
items = [('KEY', 'Shapekey', 'Switch to shapekey animation layers'), ('OBJECT', 'Object', 'Switch to object animation')], override = {'LIBRARY_OVERRIDABLE'})#, update = anim_layers.blend_type_update
auto_rename: bpy.props.BoolProperty(name="Auto Rename Layer", description="Rename layer to match to selected action", default = True, update = anim_layers.auto_rename, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
auto_blend: bpy.props.BoolProperty(name="Auto Blend", description="Apply blend type automatically based on scale and rotation values", default = False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'})
fcurves: bpy.props.IntProperty(name='fcurves', description='helper to check if fcurves are changed', default=0, override = {'LIBRARY_OVERRIDABLE'})
upper_stack : bpy.props.BoolProperty(name="Upper Stack Evaluation", description="Checks if tweak mode uses upper stack", default=False, override = {'LIBRARY_OVERRIDABLE'})
#Tools
inbetweener : bpy.props.FloatProperty(name='Inbetween Keyframe', description="Adds an inbetween Keyframe between the Layer's neighbor keyframes", soft_min = 0, soft_max = 1, default=0.5, options = set(), override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.add_inbetween_key)
share_layer_keys: bpy.props.EnumProperty(name = 'Share Layer Keys', description="Share keyframes positions between layers", items = anim_layers.share_layerkeys_items, override = {'LIBRARY_OVERRIDABLE'})
class AnimLayersItems(bpy.types.PropertyGroup):
name: bpy.props.StringProperty(name="AnimLayer", override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_name_update)
mute: bpy.props.BoolProperty(name="Mute", description="Mute Animation Layer", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_mute)
lock: bpy.props.BoolProperty(name="Lock", description="Lock Animation Layer", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_lock)
solo: bpy.props.BoolProperty(name="Solo", description="Solo Animation Layer", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_solo)
influence: bpy.props.FloatProperty(name="Layer Influence", description="Layer Influence", min = 0.0, options={'ANIMATABLE'}, max = 1.0, default = 1.0, precision = 3, update = anim_layers.influence_update, override = {'LIBRARY_OVERRIDABLE'})
influence_mute: bpy.props.BoolProperty(name="Animated Influence", description="Turn Animated influence On/Off", default=False, options={'HIDDEN'}, update = anim_layers.influence_mute_update, override = {'LIBRARY_OVERRIDABLE'})
#action_list: bpy.props.EnumProperty(name = 'Actions', description = "Select action", update = anim_layers.load_action, items = anim_layers.action_items, override = {'LIBRARY_OVERRIDABLE'})
action: bpy.props.PointerProperty(name = 'action', description = "Select action", type=bpy.types.Action, update = anim_layers.load_action, override = {'LIBRARY_OVERRIDABLE'})
action_range: bpy.props.FloatVectorProperty(name='action range', description="used to check if layer needs to update frame range", override = {'LIBRARY_OVERRIDABLE'}, size = 2)
frame_range: bpy.props.BoolProperty(name="Custom Frame Range", description="Use a custom frame range per layer instead of the scene frame range", default=False, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_frame_range)
frame_start: bpy.props.FloatProperty(name='Action Start Frame', description="First frame of the layer's action",min = 0, default=0, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_frame_start)
frame_end: bpy.props.FloatProperty(name='Action End Frame', description="End frame of the layer's action", default=0, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_frame_end)
speed: bpy.props.FloatProperty(name='Speed of the action', description="Speed of the action strip", default = 1, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_speed)
offset: bpy.props.FloatProperty(name='Offset when the action starts', description="Offseting the whole layer animation", default = 0, precision = 2, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_offset)
repeat: bpy.props.FloatProperty(name="Repeat", description="Repeat the action", min = 0.1, default = 1, options={'HIDDEN'}, override = {'LIBRARY_OVERRIDABLE'}, update = anim_layers.layer_repeat)
class AnimLayersObjects(bpy.types.PropertyGroup):
object: bpy.props.PointerProperty(name = "object", description = "objects with animation layers turned on", type=bpy.types.Object, override = {'LIBRARY_OVERRIDABLE'})
# Add-ons Preferences Update Panel
# Define Panel classes for updating
panels = anim_layers.panel_classes
def update_panel(self, context):
anim_layers.unregister_panels()
anim_layers.register_panels()
message = "AnimationLayers: Updating Panel locations has failed"
try:
for panel in panels:
if "bl_rna" in panel.__dict__:
bpy.utils.unregister_class(panel)
for panel in panels:
#print (panel.bl_category)
panel.bl_category = context.preferences.addons[__name__].preferences.category
bpy.utils.register_class(panel)
except Exception as e:
print("\n[{}]\n{}\n\nError:\n{}".format(__name__, message, e))
pass
@addon_updater_ops.make_annotations
class AnimLayersAddonPreferences(bpy.types.AddonPreferences):
# this must match the addon name, use '__package__'
# when defining this in a submodule of a python package.
bl_idname = __package__
auto_rename: bpy.props.BoolProperty(name="Sync Layer/Action Names", description="Rename layer to match to selected action", default = True)
blend_type : bpy.props.EnumProperty(name = 'Default Blend Type', description="Default Blend Type when adding layers", default = 'COMBINE',
items = [('COMBINE', 'Combine', 'Use Combine as the default blend type'), ('ADD', 'Add', 'Use Add as the default blend type'), ('REPLACE', 'Replace', 'Use Replace as the default blend type'),
('SUBTRACT', 'Subtract', 'Use as an Subtract Layer')])
frame_range_settings : bpy.props.EnumProperty(name = 'Frame Range Settings', description="Use Either Anim Layers Custom Frame Range Settings or NLA Settings", default = 'ANIMLAYERS',
items = [('ANIMLAYERS', 'Anim Layers Settings', 'Use Anim Layers properties to adjust custom frame range'),
('NLA', 'NLA Settings', 'Use the nla properties to adjust custom frame range')])
#Property for ClearActiveAction
proceed: bpy.props.EnumProperty(name="Choose how to proceed", description="Select an option how to proceed with Anim Layers", override = {'LIBRARY_OVERRIDABLE'},
items = [
('REMOVE_LAYERS', 'Remove old layers and continue with the current action', 'Remove previous Layers and continue with current action in the base layer', 0),
( 'REMOVE_ACTION', 'Remove current action and reload older Layers', 'Remove current action and continue with the previous layers', 1),
('ADD_ACTION', 'Add the current action as a new Layer', 'Keep previous Anim Layers and Add the active action as a new layer', 2),])
enabled_editors: bpy.props.EnumProperty(
name="Enabled Editors",
description="Select which editors should show animation layers panels",
items=[('VIEW_3D', "3D View", ""), ('GRAPH_EDITOR', "Graph Editor", ""), ('DOPESHEET_EDITOR', "Dope Sheet", ""),('NLA_EDITOR', "NLA Editor", ""),],
options={'ENUM_FLAG'},
default={'VIEW_3D', 'NLA_EDITOR'},
update=update_panel
)
category: bpy.props.StringProperty(
name="Tab Category",
description="Choose a name for the category of the panel",
default="Animation",
update=update_panel
)
# addon updater preferences from `__init__`, be sure to copy all of them
auto_check_update: bpy.props.BoolProperty(
name = "Auto-check for Update",
description = "If enabled, auto-check for updates using an interval",
default = False,
)
updater_interval_months: bpy.props.IntProperty(
name='Months',
description = "Number of months between checking for updates",
default=0,
min=0
)
updater_interval_days: bpy.props.IntProperty(
name='Days',
description = "Number of days between checking for updates",
default=7,
min=0,
)
updater_interval_hours: bpy.props.IntProperty(
name='Hours',
description = "Number of hours between checking for updates",
default=0,
min=0,
max=23
)
updater_interval_minutes: bpy.props.IntProperty(
name='Minutes',
description = "Number of minutes between checking for updates",
default=0,
min=0,
max=59
)
def draw(self, context):
layout = self.layout
addon_updater_ops.update_settings_ui(self, context)
col = layout.column()
col.label(text="Tab Category:")
col.prop(self, "category", text="")
row = layout.row()
row.prop(self, "enabled_editors")
col = layout.column()
col.separator(factor = 1)
col = col.box()
col.label(text="Defaults:")
#row = layout.row()
split = col.split(factor=0.5, align = True)
split.prop(self, "auto_rename")
#row.prop(self, "blend_type")
#split = row.split(factor=0.7, align = True)
split.label(text="Default Blend Type: ")
split.prop(self,'blend_type', text = '')
row = col.row()
row.label(text = "Custom Frame Range Settings")
row.prop(self, "frame_range_settings", text = '')
#row = layout.row(align = True)
#col = layout.row(bpy.context.scene.als,'blend_type', text = '')
classes = (AnimLayersSettings, AnimLayersSceneSettings, AnimLayersItems, AnimLayersObjects)
addon_keymaps = []
def register():
addon_updater_ops.register(bl_info)
register_class(AnimLayersAddonPreferences)
addon_updater_ops.make_annotations(AnimLayersAddonPreferences) # to avoid blender 2.8 warnings
if bpy.app.version < (3, 2, 0):
return
bake_ops.register()
anim_layers.register()
multikey.register()
for cls in classes:
register_class(cls)
bpy.types.Object.als = bpy.props.PointerProperty(type = AnimLayersSettings, options={'LIBRARY_EDITABLE'}, override = {'LIBRARY_OVERRIDABLE'})
bpy.types.Scene.als = bpy.props.PointerProperty(type = AnimLayersSceneSettings, options={'LIBRARY_EDITABLE'}, override = {'LIBRARY_OVERRIDABLE'})
bpy.types.Object.Anim_Layers = bpy.props.CollectionProperty(type = AnimLayersItems, override = {'LIBRARY_OVERRIDABLE', 'USE_INSERTION'})
bpy.types.Scene.AL_objects = bpy.props.CollectionProperty(type = AnimLayersObjects, options={'LIBRARY_EDITABLE'}, override = {'LIBRARY_OVERRIDABLE', 'USE_INSERTION'})
update_panel(None, bpy.context)
#update_tweak_keymap()
#Make sure TAB hotkey in the NLA goes into full stack mode
wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
km = kc.keymaps.new(name= 'NLA Generic', space_type= 'NLA_EDITOR')
if 'nla.tweakmode_enter' not in km.keymap_items:
kmi = km.keymap_items.new('nla.tweakmode_enter', type= 'TAB', value= 'PRESS')
kmi.properties.use_upper_stack_evaluation = True
addon_keymaps.append((km, kmi))
def unregister():
addon_updater_ops.unregister()
unregister_class(AnimLayersAddonPreferences)
if bpy.app.version < (3, 2, 0):
return
for cls in classes:
unregister_class(cls)
bake_ops.unregister()
anim_layers.unregister()
multikey.unregister()
del bpy.types.Object.als
del bpy.types.Object.Anim_Layers
del bpy.types.Scene.AL_objects
#removing keymaps
for km, kmi in addon_keymaps:
km.keymap_items.remove(kmi)
addon_keymaps.clear()
if __name__ == "__main__":
register()
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,17 +0,0 @@
{
"last_check": "2025-06-04 16:35:52.082677",
"backup_date": "May-6-2025",
"update_ready": true,
"ignore": false,
"just_restored": false,
"just_updated": false,
"version_text": {
"link": "https://gitlab.com/api/v4/projects/22294607/repository/archive.zip?sha=d8a2bbe2878233bf807b592e59fd534918d2dabf",
"version": [
2,
1,
9,
8
]
}
}
File diff suppressed because it is too large Load Diff
@@ -1,510 +0,0 @@
# if "bpy" in locals():
# import importlib
# if "multikey" in locals():
# importlib.reload()
import bpy
import random
import numpy as np
from mathutils import Quaternion
from . import bake_ops
from . import anim_layers
def attr_default(obj, fcu_key):
#check if the fcurve source belongs to a bone or obj
if fcu_key[0][:10] == 'pose.bones':
transform = fcu_key[0].split('.')[-1]
attr = fcu_key[0].split('"')[-2]
bone = fcu_key[0].split('"')[1]
source = obj.pose.bones[bone]
#in case of shapekey animation
elif fcu_key[0][:10] == 'key_blocks':
attr = fcu_key[0].split('"')[1]
shapekey = obj.data.shape_keys.key_blocks[attr]
return 0 if shapekey.slider_min <= 0 else shapekey.slider_min
#in case of transforms in object mode
else:# fcu_key[0] in transform_types:
source = obj
transform = fcu_key[0]
#check when it's transform property of Blender
if transform in source.bl_rna.properties.keys():
if hasattr(source.bl_rna.properties[transform], 'default_array'):
if len(source.bl_rna.properties[transform].default_array) > fcu_key[1]:
attrvalue = source.bl_rna.properties[transform].default_array[fcu_key[1]]
return attrvalue
#in case of property on object
elif fcu_key[0].split('"')[1] in obj.keys():
attr = fcu_key[0].split('"')[1]
if 'attr' not in locals():
return 0
#since blender 3 access to custom property settings changed
if attr in source:
id_attr = source.id_properties_ui(attr).as_dict()
attrvalue = id_attr['default']
return attrvalue
return 0
def store_handles(key):
#storing the distance between the handles bezier to the key value
handle_r = key.handle_right[1] - key.co[1]
handle_l = key.handle_left[1] - key.co[1]
return handle_r, handle_l
def apply_handles(key, handle_r, handle_l):
key.handle_right[1] = key.co[1] + handle_r
key.handle_left[1] = key.co[1] + handle_l
def filter_properties(obj, fcu):
'Filter the W X Y Z attributes of the transform properties'
transformations = ["rotation_quaternion","rotation_euler", "location", "scale"]
#check if the fcurve data path ends with any of the transformations
if not any(fcu.data_path.endswith(transform) for transform in transformations):
return True
transform = fcu.data_path.split('"].')[1] if obj.mode == 'POSE' else fcu.data_path
index = fcu.array_index
if 'rotation' in transform:
if transform == 'rotation_euler':
index -= 1
transform = 'rotation'
transform = 'filter_' + transform
#in case of channels like bbone_scalein that are no included then return
if not hasattr(bpy.context.scene.multikey, transform):
return True
attr = getattr(bpy.context.scene.multikey, transform)
return True if attr[index] else False
def add_value(key, value):
if key.select_control_point:
#store handle values in relative to the keyframe value
handle_r, handle_l = store_handles(key)
key.co[1] += value
apply_handles(key, handle_r, handle_l)
#calculate the difference between current value and the fcurve value
def add_diff(obj, fcurves, path, current_value, eval_array):
'''Get the difference value and add it to all selected keyframes'''
array_value = current_value - eval_array
if not any(array_value):
return
for i, value in enumerate(array_value):
fcu = fcurves.find(path, index = i)
if fcu is None or not filter_properties(obj, fcu):
continue
for key in fcu.keyframe_points:
add_value(key, value)
fcu.update()
class ScaleValuesOp(bpy.types.Operator):
"""Modal operator used while scale value is running before release"""
bl_idname = "anim.multikey_scale_value"
bl_label = "Scale Values"
bl_options = {'REGISTER', 'UNDO'}
def invoke(self, context, event):
#reset the values for dragging
self.stop = False
scene = context.scene
global is_dragging
is_dragging = True
self.avg_value = dict()
#dictionary of the keyframes and their original INITIAL values
self.keyframes_values = dict()
self.keyframes_handle_right = dict()
self.keyframes_handle_left = dict()
#the average value for each fcurve
self.keyframes_avg_value = dict()
for obj in context.selected_objects:
if obj.animation_data.action is None:
continue
action = obj.animation_data.action
fcurves = anim_layers.get_fcurves_channelbag(obj, action)
for fcu in fcurves:
if anim_layers.selected_bones_filter(obj, fcu):
continue
if not filter_properties(obj, fcu):
continue
#avg and value list per fcurve
avg_value = []
value_list = []
for key in fcu.keyframe_points:
if key.select_control_point:
value_list.append(key.co[1])
self.keyframes_values.update({key : key.co[1]})
self.keyframes_handle_right.update({key : key.handle_right[1]})
self.keyframes_handle_left.update({key : key.handle_left[1]})
if len(value_list)>1:
#the average value with the scale property added to it
avg_value = sum(value_list) / len(value_list)
for key in fcu.keyframe_points:
if key.select_control_point:
self.keyframes_avg_value.update({key : avg_value})
if not self.keyframes_avg_value:
if 'is_dragging' in globals():
del is_dragging
scene.multikey['scale'] = 1
anim_layers.redraw_areas(['VIEW_3D'])
return('CANCELLED')
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
def modal(self, context, event):
global is_dragging
try:
scene = context.scene
scale = scene.multikey.scale
#Quit the modal operator when the slider is released
if self.stop:
del is_dragging
scene.multikey['scale'] = 1
anim_layers.redraw_areas(['VIEW_3D'])
#modal is being cancelled because of undo issue with the modal running through the property
return {'FINISHED'}
if event.value == 'RELEASE': # Stop the modal on next frame. Don't block the event since we want to exit the field dragging
self.stop = True
return {'PASS_THROUGH'}
for key, key_value in self.keyframes_values.items():
if not key.select_control_point:
continue
if key not in self.keyframes_avg_value:
continue
avg_value = self.keyframes_avg_value[key]
handle_right_value = self.keyframes_handle_right[key]
handle_left_value = self.keyframes_handle_left[key]
#add the value of the distance from the average * scale factor
key.co[1] = avg_value + ((key_value - avg_value)*scale)
key.handle_right[1] = avg_value + ((handle_right_value - avg_value)*scale)
key.handle_left[1] = avg_value + ((handle_left_value - avg_value)*scale)
return {'PASS_THROUGH'}
except Exception as e:
# Log the error
print("Error:", e)
self['scale'] = 1
self.stop = True
del is_dragging
return {'CANCELLED'}
def scale_value(self, context):
if 'is_dragging' in globals():
if is_dragging:
return
obj = context.object
if obj is None:
self['scale'] = 1
return
action = obj.animation_data.action
if action is None:
self['scale'] = 1
return
if context.mode == 'POSE' and not context.selected_pose_bones:
self['scale'] = 1
return
bpy.ops.anim.multikey_scale_value('INVOKE_DEFAULT')
def random_value(self, context):
for obj in context.selected_objects:
if obj.animation_data.action is None:
continue
action = obj.animation_data.action
fcurves = anim_layers.get_fcurves_channelbag(obj, action)
for fcu in fcurves:
# if obj.mode == 'POSE':
if anim_layers.selected_bones_filter(obj, fcu):
continue
if not filter_properties(obj, fcu):
continue
value_list = []
threshold = bpy.context.scene.multikey.randomness
for key in fcu.keyframe_points:
if key.select_control_point == True:
value_list.append(key.co[1])
if len(value_list) > 0:
value = max(value_list)- min(value_list)
for key in fcu.keyframe_points:
add_value(key, value * random.uniform(-threshold, threshold))
fcu.update()
self['randomness'] = 0.1
def evaluate_combine(data_path, added_array, eval_array, array_default, influence):
if 'scale' in data_path:
eval_array = eval_array * (added_array / array_default) ** influence
elif 'rotation_quaternion' in data_path:
#multiply first the influence with the w separatly
added_array[0] = added_array[0] + (1- added_array[0])*(1 - influence)
added_array[1:] *= influence
eval_array = np.array(Quaternion(eval_array) @ Quaternion(added_array))# ** influence
#if it's a custom property
elif 'rotation_euler' not in data_path and 'location' not in data_path:
eval_array = eval_array + (added_array - array_default) * influence
return eval_array
def evaluate_array(fcurves, fcu_path, frame, array_default = [0, 0, 0]):
'''Create an array from all the indexes'''
array_len = len(array_default)
# fcu_array = array_default if array_len == 4 else [0, 0, 0]
fcu_array = []
#get the missing arrays in case quaternion is not complete
missing_arrays = []
for i in range(array_len):
fcu = fcurves.find(fcu_path, index = i)
if fcu is None:
missing_arrays.append(i)
continue
fcu_array.append(fcu.evaluate(frame))
#In case it's a quaternion and missing attributes, then adding from default value
if fcu_array and array_len == 4 and missing_arrays:
for i in missing_arrays:
fcu_array.insert(i, array_default[i])
if not len(fcu_array):
return None
return np.array(fcu_array)
def evaluate_layers(context, obj, anim_data, fcu, array_default):
'''Calculate the evaluation of all the layers when using the nla'''
if not hasattr(anim_data, 'nla_tracks') or not anim_data.use_nla:
return None
nla_tracks = anim_data.nla_tracks
if not len(nla_tracks):
return None
frame = context.scene.frame_current
blend_types = {'ADD' : '+', 'SUBTRACT' : '-', 'MULTIPLY' : '*'}
fcu_path = fcu.data_path
eval_array = array_default
for track in nla_tracks:
if track.mute:
continue
if not len(track.strips):
continue
for strip in track.strips:
if not strip.frame_start < frame < strip.frame_end:
continue
action = strip.action
if action is None:
continue
blend_type = strip.blend_type
#get the influence value either from the attribute or the fcurve. function coming from bake
influence = strip.influence
if len(strip.fcurves):
if not strip.fcurves[0].mute and len(strip.fcurves[0].keyframe_points):
influence = strip.fcurves[0].evaluate(frame)
#evaluate the frame according to the strip settings
frame_eval = frame
#change the frame if the strip is on hold
if frame < strip.frame_start:
if strip.extrapolation == 'HOLD':
frame_eval = strip.frame_start
elif frame >= strip.frame_end:
if strip.extrapolation == 'HOLD' or strip.extrapolation == 'HOLD_FORWARD':
frame_eval = strip.frame_end
last_frame = strip.frame_start + (strip.frame_end - strip.frame_start) / strip.repeat
if strip.repeat > 1 and (frame) >= last_frame:
action_range = (strip.action_frame_end * strip.scale - strip.action_frame_start * strip.scale)
frame_eval = (((frame_eval - strip.frame_start) % (action_range)) + strip.frame_start)
if strip.use_reverse:
frame_eval = last_frame - (frame_eval - strip.frame_start)
offset = (strip.frame_start * 1/strip.scale - strip.action_frame_start) * strip.scale
frame_eval = strip.frame_start * 1/strip.scale + (frame_eval - strip.frame_start) * 1/strip.scale - offset * 1/strip.scale
fcurves = anim_layers.get_fcurves_channelbag(obj, action)
eval_array = evaluate_blend_type(fcurves, eval_array, fcu_path, frame_eval, influence, array_default, blend_type, blend_types)
#Adding an extra layer from the action outside and on top of the nla
tweak_mode = anim_data.use_tweak_mode
if tweak_mode:
anim_data.use_tweak_mode = False
action = anim_data.action
if action:
influence = anim_data.action_influence
blend_type = anim_data.action_blend_type
fcurves = anim_layers.get_fcurves_channelbag(obj, action)
eval_array = evaluate_blend_type(fcurves, eval_array, fcu_path, frame, influence, array_default, blend_type, blend_types)
anim_data.use_tweak_mode = tweak_mode
return eval_array
def evaluate_blend_type(fcurves, eval_array, fcu_path, frame, influence,
array_default, blend_type, blend_types):
'''Calculate the value based on the blend type'''
fcu_array = evaluate_array(fcurves, fcu_path, frame, array_default)
if fcu_array is None:# or len(fcu_array) != len(eval_array):
return eval_array
###EVALUATION###
if blend_type =='COMBINE':
if 'location' in fcu_path or 'rotation_euler' in fcu_path:
blend_type = 'ADD'
if blend_type =='REPLACE':
eval_array = eval_array * (1 - influence) + fcu_array * influence
elif blend_type =='COMBINE':
eval_array = evaluate_combine(fcu_path, fcu_array, eval_array, array_default, influence)
else:
eval_array = eval('eval_array' + blend_types[blend_type] + 'fcu_array' + '*' + str(influence))
return eval_array
def evaluate_value(self, context):
for obj in context.selected_objects:
anim_data = obj.animation_data
if anim_data is None:
return
if anim_data.action is None:
return
action = obj.animation_data.action
fcu_paths = []
transformations = ["rotation_quaternion","rotation_euler", "location", "scale"]
if obj.mode == 'POSE':
bonelist = context.selected_pose_bones if obj.als.onlyselected else obj.pose.bones
fcurves = anim_layers.get_fcurves_channelbag(obj, action)
for fcu in fcurves:
if fcu in fcu_paths:
continue
if obj.mode == 'POSE':
if anim_layers.selected_bones_filter(obj, fcu):
continue
if not filter_properties(obj, fcu):
continue
for bone in bonelist:
#find the fcurve of the bone
if fcu.data_path.rfind(bone.name) != 12 or fcu.data_path[12 + len(bone.name)] != '"':
continue
path_split = fcu.data_path.split('"].')
if len(path_split) <= 1:
continue
else:
transform = fcu.data_path.split('"].')[1]
if transform not in transformations:
continue
current_value = getattr(obj.pose.bones[bone.name], transform)
else:
transform = fcu.data_path
current_value = getattr(obj, transform)
array_default = np.array(bake_ops.attr_default(obj, (fcu.data_path, fcu.array_index)))
eval_array = evaluate_layers(context, obj, anim_data, fcu, array_default)
if eval_array is None:
fcurves = anim_layers.get_fcurves_channelbag(obj, action)
eval_array = evaluate_array(fcurves, fcu.data_path, context.scene.frame_current, array_default)
#calculate the difference between current value and the fcurve value
add_diff(obj, fcurves, fcu.data_path, np.array(current_value), eval_array)
class MULTIKEY_OT_Multikey(bpy.types.Operator):
"""Edit all selected keyframes"""
bl_label = "Edit Selected Keyframes"
bl_idname = "fcurves.multikey"
bl_options = {'REGISTER', 'UNDO'}
# bl_description = ('Select keyframes, move your bone or objecet and press the operator. Does not work with Autokey')
@classmethod
def poll(cls, context):
return context.active_object and context.active_object.animation_data and bpy.context.scene.tool_settings.use_keyframe_insert_auto == False
def execute(self, context):
evaluate_value(self, context)
return {'FINISHED'}
class MultikeyProperties(bpy.types.PropertyGroup):
#selectedbones: bpy.props.BoolProperty(name="Affect only selected bones", description="Affect only selected bones", default=True, options={'HIDDEN'})
#handletype: bpy.props.BoolProperty(name="Keep handle types", description="Keep handle types", default=False, options={'HIDDEN'})
scale: bpy.props.FloatProperty(name="Scale Values Factor", description="Scale percentage from the average value", default=1.0, soft_max = 10, soft_min = -10, step=0.1, precision = 3, update = scale_value)
randomness: bpy.props.FloatProperty(name="Randomness", description="Random Threshold of keyframes", default=0.1, min=0.0, max = 1.0, update = random_value)
# is_dragging: bpy.props.BoolProperty(default = False)
#filters
filter_location: bpy.props.BoolVectorProperty(name="Location", description="Filter Location properties", default=(True, True, True), size = 3, options={'HIDDEN'})
filter_rotation: bpy.props.BoolVectorProperty(name="Rotation", description="Filter Rotation properties", default=(True, True, True, True), size = 4, options={'HIDDEN'})
filter_scale: bpy.props.BoolVectorProperty(name="Scale", description="Filter Scale properties", default=(True, True, True), size = 3, options={'HIDDEN'})
class FilterProperties(bpy.types.Operator):
"""Filter Location Rotation and Scale Properties"""
bl_idname = "fcurves.filter"
bl_label = "Filter Properties W X Y Z"
bl_options = {'REGISTER', 'UNDO'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self, width = 200)
def draw(self, context):
layout = self.layout
row = layout.row()
row.label(text = 'Location')
row.prop(context.scene.multikey, 'filter_location', text = '')
row = layout.row()
row.label(text = 'Rotation')
row.prop(context.scene.multikey, 'filter_rotation', text = '')
row = layout.row()
row.label(text = 'Scale')
row.prop(context.scene.multikey, 'filter_scale', text = '')
def execute(self, context):
return {'CANCELLED'}
classes = (MultikeyProperties, FilterProperties, MULTIKEY_OT_Multikey, ScaleValuesOp)
def register():
from bpy.utils import register_class
for cls in classes:
register_class(cls)
bpy.types.Scene.multikey = bpy.props.PointerProperty(type = MultikeyProperties, options={'LIBRARY_EDITABLE'}, override = {'LIBRARY_OVERRIDABLE'})
def unregister():
from bpy.utils import unregister_class
for cls in classes:
unregister_class(cls)
del bpy.types.Scene.multikey
@@ -1,649 +0,0 @@
import bpy
from . import anim_layers
from . import bake_ops
def subscriptions_remove(handler = True):
#clear all handlers and subsciptions
bpy.msgbus.clear_by_owner(bpy.context.scene)
global influence_keys, selected_bones
if 'influence_keys' in globals():
del influence_keys
if 'selected_bones' in globals():
del selected_bones
if not handler:
return
if check_handler in bpy.app.handlers.depsgraph_update_pre:
bpy.app.handlers.depsgraph_update_pre.remove(check_handler)
if animlayers_frame in bpy.app.handlers.frame_change_post:
bpy.app.handlers.frame_change_post.remove(animlayers_frame)
def subscriptions_add(scene, handler = True):
bpy.msgbus.clear_by_owner(scene)
subscribe_to_frame_end(scene)
subscribe_to_track_name(scene)
subscribe_to_action_name(scene)
subscribe_to_strip_settings(scene)
subscribe_to_influence(scene)
if not handler:
return
if check_handler not in bpy.app.handlers.depsgraph_update_pre:
bpy.app.handlers.depsgraph_update_pre.append(check_handler)
if animlayers_frame not in bpy.app.handlers.frame_change_post:
bpy.app.handlers.frame_change_post.append(animlayers_frame)
def animlayers_frame(self, context):
scene = bpy.context.scene
current = scene.frame_current_final
#Make sure the animation is playing and not just running a motion path
if not bpy.context.screen.is_animation_playing:
return
#Checking if preview range was turned on or off, when using hotkey P it doesn't recognize
#only during the frame handler
if scene.get('framerange_preview') != scene.use_preview_range:
scene['framerange_preview'] = scene.use_preview_range
frameend_update_callback()
return
frame_start, frame_end = bake_ops.frame_start_end(scene)
reset_subscription = False
if 'outofrange' not in globals():
global outofrange
outofrange = False if 0 <= current <= frame_end else True
# print('out of range ', outofrange )
if 0 <= current <= frame_end:
if outofrange:
frameend_update_callback()
outofrange = False
return
outofrange = True
# if current <= frame_end:
# return
#iterate only through objects with anim layers turned on
objects = [obj.object for obj in scene.AL_objects]
for obj in objects:
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
return
nla_tracks = anim_data.nla_tracks
if not len(nla_tracks):
return
for i, track in enumerate(nla_tracks):
if len(track.strips) != 1:
continue
#checks if the layer has a custom frame range
layer = obj.Anim_Layers[i]
if layer.frame_range:
continue
if not reset_subscription:
subscriptions_remove(handler = False)
reset_subscription = True
strip = track.strips[0]
if current < 0:
# anim_layers.strip_action_recalc(layer, track.strips[0])
strip.frame_start_ui = current
anim_layers.update_action_frame_range(current, frame_end, layer, strip)
# track.strips[0].action_frame_start = current * 1/layer.speed - layer.offset * 1/layer.speed
strip.frame_end_ui = frame_end
elif current > frame_end:
if strip.frame_start < 0:
strip.frame_start_ui = 0
anim_layers.update_action_frame_range(0, frame_end, layer, strip)
# print('animlayers_frame ', current)
strip.frame_end_ui = current + 10
if reset_subscription:
subscriptions_add(scene, handler = False)
def check_handler(self, context):
'''A main function that performs a series of checks using a handler'''
scene = bpy.context.scene
#if there are no objects included in animation layers then return
if not len(scene.AL_objects):
return
obj = bpy.context.object
#if the object was removed from the scene, then remove it from anim layers object list
if obj is None:
i = 0
while i < len(scene.AL_objects):
if scene.AL_objects[i].object not in scene.objects.values():
scene.AL_objects.remove(i)
else:
i += 1
return
if not obj.als.turn_on:
return
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
return
if not anim_data.use_nla:
obj.als.turn_on = False
return
if not len(obj.Anim_Layers):
return
if not hasattr(anim_data, 'nla_tracks') or not obj.als.turn_on: #obj.select_get() == False or
return
anim_layers.add_obj_to_animlayers(obj, [item.object for item in scene.AL_objects])
nla_tracks = anim_data.nla_tracks
layer = obj.Anim_Layers[obj.als.layer_index]
active_action_update(obj, anim_data, nla_tracks)
#check if a keyframe was removed
if bpy.context.active_operator is not None:
if bpy.context.active_operator.name in ['Transform', 'Delete Keyframes'] and obj.als.edit_all_keyframes:
anim_layers.edit_all_keyframes()
if bpy.context.active_operator.name == 'Enter Tweak Mode':
if not bpy.context.active_operator.properties['use_upper_stack_evaluation']:
obj.als.upper_stack = False
if bpy.context.active_operator.name == 'Move Channels':
anim_layers.visible_layers(obj, nla_tracks)
# check if track and layers are synchronized
if track_layer_synchronization(obj, nla_tracks):
return
anim_layers.add_obj_to_animlayers(obj, [item.object for item in scene.AL_objects])
track = nla_tracks[obj.als.layer_index]
always_sync_range(track, layer)
# sync_strip_range(track, layer)
if anim_data.use_tweak_mode and layer.lock:
layer['lock'] = False
elif not anim_data.use_tweak_mode and not layer.lock:
layer['lock'] = True
influence_sync(obj, nla_tracks)
# continue if locked
if layer.lock:
return
if obj.als.view_all_keyframes:
anim_layers.hide_view_all_keyframes(obj, anim_data)
check_selected_bones(obj)
influence_check(nla_tracks[obj.als.layer_index])
def track_layer_synchronization(obj, nla_tracks):
'''check if track and layers are synchronized'''
if len(nla_tracks) == len(obj.Anim_Layers):
return False
new_layers_names = set(track.name for track in nla_tracks).difference(set(layer.name for layer in obj.Anim_Layers))
anim_layers.visible_layers(obj, nla_tracks)
if obj.als.layer_index > len(obj.Anim_Layers)-1:
obj.als.layer_index = len(obj.Anim_Layers)-1
#update new layer with strip settings
frame_start, frame_end = bake_ops.frame_start_end(bpy.context.scene)
for layer_name in new_layers_names:
if len(nla_tracks[layer_name].strips) != 1:
continue
strip = get_strip_in_meta(nla_tracks[layer_name].strips[0])
layer = obj.Anim_Layers[layer_name]
if (strip.frame_start, strip.frame_end) != (frame_start, frame_end):
layer['frame_range'] = True
update_strip_layer_settings(strip, layer)
layer['action'] = strip.action
return True
def active_action_update(obj, anim_data, nla_tracks):
'''updating the active action into the selected layer'''
if obj.Anim_Layers[obj.als.layer_index].lock:
if anim_data.action != None:
subscriptions_remove()
anim_data.use_tweak_mode = False
anim_data.action = None
subscriptions_add(bpy.context.scene)
return
if anim_data.action == nla_tracks[obj.als.layer_index].strips[0].action:
return
if not len(nla_tracks[obj.als.layer_index].strips):
return
if not anim_data.action or anim_data.is_property_readonly('action'):
return
subscriptions_remove()
action = anim_data.action
anim_data.action = None
obj.Anim_Layers[obj.als.layer_index].action = action
subscriptions_add(bpy.context.scene)
def get_strip_in_meta(strip):
'''check if it's meta strip then access the last strip inside meta hierarchy'''
while len(strip.strips):
strip = strip.strips[0]
return strip
def sync_strip_range():
scene = bpy.context.scene
frame_start, frame_end = bake_ops.frame_start_end(scene)
if scene.frame_current_final > frame_end:
frame_end = scene.frame_current_final + 10
frame_start = scene.frame_current_final if scene.frame_current_final < 0 else 0.0
objects = [obj.object for obj in scene.AL_objects]
for obj in objects:
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
continue
nla_tracks = anim_data.nla_tracks
if not len(nla_tracks):
continue
for i, track in enumerate(nla_tracks):
if len(track.strips) != 1:
continue
if obj.Anim_Layers[i]['frame_range']:
continue
strip = track.strips[0]
strip_frame_start = strip.frame_start
strip_frame_end = strip.frame_end
if (strip_frame_start, round(strip_frame_end, 2)) != (frame_start, float(frame_end)):
obj.Anim_Layers[i]['frame_range'] = True
def always_sync_range(track, layer):
'''sync frame range when always sync turned on'''
if not len(track.strips):
return
if not layer.frame_range:
if track.strips[0].use_sync_length:
track.strips[0].use_sync_length = False
return
if not track.strips[0].use_sync_length:
if tuple(layer.action_range) != (0.0, 0.0): #reset action range when turned off
layer.action_range = (0.0, 0.0)
return
strip = track.strips[0]
if tuple(layer.action_range) == tuple((strip.action.frame_range[0], strip.action.frame_range[1])):
return
anim_layers.sync_frame_range(bpy.context)
layer.action_range = strip.action.frame_range
def influence_sync(obj, nla_tracks):
#Tracks that dont have keyframes are locked
for i, track in enumerate(nla_tracks):
if obj.Anim_Layers[i].lock:
continue
if not len(track.strips):
continue
if not len(track.strips[0].fcurves):
continue
if not len(track.strips[0].fcurves[0].keyframe_points):
#apply the influence property to the temp property when keyframes are removed (but its still locked)
if not track.strips[0].fcurves[0].lock:
obj.Anim_Layers[i].influence = track.strips[0].influence
track.strips[0].fcurves[0].lock = True
if obj.animation_data is None:
return
action = obj.animation_data.action
if action is None:
return
#if a keyframe was found in the temporary property then add it to the
data_path = 'Anim_Layers[' + str(obj.als.layer_index) + '].influence'
fcurves = anim_layers.get_fcurves_channelbag(obj, action)
fcu_influence = fcurves.find(data_path)
if fcu_influence is None:
return
if not len(fcu_influence.keyframe_points):
return
#remove the temporary influence
fcurves.remove(fcu_influence)
#if the action was created just for the influence because of empty object data type then remove the action
if action.name == obj.name + 'Action' and not len(obj.animation_data.nla_tracks) and not len(fcurves):
bpy.data.actions.remove(action)
if obj.Anim_Layers[obj.als.layer_index].influence_mute:
return
strip = nla_tracks[obj.als.layer_index].strips[0]
strip.fcurves[0].lock = False
strip.keyframe_insert('influence')
strip.fcurves[0].update()
def influence_check(selected_track):
'''update influence when a keyframe was added without autokey'''
#skip the next steps if a strip is missing or tracks were removed from the nla tracks
if len(selected_track.strips) != 1:# or obj.als.layer_index > len(nla_tracks)-2:
return
if not len(selected_track.strips[0].fcurves):
return
global influence_keys
if selected_track.strips[0].fcurves[0].mute or not len(selected_track.strips[0].fcurves[0].keyframe_points) or bpy.context.scene.tool_settings.use_keyframe_insert_auto:
if 'influence_keys' in globals():
del influence_keys
return #when the fcurve doesnt have keyframes, or when autokey is turned on, then return
#update if the influence keyframes are changed. influence_keys are first added in influence_update_callback
if 'influence_keys' not in globals():
return
if influence_keys != [tuple(key.co) for key in selected_track.strips[0].fcurves[0].keyframe_points]:
selected_track.strips[0].fcurves[0].update()
del influence_keys
def check_selected_bones(obj):
'''running in the handler and checking if the selected bones were changed during view multiply layer keyframes'''
if not obj.als.only_selected_bones:
return
global selected_bones
try:
selected_bones
except NameError:
selected_bones = bpy.context.selected_pose_bones
return
else:
if selected_bones != bpy.context.selected_pose_bones:
selected_bones = bpy.context.selected_pose_bones
obj.als.view_all_keyframes = True
########################### MSGBUS SUBSCRIPTIONS #############################
#Callback function for Scene frame end
def frameend_update_callback():
'''End the strips at the end of the scene or scene preview'''
scene = bpy.context.scene
if not scene.AL_objects:
return
frame_start, frame_end = bake_ops.frame_start_end(scene)
if scene.frame_current_final > frame_end:
frame_end = scene.frame_current_final + 10
frame_start = scene.frame_current_final if scene.frame_current_final < 0 else 0
# subscriptions_remove(handler = False)
for AL_item in scene.AL_objects:
obj = AL_item.object
if obj is None or obj not in scene.objects.values():
continue
#anim_data = anim_data_type(obj)
anim_datas = anim_layers.anim_datas_append(obj)
for anim_data in anim_datas:
if anim_data is None:
continue
if len(anim_data.nla_tracks) != len(obj.Anim_Layers):
continue
for layer, track in zip(obj.Anim_Layers, anim_data.nla_tracks):
if layer.frame_range:
continue
if len(track.strips) != 1:
continue
strip = track.strips[0]
strip.frame_start = frame_start
anim_layers.update_action_frame_range(frame_start, frame_end, layer, strip)
strip.scale = layer.speed
strip.frame_end = frame_end
# subscriptions_add(scene, handler = False)
#Subscribe to the scene frame_end
def subscribe_to_frame_end(scene):
'''subscribe_to_frame_end and frame preview end'''
subscribe_end = scene.path_resolve("frame_end", False)
subscribe_preview_end = scene.path_resolve("frame_preview_end", False)
subscribe_use_preview = scene.path_resolve("use_preview_range", False)
for subscribe in [subscribe_end, subscribe_preview_end, subscribe_use_preview]:
bpy.msgbus.subscribe_rna(
key=subscribe,
owner=scene,
args=(),
notify=frameend_update_callback,)
# bpy.msgbus.publish_rna(key=subscribe)
# def action_framestart_update_callback(*args):
# ''' update the strip start with the action start'''
def track_update_callback():
'''update layers with the tracks name'''
# global initial_call
# if initial_call:
# return
if not bpy.context.selected_objects:
return
obj = bpy.context.object
if obj is None:
return
if not obj.als.turn_on:
return
current_anim_data = anim_layers.anim_data_type(obj)
anim_datas = anim_layers.anim_datas_append(obj)
for anim_data in anim_datas:
if anim_data is None:
return
nla_tracks = anim_data.nla_tracks
if not len(nla_tracks):# or len(nla_tracks[:-1]) != len(obj.Anim_Layers):
return
override_tracks = anim_layers.check_override_tracks(obj, anim_data)
for i, track in enumerate(nla_tracks):
if anim_data != current_anim_data:
continue
#make sure there are no duplicated names
if track.name != obj.Anim_Layers[i].name:
#If its an override track, then make sure the reference object name is also synchronized
if obj.Anim_Layers[i].name in override_tracks:
override_tracks[obj.Anim_Layers[i].name].name = track.name
obj.Anim_Layers[i].name = track.name
if len(track.strips) == 1:
track.strips[0].name = track.name
def subscribe_to_track_name(scene):
'''Subscribe to the name of track'''
#subscribe_track = nla_track.path_resolve("name", False)
subscribe_track = (bpy.types.NlaTrack, 'name')
bpy.msgbus.subscribe_rna(
key=subscribe_track,
# owner of msgbus subcribe (for clearing later)
owner=scene,
# Args passed to callback function (tuple)
args=(),
# Callback function for property update
notify=track_update_callback,)
# bpy.msgbus.publish_rna(key=subscribe_track)
def action_name_callback():
'''update layers with the tracks name'''
# global initial_call
# if initial_call:
# return
obj = bpy.context.object
if obj is None:
return
if not obj.als.turn_on:
return
anim_data = anim_layers.anim_data_type(obj)
#anim_datas = anim_layers.anim_datas_append(obj)
if anim_data is None:
return
nla_tracks = anim_data.nla_tracks
if not len(nla_tracks):
return
layer = obj.Anim_Layers[obj.als.layer_index]
if not len(nla_tracks[obj.als.layer_index].strips):
return
action = nla_tracks[obj.als.layer_index].strips[0].action
if action is None:
return
if not obj.als.auto_rename or layer.name == action.name:
return
layer.name = action.name
def subscribe_to_action_name(scene):
'''Subscribe to the name of track'''
#subscribe_track = nla_track.path_resolve("name", False)
subscribe_action = (bpy.types.Action, 'name')
bpy.msgbus.subscribe_rna(
key=subscribe_action,
# owner of msgbus subcribe (for clearing later)
owner=scene,
# Args passed to callback function (tuple)
args=(),
# Callback function for property update
notify=action_name_callback,)
# bpy.msgbus.publish_rna(key=subscribe_action)
def influence_update_callback(*args):
'''update influence'''
# global initial_call
if not bpy.context.selected_objects:
return
obj = bpy.context.object
#checking if the object has nla tracks, when I used undo it was still calling the property on an object with no nla tracks
if obj is None:
return
if not obj.als.turn_on:
return
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
return
if not len(anim_data.nla_tracks):
return
track = anim_data.nla_tracks[obj.als.layer_index]
if len(track.strips) != 1:
return
if track.strips[0].fcurves[0].mute or track.strips[0].fcurves[0].lock:
return
# print('influence_update_callback')
#if the influence property and fcurve value are not the same then store the keyframes to check in the handler for a change
if track.strips[0].influence == track.strips[0].fcurves[0].evaluate(bpy.context.scene.frame_current):
return
global influence_keys
influence_keys = [tuple(key.co) for key in track.strips[0].fcurves[0].keyframe_points]
if bpy.context.scene.tool_settings.use_keyframe_insert_auto and len(track.strips[0].fcurves[0].keyframe_points):
track.strips[0].keyframe_insert('influence')
track.strips[0].fcurves[0].update()
return
def subscribe_to_influence(scene):
'''Subscribe to the influence of the track'''
subscribe_influence = (bpy.types.NlaStrip, 'influence')
bpy.msgbus.subscribe_rna(
key=subscribe_influence,
# owner of msgbus subcribe (for clearing later)
owner=scene,
# Args passed to callback function (tuple)
args=(scene,),
# Callback function for property update
notify=influence_update_callback,)
def subscribe_to_strip_settings(scene):
'''Subscribe to the strip settings of the track'''
frame_start = (bpy.types.NlaStrip, 'frame_start')
frame_end = (bpy.types.NlaStrip, 'frame_end')
action_frame_start = (bpy.types.NlaStrip, 'action_frame_start')
action_frame_end = (bpy.types.NlaStrip, 'action_frame_end')
scale = (bpy.types.NlaStrip, 'scale')
repeat = (bpy.types.NlaStrip, 'repeat')
attributes = [frame_start, frame_end, action_frame_start, action_frame_end, scale, repeat, frame_start, frame_end]
if bpy.app.version > (3, 2, 0):
#this properties exist only after Blender 3.2
frame_start_ui = (bpy.types.NlaStrip, 'frame_start_ui')
frame_end_ui = (bpy.types.NlaStrip, 'frame_end_ui')
attributes += [frame_start_ui, frame_end_ui]
for key in attributes:
bpy.msgbus.subscribe_rna(
key=key,
# owner of msgbus subcribe (for clearing later)
owner=scene,
# Args passed to callback function (tuple)
args=(),
# Callback function for property update
notify=strip_settings_callback,)
def update_strip_layer_settings(strip, layer):
layer['speed'] = strip.scale
# start_offset = strip.action.frame_range[0] - strip.frame_start
# offset = (strip.action_frame_start - strip.frame_start - start_offset) * strip.scale + start_offset
# offset = (strip.action_frame_start - strip.frame_start) * strip.scale
if strip.repeat <= 1:
offset = (strip.frame_start * 1/strip.scale - strip.action_frame_start) * strip.scale
else:
#During repeat the offset is based on the distance from the action first keyframe
offset = strip.frame_start - strip.action.frame_range[0]
layer['offset'] = round(offset, 3)
#If custom frame range is turned off return to not lose frame range values
if not layer.frame_range:
return
layer['frame_end'] = strip.frame_end
layer['frame_start'] = strip.frame_start
layer['repeat'] = strip.repeat
def strip_settings_callback():
'''subscribe_to_strip_settings callback'''
if not bpy.context.selected_objects:
return
obj = bpy.context.object
if obj is None:
return
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
return
if not len(anim_data.nla_tracks):
return
if not len(obj.Anim_Layers):
return
strip = anim_data.nla_tracks[obj.als.layer_index].strips[0]
sync_strip_range()
if not len(anim_data.nla_tracks[obj.als.layer_index].strips):
return
strip = anim_data.nla_tracks[obj.als.layer_index].strips[0]
layer = obj.Anim_Layers[obj.als.layer_index]
update_strip_layer_settings(strip, layer)
anim_layers.redraw_areas([ 'VIEW_3D'])
+211 -119
View File
@@ -3,7 +3,7 @@ from . import anim_layers
from . import subscriptions
from mathutils import Vector, Quaternion
import numpy as np
#import time
# import time
def frame_start_end(scene):
if scene.use_preview_range:
@@ -12,7 +12,7 @@ def frame_start_end(scene):
else:
frame_start = scene.frame_start
frame_end = scene.frame_end
return frame_start, frame_end
return float(frame_start), float(frame_end)
def smart_start_end(smartkeys, frame_start, frame_end):
'''add the first and last frame of the scene if necessery'''
@@ -65,11 +65,11 @@ def smart_repeat(smartkeys, fcu, strip):
#duplicate the keys on the cycle after
keyframes_dup = []
for i in range(1, int(strip.repeat)):
for key in smartkeys[1:]:
keydup = smartkey(key)
keydup.frame += fcu_range*(i)
keydup.frame += round(fcu_range*(i), 2)
#duplicate the tangents tuple values
if hasattr(key, 'handle_left'):
keydup.handle_left = Vector([key.handle_left[0] + fcu_range*(i+1), key.handle_left[1]])
@@ -104,7 +104,6 @@ def smart_cycle(smartkeys, fcu, frame_start, frame_end):
cycle_end_dup = int((mod.frame_end - fcu.range()[1])/fcu_range)+2
#copy the the right handle of the first keyframe to the last, and the left handle from the last keyframe to the first
smartkeys[-1].handle_right_type = smartkeys[0].handle_left_type
smartkeys[0].handle_left_type = smartkeys[-1].handle_right_type
# if smartkeys[-1].interpolation == 'BEZIER':
@@ -113,13 +112,13 @@ def smart_cycle(smartkeys, fcu, frame_start, frame_end):
# if smartkeys[0].interpolation == 'BEZIER':
if hasattr(smartkeys[0], 'handle_left'):
smartkeys[0].handle_left = [smartkeys[-1].handle_left[0] - fcu_range, smartkeys[0].handle_left[1]]
#duplicate the keys on the cycle after
keyframes_dup = []
for key in smartkeys[1:]:
for i in range(cycle_end_dup):
keydup = smartkey(key)
keydup.frame += float(fcu_range*(i+1))
keydup.frame += float(round(fcu_range, 2)*(i+1))
if hasattr(keydup, 'handle_left'):
#duplicate the tangents tuple values
keydup.handle_left = Vector([key.handle_left[0] + fcu_range*(i+1), key.handle_left[1]])
@@ -127,8 +126,8 @@ def smart_cycle(smartkeys, fcu, frame_start, frame_end):
#if it's the last keyframe then the right handle get the value from the first keyframes
keydup.handle_right = Vector([key.handle_right[0] + fcu_range*(i+1), key.handle_right[1]])
if keydup not in keyframes_dup:
keydup.frame = round(keydup.frame, 2)
keyframes_dup.append(keydup)
#if it's an iternal cycle then duplicate the keyframes before the cycle keyframes
if not mod.cycles_before and mod.mode_before != 'None':
cycle_start_dup = int((fcu.range()[0] - frame_start) /fcu_range)+2
@@ -138,37 +137,52 @@ def smart_cycle(smartkeys, fcu, frame_start, frame_end):
cycle_start_dup = mod.cycles_before
if mod.use_restricted_range and mod.frame_start > (fcu.range()[0] + fcu_range * cycle_start_dup):
cycle_start_dup = int((fcu.range()[0]-mod.frame_start)/fcu_range)+2
#duplicate the keys on the cycle before
for key in smartkeys[:-1]:
for i in range(cycle_start_dup):
keydup = smartkey(key)
keydup.frame -= float(fcu_range*(i+1))
keydup.frame -= fcu_range*(i+1)
if hasattr(keydup, 'handle_left'):
#duplicate the tangents
keydup.handle_left = [key.handle_left[0] - fcu_range*(i+1), key.handle_left[1]]
if hasattr(keydup, 'handle_right'):
keydup.handle_right = [key.handle_right[0] - fcu_range*(i+1), key.handle_right[1]]
#if frame_end > key.frame > frame_start:
if keydup not in keyframes_dup:
keydup.frame = round(keydup.frame, 2)
keyframes_dup.append(keydup)
#merge the keyframes from the cycle with the or iginal keyframes
smartkeys.extend(keyframes_dup)
smartkeys = list(set(smartkeys))
smartkeys.sort()
if mod.use_restricted_range:
smartkeys = smart_start_end(smartkeys, mod.frame_start, mod.frame_end)
smartkeys = smart_start_end(smartkeys, mod.frame_start+1, mod.frame_end-1)
return smartkeys
def smart_bake(context):
#record all the keyframes into smartkeys
obj = context.object
frame_start, frame_end = context.scene.als.bake_range
fcu_smartkeys = {}
anim_data = anim_layers.anim_data_type(obj)
# Initialize the progress bar
wm = context.window_manager
total_iterations = 0
for track in anim_data.nla_tracks:
if track.mute:
continue
if len(track.strips) != 1 or track.strips[0].action is None:
continue
fcurves = anim_layers.get_fcurves(obj, track.strips[0].action)
total_iterations += len(fcurves)
wm.progress_begin(0, total_iterations)
processed = 0
for layer, track in zip(obj.Anim_Layers, anim_data.nla_tracks):
if track.mute:
continue
@@ -181,7 +195,8 @@ def smart_bake(context):
for strip_fcu in strip.fcurves:
strip_keyframes = [keyframe for keyframe in strip_fcu.keyframe_points if len(strip_fcu.keyframe_points) and not strip_fcu.mute]
for fcu in strip.action.fcurves:
fcurves = anim_layers.get_fcurves(obj, strip.action)
for fcu in fcurves:
if not fcu.is_valid or fcu.mute or selected_bones_filter(obj, fcu.data_path):
continue
smartkeys = []
@@ -192,9 +207,12 @@ def smart_bake(context):
if strip.blend_type in {'COMBINE', 'REPLACE'}:
keyframe.handle_left = Vector(key.handle_left)
keyframe.handle_right = Vector(key.handle_right)
keyframe.handle_left[0] = strip_start * layer.speed + (keyframe.handle_left[0] - strip_start) * layer.speed + layer.offset
keyframe.handle_right[0] = strip_start * layer.speed + (keyframe.handle_right[0] - strip_start) * layer.speed + layer.offset
#keyframe.frame += layer.offset
keyframe.frame = strip_start * layer.speed + (keyframe.frame - strip_start) * layer.speed + layer.offset
keyframe.frame = strip_start * layer.speed + (keyframe.frame - strip_start) * layer.speed + layer.offset# * layer.speed
keyframe.frame = round(keyframe.frame, 2)
if keyframe not in smartkeys:
smartkeys.append(keyframe)
@@ -210,37 +228,44 @@ def smart_bake(context):
smartkeys.sort()
if len(fcu.modifiers) and obj.als.mergefcurves:
smartkeys = smart_cycle(smartkeys, fcu, frame_start, frame_end)
#apply strip action settings
last_frame = (strip.frame_end - strip.frame_start) / strip.repeat + strip.frame_start
if strip.use_reverse:
for key in smartkeys:
key.frame = last_frame - (key.frame - strip.frame_start)
key.frame = last_frame - (key.frame - strip.frame_start)
if strip.repeat > 1:
smartkeys = smart_start_end(smartkeys, last_frame , last_frame+1) #strip.frame_start
smartkeys = remove_outofrange_keys(smartkeys, strip.frame_start, last_frame+1) #+ layer.offset
smartkeys = smart_repeat(smartkeys, fcu, strip)
if layer.frame_range:
if layer.custom_frame_range:
smartkeys = smart_start_end(smartkeys, strip.frame_start, strip.frame_end)
smartkeys = remove_outofrange_keys(smartkeys, strip.frame_start, strip.frame_end)
#if the strip is cutting with a different strip, then add keyframes in the cut
for layercut in obj.Anim_Layers:
if layercut.mute or not layercut.frame_range or layercut == layer:
if layercut.mute or not layercut.custom_frame_range or layercut == layer:
continue
if strip_start < layercut.frame_start < strip_end:
smartkeys = smart_start_end(smartkeys, (layercut.frame_start-1), strip.frame_end-1)
if strip_start < layercut.frame_end < strip_end:
smartkeys = smart_start_end(smartkeys, (layercut.frame_end+1), strip.frame_end-1)
#if the list of keyframes exists in a different track list then add them
if (fcu.data_path, fcu.array_index) in fcu_smartkeys:
smartkeys = list(set(fcu_smartkeys[(fcu.data_path, fcu.array_index)]+smartkeys))
#Merge all duplicated keyframes
smartkeys = list(set(smartkeys))
smartkeys.sort()
fcu_smartkeys.update({(fcu.data_path, fcu.array_index):smartkeys})
processed += 1
wm.progress_update(processed)
wm.progress_end()
#add inbetweens
for fcu, smartkeys in fcu_smartkeys.items():
if not smartkeys:
@@ -267,11 +292,13 @@ def add_inbetween(smartkeys):
key2 = smartkey()
key2.frame = smartkeys[i].frame + (smartkeys[i+1].frame - smartkeys[i].frame)*2/3
key1.frame = round(key1.frame, 2)
key2.frame = round(key2.frame, 2)
key2.inbetween = True
smartkeys.insert(i+1, key1)
smartkeys.insert(i+2, key2)
i += 3
return smartkeys
class smartkey:
@@ -345,7 +372,8 @@ def mute_modifiers(obj, nla_tracks):
for track in nla_tracks:
if len(track.strips) != 1 or track.strips[0].action is None:
continue
for fcu in track.strips[0].action.fcurves:
fcurves = anim_layers.get_fcurves(obj, track.strips[0].action)
for fcu in fcurves:
if selected_bones_filter(obj, fcu.data_path):
continue
if fcu.extrapolation == 'LINEAR':
@@ -370,7 +398,8 @@ def unmute_modifiers(obj, nla_tracks, modifier_rec):
for track in nla_tracks:
if track.strips[0].action is None:
continue
for fcu in track.strips[0].action.fcurves:
fcurves = anim_layers.get_fcurves(obj, track.strips[0].action)
for fcu in fcurves:
if not fcu.is_valid or selected_bones_filter(obj, fcu.data_path):
continue
if not len(fcu.modifiers):
@@ -398,7 +427,7 @@ def select_keyframed_bones(self, context, obj):
bpy.ops.object.posemode_toggle()
bpy.ops.pose.select_all(action='DESELECT')
for i in range(0, obj.als.layer_index+1):
obj.als.layer_index = i
obj.als['layer_index'] = i
anim_layers.select_layer_bones(self, context)
def mute_constraints(obj):
@@ -422,14 +451,15 @@ def smartbake_apply(obj, nla_tracks, fcu_keys, extrapolations):
# return
# action_range = strip.frame_end - strip.frame_start
for fcu in strip.action.fcurves:
fcurves = anim_layers.get_fcurves(obj, strip.action)
for fcu in fcurves:
if not fcu.is_valid:
continue
if selected_bones_filter(obj, fcu.data_path):
continue
fcu_key = (fcu.data_path, fcu.array_index)
if fcu_key not in fcu_keys.keys():
strip.action.fcurves.remove(fcu)
fcurves.remove(fcu)
continue
#get all the frames of the smart keys
smartkeys = fcu_keys[fcu_key]
@@ -453,34 +483,6 @@ def smartbake_apply(obj, nla_tracks, fcu_keys, extrapolations):
fcu.keyframe_points[-1].co = (smart_key.frame, value)
fcu.update()
#remove unnecessery keyframes
# for i in range(int(strip.action.frame_range[0]),int(strip.action.frame_range[1]+1)):
# if i in smart_frames:
# #get the index of the smart key based on the smart frames + interpolations
# smart_index = (smart_frames.index(i)+1)*3-3
# #if key was founded add the interpolation and handles
# for key in fcu.keyframe_points:
# if key.co[0] != i:
# continue
# key.co[1] = round(key.co[1], 4)
# key.interpolation = smartkeys[smart_index].interpolation
# # key.handle_left_type = smartkeys[smart_index].handle_left_type
# # key.handle_right_type = smartkeys[smart_index].handle_right_type
# key.handle_left_type = 'AUTO_CLAMPED' if smartkeys[smart_index].handle_left_type != 'VECTOR' else 'VECTOR'
# key.handle_right_type = 'AUTO_CLAMPED' if smartkeys[smart_index].handle_right_type != 'VECTOR' else 'VECTOR'
# break
#delete the keys that are not in the list
# else:
# if fcu.data_path.split(".")[-1] in transform_types:
# print('fcu.id_data', fcu.id_data, obj.animation_data.action)
# fcu.keyframe_delete(fcu.data_path.split(".")[-1] ,index = fcu_key[1], frame = i)
# else:
# try:
# fcu.keyframe_delete(fcu.data_path.split(".")[-1], frame = i)
# except TypeError:
# pass
i = 0
while i < len(fcu.keyframe_points):
key = fcu.keyframe_points[i]
@@ -518,7 +520,7 @@ def armature_restore(obj, b_layers, layers_rec, constraint_rec):
def attr_default(obj, fcu_key):
'''Returns the default value or default array value in a list'''
#check if the fcurve source belongs to a bone or obj
if fcu_key[0][:10] == 'pose.bones':
if fcu_key[0][:10] == 'pose.bones':
transform = fcu_key[0].split('.')[-1]
attr = fcu_key[0].split('"')[-2]
bone = fcu_key[0].split('"')[1]
@@ -557,7 +559,7 @@ def attr_default(obj, fcu_key):
attr = fcu_key[0].split('"')[1]
if 'attr' not in locals():
print(fcu_key[0], 'has no attributes returning 0')
# print(fcu_key[0], 'has no attributes returning 0')
return [0]
#since blender 3 access to custom property settings changed
@@ -571,6 +573,7 @@ def attr_default(obj, fcu_key):
return [0]
def selected_bones_filter(obj, fcu_data_path):
'''using obj.als.onlyselected property for the bake'''
if not obj.als.onlyselected:
return False
if obj.mode != 'POSE':
@@ -597,7 +600,6 @@ def evaluate_combine(data_path, added_array, eval_array, array_default, influenc
return eval_array
def frame_evaluation(frame, strip):
frame_eval = frame
#change the frame if the strip is on hold
if frame < strip.frame_start:
@@ -620,6 +622,17 @@ def frame_evaluation(frame, strip):
return frame_eval
def clean_no_user_slots(action):
'''Remove all the slots that are connected to the action and object but not part of the action slot'''
if not hasattr(action, 'slots'):
return
for slot in action.slots:
if slot is None:
continue
if len(slot.users()):
continue
action.slots.remove(slot)
def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, actioncopy, baked_layer = None):
@@ -627,19 +640,37 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
if obj is None:
return
anim_data = anim_layers.anim_data_type(obj)
baked_action = anim_data.action
if obj.als.operator == 'MERGE' and not additive and anim_data.action is not None: #and obj.als.onlyselected
# baked_action = anim_data.action
track = nla_tracks[obj.als.layer_index]
baked_action = track.strips[0].action
clean_no_user_slots(baked_action)
#create the baked fcurve
baked_channelbag = anim_layers.get_channelbag(obj, baked_action)
baked_fcurves = baked_channelbag.fcurves
if obj.als.operator == 'MERGE':# and not additive: # and anim_data.action is not None: #and obj.als.onlyselected
#overwrite action
anim_data.use_tweak_mode = False
#create a duplicate of the action on the merged layer to have a clean action in order to not write over the calculation
action_copy = bpy.data.actions[baked_action.name].copy()
nla_tracks[obj.als.layer_index].strips[0].action = action_copy
baked_action.id_root = obj.als.data_type
track.strips[0].action = action_copy
if hasattr(baked_action, 'id_root'):
baked_action.id_root = obj.als.data_type
blend_types = {'ADD' : '+', 'SUBTRACT' : '-', 'MULTIPLY' : '*'}
fcu_paths = []
# Initialize the progress bar
wm = bpy.context.window_manager
fcu_set = {fcu_key[0] for fcu_key in fcu_keys.keys()}
total_iterations = len(fcu_set)
wm.progress_begin(0, total_iterations) # (start, end range)
processed = 0
for fcu_key in fcu_keys.keys():
if fcu_key[0] in fcu_paths:
continue
@@ -674,18 +705,30 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
for track in nla_tracks:
if track.mute:
continue
if not len(track.strips):
continue
if track.strips[0].action is None:
continue
# if track == baked_layer:
# continue
#finding the channel group of array
fcu = track.strips[0].action.fcurves.find(fcu_key[0], index = i)
channelbag = anim_layers.get_channelbag(obj, track.strips[0].action)
if channelbag is None:
continue
fcurves = channelbag.fcurves
fcu = fcurves.find(fcu_key[0], index = i)
# print(f'track {track.name} fcurves {len(fcurves)}')
if fcu is None:
# print('fcu is none', fcu_key[0], track.name)
continue
group = fcu.group if fcu.group is not None else None
if group is not None:
if group.name in baked_action.groups:
group = baked_action.groups[group.name]
if group.name in baked_channelbag.groups:
group = baked_channelbag.groups[group.name]
else:
group = baked_action.groups.new(group.name)
group = baked_channelbag.groups.new(group.name)
#copy and append Modifiers into mod_list. Mute them if turned on
if len(fcu.modifiers) and not obj.als.mergefcurves:
@@ -697,20 +740,22 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
# modifier_rec.append(mod)
mod.mute = True
extrapolation = True if fcu.extrapolation == 'LINEAR' else False
#### Creating or overwritting (during merge) the new baked fcurves####
baked_fcu = ensure_fcurves_bversion(baked_fcurves, fcu_key[0], i)
#create the baked fcurve
baked_fcu = baked_action.fcurves.find(fcu_key[0], index = i)
if baked_fcu is not None:
baked_action.fcurves.remove(baked_fcu)
baked_fcu = baked_action.fcurves.new(fcu_key[0], index = i)
baked_fcu.color_mode = 'AUTO_RGB'
if group is not None:
if baked_fcu.group != group:
baked_fcu.group = group
if extrapolation:
baked_fcu.extrapolation = 'LINEAR'
baked_fcus.append(baked_fcu)
#select smart bake frame range or every frame in the range
if obj.als.smartbake:
#merge all the smartframe arrays
@@ -726,9 +771,15 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
#ITERATE through all the layers to evaluate
for track in nla_tracks:
if not len(track.strips):
continue
if track.mute or track == baked_layer or track.strips[0].action is None:
continue
strip = track.strips[0]
fcurves = anim_layers.get_fcurves(obj, strip.action)
if not len(fcurves):
continue
if (frame < strip.frame_start or frame > strip.frame_end) and strip.extrapolation == 'NOTHING':
layers_count += 1
continue
@@ -750,11 +801,14 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
added_array = []
missing = 0
for i in range(array_length):
fcu = strip.action.fcurves.find(fcu_key[0], index = i)
fcu = fcurves.find(fcu_key[0], index = i)
#if the fcurve is not found then get the default value
if fcu is None:
missing += 1
value = array_default[i] if blend_type in ('REPLACE', 'COMBINE') else 0
#getting the previous value if the fcurve is missing instead of just default
#the other option would be to use an array for the influence as well
value = eval_array[i] if blend_type in ('REPLACE', 'COMBINE') else 0
else:
value = fcu.evaluate(frame_eval)
added_array.append(value)
@@ -773,7 +827,6 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
eval_array = evaluate_combine(fcu_key[0], added_array, eval_array, array_default, influence)
else:
eval_array = eval('eval_array' + blend_types[blend_type] +' added_array' + '*' + str(influence))
#extrapolation = True if fcu.extrapolation == 'LINEAR' else False
layers_count += 1
if not eval_array.size:
@@ -792,18 +845,11 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
smartkey.value = eval_array[i]
if smartkey.inbetween:
continue
# if hasattr(smartkey, 'handle_left') and not additive:
# if not smartkey.handle_left[1]:
# smartkey.handle_left[1] = array_default[i]
# if hasattr(smartkey, 'handle_right') and not additive:
# if not smartkey.handle_right[1]:
# smartkey.handle_right[1] = array_default[i]
baked_fcu.keyframe_points.add(1)
keyframe = baked_fcu.keyframe_points[-1]
keyframe.co = (frame, eval_array[i])
for baked_fcu in baked_fcus:
if not len(baked_fcu.keyframe_points):
continue
@@ -818,12 +864,32 @@ def AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, step, action
#paste the modifiers to the new baked fcurve
if i in mod_list and not len(baked_fcu.modifiers):
anim_layers.paste_modifiers(baked_fcu, mod_list[i])
processed += 1
wm.progress_update(processed)
wm.progress_end()
if not actioncopy and obj.als.operator == 'MERGE':
bpy.data.actions.remove(action_copy)
return baked_action
def ensure_fcurves_bversion(fcurves, data_path, i):
'''Either use ensure in Blender 5.0 and above or use find and new in older version'''
if hasattr(fcurves, 'ensure'):
baked_fcu = fcurves.ensure(data_path, index = i)
else:
baked_fcu = fcurves.find(data_path, index = i)
if baked_fcu is None:
baked_fcu = fcurves.new(data_path, index = i)
if len(baked_fcu.keyframe_points):
baked_fcu.keyframe_points.clear()
return baked_fcu
def non_recalc_handle_type(baked_keys):
handles_type = bpy.context.scene.als.handles_type
@@ -849,7 +915,9 @@ def add_interpolations(baked_fcu, smartkeys, layers_count = 0):
P2index = 2
if len(baked_keys) != len(keys):
print('unequal length of keys ',baked_fcu.data_path, len(baked_keys), len(keys))
print('set difference ', set([key.frame for key in keys]).difference(set([round(key.co[0], 2) for key in baked_keys])))
print('keys ', [key.frame for key in keys])
print('baked keys ', [round(key.co[0], 2) for key in baked_keys])
print('set difference ', set([key.frame for key in keys]).difference(set([key.co[0] for key in baked_keys])))
baked_keys[0].handle_left_type = 'VECTOR'
baked_keys[-1].handle_right_type = 'VECTOR'
@@ -876,7 +944,6 @@ def add_interpolations(baked_fcu, smartkeys, layers_count = 0):
skip = True
if not smartkeys[P1index].inbetween :
# print(baked_fcu.data_path, baked_keys[i].co[0], 'not with inbetween', P1index, P2index, i)
P1index += 1
P2index += 1
continue
@@ -911,11 +978,10 @@ def add_interpolations(baked_fcu, smartkeys, layers_count = 0):
#iterate through the inbetween smartkeys
P1index += 3
P2index += 3
# baked_fcu.update()
#add in-betweener
def apply_handle_types(baked_keys, smartkeys, i):
handles_type = bpy.context.scene.als.handles_type
@@ -933,35 +999,40 @@ def apply_handle_types(baked_keys, smartkeys, i):
def bake_range_type(self, context):
if self.bake_range_type == 'SCENE':
self.bake_range = frame_start_end(bpy.context.scene)
frame_start, frame_end = frame_start_end(context.scene)
self.bake_range = (int(frame_start), int(frame_end))
if self.bake_range_type == 'KEYFRAMES':
obj = context.object
anim_data = anim_layers.anim_data_type(obj)
frame_end = []
frame_start = []
posebones = context.selected_pose_bones
#if baking only selected bones then find the longest fcurves for the range
if obj.als.onlyselected:
posebones = context.selected_pose_bones
if obj.als.onlyselected and posebones:
bonespath = [bone.path_from_id() for bone in posebones]
#get the frame range from
if not bonespath:
return
for track in obj.animation_data.nla_tracks:
if not len(track.strips):
continue
action = track.strips[0].action
for fcu in action.fcurves:
for track in anim_data.nla_tracks:
if not len(track.strips):
continue
action = track.strips[0].action
if obj.als.onlyselected and posebones:
# Get fcurve range from the selected objects
fcurves = anim_layers.get_fcurves(obj, action)
for fcu in fcurves:
#check if the fcurve is in the selected bones
if any(path in fcu.data_path for path in bonespath):
frame_start.append(fcu.range()[0])
frame_end.append(fcu.range()[1])
else:
for track in obj.animation_data.nla_tracks:
if not len(track.strips):
continue
else:
# Get the action range
action = track.strips[0].action
frame_start.append(action.frame_range[0])
frame_end.append(action.frame_range[1])
# Checking for the longest action in all the actions
if frame_start:
self.bake_range = (int(min(frame_start)), int(max(frame_end)))
@@ -1042,10 +1113,23 @@ class MergeAnimLayerDown(bpy.types.Operator):
obj.als.smartbake = False
subscriptions.subscriptions_remove()
#start = time.time()
# start = time.time()
#define the start and end frame of the bake, according to scene or preview length
frame_start, frame_end = context.scene.als.bake_range
# Incase the strips are shorter then the keyframe range (because scene is shorter)
# Then updating the strips length
for layer, track in zip(obj.Anim_Layers, anim_data.nla_tracks):
if layer.custom_frame_range:
continue
if len(track.strips) != 1:
continue
strip = track.strips[0]
strip.frame_start =frame_start
anim_layers.update_action_frame_range(frame_start, frame_end, layer, strip)
strip.scale = layer.speed
strip.frame_end = frame_end
obj.als.view_all_keyframes = False
if context.scene.frame_current > frame_end:
context.scene.frame_current = frame_end
@@ -1054,8 +1138,9 @@ class MergeAnimLayerDown(bpy.types.Operator):
blendings = [track.strips[0].blend_type for track in nla_tracks[layer_index:] if len(track.strips) == 1]
#define if the new baked layer is going to be additive or replace
additive = False
if obj.als.direction == 'UP' and 'REPLACE' not in blendings and obj.als.baketype == 'AL':
additive = False
if obj.als.direction == 'UP' and 'REPLACE' not in blendings and obj.als.baketype == 'AL' and layer_index:
if 'COMBINE' in blendings:
blend = 'COMBINE'
else:
@@ -1063,15 +1148,19 @@ class MergeAnimLayerDown(bpy.types.Operator):
additive = True
else:
blend = 'REPLACE'
mute_rec = mute_unbaked_layers(layer_index, nla_tracks, additive)
fcu_keys = smart_bake(context)
if obj.als.operator == 'MERGE':
if obj.als.direction == 'DOWN':
obj.als.layer_index = 0
baked_layer = None
action = anim_data.nla_tracks[obj.als.layer_index].strips[0].action
strip = anim_data.nla_tracks[obj.als.layer_index].strips[0]
action = strip.action
if hasattr(strip, 'action_slot'):
action_slot = strip.action_slot
if action is not None: action_name = action.name
#if baking to a new layer then setup the new index and layer
@@ -1109,7 +1198,8 @@ class MergeAnimLayerDown(bpy.types.Operator):
for col in obj.data.collections:
layers_rec.update({col : col.is_visible})
col.is_visible = True
# Select the bones from all the layers
self.shift = True
select_keyframed_bones(self, context, obj)
constraint_rec = mute_constraints(obj)
@@ -1123,7 +1213,7 @@ class MergeAnimLayerDown(bpy.types.Operator):
if not obj.select_get():
obj.select_set(True)
bpy.ops.nla.bake(frame_start = frame_start, frame_end = frame_end, only_selected = True, visual_keying=True, clear_constraints=obj.als.clearconstraints, bake_types = bake_type, step = self.step)
anim_data.action.fcurves.update()
# anim_data.action.fcurves.update()
strip = track.strips[0]
old_action = strip.action
@@ -1133,7 +1223,6 @@ class MergeAnimLayerDown(bpy.types.Operator):
track.strips.remove(strip)
strip = track.strips.new(track.name, 0, action)
anim_layers.tweak_mode_upper_stack(context, obj, anim_data, enter = False)
#strip.action = anim_data.action
if obj.als.smartbake:
smartbake_apply(obj, nla_tracks, fcu_keys, extrapolations)
@@ -1141,35 +1230,39 @@ class MergeAnimLayerDown(bpy.types.Operator):
armature_restore(obj, b_layers, layers_rec, constraint_rec)
unmute_modifiers(obj, nla_tracks, modifier_rec)
anim_data.action = None
# anim_data.action = None
#bpy.data.actions.remove(old_action)
if self.actioncopy:
old_action.name = action_name + '_old'
else:
bpy.data.actions.remove(old_action)
strip.action.name = action_name
# strip.action.name = action_name
if blendings.count('COMBINE') == len(blendings) and len(blendings) and obj.als.direction == 'UP':
track.strips[0].blend_type = 'COMBINE'
else: #use anim layers bake
#print(frame_start, frame_end)
action = AL_bake(frame_start, frame_end, nla_tracks, fcu_keys, additive, self.step, self.actioncopy, baked_layer)
#action = AL_bake(self, frame_start, frame_end, nla_tracks, fcu_keys, additive, baked_layer)
anim_layers.tweak_mode_upper_stack(context, obj, anim_data, enter = False)
track.strips.remove(track.strips[0])
strip = track.strips.new(track.name, 0, action)
strip.blend_type = blend
#track.strips[0].action = action
#removing layers after merge
if obj.als.operator == 'MERGE':
if hasattr(strip, 'action_slot'):
if action_slot in strip.action.slots.values():
strip.action_slot = action_slot
else:
# During NLA Bake slot doesn't exist need to find a new on
strip.action_slot = anim_layers.get_obj_slot(obj, action)
#reset layer settings
baked_layer = obj.Anim_Layers[obj.als.layer_index]
baked_layer.repeat, baked_layer.speed, baked_layer.offset = 1, 1, 0
strip.use_sync_length = False
if baked_layer.frame_range:
baked_layer.frame_range = False
if baked_layer.custom_frame_range:
baked_layer.custom_frame_range = False
baked_layer.frame_start = frame_start
baked_layer.frame_end = frame_end
@@ -1210,7 +1303,6 @@ class MergeAnimLayerDown(bpy.types.Operator):
track.mute = True
else:
track.mute = False
action.use_fake_user = True
anim_layers.register_layers(obj, nla_tracks)
+197 -90
View File
@@ -10,6 +10,46 @@ from mathutils import Quaternion
from . import bake_ops
from . import anim_layers
def attr_default(obj, fcu_key):
#check if the fcurve source belongs to a bone or obj
if fcu_key[0][:10] == 'pose.bones':
transform = fcu_key[0].split('.')[-1]
attr = fcu_key[0].split('"')[-2]
bone = fcu_key[0].split('"')[1]
source = obj.pose.bones[bone]
#in case of shapekey animation
elif fcu_key[0][:10] == 'key_blocks':
attr = fcu_key[0].split('"')[1]
shapekey = obj.data.shape_keys.key_blocks[attr]
return 0 if shapekey.slider_min <= 0 else shapekey.slider_min
#in case of transforms in object mode
else:# fcu_key[0] in transform_types:
source = obj
transform = fcu_key[0]
#check when it's transform property of Blender
if transform in source.bl_rna.properties.keys():
if hasattr(source.bl_rna.properties[transform], 'default_array'):
if len(source.bl_rna.properties[transform].default_array) > fcu_key[1]:
attrvalue = source.bl_rna.properties[transform].default_array[fcu_key[1]]
return attrvalue
#in case of property on object
elif fcu_key[0].split('"')[1] in obj.keys():
attr = fcu_key[0].split('"')[1]
if 'attr' not in locals():
return 0
#since blender 3 access to custom property settings changed
if attr in source:
id_attr = source.id_properties_ui(attr).as_dict()
attrvalue = id_attr['default']
return attrvalue
return 0
def store_handles(key):
#storing the distance between the handles bezier to the key value
handle_r = key.handle_right[1] - key.co[1]
@@ -50,10 +90,17 @@ def add_value(key, value):
apply_handles(key, handle_r, handle_l)
#calculate the difference between current value and the fcurve value
def add_diff(obj, fcurves, path, current_value, eval_array):
def add_diff(obj, fcurves, path, current_value, eval_array):
'''Get the difference value and add it to all selected keyframes'''
if eval_array is None:
return
array_value = current_value - eval_array
if not any(array_value):
return
for i, value in enumerate(array_value):
fcu = fcurves.find(path, index = i)
if fcu is None or not filter_properties(obj, fcu):
@@ -72,7 +119,9 @@ class ScaleValuesOp(bpy.types.Operator):
#reset the values for dragging
self.stop = False
scene = context.scene
scene.multikey['is_dragging'] = True
global is_dragging
is_dragging = True
self.avg_value = dict()
#dictionary of the keyframes and their original INITIAL values
self.keyframes_values = dict()
@@ -81,15 +130,16 @@ class ScaleValuesOp(bpy.types.Operator):
#the average value for each fcurve
self.keyframes_avg_value = dict()
for obj in context.selected_objects:
if obj.animation_data.action is None:
continue
action = obj.animation_data.action
for fcu in action.fcurves:
if obj.mode == 'POSE':
if bake_ops.selected_bones_filter(obj, fcu.data_path):
continue
fcurves = anim_layers.get_fcurves(obj, action)
for fcu in fcurves:
if anim_layers.selected_bones_filter(obj, fcu):
continue
if not filter_properties(obj, fcu):
continue
@@ -112,6 +162,10 @@ class ScaleValuesOp(bpy.types.Operator):
self.keyframes_avg_value.update({key : avg_value})
if not self.keyframes_avg_value:
if 'is_dragging' in globals():
del is_dragging
scene.multikey['scale'] = 1
anim_layers.redraw_areas(['VIEW_3D'])
return('CANCELLED')
context.window_manager.modal_handler_add(self)
@@ -119,41 +173,52 @@ class ScaleValuesOp(bpy.types.Operator):
def modal(self, context, event):
scene = context.scene
scale = scene.multikey.scale
global is_dragging
try:
scene = context.scene
scale = scene.multikey.scale
#Quit the modal operator when the slider is released
if self.stop:
del is_dragging
scene.multikey['scale'] = 1
anim_layers.redraw_areas(['VIEW_3D'])
#modal is being cancelled because of undo issue with the modal running through the property
return {'FINISHED'}
if event.value == 'RELEASE': # Stop the modal on next frame. Don't block the event since we want to exit the field dragging
self.stop = True
return {'PASS_THROUGH'}
for key, key_value in self.keyframes_values.items():
if not key.select_control_point:
continue
if key not in self.keyframes_avg_value:
continue
avg_value = self.keyframes_avg_value[key]
handle_right_value = self.keyframes_handle_right[key]
handle_left_value = self.keyframes_handle_left[key]
#add the value of the distance from the average * scale factor
key.co[1] = avg_value + ((key_value - avg_value)*scale)
key.handle_right[1] = avg_value + ((handle_right_value - avg_value)*scale)
key.handle_left[1] = avg_value + ((handle_left_value - avg_value)*scale)
return {'PASS_THROUGH'}
#Quit the modal operator when the slider is released
if self.stop:
scene.multikey['is_dragging'] = False
scene.multikey['scale'] = 1
anim_layers.redraw_areas(['VIEW_3D'])
#modal is being cancelled because of undo issue with the modal running through the property
return {'FINISHED'}
if event.value == 'RELEASE': # Stop the modal on next frame. Don't block the event since we want to exit the field dragging
except Exception as e:
# Log the error
print("Error:", e)
self['scale'] = 1
self.stop = True
for key, key_value in self.keyframes_values.items():
if not key.select_control_point:
continue
if key not in self.keyframes_avg_value:
continue
avg_value = self.keyframes_avg_value[key]
handle_right_value = self.keyframes_handle_right[key]
handle_left_value = self.keyframes_handle_left[key]
#add the value of the distance from the average * scale factor
key.co[1] = avg_value + ((key_value - avg_value)*scale)
key.handle_right[1] = avg_value + ((handle_right_value - avg_value)*scale)
key.handle_left[1] = avg_value + ((handle_left_value - avg_value)*scale)
return {'PASS_THROUGH'}
del is_dragging
return {'CANCELLED'}
def scale_value(self, context):
if 'is_dragging' in globals():
if is_dragging:
return
scene = context.scene
if scene.multikey.is_dragging:
return
obj = context.object
if obj is None:
@@ -168,7 +233,6 @@ def scale_value(self, context):
if context.mode == 'POSE' and not context.selected_pose_bones:
self['scale'] = 1
return
bpy.ops.anim.multikey_scale_value('INVOKE_DEFAULT')
def random_value(self, context):
@@ -177,10 +241,11 @@ def random_value(self, context):
if obj.animation_data.action is None:
continue
action = obj.animation_data.action
for fcu in action.fcurves:
if obj.mode == 'POSE':
if bake_ops.selected_bones_filter(obj, fcu.data_path):
continue
fcurves = anim_layers.get_fcurves(obj, action)
for fcu in fcurves:
# if obj.mode == 'POSE':
if anim_layers.selected_bones_filter(obj, fcu):
continue
if not filter_properties(obj, fcu):
continue
value_list = []
@@ -197,20 +262,42 @@ def random_value(self, context):
self['randomness'] = 0.1
def evaluate_array(action, fcu_path, frame, array_len):
def evaluate_combine(data_path, added_array, eval_array, array_default, influence):
if 'scale' in data_path:
eval_array = eval_array * (added_array / array_default) ** influence
elif 'rotation_quaternion' in data_path:
#multiply first the influence with the w separatly
added_array[0] = added_array[0] + (1- added_array[0])*(1 - influence)
added_array[1:] *= influence
eval_array = np.array(Quaternion(eval_array) @ Quaternion(added_array))# ** influence
#if it's a custom property
elif 'rotation_euler' not in data_path and 'location' not in data_path:
eval_array = eval_array + (added_array - array_default) * influence
return eval_array
def evaluate_array(fcurves, fcu_path, frame, array_default = [0, 0, 0]):
'''Create an array from all the indexes'''
fcu_array = []
array_len = len(array_default)
#assigning the default array in case
fcu_array = array_default.copy()
#get the missing arrays in case quaternion is not complete
for i in range(array_len):
fcu = action.fcurves.find(fcu_path, index = i)
fcu = fcurves.find(fcu_path, index = i)
if fcu is None:
continue
fcu_array.append(fcu.evaluate(frame))
if not len(fcu_array):
return None
fcu_array[i] = fcu.evaluate(frame)
# if (fcu_array == array_default).all():
# # print('295 return none')
# return None
return np.array(fcu_array)
def evaluate_layers(context, obj, anim_data, fcu, array_len):
def evaluate_layers(context, obj, anim_data, fcu, array_default):
'''Calculate the evaluation of all the layers when using the nla'''
if not hasattr(anim_data, 'nla_tracks') or not anim_data.use_nla:
@@ -219,12 +306,11 @@ def evaluate_layers(context, obj, anim_data, fcu, array_len):
if not len(nla_tracks):
return None
frame = context.scene.frame_current
#blend_types = {'ADD' : '+', 'SUBTRACT' : '-', 'MULTIPLY' : '*'}
blend_types = {'ADD' : '+', 'SUBTRACT' : '-', 'MULTIPLY' : '*'}
fcu_path = fcu.data_path
#array_default = np.array([bake_ops.attr_default(obj, (fcu_path, i)) for i in range(4) if anim_data.action.fcurves.find(fcu_path, index = i) is not None])
array_default = np.array(bake_ops.attr_default(obj, (fcu_path, fcu.array_index)))
eval_array = array_default
eval_array = array_default.copy()
for track in nla_tracks:
if track.mute:
continue
@@ -264,43 +350,49 @@ def evaluate_layers(context, obj, anim_data, fcu, array_len):
frame_eval = last_frame - (frame_eval - strip.frame_start)
offset = (strip.frame_start * 1/strip.scale - strip.action_frame_start) * strip.scale
frame_eval = strip.frame_start * 1/strip.scale + (frame_eval - strip.frame_start) * 1/strip.scale - offset * 1/strip.scale
fcu_array = evaluate_array(action, fcu_path, frame_eval, array_len)
if fcu_array is None:
continue
###EVALUATION###
eval_array = evaluation(blend_type, fcu_path, fcu_array, eval_array, array_default, influence)
fcurves = anim_layers.get_fcurves(obj, action)
eval_array = evaluate_blend_type(fcurves, eval_array, fcu_path, frame_eval, influence, array_default, blend_type, blend_types)
#If there is an action on top of the nla tracks (not using anim layers) add it to the evaluation
if anim_data.action is not None and not anim_data.use_tweak_mode:
fcu_array = evaluate_array(anim_data.action, fcu_path, frame, array_len)
if fcu_array is not None:
eval_array = evaluation(anim_data.action_blend_type, fcu_path, fcu_array, eval_array, array_default, anim_data.action_influence)
return eval_array
#Adding an extra layer from the action outside and on top of the nla
tweak_mode = anim_data.use_tweak_mode
if tweak_mode:
anim_data.use_tweak_mode = False
def evaluation(blend_type, fcu_path, fcu_array, eval_array, array_default, influence):
blend_types = {'ADD' : '+', 'SUBTRACT' : '-', 'MULTIPLY' : '*'}
# fcu_array = evaluate_array(action, fcu_path, frame_eval, array_len)
# if fcu_array is None:
# continue
action = anim_data.action
if action:
influence = anim_data.action_influence
blend_type = anim_data.action_blend_type
fcurves = anim_layers.get_fcurves(obj, action)
eval_array = evaluate_blend_type(fcurves, eval_array, fcu_path, frame, influence, array_default, blend_type, blend_types)
anim_data.use_tweak_mode = tweak_mode
return eval_array
def evaluate_blend_type(fcurves, eval_array, fcu_path, frame, influence,
array_default, blend_type, blend_types):
'''Calculate the value based on the blend type'''
fcu_array = evaluate_array(fcurves, fcu_path, frame, array_default)
if fcu_array is None:
return eval_array
###EVALUATION###
if blend_type =='COMBINE':
if 'location' in fcu_path or 'rotation_euler' in fcu_path:
blend_type = 'ADD'
if blend_type =='REPLACE':
eval_array = eval_array * (1 - influence) + fcu_array * influence
elif blend_type =='COMBINE':
eval_array = bake_ops.evaluate_combine(fcu_path, fcu_array, eval_array, array_default, influence)
eval_array = evaluate_combine(fcu_path, fcu_array, eval_array, array_default, influence)
else:
eval_array = eval('eval_array' + blend_types[blend_type] + 'fcu_array' + '*' + str(influence))
return eval_array
def evaluate_value(self, context):
for obj in context.selected_objects:
anim_data = obj.animation_data
@@ -310,36 +402,51 @@ def evaluate_value(self, context):
return
action = obj.animation_data.action
fcu_paths = []
# fcu_paths = []
transformations = ["rotation_quaternion","rotation_euler", "location", "scale"]
if obj.mode == 'POSE':
bonelist = context.selected_pose_bones if obj.als.onlyselected else obj.pose.bones
for fcu in action.fcurves:
if fcu in fcu_paths:
fcurves = anim_layers.get_fcurves(obj, action)
for fcu in fcurves:
# if fcu in fcu_paths:
# continue
current_value = None
if not filter_properties(obj, fcu):
continue
if obj.mode == 'POSE':
if bake_ops.selected_bones_filter(obj, fcu.data_path):
if anim_layers.selected_bones_filter(obj, fcu):
continue
for bone in bonelist:
#find the fcurve of the bone
if fcu.data_path.rfind(bone.name) != 12 or fcu.data_path[12 + len(bone.name)] != '"':
continue
# transform = fcu.data_path[15 + len(bone.name):]
transform = fcu.data_path.split('"].')[1]
path_split = fcu.data_path.split('"].')
if len(path_split) <= 1:
continue
else:
transform = fcu.data_path.split('"].')[1]
if transform not in transformations:
continue
current_value = getattr(obj.pose.bones[bone.name], transform)
else:
transform = fcu.data_path
current_value = getattr(obj, transform)
eval_array = evaluate_layers(context, obj, anim_data, fcu, len(current_value))
#In case it was completly filtered out and not current value available
if not current_value:
continue
array_default = np.array(bake_ops.attr_default(obj, (fcu.data_path, fcu.array_index)))
eval_array = evaluate_layers(context, obj, anim_data, fcu, array_default)
if eval_array is None:
eval_array = evaluate_array(action, fcu.data_path, context.scene.frame_current, len(current_value))
fcurves = anim_layers.get_fcurves(obj, action)
eval_array = evaluate_array(fcurves, fcu.data_path, context.scene.frame_current, array_default)
#calculate the difference between current value and the fcurve value
add_diff(obj, action.fcurves, fcu.data_path, np.array(current_value), eval_array)
add_diff(obj, fcurves, fcu.data_path, np.array(current_value), eval_array)
class MULTIKEY_OT_Multikey(bpy.types.Operator):
"""Edit all selected keyframes"""
@@ -362,7 +469,7 @@ class MultikeyProperties(bpy.types.PropertyGroup):
#handletype: bpy.props.BoolProperty(name="Keep handle types", description="Keep handle types", default=False, options={'HIDDEN'})
scale: bpy.props.FloatProperty(name="Scale Values Factor", description="Scale percentage from the average value", default=1.0, soft_max = 10, soft_min = -10, step=0.1, precision = 3, update = scale_value)
randomness: bpy.props.FloatProperty(name="Randomness", description="Random Threshold of keyframes", default=0.1, min=0.0, max = 1.0, update = random_value)
is_dragging: bpy.props.BoolProperty(default = False)
# is_dragging: bpy.props.BoolProperty(default = False)
#filters
filter_location: bpy.props.BoolVectorProperty(name="Location", description="Filter Location properties", default=(True, True, True), size = 3, options={'HIDDEN'})
+405 -194
View File
@@ -2,10 +2,26 @@ import bpy
from . import anim_layers
from . import bake_ops
import numpy as np
import time
import inspect
def subscriptions_remove(handler = True):
#clear all handlers and subsciptions
bpy.msgbus.clear_by_owner(bpy.context.scene)
# if scene is None : scene = bpy.context.scene
global subscriptions_owner
if 'subscriptions_owner' in globals():
bpy.msgbus.clear_by_owner(subscriptions_owner)
del subscriptions_owner
global influence_keys, selected_bones
if 'influence_keys' in globals():
del influence_keys
if 'selected_bones' in globals():
del selected_bones
if not handler:
return
if check_handler in bpy.app.handlers.depsgraph_update_pre:
@@ -14,31 +30,43 @@ def subscriptions_remove(handler = True):
bpy.app.handlers.frame_change_post.remove(animlayers_frame)
def subscriptions_add(scene, handler = True):
bpy.msgbus.clear_by_owner(scene)
global initial_call
initial_call = True
subscribe_to_frame_end(scene)
subscribe_to_track_name(scene)
subscribe_to_action_name(scene)
subscribe_to_strip_settings(scene)
subscribe_to_influence(scene)
global func_running
#If I call initial call from here it calls before running the previous functions
#initial_call = False
func_running = False
global subscriptions_owner
if 'subscriptions_owner' in globals():
bpy.msgbus.clear_by_owner(subscriptions_owner)
subscriptions_owner = object()
#Checking if frame range preview was turned on when pressing P
subscribe_to_preview_frame_end(scene)
subscribe_to_track_name(subscriptions_owner)
subscribe_to_action_name(subscriptions_owner)
subscribe_to_strip_settings(subscriptions_owner)
subscribe_to_influence(subscriptions_owner)
if bpy.app.version >= (4, 4, 0):
subscribe_to_action_slot(scene)
if not handler:
return
if check_handler not in bpy.app.handlers.depsgraph_update_pre:
bpy.app.handlers.depsgraph_update_pre.append(check_handler)
if animlayers_frame not in bpy.app.handlers.frame_change_post:
bpy.app.handlers.frame_change_post.append(animlayers_frame)
def animlayers_frame(self, context):
scene = bpy.context.scene
current = scene.frame_current_final
def animlayers_frame(scene, context):
current = scene.frame_current_final
check_scene()
#During Particles bake screen attribute is empty
if bpy.context.screen is None:
return
#Make sure the animation is playing and not just running a motion path
if not bpy.context.screen.is_animation_playing:
return
#Checking if preview range was turned on or off, when using hotkey P it doesn't recognize
#only during the frame handler
if scene.get('framerange_preview') != scene.use_preview_range:
@@ -47,22 +75,28 @@ def animlayers_frame(self, context):
return
frame_start, frame_end = bake_ops.frame_start_end(scene)
# frame_start, frame_end = get_frame_range(scene)
reset_subscription = False
if 'outofrange' not in globals():
global outofrange
outofrange = False if frame_start <= current <= frame_end else True
if frame_start <= current <= frame_end:
outofrange = False if 0 <= current < frame_end else True
if 0 <= current < frame_end:
if outofrange:
frameend_update_callback()
outofrange = False
return
outofrange = True
if current <= frame_end:
return
#In case of running into empty objects then clean AL_objects
clean_AL_objects = False
#iterate only through objects with anim layers turned on
objects = [obj.object for obj in scene.AL_objects]
for obj in objects:
if obj is None:
clean_AL_objects = True
continue
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
return
@@ -74,63 +108,57 @@ def animlayers_frame(self, context):
continue
#checks if the layer has a custom frame range
if obj.Anim_Layers[i].frame_range:
layer = obj.Anim_Layers[i]
if layer.custom_frame_range:
continue
if not reset_subscription:
subscriptions_remove(handler = False)
reset_subscription = True
track.strips[0].frame_end_ui = current + 10
strip = track.strips[0]
if current < 0:
# anim_layers.strip_action_recalc(layer, track.strips[0])
strip.frame_start = current
# track.strips[0].action_frame_start = current * 1/layer.speed - layer.offset * 1/layer.speed
anim_layers.update_action_frame_range(current, frame_end, layer, strip)
strip.frame_end = frame_end + 10.0
elif current >= frame_end:
if strip.frame_start < 0:
strip.frame_start = 0
anim_layers.update_action_frame_range(0, frame_end, layer, strip)
anim_layers.update_action_frame_range(strip.frame_start, current + 10.0, layer, strip)
strip.frame_end = current + 10.0
if clean_AL_objects:
anim_layers.clean_AL_objects(scene)
if reset_subscription:
subscriptions_add(scene, handler = False)
sync_strip_range()
def objects_viewlayer(scene):
'''in case of an object excluded or included in the nla, update it because of an nla bug'''
if len(bpy.context.view_layer.objects) == scene.als.viewlayer_objects:
return
i = 0
while i < len(scene.AL_objects):
obj = scene.AL_objects[i].object
if obj is None:
scene.AL_objects.remove(i)
continue
i += 1
if obj.als.viewlayer and obj not in bpy.context.view_layer.objects.values():
obj.als.viewlayer = False
if not obj.als.viewlayer and obj in bpy.context.view_layer.objects.values():
#anim_data = anim_layers.anim_data_type(obj)
obj.als.upper_stack = False
obj.als.viewlayer = True
obj.als.layer_index = obj.als.layer_index
#anim_layers.tweak_mode_upper_stack(bpy.context, anim_data)
scene.als.viewlayer_objects = len(bpy.context.view_layer.objects)
def check_handler(self, context):
def check_handler(scene):
'''A main function that performs a series of checks using a handler'''
scene = bpy.context.scene
# scene = bpy.context.scene
#Timer for handler
# if 'last_check_time' not in globals():
# global last_check_time
# last_check_time = 0
# current_time = time.time()
# if current_time - last_check_time < 0.01:
# return
# last_check_time = current_time
#if there are no objects included in animation layers then return
if not len(scene.AL_objects):
return
objects_viewlayer(scene)
obj = bpy.context.object
#if the object was removed from the scene, then remove it from anim layers object list
if obj is None:
i = 0
while i < len(scene.AL_objects):
if scene.AL_objects[i].object not in scene.objects.values():
scene.AL_objects.remove(i)
else:
i += 1
anim_layers.clean_AL_objects(scene)
return
if not obj.als.turn_on:
return
anim_data = anim_layers.anim_data_type(obj)
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
return
if not anim_data.use_nla:
@@ -146,8 +174,6 @@ def check_handler(self, context):
active_action_update(obj, anim_data, nla_tracks)
#check if a keyframe was removed
if bpy.context.active_operator is not None:
if bpy.context.active_operator.name in ['Transform', 'Delete Keyframes'] and obj.als.edit_all_keyframes:
anim_layers.edit_all_keyframes()
if bpy.context.active_operator.name == 'Enter Tweak Mode':
if not bpy.context.active_operator.properties['use_upper_stack_evaluation']:
@@ -155,51 +181,76 @@ def check_handler(self, context):
if bpy.context.active_operator.name == 'Move Channels':
anim_layers.visible_layers(obj, nla_tracks)
# check if track and layers are synchronized
if len(nla_tracks) != len(obj.Anim_Layers):
new_layers_names = set(track.name for track in nla_tracks).difference(set(layer.name for layer in obj.Anim_Layers))
anim_layers.visible_layers(obj, nla_tracks)
if obj.als.layer_index > len(obj.Anim_Layers)-1:
obj.als.layer_index = len(obj.Anim_Layers)-1
#update new layer with strip settings
frame_start, frame_end = bake_ops.frame_start_end(bpy.context.scene)
for layer_name in new_layers_names:
if len(nla_tracks[layer_name].strips) != 1:
continue
strip = get_strip_in_meta(nla_tracks[layer_name].strips[0])
layer = obj.Anim_Layers[layer_name]
if (strip.frame_start, strip.frame_end) != (frame_start, frame_end):
layer['frame_range'] = True
update_strip_layer_settings(strip, layer)
layer['action'] = strip.action
# Making sure that scene.als.edit_all_layers_op is not somehow turned on
if not any(item.object.als.edit_all_keyframes for item in scene.AL_objects) and scene.als.edit_all_layers_op:
scene.als.edit_all_layers_op = False
# check if track and layers are synchronized
if track_layer_synchronization(obj, nla_tracks):
return
anim_layers.add_obj_to_animlayers(obj, [item.object for item in scene.AL_objects])
track = nla_tracks[obj.als.layer_index]
sync_frame_range(scene, track, layer)
# sync_strip_range(scene)
always_sync_range(track, layer)
# sync_strip_range(track, layer)
if anim_data.use_tweak_mode and layer.lock:
layer['lock'] = False
elif not anim_data.use_tweak_mode and not layer.lock:
layer['lock'] = True
influence_sync(obj, nla_tracks)
influence_sync(scene, obj, nla_tracks)
# continue if locked
if layer.lock:
return
#In case a keyframe was added and a new action slot was added to anim_data
#Check that it's synchornized with the strip action slot
strip = track.strips[0]
if hasattr(strip, 'action_slot') and strip.action:
if strip.action_slot != anim_data.action_slot:
strip.action_slot = anim_data.action_slot
if obj.als.view_all_keyframes:
anim_layers.hide_view_all_keyframes(obj, anim_data)
check_selected_bones(obj)
influence_check(nla_tracks[obj.als.layer_index])
def track_layer_synchronization(obj, nla_tracks):
'''check if track and layers are synchronized, running only when adding/removing tracks via the nla'''
if len(nla_tracks) == len(obj.Anim_Layers):
return False
new_layers_names = set(track.name for track in nla_tracks).difference(set(layer.name for layer in obj.Anim_Layers))
anim_layers.visible_layers(obj, nla_tracks)
if obj.als.layer_index > len(obj.Anim_Layers)-1:
obj.als.layer_index = len(obj.Anim_Layers)-1
#update new layer with strip settings
frame_start, frame_end = get_frame_range(bpy.context.scene)
for layer_name in new_layers_names:
if len(nla_tracks[layer_name].strips) != 1:
continue
strip = get_strip_in_meta(nla_tracks[layer_name].strips[0])
layer = obj.Anim_Layers[layer_name]
if not layer.custom_frame_range:
continue
if (strip.frame_start, strip.frame_end) != (frame_start, frame_end):
subscriptions_remove()
# print(f'strip.frame_start {strip.frame_start} strip.frame_end {strip.frame_end} frame_start {frame_start} frame_end {frame_end}')
bpy.ops.anim.custom_frame_range_warning('INVOKE_DEFAULT')
return
update_strip_layer_settings(strip, layer)
layer['action'] = strip.action
return True
def active_action_update(obj, anim_data, nla_tracks):
'''updating the active action into the selected layer'''
if obj.Anim_Layers[obj.als.layer_index].lock:
@@ -227,16 +278,62 @@ def get_strip_in_meta(strip):
strip = strip.strips[0]
return strip
def sync_strip_range():
scene = bpy.context.scene
frame_start, frame_end = bake_ops.frame_start_end(scene)
def sync_frame_range(scene, track, layer):
'''Nla strips are not updating with msgbus when changing frame range in the ui
so it checks again during check handler if the frame range is changed and syncs it'''
if scene.frame_current_final > frame_end:
frame_end = scene.frame_current_final + 10
if bpy.context.screen.is_animation_playing:
return
# scene = bpy.context.scene
if not len(track.strips):
return
strip = track.strips[0]
#In case of Custom frame range
if layer['custom_frame_range']:
if (strip.frame_start, strip.frame_end) != (layer.frame_start, layer.frame_end):
update_strip_layer_settings(strip, layer)
else:
#In case of None custom frame range, make the strips adjust to scene frame range
frame_start, frame_end = get_frame_range(scene)
#defining global frame range to check if it was changed in the handler,
# msgbus subsciption is not updated before
if 'frame_range' not in globals():
global frame_range
frame_range = (frame_start, frame_end)
if frame_range != (frame_start, frame_end):
frame_range = (frame_start, frame_end)
frameend_update_callback()
return
#Turn on custom frame range if the current strip is not following the scene frame range
if (round(strip.frame_start, 2), round(strip.frame_end, 2)) != (round(frame_start, 2), round(frame_end, 2)):
subscriptions_remove()
# print('315 custom frame range')
bpy.ops.anim.custom_frame_range_warning('INVOKE_DEFAULT')
return
def sync_strip_range(scene):
'''Checking all the strips if a value was changed in the nla (not including UI changes)
Similiar to sync custom frame range but iterating through all the layers
Currently disabled'''
frame_start, frame_end = get_frame_range(scene)
if 'frame_range' not in globals():
global frame_range
frame_range = (frame_start, frame_end)
clean_AL_objects = False
objects = [obj.object for obj in scene.AL_objects]
for obj in objects:
if obj is None:
#Turn on to clean AL_objects
clean_AL_objects = True
continue
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
continue
@@ -246,20 +343,31 @@ def sync_strip_range():
for i, track in enumerate(nla_tracks):
if len(track.strips) != 1:
continue
if obj.Anim_Layers[i]['frame_range']:
layer = obj.Anim_Layers[i]
if layer['custom_frame_range']:
if (strip.frame_start, strip.frame_end) != (layer.frame_start, layer.frame_end):
update_strip_layer_settings(strip, layer)
continue
strip = track.strips[0]
strip_frame_start = strip.frame_start
strip_frame_end = strip.frame_end
if (strip_frame_start, round(strip_frame_end)) != (0.0, float(frame_end)):
obj.Anim_Layers[i]['frame_range'] = True
if (strip_frame_start, round(strip_frame_end, 2)) != (frame_start, float(frame_end)):
subscriptions_remove()
# print('357 custom_frame_range_warning ')
# print(f'strip_frame_start {strip_frame_start} strip_frame_end {round(strip_frame_end, 2)} frame_start {frame_start} frame_end {float(frame_end)}')
bpy.ops.anim.custom_frame_range_warning('INVOKE_DEFAULT')
return
if clean_AL_objects:
anim_layers.clean_AL_objects(scene)
def always_sync_range(track, layer):
'''sync frame range when always sync turned on'''
if not len(track.strips):
return
if not layer.frame_range:
if not layer.custom_frame_range:
if track.strips[0].use_sync_length:
track.strips[0].use_sync_length = False
return
@@ -273,7 +381,7 @@ def always_sync_range(track, layer):
anim_layers.sync_frame_range(bpy.context)
layer.action_range = strip.action.frame_range
def influence_sync(obj, nla_tracks):
def influence_sync(scene, obj, nla_tracks):
#Tracks that dont have keyframes are locked
for i, track in enumerate(nla_tracks):
@@ -287,56 +395,77 @@ def influence_sync(obj, nla_tracks):
if not len(track.strips[0].fcurves[0].keyframe_points):
#apply the influence property to the temp property when keyframes are removed (but its still locked)
if not track.strips[0].fcurves[0].lock:
obj.Anim_Layers[i].influence = track.strips[0].influence
# obj.Anim_Layers[i]['influence'] = track.strips[0].influence
scene.als['influence'] = track.strips[0].influence
track.strips[0].fcurves[0].lock = True
if obj.animation_data is None:
if scene.animation_data is None:
return
action = obj.animation_data.action
action = scene.animation_data.action
if action is None:
return
#if a keyframe was found in the temporary property then add it to the
data_path = 'Anim_Layers[' + str(obj.als.layer_index) + '].influence'
fcu_influence = action.fcurves.find(data_path)
# data_path = 'Anim_Layers[' + str(obj.als.layer_index) + '].influence'
data_path = 'als.influence'
fcurves = anim_layers.get_fcurves(scene, action, data_type = 'SCENE')
if not len(fcurves):
return
# fcurves = action.fcurves
fcu_influence = fcurves.find(data_path)
if fcu_influence is None:
return
if not len(fcu_influence.keyframe_points):
return
#remove the temporary influence
action.fcurves.remove(fcu_influence)
fcurves.remove(fcu_influence)
#if the action was created just for the influence because of empty object data type then remove the action
if action.name == obj.name + 'Action' and not len(obj.animation_data.nla_tracks) and not len(action.fcurves):
if action.name == scene.name + 'Action' and not len(scene.animation_data.nla_tracks) and not len(fcurves):
bpy.data.actions.remove(action)
if obj.Anim_Layers[obj.als.layer_index].influence_mute:
return
strip = nla_tracks[obj.als.layer_index].strips[0]
if strip.fcurves[0].mute:
return
strip.fcurves[0].lock = False
# if not strip.influence:
# strip.influence = 0.0001
strip.keyframe_insert('influence')
strip.fcurves[0].update()
def influence_check(selected_track):
'''update influence when a keyframe was added without autokey'''
#skip the next steps if a strip is missing or tracks were removed from the nla tracks
if len(selected_track.strips) != 1:# or obj.als.layer_index > len(nla_tracks)-2:
return
if not len(selected_track.strips[0].fcurves):
strip = selected_track.strips[0]
if not len(strip.fcurves):
return
global influence_keys
if selected_track.strips[0].fcurves[0].mute or not len(selected_track.strips[0].fcurves[0].keyframe_points) or bpy.context.scene.tool_settings.use_keyframe_insert_auto:
if strip.fcurves[0].mute or not len(strip.fcurves[0].keyframe_points) or bpy.context.scene.tool_settings.use_keyframe_insert_auto:
if 'influence_keys' in globals():
del influence_keys
return #when the fcurve doesnt have keyframes, or when autokey is turned on, then return
#update if the influence keyframes are changed. influence_keys are first added in influence_update_callback
if 'influence_keys' not in globals():
initialize_influence_keys(strip)
return
wm = bpy.context.window_manager
if not len(wm.operators):
return
if "ANIM_OT_keyframe_insert" not in wm.operators[-1].bl_idname:
return
if influence_keys != [tuple(key.co) for key in selected_track.strips[0].fcurves[0].keyframe_points]:
selected_track.strips[0].fcurves[0].update()
del influence_keys
length = len(strip.fcurves[0].keyframe_points)*2
keyframes = np.zeros(length)
strip.fcurves[0].keyframe_points.foreach_get('co', keyframes)
# Comparing only the values, because if it updates while duplicating or moving frames than it's crashing
if np.array_equal(influence_keys, keyframes):
return
selected_track.strips[0].fcurves[0].update()
influence_keys = keyframes
def check_selected_bones(obj):
'''running in the handler and checking if the selected bones were changed during view multiply layer keyframes'''
@@ -353,23 +482,50 @@ def check_selected_bones(obj):
selected_bones = bpy.context.selected_pose_bones
obj.als.view_all_keyframes = True
def check_scene():
'''update strip frame end after scene change, this is part of the animlayers_frame handler'''
if 'current_scene' not in globals():
global current_scene
current_scene = bpy.context.scene
return
if current_scene != bpy.context.scene:
#remove old scene from subscriptions
subscriptions_remove(handler = False)
frameend_update_callback()
current_scene = bpy.context.scene
#Add the new scene to subscriptions
subscriptions_add(current_scene, handler = False)
########################### MSGBUS SUBSCRIPTIONS #############################
#Callback function for Scene frame end
def get_frame_range(scene):
'''Getting the frame range also when outside of scene frame range'''
frame_start, frame_end = bake_ops.frame_start_end(scene)
#if it's out of range add 10 frames to the current frame, else add 10 frames to the scene frame end
frame_end = scene.frame_current_final + 10.0 if scene.frame_current_final >= frame_end else frame_end + 10.0
frame_start = scene.frame_current_final if scene.frame_current_final < 0 else 0.0
return frame_start, frame_end
def frameend_update_callback():
'''End the strips at the end of the scene or scene preview'''
scene = bpy.context.scene
if not scene.AL_objects:
return
frame_start, frame_end = bake_ops.frame_start_end(scene)
if scene.frame_current_final > frame_end:
frame_end = scene.frame_current_final + 10
#return
subscriptions_remove(handler = False)
frame_start, frame_end = get_frame_range(scene)
clean_AL_objects = False
#Iterating through all the tracks
for AL_item in scene.AL_objects:
obj = AL_item.object
if obj is None or obj not in scene.objects.values():
clean_AL_objects = True
continue
#anim_data = anim_data_type(obj)
anim_datas = anim_layers.anim_datas_append(obj)
@@ -380,32 +536,39 @@ def frameend_update_callback():
if len(anim_data.nla_tracks) != len(obj.Anim_Layers):
continue
for layer, track in zip(obj.Anim_Layers, anim_data.nla_tracks):
if layer.frame_range:
if layer.custom_frame_range:
continue
if len(track.strips) == 1:
track.strips[0].action_frame_start = 0 - layer.offset * 1/layer.speed
track.strips[0].action_frame_end = frame_end * 1/layer.speed - layer.offset * 1/layer.speed
track.strips[0].frame_start = 0
track.strips[0].frame_end = frame_end
track.strips[0].scale = layer.speed
if len(track.strips) != 1:
continue
strip = track.strips[0]
strip.frame_start = frame_start
anim_layers.update_action_frame_range(frame_start, frame_end, layer, strip)
strip.scale = layer.speed
strip.frame_end = frame_end
if clean_AL_objects:
anim_layers.clean_AL_objects(scene)
subscriptions_add(scene, handler = False)
#Subscribe to the scene frame_end
def subscribe_to_frame_end(scene):
'''subscribe_to_frame_end and frame preview end'''
subscribe_end = scene.path_resolve("frame_end", False)
def subscribe_to_preview_frame_end(scene):
'''subscribe_to_preview_frame_end and frame preview end'''
global subscriptions_owner
# subscribe_end = scene.path_resolve("frame_end", False)
# Subscribing to preview frame end since it's not registering in the depsgraph
subscribe_preview_end = scene.path_resolve("frame_preview_end", False)
subscribe_use_preview = scene.path_resolve("use_preview_range", False)
for subscribe in [subscribe_end, subscribe_preview_end, subscribe_use_preview]:
# print('subscribe_to_preview_frame_end')
for subscribe in [subscribe_preview_end, subscribe_use_preview]:
bpy.msgbus.subscribe_rna(
key=subscribe,
owner=scene,
owner=subscriptions_owner,
args=(),
notify=frameend_update_callback,)
bpy.msgbus.publish_rna(key=subscribe)
# bpy.msgbus.publish_rna(key=subscribe)
# def action_framestart_update_callback(*args):
# ''' update the strip start with the action start'''
@@ -413,11 +576,9 @@ def subscribe_to_frame_end(scene):
def track_update_callback():
'''update layers with the tracks name'''
global initial_call
if initial_call:
# initial_call = False
return
# global initial_call
# if initial_call:
# return
if not bpy.context.selected_objects:
return
obj = bpy.context.object
@@ -446,7 +607,7 @@ def track_update_callback():
if len(track.strips) == 1:
track.strips[0].name = track.name
def subscribe_to_track_name(scene):
def subscribe_to_track_name(subscriptions_owner):
'''Subscribe to the name of track'''
#subscribe_track = nla_track.path_resolve("name", False)
@@ -455,21 +616,19 @@ def subscribe_to_track_name(scene):
bpy.msgbus.subscribe_rna(
key=subscribe_track,
# owner of msgbus subcribe (for clearing later)
owner=scene,
owner=subscriptions_owner,
# Args passed to callback function (tuple)
args=(),
# Callback function for property update
notify=track_update_callback,)
bpy.msgbus.publish_rna(key=subscribe_track)
# bpy.msgbus.publish_rna(key=subscribe_track)
def action_name_callback():
'''update layers with the tracks name'''
global initial_call
if initial_call:
# initial_call = False
return
# global initial_call
# if initial_call:
# return
obj = bpy.context.object
if obj is None:
return
@@ -492,7 +651,7 @@ def action_name_callback():
return
layer.name = action.name
def subscribe_to_action_name(scene):
def subscribe_to_action_name(subscriptions_owner):
'''Subscribe to the name of track'''
#subscribe_track = nla_track.path_resolve("name", False)
@@ -500,24 +659,22 @@ def subscribe_to_action_name(scene):
bpy.msgbus.subscribe_rna(
key=subscribe_action,
# owner of msgbus subcribe (for clearing later)
owner=scene,
owner=subscriptions_owner,
# Args passed to callback function (tuple)
args=(),
# Callback function for property update
notify=action_name_callback,)
bpy.msgbus.publish_rna(key=subscribe_action)
# bpy.msgbus.publish_rna(key=subscribe_action)
def influence_update_callback(*args):
def influence_update_callback():
'''update influence'''
global initial_call
if initial_call:
initial_call = False
return
# global initial_call
if not bpy.context.selected_objects:
return
obj = bpy.context.object
scene = bpy.context.scene
#checking if the object has nla tracks, when I used undo it was still calling the property on an object with no nla tracks
if obj is None:
return
@@ -528,41 +685,93 @@ def influence_update_callback(*args):
return
if not len(anim_data.nla_tracks):
return
track = anim_data.nla_tracks[obj.als.layer_index]
i = obj.als.layer_index
track = anim_data.nla_tracks[i]
if len(track.strips) != 1:
return
strip = track.strips[0]
scene.als['influence'] = strip.influence
# obj.Anim_Layers[i]['influence'] = strip.influence
if track.strips[0].fcurves[0].mute or track.strips[0].fcurves[0].lock:
if strip.fcurves[0].mute or strip.fcurves[0].lock:
return
if bpy.context.scene.tool_settings.use_keyframe_insert_auto and len(track.strips[0].fcurves[0].keyframe_points):
track.strips[0].keyframe_insert('influence')
track.strips[0].fcurves[0].update()
if not len(track.strips[0].fcurves[0].keyframe_points):
return
# This is relevant only for autokey update
if not bpy.context.scene.tool_settings.use_keyframe_insert_auto:
return
#if the influence property and fcurve value are not the same then store the keyframes to check in the handler for a change
if track.strips[0].influence != track.strips[0].fcurves[0].evaluate(bpy.context.scene.frame_current):
global influence_keys
influence_keys = [tuple(key.co) for key in track.strips[0].fcurves[0].keyframe_points]
def subscribe_to_influence(scene):
if len(track.strips[0].fcurves[0].keyframe_points):
strip.keyframe_insert('influence')
strip.fcurves[0].update()
return
def initialize_influence_keys(strip):
'''Setting up the influence keys'''
global influence_keys
length = len(strip.fcurves[0].keyframe_points)*2
keyframes = np.zeros(length)
strip.fcurves[0].keyframe_points.foreach_get('co', keyframes)
influence_keys = keyframes
def subscribe_to_influence(subscriptions_owner):
'''Subscribe to the influence of the track'''
subscribe_influence = (bpy.types.NlaStrip, 'influence')
bpy.msgbus.subscribe_rna(
key=subscribe_influence,
# owner of msgbus subcribe (for clearing later)
owner=scene,
owner=subscriptions_owner,
# Args passed to callback function (tuple)
args=(scene,),
args=(),
# Callback function for property update
notify=influence_update_callback,)
bpy.msgbus.publish_rna(key=subscribe_influence)
def subscribe_to_action_slot(subscriptions_owner):
'''Subscribe to the influence of the track'''
subscribe_slot = (bpy.types.NlaStrip, 'action_slot')
def subscribe_to_strip_settings(scene):
bpy.msgbus.subscribe_rna(
key=subscribe_slot,
# owner of msgbus subcribe (for clearing later)
owner=subscriptions_owner,
# Args passed to callback function (tuple)
args=(),
# Callback function for property update
notify=slot_update_callback,)
def slot_update_callback():
'''Always updating action slot in the active action when updated in the strip'''
if not bpy.context.selected_objects:
return
obj = bpy.context.object
if obj is None:
return
anim_data = anim_layers.anim_data_type(obj)
if anim_data is None:
return
if anim_data.action is None:
return
if not len(anim_data.nla_tracks):
return
if not len(obj.Anim_Layers):
return
if not len(anim_data.nla_tracks[obj.als.layer_index].strips):
return
strip = anim_data.nla_tracks[obj.als.layer_index].strips[0]
anim_data.action_slot = strip.action_slot
def subscribe_to_strip_settings(subscriptions_owner):
'''Subscribe to the strip settings of the track'''
frame_start = (bpy.types.NlaStrip, 'frame_start')
frame_end = (bpy.types.NlaStrip, 'frame_end')
action_frame_start = (bpy.types.NlaStrip, 'action_frame_start')
@@ -571,8 +780,8 @@ def subscribe_to_strip_settings(scene):
repeat = (bpy.types.NlaStrip, 'repeat')
attributes = [frame_start, frame_end, action_frame_start, action_frame_end, scale, repeat, frame_start, frame_end]
if bpy.app.version > (3, 2, 0):
if bpy.app.version >= (3, 3, 0):
#this properties exist only after Blender 3.2
frame_start_ui = (bpy.types.NlaStrip, 'frame_start_ui')
frame_end_ui = (bpy.types.NlaStrip, 'frame_end_ui')
@@ -582,23 +791,29 @@ def subscribe_to_strip_settings(scene):
bpy.msgbus.subscribe_rna(
key=key,
# owner of msgbus subcribe (for clearing later)
owner=scene,
owner=subscriptions_owner,
# Args passed to callback function (tuple)
args=(),
# Callback function for property update
notify=strip_settings_callback,)
#bpy.msgbus.publish_rna(key=frame_start)
def update_strip_layer_settings(strip, layer):
layer['speed'] = strip.scale
if not strip.action:
return
if strip.repeat <= 1:
#Reversing the offset calculation based on the action start frame, strip start and scale
action_start = strip.action.frame_range[0]
offset = strip.frame_start - action_start - (strip.action_frame_start - action_start) * strip.scale
else:
#During repeat the offset is based on the distance from the action first keyframe
offset = strip.frame_start - strip.action.frame_range[0]
start_offset = strip.action.frame_range[0] - strip.frame_start
offset = (strip.action_frame_start - strip.frame_start - start_offset) * strip.scale + start_offset
layer['offset'] = round(-offset, 3)
layer['speed'] = strip.scale
layer['offset'] = round(offset, 3)
#If custom frame range is turned off return to not lose frame range values
if not layer.frame_range:
if not layer.custom_frame_range:
return
layer['frame_end'] = strip.frame_end
layer['frame_start'] = strip.frame_start
@@ -607,11 +822,6 @@ def update_strip_layer_settings(strip, layer):
def strip_settings_callback():
'''subscribe_to_strip_settings callback'''
global initial_call
if initial_call:
# initial_call = False
return
if not bpy.context.selected_objects:
return
obj = bpy.context.object
@@ -624,11 +834,12 @@ def strip_settings_callback():
return
if not len(obj.Anim_Layers):
return
strip = anim_data.nla_tracks[obj.als.layer_index].strips[0]
sync_strip_range()
# sync_strip_range()
if not len(anim_data.nla_tracks[obj.als.layer_index].strips):
return
strip = anim_data.nla_tracks[obj.als.layer_index].strips[0]
layer = obj.Anim_Layers[obj.als.layer_index]
update_strip_layer_settings(strip, layer)
anim_layers.redraw_areas([ 'VIEW_3D'])
anim_layers.redraw_areas([ 'VIEW_3D'])
File diff suppressed because it is too large Load Diff
+42 -18
View File
@@ -1803,7 +1803,7 @@ def reorder_bones_matrices(bones_matrices, constrained):
return re_bones_matrices
def paste_bone_matrix(bone, matrix_copied, constrained, x_filter = True):
def paste_bone_matrix(bone, matrix_copied, constrained, bones = {}, x_filter = True):
#running again separatly in case the bones are in a hierarchy and influencing each other
# for bone, matrix_copied in bones_matrices.items():
# Determine whether to use bone.matrix or bone.matrix_world
@@ -1818,10 +1818,14 @@ def paste_bone_matrix(bone, matrix_copied, constrained, x_filter = True):
if x_filter : matrix_copied = filter_matrix_properties(context, getattr(bone, matrix_attr), matrix_copied)
# bone.matrix = bone.id_data.matrix_world.inverted() @ matrix_copied
setattr(bone, matrix_attr, matrix_copied) # bone.id_data.matrix_world.inverted() @
children = set(bone.children_recursive).intersection(bones)
if children or bone in constrained:
# print(f'found children {[child.name for child in children]} in bone {bone.name}' )
context.view_layer.update()
#Check if the bone has constrainsts on it that need extra iteration
if bone not in constrained:
# filter_matrix_properties(context, bone.matrix, matrix_copied)
return
context.view_layer.update()
matrix_copied = reverse_bone_constraints(context, bone, matrix_copied)
if x_filter : matrix_copied = filter_matrix_properties(context, bone.matrix, matrix_copied)
@@ -1832,8 +1836,12 @@ def paste_bone_matrix(bone, matrix_copied, constrained, x_filter = True):
def paste_bones_matrices(bones_matrices, constrained, x_filter = True):
#running again separatly in case the bones are in a hierarchy and influencing each other
pasted_bones = set()
for bone, matrix_copied in bones_matrices.items():
paste_bone_matrix(bone, matrix_copied, constrained, x_filter)
#Get the rest of the bones to check if they are children of the current bone
bones = set(bones_matrices.keys()).difference(pasted_bones)
paste_bone_matrix(bone, matrix_copied, constrained, bones, x_filter)
pasted_bones.add(bone)
class PasteRelativeMatrix(bpy.types.Operator):
"""paste the relative matrix of the selection"""
@@ -2522,7 +2530,15 @@ class ConvertRotationMode(bpy.types.Operator):
# @classmethod
# def poll(cls, context):
# return context.object.type == 'ARMATURE'
def switch_rot_mode_keyframes(self, obj, posebone):
# Switching any rotation mode keyframes to the new rotation mode value using to_rot_mode_index
bone_path = posebone.path_from_id() + '.' if type(posebone) == bpy.types.PoseBone else ''
fcurves = get_fcurves_channelbag(obj, obj.animation_data.action)
fcu_rotation_mode = fcurves.find(data_path = bone_path + 'rotation_mode', index = 0)
if fcu_rotation_mode:
for keyframe in fcu_rotation_mode.keyframe_points:
keyframe.co[1] = self.to_rot_mode_index
def execute(self, context):
scene = context.scene
selected_bones = context.selected_pose_bones
@@ -2530,7 +2546,8 @@ class ConvertRotationMode(bpy.types.Operator):
to_rot_mode = scene.animtoolbox.rotation_mode
to_rot_mode_fcu = rot_mode_to_channel(to_rot_mode)
#Getting the index of the rotation mode we want to convert to
self.to_rot_mode_index = list(scene.animtoolbox.bl_rna.properties['rotation_mode'].enum_items.keys()).index(to_rot_mode)
#get the keyframes from the bones
for posebone in selected_bones:
@@ -2548,16 +2565,21 @@ class ConvertRotationMode(bpy.types.Operator):
keyframes = emp.get_bone_keyframes(posebone, transform)
#get all interpolations and handle types of the keyframes
handle_types = emp.get_bone_keyframes(posebone, transform, property = 'interpolation')
interpolations = handle_types[::3]
handle_left_type = handle_types[1::3]
handle_right_type = handle_types[2::3]
# rotation_mode_keyframes = emp.get_bone_keyframes(posebone, 'rotation_mode')
self.switch_rot_mode_keyframes(obj, posebone)
inbetweens = []
smartframes = sorted(set(map(lambda x: round(x, 2), keyframes[::2])))
inbetweens = add_inbetweens(smartframes)
all_frames = sorted(smartframes + inbetweens)
#get all interpolations and handle types of the keyframes
if len(smartframes) > 1:
handle_types = emp.get_bone_keyframes(posebone, transform, property = 'interpolation')
interpolations = handle_types[::3]
handle_left_type = handle_types[1::3]
handle_right_type = handle_types[2::3]
inbetweens = add_inbetweens(smartframes)
all_frames = sorted(smartframes + inbetweens)
new_path = posebone.path_from_id() + '.' + to_rot_mode_fcu
#define array length
@@ -2632,13 +2654,15 @@ class ConvertRotationMode(bpy.types.Operator):
keyframe = new_fcu.keyframe_points[-1]
keyframe.co = (frame, fcu_keyframes[new_fcu][frame])
keyframe.interpolation = interpolations[frame_index]
keyframe.handle_left_type = handle_left_type[frame_index]
keyframe.handle_right_type = handle_right_type[frame_index]
if inbetweens:
keyframe.interpolation = interpolations[frame_index]
keyframe.handle_left_type = handle_left_type[frame_index]
keyframe.handle_right_type = handle_right_type[frame_index]
new_fcu.update()
add_interpolations(new_fcurves, fcu_inbetweens)
if inbetweens:
add_interpolations(new_fcurves, fcu_inbetweens)
posebone.rotation_mode = to_rot_mode
+64 -57
View File
@@ -20,7 +20,7 @@
bl_info = {
"name": "AnimToolBox",
"author": "Tal Hershkovich",
"version" : (0, 0, 7, 3),
"version" : (0, 0, 8),
"blender" : (3, 2, 0),
"location": "View3D - Properties - Animation Panel",
"description": "A set of animation tools",
@@ -133,15 +133,16 @@ class TempCtrlsBoneSettings(bpy.types.PropertyGroup):
setup: bpy.props.EnumProperty(name = 'Setup Type', description="Describes what kind of setup the bone is part of", override = {'LIBRARY_OVERRIDABLE'},
items = [('NONE', 'No Setup','No Setup Applied', 0),
('WORLDSPACE', 'World Space Ctrl','World Space Ctrl setup', 1),
('TEMPFK', 'Temporary FK setup','Temporary FK chain setup', 2),
('TEMPFK_FLIP', 'Temporary flipped FK setup','Temporary flipped FK chain setup', 3),
('TEMPIK', 'Temporary IK setup','Temporary IK setup', 4),
('POLE', 'Temporary IK Pole setup','Temporary IK Pole', 5),
('PARENTCTRL', 'Parent Ctrl from cursor setup','Parent Ctrl from cursor setup', 6),
('ROOT', 'Root', 'Root Ctrl for all the setups', 7),
('EMPTY', 'Root', 'Root Ctrl for all the setups', 8),
('TRACK_TO', 'Track To','World Space Track to Ctrl setup', 9),
('TRACK_TO_EMPTY', 'Track To Empty','World Space Track to Empty Ctrl setup', 10)])
('WORLDSPACE_CURSOR', 'World Space Cursor Ctrl','World Space Cursor pivot', 2),
('TEMPFK', 'Temporary FK setup','Temporary FK chain setup', 3),
('TEMPFK_FLIP', 'Temporary flipped FK setup','Temporary flipped FK chain setup', 4),
('TEMPIK', 'Temporary IK setup','Temporary IK setup', 5),
('POLE', 'Temporary IK Pole setup','Temporary IK Pole', 6),
('PARENTCTRL', 'Parent Ctrl from cursor setup','Parent Ctrl from cursor setup', 7),
('ROOT', 'Root', 'Root Ctrl for all the setups', 8),
('EMPTY', 'Root', 'Root Ctrl for all the setups', 9),
('TRACK_TO', 'Track To','World Space Track to Ctrl setup', 10),
('TRACK_TO_EMPTY', 'Track To Empty','World Space Track to Empty Ctrl setup', 11)])
#using org mostly to decide if it needs a custom shape
org: bpy.props.EnumProperty(name = 'Org Type', description="Describes what if the function of the bone", override = {'LIBRARY_OVERRIDABLE'},
@@ -152,21 +153,29 @@ class TempCtrlsBoneSettings(bpy.types.PropertyGroup):
shape: bpy.props.BoolProperty(name = "Apply shape", description = "Mark if the bone needs a shape", default = False, override = {'LIBRARY_OVERRIDABLE'})
class TempCtrlsOrgIds(bpy.types.PropertyGroup):
# A collection of the org ids used in each setup. Org ID is the direct connection
# between original bones and ctrls
pass
class TempCtrlsObjectSetups(bpy.types.PropertyGroup):
#located at obj.animtoolbox.ctrl_setups
#name: using string of the id
setup: bpy.props.EnumProperty(name = 'Setup Type', description="Describes what kind of setup the bone is part of",
items = [('NONE', 'No Setup','No Setup Applied', 0),
('WORLDSPACE', 'World Space Ctrl','World Space Ctrl setup', 1),
('TEMPFK', 'Temporary FK setup','Temporary FK chain setup', 2),
('TEMPFK_FLIP', 'Temporary flipped FK setup','Temporary flipped FK chain setup', 3),
('TEMPIK', 'Temporary IK setup','Temporary IK setup', 4),
('PARENTCTRL', 'Parent Ctrl from cursor setup','Parent Ctrl from cursor setup', 5),
('ROOT', 'Root', 'Root Ctrl for all the setups', 6),
('EMPTY', 'Root', 'Root Ctrl for all the setups', 8),
('TRACK_TO', 'Track To','World Space Track to Ctrl setup', 9),
('TRACK_TO_EMPTY', 'Track To Empty','World Space Track to Empty Ctrl setup', 10),
])
('WORLDSPACE_CURSOR', 'World Space Cursor Ctrl','World Space Cursor pivot', 2),
('TEMPFK', 'Temporary FK setup','Temporary FK chain setup', 3),
('TEMPFK_FLIP', 'Temporary flipped FK setup','Temporary flipped FK chain setup', 4),
('TEMPIK', 'Temporary IK setup','Temporary IK setup', 5),
('POLE', 'Temporary IK Pole setup','Temporary IK Pole', 6),
('PARENTCTRL', 'Parent Ctrl from cursor setup','Parent Ctrl from cursor setup', 7),
('ROOT', 'Root', 'Root Ctrl for all the setups', 8),
('EMPTY', 'Root', 'Root Ctrl for all the setups', 9),
('TRACK_TO', 'Track To','World Space Track to Ctrl setup', 10),
('TRACK_TO_EMPTY', 'Track To Empty','World Space Track to Empty Ctrl setup', 11)])
org_ids: bpy.props.CollectionProperty(type = TempCtrlsOrgIds)
class MultikeyProperties(bpy.types.PropertyGroup):
@@ -238,37 +247,6 @@ class AnimToolBoxGlobalSettings(bpy.types.PropertyGroup):
#Blendings
inbetweener : bpy.props.FloatProperty(name='Inbetween Keyframe', description="Adds an inbetween Keyframe between the Layer's neighbor keyframes", soft_min = -1, soft_max = 1, default=0.0, options = set(), update = Tools.add_inbetween_key, override = {'LIBRARY_OVERRIDABLE'})
motion_path: bpy.props.BoolProperty(name = "Motion Path", description = "Flag when Motion Path is on", default = False, override = {'LIBRARY_OVERRIDABLE'})
mp_settings: bpy.props.BoolProperty(name = "Motion Path Settings", description = "Open the settings Menu", default = False, override = {'LIBRARY_OVERRIDABLE'})
mp_keyframe_scale: bpy.props.FloatProperty(name = "Scale Selecgted Keyframes Bounding Box", description = "Change the scale of the bounding box around the selected keyframes ", default = 0.1, step = 0.1, precision = 3)
mp_color_before: bpy.props.FloatVectorProperty(name="Motion Path Before Color", subtype='COLOR', default=(1.0, 0.0, 0.0), min=0.0, max=1.0, description="Motion path color before the current frame")
mp_color_after: bpy.props.FloatVectorProperty(name="Motion Path After Color", subtype='COLOR', default=(0.0, 1.0, 0.0), min=0.0, max=1.0, description="Motion path color before the current frame")
mp_infront: bpy.props.BoolProperty(name = "Motion Path In Front", description = "Display motion path in front of all the objects", default = True, override = {'LIBRARY_OVERRIDABLE'})
mp_points: bpy.props.BoolProperty(name = "Motion Path Points", description = "Display motion path points", default = True, override = {'LIBRARY_OVERRIDABLE'})
mp_lines: bpy.props.BoolProperty(name = "Motion Path Lines", description = "Display motion path lines", default = True, override = {'LIBRARY_OVERRIDABLE'})
mp_handles: bpy.props.BoolProperty(name = "Motion Path Handles", description = "Display motion path handles on keyframe selection", default = True, override = {'LIBRARY_OVERRIDABLE'})
mp_display_frames: bpy.props.BoolProperty(name = "Frame Numbers", description = "Display frame numbers on all the keyframes", default = False, override = {'LIBRARY_OVERRIDABLE'})
mp_handle_types: bpy.props.EnumProperty(name = 'Set Keyframe Handle Type', description="Set handle type for selected keyframes", default = 'AUTO', update = emp.update_handle_type_prop,
items = [('FREE', 'Free', 'Free', 'HANDLE_FREE', 0),
('ALIGNED','Aligned', 'Aligned', 'HANDLE_ALIGNED', 1),
('VECTOR', 'Vector', 'Vector', 'HANDLE_VECTOR', 2),
('AUTO','Automatic', 'Automatic', 'HANDLE_AUTO', 3),
('AUTO_CLAMPED','Auto Clamped', 'Auto Clamped', 'HANDLE_AUTOCLAMPED', 4)])
mp_interpolation: bpy.props.EnumProperty(name = 'Set Interpolation', description="Set Keyframe Interpolation", default = 'BEZIER', update = emp.update_interpolation_prop,
items = [('BEZIER', 'Bezier', 'Bezier', 'IPO_BEZIER', 0),
('LINEAR','Linear', 'Linear', 'IPO_LINEAR', 1),
('CONSTANT', 'Constant', 'Constant', 'IPO_CONSTANT', 2)])
mp_frame_range: bpy.props.EnumProperty(name = 'Frame Range', description="Type of Frame Range", default = 'SCENE', #update = emp.mp_frame_range_update,
items = [('KEYS_ALL', 'All_Keys','Use the Scene Frame Length for the Range', 0),
('SCENE', 'Scene','Use the Scene Frame Length for the Range', 1),
('MANUAL', 'Manual','Custom Frame range using numerical input or the markers frame ranger', 2),
('AROUND', 'Around Frames','Show only around the current frame', 3)])
mp_before: bpy.props.IntProperty(name = "Before", description = "Show the frames Before the current frame", min = 0, default = 10)
mp_after: bpy.props.IntProperty(name = "After", description = "Show the frames After the current frame", min = 0, default = 10)
selected_keyframes: bpy.props.StringProperty(name="Selected Keyframes", description="Serialized representation of selected keyframes")
gizmo_size: bpy.props.IntProperty(name = "Add to Gizmo Size", description = "Addition to Gizmo Size", max = 100, min = -100, default = 10)
#Copy/Pase Matrix
@@ -312,6 +290,13 @@ class AnimToolBoxPreferences(bpy.types.AddonPreferences):
#Editable motion path
keyframes_range: bpy.props.IntProperty(name = "Keyframe Range", description = "The range of distance from the keyframes while hovering over them", min = 5, max = 100, default = 15)
mp_pref: bpy.props.BoolProperty(name = "Editable Motion Path Colors Theme", description = "Set the Color them of editable motion path visualization", default = False)
mp_keyframe_color: bpy.props.FloatVectorProperty(name="Keyframes", subtype='COLOR', default=(1.0, 1.0, 0.0, 1.0), size=4, min=0.0, max=1.0, description="Handles selection color")
mp_handle_color: bpy.props.FloatVectorProperty(name="Handles", subtype='COLOR', default=(1.0, 0.8, 0.2, 1.0), size=4, min=0.0, max=1.0, description="Handles selection color")
mp_remove_color: bpy.props.FloatVectorProperty(name="Remove Keyframes", subtype='COLOR', default=(0.0, 0.5, 1.0, 1.0), size=4, min=0.0, max=1.0, description="Keyframe color displayed before removing")
mp_hover_color: bpy.props.FloatVectorProperty(name="Hover", subtype='COLOR', default=(1.0, 0.4, 0.2, 1.0), size=4, min=0.0, max=1.0, description="Color during Hovering")
mp_handle_selection_color: bpy.props.FloatVectorProperty(name="Handles Selection", subtype='COLOR', default=(0.8, 0.65, 0.6, 0.8), size=4, min=0.0, max=1.0, description="Handles selection color")
mp_key_selection_color: bpy.props.FloatVectorProperty(name="Keyframe Selection", subtype='COLOR', default=(0.8, 0.8, 0.6, 0.8), size=4, min=0.0, max=1.0, description="Keyframe selection color")
# addon updater preferences from `__init__`, be sure to copy all of them
auto_check_update: bpy.props.BoolProperty(
@@ -371,6 +356,22 @@ class AnimToolBoxPreferences(bpy.types.AddonPreferences):
row.prop(self, 'clear_setup')
row.prop(self, 'in_front')
layout.separator()
box = layout.box()
col = box.column()
col.prop(self, 'mp_pref', icon = 'DOWNARROW_HLT', text = 'Editable Motion Path Preferences')
if self.mp_pref:
col.prop(self, 'keyframes_range', text = 'Keyframe Distance Range')
col.label(text = 'Colors Theme')
row = box.row()
row.prop(self, 'mp_keyframe_color')
row.prop(self, 'mp_handle_color')
row.prop(self, 'mp_remove_color')
row = box.row()
row.prop(self, 'mp_hover_color')
row.prop(self, 'mp_key_selection_color')
row.prop(self, 'mp_handle_selection_color')
layout.separator()
col = layout.column()
col.label(text = 'Include Extras: ')
@@ -385,12 +386,14 @@ def loadanimtoolbox_pre(self, context):
if scene.animtoolbox.bake_frame_range:
scene.animtoolbox.bake_frame_range = False
if scene.animtoolbox.motion_path:
scene.animtoolbox.motion_path = False
if scene.emp.motion_path:
scene.emp.motion_path = False
bpy.context.workspace.status_text_set(None)
if 'mp_dh' in dns:
bpy.types.SpaceView3D.draw_handler_remove(dns['mp_dh'], 'WINDOW')
bpy.app.driver_namespace.pop('mp_dh')
bpy.context.scene.emp.selected_keyframes = '{}'
if 'markers_retimer_dh' in dns:
bpy.types.SpaceView3D.draw_handler_remove(dns['markers_retimer_dh'], 'WINDOW')
bpy.app.driver_namespace.pop('markers_retimer_dh')
@@ -411,16 +414,20 @@ def loadanimtoolbox_post(self, context):
if Display.isolate_pose_mode not in bpy.app.handlers.depsgraph_update_pre:
bpy.app.handlers.depsgraph_update_pre.append(Display.isolate_pose_mode)
if scene.animtoolbox.motion_path:
scene.animtoolbox.motion_path = False
if scene.emp.motion_path:
scene.emp.motion_path = False
bpy.context.workspace.status_text_set(None)
if 'mp_dh' in dns:
bpy.types.SpaceView3D.draw_handler_remove(dns['mp_dh'], 'WINDOW')
bpy.app.driver_namespace.pop('mp_dh')
# Reset keyframe selection for motion paths it is not used in window manager
# Because it is used for undo
bpy.context.scene.emp.selected_keyframes = '{}'
Tools.selection_order(self, context)
classes = (TempCtrlsItems, TempCtrlsObjectSetups, TempCtrlsSceneSettings,TempCtrlsBoneSettings, MultikeyProperties, IsolatedRigs,
AnimToolBoxObjectSettings, AnimToolBoxUILayout, AnimToolBoxGlobalSettings) + ui.classes
classes = (TempCtrlsItems, TempCtrlsOrgIds, TempCtrlsObjectSetups, TempCtrlsSceneSettings,TempCtrlsBoneSettings, MultikeyProperties,
IsolatedRigs, AnimToolBoxObjectSettings, AnimToolBoxUILayout, AnimToolBoxGlobalSettings) + ui.classes
addon_keymaps = []
@@ -1,6 +1,6 @@
{
"last_check": "2025-06-19 15:30:39.178174",
"backup_date": "June-19-2025",
"last_check": "2025-09-23 10:58:29.201165",
"backup_date": "September-23-2025",
"update_ready": false,
"ignore": false,
"just_restored": false,
@@ -2101,6 +2101,9 @@ def smartbake(context, org_action, posebones, ids):
for fcu in fcurves:
if path not in fcu.data_path:
continue
#apply the bake only to the transformation channels
if fcu.data_path.split('"].')[-1] not in transformations:
continue
if Tools.filter_properties(context.scene.animtoolbox, fcu):
continue
if posebone.btc.setup in {'TRACK_TO', 'TRACK_TO_EMPTY'} and 'rotation' not in fcu.data_path:
@@ -2108,6 +2111,8 @@ def smartbake(context, org_action, posebones, ids):
if scene.btc.from_origin:
smartfcurve = get_smartfcurve(fcu, smartfcus, posebone, fcu.data_path, fcu.array_index, scene.btc.smartbake)
if smartfcurve is None:
continue
#if it's not the original action then create a new fcurve in org_action where it's baked to and assign it to smartfcurve
#Usefull especially when working inside a new empty layer
if action != org_action and (fcu.data_path, fcu.array_index) not in org_action_fcus:
@@ -2201,7 +2206,7 @@ def smartbake(context, org_action, posebones, ids):
smartfcurve.modifiers.append(mod)
#Remove frames to not include in the bake, in case of custom frame range
if frames_remove:
if frames_remove and smartfcurve:
smartframes = {frame for frame in smartframes if round(frame) not in frames_remove}
smartfcurve.frames = [frame for frame in smartfcurve.frames if round(frame) not in frames_remove]
smartfcurve.interpolations = {frame : interpolation for frame, interpolation in smartfcurve.interpolations.items() if round(frame) not in frames_remove}
@@ -2367,6 +2372,7 @@ def remove_constraints(context, ids, controllers, controlled_objs):
ctrls = list(controllers) + [ctrl.children[0] for ctrl in controllers if ctrl.children]
scene = context.scene
for obj in controlled_objs:
if obj.type != 'ARMATURE':
continue
@@ -2378,16 +2384,17 @@ def remove_constraints(context, ids, controllers, controlled_objs):
#check if the bone has anything assigned to it
if not bone.btc.setup_id:
continue
#reset the setup_id
bone.btc.setup_id = 0
bone.btc.org_id = 0
bone.btc.org = bone.btc.setup ='NONE'
for con in bone.constraints:
if not hasattr(con, 'target'):
continue
if con.target not in ctrls:
continue
#reset the setup_id
bone.btc.setup_id = 0
bone.btc.org_id = 0
bone.btc.org = bone.btc.setup ='NONE'
con_path = con.path_from_id()
#Removing target because of a bug in Blender 4.4, otherwise it crashes when switching mode
con.target = None
@@ -2481,6 +2488,13 @@ def get_controllers_controlled(context):
controlled_objs = {item.controlled for item in scene.btc.ctrl_items if item.controlled}
controllers = {item.controller for item in scene.btc.ctrl_items if item.controller}
#In case controlled objs are not found and there are still bones with ids
#The add the object of this bones to reset them
if not controlled_objs and context.selected_pose_bones:
for bone in context.selected_pose_bones:
if bone.btc.setup_id or bone.btc.org_id:
controlled_objs.add(bone.id_data)
return controllers, controlled_objs
def unhide_org(obj):
@@ -2652,9 +2666,9 @@ def get_bone_ids(context, id = 'setup_id'):
if select_filter == 'ALL':
#get ids from All the controller rigs and bones
# org_ids = {bone.btc.org_id for obj in scene.objects if obj.animtoolbox.controlled for bone in obj.pose.bones if bone.btc.org_id}
for obj in scene.objects:
if not obj.animtoolbox.controlled:
if not obj.animtoolbox.controlled and obj not in context.selected_objects:
#still checking selected objects in case animtoolbox.controlled is empty
continue
if obj.type == 'ARMATURE':
for bone in obj.pose.bones:
@@ -2663,11 +2677,6 @@ def get_bone_ids(context, id = 'setup_id'):
elif obj.type == 'EMPTY' and id == 'setup_id':
if getattr(obj.animtoolbox, id):
ids.add(getattr(obj.animtoolbox, id))
# ids = {getattr(bone.btc, id) for obj in scene.objects if obj.animtoolbox.controlled and obj.type == 'ARMATURE'
# for bone in obj.pose.bones if getattr(bone.btc, id)}
# if id == 'setup_id':
# ids = {getattr(obj.animtoolbox, id) for obj in scene.objects
# if obj.animtoolbox.controlled and getattr(obj.animtoolbox, id)}
return ids
@@ -2814,14 +2823,7 @@ def rebake_connection_ctrls(self, context, obj, rebake_bones, parent, root_name
# constraints_clear(ctrls)
#remove extra channels from the temporary ctrls before removing them
action = obj.animation_data.action
ctrl_paths = [ctrl.path_from_id() for ctrl in ctrls]
fcurves = Tools.get_fcurves_channelbag(obj, action)
for fcu in fcurves:
path = fcu.data_path.split('"].')[0] + ('"]')
if path in ctrl_paths:
fcurves.remove(fcu)
remove_tempctrls_channels(obj, ctrls)
#removing the temporary ctrls
bpy.ops.object.mode_set(mode = 'EDIT')
@@ -2840,6 +2842,22 @@ def rebake_connection_ctrls(self, context, obj, rebake_bones, parent, root_name
return
def remove_tempctrls_channels(obj, ctrls):
#remove extra channels from the temporary ctrls before removing them
if not obj.animation_data:
return
if not obj.animation_data.action:
return
action = obj.animation_data.action
ctrl_paths = [ctrl.path_from_id() for ctrl in ctrls]
fcurves = Tools.get_fcurves_channelbag(obj, action)
for fcu in fcurves:
path = fcu.data_path.split('"].')[0] + ('"]')
if path in ctrl_paths:
fcurves.remove(fcu)
def get_rebake_bones(rig, ids):
#get all the bones with connection (Ctrls and their children)
rebake_bones = []
@@ -2967,8 +2985,8 @@ class Cleanup(bpy.types.Operator):
scene = context.scene
ids = get_bone_ids(context)
controllers, controlled_objs = get_controllers_controlled(context)
if not scene.btc.clean_constraints:
return {'FINISHED'}
#in case the controllers are empties add their ids and if the root is selected
@@ -2977,7 +2995,6 @@ class Cleanup(bpy.types.Operator):
continue
ids.add(ctrl.animtoolbox.setup_id)
controllers_remove_child(ctrl, controllers)
remove_constraints(context, ids, controllers, controlled_objs)
if not scene.btc.clean_ctrls:
@@ -1573,7 +1573,8 @@ class PasteMatrix(bpy.types.Operator):
if bone.id_data.name in objs_matrix:
if bone.name in objs_matrix[bone.id_data.name]:
matrix_copied = objs_matrix[bone.id_data.name][bone.name]
matrix_copied = obj.matrix_world.inverted() @ matrix_copied
#Store the matrices for each bone that will use it
matrix_copied = reverse_childof_constraint(bone, matrix_copied, constrained)
@@ -1662,11 +1663,11 @@ class CopyRelativeMatrix(bpy.types.Operator):
#create a dictionary for all the realtive distance of the bones and objects
objs_matrix_dist = dict()
#get the source bofne or object
#get the source bone or object
if context.active_pose_bone:
source_active = context.active_pose_bone
source_rig_name = source_active.id_data.name
source_matrix = source_active.matrix
source_matrix = source_active.matrix
else:
source_active = context.active_object
source_matrix = source_active.matrix_world
@@ -1681,8 +1682,14 @@ class CopyRelativeMatrix(bpy.types.Operator):
continue
if bone_relative == source_active:
continue
matrix_dist = source_matrix.inverted() @ obj.matrix_world @ bone_relative.matrix# @ obj.matrix_world
#Adding the offset from the armature transform both for the active and relative
rig_offset = obj.matrix_world
if source_active.id_data.type == 'ARMATURE':
rig_offset = source_active.id_data.matrix_world.inverted() @ rig_offset
matrix_dist = source_matrix.inverted() @ rig_offset @ bone_relative.matrix
#store each bone matrix distance in a dictionary
if obj.name in objs_matrix_dist:
objs_matrix_dist[obj.name].update({bone_relative.name : matrix_dist})
@@ -1735,41 +1742,59 @@ def reverse_childof_constraint(source, matrix_source, constrained = set()):
offsets_lerp = []
offset_inv = Matrix.Identity(4)
offset_inv_lerp = Matrix.Identity(4)
#If the source is a bone then get the Armature matrix to add to the calculation
if type(source) == bpy.types.PoseBone:
obj_offset = obj.matrix_world
else:
obj_offset = Matrix.Identity(4)
#iterate and store all the inverted offsets of all the child constraints
for con in source.constraints:
if con.mute or not con.influence:
continue
if hasattr(con, 'target') and con.target is None:
continue
if con.type != 'CHILD_OF':
constrained.add(source)
continue
parent_matrix = con.target.matrix_world
if con.subtarget != '':
if con.subtarget == '':
parent_matrix = obj_offset.inverted() @ con.target.matrix_world
#remove obj.matrix_world when connected to an object
offset = parent_matrix @ con.inverse_matrix - Matrix.Identity(4)
#offset for the scale with influence already included
offset_lerp = Matrix.Identity(4).lerp(parent_matrix @ con.inverse_matrix, con.influence)
else:
parent_matrix = con.target.pose.bones[con.subtarget].matrix
offsets.append(Matrix.Identity(4) + con.influence * (parent_matrix @ con.inverse_matrix - Matrix.Identity(4)))
offsets_lerp.append(Matrix.Identity(4).lerp(parent_matrix @ con.inverse_matrix, con.influence))
if con.target != obj:
parent_matrix = obj_offset.inverted() @ con.target.matrix_world @ parent_matrix
#Include armature object matrix
offset = parent_matrix @ con.inverse_matrix - Matrix.Identity(4)
offset_lerp = Matrix.Identity(4).lerp(parent_matrix @ con.inverse_matrix, con.influence)
#Adding the influence to the offset
offset = Matrix.Identity(4) + con.influence * offset
offset_inv = offset_inv @ offset.inverted()
offset_inv_lerp = offset_inv_lerp @ offset_lerp.inverted()
offsets.append(offset)
if not offsets:
return matrix_source #@ obj.matrix_world.inverted()
return matrix_source
#Multiply all the child constraint inverted offsets
for offset, offsets_lerp in zip(offsets, offsets_lerp):
#offset_inv = offset_inv @ parent_offset_inv
offset_inv = offset_inv @ offset.inverted()
offset_inv_lerp = offset_inv_lerp @ offsets_lerp.inverted()
# add object space if it's a bone
if source != obj:
offset_inv = offset_inv #@ obj.matrix_world.inverted()
#final Matrix values
matrix_basis = offset_inv @ matrix_source
matrix_lerp = offset_inv_lerp @ matrix_source
matrix_lerp = offset_inv_lerp @ matrix_source
loc, rot, scale = matrix_basis.decompose()
loc_lerp, rot_lerp, scale_lerp = matrix_lerp.decompose()
matrix_basis = Matrix.LocRotScale(loc, rot_lerp, scale_lerp)
return matrix_basis
return matrix_basis
def reorder_bones_matrices(bones_matrices, constrained):
#Reordering the bones, so that we apply first the matrix offset to the constrained bones
@@ -1837,9 +1862,11 @@ class PasteRelativeMatrix(bpy.types.Operator):
if 'source_rig_name' in globals():
if source_rig_name in bpy.data.objects:
source_rig = bpy.data.objects[source_rig_name]
source_obj = source_rig
source_bone = source_rig.pose.bones[source_active_name]
#Get the current matrix of the source bone
matrix_source = source_bone.matrix
elif 'source_active_name' in globals():
if source_active_name in bpy.data.objects:
source_obj = bpy.data.objects[source_active_name]
@@ -1854,10 +1881,14 @@ class PasteRelativeMatrix(bpy.types.Operator):
#if the source object was in object mode during copy and now it's pose mode then quit
frame_range, inbetweens = get_frame_range(context, obj)
fcu_inbetweens = dict()
for frame in sorted(frame_range+inbetweens):
scene.frame_set(int(frame))
if obj.mode == 'POSE':
for bone in context.selected_pose_bones:
if bone.id_data != obj:
continue
#check that the selected bone is not the source bone
if bone == source_bone:
continue
@@ -1868,14 +1899,18 @@ class PasteRelativeMatrix(bpy.types.Operator):
if bone.name in objs_matrix_dist[bone.id_data.name]:
bone_matrix_dist = objs_matrix_dist[bone.id_data.name][bone.name]
matrix_new = matrix_source @ bone_matrix_dist
#Adding the offset from the armature transform both for the active and relative
#If it's the same Armature it will cancel each other
rig_offset = obj.matrix_world.inverted()
if source_rig:
rig_offset = rig_offset @ source_rig.matrix_world
matrix_new = rig_offset @ matrix_source @ bone_matrix_dist
#Store the matrices for each bone that will use it
matrix_new = reverse_childof_constraint(bone, matrix_new, constrained)
bones_matrices.update({bone : matrix_new})
matrix_copied = reverse_childof_constraint(bone, matrix_new, constrained)
# if bone not in constrained:
# matrix_copied = filter_matrix_properties(context, bone.matrix, matrix_copied)
#Reordering the bones, so that we apply first the matrix offset to the constrained bones
bones_matrices = reorder_bones_matrices(bones_matrices, constrained)
@@ -1896,16 +1931,16 @@ class PasteRelativeMatrix(bpy.types.Operator):
else:
obj_matrix_dist = matrix_dist
matrix_new = matrix_source @ obj_matrix_dist
matrix_copied = reverse_childof_constraint(target, matrix_new)
matrix_new = matrix_source @ obj_matrix_dist
matrix_new = reverse_childof_constraint(target, matrix_new)
if target not in constrained:
matrix_copied = filter_matrix_properties(context, target.matrix_world, matrix_copied)
target.matrix_world = matrix_copied
matrix_new = filter_matrix_properties(context, target.matrix_world, matrix_new)
target.matrix_world = matrix_new
if target in constrained:
context.view_layer.update()
matrix_copied = reverse_constraint_offset(target.matrix_world, matrix_copied)
target.matrix_world = filter_matrix_properties(context, target.matrix_world, matrix_copied)
matrix_new = reverse_constraint_offset(target.matrix_world, matrix_new)
target.matrix_world = filter_matrix_properties(context, target.matrix_world, matrix_new)
paste_keyframes_get_inbetweens(scene, target, inbetweens, frame, frame_range, fcu_inbetweens)
@@ -20,7 +20,7 @@
bl_info = {
"name": "AnimToolBox",
"author": "Tal Hershkovich",
"version" : (0, 0, 7, 1),
"version" : (0, 0, 7, 3),
"blender" : (3, 2, 0),
"location": "View3D - Properties - Animation Panel",
"description": "A set of animation tools",
@@ -1,17 +1,16 @@
{
"last_check": "2025-06-19 15:30:39.178174",
"backup_date": "",
"last_check": "2025-09-23 10:57:14.918240",
"backup_date": "June-19-2025",
"update_ready": true,
"ignore": false,
"just_restored": false,
"just_updated": false,
"version_text": {
"link": "https://gitlab.com/api/v4/projects/45739913/repository/archive.zip?sha=198933935077e89aa87550163d3747388f2552e8",
"link": "https://gitlab.com/api/v4/projects/45739913/repository/archive.zip?sha=cb445f00491a54eb763f0d8e72eaae3e44e7d0ba",
"version": [
0,
0,
7,
3
8
]
}
}
File diff suppressed because it is too large Load Diff
+16 -16
View File
@@ -46,7 +46,7 @@ def attr_default(obj, fcu_key):
if attr not in obj.data.shape_keys.key_blocks:
return [0]
shapekey = obj.data.shape_keys.key_blocks[attr]
return 0 if shapekey.slider_min <= 0 else shapekey.slider_min
return [0] if shapekey.slider_min <= 0 else shapekey.slider_min
#in case of transforms in object mode
else:# fcu_key[0] in transform_types:
source = obj
@@ -273,6 +273,9 @@ def random_value(self, context):
for key in fcu.keyframe_points:
add_value(key, value * random.uniform(-threshold, threshold))
fcu.update()
self['randomness'] = 0.1
def evaluate_combine(data_path, added_array, eval_array, array_default, influence):
@@ -293,23 +296,17 @@ def evaluate_array(fcurves, fcu_path, frame, array_default = [0, 0, 0]):
'''Create an array from all the indexes'''
array_len = len(array_default)
fcu_array = []
#assigning the default array in case
fcu_array = array_default.copy()
#get the missing arrays in case quaternion is not complete
missing_arrays = []
for i in range(array_len):
fcu = fcurves.find(fcu_path, index = i)
if fcu is None:
missing_arrays.append(i)
continue
fcu_array[i] = fcu.evaluate(frame)
fcu_array.append(fcu.evaluate(frame))
#In case it's a quaternion and missing attributes, then adding from default value
if fcu_array and array_len == 4 and missing_arrays:
for i in missing_arrays:
fcu_array.insert(i, array_default[i])
if not len(fcu_array):
if (fcu_array == array_default).all():
return None
return np.array(fcu_array)
@@ -325,7 +322,7 @@ def evaluate_layers(context, obj, anim_data, fcu, array_default):
blend_types = {'ADD' : '+', 'SUBTRACT' : '-', 'MULTIPLY' : '*'}
fcu_path = fcu.data_path
eval_array = array_default
eval_array = array_default.copy()
for track in nla_tracks:
if track.mute:
@@ -373,6 +370,7 @@ def evaluate_layers(context, obj, anim_data, fcu, array_default):
tweak_mode = anim_data.use_tweak_mode
if tweak_mode:
anim_data.use_tweak_mode = False
action = anim_data.action
if action:
influence = anim_data.action_influence
@@ -425,6 +423,7 @@ def evaluate_value(self, context):
for fcu in fcurves:
if fcu in fcu_paths:
continue
current_value = None
if Tools.filter_properties(context.scene.animtoolbox, fcu):
continue
if obj.mode == 'POSE':
@@ -447,10 +446,11 @@ def evaluate_value(self, context):
else:
transform = fcu.data_path
current_value = getattr(obj, transform)
#In case it was completly filtered out and not current value available
if not current_value:
continue
array_default = np.array(attr_default(obj, (fcu.data_path, fcu.array_index)))
# array_default = np.array([attr_default(obj, (fcu.data_path, i)) for i in range(4)
# if fcurves.find(fcu.data_path, index = i) is not None])
eval_array = evaluate_layers(context, obj, anim_data, fcu, array_default)
if eval_array is None:
fcurves = Tools.get_fcurves_channelbag(obj, action)
+59 -34
View File
@@ -63,6 +63,7 @@ class ANIMTOOLBOX_MT_Temp_Ctrls(bpy.types.Menu):
layout = self.layout
custom_icons = preview_collections["main"]
layout.operator('anim.bake_to_ctrl', text="World Space Ctrls", icon = 'WORLD')
# layout.operator('anim.worldspace_cursor', text="World Space Cursor Ctrls", icon ='ORIENTATION_CURSOR')
layout.operator('anim.bake_to_temp_fk', text="Temp FK Ctrls", icon = 'BONE_DATA')
layout.operator('anim.bake_to_temp_ik', text="Temp IK Ctrls", icon = 'CON_KINEMATIC')
layout.separator()
@@ -163,7 +164,7 @@ class ANIMTOOLBOX_MT_operators(bpy.types.Menu):
layout.separator(factor = 0.5)
layout.operator('anim.switch_collections_visibility', icon = 'COLLECTION_COLOR_06', text = 'Animated Collections Visibilty')
layout.operator('anim.isolate_pose_mode', icon_value = custom_icons["isolate"].icon_id, depress = scene.animtoolbox.isolate_pose_mode)
layout.operator('object.motion_path_operator', text = 'Editable Motion Path', depress = scene.animtoolbox.motion_path, icon_value = custom_icons["mt"].icon_id)
layout.operator('object.motion_path_operator', text = 'Editable Motion Path', depress = scene.emp.motion_path, icon_value = custom_icons["mt"].icon_id)
layout.separator()
layout.prop(context.preferences.addons[__package__].preferences, 'quick_menu', text = 'Use Quick Icons Menu')
# layout.prop(context.window_manager.atb_ui, 'quick_menu', text = 'Use Quick Icons Menu')
@@ -257,7 +258,10 @@ class TEMPCTRLS_PT_Panel(ANIMTOOLBOX_PT_Panel, bpy.types.Panel):
layout = self.layout
box = layout.box()
col = box.column()
col.operator('anim.bake_to_ctrl', text="WorldSpace Ctrls", icon ='WORLD') #
row = col.row()
row.operator('anim.bake_to_ctrl', text="WorldSpace Ctrls", icon ='WORLD') #
row.operator('anim.add_empty_ctrl', text="", icon ='EMPTY_AXIS')
# col.operator('anim.worldspace_cursor', text="WorldSpace Cursor Ctrls", icon ='ORIENTATION_CURSOR')
col.operator('anim.bake_to_temp_fk', text="Temp FK Ctrls", icon = 'BONE_DATA')
col.operator('anim.bake_to_temp_ik', text="Temp IK Ctrls", icon = 'CON_KINEMATIC')
@@ -540,44 +544,65 @@ class ANIMTOOLBOX_PT_Display(ANIMTOOLBOX_PT_Panel, bpy.types.Panel):
box = layout.box()
row = box.row()
row.operator('object.motion_path_operator', text = 'Editable Motion Path', depress = scene.animtoolbox.motion_path, icon_value = custom_icons["mt"].icon_id)
row.prop(scene.animtoolbox, 'mp_settings', text = '', icon = 'SETTINGS')
if scene.animtoolbox.mp_settings:
row = box.row()
row.prop(scene.animtoolbox, 'mp_color_before', text = '')
row.prop(scene.animtoolbox, 'mp_color_after', text = '')
row = box.row()
row.prop(scene.animtoolbox, 'mp_keyframe_scale', text = 'Scale Keyframes Box', icon = 'CUBE')
row = box.row()
row.prop(scene.animtoolbox, 'mp_points', text = 'Points')
row.prop(scene.animtoolbox, 'mp_lines', text = 'Lines')
row = box.row()
row.prop(scene.animtoolbox, 'mp_handles', text = 'Handles')
row.prop(scene.animtoolbox, 'mp_infront', text = 'In Front')
row = box.row()
row.prop(scene.animtoolbox, 'mp_display_frames', text = 'Display Keyframe Numbers')
row = box.row()
row.prop(context.preferences.addons[__package__].preferences, 'keyframes_range', text = 'Keyframe Distance Range')
if context.object is None:
return
row.operator('object.motion_path_operator', text = 'Editable Motion Path', depress = scene.emp.motion_path, icon_value = custom_icons["mt"].icon_id)
emp = scene.emp
row.prop(scene.emp, 'settings', text = '', icon = 'SETTINGS')
if scene.emp.settings:
split = box.split(factor = 0.4)
split.label(text ='Frame Range')
# row.prop(scene.animtoolbox, 'mp_frame_range', text = '')
split.prop(context.scene.animtoolbox, 'mp_frame_range', text = '')
if context.scene.animtoolbox.mp_frame_range == 'MANUAL':
split.prop(emp, 'frame_range', text = '')
if emp.frame_range == 'MANUAL':
row = box.row()
row.prop(context.scene.animtoolbox, 'bake_frame_start', text = 'Start')
row.prop(context.scene.animtoolbox, 'bake_frame_end', text = 'End')
row.operator("anim.markers_bakerange", icon = 'MARKER', text ='', depress = scene.animtoolbox.bake_frame_range)
elif context.scene.animtoolbox.mp_frame_range == 'AROUND':
row = box.row()
row.prop(context.scene.animtoolbox, 'mp_before', text = 'Before')
row.prop(context.scene.animtoolbox, 'mp_after', text = 'After')
row.prop(emp, 'frame_start', text = 'Start')
row.prop(emp, 'frame_end', text = 'End')
# row.operator("anim.markers_bakerange", icon = 'MARKER', text ='', depress = scene.animtoolbox.bake_frame_range)
elif emp.frame_range == 'AROUND':
row = box.row()
row.prop(emp, 'before', text = 'Before')
row.prop(emp, 'after', text = 'After')
box.separator(factor = 0.1)
col = box.column()
col.prop(emp, 'display_size', icon = 'DOWNARROW_HLT')
if emp.display_size:
col.prop(emp, 'thickness', text = 'Line Thickness')
col.prop(emp, 'keyframe_size', text = 'Keyframes Size')
col.prop(emp, 'frame_size', text = 'Frames Size')
box.separator(factor = 0.1)
row = box.row()
row.label(text = 'Visualization Type')
row.prop(emp, 'vis_type', text = '')
if emp.vis_type == 'VELOCITY':
row = box.row()
row.prop(emp, 'velocity_factor', text = '')
row.prop(emp, 'clamp_min', text = '')
row.prop(emp, 'clamp_max', text = '')
row = box.row()
row.prop(emp, 'color_before', text = '')
row.prop(emp, 'color_after', text = '')
row = box.row()
row.prop(emp, 'points', text = 'Points')
row.prop(emp, 'lines', text = 'Lines')
row = box.row()
row.prop(emp, 'handles', text = 'Handles')
row.prop(emp, 'infront', text = 'In Front')
row = box.row()
row.prop(emp, 'display_frames', text = 'Display Keyframe Numbers')
row.separator()
row = box.row()
row.operator('anim.go_to_keyframe')
# row = box.row()
# row.prop(context.preferences.addons[__package__].preferences, 'keyframes_range', text = 'Keyframe Distance Range')
# if context.object is None:
# return
# row.operator("anim.markers_bakerange", icon = 'MARKER', text ='', depress = scene.animtoolbox.bake_frame_range)
class RIGGERTOOLBOX_PT_Panel(ANIMTOOLBOX_PT_Panel, bpy.types.Panel):
bl_label = "Rigger Toolbox"
@@ -697,4 +722,4 @@ def draw_menu(self, context):
layout.operator('anim.isolate_pose_mode', text = '', depress = scene.animtoolbox.isolate_pose_mode, icon_value = custom_icons["isolate"].icon_id)
layout.separator()
layout.operator('object.motion_path_operator', text = '', depress = scene.animtoolbox.motion_path, icon_value = custom_icons["mt"].icon_id)
layout.operator('object.motion_path_operator', text = '', depress = scene.emp.motion_path, icon_value = custom_icons["mt"].icon_id)
@@ -0,0 +1,65 @@
import bpy
from . import bake_utilities
from .. Functions import constants
from .. Functions import visibility_functions
def bake_texture(self, selected_objects, bake_settings):
parent_operator = self
# ----------------------- CREATE INSTANCE --------------------#
lightmap_utilities = bake_utilities.BakeUtilities(parent_operator, selected_objects, bake_settings)
if not lightmap_utilities.checkPBR():
return
# -----------------------SET LIGHTMAP UV--------------------#
lightmap_utilities.set_active_uv_to_lightmap()
# -----------------------SETUP UV'S--------------------#
lightmap_utilities.unwrap_selected()
# -----------------------SETUP ENGINE--------------------#
lightmap_utilities.setup_engine()
# -----------------------SWITCH BACK TO SHOW ORG MATERIAL --------------------#
visibility_functions.preview_bake_texture(self,context=bpy.context)
# ----------------------- CREATE NEW MATERIAL FOR BAKING --------------------#
lightmap_utilities.create_bake_material("_AO")
# -----------------------SETUP NODES--------------------#
lightmap_utilities.add_node_setup()
# ----------------------- BAKING --------------------#
if bake_settings.lightmap_bake:
lightmap_utilities.save_metal_value()
lightmap_utilities.bake(constants.Bake_Passes.lightmap)
lightmap_utilities.load_metal_value()
lightmap_utilities.add_lightmap_flag()
if bake_settings.ao_bake:
lightmap_utilities.bake(constants.Bake_Passes.ao)
lightmap_utilities.cleanup()
del lightmap_utilities
return
def bake_on_plane(self,selected_objects,bake_settings):
parent_operator = self
# ----------------------- CREATE INSTANCE --------------------#
pbr_utilities = bake_utilities.PbrBakeUtilities(parent_operator,selected_objects,bake_settings)
# -----------------------SETUP ENGINE--------------------#
pbr_utilities.setup_engine()
# ----------------------- BAKE --------------------#
pbr_utilities.bake_materials_on_object()
del pbr_utilities
return
@@ -0,0 +1,588 @@
import bpy
from bpy.types import ObjectShaderFx
import mathutils
from .. Functions import node_functions
from .. Functions import image_functions
from .. Functions import constants
from .. Functions import visibility_functions
from .. Functions import material_functions
blender_version = bpy.app.version
class BakeUtilities():
C = bpy.context
D = bpy.data
O = bpy.ops
all_materials = None
image_texture_nodes = None
bake_settings = None
bake_image = None
render_engine = None
selected_objects = None
image_size = None
parent_operator = None
tex_node_name = None
def __init__(self,parent_operator,selected_objects, bake_settings):
self.C = bpy.context
self.D = bpy.data
self.parent_operator = parent_operator
self.render_engine = self.C.scene.render.engine
self.selected_objects = selected_objects
self.all_materials = self.D.materials
self.selected_materials = material_functions.get_selected_materials(self.selected_objects)
self.bake_settings = bake_settings
self.baked_images = []
self.image_texture_nodes = set()
self.image_size = [int(self.C.scene.img_bake_size),
int(self.C.scene.img_bake_size)]
image_name = bake_settings.bake_image_name
self.bake_image = image_functions.create_image(image_name, self.image_size)
def setup_engine(self):
# setup engine
if self.render_engine == 'BLENDER_EEVEE':
self.C.scene.render.engine = 'CYCLES'
# setup device type
self.cycles_device_type = self.C.preferences.addons['cycles'].preferences.compute_device_type
if self.cycles_device_type == 'OPTIX':
self.C.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA'
# setup samples
if self.bake_settings.pbr_bake:
self.C.scene.cycles.samples = self.bake_settings.pbr_samples
if self.bake_settings.lightmap_bake:
self.C.scene.cycles.samples = self.bake_settings.lightmap_samples
if self.bake_settings.ao_bake:
self.C.scene.cycles.samples = self.bake_settings.ao_samples
self.C.scene.render.resolution_percentage = 100
def set_active_uv_to_lightmap(self):
bpy.ops.object.set_active_uv(uv_slot=2)
def checkPBR(self):
for material in self.selected_materials:
self.active_material = material
# check if pbr node exists
check_ok = node_functions.check_pbr(self.parent_operator,material)
if not check_ok :
self.parent_operator.report({'INFO'}, "Material " + material.name + " has no PBR Node !")
return check_ok
def unwrap_selected(self):
if self.bake_settings.unwrap:
self.O.object.add_uv(uv_name=self.bake_settings.uv_name)
# apply scale on linked
sel_objects = self.C.selected_objects
scene_objects = self.D.objects
linked_objects = set()
for sel_obj in sel_objects:
for scene_obj in scene_objects:
if sel_obj.data.original is scene_obj.data and sel_obj is not scene_obj:
linked_objects.add(sel_obj)
# do not apply transform if linked objects in selection
if not len(linked_objects)>0:
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
self.O.object.mode_set(mode='EDIT')
self.O.mesh.reveal()
self.O.mesh.select_all(action='SELECT')
self.O.uv.smart_project(island_margin=self.bake_settings.unwrap_margin)
self.O.object.mode_set(mode='OBJECT')
def create_bake_material(self,material_name_suffix):
bake_materials = []
selected_materials = []
for obj in self.selected_objects:
for slot in obj.material_slots:
selected_materials.append(slot.material)
# switch to ao material if we are on org and ao was already baked
visibility_functions.switch_baked_material(True,"scene")
for obj in self.selected_objects:
for slot in obj.material_slots:
material = slot.material
bake_material_name = material.name + material_name_suffix
# check if material was already baked and continue
if material_name_suffix in material.name:
bake_materials.append(material)
continue
# if not, copy material or take one out of the previewsly filled bake list
else :
bake_material = list(filter(lambda material: material.name == bake_material_name, bake_materials))
if len(bake_material) == 0:
bake_material = material.copy()
bake_material.name = bake_material_name
bake_materials.append(bake_material)
slot.material = bake_material
else:
bake_material = bake_material[0]
slot.material = bake_material
index = bake_material.name.find(".")
if index == -1:
obj.bake_version = ""
else:
obj.bake_version = bake_material.name[index:]
material.use_fake_user = True
# remove duplicate entries
self.selected_materials = list(set(bake_materials))
def add_gltf_material_output_node(self, material):
nodes = material.node_tree.nodes
name = "glTF Material Output"
gltf_node_group = bpy.data.node_groups.new(name, 'ShaderNodeTree')
gltf_node_group.inputs.new("NodeSocketFloat", "Occlusion")
thicknessFactor = gltf_node_group.inputs.new("NodeSocketFloat", "Thickness")
thicknessFactor.default_value = 0.0
gltf_node_group.nodes.new('NodeGroupOutput')
gltf_node_group_input = gltf_node_group.nodes.new('NodeGroupInput')
specular = gltf_node_group.inputs.new("NodeSocketFloat", "Specular")
specular.default_value = 1.0
specularColor = gltf_node_group.inputs.new("NodeSocketColor", "Specular Color")
specularColor.default_value = [1.0,1.0,1.0,1.0]
gltf_node_group_input.location = -200, 0
gltf_settings_node = nodes.get(name)
if gltf_settings_node is None:
gltf_settings_node = nodes.new('ShaderNodeGroup')
gltf_settings_node.name = name
gltf_settings_node.node_tree = bpy.data.node_groups[name]
return gltf_settings_node
def add_gltf_settings_node(self, material):
nodes = material.node_tree.nodes
# create group data
gltf_settings = bpy.data.node_groups.get('glTF Settings')
if gltf_settings is None:
bpy.data.node_groups.new('glTF Settings', 'ShaderNodeTree')
# add group to node tree
gltf_settings_node = nodes.get('glTF Settings')
if gltf_settings_node is None:
gltf_settings_node = nodes.new('ShaderNodeGroup')
gltf_settings_node.name = 'glTF Settings'
gltf_settings_node.node_tree = bpy.data.node_groups['glTF Settings']
# create group inputs
if gltf_settings_node.inputs.get('Occlusion') is None:
gltf_settings_node.inputs.new('NodeSocketFloat','Occlusion')
return gltf_settings_node
def add_image_texture_node(self, material):
nodes = material.node_tree.nodes
# add image texture
if self.bake_settings.lightmap_bake:
self.tex_node_name = self.bake_settings.texture_node_lightmap
if self.bake_settings.ao_bake:
self.tex_node_name = self.bake_settings.texture_node_ao
image_texture_node = node_functions.add_node(material, constants.Shader_Node_Types.image_texture, self.tex_node_name)
image_texture_node.image = self.bake_image
self.bake_image.colorspace_settings.name = "Linear FilmLight E-Gamut"
nodes.active = image_texture_node
# save texture nodes and pbr nodes for later
self.image_texture_nodes.add(image_texture_node)
return image_texture_node
def save_metal_value(self):
for material in self.selected_materials:
pbr_node = node_functions.get_pbr_node(material)
# save metal value
metallic_value = pbr_node.inputs["Metallic"].default_value
pbr_node["original_metallic"] = metallic_value
pbr_node.inputs["Metallic"].default_value = 0
# save metal image
if pbr_node.inputs["Metallic"].is_linked:
# get metal image node, save it in pbr node and remove connection
metal_image_node_socket = pbr_node.inputs["Metallic"].links[0].from_socket
self.metal_image_node_output = metal_image_node_socket
node_functions.remove_link(material,metal_image_node_socket,pbr_node.inputs["Metallic"])
def load_metal_value(self):
for material in self.selected_materials:
pbr_node = node_functions.get_pbr_node(material)
pbr_node.inputs["Metallic"].default_value = pbr_node["original_metallic"]
# reconnect metal image
if hasattr(self,"metal_image_node_output"):
node_functions.make_link(material,self.metal_image_node_output,pbr_node.inputs["Metallic"])
def add_uv_node(self,material):
uv_node = node_functions.add_node(material, constants.Shader_Node_Types.uv, "Second_UV")
uv_node.uv_map = self.bake_settings.uv_name
return uv_node
def position_gltf_setup_nodes(self,material,uv_node,image_texture_node,gltf_settings_node):
nodes = material.node_tree.nodes
# uv node
pbr_node = node_functions.get_pbr_node(material)
pos_offset = mathutils.Vector((-900, 400))
loc = pbr_node.location + pos_offset
uv_node.location = loc
# image texture
loc = loc + mathutils.Vector((300, 0))
image_texture_node.location = loc
# ao node
loc = loc + mathutils.Vector((300, 0))
gltf_settings_node.location = loc
nodes.active = image_texture_node
def add_node_setup(self):
for material in self.selected_materials:
# AO
if self.bake_settings.ao_bake:
uv_node = self.add_uv_node(material)
image_texture_node = self.add_image_texture_node(material)
if blender_version <= (3, 3):
gltf_settings_node = self.add_gltf_settings_node(material)
else:
gltf_settings_node = self.add_gltf_material_output_node(material)
# position
self.position_gltf_setup_nodes(material,uv_node,image_texture_node,gltf_settings_node)
# linking
node_functions.make_link(material, uv_node.outputs["UV"],image_texture_node.inputs['Vector'])
node_functions.make_link(material, image_texture_node.outputs['Color'], gltf_settings_node.inputs['Occlusion'])
# LIGHTMAP
if self.bake_settings.lightmap_bake:
image_texture_node = self.add_image_texture_node(material)
uv_node = self.add_uv_node(material)
# position
image_texture_node.location = mathutils.Vector((-500, 200))
uv_node.location = mathutils.Vector((-700, 200))
# linking
node_functions.make_link(material, uv_node.outputs["UV"],image_texture_node.inputs['Vector'])
def bake(self,bake_type):
channels_to_bake = bake_type
self.baked_images = []
denoise = self.bake_settings.denoise
# no denoise
if not denoise:
channel = bake_type[0]
image = self.bake_images(self.bake_image,channel,denoise)
image_functions.save_image(image,False)
return
# bake channels for denoise
for channel in channels_to_bake:
image_name = self.bake_image.name + "_" + channel
image = image_functions.create_image(image_name,self.bake_image.size)
self.change_image_in_nodes(image)
baked_channel_image = self.bake_images(image,channel,denoise)
image_functions.save_image(image,True)
self.baked_images.append(baked_channel_image)
self.denoise()
def change_image_in_nodes(self,image):
for image_texture_node in self.image_texture_nodes:
if image_texture_node.name == self.tex_node_name:
image_texture_node.image = image
def bake_images(self, image, channel,denoise):
if channel == "NRM":
print("Baking Normal Pass")
self.C.scene.cycles.samples = 1
self.O.object.bake(type="NORMAL", use_clear=self.bake_settings.bake_image_clear, margin=self.bake_settings.bake_margin)
if channel == "COLOR":
print("Baking Color Pass")
self.C.scene.cycles.samples = 1
self.O.object.bake(type="DIFFUSE", pass_filter={'COLOR'}, use_clear=self.bake_settings.bake_image_clear, margin=self.bake_settings.bake_margin)
if channel == "AO":
if not denoise:
self.O.object.bake('INVOKE_DEFAULT',type="AO", use_clear=self.bake_settings.bake_image_clear, margin=self.bake_settings.bake_margin)
else:
self.O.object.bake(type="AO", use_clear=self.bake_settings.bake_image_clear, margin=self.bake_settings.bake_margin)
if channel == "NOISY":
print("Baking Diffuse Pass")
if not denoise:
self.O.object.bake('INVOKE_DEFAULT',type="DIFFUSE", pass_filter={'DIRECT', 'INDIRECT'}, use_clear=self.bake_settings.bake_image_clear, margin=self.bake_settings.bake_margin)
else:
self.O.object.bake(type="DIFFUSE", pass_filter={'DIRECT', 'INDIRECT'}, use_clear=self.bake_settings.bake_image_clear, margin=self.bake_settings.bake_margin)
return image
def denoise(self):
# denoise
if self.bake_settings.lightmap_bake:
denoised_image_path = node_functions.comp_ai_denoise(self.baked_images[0],self.baked_images[1],self.baked_images[2])
self.bake_image.filepath = denoised_image_path
self.bake_image.source = "FILE"
self.change_image_in_nodes(self.bake_image)
# blur
if self.bake_settings.ao_bake and self.bake_settings.denoise:
blur_image_path = node_functions.blur_bake_image(self.baked_images[0],self.baked_images[1])
self.bake_image.filepath = blur_image_path
self.bake_image.source = "FILE"
self.change_image_in_nodes(self.bake_image)
def add_lightmap_flag(self):
for obj in self.selected_objects:
obj.hasLightmap = True
def cleanup(self):
# set back engine
# self.C.scene.render.engine = self.render_engine
self.C.preferences.addons['cycles'].preferences.compute_device_type = self.cycles_device_type
# cleanup images
if self.bake_settings.cleanup_textures:
for img in self.D.images:
if self.bake_image.name in img.name and ("_COLOR" in img.name or "_NRM" in img.name or "_NOISY" in img.name) :
self.D.images.remove(img)
# show image
visibility_functions.show_image_in_image_editor(self.bake_image)
class PbrBakeUtilities(BakeUtilities):
active_material = None
parent_operator = None
def __init__(self,parent_operator,selected_objects, bake_settings):
super().__init__(parent_operator,selected_objects,bake_settings)
self.selected_materials = material_functions.get_selected_materials(selected_objects)
self.parent_operator = parent_operator
def ready_for_bake(self,material):
# check if not baked material
if "_Bake" in material.name:
print("Skipping cause already baked : " + material.name)
return False
print("\n Checking " + material.name + "\n")
# check if renderer not set to optix
self.setup_engine()
# check if selected to active is on
bpy.context.scene.render.bake.use_selected_to_active = False
# check if pbr node exists
check_ok = node_functions.check_pbr(self.parent_operator,material) and node_functions.check_is_org_material(self.parent_operator,material)
if not check_ok :
self.parent_operator.report({'INFO'}, "Material " + material.name + " has no PBR Node !")
return False
# copy texture nodes if they are linked multiple times
nodes = material.node_tree.nodes
image_textrure_nodes = node_functions.get_nodes_by_type(nodes,constants.Node_Types.image_texture)
for image_texture_node in image_textrure_nodes:
node_functions.remove_double_linking(material,image_texture_node)
return True
def bake_materials_on_object(self):
for material in self.selected_materials:
self.active_material = material
if not (self.ready_for_bake(material)):
continue
self.add_bake_plane()
self.bake_pbr()
self.create_pbr_bake_material("_Bake")
self.create_nodes_after_pbr_bake()
self.cleanup_nodes()
visibility_functions.switch_baked_material(True,"visible")
def add_bake_plane(self):
material = self.active_material
bake_plane = self.D.objects.get(material.name + "_Bake")
if bake_plane is not None:
self.parent_operator.report({'INFO'}, 'Delete Bake Plane')
return
self.O.mesh.primitive_plane_add(size=2, location=(2, 0, 0))
bake_plane = self.C.object
bake_plane.name = material.name + "_Bake"
bake_plane.data.materials.append(material)
def bake_pbr(self):
material = self.active_material
material.use_fake_user = True
nodes = material.node_tree.nodes
pbr_node = node_functions.get_pbr_node(material)
pbr_inputs = node_functions.get_pbr_inputs(pbr_node)
image_texture_node = None
# mute texture mapping
if self.bake_settings.mute_texture_nodes:
node_functions.mute_all_texture_mappings(material, True)
for pbr_input in pbr_inputs.values():
# -----------------------TESTING--------------------#
# skip if input has no connection
if not pbr_input.is_linked:
continue
# -----------------------IMAGE --------------------#
image_name = material.name + "_" + pbr_input.name
# find image
bake_image = self.D.images.get(image_name)
# remove image
if bake_image is not None:
self.D.images.remove(bake_image)
bake_image = self.D.images.new(image_name, width=self.image_size[0], height=self.image_size[1])
bake_image.name = image_name
image_texture_node = node_functions.add_node(material,constants.Shader_Node_Types.image_texture,"PBR Bake")
image_texture_node.image = bake_image
nodes.active = image_texture_node
# -----------------------SET COLOR SPACE--------------------#
if pbr_input is not pbr_inputs["base_color_input"]:
bake_image.colorspace_settings.name = "Non-Color"
# -----------------------BAKING--------------------#
if pbr_input is pbr_inputs["normal_input"]:
node_functions.link_pbr_to_output(material, pbr_node)
self.O.object.bake(type="NORMAL", use_clear=True)
else:
node_functions.emission_setup(material, pbr_input.links[0].from_socket)
self.O.object.bake(type="EMIT", use_clear=True)
# unmute texture mappings
node_functions.mute_all_texture_mappings(material, False)
# delete plane
self.O.object.delete()
# cleanup nodes
node_functions.remove_node(material,"Emission Bake")
node_functions.remove_node(material,"PBR Bake")
node_functions.reconnect_PBR(material, pbr_node)
def create_pbr_bake_material(self,material_name_suffix):
# -----------------------CREATE MATERIAL--------------------#
org_material = self.active_material
bake_material_name = org_material.name + material_name_suffix
bake_material = bpy.data.materials.get(bake_material_name)
if bake_material is not None:
bpy.data.materials.remove(bake_material)
# and create new from org. material
bake_material = org_material.copy()
bake_material.name = bake_material_name
self.bake_material = bake_material
def create_nodes_after_pbr_bake(self):
# -----------------------SETUP VARS--------------------#
org_material = self.active_material
bake_material = self.bake_material
nodes = bake_material.node_tree.nodes
pbr_node = node_functions.get_pbr_node(bake_material)
pbr_inputs = node_functions.get_pbr_inputs(pbr_node)
for pbr_input in pbr_inputs.values():
if not pbr_input.is_linked:
continue
# -----------------------REPLACE IMAGE TEXTURES--------------------#
first_node_after_input = pbr_input.links[0].from_node
tex_node = node_functions.get_node_by_type_recusivly(bake_material,first_node_after_input,constants.Node_Types.image_texture,True)
bake_image_name = org_material.name + "_" + pbr_input.name
bake_image = self.D.images.get(bake_image_name)
# if no texture node found (baking procedural textures) add new one
if tex_node is None:
tex_node = node_functions.add_node(bake_material,constants.Shader_Node_Types.image_texture,bake_image_name)
# keep org image if nothing changed
if bake_image is None:
org_image = self.D.images.get(tex_node.image.org_image_name)
tex_node.image = org_image
else:
image_functions.save_image(bake_image)
tex_node.image = bake_image
# -----------------------LINKING--------------------#
if pbr_input is pbr_inputs["normal_input"]:
normal_node = first_node_after_input
normal_node.inputs["Strength"].default_value = 1
if normal_node.type == constants.Node_Types.bump_map:
bump_node = normal_node
normal_node = node_functions.add_node(bake_material,constants.Shader_Node_Types.normal,"Normal from Bump")
normal_node.location = bump_node.location
nodes.remove(bump_node)
node_functions.make_link(bake_material, tex_node.outputs[0], normal_node.inputs["Color"])
node_functions.make_link(bake_material, normal_node.outputs["Normal"], pbr_input)
else:
node_functions.make_link(bake_material,tex_node.outputs[0], pbr_input)
# -----------------------SET COLOR SPACE--------------------#
if pbr_input is not pbr_inputs["base_color_input"]:
tex_node.image.colorspace_settings.name = "Non-Color"
self.active_material = bake_material
return bake_material
def cleanup_nodes(self):
bake_material = self.active_material
node_functions.remove_unused_nodes(bake_material)
+1
View File
@@ -0,0 +1 @@
lorenz.wieseke.glbtexturetools
@@ -0,0 +1,13 @@
def Diff(li1, li2):
return (list(set(li1) - set(li2)))
def Intersection(li1, li2):
set1 = set(li1)
set2 = set(li2)
return list(set.intersection(set1,set2))
def flatten(t):
return [item for sublist in t for item in sublist]
def remove_duplicate(l):
return list(dict.fromkeys(l))
@@ -0,0 +1,39 @@
import os
import bpy
class Node_Types:
image_texture = 'TEX_IMAGE'
pbr_node = 'BSDF_PRINCIPLED'
mapping = 'MAPPING'
normal_map = 'NORMAL_MAP'
bump_map = 'BUMP'
material_output = 'OUTPUT_MATERIAL'
class Shader_Node_Types:
emission = "ShaderNodeEmission"
image_texture = "ShaderNodeTexImage"
mapping = "ShaderNodeMapping"
normal = "ShaderNodeNormalMap"
ao = "ShaderNodeAmbientOcclusion"
uv = "ShaderNodeUVMap"
comp_image_node = 'CompositorNodeImage'
mix ="ShaderNodeMixRGB"
class Bake_Passes:
pbr = ["EMISSION"]
lightmap = ["NOISY", "NRM", "COLOR"]
ao = ["AO","COLOR"]
class Material_Suffix:
bake_type_mat_suffix = {
"pbr" : "_Bake",
"ao" : "_AO",
"lightmap" : "_AO"
}
class Path_List:
def get_project_dir():
return os.path.dirname(bpy.data.filepath)
def get_textures_dir():
return os.path.join(os.path.dirname(bpy.data.filepath),'textures','GLBTexTool')
@@ -0,0 +1,91 @@
import bpy
from bpy.app.handlers import persistent
def update_pbr_button(self,context):
self["lightmap_bake"] = False
self["ao_bake"] = False
def update_lightmap_button(self,context):
self["pbr_bake"] = False
self["ao_bake"] = False
update_active_element_in_bake_list()
def update_ao_button(self,context):
self["lightmap_bake"] = False
self["pbr_bake"] = False
update_active_element_in_bake_list()
# ----------------------- UPDATE BAKE IMAGE NAME / ENUM--------------------#
last_selection = []
@persistent
def update_on_selection(scene):
C = bpy.context
global last_selection
object = getattr(C,"object",None)
if object is None:
return
if C.selected_objects != last_selection:
last_selection = C.selected_objects
update_active_element_in_bake_list()
def update_bake_list(bake_settings,context):
bake_textures_set = set()
for obj in bpy.data.objects:
if bake_settings.lightmap_bake:
if obj.get("lightmap_name"):
bake_textures_set.add((obj.lightmap_name, obj.lightmap_name, "Baked Texture Name"))
if bake_settings.ao_bake:
if obj.get("ao_map_name"):
bake_textures_set.add((obj.ao_map_name, obj.ao_map_name, "Baked Texture Name"))
if len(bake_textures_set) == 0:
bake_textures_set.add(("-- Baking Groups --","-- Baking Groups --","No Lightmap baked yet"))
return list(bake_textures_set)
def update_active_element_in_bake_list():
C = bpy.context
active_object = C.active_object
bake_settings = C.scene.bake_settings
new_bake_image_name = ""
if bake_settings.lightmap_bake:
new_bake_image_name = active_object.get("lightmap_name")
if new_bake_image_name is None:
new_bake_image_name = "Lightmap " + active_object.name
if bake_settings.ao_bake:
new_bake_image_name = active_object.get("ao_map_name")
if new_bake_image_name is None:
new_bake_image_name = "AO " + active_object.name
enum_items = bake_settings.get_baked_lightmaps()
keys = [key[0] for key in enum_items]
if new_bake_image_name in keys:
bake_settings.bake_image_name = new_bake_image_name
bake_settings.baking_groups = new_bake_image_name
else:
if active_object.type == "MESH":
bake_settings.bake_image_name = new_bake_image_name
def headline(layout,*valueList):
box = layout.box()
row = box.row()
split = row.split()
for pair in valueList:
split = split.split(factor=pair[0])
split.label(text=pair[1])
@persistent
def init_values(self,context):
bpy.context.scene.world.light_settings.distance = 1
@@ -0,0 +1,107 @@
import bpy
import os
from . import node_functions
from . import constants
from bpy.app.handlers import persistent
@persistent
def save_images(self,context):
images = bpy.data.images
for img in images:
if img.is_dirty:
print(img.name)
save_image(img) # img.save()
def get_all_images_in_ui_list():
images_in_scene = bpy.data.images
image_name_list = bpy.types.GTT_TEX_UL_List.image_name_list
images_found = []
if len(image_name_list) > 0:
images_found = [img for img in images_in_scene for name_list_entry in image_name_list if img.name == name_list_entry]
return images_found
def save_image(image,save_internally=False):
if save_internally:
image.pack()
else:
filePath = bpy.data.filepath
path = os.path.dirname(filePath)
if not os.path.exists(path + "/textures"):
os.mkdir(path + "/textures")
if not os.path.exists(path + "/textures/GLBTexTool"):
os.mkdir(path + "/textures/GLBTexTool")
if not os.path.exists(path + "/textures/GLBTexTool/" + str(image.size[0])):
os.mkdir(path + "/textures/GLBTexTool/" + str(image.size[0]))
# file format
image.file_format = bpy.context.scene.img_file_format
# change path
savepath = path + "\\textures\\GLBTexTool\\" + str(image.size[0]) + "\\" + image.name + "." + image.file_format
# image.use_fake_user = True
image.filepath_raw = savepath
image.save()
def create_image(image_name, image_size):
D = bpy.data
# find image
image = D.images.get(image_name)
if image:
old_size = list(image.size)
new_size = list(image_size)
if old_size != new_size:
D.images.remove(image)
image = None
# image = D.images.get(image_name)
if image is None:
image = D.images.new(
image_name, width=image_size[0], height=image_size[1])
image.name = image_name
return image
def get_file_size(filepath):
size = "Unpack Files"
try:
path = bpy.path.abspath(filepath)
size = os.path.getsize(path)
size /= 1024
except:
return ("Unpack")
# print("error getting file path for " + filepath)
return (size)
def scale_image(image, new_size):
if (image.org_filepath != ''):
image.filepath = image.org_filepath
image.org_filepath = image.filepath
if new_size[0] > image.size[0] or new_size[1] > image.size[1]:
new_size[0] = image.size[0]
new_size[1] = image.size[1]
# set image back to original if size is 0, else scale it
if new_size[0] == 0:
image.filepath_raw = image.org_filepath
else:
image.scale(new_size[0], new_size[1])
save_image(image)
@@ -0,0 +1,40 @@
import bpy
def get_all_visible_materials():
objects=[ob for ob in bpy.context.view_layer.objects if ob.visible_get()]
slot_array = [object.material_slots for object in objects]
vis_mat = set()
for slots in slot_array:
for slot in slots:
vis_mat.add(slot.material)
# to remove None values in list
vis_mat = list(filter(None, vis_mat))
return vis_mat
def get_selected_materials(selected_objects):
selected_materials = set()
slots_array = [obj.material_slots for obj in selected_objects]
for slots in slots_array:
for slot in slots:
selected_materials.add(slot.material)
return selected_materials
def clean_empty_materials():
for obj in bpy.data.objects:
for slot in obj.material_slots:
mat = slot.material
if mat is None:
print("Removed Empty Materials from " + obj.name)
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.ops.object.material_slot_remove()
def clean_no_user_materials():
for material in bpy.data.materials:
if not material.users:
bpy.data.materials.remove(material)
def use_nodes():
for material in bpy.data.materials:
if not material.use_nodes:
material.use_nodes = True
@@ -0,0 +1,390 @@
import bpy.ops as O
import bpy
import os
from .. Functions import constants
import mathutils
# -----------------------COMPOSITING--------------------#
def blur_bake_image(noisy_image,color_image):
# switch on nodes and get reference
if not bpy.context.scene.use_nodes:
bpy.context.scene.use_nodes = True
tree = bpy.context.scene.node_tree
# add cam if not in scene
cam = bpy.context.scene.camera
if not cam:
bpy.ops.object.camera_add()
# bake image
image_node = tree.nodes.new(type='CompositorNodeImage')
image_node.image = noisy_image
image_node.location = 0, 0
# color image
color_image_node = tree.nodes.new(type='CompositorNodeImage')
color_image_node.image = color_image
color_image_node.location = 0, 300
# create blur node
blur_node = tree.nodes.new(type='CompositorNodeBilateralblur')
blur_node.location = 300, 0
# create output node
comp_node = tree.nodes.new('CompositorNodeComposite')
comp_node.location = 600, 0
# link nodes
links = tree.links
links.new(image_node.outputs[0], blur_node.inputs[0])
links.new(color_image_node.outputs[0], blur_node.inputs[1])
links.new(blur_node.outputs[0], comp_node.inputs[0])
# set output resolution to image res
bpy.context.scene.render.resolution_x = noisy_image.size[0]
bpy.context.scene.render.resolution_y = noisy_image.size[1]
# set output path
scene = bpy.context.scene
outputImagePath = constants.Path_List.get_textures_dir()
# set image format and quality
scene.render.image_settings.file_format = bpy.context.scene.img_file_format
scene.render.image_settings.quality = 100
scene.render.filepath = os.path.join(outputImagePath,noisy_image.name + "_Denoise_AO")
bpy.ops.render.render(write_still=True)
if bpy.context.scene.img_file_format == 'JPEG':
file_extention = '.jpg'
elif bpy.context.scene.img_file_format == 'PNG':
file_extention = '.png'
elif bpy.context.scene.img_file_format == 'HDR':
file_extention = '.hdr'
# cleanup
comp_nodes = [image_node,color_image_node,blur_node,comp_node]
for node in comp_nodes:
tree.nodes.remove(node)
return scene.render.filepath + file_extention
def comp_ai_denoise(noisy_image, nrm_image, color_image):
# switch on nodes and get reference
if not bpy.context.scene.use_nodes:
bpy.context.scene.use_nodes = True
tree = bpy.context.scene.node_tree
# add cam if not in scene
cam = bpy.context.scene.camera
if not cam:
bpy.ops.object.camera_add()
# bake image
image_node = tree.nodes.new(type='CompositorNodeImage')
image_node.image = noisy_image
image_node.location = 0, 0
# nrm image
nrm_image_node = tree.nodes.new(type='CompositorNodeImage')
nrm_image_node.image = nrm_image
nrm_image_node.location = 0, 300
# color image
color_image_node = tree.nodes.new(type='CompositorNodeImage')
color_image_node.image = color_image
color_image_node.location = 0, 600
# create denoise node
denoise_node = tree.nodes.new(type='CompositorNodeDenoise')
denoise_node.location = 300, 0
# create output node
comp_node = tree.nodes.new('CompositorNodeComposite')
comp_node.location = 600, 0
# link nodes
links = tree.links
links.new(image_node.outputs[0], denoise_node.inputs[0])
links.new(nrm_image_node.outputs[0], denoise_node.inputs[1])
links.new(color_image_node.outputs[0], denoise_node.inputs[2])
links.new(denoise_node.outputs[0], comp_node.inputs[0])
# set output resolution to image res
bpy.context.scene.render.resolution_x = noisy_image.size[0]
bpy.context.scene.render.resolution_y = noisy_image.size[1]
# set output path
scene = bpy.context.scene
outputImagePath = constants.Path_List.get_textures_dir()
# set image format and quality
scene.render.image_settings.file_format = bpy.context.scene.img_file_format
scene.render.image_settings.quality = 100
scene.render.filepath = os.path.join(outputImagePath,noisy_image.name + "_Denoise_LM")
print("Starting Denoise")
bpy.ops.render.render(write_still=True)
if bpy.context.scene.img_file_format == 'JPEG':
file_extention = '.jpg'
elif bpy.context.scene.img_file_format == 'PNG':
file_extention = '.png'
elif bpy.context.scene.img_file_format == 'HDR':
file_extention = '.hdr'
# cleanup
comp_nodes = [image_node, nrm_image_node,color_image_node, denoise_node, comp_node]
for node in comp_nodes:
tree.nodes.remove(node)
return scene.render.filepath + file_extention
# -----------------------CHECKING --------------------#
def check_pbr(self, material):
check_ok = True
if material is None:
return False
if material.node_tree is None:
return False
if material.node_tree.nodes is None:
return False
# get pbr shader
nodes = material.node_tree.nodes
pbr_node_type = constants.Node_Types.pbr_node
pbr_nodes = get_nodes_by_type(nodes, pbr_node_type)
# check only one pbr node
if len(pbr_nodes) == 0:
self.report({'INFO'}, 'No PBR Shader Found')
check_ok = False
if len(pbr_nodes) > 1:
self.report(
{'INFO'}, 'More than one PBR Node found ! Clean before Baking.')
check_ok = False
return check_ok
def check_is_org_material(self, material):
check_ok = True
if "_Bake" in material.name:
self.report({'INFO'}, 'Change back to org. Material')
check_ok = False
return check_ok
# -----------------------NODES --------------------#
def get_pbr_inputs(pbr_node):
base_color_input = pbr_node.inputs["Base Color"]
metallic_input = pbr_node.inputs["Metallic"]
specular_input = pbr_node.inputs["Specular Tint"]
roughness_input = pbr_node.inputs["Roughness"]
normal_input = pbr_node.inputs["Normal"]
emission_input = pbr_node.inputs["Emission Color"]
alpha_input = pbr_node.inputs["Alpha"]
pbr_inputs = {"base_color_input": base_color_input, "metallic_input": metallic_input,
"specular_input": specular_input, "roughness_input": roughness_input,
"normal_input": normal_input, "emission_input": emission_input,"alpha_input":alpha_input}
return pbr_inputs
def get_nodes_by_type(nodes, node_type):
nodes_found = [n for n in nodes if n.type == node_type]
return nodes_found
def get_node_by_type_recusivly(material, note_to_start, node_type, del_nodes_inbetween=False):
nodes = material.node_tree.nodes
if note_to_start.type == node_type:
return note_to_start
for input in note_to_start.inputs:
for link in input.links:
current_node = link.from_node
if (del_nodes_inbetween and note_to_start.type != constants.Node_Types.normal_map and note_to_start.type != constants.Node_Types.bump_map):
nodes.remove(note_to_start)
return get_node_by_type_recusivly(material, current_node, node_type, del_nodes_inbetween)
def get_node_by_name_recusivly(node, idname):
if node.bl_idname == idname:
return node
for input in node.inputs:
for link in input.links:
current_node = link.from_node
return get_node_by_name_recusivly(current_node, idname)
def get_pbr_node(material):
nodes = material.node_tree.nodes
pbr_node = get_nodes_by_type(nodes, constants.Node_Types.pbr_node)
if len(pbr_node) > 0:
return pbr_node[0]
def make_link(material, socket1, socket2):
links = material.node_tree.links
links.new(socket1, socket2)
def remove_link(material, socket1, socket2):
node_tree = material.node_tree
links = node_tree.links
for l in socket1.links:
if l.to_socket == socket2:
links.remove(l)
def add_in_gamme_node(material, pbrInput):
nodeToPrincipledOutput = pbrInput.links[0].from_socket
gammaNode = material.node_tree.nodes.new("ShaderNodeGamma")
gammaNode.inputs[1].default_value = 2.2
gammaNode.name = "Gamma Bake"
# link in gamma
make_link(material, nodeToPrincipledOutput, gammaNode.inputs["Color"])
make_link(material, gammaNode.outputs["Color"], pbrInput)
def remove_gamma_node(material, pbrInput):
nodes = material.node_tree.nodes
gammaNode = nodes.get("Gamma Bake")
nodeToPrincipledOutput = gammaNode.inputs[0].links[0].from_socket
make_link(material, nodeToPrincipledOutput, pbrInput)
material.node_tree.nodes.remove(gammaNode)
def emission_setup(material, node_output):
nodes = material.node_tree.nodes
emission_node = add_node(
material, constants.Shader_Node_Types.emission, "Emission Bake")
# link emission to whatever goes into current pbrInput
emission_input = emission_node.inputs[0]
make_link(material, node_output, emission_input)
# link emission to materialOutput
surface_input = get_nodes_by_type(nodes,constants.Node_Types.material_output)[0].inputs[0]
emission_output = emission_node.outputs[0]
make_link(material, emission_output, surface_input)
def link_pbr_to_output(material, pbr_node):
nodes = material.node_tree.nodes
surface_input = get_nodes_by_type(nodes,constants.Node_Types.material_output)[0].inputs[0]
make_link(material, pbr_node.outputs[0], surface_input)
def reconnect_PBR(material, pbrNode):
nodes = material.node_tree.nodes
pbr_output = pbrNode.outputs[0]
surface_input = get_nodes_by_type(
nodes, constants.Node_Types.material_output)[0].inputs[0]
make_link(material, pbr_output, surface_input)
def mute_all_texture_mappings(material, do_mute):
nodes = material.node_tree.nodes
for node in nodes:
if node.bl_idname == "ShaderNodeMapping":
node.mute = do_mute
def add_node(material, shader_node_type, node_name):
nodes = material.node_tree.nodes
new_node = nodes.get(node_name)
if new_node is None:
new_node = nodes.new(shader_node_type)
new_node.name = node_name
new_node.label = node_name
return new_node
def remove_node(material, node_name):
nodes = material.node_tree.nodes
node = nodes.get(node_name)
if node is not None:
nodes.remove(node)
def remove_reconnect_node(material, node_name):
nodes = material.node_tree.nodes
node = nodes.get(node_name)
input_node = node.inputs["Color1"].links[0].from_node
output_node = node.outputs["Color"].links[0].to_node
if node is not None:
make_link(material,input_node.outputs["Color"],output_node.inputs["Base Color"])
nodes.remove(node)
def remove_unused_nodes(material):
nodes = material.node_tree.nodes
all_nodes = set(nodes)
connected_nodes = set()
material_output = nodes.get("Material Output")
get_all_connected_nodes(material_output, connected_nodes)
unconnected_nodes = all_nodes - connected_nodes
for node in unconnected_nodes:
nodes.remove(node)
def remove_double_linking(material,texture_node):
color_output = texture_node.outputs["Color"]
links_count = len(color_output.links)
org_vector_input = texture_node.inputs["Vector"]
position_y = texture_node.location.y
if links_count > 1:
for link in color_output.links:
new_texture_node = add_node(material,constants.Shader_Node_Types.image_texture,texture_node.name + "_Copy" + str(link))
new_texture_node.image = texture_node.image
new_texture_node.location = texture_node.location
position_y -= 250
new_texture_node.location.y = position_y
# relink tex node output
make_link(material,new_texture_node.outputs["Color"],link.to_socket)
# remap texture mapping
if len(org_vector_input.links) != 0:
new_vector_input = new_texture_node.inputs["Vector"]
tex_transform_socket = org_vector_input.links[0].from_socket
make_link(material,tex_transform_socket,new_vector_input)
def get_all_connected_nodes(node, connected_nodes):
connected_nodes.add(node)
for input in node.inputs:
for link in input.links:
current_node = link.from_node
get_all_connected_nodes(current_node, connected_nodes)
@@ -0,0 +1,36 @@
import bpy
from .. Functions import node_functions
def apply_transform_on_linked():
bpy.ops.object.select_linked(type='OBDATA')
bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', object=True, obdata=True, material=False, animation=False)
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
bpy.ops.object.make_links_data(type='OBDATA')
def select_object(self, obj):
C = bpy.context
O = bpy.ops
try:
O.object.select_all(action='DESELECT')
C.view_layer.objects.active = obj
obj.select_set(True)
except:
self.report({'INFO'}, "Object not in View Layer")
def select_obj_by_mat(mat,self=None):
D = bpy.data
result = []
for obj in D.objects:
if obj.type == "MESH":
object_materials = [slot.material for slot in obj.material_slots]
if mat in object_materials:
result.append(obj)
if (self):
select_object(self, obj)
return result
# TODO - save objects in array, unlink objects, apply scale and link them back
def apply_scale_on_multiuser():
O = bpy.ops
O.object.transform_apply(location=False, rotation=False, scale=True)
@@ -0,0 +1,200 @@
import bpy
from bpy import context
from . import node_functions
from . import material_functions
from . import object_functions
from . import constants
from . import basic_functions
import mathutils
def update_selected_image(self, context):
sel_texture = bpy.data.images[self.texture_index]
show_image_in_image_editor(sel_texture)
def show_image_in_image_editor(image):
for area in bpy.context.screen.areas:
if area.type == 'IMAGE_EDITOR':
area.spaces.active.image = image
def switch_baked_material(show_bake_material,affect):
current_bake_type = bpy.context.scene.bake_settings.get_current_bake_type()
material_name_suffix = constants.Material_Suffix.bake_type_mat_suffix[current_bake_type]
# on what object to work
if affect == 'active':
objects = [bpy.context.active_object]
elif affect == 'selected':
objects = bpy.context.selected_editable_objects
elif affect == 'visible':
objects = [ob for ob in bpy.context.view_layer.objects if ob.visible_get()]
elif affect == 'scene':
objects = bpy.context.scene.objects
elif affect == 'linked':
objects = []
selected_objects = bpy.context.selected_editable_objects
selected_materials = material_functions.get_selected_materials(selected_objects)
for material in selected_materials:
objs = object_functions.select_obj_by_mat(material)
objects.append(objs)
objects = basic_functions.flatten(objects)
objects = basic_functions.remove_duplicate(objects)
all_mats = bpy.data.materials
baked_mats = [mat for mat in all_mats if material_name_suffix in mat.name]
for obj in objects:
# if current_bake_type != "pbr":
# baked_ao_flag = getattr(obj,"ao_map_name") != '' or getattr(obj,"lightmap_name") != ''
# if not baked_ao_flag:
# continue
for slot in obj.material_slots:
if show_bake_material:
for baked_mat in baked_mats:
try:
if baked_mat.name == slot.material.name + material_name_suffix + obj.bake_version:
slot.material = baked_mat
except:
pass
else:
if (material_name_suffix in slot.material.name):
bake_material = slot.material
index = bake_material.name.find(material_name_suffix)
org_mat = all_mats.get(bake_material.name[0:index])
if org_mat is not None:
slot.material = org_mat
def preview_bake_texture(self,context):
context = bpy.context
bake_settings = context.scene.bake_settings
preview_bake_texture = context.scene.texture_settings.preview_bake_texture
vis_mats = material_functions.get_all_visible_materials()
for mat in vis_mats:
if not mat.node_tree:
continue
nodes = mat.node_tree.nodes
bake_texture_node = None
if bake_settings.lightmap_bake:
bake_texture_node = nodes.get(bake_settings.texture_node_lightmap)
elif bake_settings.ao_bake:
bake_texture_node = nodes.get(bake_settings.texture_node_ao)
if bake_texture_node is not None:
if preview_bake_texture:
node_functions.emission_setup(mat, bake_texture_node.outputs["Color"])
else:
pbr_node = node_functions.get_nodes_by_type(nodes, constants.Node_Types.pbr_node)
if len(pbr_node) == 0:
return
pbr_node = pbr_node[0]
node_functions.remove_node(mat, "Emission Bake")
node_functions.reconnect_PBR(mat, pbr_node)
def preview_lightmap(self, context):
preview_lightmap = context.scene.texture_settings.preview_lightmap
vis_mats = material_functions.get_all_visible_materials()
for material in vis_mats:
if not material.node_tree:
continue
nodes = material.node_tree.nodes
lightmap_node = nodes.get("Lightmap")
if lightmap_node is None:
continue
pbr_node = node_functions.get_pbr_node(material)
if pbr_node is None:
print("\n " + material.name + " has no PBR Node \n")
continue
base_color_input = node_functions.get_pbr_inputs(pbr_node)["base_color_input"]
emission_input = node_functions.get_pbr_inputs(pbr_node)["emission_input"]
lightmap_output = lightmap_node.outputs["Color"]
if preview_lightmap:
# add mix node
mix_node_name = "Mulitply Lightmap"
mix_node = node_functions.add_node(material,constants.Shader_Node_Types.mix, mix_node_name)
mix_node.blend_type = 'MULTIPLY'
mix_node.inputs[0].default_value = 1 # set factor to 1
pos_offset = mathutils.Vector((-200, 200))
mix_node.location = pbr_node.location + pos_offset
mix_node_input1 = mix_node.inputs["Color1"]
mix_node_input2 = mix_node.inputs["Color2"]
mix_node_output = mix_node.outputs["Color"]
# image texture in base color
if base_color_input.is_linked:
node_before_base_color = base_color_input.links[0].from_node
if not node_before_base_color.name == mix_node_name:
node_functions.make_link(material, node_before_base_color.outputs["Color"], mix_node_input1)
node_functions.make_link(material, lightmap_output, mix_node_input2)
node_functions.make_link(material, mix_node_output, base_color_input)
else :
mix_node_input1.default_value = base_color_input.default_value
node_functions.make_link(material, lightmap_output, mix_node_input2)
node_functions.make_link(material, mix_node_output, base_color_input)
node_functions.remove_link(material,lightmap_output,emission_input)
if not preview_lightmap:
# remove mix and reconnect base color
mix_node = nodes.get("Mulitply Lightmap")
if mix_node is not None:
color_input_connections = len(mix_node.inputs["Color1"].links)
if (color_input_connections == 0):
node_functions.remove_node(material,mix_node.name)
else:
node_functions.remove_reconnect_node(material,mix_node.name)
node_functions.link_pbr_to_output(material,pbr_node)
def lightmap_to_emission(self, context, connect):
vis_mats = material_functions.get_all_visible_materials()
for material in vis_mats:
if not material.node_tree:
continue
nodes = material.node_tree.nodes
pbr_node = node_functions.get_pbr_node(material)
lightmap_node = nodes.get("Lightmap")
if lightmap_node is None:
continue
emission_input = node_functions.get_pbr_inputs(pbr_node)["emission_input"]
lightmap_output = lightmap_node.outputs["Color"]
if connect:
node_functions.make_link(material, lightmap_output, emission_input)
else:
node_functions.remove_link(material,lightmap_output,emission_input)
@@ -0,0 +1,20 @@
import bpy
addon_keymaps = []
# keymap
def register():
kcfg = bpy.context.window_manager.keyconfigs.addon
if kcfg:
km = kcfg.keymaps.new(name='3D View', space_type='VIEW_3D')
kmi = km.keymap_items.new("scene.node_to_texture_operator", 'B', 'PRESS', shift=True, ctrl=True)
addon_keymaps.append((km, kmi))
def unregister():
for km, kmi in addon_keymaps:
km.keymap_items.remove(kmi)
addon_keymaps.clear()
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Lorenz Wieseke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,68 @@
import bpy
from ..Bake import bake_manager
from .. Functions import gui_functions
class GTT_BakeOperator(bpy.types.Operator):
"""Bake all attached Textures"""
bl_idname = "object.gtt_bake_operator"
bl_label = "Simple Object Operator"
@classmethod
def poll(cls, context):
if len(context.selected_objects) < 1:
return False
else:
return True
def deselect_everything_but_mesh(self,selected_objects):
for obj in selected_objects:
if obj.type != 'MESH':
obj.select_set(False)
def execute(self,context):
# ----------------------- VAR --------------------#
selected_objects = context.selected_objects
bake_settings = context.scene.bake_settings
texture_settings = context.scene.texture_settings
self.deselect_everything_but_mesh(selected_objects)
# ----------------------- CHECK SELECTION --------------------#
for obj in selected_objects:
if obj.type != 'MESH':
obj.select_set(False)
if len(obj.material_slots) == 0:
self.report({'INFO'}, 'No Material on ' + obj.name)
context.view_layer.objects.active = context.selected_objects[0]
# ----------------------- SET VISIBLITY TO MATERIAL --------------------#
texture_settings.preview_bake_texture = False
# ----------------------- LIGHTMAP / AO --------------------#
if bake_settings.lightmap_bake or bake_settings.ao_bake:
bake_manager.bake_texture(self,selected_objects,bake_settings)
if bake_settings.show_texture_after_bake and bake_settings.denoise:
texture_settings.preview_bake_texture = True
for obj in selected_objects:
if bake_settings.ao_bake:
obj.ao_map_name = bake_settings.bake_image_name
if bake_settings.lightmap_bake:
obj.lightmap_name = bake_settings.bake_image_name
gui_functions.update_active_element_in_bake_list()
# ----------------------- PBR Texture --------------------#
if bake_settings.pbr_bake:
bake_manager.bake_on_plane(self,selected_objects,bake_settings)
return {'FINISHED'}
@@ -0,0 +1,19 @@
from bpy.ops import OBJECT_OT_bake as op
def callback(ret):
print('Callback triggered: {} !!'.format(ret))
def modal_wrap(modal_func, callback):
def wrap(self, context, event):
ret, = retset = modal_func(self, context, event)
if ret in {'CANCELLED'}: # my plugin emits the CANCELED event on finish - yours might do FINISH or FINISHED, you might have to look it up in the source code, __init__.py , there look at the modal() function for things like return {'FINISHED'} or function calls that return things alike.
print(f"{self.bl_idname} returned {ret}")
callback(ret)
return retset
return wrap
# op._modal_org = op.modal
op.modal = modal_wrap(op.modal, callback)
@@ -0,0 +1,465 @@
import os
import subprocess
import bpy
from ..Functions import (basic_functions, constants,
image_functions, material_functions, node_functions,
visibility_functions,object_functions)
class GTT_VerifyMaterialsOperator(bpy.types.Operator):
"""Check for each visbile material if it has a PBR Shader so the GLTF Export works fine"""
bl_idname = "object.verify_materials"
bl_label = "Verify Materials"
def execute(self, context):
vis_mats = material_functions.get_all_visible_materials()
for mat in vis_mats:
check_ok = node_functions.check_pbr(self,mat)
if not check_ok:
self.report({'INFO'}, "No PBR Shader in " + mat.name)
objects_in_scene = bpy.data.objects
for obj in objects_in_scene:
for slot in obj.material_slots:
if slot.material is None:
self.report({'INFO'}, "Empty Material Slot on " + obj.name)
return {'FINISHED'}
# ----------------------- LIGHTAP OPERATORS--------------------#
class GTT_SelectLightmapObjectsOperator(bpy.types.Operator):
"""Select all Objects in the list that have the according lightmap attached to them. Makes it easy to rebake multiple Objects"""
bl_idname = "object.select_lightmap_objects"
bl_label = "Select Lightmap Objects"
@classmethod
def poll(cls, context):
if context.scene.bake_settings.baking_groups == '-- Baking Groups --':
return False
return True
def execute(self, context):
C = context
O = bpy.ops
bake_settings = C.scene.bake_settings
active_lightmap = bake_settings.baking_groups
objects = [ob for ob in bpy.context.view_layer.objects if ob.visible_get()]
O.object.select_all(action='DESELECT')
for obj in objects:
if obj.lightmap_name == active_lightmap or obj.ao_map_name == active_lightmap:
C.view_layer.objects.active = obj
obj.select_set(True)
return {'FINISHED'}
# ----------------------- TEXTURE OPERATORS--------------------#
class GTT_GetMaterialByTextureOperator(bpy.types.Operator):
bl_idname = "scene.select_mat_by_tex"
bl_label = "Select Material By Texture"
bl_description = "Selecting all materials in scene that use the selected texture"
bl_options = {"REGISTER"}
bpy.types.Scene.materials_found = []
@classmethod
def poll(cls, context):
D = bpy.data
images = D.images
display = True
# image to index not found
try:
sel_image_texture = images[context.scene.texture_settings.texture_index]
if sel_image_texture.name in ('Viewer Node', 'Render Result'):
display = False
except:
display = False
return display
def execute(self, context):
D = bpy.data
images = D.images
sel_image_texture = images[context.scene.texture_settings.texture_index]
materials = D.materials
# to print materials with current image texture
materials_found = context.scene.materials_found
materials_found.clear()
for mat in materials:
if hasattr(mat,"node_tree"):
if hasattr(mat.node_tree,"nodes"):
nodes = mat.node_tree.nodes
tex_node_type = constants.Node_Types.image_texture
tex_nodes = node_functions.get_nodes_by_type(nodes,tex_node_type)
# if texture node in current node tree
if len(tex_nodes) > 0:
images = [node.image for node in tex_nodes]
if sel_image_texture in images:
materials_found.append(mat.name)
object_functions.select_obj_by_mat(mat,self)
return {"FINISHED"}
class GTT_ScaleImageOperator(bpy.types.Operator):
"""Scale all Images on selected Material to specific resolution"""
bl_idname = "image.scale_image"
bl_label = "Scale Images"
@classmethod
def poll(cls, context):
D = bpy.data
images = D.images
display = True
# if operate on all textures is checked we don't need to get the index
if context.scene.texture_settings.operate_on_all_textures:
return True
# image to index not found
try:
sel_image_texture = images[context.scene.texture_settings.texture_index]
if sel_image_texture.name in ('Viewer Node','Render Result'):
display = False
except:
display = False
return display
def invoke(self,context,event):
D = bpy.data
texture_settings = context.scene.texture_settings
image_size = [int(context.scene.img_bake_size),int(context.scene.img_bake_size)]
images_in_scene = D.images
all_images = image_functions.get_all_images_in_ui_list()
if texture_settings.operate_on_all_textures:
for img in all_images:
image_functions.scale_image(img,image_size)
else:
sel_image_texture = images_in_scene[texture_settings.texture_index]
image_functions.scale_image(sel_image_texture,image_size)
return {'FINISHED'}
def modal(self, context, event):
if event.type in {'RIGHTMOUSE', 'ESC'}:
return {'CANCELLED'}
return {'PASS_THROUGH'}
# ----------------------- VIEW OPERATORS--------------------#
class GTT_SwitchBakeMaterialOperator(bpy.types.Operator):
"""Switch to baked material"""
bl_idname = "object.switch_bake_mat_operator"
bl_label = "Baked Material"
def execute(self, context):
show_bake_material = True
visibility_functions.switch_baked_material(show_bake_material,context.scene.affect)
return {'FINISHED'}
class GTT_SwitchOrgMaterialOperator(bpy.types.Operator):
"""Switch from baked to original material"""
bl_idname = "object.switch_org_mat_operator"
bl_label = "Org. Material"
def execute(self, context):
show_bake_material = False
visibility_functions.switch_baked_material(show_bake_material,context.scene.affect)
return {'FINISHED'}
class GTT_PreviewBakeTextureOperator(bpy.types.Operator):
"""Connect baked texture to emission to see result"""
bl_idname = "object.preview_bake_texture"
bl_label = "Preview Bake Texture"
connect : bpy.props.BoolProperty()
def execute(self, context):
context.scene.texture_settings.preview_bake_texture = self.connect
visibility_functions.preview_bake_texture(self,context)
return {'FINISHED'}
class GTT_LightmapEmissionOperator(bpy.types.Operator):
"""Connect baked Lightmap to Emission input of Principled Shader"""
bl_idname = "object.lightmap_to_emission"
bl_label = "Lightmap to Emission"
connect : bpy.props.BoolProperty()
def execute(self, context):
visibility_functions.lightmap_to_emission(self,context,self.connect)
return {'FINISHED'}
class GTT_PreviewLightmap(bpy.types.Operator):
"""Connect baked Lightmap to Base Color input of Principled Shader"""
bl_idname = "object.preview_lightmap"
bl_label = "Lightmap to Base Color"
connect : bpy.props.BoolProperty()
def execute(self, context):
context.scene.texture_settings.preview_lightmap = self.connect
visibility_functions.preview_lightmap(self,context)
return {'FINISHED'}
# ----------------------- UV OPERATORS--------------------#
class GTT_AddUVOperator(bpy.types.Operator):
"""Add uv layer with layer name entered above"""
bl_idname = "object.add_uv"
bl_label = "Add UV to all selected objects"
uv_name:bpy.props.StringProperty()
def execute(self, context):
sel_objects = context.selected_objects
for obj in sel_objects:
if obj.type != "MESH":
continue
uv_layers = obj.data.uv_layers
if self.uv_name in uv_layers:
print("UV Name already take, choose another one")
continue
uv_layers.new(name=self.uv_name)
uv_layers.get(self.uv_name).active = True
return {'FINISHED'}
class GTT_RemoveUVOperator(bpy.types.Operator):
"""Delete all uv layers found in uv_slot entered above"""
bl_idname = "object.remove_uv"
bl_label = "Remove UV"
uv_slot: bpy.props.IntProperty()
def execute(self, context):
sel_objects = context.selected_objects
self.uv_slot -= 1
for obj in sel_objects:
if obj.type != "MESH":
continue
uv_layers = obj.data.uv_layers
if len(uv_layers) > self.uv_slot:
uv_layers.remove(uv_layers[self.uv_slot])
return {'FINISHED'}
class GTT_SetActiveUVOperator(bpy.types.Operator):
"""Set the acive uv to the slot entered above"""
bl_idname = "object.set_active_uv"
bl_label = "Set Active UV"
uv_slot:bpy.props.IntProperty()
def execute(self, context):
sel_objects = context.selected_objects
self.uv_slot -= 1
for obj in sel_objects:
if obj.type != "MESH":
continue
uv_layers = obj.data.uv_layers
if len(uv_layers) > self.uv_slot:
uv_layers.active_index = self.uv_slot
return {'FINISHED'}
# ----------------------- CLEAN OPERATORS--------------------#
# class CleanBakesOperator(bpy.types.Operator):
class GTT_RemoveLightmapOperator(bpy.types.Operator):
"""Remove Lightmap and UV Node"""
bl_idname = "material.clean_lightmap"
bl_label = "Clean Lightmap"
def execute(self, context):
selected_objects = context.selected_objects
bake_settings = context.scene.bake_settings
all_materials = set()
slots_array = [obj.material_slots for obj in selected_objects]
for slots in slots_array:
for slot in slots:
all_materials.add(slot.material)
for mat in all_materials:
if mat is None:
continue
node_functions.remove_node(mat,bake_settings.texture_node_lightmap)
node_functions.remove_node(mat,"Mulitply Lightmap")
node_functions.remove_node(mat,"Second_UV")
#remove lightmap flag
for obj in selected_objects:
obj.hasLightmap = False
if obj.get('lightmap_name') is not None :
del obj["lightmap_name"]
return {'FINISHED'}
class GTT_RemoveAOOperator(bpy.types.Operator):
"""Remove AO Node and clear baking flags on object"""
bl_idname = "material.clean_ao_map"
bl_label = "Clean AO map"
def execute(self, context):
# visibility_functions.switch_baked_material(False,"scene")
bpy.ops.material.clean_materials()
bake_settings = context.scene.bake_settings
selected_objects = context.selected_objects
all_materials = set()
slots_array = [obj.material_slots for obj in selected_objects]
for slots in slots_array:
for slot in slots:
all_materials.add(slot.material)
for mat in all_materials:
if mat is None:
continue
node_functions.remove_node(mat,bake_settings.texture_node_ao)
node_functions.remove_node(mat,"glTF Settings")
#remove flag
for obj in selected_objects:
if obj.get('ao_map_name') is not None :
del obj["ao_map_name"]
if obj.get('bake_version') is not None :
del obj["bake_version"]
return {'FINISHED'}
class GTT_CleanTexturesOperator(bpy.types.Operator):
"""Remove unreferenced images"""
bl_idname = "image.clean_textures"
bl_label = "Clean Textures"
def execute(self, context):
for image in bpy.data.images:
if not image.users or list(image.size) == [0,0]:
bpy.data.images.remove(image)
return {'FINISHED'}
class GTT_CleanMaterialsOperator(bpy.types.Operator):
"""Clean materials with no users and remove empty material slots"""
bl_idname = "material.clean_materials"
bl_label = "Clean Materials"
def execute(self, context):
material_functions.clean_empty_materials()
material_functions.clean_no_user_materials()
material_functions.use_nodes()
return {'FINISHED'}
class GTT_CleanUnusedImagesOperator(bpy.types.Operator):
"""Clean all images from Hard Disk that are not used in scene"""
bl_idname = "scene.clean_unused_images"
bl_label = "Clean Images"
bl_options = {"REGISTER"}
@classmethod
def poll(cls, context):
return True
def execute(self, context):
images_in_folder = []
images_in_blender = bpy.data.images
image_paths_in_blender = []
filePath = bpy.data.filepath
path = os.path.dirname(filePath) + "\\textures"
# find images on hard drive
if os.path.exists(path):
for path, subdirs, files in os.walk(path):
for name in files:
images_in_folder.append(path+"\\"+name)
for img in images_in_blender:
image_paths_in_blender.append(img.filepath)
images_intersection = basic_functions.Intersection(image_paths_in_blender,images_in_folder)
images_to_clean = basic_functions.Diff(images_in_folder,images_intersection)
print("Deleting files :")
for img in images_to_clean:
os.remove(img)
print(img)
return {'FINISHED'}
# ----------------------- FILE OPERATORS--------------------#
class GTT_OpenTexturesFolderOperator(bpy.types.Operator):
"""Open Texture folder if it exists, bake or scale texture to create texture folder"""
bl_idname = "scene.open_textures_folder"
bl_label = "Open Folder"
texture_path="\\textures\\"
@classmethod
def poll(self, context):
filePath = bpy.data.filepath
path = os.path.dirname(filePath)
if os.path.exists(path + self.texture_path):
return True
return False
def execute(self, context):
filepath = bpy.data.filepath
directory = os.path.dirname(filepath) + self.texture_path
if filepath != "":
subprocess.call("explorer " + directory, shell=True)
else:
self.report({'INFO'}, 'You need to save Blend file first !')
return {"FINISHED"}
class GOVIE_Open_Link_Operator(bpy.types.Operator):
bl_idname = "scene.open_link"
bl_label = "Open Website"
bl_description = "Go to GOVIE Website"
url : bpy.props.StringProperty(name="url")
@classmethod
def poll(cls, context):
return True
def execute(self, context):
bpy.ops.wm.url_open(url=self.url)
return {"FINISHED"}
@@ -0,0 +1,260 @@
import bpy
from .. Functions import gui_functions
# from .. Update import addon_updater_ops
class GTT_ResolutionPanel(bpy.types.Panel):
bl_idname = "GLBTEXTOOLS_PT_resolution_panel"
bl_label = "Global Settings"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = 'GLB Texture Tools'
# bl_parent_id = "TEXTURETOOLS_PT_parent_panel"
bl_order = 0
def draw(self, context):
layout = self.layout
scene = context.scene
box = layout.box()
column = box.column()
column.prop(scene, "img_bake_size")
column.prop(scene,"img_file_format")
column.prop(scene,"affect")
column.prop(scene.cycles,"device")
class GTT_BakeTexturePanel(bpy.types.Panel):
bl_idname = "GLBTEXTOOLS_PT_bake_panel"
bl_label = "Baking"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = 'GLB Texture Tools'
bl_order = 1
def draw(self, context):
layout = self.layout
scene = context.scene
data = bpy.data
bake_settings = bpy.context.scene.bake_settings
row = layout.row()
row.prop(bake_settings, 'open_bake_settings_menu', text="Bake Settings", icon = 'TRIA_DOWN' if bake_settings.open_bake_settings_menu else 'TRIA_RIGHT' )
if bake_settings.open_bake_settings_menu:
box = layout.box()
col = box.column(align = True)
row = col.row(align = True)
row.prop(scene.bake_settings, 'pbr_bake', text="PBR",toggle = True)
row.prop(scene.bake_settings, 'pbr_samples', text="Samples",toggle = True)
row = col.row(align = True)
row.prop(scene.bake_settings, 'ao_bake', text="AO",toggle = True)
row.prop(scene.bake_settings, 'ao_samples', text="Samples")
row = col.row(align = True)
row.prop(scene.bake_settings, 'lightmap_bake', text="Lightmap",toggle = True)
row.prop(scene.bake_settings, 'lightmap_samples', text="Samples")
if bake_settings.pbr_bake:
row = box.row()
# col = row.collumn()
row.prop(scene.bake_settings, 'mute_texture_nodes', text="Mute Texture Mapping")
# row.prop(scene.bake_settings, 'bake_image_clear', text="Clear Bake Image")
if bake_settings.lightmap_bake or bake_settings.ao_bake:
row = box.row()
row.prop(scene.bake_settings, 'bake_image_name', text="")
row = box.row()
row.prop(scene.bake_settings, 'baking_groups',text="")
row.operator("object.select_lightmap_objects",text="",icon="RESTRICT_SELECT_OFF")
if bake_settings.lightmap_bake:
try:
box.prop(scene.world.node_tree.nodes["Background"].inputs[1],'default_value',text="World Influence")
except:
pass
if bake_settings.ao_bake:
box.prop(scene.world.light_settings,"distance",text="AO Distance")
box.prop(scene.bake_settings, 'unwrap_margin', text="UV Margin")
box.prop(scene.bake_settings, 'bake_margin', text="Bake Margin")
split = box.split()
col = split.column(align=True)
col.prop(scene.bake_settings, 'unwrap', text="Unwrap")
col.prop(scene.bake_settings, 'bake_image_clear', text="Clear Bake Image")
col = split.column(align=True)
col.prop(scene.bake_settings, 'denoise', text="Denoise")
if bake_settings.denoise:
col.prop(scene.bake_settings, 'show_texture_after_bake', text="Show Texture after Bake")
# LIGHTMAPPED OBJECT LIST
# row = layout.row()
# row.prop(scene.bake_settings, 'open_object_bake_list_menu', text="Lightmapped Objects", icon = 'TRIA_DOWN' if bake_settings.open_object_bake_list_menu else 'TRIA_RIGHT' )
# BAKE LIST
if bake_settings.open_object_bake_list_menu:
layout.template_list("GTT_BAKE_IMAGE_UL_List", "", data, "objects", scene.bake_settings, "bake_object_index")
row = layout.row(align=True)
row.scale_y = 2.0
row.operator("object.gtt_bake_operator",text="Bake Textures")
row.operator("scene.open_textures_folder",icon='FILEBROWSER')
class GTT_VisibilityPanel(bpy.types.Panel):
bl_idname = "GLBTEXTOOLS_PT_visibility_panel"
bl_label = "Visibility"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = 'GLB Texture Tools'
bl_order = 2
def draw(self, context):
layout = self.layout
scene = context.scene
col = layout.column()
row = col.row()
row.operator("object.switch_org_mat_operator",icon = 'NODE_MATERIAL', text="Show Original Material")
row.operator("object.switch_bake_mat_operator",icon = 'MATERIAL', text="Show Baked Material")
# row = col.row(align=True)
layout.prop(scene.texture_settings,"preview_lightmap",text="Show without Lightmap" if scene.texture_settings.preview_lightmap else "Preview Lightmap on Material", icon="SHADING_RENDERED" if scene.texture_settings.preview_bake_texture else "NODE_MATERIAL")
layout.prop(scene.texture_settings,"preview_bake_texture", text="Show Material" if scene.texture_settings.preview_bake_texture else "Preview Baked Texture", icon="SHADING_RENDERED" if scene.texture_settings.preview_bake_texture else "NODE_MATERIAL")
class GTT_CleanupPanel(bpy.types.Panel):
bl_idname = "GLBTEXTOOLS_PT_cleanup_panel"
bl_label = "Cleanup"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = 'GLB Texture Tools'
bl_order = 3
def draw(self, context):
layout = self.layout
row = layout.row()
row.operator("image.clean_textures",text="Clean Textures",icon = 'OUTLINER_OB_IMAGE')
row.operator("material.clean_materials",text="Clean Materials",icon = 'NODE_MATERIAL')
row = layout.row()
row.operator("material.clean_lightmap",text="Clean Lightmap",icon = 'MOD_UVPROJECT')
row.operator("material.clean_ao_map",text="Clean AO Map",icon = 'TRASH')
row = layout.row()
# row.operator("scene.clean_unused_images",text="Clean Unused Images",icon = 'TRASH')
class GTT_TextureSelectionPanel(bpy.types.Panel):
bl_idname = "GLBTEXTOOLS_PT_tex_selection_panel"
bl_label = "Texture"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = 'GLB Texture Tools'
# bl_parent_id = "TEXTURETOOLS_PT_parent_panel"
bl_order = 4
def draw(self, context):
layout = self.layout
scene = context.scene
data = bpy.data
texture_settings = bpy.context.scene.texture_settings
# UI LIST
gui_functions.headline(layout,(0.6,"IMAGE NAME"),(0.5,"SIZE"),(1,"KB"))
layout.template_list("GTT_TEX_UL_List", "", data, "images", scene.texture_settings, "texture_index")
row = layout.row()
row.prop(texture_settings, 'open_texture_settings_menu', text="Texture Settings", icon = 'TRIA_DOWN' if texture_settings.open_texture_settings_menu else 'TRIA_RIGHT' )
if texture_settings.open_texture_settings_menu:
box = layout.box()
box.prop(scene.texture_settings, 'show_all_textures', text="Show all Textures")
box.prop(scene.texture_settings, 'show_per_material', text="Show Textures per Material")
box.prop(scene.texture_settings, 'operate_on_all_textures', text="Operate on all Textures in List")
box.label(text="If scaled images don't get saved/exported, try unpacking before scaling !")
row = box.row()
row.operator("file.unpack_all",text="Unpack")
row.operator("file.pack_all",text="Pack")
# Select Material by Texture
row = layout.row()
row.prop(scene.texture_settings,"open_sel_mat_menu",text="Select Material by Texture", icon = 'TRIA_DOWN' if scene.texture_settings.open_sel_mat_menu else 'TRIA_RIGHT' )
if scene.texture_settings.open_sel_mat_menu:
box = layout.box()
col = box.column(align = True)
col.operator("scene.select_mat_by_tex",text="Select Material",icon='RESTRICT_SELECT_OFF')
col = box.column(align = True)
if len(scene.materials_found) > 0:
col.label(text="Texture found in Material :")
for mat in scene.materials_found:
col.label(text=mat)
else:
col.label(text="Texture not used")
# Scale and Clean
row = layout.row()
row.scale_y = 2.0
row.operator("image.scale_image",text="Scale Image",icon= 'FULLSCREEN_EXIT')
class GTT_UVPanel(bpy.types.Panel):
bl_idname = "GLBTEXTOOLS_PT_UV_panel"
bl_label = "UV"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "GLB Texture Tools"
bl_options = {'DEFAULT_CLOSED'}
bl_order = 5
def draw(self, context):
layout = self.layout
uv_settings = context.scene.uv_settings
box = layout.box()
row = box.row()
row.prop(uv_settings,"uv_name", text="UV Name")
row.prop(uv_settings,"uv_slot", text="UV Slot")
row = box.row()
row.operator("object.add_uv",text="Add UV",icon = 'ADD').uv_name = uv_settings.uv_name
row.operator("object.remove_uv",text="Remove UV",icon = 'REMOVE').uv_slot = uv_settings.uv_slot
row.operator("object.set_active_uv",text="Set Active",icon = 'RESTRICT_SELECT_OFF').uv_slot = uv_settings.uv_slot
class GTT_HelpPanel(bpy.types.Panel):
bl_idname = "GLBTEXTOOLS_PT_help_panel"
bl_label = "Help"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "GLB Texture Tools"
bl_order = 6
def draw(self,context):
layout = self.layout
lang = bpy.app.translations.locale
if lang == 'en_US':
layout.label(text="Find out how to use this addon")
layout.operator("scene.open_link",text="Add-on Documentation",icon='HELP').url = "https://govie.de/en/tutorials-blender/?utm_source=blender-add-on&utm_medium=button#glb_texture_tools"
if lang == 'de_DE':
layout.label(text="Hilfe zur Bedienung des Add-ons")
layout.operator("scene.open_link",text="Add-on Documentation",icon='HELP').url = "https://govie.de/tutorials-blender/?utm_source=blender-add-on&utm_medium=button#glb_texture_tools"
@@ -0,0 +1,88 @@
import bpy
from .. Functions import node_functions
from .. Functions import image_functions
from .. Functions import constants
class GTT_TEX_UL_List(bpy.types.UIList):
image_name_list = set()
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index, flt_flag):
if self.layout_type in {'DEFAULT', 'COMPACT'}:
row = layout.row()
split = row.split(factor=0.6)
split.label(text=str(item.users) + " " +item.name)
split = split.split(factor=0.5)
split.label(text=str(item.size[0]))
split = split.split(factor=1)
filepath = item.filepath
if filepath != '':
filesize = image_functions.get_file_size(filepath)
split.label(text=str(filesize).split('.')[0])
else:
split.label(text="file not saved")
def filter_items(self, context, data, propname):
texture_settings = context.scene.texture_settings
selected_objects = context.selected_objects
all_materials = set()
all_image_names = [image.name for image in data.images]
slots_array = [obj.material_slots for obj in selected_objects]
for slots in slots_array:
for slot in slots:
all_materials.add(slot.material)
# Default return values.
flt_flags = []
flt_neworder = []
images = []
if texture_settings.show_all_textures:
images = [image.name for image in data.images if image.name not in ('Viewer Node','Render Result')]
if texture_settings.show_per_material:
mat = context.active_object.active_material
nodes = mat.node_tree.nodes
tex_nodes = node_functions.get_nodes_by_type(nodes,constants.Node_Types.image_texture)
[images.append(node.image.name) for node in tex_nodes]
else:
for mat in all_materials:
if mat is None:
continue
nodes = mat.node_tree.nodes
tex_nodes = node_functions.get_nodes_by_type(nodes,constants.Node_Types.image_texture)
[images.append(node.image.name) for node in tex_nodes]
# save filtered list to texture settings / ui_list_itmes
self.image_name_list.clear()
for img in images:
self.image_name_list.add(img)
flt_flags = [self.bitflag_filter_item if name in images else 0 for name in all_image_names]
return flt_flags, flt_neworder
class GTT_BAKE_IMAGE_UL_List(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index, flt_flag):
if self.layout_type in {'DEFAULT', 'COMPACT'}:
row = layout.row()
row.label(text=item.name)
def filter_items(self, context, data, propname):
bake_settings = context.scene.bake_settings
objects = data.objects
# Default return values.
flt_flags = []
flt_neworder = []
flt_flags = [self.bitflag_filter_item if obj.lightmap_name == bake_settings.baking_groups and obj.hasLightmap else 0 for obj in objects]
return flt_flags, flt_neworder
@@ -0,0 +1,150 @@
import bpy
from bpy import context
from bpy.props import *
from .. Functions import gui_functions
from .. Functions import visibility_functions
bpy.types.Scene.img_bake_size = EnumProperty(
name='Image Size',
description='Set resolution for baking and scaling images. This effects PBR, AO and Lightmap baking as well as scaling imges. As of scaling images, choose ORIGINAL to switch back to your image before scaling.',
default='1024',
items=[
('128', '128', 'Set image size to 128'),
('256', '256', 'Set image size to 256'),
('512', '512', 'Set image size to 512'),
('1024', '1024', 'Set image size to 1024'),
('2048', '2048', 'Set image size to 2048'),
('4096', '4096', 'Set image size to 4096'),
('8184', '8184', 'Set image size to 8184'),
('0', 'Original', 'Set image back to original file'),
])
bpy.types.Scene.img_file_format = EnumProperty(
name='File Format',
description='Set file format for output image',
default='JPEG',
items=[
('JPEG', 'JPEG', 'JPG is a lossy format with no additional alpha channel, use for color maps'),
('PNG', 'PNG', 'PNG is lossless and has option for alpha channel, use for normal maps'),
('HDR', 'HDR', 'HDR is a 32 bit format, use if you need more details or see color banding'),
])
bpy.types.Scene.affect = EnumProperty(
name='Affect',
description='Define if operator should run on active material, all materials on selected object, all materials on visible objects or all materials in scene.',
default='linked',
items=[
('active', 'ACTIVE', 'Change only active materials'),
('selected', 'SELECTED', 'Change all selected materials'),
('linked', 'LINKED MATERIALS', 'Change all materials on selected objects and all objects that share these materials'),
('visible', 'VISIBLE', 'Change all visible materials'),
('scene', 'SCENE', 'Change all materials in scene'),
])
class GTT_UV_Settings(bpy.types.PropertyGroup):
uv_slot: IntProperty(default=1)
uv_name: StringProperty(default="AO")
bpy.utils.register_class(GTT_UV_Settings)
bpy.types.Scene.uv_settings = PointerProperty(type=GTT_UV_Settings)
class GTT_Cleanup_Settings(bpy.types.PropertyGroup):
clean_texture: BoolProperty(default=True)
clean_material: BoolProperty(default=True)
clean_bake: BoolProperty(default=False)
clean_node_tree: BoolProperty(default=False)
bpy.utils.register_class(GTT_Cleanup_Settings)
bpy.types.Scene.cleanup_settings = PointerProperty(type=GTT_Cleanup_Settings)
class GTT_Bake_Settings(bpy.types.PropertyGroup):
open_bake_settings_menu: BoolProperty(default = False)
open_object_bake_list_menu: BoolProperty(default = False)
# Type of bake
pbr_bake: BoolProperty(default = True,update=gui_functions.update_pbr_button)
pbr_samples: IntProperty(name = "Samples for PBR bake", default = 1)
ao_bake: BoolProperty(default = False,update=gui_functions.update_ao_button)
ao_samples: IntProperty(name = "Samples for AO bake", default = 2)
lightmap_bake: BoolProperty(default = False,update=gui_functions.update_lightmap_button)
lightmap_samples: IntProperty(name = "Samples for Lightmap bake", default = 10)
baking_groups: EnumProperty(
name='Baked Textures',
description='Groups of objects that share the same baking maps. Click on cursor on the right to select all objectes in that group.',
items=gui_functions.update_bake_list
)
def get_current_bake_type(self):
if self.pbr_bake:
current_bake_type = "pbr"
if self.ao_bake:
current_bake_type = "ao"
if self.lightmap_bake:
current_bake_type = "lightmap"
return current_bake_type
def get_baked_lightmaps(context):
return gui_functions.update_bake_list(context,context)
# render_pass : EnumProperty(name='Render Pass',description='Define Render Pass',items=[("Combined","Combined","Bake all passes in this singel Combined Pass"),("Lightmap","Lightmap","Lightmap")])
# Checkbox settings
bake_image_name: StringProperty(default="Lightmap")
bake_image_clear: BoolProperty(default= True)
mute_texture_nodes: BoolProperty(default = True)
bake_margin:IntProperty(default=2)
unwrap_margin:FloatProperty(default=0.002)
unwrap: BoolProperty(default= True)
denoise: BoolProperty(default=False)
show_texture_after_bake: BoolProperty(default=True)
bake_object_index:IntProperty(name = "Index for baked Objects", default = 0)
uv_name="Lightmap"
texture_node_lightmap="Lightmap"
texture_node_ao="AO"
cleanup_textures=False
bpy.utils.register_class(GTT_Bake_Settings)
bpy.types.Scene.bake_settings = PointerProperty(type=GTT_Bake_Settings)
class GTT_Texture_Settings(bpy.types.PropertyGroup):
open_texture_settings_menu:BoolProperty(default=False)
open_sel_mat_menu:BoolProperty(default=False)
show_all_textures:BoolProperty(default=False)
show_per_material:BoolProperty(default=False)
operate_on_all_textures:BoolProperty(default=False)
preview_bake_texture:BoolProperty(default=False,update=visibility_functions.preview_bake_texture)
preview_lightmap:BoolProperty(default=False,update=visibility_functions.preview_lightmap)
texture_index:IntProperty(name = "Index for Texture List", default=0, update=visibility_functions.update_selected_image)
bpy.utils.register_class(GTT_Texture_Settings)
bpy.types.Scene.texture_settings = PointerProperty(type=GTT_Texture_Settings)
# HELP PANEL PROPERTIES
def run_help_operator(self,context):
bpy.ops.scene.help('INVOKE_DEFAULT')
bpy.types.Scene.help_tex_tools = BoolProperty(default=False,update=run_help_operator)
# MATERIAL PROPERTIES
bpy.types.Material.bake_material_name = StringProperty()
# IMAGE PROPERTIES
bpy.types.Image.org_filepath = StringProperty()
bpy.types.Image.org_image_name = StringProperty()
# OBJECT PROPERTIES
bpy.types.Object.hasLightmap = BoolProperty()
bpy.types.Object.lightmap_name = StringProperty()
bpy.types.Object.ao_map_name = StringProperty()
bpy.types.Object.bake_version = StringProperty()
+3
View File
@@ -0,0 +1,3 @@
Documentation can be found here and a help
https://docs.google.com/document/d/1w1h3ySyZG4taG01RbbDsPODsUP06cRCggxQKCt32QTk/edit
@@ -0,0 +1,34 @@
import bpy
from . import functions
from .. Functions import material_functions
def Diff(li1, li2):
return (list(set(li1) - set(li2)))
def compareImages(images):
firstImg = images[0]
firstImgPixels = firstImg.pixels
for img in images[1:]:
currentImgPixels = img.pixels
diff = Diff(firstImgPixels, currentImgPixels)
if len(diff) == 0:
print(firstImg.name + " and " + img.name + " map !")
return compareImages(images[1:])
class CleanDupliTexturesOperator(bpy.types.Operator):
"""By checking the incoming links in the PBR Shader, new Textures are generated that will include all the node transformations."""
bl_idname = "object.clean_dupli_textures"
bl_label = "Delete Texture Duplicates"
def execute(self, context):
# images = bpy.data.images
# compareImages(images)
material_functions.clean_empty_materials(self)
return {'FINISHED'}
@@ -0,0 +1,50 @@
# 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
# MERCHANTIBILITY 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 <http://www.gnu.org/licenses/>.
bl_info = {
"name": "GLBTextureTools",
"author": "Lorenz Wieseke",
"description": "",
"blender": (4, 0, 0),
"version": (0,1,5),
"location": "3DView > Properties (N -KEY) > GLB Texture Tools",
"warning": "",
"wiki_url": "https://govie-editor.de/help/glb-texture-tools/",
"tracker_url": "https://github.com/LorenzWieseke/GLBTextureTools/issues",
"category": "Generic"
}
import bpy
from .Functions import gui_functions
from .Functions import image_functions
from . import auto_load
auto_load.init()
classes = auto_load.init()
def register():
auto_load.register()
bpy.app.handlers.depsgraph_update_post.clear()
bpy.app.handlers.depsgraph_update_post.append(gui_functions.update_on_selection)
bpy.app.handlers.load_post.append(gui_functions.init_values)
bpy.app.handlers.save_pre.append(image_functions.save_images)
def unregister():
auto_load.unregister()
bpy.app.handlers.depsgraph_update_post.clear()
bpy.app.handlers.load_post.clear()
bpy.app.handlers.save_pre.clear()
@@ -0,0 +1 @@
theme: jekyll-theme-cayman
+157
View File
@@ -0,0 +1,157 @@
import os
import bpy
import sys
import typing
import inspect
import pkgutil
import importlib
from pathlib import Path
__all__ = (
"init",
"register",
"unregister",
)
blender_version = bpy.app.version
modules = None
ordered_classes = None
def init():
global modules
global ordered_classes
modules = get_all_submodules(Path(__file__).parent)
ordered_classes = get_ordered_classes_to_register(modules)
def register():
for cls in ordered_classes:
bpy.utils.register_class(cls)
for module in modules:
if module.__name__ == __name__:
continue
if hasattr(module, "register"):
module.register()
def unregister():
for cls in reversed(ordered_classes):
bpy.utils.unregister_class(cls)
for module in modules:
if module.__name__ == __name__:
continue
if hasattr(module, "unregister"):
module.unregister()
# Import modules
#################################################
def get_all_submodules(directory):
return list(iter_submodules(directory, directory.name))
def iter_submodules(path, package_name):
for name in sorted(iter_submodule_names(path)):
yield importlib.import_module("." + name, package_name)
def iter_submodule_names(path, root=""):
for _, module_name, is_package in pkgutil.iter_modules([str(path)]):
if is_package:
sub_path = path / module_name
sub_root = root + module_name + "."
yield from iter_submodule_names(sub_path, sub_root)
else:
yield root + module_name
# Find classes to register
#################################################
def get_ordered_classes_to_register(modules):
return toposort(get_register_deps_dict(modules))
def get_register_deps_dict(modules):
my_classes = set(iter_my_classes(modules))
my_classes_by_idname = {cls.bl_idname : cls for cls in my_classes if hasattr(cls, "bl_idname")}
deps_dict = {}
for cls in my_classes:
deps_dict[cls] = set(iter_my_register_deps(cls, my_classes, my_classes_by_idname))
return deps_dict
def iter_my_register_deps(cls, my_classes, my_classes_by_idname):
yield from iter_my_deps_from_annotations(cls, my_classes)
yield from iter_my_deps_from_parent_id(cls, my_classes_by_idname)
def iter_my_deps_from_annotations(cls, my_classes):
for value in typing.get_type_hints(cls, {}, {}).values():
dependency = get_dependency_from_annotation(value)
if dependency is not None:
if dependency in my_classes:
yield dependency
def get_dependency_from_annotation(value):
if blender_version >= (2, 93):
if isinstance(value, bpy.props._PropertyDeferred):
return value.keywords.get("type")
else:
if isinstance(value, tuple) and len(value) == 2:
if value[0] in (bpy.props.PointerProperty, bpy.props.CollectionProperty):
return value[1]["type"]
return None
def iter_my_deps_from_parent_id(cls, my_classes_by_idname):
if bpy.types.Panel in cls.__bases__:
parent_idname = getattr(cls, "bl_parent_id", None)
if parent_idname is not None:
parent_cls = my_classes_by_idname.get(parent_idname)
if parent_cls is not None:
yield parent_cls
def iter_my_classes(modules):
base_types = get_register_base_types()
for cls in get_classes_in_modules(modules):
if any(base in base_types for base in cls.__bases__):
if not getattr(cls, "is_registered", False):
yield cls
def get_classes_in_modules(modules):
classes = set()
for module in modules:
for cls in iter_classes_in_module(module):
classes.add(cls)
return classes
def iter_classes_in_module(module):
for value in module.__dict__.values():
if inspect.isclass(value):
yield value
def get_register_base_types():
return set(getattr(bpy.types, name) for name in [
"Panel", "Operator", "PropertyGroup",
"AddonPreferences", "Header", "Menu",
"Node", "NodeSocket", "NodeTree",
"UIList", "RenderEngine",
"Gizmo", "GizmoGroup",
])
# Find order to register to solve dependencies
#################################################
def toposort(deps_dict):
sorted_list = []
sorted_values = set()
while len(deps_dict) > 0:
unsorted = []
for value, deps in deps_dict.items():
if len(deps) == 0:
sorted_list.append(value)
sorted_values.add(value)
else:
unsorted.append(value)
deps_dict = {value : deps_dict[value] - sorted_values for value in unsorted}
return sorted_list
+6
View File
@@ -0,0 +1,6 @@
use uv-packmaster if installed
change camera size back to what is was
reconstruct node tree in compositor
pbr texture bake -> add same uv to bake plane to be able to bake procedural textures or ! add uv automaticly
-210
View File
@@ -1,210 +0,0 @@
bl_info = {
"name": "Lip Sync",
"description": "A tool for generating lip-sync animations using poses from the Asset Browser.",
"author": "Blackout Creatively",
"version": (1, 0, 3),
"blender": (4, 3, 0),
"location": "View3D > Tool > My Lipsync",
"category": "Animation",
}
import bpy
class LipSyncProperties(bpy.types.PropertyGroup):
"""Properties for Lip Sync Tool"""
prefix: bpy.props.StringProperty(name="Pose Prefix", default="") # Prefix for pose names
pose_0: bpy.props.StringProperty(name="Rest", default="Rest")
pose_1: bpy.props.StringProperty(name="Aa", default="Aa")
pose_2: bpy.props.StringProperty(name="D", default="D")
pose_3: bpy.props.StringProperty(name="Ee", default="Ee")
pose_4: bpy.props.StringProperty(name="F", default="F")
pose_5: bpy.props.StringProperty(name="L", default="L")
pose_6: bpy.props.StringProperty(name="M", default="M")
pose_7: bpy.props.StringProperty(name="Oh", default="Oh")
pose_8: bpy.props.StringProperty(name="R", default="R")
pose_9: bpy.props.StringProperty(name="S", default="S")
pose_10: bpy.props.StringProperty(name="Uh", default="Uh")
pose_11: bpy.props.StringProperty(name="W-Oo", default="W-Oo")
holdPoseOffset: bpy.props.IntProperty(name="Hold Pose Frame Offset", default=2)
class LipSyncPluginOperator(bpy.types.Operator):
"""Lip Sync Animation Plugin"""
bl_idname = "object.lip_sync_plugin"
bl_label = "Lip Sync Animation"
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
props = context.scene.lip_sync_properties
prefix = props.prefix.strip() # Get prefix, if any
value_to_string = {
0: f"{prefix}{props.pose_0}",
1: f"{prefix}{props.pose_1}",
2: f"{prefix}{props.pose_2}",
3: f"{prefix}{props.pose_3}",
4: f"{prefix}{props.pose_4}",
5: f"{prefix}{props.pose_5}",
6: f"{prefix}{props.pose_6}",
7: f"{prefix}{props.pose_7}",
8: f"{prefix}{props.pose_8}",
9: f"{prefix}{props.pose_9}",
10: f"{prefix}{props.pose_10}",
11: f"{prefix}{props.pose_11}",
}
hold_offset = props.holdPoseOffset
try:
with open(self.filepath, 'r') as file:
lines = file.readlines()
except Exception as e:
self.report({'ERROR'}, f"Failed to read file: {e}")
return {'CANCELLED'}
action_name = "Lip Sync"
action = bpy.data.actions.get(action_name)
if not action:
action = bpy.data.actions.new(name=action_name)
obj = context.object
if not obj or obj.type != 'ARMATURE':
self.report({'ERROR'}, "No armature selected.")
return {'CANCELLED'}
obj.animation_data_create()
obj.animation_data.action = action
bpy.ops.object.mode_set(mode='POSE')
keyframe_data = []
for line in lines:
try:
parts = line.strip().split('\t')
if len(parts) != 2:
self.report({'WARNING'}, f"Skipping malformed line: '{line.strip()}'")
continue
time = round(float(parts[0]))
int_value = int(parts[1])
pose_name = value_to_string.get(int_value, None)
if pose_name is None:
self.report({'WARNING'}, f"Integer value {int_value} is not mapped. Skipping.")
continue
keyframe_data.append((time, pose_name))
except Exception as e:
self.report({'WARNING'}, f"Error processing line '{line.strip()}': {e}")
continue
keyframe_data.sort()
selected_bones = [bone.name for bone in obj.pose.bones if bone.bone.select]
for i, (time, pose_name) in enumerate(keyframe_data):
# Apply the pose
context.scene.frame_set(time)
pose_asset = next(
(action for action in bpy.data.actions if action.asset_data and action.name == pose_name),
None
)
if not pose_asset:
self.report({'WARNING'}, f"Pose '{pose_name}' not found in the asset library. Skipping.")
continue
for fcurve in pose_asset.fcurves:
data_path = fcurve.data_path
bone_name = data_path.split('"')[1] if '"' in data_path else None
if not bone_name or bone_name not in selected_bones:
continue
pose_bone = obj.pose.bones.get(bone_name)
if not pose_bone:
continue
for keyframe in fcurve.keyframe_points:
frame, value = keyframe.co
if "location" in data_path:
pose_bone.location[fcurve.array_index] = value
elif "rotation_quaternion" in data_path:
pose_bone.rotation_quaternion[fcurve.array_index] = value
elif "scale" in data_path:
pose_bone.scale[fcurve.array_index] = value
for bone_name in selected_bones:
bone = obj.pose.bones.get(bone_name)
if bone:
bone.keyframe_insert(data_path="location", frame=time)
bone.keyframe_insert(data_path="rotation_quaternion", frame=time)
bone.keyframe_insert(data_path="scale", frame=time)
# Duplicate the pose if the gap between keyframes is too large and holdPoseOffset > 0
if hold_offset > 0 and i < len(keyframe_data) - 1:
next_time, _ = keyframe_data[i + 1]
if next_time - time > hold_offset + 1:
hold_time = next_time - hold_offset
context.scene.frame_set(hold_time)
for bone_name in selected_bones:
bone = obj.pose.bones.get(bone_name)
if bone:
bone.keyframe_insert(data_path="location", frame=hold_time)
bone.keyframe_insert(data_path="rotation_quaternion", frame=hold_time)
bone.keyframe_insert(data_path="scale", frame=hold_time)
bpy.ops.object.mode_set(mode='OBJECT')
self.report({'INFO'}, "Lip Sync animation created successfully.")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class LipSyncPluginPanel(bpy.types.Panel):
"""Creates a Panel in the Tool shelf"""
bl_label = "Lip Sync Tool"
bl_idname = "OBJECT_PT_lip_sync_tool"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Lipsync"
def draw(self, context):
layout = self.layout
props = context.scene.lip_sync_properties
layout.label(text="Pose Prefix:")
layout.prop(props, "prefix")
layout.label(text="Pose Mappings:")
for i in range(12):
layout.prop(props, f"pose_{i}")
layout.prop(props, "holdPoseOffset")
layout.operator(LipSyncPluginOperator.bl_idname, text="Run Lip Sync Tool")
def register():
bpy.utils.register_class(LipSyncProperties)
bpy.types.Scene.lip_sync_properties = bpy.props.PointerProperty(type=LipSyncProperties)
bpy.utils.register_class(LipSyncPluginOperator)
bpy.utils.register_class(LipSyncPluginPanel)
def unregister():
bpy.utils.unregister_class(LipSyncPluginPanel)
bpy.utils.unregister_class(LipSyncPluginOperator)
del bpy.types.Scene.lip_sync_properties
bpy.utils.unregister_class(LipSyncProperties)
if __name__ == "__main__":
register()
@@ -1,66 +0,0 @@
# 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
# MERCHANTIBILITY 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 <http://www.gnu.org/licenses/>.
from .model.node_relax_props import NodeRelaxProps
from .operators.node_relax_arrange import NodeRelaxArrange
from .operators.node_relax_brush import NodeRelaxBrush
from .panels.node_relax_arrange import NodeRelaxArrangePanel
from .panels.node_relax_brush import NodeRelaxBrushPanel
bl_info = {
"name": "Node Relax",
"author": "Shahzod Boyhonov (Specoolar)",
"description": "Tool for arranging nodes easier",
"blender": (2, 92, 0),
"version": (1, 0, 0),
"location": "Node Editor > Properties > Node Relax. Shortcut: Shift R",
"category": "Node",
}
import bpy
addon_keymaps = []
def register():
wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
if kc:
km = kc.keymaps.new(name='Node Editor', space_type='NODE_EDITOR')
kmi = km.keymap_items.new("node_relax.brush", 'R', 'PRESS', shift=True)
addon_keymaps.append((km, kmi))
bpy.utils.register_class(NodeRelaxBrush)
bpy.utils.register_class(NodeRelaxBrushPanel)
bpy.utils.register_class(NodeRelaxArrange)
bpy.utils.register_class(NodeRelaxArrangePanel)
bpy.utils.register_class(NodeRelaxProps)
bpy.types.Scene.NodeRelax_props = bpy.props.PointerProperty(type=NodeRelaxProps)
def unregister():
for km, kmi in addon_keymaps:
km.keymap_items.remove(kmi)
addon_keymaps.clear()
bpy.utils.unregister_class(NodeRelaxBrush)
bpy.utils.unregister_class(NodeRelaxBrushPanel)
bpy.utils.unregister_class(NodeRelaxArrange)
bpy.utils.unregister_class(NodeRelaxArrangePanel)
bpy.utils.unregister_class(NodeRelaxProps)
del bpy.types.Scene.NodeRelax_props
if __name__ == "__main__":
register()
@@ -0,0 +1,66 @@
# 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
# MERCHANTIBILITY 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 <http://www.gnu.org/licenses/>.
from .model.node_relax_props import NodeRelaxProps
from .operators.node_relax_arrange import NodeRelaxArrange
from .operators.node_relax_brush import NodeRelaxBrush
from .panels.node_relax_arrange import NodeRelaxArrangePanel
from .panels.node_relax_brush import NodeRelaxBrushPanel
bl_info = {
"name": "Node Relax",
"author": "Shahzod Boyhonov (Specoolar)",
"description": "Tool for arranging nodes easier",
"blender": (4, 4, 0),
"version": (1, 1, 0),
"location": "Node Editor > Properties > Node Relax. Shortcut: Shift R",
"category": "Node",
}
import bpy
addon_keymaps = []
def register():
wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
if kc:
km = kc.keymaps.new(name='Node Editor', space_type='NODE_EDITOR')
kmi = km.keymap_items.new("node_relax.brush", 'R', 'PRESS', shift=True)
addon_keymaps.append((km, kmi))
bpy.utils.register_class(NodeRelaxBrush)
bpy.utils.register_class(NodeRelaxBrushPanel)
bpy.utils.register_class(NodeRelaxArrange)
bpy.utils.register_class(NodeRelaxArrangePanel)
bpy.utils.register_class(NodeRelaxProps)
bpy.types.Scene.NodeRelax_props = bpy.props.PointerProperty(type=NodeRelaxProps)
def unregister():
for km, kmi in addon_keymaps:
km.keymap_items.remove(kmi)
addon_keymaps.clear()
bpy.utils.unregister_class(NodeRelaxBrush)
bpy.utils.unregister_class(NodeRelaxBrushPanel)
bpy.utils.unregister_class(NodeRelaxArrange)
bpy.utils.unregister_class(NodeRelaxArrangePanel)
bpy.utils.unregister_class(NodeRelaxProps)
del bpy.types.Scene.NodeRelax_props
if __name__ == "__main__":
register()
@@ -39,17 +39,6 @@ class NodeRelaxBrush(bpy.types.Operator):
bl_options = {"UNDO", "REGISTER"}
def __init__(self):
self.radius = 100
self.lmb = False
self.delta = mathutils.Vector((0, 0))
self.cursor_pos = mathutils.Vector((0, 0))
self.cursor_prev_pos = mathutils.Vector((0, 0))
self.slide_vec = mathutils.Vector((0, 0))
self. drag_mode = False
self.is_dragging = False
self.dragging_node = None
@classmethod
def poll(cls, context):
space = context.space_data
@@ -188,11 +177,20 @@ class NodeRelaxBrush(bpy.types.Operator):
return {'CANCELLED'}
self.tree = context.space_data.edit_tree
# Initialize runtime state here (avoid __init__ for Blender RNA types)
self.radius = 100
self.lmb = False
self.delta = mathutils.Vector((0, 0))
self.cursor_pos = mathutils.Vector((0, 0))
self.cursor_prev_pos = mathutils.Vector((0, 0))
self.slide_vec = mathutils.Vector((0, 0))
self.drag_mode = False
self.is_dragging = False
self.dragging_node = None
context.window_manager.modal_handler_add(self)
st = bpy.types.SpaceNodeEditor
self.draw_handler = st.draw_handler_add(draw_callback, (self,), 'WINDOW', 'POST_VIEW')
self.lmb = False
props.IsRunning = True
self.update_cursor_pos(context, event)
self.update_radius(context, props.BrushSize)
-1
View File
@@ -1 +0,0 @@
This file indicates that CG Cookie built this version of RetopoFlow for release on GitHub.
-103
View File
@@ -1,103 +0,0 @@
# RetopoFlow
RetopoFlow is a suite of fun, sketch-based retopology tools for Blender from [Orange Turbine](https://orangeturbine.com) that generate geometry which snap to your high poly objects as you draw on the surface.
This documentation covers the installation and usage of all tools included in the add-on.
You can read about the features and purchase a copy on [our website](https://orangeturbine.com/downloads/retopoflow) or the [Blender Market](https://blendermarket.com/products/retopoflow/).
![Blender Market](help/images/blendermarket_screenshot.png)
If youre brand new to RetopoFlow, check the [Quick Start page](https://docs.retopoflow.com/quick_start.html).
Otherwise, jump right over to the [Table of Contents](https://docs.retopoflow.com/table_of_contents.html).
## Requirements
Below is a table showing which versions of RetopoFlow and Blender are compatible.
| RetopoFlow | Blender |
| ---------- | -------------- |
| 3.4.0 | 3.6 or later |
| 3.3.0 | 2.93--3.5 |
| 3.2.4 | 2.8x--2.9x |
| 2.0.3 | 2.79 or before |
All versions of RetopoFlow will work on any operating system the Blender supports.
## Downloading
Future updates to RetopoFlow are funded by Blender Market purchases, and we provide top priority support through the Blender Market.
However, we also made RetopoFlow accessible on RetopoFlow's [GitHub Page](https://github.com/CGCookie/retopoflow), especially for students, teachers, and those using RetopoFlow for educational purposes.
You may download RetopoFlow from your [account dashboard](https://blendermarket.com/account/orders) on the Blender Market once you have already purchased it or from RetopoFlow's [GitHub Releases Page](https://github.com/CGCookie/retopoflow/releases).
For the more techie crowd, you can also symlink a clone of the GitHub repo to your add-ons folder.
Important: Blender has issues with the zip files that GitHub automatically packages with the green `Code` button on the main GitHub page.
Do _not_ use the zip files created by GitHub.
Instead, use the officially packaged versions that we provide through the Blender Market or the GitHub Releases Page.
The code for RetopoFlow is open source under the [GPL 3.0](https://www.gnu.org/licenses/gpl-3.0.en.html) license.
The non-code assets in this repository are not.
## Installing
The easiest way to install RetopoFlow is to do so directly within Blender.
You can do this by going to Edit > Preferences > Add-ons > Install.
This will open a File Browser in Blender, allowing to you navigate to and select the zip file you downloaded.
Press Install from file.
_If your browser auto-extracted the downloaded zip file, then you will need to re-compress the **RetopoFlow** folder before installing, or use Save As to save the zip file without extracting the contents._
Once installed, Blender should automatically filter the list of add-ons to show only RetopoFlow.
You can then enable the add-on by clicking the checkbox next to `3D View: RetopoFlow`.
![Installing RetopoFlow](help/images/install.png)
If you have any issues with installing, please try the following steps:
1. Download the latest version of RetopoFlow for your version of Blender (see Requirements section above).
2. Open Blender
3. Head to Edit > Preferences > Add-ons and search for RetopoFlow
4. Expand by clicking the triangle, and then press Remove
5. Close Blender to completely clear out the previous version
6. Open Blender and head to preferences again
7. Click Install
8. Navigate to your RetopoFlow zip file (please do not unzip)
9. Click Install Add-on
10. Enable RetopoFlow
## Updating
RetopoFlow 3 comes with a built-in updater.
Once you've installed it the first time, simply check for updates using the RetopoFlow menu.
If you need to update the add-on manually for any reason, please be sure to uninstall the old version and restart Blender before installing the new version.
The RetopoFlow updater will keep all of your previous settings intact.
If you need to update manually for whatever reason, you can also keep your preferences by copying the `RetopoFlow_keymaps.json` and `RetopoFlow_options.json` files from the previous version's folder before installation and pasting them into the new version's folder after installation.
See the [Updater page](https://docs.retopoflow.com/addon_updater.html) for more details.
## Getting Support
Here are ways to get help with a problem or a question that the [documentation](https://docs.retopoflow.com) isn't answering:
- Get high priority support from Orange Turbine by sending a message from your [Blender Market inbox](https://blendermarket.com/inbox) once you've purchased a copy.
- Create a new [issue](https://github.com/CGCookie/retopoflow/issues/new/choose) on RetopoFlow's [GitHub page](https://github.com/CGCookie/retopoflow).
- Reach out to us via email at [retopoflow@cgcookie.com](mailto:retopoflow@cgcookie.com).
Please provide as much information and detail as possible, such as steps to reproduce the issue, what behavior you expected to see vs what you actually saw, screenshots, and so on.
See [Debugging](https://docs.retopoflow.com/debugging.html) for details on getting as much useful information as possible.
Also, if possible, please consider sending us the `.blend` file.
## Contributing
Pull requests are welcome!
If you'd like to contribute to the project then simply fork the repo, work on your changes, and then submit a pull request.
We are quite strict on what we allow in, but all suggestions are welcome.
If you're unsure what to contribute, then look at the [open issues](https://github.com/CGCookie/retopoflow/issues) for the current to-dos.
@@ -1,20 +0,0 @@
Copyright (C) 2023 Orange Turbine
http://orangeturbine.com
retopoflow@cgcookie.com
Created by Dr. Jonathan Denning, Patrick Moore, Jonathan Williamson, and Jonathan Lampel
All code included in this repository 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 <http://www.gnu.org/licenses/>.
All non-code assets, unless otherwise stated, are property of CG Cookie Inc and may not be distributed with the source code unless granted permission by Orange Turbine.
@@ -1,9 +0,0 @@
{
"escape to quit": true,
"expand advanced panel": true,
"last auto save path": "C:\\Users\\drago\\OneDrive\\Desktop\\BondingArtifact\\assets\\ArtifactObsidian\\Obsidian2_retopo\\Obsidian2_051_RetopoFlow_AutoSave.blend",
"rf version": "3.4.3",
"starting tool": "Tweak",
"version update": false,
"welcome": false
}
-78
View File
@@ -1,78 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore
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 <http://www.gnu.org/licenses/>.
'''
# initialize deep debugging as early as possible
from .addon_common.terminal.deepdebug import DeepDebug
DeepDebug.init(
fn_debug='RetopoFlow_debug.txt',
clear=True, # clear deep debugging file every Blender session
enable_only_once=True, # only allow this feature to be enabled for one session
)
#################################################################################################################################
# NOTE: the following lines are automatically updated based on hive.json
# if "warning" is present (not commented out), a warning icon will show in add-ons list
bl_info = {
"name": "RetopoFlow",
"description": "A suite of retopology tools for Blender through a unified retopology mode",
"author": "Jonathan Denning, Jonathan Lampel, Jonathan Williamson, Patrick Moore, Patrick Crawford, Christopher Gearhart",
"blender": (3, 6, 0),
"version": (3, 4, 3),
"doc_url": "https://docs.retopoflow.com",
"tracker_url": "https://github.com/CGCookie/retopoflow/issues",
"location": "View 3D > Header",
"category": "3D View",}
# update bl_info above based on hive data
from .addon_common.hive.hive import Hive
Hive.update_bl_info(bl_info, __file__)
import bpy
def register(): pass
def unregister(): pass
from .addon_common.terminal import term_printer
if bpy.app.background:
term_printer.boxed(
f'Blender is running in background',
f'Skipping any further initialization',
title='RetopoFlow', margin=' ', sides='double', color='black', highlight='blue',
)
elif bpy.app.version < Hive.get_version('blender hard minimum version'):
term_printer.boxed(
f'Blender version does not meet hard requirements',
f'Minimum Blender Version: {Hive.get("blender hard minimum version")}',
f'Skipping any further initialization',
title='RetopoFlow', margin=' ', sides='double', color='black', highlight='red',
)
else:
from .retopoflow import blenderregister
def register(): blenderregister.register(bl_info)
def unregister(): blenderregister.unregister(bl_info)
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
@@ -1,11 +0,0 @@
# addon_common
This repo contains the CookieCutter Blender add-on framework.
## Example Add-on
As an example add-on, see the [ExtruCut](https://github.com/CGCookie/ExtruCut) project.
## resources
- Blender Conference 2018 workshop [slides](https://gfx.cse.taylor.edu/courses/bcon18/index.md.html?scale) and [presentation](https://www.youtube.com/watch?v=YSHdSNhMO1c)
@@ -1,62 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, Patrick Moore
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 <http://www.gnu.org/licenses/>.
'''
__all__ = [
'bezier',
'blender',
'blender_preferences',
'bmesh_render',
'boundvar',
'colors',
'debug',
'decorators',
'drawing',
'fontmanager',
'fsm',
'globals',
'hasher',
'irc',
'logger',
'markdown',
'maths',
'metaclasses',
'parse',
'profiler',
'shaders',
'ui_core',
'ui_document',
'ui_styling',
'ui_core_utilities',
'updater_core',
'updater_ops',
'useractions',
'utils',
]
import bpy
if bpy.app.version >= (3, 2, 0):
# import the following only to populate the globals
from . import debug as _
from . import drawing as _
from . import logger as _
from . import profiler as _
from . import ui_core as _
@@ -1,636 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import math
from mathutils import Vector, Matrix
from .maths import Point, Vec
from .utils import iter_running_sum
def compute_quadratic_weights(t):
t0, t1 = t, (1-t)
return (t1**2, 2*t0*t1, t0**2)
def compute_cubic_weights(t):
t0, t1 = t, (1-t)
return (t1**3, 3*t0*t1**2, 3*t0**2*t1, t0**3)
def interpolate_cubic(v0, v1, v2, v3, t):
b0, b1, b2, b3 = compute_cubic_weights(t)
return v0*b0 + v1*b1 + v2*b2 + v3*b3
def compute_cubic_error(v0, v1, v2, v3, l_v, l_t):
return math.sqrt(sum(
(interpolate_cubic(v0, v1, v2, v3, t) - v)**2
for v, t in zip(l_v, l_t)
))
def fit_cubicbezier(l_v, l_t):
#########################################################
# http://nbviewer.ipython.org/gist/anonymous/5688579
# make the summation functions for A (16 of them)
A_fns = [
lambda l_t: sum([2*t**0*(t-1)**6 for t in l_t]),
lambda l_t: sum([-6*t**1*(t-1)**5 for t in l_t]),
lambda l_t: sum([6*t**2*(t-1)**4 for t in l_t]),
lambda l_t: sum([-2*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([-6*t**1*(t-1)**5 for t in l_t]),
lambda l_t: sum([18*t**2*(t-1)**4 for t in l_t]),
lambda l_t: sum([-18*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([6*t**4*(t-1)**2 for t in l_t]),
lambda l_t: sum([6*t**2*(t-1)**4 for t in l_t]),
lambda l_t: sum([-18*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([18*t**4*(t-1)**2 for t in l_t]),
lambda l_t: sum([-6*t**5*(t-1)**1 for t in l_t]),
lambda l_t: sum([-2*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([6*t**4*(t-1)**2 for t in l_t]),
lambda l_t: sum([-6*t**5*(t-1)**1 for t in l_t]),
lambda l_t: sum([2*t**6*(t-1)**0 for t in l_t])
]
# make the summation functions for b (4 of them)
b_fns = [
lambda l_t, l_v: sum(v * (-2 * (t**0) * ((t-1)**3))
for t, v in zip(l_t, l_v)),
lambda l_t, l_v: sum(v * (6 * (t**1) * ((t-1)**2))
for t, v in zip(l_t, l_v)),
lambda l_t, l_v: sum(v * (-6 * (t**2) * ((t-1)**1))
for t, v in zip(l_t, l_v)),
lambda l_t, l_v: sum(v * (2 * (t**3) * ((t-1)**0))
for t, v in zip(l_t, l_v)),
]
# compute the data we will put into matrix A
A_values = [fn(l_t) for fn in A_fns]
# fill the A matrix with data
A_matrix = Matrix(tuple(zip(*[iter(A_values)]*4)))
try:
A_inv = A_matrix.inverted()
except:
return (float('inf'), l_v[0], l_v[0], l_v[0], l_v[0])
# compute the data we will put into the b vector
b_values = [fn(l_t, l_v) for fn in b_fns]
# fill the b vector with data
b_vector = Vector(b_values)
# solve for the unknowns in vector x
v0, v1, v2, v3 = A_inv @ b_vector
err = compute_cubic_error(v0, v1, v2, v3, l_v, l_t) #/ len(l_v)
return (err, v0, v1, v2, v3)
def fit_cubicbezier_spline(
l_co, error_scale, depth=0,
t0=0, t3=-1, allow_split=True, force_split=False,
min_count_split=15, max_depth_split=4,
):
'''
fits cubic bezier to given points
returns list of tuples of (t0,t3,p0,p1,p2,p3)
that best fits the given points l_co
where t0 and t3 are the passed-in t0 and t3
and p0,p1,p2,p3 are the control points of bezier
'''
count = len(l_co)
if t3 == -1:
t3 = count-1
assert count > 2, "Need at least 2 points to fit cubic bezier"
if count == 2:
# special case: line
p0, p3 = l_co[0], l_co[-1]
diff = p3 - p0
return [(t0, t3, p0, p0+diff*0.33, p0+diff*0.66, p3)]
if count == 3:
new_co = [
l_co[0],
Point.average(l_co[:2]),
l_co[1],
Point.average(l_co[1:]),
l_co[2]
]
return fit_cubicbezier_spline(
new_co, error_scale,
depth=depth,
t0=t0, t3=t3,
allow_split=allow_split, force_split=force_split
)
l_d = [0] + [(v0-v1).length for v0, v1 in zip(l_co[:-1], l_co[1:])]
l_ad = [s for d, s in iter_running_sum(l_d)]
dist = sum(l_d)
if dist <= 0:
# print(spc + 'fit_cubicbezier_spline: returning []')
return [] # [(t0,t3,l_co[0],l_co[0],l_co[0],l_co[0])]
l_t = [ad/dist for ad in l_ad]
ex, x0, x1, x2, x3 = fit_cubicbezier([co[0] for co in l_co], l_t)
ey, y0, y1, y2, y3 = fit_cubicbezier([co[1] for co in l_co], l_t)
ez, z0, z1, z2, z3 = fit_cubicbezier([co[2] for co in l_co], l_t)
tot_error = ex+ey+ez
#print(f'error={tot_error} max={error_scale} force={force_split} allow={allow_split}') #, l=4)
if not force_split:
do_not_split = tot_error < error_scale
do_not_split |= depth == max_depth_split
do_not_split |= len(l_co) <= min_count_split
do_not_split |= not allow_split
if do_not_split:
p0, p1 = Point((x0, y0, z0)), Point((x1, y1, z1))
p2, p3 = Point((x2, y2, z2)), Point((x3, y3, z3))
return [(t0, t3, p0, p1, p2, p3)]
# too much error in fit. split sequence in two, and fit each sub-sequence
# find a good split point
ind_split = -1
mindot = 1.0
for ind in range(5, len(l_co)-5):
if l_t[ind] < 0.4:
continue
if l_t[ind] > 0.6:
break
# if l_ad[ind] < 0.1: continue
# if l_ad[ind] > dist-0.1: break
v0 = l_co[ind-4]
v1 = l_co[ind+0]
v2 = l_co[ind+4]
d0 = (v1-v0).normalized()
d1 = (v2-v1).normalized()
dot01 = d0.dot(d1)
if ind_split == -1 or dot01 < mindot:
ind_split = ind
mindot = dot01
if ind_split == -1:
# did not find a good splitting point!
p0, p1, p2, p3 = Point((x0, y0, z0)), Point(
(x1, y1, z1)), Point((x2, y2, z2)), Point((x3, y3, z3))
#p0,p3 = Point(l_co[0]),Point(l_co[-1])
return [(t0, t3, p0, p1, p2, p3)]
#print(spc + 'splitting at %d' % ind_split)
l_co0, l_co1 = l_co[:ind_split+1], l_co[ind_split:] # share split point
tsplit = ind_split # / (len(l_co)-1)
bezier0 = fit_cubicbezier_spline(
l_co0, error_scale, depth=depth+1, t0=t0, t3=tsplit)
bezier1 = fit_cubicbezier_spline(
l_co1, error_scale, depth=depth+1, t0=tsplit, t3=t3)
return bezier0 + bezier1
class CubicBezier:
split_default = 100
segments_default = 100
@staticmethod
def create_from_points(pts_list):
'''
Estimates best spline to fit given points
'''
count = len(pts_list)
if count == 0:
assert False
if count == 1:
assert False
if count == 2:
p0, p3 = pts_list
diff = p3-p0
p1, p2 = p0+diff*0.33, p0+diff*0.66
return CubicBezier(p0, p1, p2, p3)
if count == 3:
p0, p03, p3 = pts_list
d003, d303 = (p03-p0), (p03-p3)
p1, p2 = p0+d003*0.5, p3+d303*0.5
return CubicBezier(p0, p1, p2, p3)
l_d = [0] + [(p0-p1).length for p0,
p1 in zip(pts_list[:-1], pts_list[1:])]
l_ad = [s for d, s in iter_running_sum(l_d)]
dist = sum(l_d)
if dist <= 0:
p0 = pts_list[0]
return CubicBezier(p0, p0, p0, p0)
l_t = [ad/dist for ad in l_ad]
ex, x0, x1, x2, x3 = fit_cubicbezier([pt[0] for pt in pts_list], l_t)
ey, y0, y1, y2, y3 = fit_cubicbezier([pt[1] for pt in pts_list], l_t)
ez, z0, z1, z2, z3 = fit_cubicbezier([pt[2] for pt in pts_list], l_t)
p0 = Point((x0, y0, z0))
p1 = Point((x1, y1, z1))
p2 = Point((x2, y2, z2))
p3 = Point((x3, y3, z3))
return CubicBezier(p0, p1, p2, p3)
def __init__(self, p0, p1, p2, p3):
self.p0, self.p1, self.p2, self.p3 = p0, p1, p2, p3
self.tessellation = []
def __iter__(self): return iter([self.p0, self.p1, self.p2, self.p3])
def points(self): return (self.p0, self.p1, self.p2, self.p3)
def copy(self):
''' shallow copy '''
return CubicBezier(self.p0, self.p1, self.p2, self.p3)
def eval(self, t):
p0, p1, p2, p3 = self.p0, self.p1, self.p2, self.p3
b0, b1, b2, b3 = compute_cubic_weights(t)
return Point.weighted_average([
(b0, p0), (b1, p1), (b2, p2), (b3, p3)
])
def eval_derivative(self, t):
p0, p1, p2, p3 = self.p0, self.p1, self.p2, self.p3
q0, q1, q2 = 3*(p1-p0), 3*(p2-p1), 3*(p3-p2)
b0, b1, b2 = compute_quadratic_weights(t)
return q0*b0 + q1*b1 + q2*b2
def subdivide(self, iters=1):
if iters == 0:
return [self]
# de casteljau subdivide
p0, p1, p2, p3 = self.p0, self.p1, self.p2, self.p3
q0, q1, q2 = (p0+p1)/2, (p1+p2)/2, (p2+p3)/2
r0, r1 = (q0+q1)/2, (q1+q2)/2
s = (r0+r1)/2
cb0, cb1 = CubicBezier(p0, q0, r0, s), CubicBezier(s, r1, q2, p3)
if iters == 1:
return [cb0, cb1]
return cb0.subdivide(iters=iters-1) + cb1.subdivide(iters=iters-1)
def compute_linearity(self, fn_dist):
'''
Estimating measure of linearity as ratio of distances
of curve mid-point and mid-point of end control points
over half the distance between end control points
p1 _
/
|
p0 * * p3
_/
p2
'''
p0, p1, p2, p3 = Vector(self.p0), Vector(
self.p1), Vector(self.p2), Vector(self.p3)
q0, q1, q2 = (p0+p1)/2, (p1+p2)/2, (p2+p3)/2
r0, r1 = (q0+q1)/2, (q1+q2)/2
s = (r0+r1)/2
m = (p0+p3)/2
d03 = fn_dist(p0, p3)
dsm = fn_dist(s, m)
return 2 * dsm / d03
def subdivide_linesegments(self, fn_dist, max_linearity=None):
if self.compute_linearity(fn_dist) < (max_linearity or 0.1):
return [self]
# de casteljau subdivide:
p0, p1, p2, p3 = Vector(self.p0), Vector(
self.p1), Vector(self.p2), Vector(self.p3)
q0, q1, q2 = (p0+p1)/2, (p1+p2)/2, (p2+p3)/2
r0, r1 = (q0+q1)/2, (q1+q2)/2
s = (r0+r1)/2
cbs = CubicBezier(p0, q0, r0, s), CubicBezier(s, r1, q2, p3)
segs0, segs1 = [cb.subdivide_linesegments(
fn_dist, max_linearity=max_linearity) for cb in cbs]
return segs0 + segs1
def length(self, fn_dist, max_linearity=None):
l = self.subdivide_linesegments(fn_dist, max_linearity=max_linearity)
return sum(fn_dist(cb.p0, cb.p3) for cb in l)
def approximate_length_uniform(self, fn_dist, split=None):
split = split or self.split_default
p = self.p0
d = 0
for i in range(split):
q = self.eval((i+1) / split)
d += fn_dist(p, q)
p = q
return d
def approximate_t_at_interval_uniform(self, interval, fn_dist, split=None):
split = split or self.split_default
p = self.p0
d = 0
for i in range(split):
percent = (i+1) / split
q = self.eval(percent)
d += fn_dist(p, q)
if interval <= d:
return percent
p = q
return 1
def approximate_ts_at_intervals_uniform(
self, intervals, fn_dist, split=None
):
a = self.approximate_t_at_interval_uniform
def approx(i): return a(i, fn_dist, split=None)
return [approx(interval) for interval in intervals]
def get_tessellate_uniform(self, fn_dist, split=None):
split = split or self.split_default
ts = [i/(split-1) for i in range(split)]
ps = [self.eval(t) for t in ts]
ds = [0] + [fn_dist(p, q) for p, q in zip(ps[:-1], ps[1:])]
return [(t, p, d) for t, p, d in zip(ts, ps, ds)]
def tessellate_uniform_points(self, segments=None):
segments = segments or self.segments_default
ts = [i/(segments-1) for i in range(segments)]
ps = [self.eval(t) for t in ts]
return ps
#########################################
# #
# the following code **requires** that #
# self.tessellate_uniform() is called #
# beforehand! #
# #
#########################################
def tessellate_uniform(self, fn_dist, split=None):
self.tessellation = self.get_tessellate_uniform(fn_dist, split=split)
def approximate_t_at_point_tessellation(self, point, fn_dist):
bd, bt = None, None
for t, q, _ in self.tessellation:
d = fn_dist(point, q)
if bd is None or d < bd:
bd, bt = d, t
return bt
def approximate_totlength_tessellation(self):
return sum(self.approximate_lengths_tessellation())
def approximate_lengths_tessellation(self):
return [d for _, _, d in self.tessellation]
class CubicBezierSpline:
@staticmethod
def create_from_points(pts_list, max_error, **kwargs):
'''
Estimates best spline to fit given points
'''
cbs = []
inds = []
for pts in pts_list:
cbs_pts = fit_cubicbezier_spline(pts, max_error, **kwargs)
cbs += [CubicBezier(p0, p1, p2, p3) for _, _, p0, p1, p2, p3 in cbs_pts]
inds += [(ind0, ind1) for ind0, ind1, _, _, _, _ in cbs_pts]
return CubicBezierSpline(cbs=cbs, inds=inds)
def __init__(self, cbs=None, inds=None):
if cbs is None:
cbs = []
if inds is None:
inds = []
if type(cbs) is CubicBezierSpline:
cbs = [cb.copy() for cb in cbs.cbs]
assert type(cbs) is list, "expected list"
self.cbs = cbs
self.inds = inds
self.tessellation = []
def copy(self):
return CubicBezierSpline(
cbs=[cb.copy() for cb in self.cbs],
inds=list(self.inds)
)
def __add__(self, other):
t = type(other)
if t is CubicBezierSpline:
return CubicBezierSpline(
self.cbs + other.cbs,
self.inds + other.inds
)
if t is CubicBezier:
return CubicBezierSpline(self.cbs + [other])
if t is list:
return CubicBezierSpline(self.cbs + other)
assert False, "unhandled type: %s (%s)" % (str(other), str(t))
def __iadd__(self, other):
t = type(other)
if t is CubicBezierSpline:
self.cbs += other.cbs
self.inds += other.inds
elif t is CubicBezier:
self.cbs += [other]
self.inds = []
elif t is list:
self.cbs += other
self.inds = []
else:
assert False, "unhandled type: %s (%s)" % (str(other), str(t))
def __len__(self): return len(self.cbs)
def __iter__(self): return self.cbs.__iter__()
def __getitem__(self, idx): return self.cbs[idx]
def eval(self, t):
if t < 0.0:
t = 0
idx = 0
elif t >= len(self):
t = 1
idx = len(self)-1
else:
idx = int(t)
t = t - idx
return self.cbs[idx].eval(t)
def eval_derivative(self, t):
if t < 0.0:
t = 0
idx = 0
elif t >= len(self):
t = 1
idx = len(self)-1
else:
idx = int(t)
t = t - idx
return self.cbs[idx].eval_derivative(t)
def approximate_totlength_uniform(self, fn_dist, split=None):
return sum(self.approximate_lengths_uniform(fn_dist, split=split))
def approximate_lengths_uniform(self, fn_dist, split=None):
return [
cb.approximate_length_uniform(fn_dist, split=split)
for cb in self.cbs
]
def approximate_ts_at_intervals_uniform(
self, intervals, fn_dist, split=None
):
lengths = self.approximate_lengths_uniform(fn_dist, split=split)
totlength = sum(lengths)
ts = []
for interval in intervals:
if interval < 0:
ts.append(0)
continue
if interval >= totlength:
ts.append(len(self.cbs))
continue
for i, length in enumerate(lengths):
if interval <= length:
t = self.cbs[i].approximate_t_at_interval_uniform(
interval, fn_dist, split=split)
ts.append(i + t)
break
interval -= length
else:
assert False
return ts
def subdivide_linesegments(self, fn_dist, max_linearity=None):
return CubicBezierSpline(cbi
for cb in self.cbs
for cbi in cb.subdivide_linesegments(
fn_dist,
max_linearity=max_linearity
))
#########################################
# #
# the following code **requires** that #
# self.tessellate_uniform() is called #
# beforehand! #
# #
#########################################
def tessellate_uniform(self, fn_dist, split=None):
self.tessellation.clear()
for i, cb in enumerate(self.cbs):
cb_tess = cb.get_tessellate_uniform(fn_dist, split=split)
self.tessellation.append(cb_tess)
def approximate_totlength_tessellation(self):
return sum(self.approximate_lengths_tessellation())
def approximate_lengths_tessellation(self):
return [sum(d for _, _, d in cb_tess) for cb_tess in self.tessellation]
def approximate_ts_at_intervals_tessellation(self, intervals):
lengths = self.approximate_lengths_tessellation()
totlength = sum(lengths)
ts = []
for interval in intervals:
if interval < 0:
ts.append(0)
continue
if interval >= totlength:
ts.append(len(self.cbs))
continue
for i, length in enumerate(lengths):
if interval > length:
interval -= length
continue
cb_tess = self.tessellation[i]
for t, p, d in cb_tess:
if interval > d:
interval -= d
continue
ts.append(i+t)
break
else:
assert False
break
else:
assert False
return ts
def approximate_ts_at_points_tessellation(self, points, fn_dist):
ts = []
for p in points:
bd, bt = None, None
for i, cb_tess in enumerate(self.tessellation):
for t, q, _ in cb_tess:
d = fn_dist(p, q)
if bd is None or d < bd:
bd, bt = d, i+t
ts.append(bt)
return ts
def approximate_t_at_point_tessellation(self, point, fn_dist):
bd, bt = None, None
for i, cb_tess in enumerate(self.tessellation):
for t, q, _ in cb_tess:
d = fn_dist(point, q)
if bd is None or d < bd:
bd, bt = d, i+t
return bt
class GenVector(list):
'''
Generalized Vector, allows for some simple ordered items to be linearly combined
which is useful for interpolating arbitrary points of Bezier Spline.
'''
def __mul__(self, scalar: float): # ->GVector:
for idx in range(len(self)):
self[idx] *= scalar
return self
def __rmul__(self, scalar: float): # ->GVector:
return self.__mul__(scalar)
def __add__(self, other: list): # ->GVector:
for idx in range(len(self)):
self[idx] += other[idx]
return self
if __name__ == '__main__':
# run tests
print('-'*50)
l = GenVector([Vector((1, 2, 3)), 23])
print(l)
print(l * 2)
print(4 * l)
l2 = GenVector([Vector((0, 0, 1)), 10])
print(l + l2)
print(2 * l + l2 * 4)
File diff suppressed because it is too large Load Diff
@@ -1,90 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import bpy
from .globals import Globals
class Cursors:
# https://docs.blender.org/api/current/bpy.types.Window.html#bpy.types.Window.cursor_set
_cursors = {
# blender cursors
'DEFAULT': 'DEFAULT',
'NONE': 'NONE',
'WAIT': 'WAIT',
'CROSSHAIR': 'CROSSHAIR',
'MOVE_X': 'MOVE_X',
'MOVE_Y': 'MOVE_Y',
'KNIFE': 'KNIFE',
'TEXT': 'TEXT',
'PAINT_BRUSH': 'PAINT_BRUSH',
'HAND': 'HAND',
'SCROLL_X': 'SCROLL_X',
'SCROLL_Y': 'SCROLL_Y',
'EYEDROPPER': 'EYEDROPPER',
# lower case version of blender cursors
'default': 'DEFAULT',
'none': 'NONE',
'wait': 'WAIT',
'crosshair': 'CROSSHAIR',
'move_x': 'MOVE_X',
'move_y': 'MOVE_Y',
'knife': 'KNIFE',
'text': 'TEXT',
'paint_brush': 'PAINT_BRUSH',
'hand': 'HAND',
'scroll_x': 'SCROLL_X',
'scroll_y': 'SCROLL_Y',
'eyedropper': 'EYEDROPPER',
}
@staticmethod
def __getattr__(cursor):
assert cursor in Cursors._cursors
return Cursors._cursors.get(cursor, 'DEFAULT')
@staticmethod
def set(cursor):
# print('Cursors.set', cursor)
cursor = Cursors._cursors.get(cursor, 'DEFAULT')
for wm in bpy.data.window_managers:
for win in wm.windows:
win.cursor_modal_set(cursor)
@staticmethod
def restore():
for wm in bpy.data.window_managers:
for win in wm.windows:
win.cursor_modal_restore()
@property
@staticmethod
def cursor(): return 'DEFAULT' # TODO: how to get??
@cursor.setter
@staticmethod
def cursor(cursor): Cursors.set(cursor)
@staticmethod
def warp(x, y): bpy.context.window.cursor_warp(x, y)
Globals.set(Cursors())
@@ -1,61 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import bpy
def get_preferences(ctx=None):
return (ctx if ctx else bpy.context).preferences
def mouse_doubleclick():
# time/delay (in seconds) for a double click
return bpy.context.preferences.inputs.mouse_double_click_time / 1000
def mouse_drag():
# number of pixels to drag before tweak/drag event is triggered
return bpy.context.preferences.inputs.drag_threshold_mouse
def mouse_move():
# number of pixels to move before the cursor is considered to have moved
# (used for cycling selected items on successive clicks)
return bpy.context.preferences.inputs.move_threshold
def mouse_select():
# returns 'LEFT' if LMB is used for selection or 'RIGHT' if RMB is used for selection
user_keyconfigs = bpy.context.window_manager.keyconfigs.user
map_select_type = {'LEFTMOUSE': 'LEFT', 'RIGHTMOUSE': 'RIGHT'}
try:
select_type = user_keyconfigs.keymaps['3D View'].keymap_items['view3d.select'].type
return map_select_type[select_type]
except Exception as e:
if hasattr(mouse_select, 'reported'): return # already reported
mouse_select.reported = True
print('Addon Common: Exception caught in mouse_select')
print('NOTE: only reporting this once')
print(f'Exception: {e}')
return 'LEFT' # fallback to 'LEFT'
@@ -1,326 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore
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 <http://www.gnu.org/licenses/>.
'''
'''
notes: something is really wrong here to have such poor performance
Below are some related, interesting links
- https://machinesdontcare.wordpress.com/2008/02/02/glsl-discard-z-fighting-supersampling/
- https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/BestPracticesforShaders/BestPracticesforShaders.html
- https://stackoverflow.com/questions/16415037/opengl-core-profile-incredible-slowdown-on-os-x
'''
import os
import re
import math
import ctypes
import random
import traceback
import gpu
import bpy
from bpy_extras.view3d_utils import region_2d_to_origin_3d
from mathutils import Vector, Matrix, Quaternion
from mathutils.bvhtree import BVHTree
from . import gpustate
from .debug import dprint
from .decorators import blender_version_wrapper, add_cache, only_in_blender_version
from .drawing import Drawing
from .maths import (Point, Direction, Frame, XForm, invert_matrix, matrix_normal)
from .profiler import profiler
from .utils import shorten_floats
def glSetDefaultOptions():
gpustate.blend('ALPHA')
gpustate.depth_test('LESS_EQUAL')
def glSetMirror(symmetry=None, view=None, effect=0.0, frame: Frame=None):
mirroring = (0, 0, 0)
if symmetry and frame:
mx = 1.0 if 'x' in symmetry else 0.0
my = 1.0 if 'y' in symmetry else 0.0
mz = 1.0 if 'z' in symmetry else 0.0
mirroring = (mx, my, mz)
bmeshShader.assign('mirror_o', frame.o)
bmeshShader.assign('mirror_x', frame.x)
bmeshShader.assign('mirror_y', frame.y)
bmeshShader.assign('mirror_z', frame.z)
bmeshShader.assign('mirror_view', {'Edge': 1, 'Face': 2}.get(view, 0))
bmeshShader.assign('mirror_effect', effect)
bmeshShader.assign('mirroring', mirroring)
def triangulateFace(verts):
l = len(verts)
if l < 3: return
if l == 3:
yield verts
return
if l == 4:
v0,v1,v2,v3 = verts
yield (v0,v1,v2)
yield (v0,v2,v3)
return
iv = iter(verts)
v0, v2 = next(iv), next(iv)
for v3 in iv:
v1, v2 = v2, v3
yield (v0, v1, v2)
#############################################################################################################
#############################################################################################################
#############################################################################################################
import gpu
from gpu_extras.batch import batch_for_shader
if not bpy.app.background:
Drawing.glCheckError(f'Pre-compile check: bmesh render shader')
verts_vs, verts_fs = gpustate.shader_parse_file('bmesh_render_verts.glsl', includeVersion=False)
verts_shader, verts_ubos = gpustate.gpu_shader('bmesh render: verts', verts_vs, verts_fs)
edges_vs, edges_fs = gpustate.shader_parse_file('bmesh_render_edges.glsl', includeVersion=False)
edges_shader, edges_ubos = gpustate.gpu_shader('bmesh render: edges', edges_vs, edges_fs)
faces_vs, faces_fs = gpustate.shader_parse_file('bmesh_render_faces.glsl', includeVersion=False)
faces_shader, faces_ubos = gpustate.gpu_shader('bmesh render: faces', faces_vs, faces_fs)
Drawing.glCheckError(f'Compiled bmesh render shader')
class BufferedRender_Batch:
_quarantine = {}
POINTS = 1
LINES = 2
TRIANGLES = 3
def __init__(self, drawtype):
global faces_shader, edges_shader, verts_shader
self.count = 0
self.drawtype = drawtype
self.shader, self.shader_ubos, self.shader_type, self.drawtype_name, self.gl_count, self.options_prefix = {
self.POINTS: (verts_shader, verts_ubos, 'POINTS', 'points', 1, 'point'),
self.LINES: (edges_shader, edges_ubos, 'LINES', 'lines', 2, 'line'),
self.TRIANGLES: (faces_shader, faces_ubos, 'TRIS', 'triangles', 3, 'poly'),
}[self.drawtype]
self.batch = None
self._quarantine.setdefault(self.shader, set())
def buffer(self, pos, norm, sel, warn, pin, seam):
if self.shader == None: return
if self.shader_type == 'POINTS':
data = {
# repeat each value 6 times
'vert_pos': [p for p in pos for __ in range(6)],
'vert_norm': [n for n in norm for __ in range(6)],
'selected': [s for s in sel for __ in range(6)],
'warning': [w for w in warn for __ in range(6)],
'pinned': [p for p in pin for __ in range(6)],
'seam': [p for p in seam for __ in range(6)],
'vert_offset': [o for _ in pos for o in [(0,0), (1,0), (0,1), (0,1), (1,0), (1,1)]],
}
elif self.shader_type == 'LINES':
data = {
# repeat each value 6 times
'vert_pos0': [p0 for p0 in pos [0::2] for __ in range(6)],
'vert_pos1': [p1 for p1 in pos [1::2] for __ in range(6)],
'vert_norm': [n for n in norm[0::2] for __ in range(6)],
'selected': [s for s in sel [0::2] for __ in range(6)],
'warning': [w for w in warn[0::2] for __ in range(6)],
'pinned': [p for p in pin [0::2] for __ in range(6)],
'seam': [s for s in seam[0::2] for __ in range(6)],
'vert_offset': [o for _ in pos[0::2] for o in [(0,0), (0,1), (1,1), (0,0), (1,1), (1,0)]],
}
elif self.shader_type == 'TRIS':
data = {
'vert_pos': pos,
'vert_norm': norm,
'selected': sel,
'pinned': pin,
# 'seam': seam,
}
else: assert False, f'BufferedRender_Batch.buffer: Unhandled type: {self.shader_type}'
self.batch = batch_for_shader(self.shader, 'TRIS', data)
self.count = len(pos)
def set_options(self, prefix, opts):
if not opts: return
prefix = f'{prefix} ' if prefix else ''
def set_if_set(opt, cb):
opt = f'{prefix}{opt}'
if opt not in opts: return
cb(opts[opt])
Drawing.glCheckError(f'setting {opt} to {opts[opt]}')
Drawing.glCheckError('BufferedRender_Batch.set_options: start')
dpi_mult = opts.get('dpi mult', 1.0)
set_if_set('color', lambda v: self.set_shader_option('color_normal', v))
set_if_set('color selected', lambda v: self.set_shader_option('color_selected', v))
set_if_set('color warning', lambda v: self.set_shader_option('color_warning', v))
set_if_set('color pinned', lambda v: self.set_shader_option('color_pinned', v))
set_if_set('color seam', lambda v: self.set_shader_option('color_seam', v))
set_if_set('hidden', lambda v: self.set_shader_option('hidden', (v, 0, 0, 0)))
set_if_set('offset', lambda v: self.set_shader_option('offset', (v, 0, 0, 0)))
set_if_set('dotoffset', lambda v: self.set_shader_option('dotoffset', (v, 0, 0, 0)))
if self.shader_type == 'POINTS':
set_if_set('size', lambda v: self.set_shader_option('radius', (v*dpi_mult, 0, 0, 0)))
elif self.shader_type == 'LINES':
set_if_set('width', lambda v: self.set_shader_option('radius', (v*dpi_mult, 2*dpi_mult, 0, 0)))
def _draw(self, sx, sy, sz):
self.set_shader_option('vert_scale', (sx, sy, sz, 0))
self.shader_ubos.update_shader()
self.batch.draw(self.shader)
def is_quarantined(self, k):
return k in self._quarantine[self.shader]
def quarantine(self, k):
# dprint(f'BufferedRender_Batch: quarantining {k} for {self.shader}')
pass
self._quarantine[self.shader].add(k)
def set_shader_option(self, k, v):
if self.is_quarantined(k): return
try: self.shader_ubos.options.assign(k, v)
except Exception as e: self.quarantine(k)
def draw(self, opts):
if self.shader == None or self.count == 0: return
if self.drawtype == self.LINES and opts.get('line width', 1.0) <= 0: return
if self.drawtype == self.POINTS and opts.get('point size', 1.0) <= 0: return
ctx = bpy.context
area, spc, r3d = ctx.area, ctx.space_data, ctx.space_data.region_3d
rgn = ctx.region
if 'blend' in opts: gpustate.blend(opts['blend'])
if 'depth test' in opts: gpustate.depth_test(opts['depth test'])
if 'depth mask' in opts: gpustate.depth_mask(opts['depth mask'])
self.shader.bind()
# set defaults
self.set_shader_option('color_normal', (1.0, 1.0, 1.0, 0.5))
self.set_shader_option('color_selected', (0.5, 1.0, 0.5, 0.5))
self.set_shader_option('color_warning', (1.0, 0.5, 0.0, 0.5))
self.set_shader_option('color_pinned', (1.0, 0.0, 0.5, 0.5))
self.set_shader_option('color_seam', (1.0, 0.0, 0.5, 0.5))
self.set_shader_option('hidden', (0.9, 0, 0, 0))
self.set_shader_option('offset', (0.0, 0, 0, 0))
self.set_shader_option('dotoffset', (0.0, 0, 0, 0))
self.set_shader_option('vert_scale', (1.0, 1.0, 1.0))
self.set_shader_option('radius', (1.0, 0, 0, 0))
use0 = [
1.0 if (not opts.get('no selection', False)) else 0.0,
1.0 if (not opts.get('no warning', False)) else 0.0,
1.0 if (not opts.get('no pinned', False)) else 0.0,
1.0 if (not opts.get('no seam', False)) else 0.0,
]
use1 = [
1.0 if (self.drawtype == self.POINTS) else 0.0,
0.0,
0.0,
0.0,
]
self.set_shader_option('use_settings0', use0)
self.set_shader_option('use_settings1', use1)
self.set_shader_option('matrix_m', opts['matrix model'])
self.set_shader_option('matrix_mn', opts['matrix normal'])
self.set_shader_option('matrix_t', opts['matrix target'])
self.set_shader_option('matrix_ti', opts['matrix target inverse'])
self.set_shader_option('matrix_v', opts['matrix view'])
self.set_shader_option('matrix_vn', opts['matrix view normal'])
self.set_shader_option('matrix_p', opts['matrix projection'])
mx, my, mz = opts.get('mirror x', False), opts.get('mirror y', False), opts.get('mirror z', False)
symmetry = opts.get('symmetry', None)
symmetry_frame = opts.get('symmetry frame', None)
symmetry_view = opts.get('symmetry view', None)
symmetry_effect = opts.get('symmetry effect', 0.0)
mirroring = (0, 0, 0, 0)
if symmetry and symmetry_frame:
mirroring = (
1 if 'x' in symmetry else 0,
1 if 'y' in symmetry else 0,
1 if 'z' in symmetry else 0,
)
self.set_shader_option('mirror_o', symmetry_frame.o)
self.set_shader_option('mirror_x', symmetry_frame.x)
self.set_shader_option('mirror_y', symmetry_frame.y)
self.set_shader_option('mirror_z', symmetry_frame.z)
mirror_settings = [
{'Edge': 1.0, 'Face': 2.0}.get(symmetry_view, 0.0),
symmetry_effect,
0.0,
0.0,
]
self.set_shader_option('mirror_settings', mirror_settings)
self.set_shader_option('mirroring', mirroring)
view_settings0 = [
r3d.view_distance,
0.0 if (r3d.view_perspective == 'ORTHO') else 1.0,
opts.get('focus mult', 1.0),
opts.get('alpha backface', 0.5),
]
view_settings1 = [
1.0 if opts.get('cull backfaces', False) else 0.0,
opts['unit scaling factor'],
opts.get('normal offset', 0.0) if symmetry_view is None else 0.05,
1.0 if opts.get('constrain offset', True) else 0.0,
]
view_settings2 = [
0.99 if symmetry_view is None else 1.0,
0.0,
0.0,
0.0,
]
self.set_shader_option('view_settings0', view_settings0)
self.set_shader_option('view_settings1', view_settings1)
self.set_shader_option('view_settings2', view_settings2)
self.set_shader_option('view_position', region_2d_to_origin_3d(rgn, r3d, (area.width/2, area.height/2)))
self.set_shader_option('clip', (spc.clip_start, spc.clip_end, 0.0, 0.0))
self.set_shader_option('screen_size', (area.width, area.height, 0.0, 0.0))
self.set_options(self.options_prefix, opts)
self._draw(1, 1, 1)
if opts['draw mirrored'] and (mx or my or mz):
self.set_options(f'{self.options_prefix} mirror', opts)
if mx: self._draw(-1, 1, 1)
if my: self._draw( 1, -1, 1)
if mz: self._draw( 1, 1, -1)
if mx and my: self._draw(-1, -1, 1)
if mx and mz: self._draw(-1, 1, -1)
if my and mz: self._draw( 1, -1, -1)
if mx and my and mz: self._draw(-1, -1, -1)
gpu.shader.unbind()
@@ -1,250 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import re
import copy
import math
import inspect
class IgnoreChange(Exception): pass
class BoundVar:
def __init__(self, value_str, *, on_change=None, frame_depth=1, frames_deep=1, f_globals=None, f_locals=None, callbacks=None, validators=None, disabled=False, pre_wrap=None, post_wrap=None, wrap=None):
assert type(value_str) is str, f'BoundVar: constructor needs value as string, but received {value_str} instead!'
if f_globals is None or f_locals is None:
frame = inspect.currentframe()
ff_globals, ff_locals = {}, {}
for i in range(frame_depth + frames_deep):
if i >= frame_depth:
ff_globals = frame.f_globals | ff_globals
ff_locals = frame.f_locals | ff_locals
frame = frame.f_back
self._f_globals = f_globals or ff_globals
self._f_locals = dict(f_locals or ff_locals)
else:
self._f_globals = f_globals
self._f_locals = dict(f_locals)
try:
exec(value_str, self._f_globals, self._f_locals)
except Exception as e:
print(f'Caught exception when trying to bind to variable')
print(f'exception: {e}')
print(f'globals: {self._f_globals}')
print(f'locals: {self._f_locals}')
assert False, f'BoundVar: value string ("{value_str}") must be a valid variable!'
self._f_locals.update({'boundvar_interface': self._boundvar_interface})
self._value_str = value_str
self._callbacks = callbacks or []
self._validators = validators or []
self._disabled = disabled
self._pre_wrap = wrap if wrap is not None else pre_wrap if pre_wrap is not None else ''
self._post_wrap = wrap if wrap is not None else post_wrap if post_wrap is not None else ''
if on_change: self.on_change(on_change)
def clone_with_overrides(self, **overrides):
# perform SHALLOW copy (shared attribs, such as _callbacks!) and override attribs as given
other = copy.copy(self)
for k, v in overiddes.iteritems():
try:
setattr(other, k, v)
except AttributeError:
setattr(other, f'_{k}', v)
return other
def _boundvar_interface(self, v): self._v = v
def _call_callbacks(self):
for cb in self._callbacks: cb()
def __str__(self): return str(self.value)
def get(self):
return self.value
def set(self, value):
self.value = value
@property
def disabled(self):
return self._disabled
@disabled.setter
def disabled(self, v):
self._disabled = bool(v)
self._call_callbacks()
def get_value(self):
exec(f'boundvar_interface({self._value_str})', self._f_globals, self._f_locals)
return self._v
def set_value(self, value):
try:
for validator in self._validators: value = validator(value)
except IgnoreChange:
return
if self.value == value: return
exec(f'{self._value_str} = {self._pre_wrap}{value}{self._post_wrap}', self._f_globals, self._f_locals)
self._call_callbacks()
@property
def value(self): return self.get_value()
@value.setter
def value(self, value): self.set_value(value)
@property
def value_as_str(self): return str(self)
@property
def is_bounded(self): return False
def on_change(self, fn): self._callbacks.append(fn)
def add_validator(self, fn): self._validators.append(fn)
class BoundString(BoundVar):
def __init__(self, value_str, *, frame_depth=2, **kwargs):
super().__init__(value_str, frame_depth=frame_depth, wrap='"', **kwargs)
class BoundStringToBool(BoundVar):
def __init__(self, value_str, true_str, *, frame_depth=2, **kwargs):
self._true_str = true_str
super().__init__(value_str, frame_depth=frame_depth, wrap='"', **kwargs)
@property
def value(self):
return self.get_value() == self._true_str
@value.setter
def value(self, v):
if bool(v): self.set_value(self._true_str)
@property
def checked(self):
return self.get_value() == self._true_str
@checked.setter
def checked(self, v):
# sets to a true str iff v is True
# assuming that some other BoundStringToBool will get set to True
if bool(v): self.value = self._true_str
class BoundBool(BoundVar):
def __init__(self, value_str, *, frame_depth=2, **kwargs):
super().__init__(value_str, frame_depth=frame_depth, **kwargs)
@property
def checked(self): return self.get_value()
@checked.setter
def checked(self,v): self.set_value(v)
class BoundInt(BoundVar):
def __init__(self, value_str, *, min_value=None, max_value=None, step_size=None, frame_depth=2, **kwargs):
super().__init__(value_str, frame_depth=frame_depth, **kwargs)
self._min_value = min_value
self._max_value = max_value
self._step_size = step_size or 0
self.add_validator(self.int_validator)
@property
def min_value(self): return self._min_value
@property
def max_value(self): return self._max_value
@property
def step_size(self): return self._step_size
@property
def is_bounded(self):
return self._min_value is not None and self._max_value is not None
@property
def bounded_ratio(self):
assert self.is_bounded, f'Cannot compute bounded_ratio of unbounded BoundInt'
return (self.value - self.min_value) / (self.max_value - self.min_value)
def int_validator(self, value):
try:
t = type(value)
if t is str: nv = int(re.sub(r'[^\d.-]', '', value))
elif t is int: nv = value
elif t is float: nv = int(value)
else: assert False, 'Unhandled type of value: %s (%s)' % (str(value), str(t))
if self._min_value is not None: nv = max(nv, self._min_value)
if self._max_value is not None: nv = min(nv, self._max_value)
if self._step_size and self._min_value is not None:
nv = math.floor((nv - self._min_value) / self._step_size) * self._step_size + self._min_value
return nv
except ValueError as e:
raise IgnoreChange()
except Exception:
# ignoring all exceptions?
raise IgnoreChange()
def add_delta(self, scale):
self.value += self.step_size * scale
class BoundFloat(BoundVar):
def __init__(self, value_str, *, min_value=None, max_value=None, step_size=None, frame_depth=2, format_str=None, **kwargs):
super().__init__(value_str, frame_depth=frame_depth, **kwargs)
self._min_value = min_value
self._max_value = max_value
self._step_size = step_size or 0
self.add_validator(self.float_validator)
self._format_str = '%0.5f' if format_str is None else format_str
def __str__(self):
return self._format_str % self.value
@property
def min_value(self): return self._min_value
@property
def max_value(self): return self._max_value
@property
def step_size(self): return self._step_size
@property
def is_bounded(self):
return self._min_value is not None and self._max_value is not None
@property
def bounded_ratio(self):
assert self.is_bounded, f'Cannot compute bounded_ratio of unbounded BoundFloat'
return (self.value - self.min_value) / (self.max_value - self.min_value)
def float_validator(self, value):
try:
t = type(value)
if t is str: nv = float(re.sub(r'[^\d.-]', '', value))
elif t is int: nv = float(value)
elif t is float: nv = value
else: assert False, 'Unhandled type of value: %s (%s)' % (str(value), str(t))
if self._min_value is not None: nv = max(nv, self._min_value)
if self._max_value is not None: nv = min(nv, self._max_value)
if self._step_size and self._min_value is not None:
nv = math.floor((nv - self._min_value) / self._step_size) * self._step_size + self._min_value
return nv
except ValueError as e:
raise IgnoreChange()
except Exception:
# ignoring all exceptions?
raise IgnoreChange()
def add_delta(self, scale):
self.value += self.step_size * scale
@@ -1,181 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
#####################################################################################
# below are various token converters
# dictionary to convert color name to color values, either (R,G,B) or (R,G,B,a)
# https://www.quackit.com/css/css_color_codes.cfm
colorname_to_color = {
'transparent': (0, 0, 0, 0),
# https://www.quackit.com/css/css_color_codes.cfm
'indianred': (205,92,92),
'lightcoral': (240,128,128),
'salmon': (250,128,114),
'darksalmon': (233,150,122),
'lightsalmon': (255,160,122),
'crimson': (220,20,60),
'red': (255,0,0),
'firebrick': (178,34,34),
'darkred': (139,0,0),
'pink': (255,192,203),
'lightpink': (255,182,193),
'hotpink': (255,105,180),
'deeppink': (255,20,147),
'mediumvioletred': (199,21,133),
'palevioletred': (219,112,147),
'coral': (255,127,80),
'tomato': (255,99,71),
'orangered': (255,69,0),
'darkorange': (255,140,0),
'orange': (255,165,0),
'gold': (255,215,0),
'yellow': (255,255,0),
'lightyellow': (255,255,224),
'lemonchiffon': (255,250,205),
'lightgoldenrodyellow': (250,250,210),
'papayawhip': (255,239,213),
'moccasin': (255,228,181),
'peachpuff': (255,218,185),
'palegoldenrod': (238,232,170),
'khaki': (240,230,140),
'darkkhaki': (189,183,107),
'lavender': (230,230,250),
'thistle': (216,191,216),
'plum': (221,160,221),
'violet': (238,130,238),
'orchid': (218,112,214),
'fuchsia': (255,0,255),
'magenta': (255,0,255),
'mediumorchid': (186,85,211),
'mediumpurple': (147,112,219),
'blueviolet': (138,43,226),
'darkviolet': (148,0,211),
'darkorchid': (153,50,204),
'darkmagenta': (139,0,139),
'purple': (128,0,128),
'rebeccapurple': (102,51,153),
'indigo': (75,0,130),
'mediumslateblue': (123,104,238),
'slateblue': (106,90,205),
'darkslateblue': (72,61,139),
'greenyellow': (173,255,47),
'chartreuse': (127,255,0),
'lawngreen': (124,252,0),
'lime': (0,255,0),
'limegreen': (50,205,50),
'palegreen': (152,251,152),
'lightgreen': (144,238,144),
'mediumspringgreen': (0,250,154),
'springgreen': (0,255,127),
'mediumseagreen': (60,179,113),
'seagreen': (46,139,87),
'forestgreen': (34,139,34),
'green': (0,128,0),
'darkgreen': (0,100,0),
'yellowgreen': (154,205,50),
'olivedrab': (107,142,35),
'olive': (128,128,0),
'darkolivegreen': (85,107,47),
'mediumaquamarine': (102,205,170),
'darkseagreen': (143,188,143),
'lightseagreen': (32,178,170),
'darkcyan': (0,139,139),
'teal': (0,128,128),
'aqua': (0,255,255),
'cyan': (0,255,255),
'lightcyan': (224,255,255),
'paleturquoise': (175,238,238),
'aquamarine': (127,255,212),
'turquoise': (64,224,208),
'mediumturquoise': (72,209,204),
'darkturquoise': (0,206,209),
'cadetblue': (95,158,160),
'steelblue': (70,130,180),
'lightsteelblue': (176,196,222),
'powderblue': (176,224,230),
'lightblue': (173,216,230),
'skyblue': (135,206,235),
'lightskyblue': (135,206,250),
'deepskyblue': (0,191,255),
'dodgerblue': (30,144,255),
'cornflowerblue': (100,149,237),
'royalblue': (65,105,225),
'blue': (0,0,255),
'mediumblue': (0,0,205),
'darkblue': (0,0,139),
'navy': (0,0,128),
'midnightblue': (25,25,112),
'cornsilk': (255,248,220),
'blanchedalmond': (255,235,205),
'bisque': (255,228,196),
'navajowhite': (255,222,173),
'wheat': (245,222,179),
'burlywood': (222,184,135),
'tan': (210,180,140),
'rosybrown': (188,143,143),
'sandybrown': (244,164,96),
'goldenrod': (218,165,32),
'darkgoldenrod': (184,134,11),
'peru': (205,133,63),
'chocolate': (210,105,30),
'saddlebrown': (139,69,19),
'sienna': (160,82,45),
'brown': (165,42,42),
'maroon': (128,0,0),
'white': (255,255,255),
'snow': (255,250,250),
'honeydew': (240,255,240),
'mintcream': (245,255,250),
'azure': (240,255,255),
'aliceblue': (240,248,255),
'ghostwhite': (248,248,255),
'whitesmoke': (245,245,245),
'seashell': (255,245,238),
'beige': (245,245,220),
'oldlace': (253,245,230),
'floralwhite': (255,250,240),
'ivory': (255,255,240),
'antiquewhite': (250,235,215),
'linen': (250,240,230),
'lavenderblush': (255,240,245),
'mistyrose': (255,228,225),
'gainsboro': (220,220,220),
'lightgray': (211,211,211),
'lightgrey': (211,211,211),
'silver': (192,192,192),
'darkgray': (169,169,169),
'darkgrey': (169,169,169),
'gray': (128,128,128),
'grey': (128,128,128),
'dimgray': (105,105,105),
'dimgrey': (105,105,105),
'lightslategray': (119,136,153),
'lightslategrey': (119,136,153),
'slategray': (112,128,144),
'slategrey': (112,128,144),
'darkslategray': (47,79,79),
'darkslategrey': (47,79,79),
'black': (0,0,0),
}
@@ -1,940 +0,0 @@
/*
https://en.wikipedia.org/wiki/Flat_design#/media/File:Flat_widgets.png
https://bulma.io/documentation/elements/button/
*/
* {
margin: 2px 2px;
padding: 4px 8px;
width: auto;
height: auto;
min-width: 0;
min-height: 0;
max-width: auto;
max-height: auto;
background-color: transparent;
border-width: 1px;
border-color: rgba(0, 0, 0, 0.75);
border-radius: 4px;
overflow: hidden;
font: normal normal 12pt sans-serif;
text-align: left;
}
body {
position: fixed;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border: 4px rgba(0,0,0,0.25);
border-radius: 8px;
cursor: default;
overflow: hidden;
}
text::text {
display: inline;
background: transparent;
margin: 0px;
border: 0px;
padding: 0px;
}
button {
white-space: normal;
cursor: default;
display: inline;
border-width: 0px;
border-radius: 4px;
border-color: white rgb(96,96,96) rgb(32,32,32) rgb(224,224,224);
background: rgba(160,160,160, 0.50);
color: black;
}
button:focus {
/*background: yellow;*/
/*background: lightcyan;*/
background: rgba(160,160,160, 1.00);
}
button:active {
/*background: rgb(192,128,128);*/
background: hsla(210, 100%, 45%, 1.0);
}
button:hover {
background: rgba(160, 160, 160, 1.00); /* hsla(200, 100%, 62.5%, 1.0); /* rgb(64,192,255); */
}
button:active:hover {
background: hsla(210, 60%, 35%, 1.0);
}
button:disabled {
background-color: rgb(128,128,128);
color: rgb(192,192,192);
/*border-width: 1px;*/
border-color: rgb(96,96,96);
cursor: default;
}
p {
display: block;
width: 100%;
/*margin: 2px 0px;*/
padding: 2px;
border-width: 0px;
color: white;
}
p span {
margin: 0;
padding: 0;
border-width: 0;
}
code {
font-family: monospace;
white-space: pre;
}
pre {
width: 100%;
display: block;
font-family: monospace;
background-color: rgba(128, 128, 128, 0.5);
font-size: 10pt;
white-space: pre-wrap;
}
textarea {
display: block;
width: 100%;
/*margin: 2px 0px;*/
padding: 4px;
background-color: rgba(255,255,255,0.9);
border: 1px black;
border-radius: 4px;
color: black;
cursor: text;
}
div {
background-color: rgba(0,0,0,0.25);
display: block;
width: 100%;
margin: 2px 0px;
padding: 2px;
}
br {
display: block;
width: 0px;
height: 0px;
margin: 0px;
padding: 0px;
border-width: 0px;
}
img {
/*max-width: 100%;*/
object-fit: contain;
border-width: 1px;
border-color: rgba(0,0,0,0.25);
background-color: hsla(200, 100%, 62.5%, 0.0); /* rgba(255,0,0,0); */
padding: 2px;
}
span {
color: white;
border-width: 0px;
}
/* make sure we handle cases correctly! */
input {
background: pink;
}
ul {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
}
ul > li {
position: relative;
left: 0px;
top: 0px;
margin: 0px;
border: 0px;
padding: 0px;
padding: 0px 0px 0px 12px;
display: block;
overflow: visible;
}
ul > li::marker {
position: absolute;
left: -8px;
margin: 5px 5px 0px 5px;
border: 0px;
padding: 0px;
width: 15px;
height: 10px;
background-image: url('radio.png');
}
ol {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
}
ol > li {
position: relative;
left: 0px;
top: 0px;
margin: 0px;
border: 0px;
padding: 0px;
padding: 0px 0px 0px 12px;
display: block;
overflow: visible;
}
ol > li::marker {
color: white;
position: absolute;
/*left: -8px;*/
left: 0px;
/*margin: 5px 5px 0px 5px;*/
margin: 0px;
border: 0px;
padding: 0px;
width: 15px;
/*height: 10px;*/
/*background-image: url('radio.png');*/
}
dialog {
position: fixed;
border-radius: 4px;
border: 1px black;
background: rgba(32, 32, 32, 0.75);
/*overflow-x: scroll;*/
overflow-y: scroll;
color: white;
width: 500px;
/*max-width: 750px;*/
min-width: 200px;
display: block;
}
dialog.framed {
border: 2px rgba(0,0,0,0.75);
border-radius: 5px;
overflow: hidden;
padding: 0px;
margin: 5px;
}
dialog div.contents {
overflow-y: scroll;
}
div.dialog-header {
background: hsla(200, 0%, 25%, 0.75); /* hsla(0, 0%, 25%, 0.75); */
margin: 0px;
padding: 2px;
border: 1px rgba(0,0,0,0.25) rgba(0,0,0,0.25) rgba(0,0,0,1) rgba(0,0,0,0.25);
border-radius: 0px;
}
dialog.framed.moveable div.dialog-header {
cursor: grab;
}
dialog.framed.moveable div.dialog-header:hover {
background-color: hsla(200, 25%, 40%, 0.75); /* hsla(0,0%,40%,0.75);*/
}
dialog.framed.moveable div.dialog-header:active {
background-color: hsla(200, 100%, 60%, 0.75); /*hsla(0,0%,40%,0.5);*/
}
span.dialog-title {
margin: 0px;
border: 0px white;
padding: 2px;
color: white;
/*font-weight: bold;*/
white-space: pre;
cursor: grab;
text-shadow: 2px 2px rgba(0,0,0,0.25);
}
button.dialog-close {
margin: 0px;
padding: 2px;
border: 0px;
display: inline;
width: 16px;
height: 16px;
background: url('close.png');
}
dialog.framed > div.inside {
margin: 0px;
border-width: 1px;
border-radius: 0px;
border-color: rgba(0,0,0,1.0) rgba(0,0,0,0.25) rgba(0,0,0,0.25) rgba(0,0,0,0.25);
padding: 5px 2px 2px 2px;
}
div.dialog-footer {
position: absolute;
left: auto;
right: 50px;
top: -200px;
width: 100%;
/*bottom: 0px;*/
background: hsla(200, 0%, 25%, 0.75); /* hsla(0, 0%, 25%, 0.75); */
margin: 0px;
padding: 2px;
border: 1px rgba(0,0,0,1) rgba(0,0,0,0.25) rgba(0,0,0,0.25) rgba(0,0,0,0.25);
border-radius: 0px;
}
div.dialog-footer > * {
margin: 0px;
border: 0px white;
padding: 2px;
}
/*******************/
/* TABLES */
table {
width: 100%;
display: table;
background: rgba(0,0,0,0.2);
border: 1px rgba(0,0,0,1);
margin: 0px 10px;
padding: 4px;
}
tr {
width: 100%;
display: table-row;
margin: 0px 0px;
border: 0px;
padding: 0px 2px;
}
th {
display: table-cell;
margin: 0px;
border: 0px;
padding: 2px;
}
td {
display: table-cell;
margin: 0px;
border: 0px;
padding: 2px;
}
/*******************/
/* MARKDOWN */
article.mdown {
margin: 2px;
border: 1px rgba(0,0,0,0.5);
padding: 4px 4px 4px 4px;
/*padding: 4px 4px 16px 4px;*/
background: rgba(48,48,48,0.75);
}
article.mdown div {
margin: 0;
padding: 0;
border: 0;
}
article.mdown span {
margin: 0;
padding: 0;
border: 0;
}
article.mdown h1 {
width: 100%;
margin: 0px 4px 4px 4px;
padding: 4px 4px 4px 12px;
border: 0px;
font-size: 24;
font-weight: bold;
text-shadow: 2px 2px rgba(0,0,0,0.5);
}
article.mdown h2 {
width: 100%;
margin: 8px 4px 4px 4px;
padding: 4px 4px 4px 12px;
border: 1px transparent;
border-bottom-color: rgba(255, 255, 255, 0.25);
border-radius: 0px;
font-size: 18;
font-weight: bold;
text-shadow: 2px 2px rgba(0,0,0,0.5);
}
article.mdown h3 {
width: 100%;
margin: 8px 16px 4px 16px;
padding: 4px 4px 4px 12px;
border: 1px transparent;
border-bottom-color: rgba(255, 255, 255, 0.125);
border-radius: 0px;
font-size: 15;
font-weight: bold;
text-shadow: 2px 2px rgba(0,0,0,0.5);
}
article.mdown img {
display: block;
width: 100%;
border: 1px rgba(0, 0, 0, 0.50);
border-radius: 4px;
}
article.mdown p { }
article.mdown i {
margin: 0px;
padding: 0px;
border: 0px;
font-style: italic;
}
article.mdown b {
margin: 0px;
padding: 0px;
border: 0px;
font-weight: bold;
}
article.mdown pre {
font-family: monospace;
white-space: pre;
margin: 0px;
padding: 0px 4px;
background-color: rgba(255, 255, 255, 0.25);
}
article.mdown code {
font-family: monospace;
white-space: pre;
margin: 0px;
padding: 0px 4px;
background-color: rgba(255, 255, 255, 0.25);
}
/*article.mdown ul {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
}
article.mdown ul > li {
/*margin: 8px 0px;* /
margin: 0px;
border: 0px;
padding: 0px;
padding: 0px 0px 0px 8px;
display: block;
}
article.mdown ul > li > img.dot {
display: inline;
margin: 5px 10px 0px 5px;
border: 0px;
padding: 0px;
width: 20px;
height: 10px;
}
article.mdown ul > li > span.text {
margin: 0px;
border: 0px;
padding: 0px;
display: inline;
}*/
/*article.mdown ol {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
}
article.mdown ol > li {
/*margin: 8px 0px;* /
margin: 0px;
border: 0px;
padding: 0px;
padding: 0px 0px 0px 8px;
display: block;
}
article.mdown ol > li > span.number {
display: inline;
margin: 0px;
border: 0px;
padding: 0px;
width: 20px;
/*height: 10px;* /
}
article.mdown ol > li > span.text {
margin: 0px 0px 0px 8px;
border: 0px;
padding: 0px;
display: inline;
}
*/
/* background-color: hsla(200, 25%, 25%, 0.75); */
/* background-color: hsla(200, 25%, 40%, 0.75); */
/* background-color: hsla(200, 25%, 60%, 0.75); */
article.mdown a {
padding: 0px -1px 0px 0px;
margin: 0px;
background-color: transparent; /* hsla(200, 25%, 25%, 0.75); */
border: 1px transparent; /* hsla(200, 25%, 25%, 0.75); */
border-radius: 0px;
border-bottom-color: rgba(255,255,255,0.5);
cursor: pointer;
}
article.mdown a:hover {
background-color: hsla(200, 25%, 40%, 0.75);
border: 1px hsla(200, 25%, 40%, 0.75);
border-bottom-color: rgba(255,255,255,0.5);
}
article.mdown img.inline {
display: inline;
border: 0px;
}
/**********************/
/* CHECKBOX INPUT */
input[type="checkbox"] {
background-color: transparent;
border-width: 0px;
padding: 0px;
}
input[type="checkbox"] > img.checkbox {
display: inline;
margin: 0;
padding: 4px;
margin-right: 5px;
border-width: 0px;
width: 29px;
height: 24px;
background-color: rgba(160, 160, 160, 0.50); /* hsla(200, 0%, 62.5%, 1.0);*/
background-image: none;
}
input[type="checkbox"]:hover > img.checkbox {
background-color: rgba(160, 160, 160, 1.00); /* hsla(200, 0%, 75%, 1.0); */
}
input[type="checkbox"]:checked > img.checkbox {
background-color: hsla(200, 100%, 62.5%, 1.0);
background-image: url('checkmark.png');
}
input[type="checkbox"]:active > img.checkbox {
background-color: hsla(200, 100%, 75%, 1.0);
}
input[type="checkbox"] > label {
color: rgba(255, 255, 255, 0.50);
margin: 0px;
padding: 0px;
padding-top: 3px;
padding-right: 10px;
border-width: 0px;
}
input[type="checkbox"]:hover > label {
color: rgba(255, 255, 255, 1.00);
}
input[type="checkbox"]:checked > label {
color: rgba(255, 255, 255, 1.00);
}
/*******************/
/* RADIO INPUT */
input[type="radio"] {
background-color: transparent;
border-width: 0px;
padding: 0px;
}
input[type="radio"] > img.radio {
margin: 0;
padding: 4px;
margin-right: 5px;
border: 0px;
border-radius: 12px;
width: 29px;
height: 24px;
background-color: rgba(160, 160, 160, 0.50); /* hsla(200, 0%, 62.5%, 1.0);*/
background-image: none;
}
input[type="radio"]:hover > img.radio {
background-color: rgba(160, 160, 160, 1.00); /* hsla(200, 0%, 75%, 1.0); */
}
input[type="radio"]:active > img.radio {
background-color: hsla(200, 100%, 75%, 1.0);
}
input[type="radio"]:checked > img.radio {
background: hsla(200, 100%, 62.5%, 1.0) url('radio.png');
}
input[type="radio"] > label {
color: rgba(255, 255, 255, 0.50);
margin: 0px;
padding: 0px;
padding-top: 3px;
padding-right: 10px;
border-width: 0px;
}
input[type="radio"]:hover > label {
color: rgba(255, 255, 255, 1.00);
}
input[type="radio"]:checked > label {
color: rgba(255, 255, 255, 1.00);
}
/**************************/
/* COLLAPSIBLE COLLECTION */
/*div.collapsible > input.header {
display: block;
width: 100%;
}
div.collapsible > input.header > img {
background: transparent url('collapse_open.png');
}
div.collapsible > input.header:checked > img {
background: transparent url('collapse_close.png');
}
div.collapsible > div.inside {
display: block;
margin-top: 2px;
margin-left: 16px;
}
div.collapsible > div.inside.collapsed {
display: none;
}*/
details > div.header {
display: block;
width: 100%;
}
details > div.header > img.marker {
background: transparent url('collapse_close.png');
}
details[open] > div.header > img.marker {
background: transparent url('collapse_open.png');
}
details > div.inside {
display: none;
}
details[open] > div.inside {
display: block;
margin-top: 2px;
margin-left: 16px;
}
/**********************/
/* TEXT INPUT */
/*
div.inputtext-container
input.inputtext-input
span.inputtext-cursor
*/
/*.inputtext-container {
margin: 0px;
/*position: relative;* /
left: 0px;
top: 0px;
width: 100%;
min-height: 28px;
padding: 0px;
display: block;
background: rgba(160,160,160, 0.50);
/*background-color: rgba(255,255,255,0.5);* /
border-width: 1px;
border-radius: 4px;
border-color: black;
}
*.inputtext-container:hover {
background-color: rgba(160,160,160,1.00);
}*/
/**.inputtext-container > */
*.inputtext-input {
position: relative; /* necessary for cursor! */
left: 0px;
top: 0px;
background-color: transparent;
white-space: pre;
display: block;
width: 100%;
min-height: 26px;
margin: 0px;
padding: 3px;
border-width: 2px;
border-color: transparent;
color: black;
overflow-x: scroll;
cursor: text;
}
/**.inputtext-container > */
*.inputtext-input:focus {
background-color: rgba(255, 255, 255, 1.0);
border-color: hsla(200, 100%, 62.5%, 1.0);
}
/**.inputtext-cursor {
position: absolute;
margin: 0px;
padding: 0px;
border-width: 0px;
left: 0px;
top: 0px;
display: none;
color: hsla(200, 100%, 12.5%, 1.0); /* l=62.5% * /
}*/
/*input[type="text"]:focus *.inputtext-cursor {
display: span;
background: pink;
}*/
input[type="text"] {
position: relative; /* necessary for cursor! */
left: 0px;
top: 0px;
background-color: transparent;
white-space: pre;
display: block;
width: 100%;
min-height: 26px;
margin: 0px;
padding: 3px;
border: 2px transparent;
color: black;
overflow-x: scroll;
cursor: text;
}
input[type="text"]:focus {
background-color: rgba(255, 255, 255, 1.0);
border-color: hsla(200, 100%, 62.5%, 1.0);
}
input[type="text"]::marker {
position: absolute;
margin: -1px 0px 0px 0px;
border: 0px;
padding: 0px;
background: transparent;
color: white;
left: 0px;
top: 0px;
content: "|";
}
input[type="number"] {
position: relative; /* necessary for cursor! */
left: 0px;
top: 0px;
background-color: transparent;
white-space: pre;
display: block;
width: 100%;
min-height: 26px;
margin: 0px;
padding: 3px;
border: 2px transparent;
color: black;
overflow-x: scroll;
cursor: text;
}
input[type="number"]:focus {
background-color: rgba(255, 255, 255, 1.0);
border-color: hsla(200, 100%, 62.5%, 1.0);
}
input[type="number"]::marker {
position: absolute;
margin: -1px 0px 0px 0px;
border: 0px;
padding: 0px;
background: transparent;
color: white;
left: 0px;
top: 0px;
content: "|";
}
/***********************/
/* LABELED TEXT INPUT */
/*
div.labeledinputtext-container
div.labeledinputtext-label-container
label.labeledinputtext-label
div.labeledinputtext-input-container
div.inputtext-container
input.inputtext-input
span.inputtext-cursor
*/
*.labeledinputtext-container {
margin: 2px;
border: 0px;
padding: 0px;
display: block;
width: 100%;
background: transparent;
}
*.labeledinputtext-container > *.labeledinputtext-label-container {
margin: 0px;
border: 0px;
padding: 4px 4px 0px 0px;
display: inline;
width: 50%;
background: transparent;
}
*.labeledinputtext-container > *.labeledinputtext-label-container > *.labeledinputtext-label {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
width: 100%;
background: transparent;
}
*.labeledinputtext-container > *.labeledinputtext-input-container {
margin: 0px;
border: 0px;
padding: 0px;
display: inline;
width: 50%;
}
*.labeledinputtext-container > *.labeledinputtext-input-container > *.inputtext-container {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
width: 100%;
/*max-height: 22px;*/
height: 26px;
}
*.labeledinputtext-container > *.labeledinputtext-input-container > *.inputtext-container > *.inputtext-input {
margin: 0px;
white-space: pre;
}
/*************************/
/* INPUT RANGE */
input[type="range"] {
position: relative;
display: block;
margin: 0px 0px 0px 0px;
padding: 0px 8px 0px 0px;
border: 0px;
width: 100%;
height: 22px;
background-color: transparent;
}
input[type="range"] > * {
margin: 0px;
padding: 0px;
border-radius: 4px;
}
input[type="range"] > *.inputrange-left {
display: inline;
position: absolute;
top: -4px;
height: 8px;
border: 1px white;
background-color: rgba(0, 0, 255, 1);
}
input[type="range"] > *.inputrange-right {
display: inline;
position: absolute;
top: -4px;
height: 8px;
border: 1px white;
background-color: rgba(255, 0, 255, 1);
}
input[type="range"] > *.inputrange-handle {
display: inline;
position: absolute;
left: 0px;
top: 0px;
width: 16px;
height: 16px;
border: 1px black;
background-color: rgba(128, 128, 128, 1);
}
input[type="range"]:hover > *.inputrange-handle {
background-color: rgba(192, 192, 192, 1);
}
input[type="range"]:active > *.inputrange-handle {
background-color: rgba(255, 255, 255, 1);
}
dialog.tooltip {
z-index: 100000;
position: fixed;
/*display: block;*/
border: 1px black;
background: hsla(200, 25%, 25%, 0.95); /*rgba(32,32,32,0.8);*/
color: white;
margin: 2px;
padding: 4px;
width: auto;
min-width: 0px;
max-width: 300px;
}
@@ -1,260 +0,0 @@
'''
Copyright (C) 2014 Plasmasolutions
software@plasmasolutions.de
Created by Thomas Beck
Donated to CGCookie and the world
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 <http://www.gnu.org/licenses/>.
'''
'''
Note: not all of the following code was provided by Plasmasolutions
TODO: split into separate files?
'''
import os
import sys
import time
import inspect
import itertools
import linecache
import traceback
from math import floor
from hashlib import md5
from datetime import datetime
from functools import wraps
from .blender import show_blender_popup
from .functools import find_fns
from .globals import Globals
from .hasher import Hasher
class Debugger:
_error_level = 1
_exception_count = 0
def __init__(self):
pass
@staticmethod
def set_error_level(l):
Debugger._error_level = max(0, min(5, int(l)))
@staticmethod
def get_error_level():
return Debugger._error_level
@staticmethod
def dprint(*objects, sep=' ', end='\n', file=sys.stdout, flush=True, l=2):
if Debugger._error_level < l: return
sobjects = sep.join(str(o) for o in objects)
print(
f'DEBUG({l}): {sobjects}',
end=end, file=file, flush=flush
)
@staticmethod
def dcallstack(l=2):
''' print out the calling stack, skipping the first (call to dcallstack) '''
Debugger.dprint('Call Stack Dump:', l=l)
for i, entry in enumerate(inspect.stack()):
if i > 0:
Debugger.dprint(' %s' % str(entry), l=l)
@staticmethod
def call_stack():
return traceback.format_stack()
# http://stackoverflow.com/questions/14519177/python-exception-handling-line-number
@staticmethod
def get_exception_info_and_hash():
'''
this function is a duplicate of the one above, but this will attempt
to create a hash to make searching for duplicate bugs on github easier (?)
'''
exc_type, exc_obj, tb = sys.exc_info()
pathabs, pathdir = os.path.abspath, os.path.dirname
pathjoin, pathsplit = os.path.join, os.path.split
base_path = pathabs(pathjoin(pathdir(__file__), '..'))
hasher = Hasher()
errormsg = ['EXCEPTION (%s): %s' % (exc_type, exc_obj)]
hasher.add(errormsg[0])
# errormsg += ['Base: %s' % base_path]
etb = traceback.extract_tb(tb)
pfilename = None
for i,entry in enumerate(reversed(etb)):
filename,lineno,funcname,line = entry
if pfilename is None:
# only hash in details of where the exception occurred
hasher.add(os.path.split(filename)[1])
# hasher.add(lineno)
hasher.add(funcname)
hasher.add(line.strip())
if filename != pfilename:
pfilename = filename
if filename.startswith(base_path):
filename = '.../%s' % filename[len(base_path)+1:]
errormsg += [' %s' % (filename, )]
errormsg += ['%03d %04d:%s() %s' % (i, lineno, funcname, line.strip())]
return ('\n'.join(errormsg), hasher.get_hash())
@staticmethod
def print_exception():
Debugger._exception_count += 1
errormsg, errorhash = Debugger.get_exception_info_and_hash()
message = []
message += ['Exception Info']
message += ['- Time: %s' % datetime.today().isoformat(' ')]
message += ['- Count: %d' % Debugger._exception_count]
message += ['- Hash: %s' % str(errorhash)]
message += ['- Info:']
message += [' - %s' % s for s in errormsg.splitlines()]
message = '\n'.join(message)
print('%s\n%s\n%s' % ('_' * 100, message, '^' * 100))
logger = Globals.logger
if logger: logger.add(message) # write error to log text object
# if Debugger._exception_count < 10:
# show_blender_popup(
# message,
# title='Exception Info',
# icon='ERROR',
# wrap=240
# )
return message
# @staticmethod
# def print_exception2():
# exc_type, exc_value, exc_traceback = sys.exc_info()
# print("*** print_tb:")
# traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
# print("*** print_exception:")
# traceback.print_exception(exc_type, exc_value, exc_traceback,
# limit=2, file=sys.stdout)
# print("*** print_exc:")
# traceback.print_exc()
# print("*** format_exc, first and last line:")
# formatted_lines = traceback.format_exc().splitlines()
# print(formatted_lines[0])
# print(formatted_lines[-1])
# print("*** format_exception:")
# print(repr(traceback.format_exception(exc_type, exc_value,exc_traceback)))
# print("*** extract_tb:")
# print(repr(traceback.extract_tb(exc_traceback)))
# print("*** format_tb:")
# print(repr(traceback.format_tb(exc_traceback)))
# if exc_traceback:
# print("*** tb_lineno:", exc_traceback.tb_lineno)
start_time = time.time()
last_time = time.time()
@staticmethod
def tprint(*args):
t = time.time()
td = t - Debugger.last_time
lbar = min(25, floor(td*20))
bar = '%s%s' % ('X' * lbar, '_' * (25-lbar))
print(bar, '%8.4f' % td, *args)
sys.stdout.flush()
Debugger.last_time = t
class ExceptionHandler:
_universal = []
@staticmethod
def on_exception(fn):
fn._exceptionhandler_on_exception = True
return fn
def __init__(self, obj=None, *, universal=False):
# print(f'ExceptionHandler.__init__({self})')
self._single = []
self._um = []
self._universal_only = universal
self.collect_callbacks(obj)
def __del__(self):
# print(f'ExceptionHandler.__del__({self})')
for fn in getattr(self, '_um', []):
self.remove_universal_callback(fn)
def collect_callbacks(self, obj):
if not obj: return
for (_, fn) in find_fns(obj, '_exceptionhandler_on_exception'):
self.add_callback(fn)
@staticmethod
def add_universal_callback(fn):
ExceptionHandler._universal += [fn]
@staticmethod
def remove_universal_callback(fn):
if fn not in ExceptionHandler._universal: return
ExceptionHandler._universal.remove(fn)
@staticmethod
def clear_universal_callbacks():
ExceptionHandler._universal = []
def add_callback(self, fn, universal=None):
# print(f'ExceptionHandler.add_callback({self}, {fn}, {universal})')
if getattr(fn, '_exceptionhandler_collected', False): return
fn._exceptionhandler_collected = True
if universal is None and self._universal_only: universal = True
if universal:
self._universal += [fn]
self._um += [fn]
else:
self._single += [fn]
def wrap(self, def_val, only=Exception):
def wrapper(fn):
def wrapped(*args, **kwargs):
ret = def_val
try:
ret = fn(*args, **kwargs)
except only as e:
self.handle_exception(e)
return ret
return wrapped
return wrapper
def handle_exception(self, e):
# print(f'ExceptionHandler: calling back these fns')
# for fn in itertools.chain(self._universal, self._single):
# print(f' {fn}')
for fn in itertools.chain(self._universal, self._single):
try:
fn(e)
except Exception as e2:
print(f'ExceptionHandler: Caught exception while calling back exception callbacks: {fn.__name__}')
print(f' original: {e}')
print(f' additional: {e2}')
debugger.print_exception()
debugger = Debugger()
dprint = debugger.dprint
tprint = debugger.tprint
exceptionhandler = ExceptionHandler(universal=True)
Globals.set(debugger)
Globals.dprint = dprint
Globals.exceptionhandler = exceptionhandler
@@ -1,419 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import os
import re
import json
import time
import inspect
from functools import wraps
import bpy
def run(*args, **kwargs):
if len(args) == 1 and not kwargs and inspect.isfunction(args[0]):
# call right away
return args[0]()
def wrapper(fn):
return fn(*args, **kwargs)
return wrapper
debug_run_test_calls = False
def debug_test_call(*args, **kwargs):
def wrapper(fn):
if debug_run_test_calls:
ret = str(fn(*args,*kwargs))
print('TEST: %s()' % fn.__name__)
if args:
print(' arg:', args)
if kwargs:
print(' kwa:', kwargs)
print(' ret:', ret)
return fn
return wrapper
def ignore_exceptions(*exceptions, default=None, warn=False):
def wrap(fn):
@wraps(fn)
def run_with_ignore_exceptions(*args, **kwargs):
ret = default
try:
ret = fn(*args, **kwargs)
except Exception as e:
if not any(isinstance(e, ex) for ex in exceptions):
# this exception should not be ignored
raise e
# ignoring thrown exception!
if warn:
print(f'Addon Common: ignoring exception')
print(f' Function: {fn.__name__}')
print(f' Exception: {e}')
return ret
return run_with_ignore_exceptions
return wrap
def stats_wrapper(fn):
return fn
if not hasattr(stats_report, 'stats'):
stats_report.stats = dict()
frame = inspect.currentframe().f_back
f_locals = frame.f_locals
filename = os.path.basename(frame.f_code.co_filename)
clsname = f_locals['__qualname__'] if '__qualname__' in f_locals else ''
linenum = frame.f_lineno
fnname = fn.__name__
key = '%s%s (%s:%d)' % (
clsname + ('.' if clsname else ''),
fnname, filename, linenum
)
stats = stats_report.stats
stats[key] = {
'filename': filename,
'clsname': clsname,
'linenum': linenum,
'fileline': '%s:%d' % (filename, linenum),
'fnname': fnname,
'count': 0,
'total time': 0,
'average time': 0,
}
def wrapped(*args, **kwargs):
time_beg = time.time()
ret = fn(*args, **kwargs)
time_end = time.time()
time_delta = time_end - time_beg
d = stats[key]
d['count'] += 1
d['total time'] += time_delta
d['average time'] = d['total time'] / d['count']
return ret
return wrapped
def stats_report():
return
stats = stats_report.stats if hasattr(stats_report, 'stats') else dict()
l = max(len(k) for k in stats)
def fmt(s):
return s + ' ' * (l - len(s))
print()
print('Call Statistics Report')
cols = [
('class', 'clsname', '%s'),
('func', 'fnname', '%s'),
('location', 'fileline', '%s'),
# ('line','linenum','% 10d'),
('count', 'count', '% 8d'),
('total (sec)', 'total time', '% 10.4f'),
('avg (sec)', 'average time', '% 10.6f'),
]
data = [stats[k] for k in sorted(stats)]
data = [[h] + [f % row[c] for row in data] for (h, c, f) in cols]
colwidths = [max(len(d) for d in col) for col in data]
totwidth = sum(colwidths) + len(colwidths) - 1
def rpad(s, l):
return '%s%s' % (s, ' ' * (l - len(s)))
def printrow(i_row):
row = [col[i_row] for col in data]
print(' '.join(rpad(d, w) for (d, w) in zip(row, colwidths)))
printrow(0)
print('-' * totwidth)
for i in range(1, len(data[0])):
printrow(i)
def add_cache(attr, default):
def wrapper(fn):
setattr(fn, attr, default)
return fn
return wrapper
class LimitRecursion:
def __init__(self, count, def_ret):
self.count = count
self.def_ret = def_ret
self.calls = 0
def __call__(self, fn):
def wrapped(*args, **kwargs):
ret = self.def_ret
if self.calls < self.count:
try:
self.calls += 1
ret = fn(*args, **kwargs)
finally:
self.calls -= 1
return ret
return wrapped
@add_cache('data', {'nested':0, 'last':None})
def timed_call(label):
def wrapper(fn):
def wrapped(*args, **kwargs):
data = timed_call.data
if data['last']: print(data['last'])
data['last'] = f'''{" " * data['nested']}Timing {label}'''
data['nested'] += 1
time_beg = time.time()
ret = fn(*args, **kwargs)
time_end = time.time()
time_delta = time_end - time_beg
if data['last']:
print(f'''{data['last']}: {time_delta:0.4f}s''')
data['last'] = None
else:
print(f'''{" " * data['nested']}{time_delta:0.4f}s''')
data['nested'] -= 1
return ret
return wrapped
return wrapper
# corrected bug in previous version of blender_version fn wrapper
# https://github.com/CGCookie/retopoflow/commit/135746c7b4ee0052ad0c1842084b9ab983726b33#diff-d4260a97dcac93f76328dfaeb5c87688
def blender_version_wrapper(op, ver):
self = blender_version_wrapper
if not hasattr(self, 'fns'):
major, minor, rev = bpy.app.version
self.blenderver = '%d.%02d' % (major, minor)
self.fns = fns = {}
self.ops = {
'<': lambda v: self.blenderver < v,
'>': lambda v: self.blenderver > v,
'<=': lambda v: self.blenderver <= v,
'==': lambda v: self.blenderver == v,
'>=': lambda v: self.blenderver >= v,
'!=': lambda v: self.blenderver != v,
}
update_fn = self.ops[op](ver)
def wrapit(fn):
nonlocal self, update_fn
fn_name = fn.__name__
fns = self.fns
error_msg = "Could not find appropriate function named %s for version Blender %s" % (fn_name, self.blenderver)
if update_fn: fns[fn_name] = fn
def callit(*args, **kwargs):
nonlocal fns, fn_name, error_msg
fn = fns.get(fn_name, None)
assert fn, error_msg
ret = fn(*args, **kwargs)
return ret
return callit
return wrapit
def only_in_blender_version(*args, ignore_others=False, ignore_return=None):
self = only_in_blender_version
if not hasattr(self, 'fns'):
major, minor, rev = bpy.app.version
self.blenderver = f'{major}.{minor:02d}'
self.fns = {}
self.ignores = {}
self.ops = {
'<': lambda v: self.blenderver < v,
'>': lambda v: self.blenderver > v,
'<=': lambda v: self.blenderver <= v,
'==': lambda v: self.blenderver == v,
'>=': lambda v: self.blenderver >= v,
'!=': lambda v: self.blenderver != v,
}
self.re_blender_version = re.compile(r'^(?P<comparison><|<=|==|!=|>=|>) *(?P<version>\d\.\d+)$')
def ver(mver):
major, minor = map(int, mver.split('.'))
return f'{major}.{minor:02d}'
matches = [self.re_blender_version.match(arg) for arg in args]
assert all(match is not None for match in matches), f'At least one arg did not match version comparison: {args}'
results = [self.ops[match.group('comparison')](ver(match.group('version'))) for match in matches]
version_matches = all(results)
def wrapit(fn):
fn_name = fn.__name__
if version_matches:
assert fn_name not in self.fns, f'Multiple functions {fn_name} match the Blender version {self.blenderver}'
self.fns[fn_name] = fn
if ignore_others and fn_name not in self.ignores:
self.ignores[fn_name] = ignore_return
@wraps(fn)
def callit(*args, **kwargs):
fn = self.fns.get(fn_name, None)
if fn_name not in self.ignores:
assert fn, f'Could not find appropriate function named {fn_name} for version Blender version {self.blenderver}'
elif fn is None:
return self.ignores[fn_name]
return fn(*args, **kwargs)
return callit
return wrapit
def warn_once(warning):
def wrapper(fn):
nonlocal warning
@wraps(fn)
def wrapped(*args, **kwargs):
nonlocal warning
if warning:
print(warning)
warning = None
return fn(*args, **kwargs)
return wrapped
return wrapper
class PersistentOptions:
class WrappedDict:
def __init__(self, cls, filename, version, defaults, update_external):
self._dirty = False
self._last_save = time.time()
self._write_delay = 2.0
self._defaults = defaults
self._update_external = update_external
self._defaults['persistent options version'] = version
self._dict = {}
if filename:
src = inspect.getsourcefile(cls)
path = os.path.split(os.path.abspath(src))[0]
self._fndb = os.path.join(path, filename)
else:
self._fndb = None
self.read()
if self._dict.get('persistent options version', None) != version:
self.reset()
self.update_external()
def update_external(self):
upd = self._update_external
if upd:
upd()
def dirty(self):
self._dirty = True
self.update_external()
def clean(self, force=False):
if not force:
if not self._dirty:
return
if time.time() < self._last_save + self._write_delay:
return
if self._fndb:
json.dump(self._dict, open(self._fndb, 'wt'), indent=2, sort_keys=True)
self._dirty = False
self._last_save = time.time()
def read(self):
self._dict = {}
if self._fndb and os.path.exists(self._fndb):
try:
self._dict = json.load(open(self._fndb, 'rt'))
except Exception as e:
print('Exception caught while trying to read options from "%s"' % self._fndb)
print(str(e))
for k in set(self._dict.keys()) - set(self._defaults.keys()):
print('Deleting extraneous key "%s" from options' % k)
del self._dict[k]
self.update_external()
self._dirty = False
def keys(self):
return self._defaults.keys()
def reset(self):
keys = list(self._dict.keys())
for k in keys:
del self._dict[k]
self._dict['persistent options version'] = self['persistent options version']
self.dirty()
self.clean()
def __getitem__(self, key):
return self._dict[key] if key in self._dict else self._defaults[key]
def __setitem__(self, key, val):
assert key in self._defaults, 'Attempting to write "%s":"%s" to options, but key does not exist in defaults' % (str(key), str(val))
if self[key] == val: return
self._dict[key] = val
self.dirty()
self.clean()
def gettersetter(self, key, fn_get_wrap=None, fn_set_wrap=None):
if not fn_get_wrap: fn_get_wrap = lambda v: v
if not fn_set_wrap: fn_set_wrap = lambda v: v
oself = self
class GetSet:
def get(self):
return fn_get_wrap(oself[key])
def set(self, v):
v = fn_set_wrap(v)
if oself[key] != v:
oself[key] = v
return GetSet()
def __init__(self, filename=None, version=None):
self._filename = filename
self._version = version
self._db = None
def __call__(self, cls):
upd = getattr(cls, 'update', None)
if upd:
u = upd
def wrap():
def upd_wrap(*args, **kwargs):
u(None)
return upd_wrap
upd = wrap()
self._db = PersistentOptions.WrappedDict(cls, self._filename, self._version, cls.defaults, upd)
db = self._db
class WrappedClass:
def __init__(self, *args, **kwargs):
self._db = db
self._def = cls.defaults
def __getitem__(self, key):
return self._db[key]
def __setitem__(self, key, val):
self._db[key] = val
def keys(self):
return self._db.keys()
def reset(self):
self._db.reset()
def clean(self):
self._db.clean()
def gettersetter(self, key, fn_get_wrap=None, fn_set_wrap=None):
return self._db.gettersetter(key, fn_get_wrap=fn_get_wrap, fn_set_wrap=fn_set_wrap)
return WrappedClass
@@ -1,913 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import os
import re
import math
import time
import ctypes
import random
from typing import List
import traceback
import functools
import contextlib
import urllib.request
from functools import wraps
from itertools import chain
import bpy
import gpu
from bpy.types import BoolProperty
from mathutils import Matrix, Vector
from bpy_extras.view3d_utils import location_3d_to_region_2d, region_2d_to_vector_3d
from bpy_extras.view3d_utils import region_2d_to_location_3d, region_2d_to_origin_3d
from .blender import bversion, get_path_from_addon_root, get_path_from_addon_common
from .blender_cursors import Cursors
from .blender_preferences import get_preferences
from .debug import dprint, debugger
from .decorators import blender_version_wrapper, add_cache, only_in_blender_version
from .fontmanager import FontManager as fm
from .functools import find_fns
from .globals import Globals
from .hasher import Hasher
from .maths import Point2D, Vec2D, Point, Ray, Direction, mid, Color, Normal, Frame
from .profiler import profiler
from .utils import iter_pairs
from . import gpustate
class Drawing:
_instance = None
_dpi_mult = 1
_custom_dpi_mult = 1
_prefs = get_preferences()
_error_check = True
_error_count = 0
_error_limit = 10 # after this many check errors, no more will be reported to console
@staticmethod
def get_custom_dpi_mult():
return Drawing._custom_dpi_mult
@staticmethod
def set_custom_dpi_mult(v):
Drawing._custom_dpi_mult = v
Drawing.update_dpi()
@staticmethod
def update_dpi():
# print(f'view.ui_scale={Drawing._prefs.view.ui_scale}, system.ui_scale={Drawing._prefs.system.ui_scale}, system.dpi={Drawing._prefs.system.dpi}')
Drawing._dpi_mult = (
1.0
* Drawing._custom_dpi_mult
# * Drawing._prefs.view.ui_scale
* max(0.25, Drawing._prefs.system.ui_scale) # math.floor(Drawing._prefs.system.ui_scale))
# * (72.0 / Drawing._prefs.system.dpi)
# * Drawing._prefs.system.pixel_size
)
@staticmethod
def initialize():
Drawing.update_dpi()
if Globals.is_set('drawing'): return
Drawing._creating = True
Globals.set(Drawing())
del Drawing._creating
Drawing._instance = Globals.drawing
def __init__(self):
assert hasattr(self, '_creating'), "Do not instantiate directly. Use Drawing.get_instance()"
self.area,self.space,self.rgn,self.r3d,self.window = None,None,None,None,None
# self.font_id = 0
self.last_font_key = None
self.fontid = 0
self.fontsize = None
self.fontsize_scaled = None
self.line_cache = {}
self.size_cache = {}
self.set_font_size(12)
self._pixel_matrix = None
def set_region(self, area, space, rgn, r3d, window):
self.area = area
self.space = space
self.rgn = rgn
self.r3d = r3d
self.window = window
@staticmethod
def set_cursor(cursor): Cursors.set(cursor)
def scale(self, s): return s * self._dpi_mult if s is not None else None
def unscale(self, s): return s / self._dpi_mult if s is not None else None
def get_dpi_mult(self): return self._dpi_mult
def get_pixel_size(self): return self._pixel_size
def line_width(self, width): gpustate.line_width(max(1, self.scale(width)))
def point_size(self, size): gpustate.point_size(max(1, self.scale(size)))
def set_font_color(self, fontid, color):
fm.color(color, fontid=fontid)
def set_font_size(self, fontsize, fontid=None, force=False):
if fontid is None: fontid = fm._last_fontid
else: fontid = fm.load(fontid)
fontsize_prev = self.fontsize
fontsize, fontsize_scaled = int(fontsize), int(int(fontsize) * self._dpi_mult)
cache_key = (fontid, fontsize_scaled)
if self.last_font_key == cache_key and not force: return fontsize_prev
fm.size(fontsize_scaled, fontid=fontid)
if cache_key not in self.line_cache:
# cache away useful details about font (line height, line base)
# dprint('Caching new scaled font size:', cache_key)
pass
all_chars = ''.join([
'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'0123456789',
'!@#$%%^&*()`~[}{]/?=+\\|-_\'",<.>',
'ΑαΒβΓγΔδΕεΖζΗηΘθΙιΚκΛλΜμΝνΞξΟοΠπΡρΣσςΤτΥυΦφΧχΨψΩω',
])
all_caps = all_chars.upper()
self.line_cache[cache_key] = {
'line height': math.ceil(fm.dimensions(all_chars, fontid=fontid)[1] + self.scale(4)),
'line base': math.ceil(fm.dimensions(all_caps, fontid=fontid)[1]),
}
info = self.line_cache[cache_key]
self.line_height = info['line height']
self.line_base = info['line base']
self.fontid = fontid
self.fontsize = fontsize
self.fontsize_scaled = fontsize_scaled
self.last_font_key = cache_key
return fontsize_prev
def get_text_size_info(self, text, item, fontsize=None, fontid=None):
if fontsize or fontid: size_prev = self.set_font_size(fontsize, fontid=fontid)
if text is None: text, lines = '', []
elif type(text) is list: text, lines = '\n'.join(text), text
else: text, lines = text, text.splitlines()
fontid = fm.load(fontid)
key = (text, self.fontsize_scaled, fontid)
# key = (text, self.fontsize_scaled, self.font_id)
if key not in self.size_cache:
d = {}
if not text:
d['width'] = 0
d['height'] = 0
d['line height'] = self.line_height
else:
get_width = lambda t: math.ceil(fm.dimensions(t, fontid=fontid)[0])
get_height = lambda t: math.ceil(fm.dimensions(t, fontid=fontid)[1])
d['width'] = max(get_width(l) for l in lines)
d['height'] = get_height(text)
d['line height'] = self.line_height * len(lines)
self.size_cache[key] = d
if False:
print('')
print('--------------------------------------')
print('> computed new size')
print('> key: %s' % str(key))
print('> size: %s' % str(d))
print('--------------------------------------')
print('')
if fontsize: self.set_font_size(size_prev, fontid=fontid)
return self.size_cache[key][item]
def get_text_width(self, text, fontsize=None, fontid=None):
return self.get_text_size_info(text, 'width', fontsize=fontsize, fontid=fontid)
def get_text_height(self, text, fontsize=None, fontid=None):
return self.get_text_size_info(text, 'height', fontsize=fontsize, fontid=fontid)
def get_line_height(self, text=None, fontsize=None, fontid=None):
return self.get_text_size_info(text, 'line height', fontsize=fontsize, fontid=fontid)
def set_clipping(self, xmin, ymin, xmax, ymax, fontid=None):
fm.clipping((xmin, ymin), (xmax, ymax), fontid=fontid)
# blf.clipping(self.font_id, xmin, ymin, xmax, ymax)
self.enable_clipping()
def enable_clipping(self, fontid=None):
fm.enable_clipping(fontid=fontid)
# blf.enable(self.font_id, blf.CLIPPING)
def disable_clipping(self, fontid=None):
fm.disable_clipping(fontid=fontid)
# blf.disable(self.font_id, blf.CLIPPING)
def text_color_set(self, color, fontid):
if color is not None: fm.color(color, fontid=fontid)
def text_draw2D(self, text, pos:Point2D, *, color=None, dropshadow=None, fontsize=None, fontid=None, lineheight=True):
if fontsize: size_prev = self.set_font_size(fontsize, fontid=fontid)
lines = str(text).splitlines()
l,t = round(pos[0]),round(pos[1])
lh,lb = self.line_height,self.line_base
if dropshadow:
self.text_draw2D(text, (l+1,t-1), color=dropshadow, fontsize=fontsize, fontid=fontid, lineheight=lineheight)
gpustate.blend('ALPHA')
self.text_color_set(color, fontid)
for line in lines:
fm.draw(line, xyz=(l, t - lb, 0), fontid=fontid)
t -= lh if lineheight else self.get_text_height(line)
if fontsize: self.set_font_size(size_prev, fontid=fontid)
def text_draw2D_simple(self, text, pos:Point2D):
l,t = round(pos[0]),round(pos[1])
lb = self.line_base
fm.draw_simple(text, xyz=(l, t - lb, 0))
def get_mvp_matrix(self, view3D=True):
'''
if view3D == True: returns MVP for 3D view
else: returns MVP for pixel view
TODO: compute separate M,V,P matrices
'''
if not self.r3d: return None
if view3D:
# 3D view
return self.r3d.perspective_matrix
else:
# pixel view
return self.get_pixel_matrix()
mat_model = Matrix()
mat_view = Matrix()
mat_proj = Matrix()
view_loc = self.r3d.view_location # vec
view_rot = self.r3d.view_rotation # quat
view_per = self.r3d.view_perspective # 'PERSP' or 'ORTHO'
return mat_model,mat_view,mat_proj
def get_pixel_matrix_list(self):
if not self.r3d: return None
x,y = self.rgn.x,self.rgn.y
w,h = self.rgn.width,self.rgn.height
ww,wh = self.window.width,self.window.height
return [[2/w,0,0,-1], [0,2/h,0,-1], [0,0,1,0], [0,0,0,1]]
def load_pixel_matrix(self, m):
self._pixel_matrix = m
@add_cache('_cache', {'w':-1, 'h':-1, 'm':None})
def get_pixel_matrix(self):
'''
returns MVP for pixel view
TODO: compute separate M,V,P matrices
'''
if not self.r3d: return None
if self._pixel_matrix: return self._pixel_matrix
w,h = self.rgn.width,self.rgn.height
cache = self.get_pixel_matrix._cache
if cache['w'] != w or cache['h'] != h:
mx, my, mw, mh = -1, -1, 2 / w, 2 / h
cache['w'],cache['h'] = w,h
cache['m'] = Matrix([
[ mw, 0, 0, mx],
[ 0, mh, 0, my],
[ 0, 0, 1, 0],
[ 0, 0, 0, 1]
])
return cache['m']
def get_view_matrix_list(self):
return list(self.get_view_matrix()) if self.r3d else None
def get_view_matrix(self):
return self.r3d.perspective_matrix if self.r3d else None
def get_view_version(self):
if not self.r3d: return None
return Hasher(self.r3d.view_matrix, self.space.lens, self.r3d.view_distance)
@staticmethod
def glCheckError(title, **kwargs):
return gpustate.get_glerror(title, **kwargs)
@staticmethod
@contextlib.contextmanager
def glCheckError_wrap(title, *, stop_on_error=False):
if Drawing.glCheckError(f'addon common: pre {title}') and stop_on_error: return True
yield None
if Drawing.glCheckError(f'addon common: post {title}') and stop_on_error: return True
return False
def get_view_origin(self, *, orthographic_distance=1000):
focus = self.r3d.view_location
rot = self.r3d.view_rotation
dist = self.r3d.view_distance if self.r3d.is_perspective else orthographic_distance
return focus + (rot @ Vector((0, 0, dist)))
# # the following fails in weird ways when in orthographic projection
# center = Point2D((self.area.width / 2, self.area.height / 2))
# return Point(region_2d_to_origin_3d(self.rgn, self.r3d, center))
def Point2D_to_Ray(self, p2d):
o = Point(region_2d_to_origin_3d(self.rgn, self.r3d, p2d))
d = Direction(region_2d_to_vector_3d(self.rgn, self.r3d, p2d))
return Ray(o, d)
def Point_to_Point2D(self, p3d):
return Point2D(location_3d_to_region_2d(self.rgn, self.r3d, p3d))
@blender_version_wrapper('>=', '2.80')
def draw2D_point(self, pt:Point2D, color:Color, *, radius=1, border=0, borderColor=None):
radius = self.scale(radius)
border = self.scale(border)
if borderColor is None: borderColor = (0,0,0,0)
shader_2D_point.bind()
ubos_2D_point.options.screensize = (self.area.width, self.area.height, 0, 0)
ubos_2D_point.options.mvpmatrix = self.get_pixel_matrix()
ubos_2D_point.options.radius_border = (radius, border, 0, 0)
ubos_2D_point.options.color = color
ubos_2D_point.options.colorBorder = borderColor
ubos_2D_point.options.center = (*pt, 0, 1)
ubos_2D_point.update_shader()
batch_2D_point.draw(shader_2D_point)
gpu.shader.unbind()
@blender_version_wrapper('>=', '2.80')
def draw2D_points(self, pts:[Point2D], color:Color, *, radius=1, border=0, borderColor=None):
radius = self.scale(radius)
border = self.scale(border)
if borderColor is None: borderColor = (0,0,0,0)
shader_2D_point.bind()
ubos_2D_point.options.screensize = (self.area.width, self.area.height, 0, 0)
ubos_2D_point.options.mvpmatrix = self.get_pixel_matrix()
ubos_2D_point.options.radius_border = (radius, border, 0, 0)
ubos_2D_point.options.color = color
ubos_2D_point.options.colorBorder = borderColor
for pt in pts:
ubos_2D_point.options.center = (*pt, 0, 1)
ubos_2D_point.update_shader()
batch_2D_point.draw(shader_2D_point)
gpu.shader.unbind()
# draw line segment in screen space
def draw2D_line(self, p0:Point2D, p1:Point2D, color0:Color, *, color1=None, width=1, stipple=None, offset=0):
if color1 is None: color1 = (color0[0],color0[1],color0[2],0)
width = self.scale(width)
stipple = [self.scale(v) for v in stipple] if stipple else [1.0, 0.0]
offset = self.scale(offset)
shader_2D_lineseg.bind()
ubos_2D_lineseg.options.MVPMatrix = self.get_pixel_matrix()
ubos_2D_lineseg.options.screensize = (self.area.width, self.area.height, 0, 0)
ubos_2D_lineseg.options.pos0 = (*p0, 0, 1)
ubos_2D_lineseg.options.color0 = color0
ubos_2D_lineseg.options.pos1 = (*p1, 0, 1)
ubos_2D_lineseg.options.color1 = color1
ubos_2D_lineseg.options.stipple_width = (stipple[0], stipple[1], offset, width)
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
gpu.shader.unbind()
def draw2D_lines(self, points, color0:Color, *, color1=None, width=1, stipple=None, offset=0):
self.glCheckError('starting draw2D_lines')
if color1 is None: color1 = (color0[0],color0[1],color0[2],0)
width = self.scale(width)
stipple = [self.scale(v) for v in stipple] if stipple else [1.0, 0.0]
offset = self.scale(offset)
shader_2D_lineseg.bind()
ubos_2D_lineseg.options.MVPMatrix = self.get_pixel_matrix()
ubos_2D_lineseg.options.screensize = (self.area.width, self.area.height, 0, 0)
ubos_2D_lineseg.options.color0 = color0
ubos_2D_lineseg.options.color1 = color1
ubos_2D_lineseg.options.stipple_width = (stipple[0], stipple[1], offset, width)
for i in range(len(points)//2):
p0,p1 = points[i*2:i*2+2]
if p0 is None or p1 is None: continue
ubos_2D_lineseg.options.pos0 = (*p0, 0, 1)
ubos_2D_lineseg.options.pos1 = (*p1, 0, 1)
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
gpu.shader.unbind()
self.glCheckError('done with draw2D_lines')
def draw3D_lines(self, points, color0:Color, *, color1=None, width=1, stipple=None, offset=0):
self.glCheckError('starting draw3D_lines')
if color1 is None: color1 = (color0[0],color0[1],color0[2],0)
width = self.scale(width)
stipple = [self.scale(v) for v in stipple] if stipple else [1.0, 0.0]
offset = self.scale(offset)
shader_2D_lineseg.bind()
ubos_2D_lineseg.options.screensize = (self.area.width, self.area.height)
ubos_2D_lineseg.options.color0 = color0
ubos_2D_lineseg.options.color1 = color1
ubos_2D_lineseg.options.stipple_width = (stipple[0], stipple[1], offset, width)
ubos_2D_lineseg.options.MVPMatrix = self.get_view_matrix()
for i in range(len(points)//2):
p0,p1 = points[i*2:i*2+2]
if p0 is None or p1 is None: continue
ubos_2D_lineseg.options.pos0 = (*p0, 0, 1)
ubos_2D_lineseg.options.pos1 = (*p1, 0, 1)
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
gpu.shader.unbind()
self.glCheckError('done with draw3D_lines')
def draw2D_linestrip(self, points, color0:Color, *, color1=None, width=1, stipple=None, offset=0):
if color1 is None: color1 = (color0[0],color0[1],color0[2],0)
width = self.scale(width)
stipple = [self.scale(v) for v in stipple] if stipple else [1.0, 0.0]
offset = self.scale(offset)
shader_2D_lineseg.bind()
ubos_2D_lineseg.options.MVPMatrix = self.get_pixel_matrix()
ubos_2D_lineseg.options.screensize = (self.area.width, self.area.height)
ubos_2D_lineseg.options.color0 = color0
ubos_2D_lineseg.options.color1 = color1
for p0,p1 in iter_pairs(points, False):
ubos_2D_lineseg.options.pos0 = (*p0, 0, 1)
ubos_2D_lineseg.options.pos1 = (*p1, 0, 1)
ubos_2D_lineseg.options.stipple_width = (stipple[0], stipple[1], offset, width)
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
offset += (p1 - p0).length
gpu.shader.unbind()
# draw circle in screen space
def draw2D_circle(self, center:Point2D, radius:float, color0:Color, *, color1=None, width=1, stipple=None, offset=0):
if color1 is None: color1 = (color0[0],color0[1],color0[2],0)
radius = self.scale(radius)
width = self.scale(width)
stipple = [self.scale(v) for v in stipple] if stipple else [1,0]
offset = self.scale(offset)
shader_2D_circle.bind()
ubos_2D_circle.options.MVPMatrix = self.get_pixel_matrix()
ubos_2D_circle.options.screensize = (self.area.width, self.area.height, 0.0, 0.0)
ubos_2D_circle.options.center = (center.x, center.y, 0.0, 0.0)
ubos_2D_circle.options.color0 = color0
ubos_2D_circle.options.color1 = color1
ubos_2D_circle.options.radius_width = (radius, width, 0.0, 0.0)
ubos_2D_circle.options.stipple_data = (*stipple, offset, 0.0)
ubos_2D_circle.update_shader()
batch_2D_circle.draw(shader_2D_circle)
gpu.shader.unbind()
def draw3D_circle(self, center:Point, radius:float, color:Color, *, width=1, n:Normal=None, x:Direction=None, y:Direction=None, depth_near=0, depth_far=1):
assert n is not None or x is not None or y is not None, 'Must specify at least one of n,x,y'
f = Frame(o=center, x=x, y=y, z=n)
radius = self.scale(radius)
width = self.scale(width)
shader_3D_circle.bind()
ubos_3D_circle.options.MVPMatrix = self.get_view_matrix()
ubos_3D_circle.options.screensize = (self.area.width, self.area.height, 0.0, 0.0)
ubos_3D_circle.options.center = f.o
ubos_3D_circle.options.color = color
ubos_3D_circle.options.plane_x = f.x
ubos_3D_circle.options.plane_y = f.y
ubos_3D_circle.options.settings = (radius, width, depth_near, depth_far)
ubos_3D_circle.update_shader()
batch_3D_circle.draw(shader_3D_circle)
gpu.shader.unbind()
def draw3D_triangles(self, points:[Point], colors:[Color]):
self.glCheckError('starting draw3D_triangles')
shader_3D_triangle.bind()
ubos_3D_triangle.options.MVPMatrix = self.get_view_matrix()
for i in range(0, len(points), 3):
p0,p1,p2 = points[i:i+3]
c0,c1,c2 = colors[i:i+3]
if p0 is None or p1 is None or p2 is None: continue
if c0 is None or c1 is None or c2 is None: continue
ubos_3D_triangle.options.pos0 = p0
ubos_3D_triangle.options.color0 = c0
ubos_3D_triangle.options.pos1 = p1
ubos_3D_triangle.options.color1 = c1
ubos_3D_triangle.options.pos2 = p2
ubos_3D_triangle.options.color2 = c2
ubos_3D_triangle.update_shader()
batch_3D_triangle.draw(shader_3D_triangle)
gpu.shader.unbind()
self.glCheckError('done with draw3D_triangles')
@contextlib.contextmanager
def draw(self, draw_type:"CC_DRAW"):
assert getattr(self, '_draw', None) is None, 'Cannot nest Drawing.draw calls'
self._draw = draw_type
self.glCheckError('starting draw')
try:
draw_type.begin()
yield draw_type
draw_type.end()
except Exception as e:
print('Exception caught while in Drawing.draw with %s' % str(draw_type))
debugger.print_exception()
self.glCheckError('done with draw')
self._draw = None
if not bpy.app.background:
Drawing.glCheckError(f'pre-init check: Drawing')
Drawing.initialize()
Drawing.glCheckError(f'post-init check: Drawing')
if not bpy.app.background and bpy.app.version >= (3, 2, 0):
import gpu
from gpu_extras.batch import batch_for_shader
# https://docs.blender.org/api/blender2.8/gpu.html#triangle-with-custom-shader
def create_shader(fn_glsl):
path_glsl = get_path_from_addon_common('common', 'shaders', fn_glsl)
txt = open(path_glsl, 'rt').read()
vert_source, frag_source = gpustate.shader_parse_string(txt)
try:
Drawing.glCheckError(f'pre-compile check: {fn_glsl}')
ret = gpustate.gpu_shader(f'drawing {fn_glsl}', vert_source, frag_source)
Drawing.glCheckError(f'post-compile check: {fn_glsl}')
return ret
except Exception as e:
print('ERROR WHILE COMPILING SHADER %s' % fn_glsl)
assert False
Drawing.glCheckError(f'Pre-compile check: point, lineseg, circle, triangle shaders')
# 2D point
shader_2D_point, ubos_2D_point = create_shader('point_2D.glsl')
batch_2D_point = batch_for_shader(shader_2D_point, 'TRIS', {"pos": [(0,0), (1,0), (1,1), (0,0), (1,1), (0,1)]})
# 2D line segment
shader_2D_lineseg, ubos_2D_lineseg = create_shader('lineseg_2D.glsl')
batch_2D_lineseg = batch_for_shader(shader_2D_lineseg, 'TRIS', {"pos": [(0,0), (1,0), (1,1), (0,0), (1,1), (0,1)]})
# 2D circle
shader_2D_circle, ubos_2D_circle = create_shader('circle_2D.glsl')
# create batch to draw large triangle that covers entire clip space (-1,-1)--(+1,+1)
cnt = 100
pts = [
p for i0 in range(cnt)
for p in [
((i0+0)/cnt,0), ((i0+1)/cnt,0), ((i0+1)/cnt,1),
((i0+0)/cnt,0), ((i0+1)/cnt,1), ((i0+0)/cnt,1),
]
]
batch_2D_circle = batch_for_shader(shader_2D_circle, 'TRIS', {"pos": pts})
# 3D circle
shader_3D_circle, ubos_3D_circle = create_shader('circle_3D.glsl')
# create batch to draw large triangle that covers entire clip space (-1,-1)--(+1,+1)
cnt = 100
pts = [
p for i0 in range(cnt)
for p in [
((i0+0)/cnt,0), ((i0+1)/cnt,0), ((i0+1)/cnt,1),
((i0+0)/cnt,0), ((i0+1)/cnt,1), ((i0+0)/cnt,1),
]
]
batch_3D_circle = batch_for_shader(shader_3D_circle, 'TRIS', {"pos": pts})
# 3D triangle
shader_3D_triangle, ubos_3D_triangle = create_shader('triangle_3D.glsl')
batch_3D_triangle = batch_for_shader(shader_3D_triangle, 'TRIS', {'pos': [(1,0), (0,1), (0,0)]})
# 3D triangle
shader_2D_triangle, ubos_2D_triangle = create_shader('triangle_2D.glsl')
batch_2D_triangle = batch_for_shader(shader_2D_triangle, 'TRIS', {'pos': [(1,0), (0,1), (0,0)]})
Drawing.glCheckError(f'Compiled point, lineseg, circle shaders')
######################################################################################################
# The following classes mimic the immediate mode for (old-school way of) drawing geometry
# glBegin(GL_TRIANGLES)
# glColor3f(p)
# glVertex3f(p)
# glEnd()
class CC_DRAW:
_point_size:float = 1
_line_width:float = 1
_border_width:float = 0
_border_color:Color = Color((0, 0, 0, 0))
_stipple_pattern:List[float] = [1,0]
_stipple_offset:float = 0
_stipple_color:Color = Color((0, 0, 0, 0))
_default_color = Color((1, 1, 1, 1))
_default_point_size = 1
_default_line_width = 1
_default_border_width = 0
_default_border_color = Color((0, 0, 0, 0))
_default_stipple_pattern = [1,0]
_default_stipple_color = Color((0, 0, 0, 0))
@classmethod
def reset(cls):
s = Drawing._instance.scale
CC_DRAW._point_size = s(CC_DRAW._default_point_size)
CC_DRAW._line_width = s(CC_DRAW._default_line_width)
CC_DRAW._border_width = s(CC_DRAW._default_border_width)
CC_DRAW._border_color = CC_DRAW._default_border_color
CC_DRAW._stipple_offset = 0
CC_DRAW._stipple_pattern = [s(v) for v in CC_DRAW._default_stipple_pattern]
CC_DRAW._stipple_color = CC_DRAW._default_stipple_color
cls.update()
@classmethod
def update(cls): pass
@classmethod
def point_size(cls, size):
s = Drawing._instance.scale
CC_DRAW._point_size = s(size)
cls.update()
@classmethod
def line_width(cls, width):
s = Drawing._instance.scale
CC_DRAW._line_width = s(width)
cls.update()
@classmethod
def border(cls, *, width=None, color=None):
s = Drawing._instance.scale
if width is not None:
CC_DRAW._border_width = s(width)
if color is not None:
CC_DRAW._border_color = color
cls.update()
@classmethod
def stipple(cls, *, pattern=None, offset=None, color=None):
s = Drawing._instance.scale
if pattern is not None:
CC_DRAW._stipple_pattern = [s(v) for v in pattern]
if offset is not None:
CC_DRAW._stipple_offset = s(offset)
if color is not None:
CC_DRAW._stipple_color = color
cls.update()
@classmethod
def end(cls):
gpu.shader.unbind()
if not bpy.app.background:
CC_DRAW.reset()
class CC_2D_POINTS(CC_DRAW):
@classmethod
def begin(cls):
shader_2D_point.bind()
ubos_2D_point.options.mvpmatrix = Drawing._instance.get_pixel_matrix()
ubos_2D_point.options.screensize = (Drawing._instance.area.width, Drawing._instance.area.height, 0, 0)
ubos_2D_point.options.color = cls._default_color
cls.update()
@classmethod
def update(cls):
ubos_2D_point.options.radius_border = (cls._point_size, cls._border_width, 0, 0)
ubos_2D_point.options.colorBorder = cls._border_color
@classmethod
def color(cls, c:Color):
ubos_2D_point.options.color = c
@classmethod
def vertex(cls, p:Point2D):
if p:
ubos_2D_point.options.center = (*p, 0, 1)
ubos_2D_point.options.update_shader()
batch_2D_point.draw(shader_2D_point)
class CC_2D_LINES(CC_DRAW):
@classmethod
def begin(cls):
shader_2D_lineseg.bind()
mvpmatrix = Drawing._instance.get_pixel_matrix()
ubos_2D_lineseg.options.MVPMatrix = mvpmatrix
ubos_2D_lineseg.options.screensize = (Drawing._instance.area.width, Drawing._instance.area.height, 0, 0)
ubos_2D_lineseg.options.color0 = cls._default_color
cls.stipple(offset=0)
cls._c = 0
cls._last_p = None
@classmethod
def update(cls):
ubos_2D_lineseg.options.color1 = cls._stipple_color
ubos_2D_lineseg.options.stipple_width = (cls._stipple_pattern[0], cls._stipple_pattern[1], cls._stipple_offset, cls._line_width)
@classmethod
def color(cls, c:Color):
ubos_2D_lineseg.options.color0 = c
@classmethod
def vertex(cls, p:Point2D):
if p: ubos_2D_lineseg.options.assign(f'pos{cls._c}', (*p, 0, 1))
cls._c = (cls._c + 1) % 2
if cls._c == 0 and cls._last_p and p:
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
cls._last_p = p
class CC_2D_LINE_STRIP(CC_2D_LINES):
@classmethod
def begin(cls):
super().begin()
cls._last_p = None
@classmethod
def vertex(cls, p:Point2D):
if cls._last_p is None:
cls._last_p = p
else:
if cls._last_p and p:
ubos_2D_lineseg.options.pos0 = (*cls._last_p, 0, 1)
ubos_2D_lineseg.options.pos1 = (*p, 0, 1)
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
cls._last_p = p
class CC_2D_LINE_LOOP(CC_2D_LINES):
@classmethod
def begin(cls):
super().begin()
cls._first_p = None
cls._last_p = None
@classmethod
def vertex(cls, p:Point2D):
if cls._first_p is None:
cls._first_p = cls._last_p = p
else:
if cls._last_p and p:
ubos_2D_lineseg.options.pos0 = (*cls._last_p, 0, 1)
ubos_2D_lineseg.options.pos1 = (*p, 0, 1)
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
cls._last_p = p
@classmethod
def end(cls):
if cls._last_p and cls._first_p:
ubos_2D_lineseg.options.pos0 = (*cls._last_p, 0, 1)
ubos_2D_lineseg.options.pos1 = (*cls._first_p, 0, 1)
ubos_2D_lineseg.update_shader()
batch_2D_lineseg.draw(shader_2D_lineseg)
super().end()
class CC_2D_TRIANGLES(CC_DRAW):
@classmethod
def begin(cls):
shader_2D_triangle.bind()
#shader_2D_triangle.uniform_float('screensize', (Drawing._instance.area.width, Drawing._instance.area.height))
ubos_2D_triangle.options.MVPMatrix = Drawing._instance.get_pixel_matrix()
cls._c = 0
cls._last_color = None
cls._last_p0 = None
cls._last_p1 = None
@classmethod
def color(cls, c:Color):
if c is None: return
ubos_2D_triangle.options.assign(f'color{cls._c}', c)
cls._last_color = c
@classmethod
def vertex(cls, p:Point2D):
if p: ubos_2D_triangle.options.assign(f'pos{cls._c}', (*p, 0, 1))
cls._c = (cls._c + 1) % 3
if cls._c == 0 and p and cls._last_p0 and cls._last_p1:
ubos_2D_triangle.update_shader()
batch_2D_triangle.draw(shader_2D_triangle)
cls.color(cls._last_color)
cls._last_p1 = cls._last_p0
cls._last_p0 = p
class CC_2D_TRIANGLE_FAN(CC_DRAW):
@classmethod
def begin(cls):
shader_2D_triangle.bind()
ubos_2D_triangle.options.MVPMatrix = Drawing._instance.get_pixel_matrix()
cls._c = 0
cls._last_color = None
cls._first_p = None
cls._last_p = None
cls._is_first = True
@classmethod
def color(cls, c:Color):
if c is None: return
ubos_2D_triangle.options.assign(f'color{cls._c}', c)
cls._last_color = c
@classmethod
def vertex(cls, p:Point2D):
if p: ubos_2D_triangle.options.assign(f'pos{cls._c}', (*p, 0, 1))
cls._c += 1
if cls._c == 3:
if p and cls._first_p and cls._last_p:
ubos_2D_triangle.update_shader()
batch_2D_triangle.draw(shader_2D_triangle)
cls._c = 1
cls.color(cls._last_color)
if cls._is_first:
cls._first_p = p
cls._is_first = False
else: cls._last_p = p
class CC_3D_TRIANGLES(CC_DRAW):
@classmethod
def begin(cls):
shader_3D_triangle.bind()
ubos_3D_triangle.options.MVPMatrix = Drawing._instance.get_view_matrix()
cls._c = 0
cls._last_color = None
cls._last_p0 = None
cls._last_p1 = None
@classmethod
def color(cls, c:Color):
if c is None: return
ubos_3D_triangle.options.assign(f'color{cls._c}', c)
cls._last_color = c
@classmethod
def vertex(cls, p:Point):
if p: ubos_3D_triangle.options.assign(f'pos{cls._c}', p)
cls._c = (cls._c + 1) % 3
if cls._c == 0 and p and cls._last_p0 and cls._last_p1:
ubos_3D_triangle.update_shader()
batch_3D_triangle.draw(shader_3D_triangle)
cls.color(cls._last_color)
cls._last_p1 = cls._last_p0
cls._last_p0 = p
class DrawCallbacks:
@staticmethod
def on_draw(mode):
def wrapper(fn):
nonlocal mode
assert mode in {'predraw', 'pre3d', 'post3d', 'post2d'}, f'DrawCallbacks: unexpected draw mode {mode} for {fn}'
@wraps(fn)
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except Exception as e:
print(f'DrawCallbacks: caught exception in on_draw with {fn}')
debugger.print_exception()
print(e)
return
setattr(wrapped, f'_on_{mode}', True)
return wrapped
return wrapper
@staticmethod
def on_predraw():
return DrawCallbacks.on_draw('predraw')
def __init__(self, obj):
self.obj = obj
self._fns = {
'pre': [ fn for (_, fn) in find_fns(obj, '_on_predraw') ],
'pre3d': [ fn for (_, fn) in find_fns(obj, '_on_pre3d' ) ],
'post3d': [ fn for (_, fn) in find_fns(obj, '_on_post3d' ) ],
'post2d': [ fn for (_, fn) in find_fns(obj, '_on_post2d' ) ],
}
self.reset_pre()
def reset_pre(self):
self._called_pre = False
def _call(self, n, *, call_predraw=True):
if not self._called_pre:
self._called_pre = True
for fn in self._fns['pre']: fn(self.obj)
for fn in self._fns[n]: fn(self.obj)
def pre3d(self): self._call('pre3d')
def post3d(self): self._call('post3d')
def post2d(self): self._call('post2d')
@@ -1,425 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import re
import time
import inspect
from copy import deepcopy
import bpy
from .debug import dprint
from .decorators import blender_version_wrapper
from .human_readable import convert_actions_to_human_readable, convert_human_readable_to_actions
from .maths import Point2D, Vec2D
from .timerhandler import TimerHandler
from . import blender_preferences as bprefs
###
###
### The classes here will _eventually_ replace those in useractions.py
###
###
'''
copied from:
- https://docs.blender.org/api/current/bpy.types.Event.html
- https://docs.blender.org/api/current/bpy.types.KeyMapItem.html
direction: { 'ANY', 'NORTH', 'NORTH_EAST', 'EAST', 'SOUTH_EAST', 'SOUTH', 'SOUTH_WEST', 'WEST', 'NORTH_WEST' }
type: {
'NONE',
# System
'WINDOW_DEACTIVATE', # window lost focus (minimized, switch away from, etc.)
'ACTIONZONE_AREA', 'ACTIONZONE_REGION', 'ACTIONZONE_FULLSCREEN',
# Mouse
'LEFTMOUSE', 'MIDDLEMOUSE', 'RIGHTMOUSE', 'BUTTON4MOUSE', 'BUTTON5MOUSE', 'BUTTON6MOUSE', 'BUTTON7MOUSE',
'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE',
'MOUSEROTATE', 'MOUSESMARTZOOM', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'WHEELINMOUSE', 'WHEELOUTMOUSE',
'PEN', 'ERASER',
'TRACKPADPAN', 'TRACKPADZOOM',
# Keyboard
'LEFT_CTRL', 'LEFT_ALT', 'LEFT_SHIFT', 'RIGHT_ALT', 'RIGHT_CTRL', 'RIGHT_SHIFT', 'OSKEY',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE',
'SEMI_COLON', 'PERIOD', 'COMMA', 'QUOTE', 'ACCENT_GRAVE', 'MINUS', 'PLUS', 'SLASH', 'BACK_SLASH', 'EQUAL', 'LEFT_BRACKET', 'RIGHT_BRACKET',
'GRLESS',
'NUMPAD_2', 'NUMPAD_4', 'NUMPAD_6', 'NUMPAD_8', 'NUMPAD_1', 'NUMPAD_3', 'NUMPAD_5', 'NUMPAD_7', 'NUMPAD_9',
'NUMPAD_PERIOD', 'NUMPAD_SLASH', 'NUMPAD_ASTERIX', 'NUMPAD_0', 'NUMPAD_MINUS', 'NUMPAD_ENTER', 'NUMPAD_PLUS',
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F20', 'F21', 'F22', 'F23', 'F24',
'PAUSE', 'INSERT',
'HOME', 'PAGE_UP', 'PAGE_DOWN', 'END',
'MEDIA_PLAY', 'MEDIA_STOP', 'MEDIA_FIRST', 'MEDIA_LAST',
'ESC', 'TAB', 'RET', 'SPACE', 'LINE_FEED', 'BACK_SPACE', 'DEL',
'LEFT_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'UP_ARROW',
# ???
'APP',
# Text Input
'TEXTINPUT',
# Timer
'TIMER', 'TIMER0', 'TIMER1', 'TIMER2', 'TIMER_JOBS', 'TIMER_AUTOSAVE', 'TIMER_REPORT', 'TIMERREGION',
# NDOF
'NDOF_MOTION', 'NDOF_BUTTON_MENU', 'NDOF_BUTTON_FIT', 'NDOF_BUTTON_TOP', 'NDOF_BUTTON_BOTTOM', 'NDOF_BUTTON_LEFT', 'NDOF_BUTTON_RIGHT',
'NDOF_BUTTON_FRONT', 'NDOF_BUTTON_BACK', 'NDOF_BUTTON_ISO1', 'NDOF_BUTTON_ISO2', 'NDOF_BUTTON_ROLL_CW', 'NDOF_BUTTON_ROLL_CCW',
'NDOF_BUTTON_SPIN_CW', 'NDOF_BUTTON_SPIN_CCW', 'NDOF_BUTTON_TILT_CW', 'NDOF_BUTTON_TILT_CCW', 'NDOF_BUTTON_ROTATE', 'NDOF_BUTTON_PANZOOM',
'NDOF_BUTTON_DOMINANT', 'NDOF_BUTTON_PLUS', 'NDOF_BUTTON_MINUS',
'NDOF_BUTTON_1', 'NDOF_BUTTON_2', 'NDOF_BUTTON_3', 'NDOF_BUTTON_4', 'NDOF_BUTTON_5', 'NDOF_BUTTON_6', 'NDOF_BUTTON_7', 'NDOF_BUTTON_8', 'NDOF_BUTTON_9', 'NDOF_BUTTON_10',
'NDOF_BUTTON_A', 'NDOF_BUTTON_B', 'NDOF_BUTTON_C',
# ???
'XR_ACTION'
}
value: { 'ANY', 'PRESS', 'RELEASE', 'CLICK', 'DOUBLE_CLICK', 'CLICK_DRAG', 'NOTHING' }
class bpy.types.Event:
alt True when the Alt/Option key is held (unless both alt keys pressed and one is released)
ascii single ASCII character for this event
ctrl True when Ctrl key is held (unless both ctrl keys pressed and one is released)
direction drag direction (never used?)
is_mouse_absolute last motion event was an absolute input
is_repeat event is generated by holding a key down
is_tablet event has tablet data
mouse_prev_press_x window relative location of the last press event (most recent press)
mouse_prev_press_y
mouse_prev_x window relative location of mouse (in last event?)
mouse_prev_y
mouse_region_x region relative location of mouse
mouse_region_y
mouse_x window relative location of mouse
mouse_y
oskey True when Cmd key is held
pressure pressure of tablet or 1.0 if no tablet present
shift True when Shift key is held (unless both shift keys pressed and one is released)
tilt pressure (tilt?) of tablet or zeros if no tablet present ([float, float])
type (Type of event?)
type_prev: (type of last event?)
unicode: single unicode character for this event
value: type of event, only applies to some
value_prev: type of (last?) event, only applies to some
xr: XR event data
class bpy.types.KeyMapItem:
active True when KMI is active
alt Alt key pressed (int), -1 for any state
alt_ui (bool)
any any modifier keys pressed
ctrl Control key pressed (int), -1 for any state
ctrl_ui (bool)
direction drag direction
id ID of item (int [-32768, 32767], default 0)
idname identifier of operator to call on input event
is_user_defined True if KMI is user defined (doesn't just replace a builtin item)
is_user_modified True if KMI is modified by user
key_modifier Regular key pressed as a modifier (see type above)
map_type type of event mapping, { 'KEYBOARD', 'MOUSE', 'NDOF', 'TEXTINPUT', 'TIMER' }
name name of operator (translated) to call on input event
oskey Operating System Key pressed (int), -1 for any state
oskey_ui (bool)
properties Properties to set when the operator is called
propvalue the value this event translates to in a modal keymap
repeat active on key-repeat events (when key is held)
shift Shift key pressed (int), -1 for any state
shift_ui (bool)
show_expanded Show key map event and property details in the user interface
type type of event
value (value of event?)
bprefs.mouse_doubleclick()
bprefs.mouse_drag()
bprefs.mouse_move()
bprefs.mouse_select()
notes:
* if lshift is pressed, then shift is True. if rshift is pressed, then shift will still be True.
if lshift or rshift are released, shift will be False! but, this isn't an issue, as blender handles it in the same way.
* if modal operator invokes another operator on action, modal operator will only see the release of the action in (type_prev, value_prev)
* mouse_prev_press_* will hold location of mouse at most recent press (keyboard, mouse, anything!)
'''
class EventHandler:
keyboard_modifier_types = {
'LEFT_CTRL', 'LEFT_ALT', 'LEFT_SHIFT', 'RIGHT_ALT', 'RIGHT_CTRL', 'RIGHT_SHIFT', 'OSKEY',
}
keyboard_alpha_types = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
}
keyboard_number_types = {
'ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE',
'NUMPAD_2', 'NUMPAD_4', 'NUMPAD_6', 'NUMPAD_8', 'NUMPAD_1', 'NUMPAD_3', 'NUMPAD_5', 'NUMPAD_7', 'NUMPAD_9', 'NUMPAD_0',
}
keyboard_numpad_types = {
'NUMPAD_2', 'NUMPAD_4', 'NUMPAD_6', 'NUMPAD_8', 'NUMPAD_1', 'NUMPAD_3', 'NUMPAD_5', 'NUMPAD_7', 'NUMPAD_9', 'NUMPAD_0',
'NUMPAD_PERIOD', 'NUMPAD_SLASH', 'NUMPAD_ASTERIX', 'NUMPAD_MINUS', 'NUMPAD_PLUS',
'NUMPAD_ENTER',
}
keyboard_function_types = {
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F20', 'F21', 'F22', 'F23', 'F24',
}
keyboard_symbols_types = {
'SEMI_COLON', 'PERIOD', 'COMMA', 'QUOTE', 'ACCENT_GRAVE', 'MINUS', 'PLUS', 'SLASH', 'BACK_SLASH', 'EQUAL', 'LEFT_BRACKET', 'RIGHT_BRACKET',
'NUMPAD_PERIOD', 'NUMPAD_SLASH', 'NUMPAD_ASTERIX', 'NUMPAD_MINUS', 'NUMPAD_PLUS',
'GRLESS',
}
keyboard_media_types = {
'MEDIA_PLAY', 'MEDIA_STOP', 'MEDIA_FIRST', 'MEDIA_LAST',
'PAUSE', # ???
}
keyboard_movement_types = {
'HOME', 'PAGE_UP', 'PAGE_DOWN', 'END',
'LEFT_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'UP_ARROW',
}
keyboard_escape_types = {
'ESC',
# 'TAB', ???
}
keyboard_edit_types = {
'INSERT', 'TAB', 'RET', 'SPACE', 'LINE_FEED', 'BACK_SPACE', 'DEL',
}
keyboard_drag_types = {
*keyboard_alpha_types,
*keyboard_number_types,
*keyboard_numpad_types,
*keyboard_symbols_types,
}
keyboard_types = {
*keyboard_modifier_types,
*keyboard_alpha_types,
*keyboard_number_types,
*keyboard_numpad_types,
*keyboard_function_types,
*keyboard_symbols_types,
*keyboard_media_types,
*keyboard_movement_types,
*keyboard_edit_types,
}
mouse_button_types = {
'LEFTMOUSE', 'MIDDLEMOUSE', 'RIGHTMOUSE', 'BUTTON4MOUSE', 'BUTTON5MOUSE', 'BUTTON6MOUSE', 'BUTTON7MOUSE',
'MOUSEROTATE', 'MOUSESMARTZOOM', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'WHEELINMOUSE', 'WHEELOUTMOUSE',
'PEN', 'ERASER',
'TRACKPADPAN', 'TRACKPADZOOM',
}
mouse_move_types = {
'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE',
}
mouse_types = { *mouse_button_types, *mouse_move_types, }
ndof_types = {
'NDOF_MOTION',
'NDOF_BUTTON_MENU', 'NDOF_BUTTON_FIT', 'NDOF_BUTTON_TOP', 'NDOF_BUTTON_BOTTOM', 'NDOF_BUTTON_LEFT', 'NDOF_BUTTON_RIGHT',
'NDOF_BUTTON_FRONT', 'NDOF_BUTTON_BACK', 'NDOF_BUTTON_ISO1', 'NDOF_BUTTON_ISO2', 'NDOF_BUTTON_ROLL_CW', 'NDOF_BUTTON_ROLL_CCW',
'NDOF_BUTTON_SPIN_CW', 'NDOF_BUTTON_SPIN_CCW', 'NDOF_BUTTON_TILT_CW', 'NDOF_BUTTON_TILT_CCW', 'NDOF_BUTTON_ROTATE', 'NDOF_BUTTON_PANZOOM',
'NDOF_BUTTON_DOMINANT', 'NDOF_BUTTON_PLUS', 'NDOF_BUTTON_MINUS',
'NDOF_BUTTON_1', 'NDOF_BUTTON_2', 'NDOF_BUTTON_3', 'NDOF_BUTTON_4', 'NDOF_BUTTON_5', 'NDOF_BUTTON_6', 'NDOF_BUTTON_7', 'NDOF_BUTTON_8', 'NDOF_BUTTON_9', 'NDOF_BUTTON_10',
'NDOF_BUTTON_A', 'NDOF_BUTTON_B', 'NDOF_BUTTON_C',
}
timer_types = {
'TIMER', 'TIMER0', 'TIMER1', 'TIMER2', 'TIMER_JOBS', 'TIMER_AUTOSAVE', 'TIMER_REPORT', 'TIMERREGION',
}
scrollable_types = {
'HOME', 'PAGE_UP', 'PAGE_DOWN', 'END',
'LEFT_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'UP_ARROW',
'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'WHEELINMOUSE', 'WHEELOUTMOUSE',
'TRACKPADPAN',
}
pressable_types = {
# pressable also means releasable, clickable, double-clickable
*keyboard_types,
*mouse_button_types,
*ndof_types
}
special_types = {
'mousemove': { 'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE' },
'timer': { 'TIMER', 'TIMER_REPORT', 'TIMERREGION' },
'deactivate': { 'WINDOW_DEACTIVATE' },
}
modifier_keys = {
'alt', 'ctrl', 'shift', 'oskey',
}
def __init__(self, context, *, allow_keyboard_dragging=False):
self._allow_keyboard_dragging = allow_keyboard_dragging
self.reset()
def reset(self):
# current states
self.mods = { mod: False for mod in self.modifier_keys }
self.mouse = None
self.mouse_prev = None
self._held = {} # types that are currently held. {event.type: time of first held}
self._is_dragging = False
self.is_navigating = False # <- need this???
# memory
self._first_held = None # contains details of when first held action happened (held type, mouse loc, time)
self._last_event_type = None
self._just_released = None # keep track of last pressed for double click
# these properties are for very temporal state changes
@property
def is_mousemove(self):
return self._last_event_type in self.special_types['mousemove']
@property
def is_timer(self):
return self._last_event_type in self.special_types['timer']
@property
def is_deactivate(self):
return self._last_event_type in self.special_types['deactivate']
def is_draggable(self, event):
if self._allow_keyboard_dragging and event.type in self.keyboard_drag_types:
return True
if event.type in self.mouse_button_types:
return True
return False
def is_double_click(self, *, event=None):
if event and event.type != self.get_just_held('type'):
return False
delta = self.get_just_held('time') - time.time()
return delta < prefs.mouse_doubleclick()
def is_dragging(self, *, event=None):
return get_held(event.type, prop='dragging') if event else self.get_first_held(prop='dragging')
def holding_non_modifiers(self):
return bool(t for t in self._held if t not in self.keyboard_modifier_types)
def get_held(self, etype, *, prop=None, default=None):
if etype not in self._held: return default
d = self._held[etype]
return d[prop] if prop else d
def get_first_held(self, *, ignore_mods=True, prop=None, default=None):
held = self._held
if ignore_mods:
held = {htype:held[htype] for htype in held if htype not in self.keyboard_modifier_types}
if not held: return default
d = min(held, key=lambda htype: held[htype]['time'])
return d[prop] if prop else d
def get_just_held(self, *, prop=None, default=None):
return self._first_held[prop] if self._first_held else default
def _update_press(self, event):
# ignore non-pressable events
if event.type not in self.pressable_types:
return
# FIRST, if nothing is held (ignoring modifiers), record first held details
if not self.holding_non_modifiers():
self._first_held = {
'type': event.type,
'time': time.time(),
'mouse': self.mouse,
'dragging': False,
'can drag': self.is_type_draggable(event),
'double': self.is_double_click(event),
}
self._held[event.type] = {
'type': event.type,
'time': time.time(),
'mouse': self.mouse,
'dragging': False,
'can drag': self.is_type_draggable(event),
'double': self.is_double_click(event),
}
def _update_release(self, event, *, prev=False):
etype = event.type if not prev else event.prev_type
if etype == self.get_first_held(prop='type'):
self._just_released = self._first_held
self._first_held = None
if etype in self.held:
del self._held[etype]
def _update_drag(self, event):
first_held = self.get_first_held()
if first_held['dragging'] or not first_held['can drag']:
return
# has mouse moved far enough?
mouse_travel = (first_held['mouse'] - self.mouse).length
if mouse_travel > bprefs.mouse_drag():
self._first_held['dragging'] = True
fhtype = self._first_held['type']
if self._allow_keyboard_dragging and fhtype in self.keyboard_drag_types:
self._first_held['dragging'] = True
elif fhtype in self.mouse_button_types:
self._first_held['dragging'] = True
def update(self, context, event):
self._last_event_type = event.type
if self.is_deactivate:
# any time these actions are received, all action states will be flushed
self.reset()
self.mods['alt'] = event.alt
self.mods['ctrl'] = event.ctrl
self.mods['oskey'] = event.oskey
self.mods['shift'] = event.shift
self.mouse = Point2D((event.mouse_x, event.mouse_y))
self.mouse_prev = Point2D((event.mouse_prev_x, event.mouse_prev_y))
if event.value_prev == 'RELEASE':
self._update_release(event, prev=True)
if event.value == 'PRESS':
self._update_press(event)
elif event.value == 'RELEASE':
self._update_release(event)
elif event.value == 'NOTHING':
if event.type == 'MOUSEMOVE':
pass
if event.type not in self.mouse_move_types:
self._update_drag(event)
@@ -1,191 +0,0 @@
'''
Copyright (C) 2023 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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 <http://www.gnu.org/licenses/>.
'''
import bpy
import blf
import gpu
from . import gpustate
from .blender import get_path_from_addon_root, get_path_shortened_from_addon_root
from .blender_preferences import get_preferences
from .debug import dprint
from .decorators import blender_version_wrapper, only_in_blender_version
from .profiler import profiler
# https://docs.blender.org/api/current/blf.html
class FontManager:
_cache = {0:0}
_last_fontid = 0
_prefs = get_preferences()
@staticmethod
@property
def last_fontid(): return FontManager._last_fontid
@staticmethod
def get_dpi():
ui_scale = FontManager._prefs.view.ui_scale
pixel_size = FontManager._prefs.system.pixel_size
dpi = 72 # FontManager._prefs.system.dpi
return int(dpi * ui_scale * pixel_size)
@staticmethod
def load(val, load_callback=None):
if val is None:
fontid = FontManager._last_fontid
else:
if val not in FontManager._cache:
# note: loading the same file multiple times is not a problem.
# blender is smart enough to cache
fontid = blf.load(val)
print(f'Addon Common: Loaded font id={fontid}: {val}')
FontManager._cache[val] = fontid
FontManager._cache[fontid] = fontid
if load_callback: load_callback(fontid)
fontid = FontManager._cache[val]
FontManager._last_fontid = fontid
return fontid
@staticmethod
def unload_fontids():
unloaded = []
for name,fontid in FontManager._cache.items():
if type(name) is str:
blf.unload(name)
unloaded += [name]
for name in unloaded:
del FontManager._cache[name]
FontManager._last_fontid = 0
@staticmethod
def unload(filename):
assert filename in FontManager._cache
fontid = FontManager._cache[filename]
# dprint('Unloading font "%s" as id %d' % (filename, fontid))
pass
blf.unload(filename)
del FontManager._cache[filename]
if fontid == FontManager._last_fontid:
FontManager._last_fontid = 0
@staticmethod
def aspect(aspect, fontid=None):
return blf.aspect(FontManager.load(fontid), aspect)
@staticmethod
def blur(radius, fontid=None):
return blf.blur(FontManager.load(fontid), radius)
@staticmethod
def clipping(xymin, xymax, fontid=None):
return blf.clipping(FontManager.load(fontid), *xymin, *xymax)
@staticmethod
def color(color, fontid=None):
blf.color(FontManager.load(fontid), *color)
@staticmethod
def dimensions(text, fontid=None):
return blf.dimensions(FontManager.load(fontid), text)
@staticmethod
def disable(option, fontid=None):
return blf.disable(FontManager.load(fontid), option)
@staticmethod
def disable_rotation(fontid=None):
return blf.disable(FontManager.load(fontid), blf.ROTATION)
@staticmethod
def disable_clipping(fontid=None):
return blf.disable(FontManager.load(fontid), blf.CLIPPING)
@staticmethod
def disable_shadow(fontid=None):
return blf.disable(FontManager.load(fontid), blf.SHADOW)
@staticmethod
def disable_word_wrap(fontid=None):
return blf.disable(FontManager.load(fontid), blf.WORD_WRAP)
@staticmethod
def draw(text, xyz=None, fontsize=None, fontid=None):
fontid = FontManager.load(fontid)
if xyz: blf.position(fontid, *xyz)
if fontsize: FontManager.size(fontsize, fontid=fontid)
return blf.draw(fontid, text)
@staticmethod
def draw_simple(text, xyz):
fontid = FontManager._last_fontid
blf.position(fontid, *xyz)
blend_eqn = gpustate.get_blend() # storing blend settings, because blf.draw used to overwrite them (not sure if still applies)
ret = blf.draw(fontid, text)
gpustate.blend(blend_eqn) # restore blend settings
return ret
@staticmethod
def enable(option, fontid=None):
return blf.enable(FontManager.load(fontid), option)
@staticmethod
def enable_rotation(fontid=None):
return blf.enable(FontManager.load(fontid), blf.ROTATION)
@staticmethod
def enable_clipping(fontid=None):
return blf.enable(FontManager.load(fontid), blf.CLIPPING)
@staticmethod
def enable_shadow(fontid=None):
return blf.enable(FontManager.load(fontid), blf.SHADOW)
@staticmethod
def enable_word_wrap(fontid=None):
# note: not a listed option in docs for `blf.enable`, but see `blf.word_wrap`
return blf.enable(FontManager.load(fontid), blf.WORD_WRAP)
@staticmethod
def position(xyz, fontid=None):
return blf.position(FontManager.load(fontid), *xyz)
@staticmethod
def rotation(angle, fontid=None):
return blf.rotation(FontManager.load(fontid), angle)
@staticmethod
def shadow(level, rgba, fontid=None):
return blf.shadow(FontManager.load(fontid), level, *rgba)
@staticmethod
def shadow_offset(xy, fontid=None):
return blf.shadow_offset(FontManager.load(fontid), *xy)
@staticmethod
def size(size, fontid=None):
return blf.size(FontManager.load(fontid), size)
@staticmethod
def word_wrap(wrap_width, fontid=None):
return blf.word_wrap(FontManager.load(fontid), wrap_width)
@@ -1,187 +0,0 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$

Some files were not shown because too many files have changed in this diff Show More