__init__.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. # ----------------------------------------------------------
  2. # File __init__.py
  3. # ----------------------------------------------------------
  4. # Imports
  5. # Check if this add-on is being reloaded
  6. if "bpy" in locals():
  7. # reloading .py files
  8. import bpy
  9. import importlib
  10. # from . import zs_renderscene as zsrs
  11. # importlib.reload(zsrs)
  12. # or if this is the first load of this add-on
  13. else:
  14. import bpy
  15. import json
  16. from pathlib import Path
  17. from dataclasses import dataclass
  18. from mathutils import Euler, Vector, Quaternion, Matrix
  19. import math
  20. import os
  21. import base64
  22. import numpy as np
  23. import shutil
  24. # from . import zs_renderscene as zsrs # noqa
  25. # Addon info
  26. bl_info = {
  27. "name": "ZS Stable Diffusion Connection V0.0.1",
  28. "author": "Sergiu <sergiu@zixelise.com>",
  29. "Version": (0, 0, 1),
  30. "blender": (4, 00, 0),
  31. "category": "Scene",
  32. "description": "Stable Diffusion Connection",
  33. }
  34. # -------------------------------------------------------------------
  35. # Functions
  36. # -------------------------------------------------------------------
  37. @dataclass
  38. class AssetData:
  39. path: str
  40. collection_name: str
  41. type: str
  42. product_asset = AssetData(
  43. path="sample_scene/01_Products", collection_name="01_Products", type="product"
  44. )
  45. element_asset = AssetData(
  46. path="sample_scene/02_Elements", collection_name="02_Elements", type="asset"
  47. )
  48. basic_shapes_asset = AssetData(
  49. path="sample_scene/03_BasicShapes",
  50. collection_name="03_BasicShapes",
  51. type="shape",
  52. )
  53. def convert_base64_string_to_object(base64_string):
  54. bytes = base64.b64decode(base64_string)
  55. string = bytes.decode("ascii")
  56. return json.loads(string)
  57. return string
  58. def load_scene():
  59. print("Loading Scene")
  60. # load scene data
  61. scene_data = load_scene_data()
  62. print(scene_data)
  63. # create parent collections
  64. create_parent_collections(product_asset.collection_name)
  65. create_parent_collections(element_asset.collection_name)
  66. create_parent_collections(basic_shapes_asset.collection_name)
  67. create_parent_collections("05_Cameras")
  68. # append products
  69. products_data = load_objects_data(scene_data, product_asset.type)
  70. for index, product in enumerate(products_data):
  71. append_objects(product, index, product_asset)
  72. # append elements
  73. elements_data = load_objects_data(scene_data, element_asset.type)
  74. for index, product in enumerate(elements_data):
  75. append_objects(product, index, element_asset)
  76. # append shapes
  77. basic_shapes_data = load_objects_data(scene_data, basic_shapes_asset.type)
  78. for index, product in enumerate(basic_shapes_data):
  79. append_objects(product, index, basic_shapes_asset)
  80. # set lighting
  81. set_environment(scene_data)
  82. # set camera
  83. create_cameras(scene_data)
  84. # rename outputs
  85. set_output_paths(
  86. "D://Git//ap-canvas-creation-module//03_blender//sd_blender//sample_scene//Renders",
  87. scene_data["project_id"],
  88. )
  89. # setup compositing
  90. set_cryptomatte_objects("01_Products", "mask_product")
  91. def invert_id_name(json_data):
  92. for obj in json_data["scene"]["objects"]:
  93. obj["name"], obj["id"] = obj["id"], obj["name"]
  94. return json_data
  95. def load_scene_data():
  96. # print("Loading Scene Data")
  97. # # load scene data
  98. # # to be replaced with actual data
  99. # # open scene_info.json
  100. # script_path = Path(__file__).resolve()
  101. # scene_data_path = script_path.parent / "sample_scene" / "scene_info.json"
  102. # with scene_data_path.open() as file:
  103. # scene_data = json.load(file)
  104. # print(scene_data)
  105. # return scene_data
  106. # load scene data
  107. print("Loading Scene Data")
  108. if bpy.context.scene.load_local_DB:
  109. loaded_scene_data = bpy.context.scene.config_string
  110. # check if loaded_scene_data is base64 encoded
  111. if loaded_scene_data.startswith("ey"):
  112. scene_data = convert_base64_string_to_object(loaded_scene_data)
  113. else:
  114. scene_data = json.loads(loaded_scene_data)
  115. else:
  116. scene_data = json.loads(bpy.context.scene.shot_info_ai)
  117. # invert_scene_data = invert_id_name(scene_data)
  118. return scene_data
  119. def load_objects_data(scene_data, object_type: str):
  120. print("Loading Assets Data")
  121. # load assets data
  122. objects_data = []
  123. for object in scene_data["scene"]["objects"]:
  124. if object["group_type"] == object_type:
  125. # get additional object data by id and combine with object data
  126. object_data = get_object_data_by_id(object["id"])
  127. if object_data:
  128. # temporary fix
  129. # object_data = get_object_data_by_id(object["name"])
  130. object.update(object_data)
  131. objects_data.append(object)
  132. else:
  133. print("Object not found in database", object["id"], object["name"])
  134. return objects_data
  135. # to be replaced with actual data
  136. def get_object_data_by_id(object_id: str):
  137. print("Getting Object Data")
  138. # open assets_database.json
  139. script_path = Path(__file__).resolve()
  140. assets_data_path = script_path.parent / "sample_scene" / "assets_database.json"
  141. with assets_data_path.open() as file:
  142. assets_data = json.load(file)
  143. # get object data by id
  144. for object in assets_data:
  145. if object["id"] == object_id:
  146. return object
  147. def get_hdri_data_by_id(object_id: str):
  148. print("Getting HDRI Data")
  149. # open assets_database.json
  150. script_path = Path(__file__).resolve()
  151. assets_data_path = script_path.parent / "sample_scene" / "lighting_database.json"
  152. with assets_data_path.open() as file:
  153. assets_data = json.load(file)
  154. # get object data by id
  155. for object in assets_data:
  156. if object["id"] == object_id:
  157. return object
  158. def append_objects(asset_info, index, asset_data: AssetData):
  159. print("Appending Objects")
  160. blendFileName = asset_info["name"]
  161. # visibleLayersJSONName = productInfo["Version"]
  162. # activeSwitchMaterials = json.dumps(productInfo["ActiveMaterials"])
  163. collectionName = blendFileName + "_" + str(index)
  164. append_active_layers(collectionName, asset_info, asset_data)
  165. # replace_switch_materials(shotInfo, productInfo["ActiveMaterials"])
  166. link_collection_to_collection(
  167. asset_data.collection_name, bpy.data.collections[collectionName]
  168. )
  169. def append_active_layers(newCollectionName, product_info, asset_data: AssetData):
  170. utility_collections = [
  171. "MaterialLibrary",
  172. "Animation_Controller",
  173. "Animation_Rig",
  174. "Animation_Target",
  175. ]
  176. # visible_layers = utility_collections + product_info["VisibleLayers"]
  177. visible_layers = utility_collections
  178. script_path = Path(__file__).resolve().parent
  179. filePath = str(
  180. script_path
  181. / asset_data.path
  182. / product_info["name"]
  183. / "BLEND"
  184. / (product_info["name"] + ".blend")
  185. )
  186. print(filePath)
  187. # delete all objects and collections from product collection
  188. create_parent_collections(newCollectionName)
  189. # append active collections
  190. with bpy.data.libraries.load(filePath) as (data_from, data_to):
  191. data_to.collections = []
  192. for name in data_from.collections:
  193. if name in visible_layers:
  194. data_to.collections.append(name)
  195. if "NonConfigurable" in name:
  196. data_to.collections.append(name)
  197. # link appended colections to newCollection
  198. for collection in data_to.collections:
  199. # try:
  200. # bpy.context.scene.collection.children.link(collection)
  201. # except:
  202. # print(collection)
  203. link_collection_to_collection(newCollectionName, collection)
  204. # hide utility collections
  205. for utilityCollectionName in utility_collections:
  206. if utilityCollectionName in collection.name:
  207. # rename utility collections
  208. collection.name = newCollectionName + "_" + utilityCollectionName
  209. hide_collection(collection)
  210. # need to redo this in the future
  211. if "Animation_Target" in collection.name:
  212. # set the x location
  213. collection.objects[0].location.x = product_info["properties"][
  214. "transform"
  215. ]["position"][0]
  216. # set the y location
  217. collection.objects[0].location.y = -product_info["properties"][
  218. "transform"
  219. ]["position"][2]
  220. # set the z location
  221. collection.objects[0].location.z = product_info["properties"][
  222. "transform"
  223. ]["position"][1]
  224. # collection.objects[0].location = product_info["properties"][
  225. # "transform"
  226. # ]["position"]
  227. # collection.objects[0].rotation_euler = product_info["properties"][
  228. # "transform"
  229. # ]["rotation"]
  230. rotation_in_degrees = product_info["properties"]["transform"][
  231. "rotation"
  232. ]
  233. rotation_in_degrees[0] = rotation_in_degrees[0] + 90
  234. # set object rotation in euler from radians
  235. collection.objects[0].rotation_euler = (
  236. math.radians(rotation_in_degrees[0]),
  237. math.radians(rotation_in_degrees[2]),
  238. math.radians(rotation_in_degrees[1]),
  239. )
  240. collection.objects[0].scale = product_info["properties"]["transform"][
  241. "scale"
  242. ]
  243. # make all objects in collection local
  244. for obj in bpy.data.collections[newCollectionName].all_objects:
  245. if obj.type == "MESH":
  246. obj.make_local()
  247. obj.data.make_local()
  248. # remove duplicated material slots
  249. mats = bpy.data.materials
  250. for obj in bpy.data.collections[newCollectionName].all_objects:
  251. for slot in obj.material_slots:
  252. part = slot.name.rpartition(".")
  253. if part[2].isnumeric() and part[0] in mats:
  254. slot.material = mats.get(part[0])
  255. def create_parent_collections(group_name: str):
  256. if collection_exists(group_name):
  257. remove_collection_and_objects(group_name)
  258. else:
  259. create_collection(group_name)
  260. def set_environment(scene_data):
  261. # Find the group named NG_Canvas_Background in the Blender world
  262. world = bpy.context.scene.world
  263. if world is not None:
  264. # Get the node group named NG_Canvas_Background
  265. node_group = world.node_tree.nodes.get("NG_Canvas_Background")
  266. if node_group is not None:
  267. # Set the group's properties from scene_data
  268. node_group.inputs[0].default_value = float(
  269. scene_data["scene"]["environment"]["lighting"]["rotation"]
  270. )
  271. node_group.inputs[1].default_value = float(
  272. scene_data["scene"]["environment"]["lighting"]["intensity"]
  273. )
  274. if scene_data["scene"]["environment"]["lighting"]["visible"] == True:
  275. node_group.inputs[2].default_value = 1.0
  276. else:
  277. node_group.inputs[2].default_value = 0.0
  278. node_group.inputs[3].default_value = (
  279. scene_data["scene"]["environment"]["background"]["color"]["r"],
  280. scene_data["scene"]["environment"]["background"]["color"]["g"],
  281. scene_data["scene"]["environment"]["background"]["color"]["b"],
  282. 1.0,
  283. )
  284. hdri_data = get_hdri_data_by_id(
  285. scene_data["scene"]["environment"]["lighting"]["id"]
  286. )
  287. # go inside the node group, and find the image texture node, and set the image to the one from the scene data
  288. for node in node_group.node_tree.nodes:
  289. if node.name == "environment_map":
  290. node.image = bpy.data.images.load(
  291. str(
  292. Path(__file__).resolve().parent
  293. / "sample_scene"
  294. / "05_Lighting"
  295. / "HDRI"
  296. / (hdri_data["name"] + ".exr")
  297. )
  298. )
  299. else:
  300. print("Group 'NG_Canvas_Background' not found")
  301. def calculate_focal_length(fov, film_height):
  302. # Convert FOV from degrees to radians
  303. fov_rad = math.radians(fov)
  304. # Calculate the focal length
  305. focal_length = (film_height / 2) / math.tan(fov_rad / 2)
  306. return focal_length
  307. def quaternion_multiply(q1, q2):
  308. """
  309. Multiplies two quaternions.
  310. q1 and q2 are arrays or lists of length 4.
  311. Returns the resulting quaternion as a NumPy array.
  312. """
  313. w1, x1, y1, z1 = q1
  314. w2, x2, y2, z2 = q2
  315. w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
  316. x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
  317. y = w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2
  318. z = w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2
  319. return np.array([w, x, y, z])
  320. def create_cameras(scene_data):
  321. # # Get the 05_Cameras collection, or create it if it doesn't exist
  322. collection_name = "05_Cameras"
  323. if collection_name in bpy.data.collections:
  324. collection = bpy.data.collections[collection_name]
  325. else:
  326. return
  327. # Assuming `scene_data` and `collection` are already defined
  328. for camera_data in scene_data["scene"]["cameras"]:
  329. # Create a new camera object
  330. bpy.ops.object.camera_add()
  331. # Get the newly created camera
  332. camera = bpy.context.object
  333. # Set the camera's name
  334. camera.name = camera_data["name"]
  335. # Set the camera's position
  336. position = camera_data["properties"]["transform"]["position"]
  337. camera.location.x = position[0]
  338. camera.location.y = -position[2]
  339. camera.location.z = position[1]
  340. # Set the camera's rotation
  341. # # euler
  342. # rotation_euler = camera_data["properties"]["transform"]["rotation"]
  343. # rotation_euler = Euler(
  344. # (
  345. # math.radians(rotation_euler[0] + 90),
  346. # math.radians(-rotation_euler[2]),
  347. # math.radians(rotation_euler[1]),
  348. # ),
  349. # "XYZ",
  350. # )
  351. # quaternion
  352. rotation_quat_data = camera_data["properties"]["transform"]["rotation"]
  353. # rotation_quat = (
  354. # rotation_quat[3],
  355. # rotation_quat[0],
  356. # rotation_quat[1],
  357. # rotation_quat[2],
  358. # )
  359. # new_quat = Quaternion((2**0.5 / 2, 2**0.5 / 2, 0.0, 0.0))
  360. # current_quat = Quaternion(rotation_quat)
  361. # result_quat = current_quat @ new_quat
  362. # rotation_quat = (result_quat.w, result_quat.x, result_quat.y, result_quat.z)
  363. rotation_quat = [
  364. rotation_quat_data[3],
  365. rotation_quat_data[0],
  366. rotation_quat_data[1],
  367. rotation_quat_data[2],
  368. ] # Example quaternion
  369. # new_quat = [2**0.5 / 2, 2**0.5 / 2, 0.0, 0.0]
  370. # result_quat = quaternion_multiply(rotation_quat, new_quat)
  371. # Example quaternion from GLTF: [x, y, z, w]
  372. gltf_quat = [0.0, 0.707, 0.0, 0.707]
  373. # Convert the GLTF quaternion to Blender space (Y-up to Z-up)
  374. converted_quat = Quaternion(
  375. [
  376. rotation_quat_data[3],
  377. rotation_quat_data[0],
  378. rotation_quat_data[1],
  379. rotation_quat_data[2],
  380. ]
  381. )
  382. # Define the camera correction quaternion (from GLTF file)
  383. camera_correction = Quaternion((2**0.5 / 2, 2**0.5 / 2, 0.0, 0.0))
  384. # Apply the camera correction to the converted quaternion
  385. corrected_quat = camera_correction @ converted_quat
  386. # Apply the corrected quaternion to the camera's rotation
  387. camera.rotation_mode = "QUATERNION"
  388. camera.rotation_quaternion = corrected_quat
  389. # camera.rotation_mode = "QUATERNION"
  390. # camera.rotation_quaternion = rotation_quat
  391. # Apply the local rotation to the camera
  392. # Set the camera's lens properties
  393. lens = camera_data["properties"]["lens"]
  394. type_mapping = {
  395. "PERSPECTIVE": "PERSP",
  396. "ORTHOGRAPHIC": "ORTHO",
  397. "PANORAMIC": "PANO",
  398. }
  399. camera.data.lens = lens["focalLength"]
  400. camera.data.type = type_mapping.get(lens["type"].upper(), "PERSP")
  401. camera.data.clip_start = lens["near"]
  402. camera.data.clip_end = lens["far"]
  403. # Add the camera to the 05_Cameras collection
  404. collection.objects.link(camera)
  405. # Unlink the camera from the scene collection
  406. # check all objects in scene collection, if camera is there, unlink it
  407. for obj in bpy.context.scene.collection.objects:
  408. if obj.name == camera.name:
  409. bpy.context.scene.collection.objects.unlink(camera)
  410. # Set the camera as the active camera if "active" is true
  411. if camera_data["properties"]["active"]:
  412. bpy.context.scene.camera = camera
  413. def set_output_paths(base_path, project_name):
  414. # check if folder exist, if not create it
  415. folder_path = base_path + "//" + project_name
  416. if not os.path.exists(folder_path):
  417. os.makedirs(folder_path)
  418. # Get the current scene
  419. scene = bpy.context.scene
  420. # Check if the scene has a compositor node tree
  421. if scene.node_tree:
  422. # Iterate over all nodes in the node tree
  423. for node in scene.node_tree.nodes:
  424. # Check if the node is an output node
  425. if node.type == "OUTPUT_FILE":
  426. # Set the base path of the output node
  427. node.base_path = folder_path
  428. # Iterate over all file slots of the output node
  429. # for file_slot in node.file_slots:
  430. # # Set the path of the file slot
  431. # file_slot.path = project_name
  432. def set_cryptomatte_objects(collection_name, node_name):
  433. # Get all objects in the specified collection
  434. objects = bpy.data.collections[collection_name].all_objects
  435. # Convert the objects to a list
  436. object_names = [obj.name for obj in objects]
  437. print(object_names)
  438. # Get the current scene
  439. scene = bpy.context.scene
  440. # Check if the scene has a compositor node tree
  441. if scene.node_tree:
  442. # Iterate over all nodes in the node tree
  443. for node in scene.node_tree.nodes:
  444. # Check if the node is a Cryptomatte node with the specified name
  445. if node.type == "CRYPTOMATTE_V2" and node.name == node_name:
  446. # Set the Matte ID objects of the node
  447. node.matte_id = ",".join(object_names)
  448. # -------------------------------------------------------------------
  449. # Utilities
  450. # -------------------------------------------------------------------
  451. def remove_collection_and_objects(collection_name):
  452. oldObjects = list(bpy.data.collections[collection_name].all_objects)
  453. for obj in oldObjects:
  454. bpy.data.objects.remove(obj, do_unlink=True)
  455. old_collection = bpy.data.collections[collection_name]
  456. if old_collection is not None:
  457. old_collection_names = get_subcollection_names(old_collection)
  458. else:
  459. print("Collection not found.")
  460. # print line break
  461. print("-----------------------------------------------------------------")
  462. print(old_collection_names)
  463. print("-----------------------------------------------------------------")
  464. for old_collection_name in old_collection_names:
  465. for collection in bpy.data.collections:
  466. if collection.name == old_collection_name:
  467. bpy.data.collections.remove(collection)
  468. bpy.ops.outliner.orphans_purge(
  469. do_local_ids=True, do_linked_ids=True, do_recursive=True
  470. )
  471. def get_subcollection_names(collection):
  472. subcollection_names = []
  473. for child in collection.children:
  474. subcollection_names.append(child.name)
  475. subcollection_names.extend(get_subcollection_names(child))
  476. return subcollection_names
  477. def select_objects_in_collection(collection):
  478. """Recursively select all objects in the given collection and its subcollections."""
  479. for obj in collection.objects:
  480. obj.select_set(True)
  481. for subcollection in collection.children:
  482. select_objects_in_collection(subcollection)
  483. def link_collection_to_collection(parentCollectionName, childCollection):
  484. if bpy.context.scene.collection.children:
  485. parentCollection = bpy.context.scene.collection.children.get(
  486. parentCollectionName
  487. )
  488. # Add it to the main collection
  489. # childCollection = bpy.context.scene.collection.children.get(childCollection)
  490. parentCollection.children.link(childCollection)
  491. # if child collection is in scene collection unlink it
  492. if bpy.context.scene.collection.children.get(childCollection.name):
  493. bpy.context.scene.collection.children.unlink(childCollection)
  494. # bpy.context.scene.collection.children.unlink(childCollection)
  495. # link collection to collection
  496. def link_collection_to_collection_old(parentCollectionName, childCollection):
  497. if bpy.context.scene.collection.children:
  498. parentCollection = bpy.context.scene.collection.children.get(
  499. parentCollectionName
  500. )
  501. # Add it to the main collection
  502. try:
  503. childCollection = bpy.data.collections[childCollection]
  504. except:
  505. print("Collection not found.")
  506. return
  507. parentCollection.children.link(childCollection)
  508. bpy.context.scene.collection.children.unlink(childCollection)
  509. # function that checks if a collection exists
  510. def collection_exists(collection_name):
  511. return collection_name in bpy.data.collections
  512. # function that creates a new collection and adds it to the scene
  513. def create_collection(collection_name):
  514. new_collection = bpy.data.collections.new(collection_name)
  515. bpy.context.scene.collection.children.link(new_collection)
  516. def hide_collection(collection):
  517. collection.hide_render = True
  518. collection.hide_viewport = True
  519. def check_if_selected_objects_have_parent(self):
  520. for obj in bpy.context.selected_objects:
  521. if obj.parent is None:
  522. message = f"Object {obj.name} has no parent"
  523. self.report({"ERROR"}, message)
  524. return False
  525. return True
  526. def add_rig_controller_to_selection(self):
  527. # add "Rig_Controller_Main" to the selection
  528. has_controller_object = False
  529. for obj in bpy.data.objects:
  530. if obj.name == "Rig_Controller_Main":
  531. if obj.hide_viewport:
  532. self.report({"ERROR"}, "Rig_Controller_Main is hidden")
  533. return has_controller_object
  534. obj.select_set(True)
  535. # if object is not visible, make it visible
  536. has_controller_object = True
  537. return has_controller_object
  538. if not has_controller_object:
  539. message = f"Rig_Controller_Main not found"
  540. self.report({"ERROR"}, message)
  541. print("Rig_Controller_Main not found")
  542. return has_controller_object
  543. def select_objects_in_collection(collection):
  544. """Recursively select all objects in the given collection and its subcollections."""
  545. for obj in collection.objects:
  546. obj.select_set(True)
  547. for subcollection in collection.children:
  548. select_objects_in_collection(subcollection)
  549. def check_if_object_has_principled_material(obj):
  550. for slot in obj.material_slots:
  551. # if more than one slot is principled, return
  552. for node in slot.material.node_tree.nodes:
  553. # print(node.type)
  554. if node.type == "BSDF_PRINCIPLED":
  555. return True
  556. else:
  557. print("Object has no principled material", obj.name)
  558. return False
  559. return True
  560. def unhide_all_objects():
  561. # show all objects using operator
  562. bpy.ops.object.hide_view_clear()
  563. # -------------------------------------------------------------------
  564. # Scene optimization
  565. # -------------------------------------------------------------------
  566. def export_non_configurable_to_fbx():
  567. # Get the current .blend file path
  568. blend_filepath = bpy.data.filepath
  569. if not blend_filepath:
  570. print("Save the .blend file first.")
  571. return
  572. # Get the parent directory of the .blend file
  573. blend_dir = os.path.dirname(blend_filepath)
  574. parent_dir = os.path.dirname(blend_dir)
  575. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  576. # Create the FBX export path
  577. fbx_export_path = os.path.join(parent_dir, "FBX", f"{blend_filename}.fbx")
  578. # Ensure the FBX directory exists
  579. os.makedirs(os.path.dirname(fbx_export_path), exist_ok=True)
  580. # Deselect all objects
  581. bpy.ops.object.select_all(action="DESELECT")
  582. # Select all objects in the NonConfigurable collection
  583. collection_name = "NonConfigurable"
  584. if collection_name in bpy.data.collections:
  585. collection = bpy.data.collections[collection_name]
  586. for obj in collection.objects:
  587. obj.select_set(True)
  588. else:
  589. print(f"Collection '{collection_name}' not found.")
  590. return
  591. def export_scene_to_fbx(self):
  592. # Ensure the .blend file is saved
  593. if not bpy.data.is_saved:
  594. print("Save the .blend file first.")
  595. self.report({"ERROR"}, "Save the .blend file first.")
  596. return
  597. # Get the current .blend file path
  598. blend_filepath = bpy.data.filepath
  599. if not blend_filepath:
  600. print("Unable to get the .blend file path.")
  601. return
  602. # Get the parent directory of the .blend file
  603. blend_dir = os.path.dirname(blend_filepath)
  604. parent_dir = os.path.dirname(blend_dir)
  605. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  606. # Create the FBX export path
  607. fbx_export_path = os.path.join(parent_dir, "FBX", f"{blend_filename}.fbx")
  608. # Ensure the FBX directory exists
  609. os.makedirs(os.path.dirname(fbx_export_path), exist_ok=True)
  610. # unhide all objects
  611. unhide_all_objects()
  612. # Deselect all objects
  613. bpy.ops.object.select_all(action="DESELECT")
  614. # Select all objects in the NonConfigurable collection and its subcollections
  615. collection_name = "NonConfigurable"
  616. if collection_name in bpy.data.collections:
  617. collection = bpy.data.collections[collection_name]
  618. select_objects_in_collection(collection)
  619. else:
  620. print(f"Collection '{collection_name}' not found.")
  621. return
  622. # check if all objects selected have a parent, if not return
  623. if not check_if_selected_objects_have_parent(self):
  624. return
  625. if not add_rig_controller_to_selection(self):
  626. return
  627. # Export selected objects to FBX
  628. bpy.ops.export_scene.fbx(
  629. filepath=fbx_export_path,
  630. use_selection=True,
  631. global_scale=1.0,
  632. apply_unit_scale=True,
  633. bake_space_transform=False,
  634. object_types={"MESH", "ARMATURE", "EMPTY"},
  635. use_mesh_modifiers=True,
  636. mesh_smooth_type="FACE",
  637. use_custom_props=True,
  638. # bake_anim=False,
  639. )
  640. print(f"Exported to {fbx_export_path}")
  641. def export_scene_to_glb(self):
  642. # Ensure the .blend file is saved
  643. if not bpy.data.is_saved:
  644. print("Save the .blend file first.")
  645. self.report({"ERROR"}, "Save the .blend file first.")
  646. return
  647. # Get the current .blend file path
  648. blend_filepath = bpy.data.filepath
  649. if not blend_filepath:
  650. print("Unable to get the .blend file path.")
  651. return
  652. # Get the parent directory of the .blend file
  653. blend_dir = os.path.dirname(blend_filepath)
  654. parent_dir = os.path.dirname(blend_dir)
  655. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  656. # Create the GLB export path
  657. glb_export_path = os.path.join(parent_dir, "WEB", f"{blend_filename}.glb")
  658. # Ensure the GLB directory exists
  659. os.makedirs(os.path.dirname(glb_export_path), exist_ok=True)
  660. # unhide all objects
  661. unhide_all_objects()
  662. # Deselect all objects
  663. bpy.ops.object.select_all(action="DESELECT")
  664. # Select all objects in the NonConfigurable collection and its subcollections
  665. collection_name = "WebGL"
  666. if collection_name in bpy.data.collections:
  667. collection = bpy.data.collections[collection_name]
  668. select_objects_in_collection(collection)
  669. else:
  670. print(f"Collection '{collection_name}' not found.")
  671. return
  672. if not check_if_selected_objects_have_parent(self):
  673. return
  674. # check if all objects selected have a parent, if not return
  675. if not add_rig_controller_to_selection(self):
  676. return
  677. # # for each selected objects, check if the the material is principled, if not return
  678. # for obj in bpy.context.selected_objects:
  679. # if not check_if_object_has_principled_material(obj):
  680. # message = f"Object {obj.name} has no principled material"
  681. # self.report({"ERROR"}, message)
  682. # return
  683. # Export selected objects to GLB
  684. bpy.ops.export_scene.gltf(
  685. filepath=glb_export_path,
  686. export_format="GLB",
  687. use_selection=True,
  688. export_apply=True,
  689. export_animations=False,
  690. export_yup=True,
  691. export_cameras=False,
  692. export_lights=False,
  693. export_materials="EXPORT",
  694. export_normals=True,
  695. export_tangents=True,
  696. export_morph=False,
  697. export_skins=False,
  698. export_draco_mesh_compression_enable=False,
  699. export_draco_mesh_compression_level=6,
  700. export_draco_position_quantization=14,
  701. export_draco_normal_quantization=10,
  702. export_draco_texcoord_quantization=12,
  703. export_draco_color_quantization=10,
  704. export_draco_generic_quantization=12,
  705. export_keep_originals=False,
  706. export_texture_dir="",
  707. )
  708. print(f"Exported to {glb_export_path}")
  709. def copy_and_relink_textures(collection_name):
  710. # Ensure the target directory exists
  711. target_directory = bpy.path.abspath("//..")
  712. textures_directory = os.path.join(target_directory, "0_Textures")
  713. os.makedirs(textures_directory, exist_ok=True)
  714. # Get the collection
  715. collection = bpy.data.collections.get(collection_name)
  716. if not collection:
  717. print(f"Collection '{collection_name}' not found.")
  718. return
  719. # Iterate through each object in the collection
  720. for obj in collection.objects:
  721. if obj.type != "MESH":
  722. continue
  723. # Iterate through each material of the object
  724. for mat_slot in obj.material_slots:
  725. material = mat_slot.material
  726. if not material:
  727. continue
  728. # Check if the material contains any image textures
  729. if material.use_nodes:
  730. for node in material.node_tree.nodes:
  731. if node.type == "TEX_IMAGE":
  732. image = node.image
  733. if image:
  734. # Copy the image texture to the target directory
  735. src_path = bpy.path.abspath(image.filepath)
  736. filename = os.path.basename(src_path)
  737. dest_path = os.path.join(textures_directory, filename)
  738. # Check if the source and destination paths are the same
  739. if os.path.abspath(src_path) != os.path.abspath(dest_path):
  740. # Check if the file already exists in the destination directory
  741. if not os.path.exists(dest_path):
  742. shutil.copy(src_path, dest_path)
  743. else:
  744. print(
  745. f"File '{filename}' already exists in '{textures_directory}', relinking."
  746. )
  747. # Relink the image texture to the new location
  748. image.filepath = bpy.path.relpath(dest_path)
  749. image.reload()
  750. print(f"Textures copied and relinked to '{textures_directory}'.")
  751. def set_assets_render_output_paths():
  752. # Get the current scene
  753. scene = bpy.context.scene
  754. target_directory = bpy.path.abspath("//..")
  755. custom_folder = os.path.join(target_directory, "PNG")
  756. blender_file_name = os.path.splitext(bpy.path.basename(bpy.data.filepath))[0]
  757. components = blender_file_name.split("_")
  758. if len(components) != 7:
  759. raise ValueError(
  760. "Blender file name must be in the format 'Brand_AssetName_Year_ContentUsage_ContentType_AssetType_AssetNumber'"
  761. )
  762. brand = components[0]
  763. asset_name = components[1]
  764. year = components[2]
  765. content_usage = components[3]
  766. content_type = components[4]
  767. asset_type = components[5]
  768. asset_number = components[6]
  769. imag_asset_type = "IMG"
  770. # Construct the new .blend file name
  771. image_name = f"{brand}_{asset_name}_{year}_{content_usage}_{content_type}_{imag_asset_type}_{asset_number}_"
  772. # Ensure the scene has a compositor node tree
  773. if not scene.use_nodes:
  774. print("Scene does not use nodes.")
  775. return
  776. node_tree = scene.node_tree
  777. # Search for the ZS_Canvas_Output group node
  778. for node in node_tree.nodes:
  779. if node.type == "GROUP" and node.node_tree.name == "ZS_Canvas_Output":
  780. # Check inside the group for all file output nodes
  781. for sub_node in node.node_tree.nodes:
  782. if sub_node.type == "OUTPUT_FILE":
  783. # Set the base_path to the custom folder
  784. sub_node.base_path = custom_folder
  785. # Set the path for each file output slot to the Blender file name
  786. for output in sub_node.file_slots:
  787. output.path = image_name
  788. print("Output paths set.")
  789. # -------------------------------------------------------------------
  790. # Operators
  791. # -------------------------------------------------------------------
  792. # load scene operator
  793. class ZSSD_OT_LoadScene(bpy.types.Operator):
  794. bl_idname = "zs_sd_loader.load_scene"
  795. bl_label = "Load Scene"
  796. bl_description = "Load Scene"
  797. def execute(self, context):
  798. load_scene()
  799. return {"FINISHED"}
  800. # canvas exporter operator
  801. class ZSSD_OT_ExportAssets(bpy.types.Operator):
  802. bl_idname = "zs_canvas.export_assets"
  803. bl_label = "Export Assets"
  804. bl_description = "Export Scene Assets to FBX and GLB"
  805. def execute(self, context):
  806. copy_and_relink_textures("NonConfigurable")
  807. copy_and_relink_textures("WebGL")
  808. set_assets_render_output_paths()
  809. export_scene_to_fbx(self)
  810. export_scene_to_glb(self)
  811. return {"FINISHED"}
  812. # parent class for panels
  813. class ZSSDPanel:
  814. bl_space_type = "VIEW_3D"
  815. bl_region_type = "UI"
  816. bl_category = "ZS SD Loader"
  817. # -------------------------------------------------------------------
  818. # Draw
  819. # -------------------------------------------------------------------
  820. # Panels
  821. class ZSSD_PT_Main(ZSSDPanel, bpy.types.Panel):
  822. bl_label = "SD Loader"
  823. def draw(self, context):
  824. layout = self.layout
  825. scene = context.scene
  826. col = layout.column()
  827. self.is_connected = False
  828. col.label(text="Stable Diffusion Connection")
  829. col.prop(context.scene, "load_local_DB")
  830. col.prop(context.scene, "config_string")
  831. # load scene button
  832. col.operator("zs_sd_loader.load_scene", text="Load Scene")
  833. col.separator()
  834. # export assets button
  835. col.operator("zs_canvas.export_assets", text="Export Assets")
  836. # modify after making products
  837. blender_classes = [
  838. ZSSD_PT_Main,
  839. ZSSD_OT_LoadScene,
  840. ZSSD_OT_ExportAssets,
  841. ]
  842. def register():
  843. # register classes
  844. for blender_class in blender_classes:
  845. bpy.utils.register_class(blender_class)
  846. bpy.types.Scene.shot_info_ai = bpy.props.StringProperty(
  847. name="Shot Info",
  848. )
  849. bpy.types.Scene.config_string = bpy.props.StringProperty( # type: ignore
  850. name="Configuration String",
  851. )
  852. bpy.types.Scene.load_local_DB = bpy.props.BoolProperty( # type: ignore
  853. name="Load Local DB",
  854. )
  855. # Has to be afqter class registering to correctly register property
  856. # register global properties
  857. # register list
  858. # list data
  859. # bpy.types.Scene.zs_product_list = bpy.props.CollectionProperty(
  860. # type=ZS_Product_ListItem)
  861. # current item in list
  862. def unregister():
  863. # unregister classes
  864. for blender_class in blender_classes:
  865. bpy.utils.unregister_class(blender_class)
  866. # unregister global properties
  867. del bpy.types.Scene.shot_info_ai
  868. del bpy.types.Scene.config_string
  869. del bpy.types.Scene.load_local_DB
  870. # unregister list items
  871. # del bpy.types.Scene.my_list
  872. # del bpy.types.Scene.product_product_list_index