trailing whitespaces cleanup

This commit is contained in:
pullusb
2023-01-18 14:28:27 +01:00
parent f3646e37df
commit 12cce98e41
23 changed files with 361 additions and 362 deletions
+87 -87
View File
@@ -20,11 +20,11 @@ def is_valid_name(name):
if name.startswith('.'):
return False
## FIXME: /!\ "note" as an exclude word is not good practice, temporary fix
if name.lower() == 'note':
return False
return True
### -- node basic
@@ -38,7 +38,7 @@ def create_node(type, tree=None, **kargs):
node = tree.nodes.new(type)
for k,v in kargs.items():
setattr(node, k, v)
return node
def new_aa_node(tree, **kargs):
@@ -62,7 +62,7 @@ def create_aa_nodegroup(tree):
sep = create_node('CompositorNodeSepRGBA', tree=ngroup, location=(-150,0))
comb = create_node('CompositorNodeCombRGBA', tree=ngroup, location=(350,25))
# in AA
# ngroup.links.new(comb.outputs[0], ng_out.inputs[0]) # <- connect without out AA
aa = new_aa_node(ngroup, location=(-400, 0))
@@ -73,24 +73,24 @@ def create_aa_nodegroup(tree):
# ngroup.links.new(ng_in.outputs[0], sep.inputs[0])
for i in range(3):
ngroup.links.new(sep.outputs[i], comb.inputs[i])
# alpha AA
alpha_aa = new_aa_node(ngroup, location=(100,-150))
ngroup.links.new(sep.outputs[3], alpha_aa.inputs[0])
ngroup.links.new(alpha_aa.outputs[0], comb.inputs[3])
ngroup.links.new(comb.outputs[0], ng_out.inputs[0])
ng = create_node('CompositorNodeGroup', tree=tree)
ng.node_tree = ngroup
ng.name = ngroup.name
ng.hide=True
return ng
## -- object and scene settings
## -- object and scene settings
def activate_workspace(name='', context=None):
if not name:
@@ -105,11 +105,11 @@ def activate_workspace(name='', context=None):
if (wkspace := bpy.data.workspaces.get(name)):
context.window.workspace = wkspace
return True
# Same name with spaces as underscore
dir_name = name.replace(' ', '_')
filepath = Path(__file__).parent / 'app_templates' / dir_name / 'startup.blend'
ret = bpy.ops.workspace.append_activate(idname=name, filepath=str(filepath))
if ret != {'FINISHED'}:
print(f'Could not found {name} at {filepath}')
@@ -119,7 +119,7 @@ def activate_workspace(name='', context=None):
def copy_settings(obj_a, obj_b):
exclusion = ['bl_rna', 'id_data', 'identifier','name_property','rna_type','properties', 'stamp_note_text','use_stamp_note',
'settingsFilePath', 'settingsStamp', 'select', 'matrix_local', 'matrix_parent_inverse',
'settingsFilePath', 'settingsStamp', 'select', 'matrix_local', 'matrix_parent_inverse',
'matrix_basis','location','rotation_euler', 'rotation_quaternion', 'rotation_axis_angle', 'scale']
for attr in dir(obj_a):
@@ -169,7 +169,7 @@ def set_settings(scene=None, aa=True):
'''aa == using native AA, else disable scene AA'''
if not scene:
scene = bpy.context.scene
# specify scene settings for these kind of render
set_scene_aa_settings(scene=scene, aa=aa)
@@ -177,7 +177,7 @@ def set_settings(scene=None, aa=True):
scene.render.use_compositing = True
scene.render.use_sequencer = False
scene.view_settings.view_transform = 'Standard'
scene.render.resolution_percentage = 100
# output (fast write settings since this is just to delete afterwards...)
@@ -192,7 +192,7 @@ def scene_aa(scene=None, toggle=True):
scene=bpy.context.scene
# enable/disable native anti-alias on active scene
set_scene_aa_settings(scene=scene, aa=toggle)
set_scene_aa_settings(scene=scene, aa=toggle)
# mute/unmute AA nodegroups
for n in scene.node_tree.nodes:
if n.type == 'GROUP' and n.name.startswith('NG_'):
@@ -216,7 +216,7 @@ def new_scene_from(name, src_scn=None, regen=True, crop=True, link_cam=True, lin
for attr in ['frame_start', 'frame_end', 'frame_current', 'camera', 'world']:
setattr(scn, attr, getattr(src_scn, attr))
copy_settings(src_scn.render, scn.render)
## link cameras (and lights ?)
for ob in src_scn.objects:
if link_cam and ob.type == 'CAMERA':
@@ -226,7 +226,7 @@ def new_scene_from(name, src_scn=None, regen=True, crop=True, link_cam=True, lin
# set adapted render settings
set_settings(scn)
if crop:
scn.render.use_border = True
scn.render.use_crop_to_border = True
@@ -239,7 +239,7 @@ def get_render_scene():
if render_scn:
return render_scn
## -- Create render scene
## -- Create render scene
current = bpy.context.scene
## With data
@@ -256,14 +256,14 @@ def get_render_scene():
for attr in ['frame_start', 'frame_end', 'frame_current', 'camera', 'world']:
setattr(render_scn, attr, getattr(current, attr))
copy_settings(current.render, render_scn.render)
## link cameras (and lights ?)
for ob in current.objects:
if ob.type in ('CAMERA', 'LIGHT'):
render_scn.collection.objects.link(ob)
render_scn.use_nodes = True
## Clear node tree (initial view layer stuff)
render_scn.node_tree.nodes.clear()
# for n in reversed(render_scn.node_tree.nodes):
@@ -326,15 +326,15 @@ def get_frame_transform(f, node_tree=None):
childs = [n for n in node_tree.nodes if n.parent == f]
# real_locs = [f.location + n.location for n in childs]
xs = [n.location.x for n in childs] + [n.location.x + n.dimensions.x for n in childs]
ys = [n.location.y for n in childs] + [n.location.y - n.dimensions.y for n in childs]
xs.sort(key=lambda loc: loc) # x val : ascending
xs.sort(key=lambda loc: loc) # x val : ascending
ys.sort(key=lambda loc: loc) # ascending # , reversed=True) # y val : descending
loc = Vector((min(xs), max(ys)))
dim = Vector((max(xs) - min(xs) + 60, max(ys) - min(ys) + 60))
return loc, dim
@@ -359,7 +359,7 @@ def bbox(f, frames):
ys += [loc.y, loc.y - n.dimensions.y] # - (n.dimensions.y/get_dpi_factor())
# margin ~= 30
# margin ~= 30
# return xs and ys
return [min(xs)-30, max(xs)+30], [min(ys)-30, max(ys)+30]
@@ -376,15 +376,15 @@ def get_frames_bbox(node_tree):
continue
# also contains frames
frames[n.parent].append(n)
# Dic for bbox coord
for f, nodes in frames.items():
if f.parent:
continue
xs, ys = bbox(f, frames)
# xs, ys = bbox(nodes, frames)
## returning: list of corner coords
# coords = [
# Vector((xs[0], ys[1])),
@@ -411,7 +411,7 @@ def merge_gplayer_viewlayers(ob, act=None, layers=None):
rd_scn = bpy.data.scenes.get('Render')
if not rd_scn:
return ({'ERROR'}, 'Viewlayers needs to be generated first!')
if not act.viewlayer_render:
return ({'ERROR'}, f'Active layer {act.info} has no viewlayer assigned')
@@ -433,14 +433,14 @@ def merge_gplayer_viewlayers(ob, act=None, layers=None):
sockout = grp.outputs.get(sockin.name)
if not sockout:
continue
for grplink in sockout.links:
if grplink.to_node.type != 'OUTPUT_FILE':
continue
fo_socket = grplink.to_socket
fo = grplink.to_node
fo.file_slots.remove(fo_socket)
# remove input and output from group
# grp.inputs.remove(sockin) # do not clear inside !!
# grp.outputs.remove(sockout) # do not clear inside !!
@@ -453,19 +453,19 @@ def merge_gplayer_viewlayers(ob, act=None, layers=None):
if grp.outputs[i].name == sockout.name:
ngroup.outputs.remove(ngroup.outputs[i])
break
# remove render_layer node
rd_scn.node_tree.nodes.remove(n)
# assign view layer from active to selected
for l in layers:
l.viewlayer_render = act.viewlayer_render
## delete unused_vl
# used_vl_name = [n.layer for n in rd_scn.node_tree.nodes if n.type == 'R_LAYERS' and n.layer]
# used_vl_name = [n.layer for n in rd_scn.node_tree.nodes if n.type == 'R_LAYERS' and n.layer]
for vl in vls:
rd_scn.view_layers.remove(vl)
rd_scn.view_layers.remove(vl)
# if not vl.name in used_vl_name:
# rd_scn.view_layers.remove(vl)
@@ -478,13 +478,13 @@ def group_adjacent_layer_prefix_rlayer(ob, excluded_prefix=[], first_name=True):
from itertools import groupby
re_prefix = re.compile(r'^([A-Z]{2})_')
if isinstance(excluded_prefix, str):
excluded_prefix = [p.strip() for p in excluded_prefix.split(',')]
## Create adjacent grp list: [('CO', [layer1, layer2]), ('LN', [layer3, layer4])]
## Create adjacent grp list: [('CO', [layer1, layer2]), ('LN', [layer3, layer4])]
adjacent_prefix_groups = [
(g[0], list(g[1])) for g in
(g[0], list(g[1])) for g in
groupby([l for l in ob.data.layers],
key=lambda l: re_prefix.search(l.info).group(1) if re_prefix.search(l.info) else '')
]
@@ -559,7 +559,7 @@ def rearrange_frames(node_tree):
## order the dict by frame.y location
frame_d = {key: value for key, value in sorted(frame_d.items(), key=lambda pair: pair[1][0].y - pair[1][1].y, reverse=True)}
frames = [[f, v[0], v[1].y] for f, v in frame_d.items()] # [frame_node, real_loc, real dimensions]
top = frames[0][1].y # upper node location.y
# top = 0 #always start a 0
offset = 0
@@ -571,7 +571,7 @@ def rearrange_frames(node_tree):
f[0].location.y = (f[1].y - f[0].location.y) - offset # avoid offset when recalculating from 0 top
# f[0].location.y = f[1].y - top - offset
offset += f[2] + 200 # gap
f[0].update()
def reorder_inputs(ng):
@@ -657,7 +657,7 @@ def all_connected_forward(n, nlist=[]):
else:
return nlist
else:
nlist = all_connected_forward(lnk.to_node, nlist)
nlist = all_connected_forward(lnk.to_node, nlist)
if n in nlist:
return nlist
return nlist + [n]
@@ -692,7 +692,7 @@ def reorder_nodegroup_content(ngroup):
n_thread = all_connected_forward_from_socket(out)
if n_thread:
n_threads.append(n_thread)
level = grp_in.location.y
for thread in n_threads:
top = max([n.location.y for n in thread])
@@ -718,7 +718,7 @@ def clear_nodegroup_content_if_disconnected(ngroup):
continue
if not connect_to_group_input(n) and not connect_to_group_output(n): # is disconnected from both side
ngroup.nodes.remove(n)
reorder_nodegroup_content(ngroup)
def clean_nodegroup_inputs(ng, skip_existing_pass=True):
@@ -756,7 +756,7 @@ def bridge_reconnect_nodegroup(ng, socket_name=None):
ngroup.links.new(sockin, aa.inputs[0])
ngroup.links.new(aa.outputs[0], sockout)
print(f'{ng.name}: Bridged {sockin.name}')
def random_color(alpha=False):
import random
@@ -789,7 +789,7 @@ def nodegroup_merge_inputs(ngroup):
ao = create_node('CompositorNodeAlphaOver', tree=ngroup, location=(x,y), hide=True)
ngroup.links.new(prev.outputs[0], ao.inputs[1])
ngroup.links.new(inp, ao.inputs[2])
x += offset_x
y += offset_y
prev = ao
@@ -798,7 +798,7 @@ def nodegroup_merge_inputs(ngroup):
aa = create_aa_nodegroup(ngroup) # new_aa_node(ngroup)
aa.location = (ao.location.x + 200, ao.location.y)
ngroup.links.new(ao.outputs[0], aa.inputs[0]) # node_tree
# create one input and link
out = ngroup.outputs.new('NodeSocketColor', ngroup.inputs[0].name)
ngroup.links.new(aa.outputs[0], ng_out.inputs[0])
@@ -852,7 +852,7 @@ def delete_numbering(fo): # padding=3
elems = fs.path.split('/')
for i, e in enumerate(elems):
elems[i] = re.sub(r'^\d{3}_', '', e)
new = '/'.join(elems)
fs.path = new
@@ -868,7 +868,7 @@ def renumber_keep_existing(fo, offset=10, invert=True):
if fo.type != 'OUTPUT_FILE': return
ct = 10
if invert:
reverse_fileout_inputs(fo)
@@ -931,7 +931,7 @@ def renumber_keep_existing(fo, offset=10, invert=True):
add_fileslot_number(fs, prev_num + offset)
else:
add_fileslot_number(fs, ct)
else:
if prev_num is not None:
# iterate rename
@@ -968,7 +968,7 @@ def normalize_layer_name(layer, prefix='', desc='', suffix='', lower=True, dash_
import re
name = layer.info
pattern = PATTERN
sep = '_'
res = re.search(pattern, name.strip())
@@ -993,7 +993,7 @@ def normalize_layer_name(layer, prefix='', desc='', suffix='', lower=True, dash_
# tag2 = prefix2.upper().strip() + sep
if desc:
name = desc
if suffix:
if suffix == 'suffixkillcode':
sfix = ''
@@ -1013,7 +1013,7 @@ def normalize_layer_name(layer, prefix='', desc='', suffix='', lower=True, dash_
old = layer.info
print(f'{old} >> {new}')
layer.info = new
# Also change name string in modifier target !
for ob in [o for o in bpy.data.objects if o.type == 'GPENCIL' and o.data == layer.id_data]:
for m in ob.grease_pencil_modifiers:
@@ -1037,7 +1037,7 @@ def build_layers_targets_from_dopesheet(context):
gpl = context.object.data.layers
act = gpl.active
dopeset = context.space_data.dopesheet
if dopeset.show_only_selected:
pool = [o for o in context.selected_objects if o.type == 'GPENCIL']
@@ -1048,7 +1048,7 @@ def build_layers_targets_from_dopesheet(context):
layer_pool = [l for o in pool for l in o.data.layers]
layer_pool = list(set(layer_pool)) # remove dupli-layers from same data source with
# apply search filter
if dopeset.filter_text:
layer_pool = [l for l in layer_pool if (dopeset.filter_text.lower() in l.info.lower()) ^ dopeset.use_filter_invert]
@@ -1067,7 +1067,7 @@ def show_message_box(_message = "", _title = "Message Box", _icon = 'INFO'):
self.layout.label(text=l)
else:
self.layout.label(text=l[0], icon=l[1])
if isinstance(_message, str):
_message = [_message]
bpy.context.window_manager.popup_menu(draw, title = _title, icon = _icon)
@@ -1092,7 +1092,7 @@ def show_message_box(_message = "", _title = "Message Box", _icon = 'INFO'):
elif len(l) == 3: # ops
self.layout.operator_context = "INVOKE_DEFAULT"
self.layout.operator(l[0], text=l[1], icon=l[2], emboss=False) # <- highligh the entry
if isinstance(_message, str):
_message = [_message]
bpy.context.window_manager.popup_menu(draw, title = _title, icon = _icon)
@@ -1122,15 +1122,15 @@ def is_render_included(o, scn):
def get_crop_pixel_coord(scn):
# width height probably not needed. might need
# width height probably not needed. might need
px_width = (scn.render.border_max_x - scn.render.border_min_x) * scn.render.resolution_x
px_height = (scn.render.border_max_y - scn.render.border_min_y) * scn.render.resolution_y
pos_x = (scn.render.border_min_x + ((scn.render.border_max_x - scn.render.border_min_x) / 2)) * scn.render.resolution_x
## coord y > image center coord from bottom-left (Blender)
# pos_y = (scn.render.border_min_y + ((scn.render.border_max_y - scn.render.border_min_y) / 2)) * scn.render.resolution_y,
## image center coord from top-left (AE)
pos_y = ((1 - scn.render.border_max_y) + ((scn.render.border_max_y - scn.render.border_min_y) / 2)) * scn.render.resolution_y
@@ -1145,15 +1145,15 @@ def get_crop_pixel_coord(scn):
def export_crop_to_json():
'''Export crop to json coords for AE
'''
blend = Path(bpy.data.filepath)
json_path = blend.parent / 'render' / f'{blend.stem}.json' #f'{ob.name}.json'
## per scene : json_path = Path(bpy.data.filepath).parent / 'render' / f'{scn.name}.json'
# json_path = Path(bpy.data.filepath).parent / 'render' / f'{scn.name}.json' #f'{ob.name}.json'
coord_dic = {}
for scn in bpy.data.scenes:
# if scn.name in {'Scene', 'Render'}:
# if scn.name == 'Scene':
@@ -1178,7 +1178,7 @@ def export_crop_to_json():
# save bbox
with json_path.open('w') as fd:
json.dump(coord_dic, fd, indent='\t')
print(f'Coords saved at: {json_path}')
return coord_dic
@@ -1189,13 +1189,13 @@ def set_border_region_from_coord(coords, scn=None, margin=30, export_json=True):
'''
scn = scn or bpy.context.scene
coords2d_x = sorted([c[0] for c in coords])
coords2d_y = sorted([c[1] for c in coords])
margin_width = margin / scn.render.resolution_x
margin_height = margin / scn.render.resolution_y
# set crop
scn.render.border_min_x = coords2d_x[0] - margin_width
scn.render.border_max_x = coords2d_x[-1] + margin_width
@@ -1223,17 +1223,17 @@ def set_border_region_from_coord(coords, scn=None, margin=30, export_json=True):
def get_gp_box_all_frame(ob, cam=None):
'''set crop to object bounding box considering whole animation. Cam should not be animated (render in bg_cam)
return 2d bbox in pixels
return 2d bbox in pixels
'''
from bpy_extras.object_utils import world_to_camera_view
coords_cam_list = []
scn = bpy.context.scene
cam = cam or scn.camera
start = time()
if ob.animation_data and ob.animation_data.action: # use frame set on all frames
print(f'{ob.name} has anim')
# frame_nums = sorted(list(set([f.frame_number for l in ob.data.layers if len(l.frames) for f in l.frames if len(f.strokes) and scn.frame_start <= f.frame_number <= scn.frame_end])))
# frame_nums = sorted(list(set([f.frame_number for l in ob.data.layers if len(l.frames) for f in l.frames if len(f.strokes) and scn.frame_start <= f.frame_number <= scn.frame_end])))
for num in range(scn.frame_start, scn.frame_end+1):
scn.frame_set(num)
for l in ob.data.layers:
@@ -1257,7 +1257,7 @@ def get_gp_box_all_frame(ob, cam=None):
if len(s.points) == 1: # skip isolated points
continue
coords_cam_list += [world_to_camera_view(scn, cam, ob.matrix_world @ p.co) for p in s.points]
print(time() - start) # Dbg-time
return coords_cam_list
@@ -1276,7 +1276,7 @@ def has_keyframe(ob, attr):
def get_gp_box_all_frame_selection(oblist=None, scn=None, cam=None, timeout=40):
'''
get points of all selection
return 2d bbox in pixels
return 2d bbox in pixels
return None if timeout (too long to process, better to do it visually)
'''
@@ -1289,7 +1289,7 @@ def get_gp_box_all_frame_selection(oblist=None, scn=None, cam=None, timeout=40):
cam = cam or scn.camera
start = time()
if any(has_anim(ob) for ob in oblist):
print(f'at least one is animated: {oblist}')
for num in range(scn.frame_start, scn.frame_end+1):
@@ -1304,7 +1304,7 @@ def get_gp_box_all_frame_selection(oblist=None, scn=None, cam=None, timeout=40):
if len(s.points) == 1: # skip isolated points
continue
coords_cam_list += [world_to_camera_view(scn, cam, ob.matrix_world @ p.co) for p in s.points]
if time() - t0 > timeout:
print(f'timeout (more than {timeout}s to calculate) evaluating frame position of objects {oblist}')
return
@@ -1325,16 +1325,16 @@ def get_gp_box_all_frame_selection(oblist=None, scn=None, cam=None, timeout=40):
if len(s.points) == 1: # skip isolated points
continue
coords_cam_list += [world_to_camera_view(scn, cam, ob.matrix_world @ p.co) for p in s.points]
print(f'{len(coords_cam_list)} gp points listed {time() - start:.1f}s')
return coords_cam_list
def get_bbox_2d(ob, cam=None):
from bpy_extras.object_utils import world_to_camera_view
scn = bpy.context.scene
scn = bpy.context.scene
cam = cam or scn.camera
coords2d = [world_to_camera_view(scn, cam, p) for p in get_bbox_3d(ob)]
coords2d = [world_to_camera_view(scn, cam, p) for p in get_bbox_3d(ob)]
coords2d_x = sorted([c[0] for c in coords2d])
coords2d_y = sorted([c[1] for c in coords2d])
@@ -1348,9 +1348,9 @@ def get_bbox_2d(ob, cam=None):
return [Vector(b) for b in bbox2d_coords]
def set_box_from_selected_objects(scn=None, cam=None, export_json=False):
scn = scn or bpy.context.scene
scn = scn or bpy.context.scene
cam = cam or scn.camera
selection = [o for o in scn.objects if o.select_get()] # selected_objects
coords = get_gp_box_all_frame_selection(oblist=selection, scn=scn, cam=cam)
if not coords:
@@ -1445,10 +1445,10 @@ def get_collection_childs_recursive(col, cols=[], include_root=True):
cols.append(sub)
if len(sub.children):
cols = get_collection_childs_recursive(sub, cols)
if include_root and col not in cols: # add root col
cols.append(col)
return cols
def unlink_objects_from_scene(oblist, scn):
@@ -1473,7 +1473,7 @@ def split_object_to_scene():
active = bpy.context.object
scene_name = active.name
objs = [o for o in bpy.context.selected_objects]
if bpy.data.scenes.get(scene_name):
print(f'Scene "{scene_name}" Already Exists')
raise Exception(f'Scene "{scene_name}" Already Exists')
@@ -1497,7 +1497,7 @@ def split_object_to_scene():
continue
if sob not in objs:
col.objects.unlink(sob)
frame_names = [n.label for n in new.node_tree.nodes if n.type == 'FRAME' if new.objects.get(n.label)]
remove_scene_nodes_by_obj_names(new, frame_names, negative=True)
@@ -1511,7 +1511,7 @@ def split_object_to_scene():
## remove asset from original scene
#src_frame_names = [n.label for n in src.node_tree.nodes if n.type == 'FRAME' and n.label in [o.name for o in objs]]
#remove_scene_nodes_by_obj_names(src, src_frame_names)
#remove_scene_nodes_by_obj_names(src, src_frame_names)
remove_scene_nodes_by_obj_names(src, frame_names, negative=False)
# unlink objects ?
@@ -1522,7 +1522,7 @@ def split_object_to_scene():
coords = get_gp_box_all_frame_selection(oblist=gp_objs, scn=new, cam=new.camera)
if not coords:
return f'Scene "{scene_name}" created. But Border was not set (Timeout during GP analysis), should be done by hand if needed then use export crop to json'
set_border_region_from_coord(coords, margin=30, scn=new, export_json=True)
export_crop_to_json()
@@ -1548,7 +1548,7 @@ def clear_frame_out_of_range(o, verbose=False):
print(f'del: obj {o.name} > layer {l.info} > frame {f.frame_number}')
l.frames.remove(f)
ct += 1
# before
elif f.frame_number < scn.frame_start - 1:
if first:
@@ -1596,7 +1596,7 @@ def set_scene_output_from_active_fileout_item():
excluded = ['file_format', 'color_mode', 'color_depth',
'view_settings', 'views_format']
''' ## all attrs
# 'cineon_black', 'cineon_gamma', 'cineon_white',
# 'color_depth', 'color_mode', 'compression', 'display_settings',
@@ -1641,7 +1641,7 @@ def set_layer_colors(skip_if_colored=False):
continue
print(l.info, '->', color)
l.channel_color = color
bpy.context.preferences.edit.use_anim_channel_group_colors = True