refacto to use import_planes as a functions

This commit is contained in:
ChristopheSeux
2023-09-28 12:54:37 +02:00
parent ba5084e458
commit 11029606df
12 changed files with 344 additions and 308 deletions
+13
View File
@@ -0,0 +1,13 @@
from . import operators
modules = (
operators,
)
def register():
for module in modules:
bpy.utils.register_class(module)
def unregister():
for module in reversed(modules):
bpy.utils.unregister_class(module)
+158
View File
@@ -0,0 +1,158 @@
import bpy
import json
from pathlib import Path
import os
import re
import time
from pathlib import Path
from mathutils import Vector, geometry
from pprint import pprint as pp
from ..constants import PREFIX, BGCOL, INIT_POS
from ..core import (create_cam, set_collection, get_image_infos_from_object, get_col,
import_image_as_gp_reference, create_image_plane, set_collection, get_image,
create_empty_image, create_plane_holder, create_plane_driver, reload_bg_list)
def get_json_infos(json_path) -> tuple((list, tuple)):
'''return a tuple with (image paths list, [x, y] original psd resolution'''
import json
setup_json_path = Path(json_path)
setup_json = json.loads(setup_json_path.read_text())
# psd = Path(setup_json['psd']) # path to psd
# image_size = setup_json['image_size'] # image size (reduced)
# png_dir = Path(setup_json['png_dir']) # path to png directory
layers = setup_json['layers'] # dic : name, lbbox, bbox, index, path
org_image_size = setup_json['org_image_size'] # original PSD dimensions
img_list = [Path(l['path']) for l in layers] # (png_dir /l['name']).with_suffix('.png')
return img_list, org_image_size
def setup_bg_camera(image_size, scene=None, cam_type=None):
'''Create background camera from scene active camera according to background image resolution
image_size ::
cam_type :: wether the BG camera should be set to perspective or orthographic
'''
scn = scene or bpy.context.scene
movie_resolution = scn.render.resolution_x, scn.render.resolution_y
anim_cam = scn.camera
anim_cam_scale = 6 # anim_cam.data.ortho_scale
anim_cam_focale = 50 # anim_cam.data.lens
cam_type = cam_type or anim_cam.data.type
## scale up plane scale and bg_cam ortho_scale according to film res
bg_factor = (anim_cam_scale * image_size[0]) / movie_resolution[0]
#print(f'({anim_cam_scale} * {image_size[0]}) / {movie_resolution[0]} = {bg_factor}')
## scale down the focal according to film res
bg_focale = (anim_cam_focale * movie_resolution[0]) / image_size[0]
#print(f'({anim_cam_focale} * {movie_resolution[0]}) / {image_size[0]} = {bg_focale}')
bg_cam = scn.objects.get('bg_cam')
if not bg_cam:
bg_cam = create_cam(name='bg_cam', type=cam_type, size=bg_factor, focale=bg_focale)
bg_cam['resolution'] = image_size
bg_cam.matrix_world = anim_cam.matrix_world
bg_cam.hide_select = True
bg_cam.lock_location = bg_cam.lock_rotation = bg_cam.lock_scale = [True]*3
set_collection(bg_cam, 'Camera')
set_collection(anim_cam, 'Camera')
return bg_cam
def import_planes(images, import_type='GPENCIL', mode='REPLACE', image_size=None):
scn = bpy.context.scene
existing_backgrounds = [(o, *img_info) for o in scn.objects \
if o.get('is_background') and (img_info := get_image_infos_from_object(o)) and o.get('is_background') and o.parent]
existing_backgrounds.sort(key=lambda x: x[0].parent.location.z, reverse=True) # sort by parent (holder) location Z
far_plane = INIT_POS
if existing_backgrounds:
far_plane = existing_backgrounds[-1][0].parent.location.z
## Ensure bg_cam setup (option to use active camera ?)
bg_cam = scn.objects.get('bg_cam')
if not bg_cam:
if not image_size:
## Get image size from first file
img = bpy.data.images.load(str(images[0]), check_existing=True)
image_size = (img.size[0], img.size[1])
bg_cam = setup_bg_camera(image_size)
## Ensure Background collection
backgrounds = get_col(BGCOL) # Create if needed
for image_path in images:
image_path = Path(image_path)
print(f'Importing {image_path.name}')
current_holder = None
file_stem = image_path.stem
# current_bg = next((o for o if o.parent and get_image_infos_from_object(o)), None)
current_bg = next((o for o in existing_backgrounds if Path(o[1].filepath) == image_path), None)
if current_bg:
current_holder = current_bg.parent
# TODO store opacity or delete existing objects only after loop
if current_bg and mode == 'SKIP':
print(f' - SKIP: existing {current_bg.name}')
continue
if current_bg and mode == 'REPLACE':
print(f' - DEL: existing {current_bg.name}')
bpy.data.objects.remove(current_bg)
# Import image
if import_type == 'GPENCIL':
bg_img = import_image_as_gp_reference(
image=str(image_path),
pack_image=False,
)
elif import_type == 'MESH':
bg_img = create_image_plane(image_path)
elif import_type == 'EMPTY':
bg_img = create_empty_image(image_path)
bg_img.name = file_stem + '_texgp'
bg_img.hide_select = True
if current_holder:
bg_img.parent = current_holder
set_collection(bg_img, current_holder.users_collection[0].name)
continue
# img, opacity = get_image_infos_from_object(bg_img)
print('bg_img: ', bg_img)
img = get_image(bg_img)
# bg_name = clean_image_name(img.name)
file_stem = file_stem
# Get create collection from image clean name
bg_col = get_col(file_stem, parent=backgrounds)
## Set in collection
bg_col.objects.link(bg_img)
print('img: ', img.name, bg_img.name, bg_img.users_collection)
## create the holder, parent to camera, set driver and set collection. Could also pass 'fp'
holder = create_plane_holder(img, name=PREFIX + file_stem, parent=bg_cam, link_in_col=bg_col)
print('holder: ', holder.name)
create_plane_driver(holder, bg_cam, distance=far_plane)
bg_img.parent = holder
far_plane += 2
reload_bg_list(scene=scn)
+130
View File
@@ -0,0 +1,130 @@
# SPDX-License-Identifier: GPL-3.0-or-later
## Standalone based on SPA code
## Code from create_gp_texture_ref.py (Copyright (C) 2023, The SPA Studios. All rights reserved.)
## adapted to create as a single 'GP as image' and fit in camera with driver
import bpy
from bpy_extras.io_utils import ImportHelper
from bpy.props import (StringProperty,
CollectionProperty,
BoolProperty,
EnumProperty)
import json
import bpy_extras
from mathutils import Vector
import os
from pathlib import Path
from .. import core
from .. constants import *
from .. export_psd_layers import export_psd_bg
from . core import import_planes, get_json_infos
class BPM_OT_import_bg_images(bpy.types.Operator, ImportHelper):
bl_idname = "bpm.import_bg_images"
bl_label = "Import Background images"
bl_description = "Import either a Json, a PSD, multiple files"
bl_options = {"REGISTER"} # , "INTERNAL"
# filename_ext = '.json'
filter_glob: StringProperty(
default=';'.join([f'*{i}' for i in bpy.path.extensions_image]) + ';*.json',
options={'HIDDEN'} )
## Active selection
filepath : StringProperty(
name="File Path",
description="File path used for import",
maxlen= 1024) # the active file
## Handle multi-selection
files: CollectionProperty(
name="File Path",
type=bpy.types.OperatorFileListElement,
) # The filelist collection
## Choice to place before or after ?
import_type : EnumProperty(
name="Import As", description="Type of import to ", default='GPENCIL', options={'ANIMATABLE'},
items=(
('GPENCIL', 'Gpencil Object', 'Import bg planes as gpencil objects', 0),
('EMPTY', 'Empty Reference', 'Import bg planes as empty objects', 1),
('MESH', 'Texture Plane', 'Import bg planes as mesh objects', 2),
))
mode : EnumProperty(
name="Mode", description="", default='REPLACE', options={'ANIMATABLE'},
items=(
('REPLACE', 'Replace Existing', 'Replace the image if already exists', 0),
('SKIP', 'Skip Existing', 'Skip the import if the image alreaady exists in planes', 1),
# ('PURGE', 'Purge', 'When object exists, fully delete it before linking, even associated collection and holder', 2),
))
def execute(self, context):
org_image_size = None
scn = context.scene
active_file = Path(self.filepath)
if len(self.files) == 1 and active_file.suffix.lower() in ('.json', '.psd'):
json_path = None
print('active_file.suffix.lower(): ', active_file.suffix.lower())
if active_file.suffix.lower() == '.psd':
print('Is a PSD')
## Export layers and create json setup file
# Export passes in a 'render' or 'render_hd' folder aside psd
json_path = export_psd_bg(str(active_file))
elif active_file.suffix.lower() == '.json':
print('Is a json')
# Use json data to batch import
json_path = active_file
if not json_path:
self.report({'ERROR'}, 'No json path to load, you can try loading from psd or selecting image file directly')
return {'CANCELLED'}
file_list, org_image_size = get_json_infos(json_path)
folder = Path(json_path).parent # render folder
else:
folder = active_file.parent
# Filter out json (we may want ot import the PSD as imagelisted in bpy.path.extensions_image)
file_list = [folder / f.name for f in self.files if Path(f.name).suffix in bpy.path.extensions_image]
if not file_list:
self.report({'ERROR'}, 'Image file list is empty')
return {'CANCELLED'}
## simple_list
# existing_backgrounds = [o for o in context.scene.objects if o.get('is_background')]
# existing_holders = [o for o in context.scene.objects if o.name.startswith(PREFIX) and o.type == 'MESH' and o.children]
## Has dict
# existing_backgrounds = {o : img_info for o in context.scene.objects if o.get('is_background') and (img_info := o.get('is_background'))}
# FIXME: Use existing background custom prop? : o.get('is_background')
## list of Tuples : [(plane_object, img_data, transparency_value), ...]
import_planes(file_list, import_type=self.import_type, image_size=org_image_size)
return {"FINISHED"}
classes = (
BPM_OT_import_bg_images,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)