2025-07-01

This commit is contained in:
2026-03-17 14:30:01 -06:00
parent f9a22056dd
commit 62b5978595
4579 changed files with 1257472 additions and 0 deletions
@@ -0,0 +1,403 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: __init__.py
# brief: Addon registration
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
bl_info = {
"name": "Adobe Substance 3D add-on for Blender",
"author": "Adobe Inc.",
"location": "Node Editor Toolbar -- Shift-Ctrl-U",
"version": (2, 1, 1),
"blender": (2, 90, 0),
"description": "Adobe Substance 3D add-on for Blender",
'tracker_url': "https://discord.gg/substance3d",
"category": "Node"
}
try:
import traceback
import bpy
from bpy.utils import register_class, unregister_class
from .persistance import SUBSTANCE_Persistance
from .api import SUBSTANCE_Api
from .utils import SUBSTANCE_Utils
from .thread_ops import SUBSTANCE_Threads
from .callbacks.render import Server_POST_Render
from .callbacks.link import Server_POST_Link
from .common import Code_Response, UI_SPACES, ADDON_PACKAGE, SHORTCUT_CLASS_NAME
from .ui.presets import SUBSTANCE_MT_PresetOptions
from .ui.shortcut import SubstanceShortcutMenuFactory
from .ui.sbsar import (
SubstanceMainPanelFactory,
SubstanceGraphPanelFactory,
SubstancePreviewFactory,
SubstanceOutputsPanelFactory,
SubstanceInputsPanelFactory,
SUBSTANCE_UL_SbsarList
)
from .preferences import SUBSTANCE_AddonPreferences
from .ops.common import SUBSTANCE_OT_Message, SUBSTANCE_OT_Version
from .ops.material import SUBSTANCE_OT_SetMaterial
from .ops.toolkit import (
SUBSTANCE_OT_InstallTools,
SUBSTANCE_OT_UpdateTools,
SUBSTANCE_OT_UninstallTools,
SUBSTANCE_OT_OpenTools,
SUBSTANCE_OT_ResetTools
)
from .ops.web import (
SUBSTANCE_OT_GoToWebsite,
SUBSTANCE_OT_GetTools,
SUBSTANCE_OT_GoToShare,
SUBSTANCE_OT_GoToSource,
SUBSTANCE_OT_GoToDocs,
SUBSTANCE_OT_GoToForums,
SUBSTANCE_OT_GoToDiscord
)
from .ops.inputs import (
SUBSTANCE_OT_RandomizeSeed,
SUBSTANCE_OT_InputGroupsCollapse,
SUBSTANCE_OT_InputGroupsExpand
)
from .ops.presets import (
SUBSTANCE_OT_AddPreset,
SUBSTANCE_OT_ImportPreset,
SUBSTANCE_OT_ExportPreset,
SUBSTANCE_OT_ExportAll,
SUBSTANCE_OT_DeletePreset,
SUBSTANCE_OT_DeletePresetModal
)
from .ops.sbsar import (
SUBSTANCE_OT_LoadSBSAR,
SUBSTANCE_OT_ApplySBSAR,
SUBSTANCE_OT_RemoveSBSAR,
SUBSTANCE_OT_ReloadSBSAR,
SUBSTANCE_OT_DuplicateSBSAR
)
from .ops.shader import (
SUBSTANCE_OT_ResetShaderPreset,
SUBSTANCE_OT_LoadShaderPresets,
SUBSTANCE_OT_RemoveShaderPresets,
SUBSTANCE_OT_SaveShaderPresets
)
from .ops.sync import (
SUBSTANCE_OT_SyncInitTools,
SUBSTANCE_OT_SyncLoadSBSAR
)
from .props.shortcuts import SUBSTANCE_PG_Shortcuts
from .props.common import SUBSTANCE_PG_Tiling, SUBSTANCE_PG_Resolution, SUBSTANCE_PG_SbsarPhysicalSize
from .props.sbsar_graph import SUBSTANCE_PG_SbsarGraph, SUBSTANCE_PG_SbsarMaterial, SUBSTANCE_PG_SbsarTiling
from .props.sbsar_input import SUBSTANCE_PG_SbsarInputGroup, SUBSTANCE_PG_SbsarInput
from .props.sbsar_output import SUBSTANCE_PG_SbsarOutput, SUBSTANCE_PG_SbsarOutputChannelUse
from .props.sbsar_preset import SUBSTANCE_PG_SbsarPreset
from .props.sbsar import SUBSTANCE_PG_Sbsar
from .props.shader import SUBSTANCE_PG_ShaderPreset, SUBSTANCE_PG_ShaderInput, SUBSTANCE_PG_ShaderOutput
SHORTCUT_KEYMAPS = []
FACTORY_CLASSES = []
DEFAULT_CLASSES = [
# /props/common
SUBSTANCE_PG_Tiling,
SUBSTANCE_PG_Resolution,
# /props/sbsar
SUBSTANCE_PG_SbsarPhysicalSize,
SUBSTANCE_PG_SbsarInputGroup,
SUBSTANCE_PG_SbsarInput,
SUBSTANCE_PG_SbsarOutputChannelUse,
SUBSTANCE_PG_SbsarOutput,
SUBSTANCE_PG_SbsarPreset,
SUBSTANCE_PG_SbsarMaterial,
SUBSTANCE_PG_SbsarTiling,
SUBSTANCE_PG_SbsarGraph,
SUBSTANCE_PG_Sbsar,
# /props/shader
SUBSTANCE_PG_ShaderOutput,
SUBSTANCE_PG_ShaderInput,
SUBSTANCE_PG_ShaderPreset,
# /props/shortcuts
SUBSTANCE_PG_Shortcuts,
# /preferences
SUBSTANCE_AddonPreferences,
# /ops/common
SUBSTANCE_OT_Version,
SUBSTANCE_OT_Message,
# /ops/toolkit
SUBSTANCE_OT_InstallTools,
SUBSTANCE_OT_UpdateTools,
SUBSTANCE_OT_UninstallTools,
SUBSTANCE_OT_OpenTools,
SUBSTANCE_OT_ResetTools,
# /ops/web
SUBSTANCE_OT_GoToWebsite,
SUBSTANCE_OT_GetTools,
SUBSTANCE_OT_GoToShare,
SUBSTANCE_OT_GoToSource,
SUBSTANCE_OT_GoToDocs,
SUBSTANCE_OT_GoToForums,
SUBSTANCE_OT_GoToDiscord,
# /ops/inputs
SUBSTANCE_OT_RandomizeSeed,
SUBSTANCE_OT_InputGroupsCollapse,
SUBSTANCE_OT_InputGroupsExpand,
# /ops/presets
SUBSTANCE_OT_AddPreset,
SUBSTANCE_OT_ImportPreset,
SUBSTANCE_OT_ExportPreset,
SUBSTANCE_OT_ExportAll,
SUBSTANCE_OT_DeletePreset,
SUBSTANCE_OT_DeletePresetModal,
# /ops/sbsar
SUBSTANCE_OT_LoadSBSAR,
SUBSTANCE_OT_ApplySBSAR,
SUBSTANCE_OT_RemoveSBSAR,
SUBSTANCE_OT_ReloadSBSAR,
SUBSTANCE_OT_DuplicateSBSAR,
# /ops/shader
SUBSTANCE_OT_LoadShaderPresets,
SUBSTANCE_OT_RemoveShaderPresets,
SUBSTANCE_OT_SaveShaderPresets,
SUBSTANCE_OT_ResetShaderPreset,
# /ops/material
SUBSTANCE_OT_SetMaterial,
# /ops/sync
SUBSTANCE_OT_SyncInitTools,
SUBSTANCE_OT_SyncLoadSBSAR,
# /ui/presets
SUBSTANCE_MT_PresetOptions,
# /ui/sbsar
SUBSTANCE_UL_SbsarList
]
# Callback for SBSAR
def sbsar_index_changed(self, context):
SUBSTANCE_Utils.toggle_redraw(context)
# Preview Update FIX
def sbsar_redraw_changed(self, context):
try:
context.area.tag_redraw()
except Exception:
pass
post_render = Server_POST_Render()
post_link = Server_POST_Link()
def register():
# Add Panels
if len(FACTORY_CLASSES) == 0:
for _space in UI_SPACES:
# Add Substance List Panel
_cls = SubstanceMainPanelFactory(_space[1])
FACTORY_CLASSES.append(_cls)
_cls = SubstancePreviewFactory(_space[1])
FACTORY_CLASSES.append(_cls)
_cls = SubstanceGraphPanelFactory(_space[1])
FACTORY_CLASSES.append(_cls)
_cls = SubstanceOutputsPanelFactory(_space[1])
FACTORY_CLASSES.append(_cls)
_cls = SubstanceInputsPanelFactory(_space[1])
FACTORY_CLASSES.append(_cls)
_menu_cls = SubstanceShortcutMenuFactory(_space[1])
FACTORY_CLASSES.append(_menu_cls)
# Register blender classes
for _cls in DEFAULT_CLASSES:
register_class(_cls)
for _cls in FACTORY_CLASSES:
register_class(_cls)
# Addon Preferences
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
# Shortcuts
_shortcuts = _addon_prefs.shortcuts
wm = bpy.context.window_manager
_kc = wm.keyconfigs.addon
for _space in UI_SPACES:
if _kc:
_km = wm.keyconfigs.addon.keymaps.new(name=_space[0], space_type=_space[1])
_kmi = _km.keymap_items.new(
'wm.call_menu',
_shortcuts.menu_key,
'PRESS',
ctrl=_shortcuts.menu_ctrl,
shift=_shortcuts.menu_shift,
alt=_shortcuts.menu_alt
)
_kmi.properties.name = SHORTCUT_CLASS_NAME.format(_space[1])
SHORTCUT_KEYMAPS.append((_km, _kmi))
_kmi = _km.keymap_items.new(
SUBSTANCE_OT_LoadSBSAR.bl_idname,
_shortcuts.load_key,
'PRESS',
ctrl=_shortcuts.load_ctrl,
shift=_shortcuts.load_shift,
alt=_shortcuts.load_alt
)
SHORTCUT_KEYMAPS.append((_km, _kmi))
_kmi = _km.keymap_items.new(
SUBSTANCE_OT_ApplySBSAR.bl_idname,
_shortcuts.apply_key,
'PRESS',
ctrl=_shortcuts.apply_ctrl,
shift=_shortcuts.apply_shift,
alt=_shortcuts.apply_alt
)
SHORTCUT_KEYMAPS.append((_km, _kmi))
# Create scene SBSAR variables
bpy.types.Scene.loaded_sbsars = bpy.props.CollectionProperty(type=SUBSTANCE_PG_Sbsar)
bpy.types.Scene.sbsar_index = bpy.props.IntProperty(
name='sbsar_index',
default=0,
options={'HIDDEN'},
update=sbsar_index_changed
)
# Create a dumb variable to fix the Preview Update
bpy.types.Scene.sbsar_redraw = bpy.props.IntProperty(
name='sbsar_redraw',
default=0,
options={'HIDDEN'},
update=sbsar_redraw_changed
)
# Init icons
SUBSTANCE_Utils.init_icons()
# Shader Presets
_result = SUBSTANCE_Api.shader_initialize(_addon_prefs)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Shader presets cannot be initialized...".format(_result))
return
SUBSTANCE_Utils.log_data("INFO", "Shader Presets initialized...")
# Add main thread listener
if not bpy.app.timers.is_registered(SUBSTANCE_Threads.exec_queued_function):
bpy.app.timers.register(SUBSTANCE_Threads.exec_queued_function)
# Initialize blender handlers
bpy.app.handlers.load_post.append(SUBSTANCE_Persistance.sbs_load_post_handler)
bpy.app.handlers.load_pre.append(SUBSTANCE_Persistance.sbs_load_pre_handler)
bpy.app.handlers.save_pre.append(SUBSTANCE_Persistance.sbs_save_pre_handler)
bpy.app.handlers.save_post.append(SUBSTANCE_Persistance.sbs_save_post_handler)
bpy.app.handlers.undo_post.append(SUBSTANCE_Persistance.sbs_undo_post_handler)
bpy.app.handlers.depsgraph_update_post.append(SUBSTANCE_Persistance.sbs_depsgraph_update_post)
# Initialize SUBSTANCE_Api listeners
SUBSTANCE_Api.listeners_add("post", post_render)
SUBSTANCE_Api.listeners_add("post", post_link)
# Initialize SRE if enabled
if _addon_prefs.auto_start_sre:
_result = SUBSTANCE_Api.initialize()
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] The SRE cannot initialize...".format(_result))
def unregister():
# Remove shortcuts
for _km, _kmi in SHORTCUT_KEYMAPS:
_km.keymap_items.remove(_kmi)
SHORTCUT_KEYMAPS.clear()
# Remove sbsar dynamic classes
for _scene in bpy.data.scenes:
for _item in _scene.loaded_sbsars:
SUBSTANCE_Api.sbsar_unregister(_item.uuid)
_scene.loaded_sbsars.clear()
# Shutdown SUBSTANCE_Api
SUBSTANCE_Api.listeners_remove("post", post_render)
SUBSTANCE_Api.listeners_remove("post", post_link)
SUBSTANCE_Api.shutdown()
# Remove blender handlers
for _func in bpy.app.handlers.load_pre[:]:
if _func.__name__ == SUBSTANCE_Persistance.sbs_load_pre_handler.__name__:
bpy.app.handlers.load_pre.remove(_func)
for _func in bpy.app.handlers.load_post[:]:
if _func.__name__ == SUBSTANCE_Persistance.sbs_load_post_handler.__name__:
bpy.app.handlers.load_post.remove(_func)
for _func in bpy.app.handlers.save_pre[:]:
if _func.__name__ == SUBSTANCE_Persistance.sbs_save_pre_handler.__name__:
bpy.app.handlers.save_pre.remove(_func)
for _func in bpy.app.handlers.save_post[:]:
if _func.__name__ == SUBSTANCE_Persistance.sbs_save_post_handler.__name__:
bpy.app.handlers.save_post.remove(_func)
for _func in bpy.app.handlers.undo_post[:]:
if _func.__name__ == SUBSTANCE_Persistance.sbs_undo_post_handler.__name__:
bpy.app.handlers.undo_post.remove(_func)
for _func in bpy.app.handlers.depsgraph_update_post[:]:
if _func.__name__ == SUBSTANCE_Persistance.sbs_depsgraph_update_post.__name__:
bpy.app.handlers.depsgraph_update_post.remove(_func)
# Remove main thread listener
if bpy.app.timers.is_registered(SUBSTANCE_Threads.exec_queued_function):
bpy.app.timers.unregister(SUBSTANCE_Threads.exec_queued_function)
# Cleanup Shader Presets list
bpy.ops.substance.save_shader_presets()
bpy.ops.substance.remove_shader_presets()
# Delete scene SBSAR variables
del bpy.types.Scene.loaded_sbsars
del bpy.types.Scene.sbsar_index
del bpy.types.Scene.sbsar_redraw
# Unregister blender classes
for _cls in reversed(DEFAULT_CLASSES):
unregister_class(_cls)
for _cls in reversed(FACTORY_CLASSES):
unregister_class(_cls)
if __name__ == "__main__":
register()
except Exception:
print(traceback.format_exc())
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,130 @@
{
"label":"Cycles/Eevee Standard",
"inputs":{
"disp_midlevel":{"id":"disp_midlevel", "label":"Displacement Midlevel","type":"float_slider", "default":0.5, "min":0, "max":1},
"disp_scale":{"id":"disp_scale", "label":"Displacement Scale","type":"float_maxmin", "default":0.1, "min":0, "max":1000},
"emissive_intensity":{"id":"emissive_intensity", "label":"Emissive Intensity","type":"float_maxmin", "default":2.0, "min":0, "max":9999},
"ao_mix":{"id":"ao_mix", "label":"AO Mix","type":"float_slider", "default":0.5, "min":0, "max":1}
},
"outputs":{
"baseColor":{"id":"baseColor", "label":"Base Color", "enabled":true, "optional":false, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"metallic":{"id":"metallic", "label":"Metallic", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"roughness":{"id":"roughness", "label":"Roughness", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"normal":{"id":"normal", "label":"Normal", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true},
"height":{"id":"height", "label":"Height", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"emissive":{"id":"emissive", "label":"Emissive Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"opacity":{"id":"opacity", "label":"Opacity", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"ambientOcclusion":{"id":"ambientOcclusion", "label":"Ambient Occlusion", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"anisotropyLevel":{"id":"anisotropyLevel", "label":"Anisotropy Level", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"anisotropyAngle":{"id":"anisotropyAngle", "label":"Anisotropy Angle", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"IOR":{"id":"IOR", "label":"IOR", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"specularColor":{"id":"specularColor", "label":"Specular Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"scattering":{"id":"scattering", "label":"Scattering", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"scatteringColor":{"id":"scatteringColor", "label":"Scattering Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"coatWeight":{"id":"coatWeight", "label":"Coat Weight", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatRoughness":{"id":"coatRoughness", "label":"Coat Roughness", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatNormal":{"id":"coatNormal", "label":"Coat Normal", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true}
},
"nodes":[
{"id":"OUT", "path":"root", "type":"ShaderNodeOutputMaterial", "name":"Output", "location":[300,0]},
{"id":"MAT", "path":"root", "type":"ShaderNodeBsdfPrincipled", "name":"Material", "location":[0,0]},
{"id":"tx_coord", "path":"root", "type":"ShaderNodeTexCoord", "name":"Tx Coords", "location":[-1200,0]},
{"id":"mapping", "path":"root", "type":"ShaderNodeMapping", "name":"Mapping", "location":[-900,0]},
{"id":"mapping_frame", "path":"root", "type":"NodeFrame", "name":"Mapping Frame", "label":"Mapping", "children":["tx_coord", "mapping"]},
{"id":"SBSAR", "path":"root", "type":"ShaderNodeGroup", "name":"$matname_sbsar", "location":[-600,0]},
{"id":"NODE_GROUP_OUT", "path":"root/SBSAR", "type":"NodeGroupOutput", "name":"Outputs", "location":[0,0]},
{"id":"NODE_GROUP_IN", "path":"root/SBSAR", "type":"NodeGroupInput", "name":"Inputs", "location":[-900,0]},
{"id":"displacement", "path":"root", "type":"ShaderNodeDisplacement", "name":"Displacement", "location":[0,-700], "dependency":["tx_height"]},
{"id":"ao_mix", "path":"root", "type":"ShaderNodeMixRGB", "name":"AO Mix", "location":[-300,0], "dependency":["tx_ambientOcclusion", "tx_baseColor"]}
],
"properties":[
{"id":"MAT", "type":"string", "name":"distribution", "value":"GGX"},
{"id":"mapping", "type":"tiling", "input":3, "name":"default_value"},
{"id":"ao_mix", "type":"string", "name":"blend_type", "value":"MULTIPLY"},
{"id":"ao_mix", "type":"ao_mix", "input":0, "name":"default_value"},
{"id":"MAT", "type":"emissive_intensity", "input":27, "name":"default_value"},
{"id":"displacement", "type":"disp_midlevel", "input":1, "name":"default_value", "dependency":["tx_height"]},
{"id":"displacement", "type":"disp_scale", "input":2, "name":"default_value", "dependency":["tx_height"]}
],
"sockets":[
{"id":"SBSAR", "source":"input", "type":"NodeSocketVector", "name":"UV"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"baseColor", "dependency":"tx_baseColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"metallic", "dependency":"tx_metallic"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"roughness", "dependency":"tx_roughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"normal", "dependency":"tx_normal"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"height", "dependency":"tx_height"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"emissive", "dependency":"tx_emissive"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"opacity", "dependency":"tx_opacity"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"ambientOcclusion", "dependency":"tx_ambientOcclusion"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"anisotropyLevel", "dependency":"tx_anisotropyLevel"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"anisotropyAngle", "dependency":"tx_anisotropyAngle"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"IOR", "dependency":"tx_IOR"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"specularColor", "dependency":"tx_specularColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"scattering", "dependency":"tx_scattering"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"scatteringColor", "dependency":"tx_scatteringColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatWeight", "dependency":"tx_coatWeight"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatRoughness", "dependency":"tx_coatRoughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"coatNormal", "dependency":"tx_coatNormal"}
],
"links":[
{"from":"tx_coord", "to":"mapping", "output":"UV", "input":"Vector", "path":"root"},
{"from":"mapping", "to":"SBSAR", "output":"Vector", "input":"UV", "path":"root"},
{"from":"NODE_GROUP_IN", "to":"tx_baseColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_metallic", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_roughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_normal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_height", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_emissive", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_opacity", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_ambientOcclusion", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyLevel", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyAngle", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_IOR", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_specularColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scattering", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scatteringColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatWeight", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatRoughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatNormal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"tx_baseColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"baseColor", "path":"root/SBSAR"},
{"from":"tx_metallic", "to":"NODE_GROUP_OUT", "output":"Color", "input":"metallic", "path":"root/SBSAR"},
{"from":"tx_roughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"roughness", "path":"root/SBSAR"},
{"from":"tx_normal", "to":"normal_normal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_normal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"normal", "path":"root/SBSAR"},
{"from":"tx_height", "to":"NODE_GROUP_OUT", "output":"Color", "input":"height", "path":"root/SBSAR"},
{"from":"tx_emissive", "to":"NODE_GROUP_OUT", "output":"Color", "input":"emissive", "path":"root/SBSAR"},
{"from":"tx_opacity", "to":"NODE_GROUP_OUT", "output":"Color", "input":"opacity", "path":"root/SBSAR"},
{"from":"tx_ambientOcclusion", "to":"NODE_GROUP_OUT", "output":"Color", "input":"ambientOcclusion", "path":"root/SBSAR"},
{"from":"tx_anisotropyLevel", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyLevel", "path":"root/SBSAR"},
{"from":"tx_anisotropyAngle", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyAngle", "path":"root/SBSAR"},
{"from":"tx_IOR", "to":"NODE_GROUP_OUT", "output":"Color", "input":"IOR", "path":"root/SBSAR"},
{"from":"tx_specularColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"specularColor", "path":"root/SBSAR"},
{"from":"tx_scattering", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scattering", "path":"root/SBSAR"},
{"from":"tx_scatteringColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scatteringColor", "path":"root/SBSAR"},
{"from":"tx_coatWeight", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatWeight", "path":"root/SBSAR"},
{"from":"tx_coatRoughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatRoughness", "path":"root/SBSAR"},
{"from":"tx_coatNormal", "to":"normal_coatNormal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_coatNormal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"coatNormal", "path":"root/SBSAR"},
{"from":"SBSAR", "to":"MAT", "output":"baseColor", "input":"Base Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"metallic", "input":"Metallic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"roughness", "input":"Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"normal", "input":"Normal", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"emissive", "input":"Emission Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"opacity", "input":"Alpha", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyLevel", "input":"Anisotropic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyAngle", "input":"Anisotropic Rotation", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"IOR", "input":"IOR", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"specularColor", "input":"Specular Tint", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scattering", "input":"Subsurface", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scatteringColor", "input":"Subsurface Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatWeight", "input":"Clearcoat", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatRoughness", "input":"Clearcoat Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatNormal", "input":"Clearcoat Normal", "path":"root"},
{"from":"SBSAR", "to":"displacement", "output":"height", "input":"Height", "path":"root"},
{"from":"displacement", "to":"OUT", "output":"Displacement", "input":"Displacement", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"baseColor", "input":"Color1", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"ambientOcclusion", "input":"Color2", "path":"root"},
{"from":"ao_mix", "to":"MAT", "output":"Color", "input":"Base Color", "path":"root", "force":true},
{"from":"MAT", "to":"OUT", "output":"BSDF", "input":"Surface", "path":"root"}
]
}
@@ -0,0 +1,167 @@
{
"label":"Cycles/Eevee Projection Box",
"inputs":{
"disp_midlevel":{"id":"disp_midlevel", "label":"Displacement Midlevel","type":"float_slider", "default":0.5, "min":0, "max":1},
"disp_scale":{"id":"disp_scale", "label":"Displacement Scale","type":"float_maxmin", "default":0.1, "min":0, "max":1000},
"emissive_intensity":{"id":"emissive_intensity", "label":"Emissive Intensity","type":"float_maxmin", "default":2.0, "min":0, "max":9999},
"projection_blend":{"id":"projection_blend", "label":"Projection Blend","type":"float_slider", "default":0.5, "min":0, "max":1},
"ao_mix":{"id":"ao_mix", "label":"AO Mix","type":"float_slider", "default":0.5, "min":0, "max":1}
},
"outputs":{
"baseColor":{"id":"baseColor", "label":"Base Color", "enabled":true, "optional":false, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"metallic":{"id":"metallic", "label":"Metallic", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"roughness":{"id":"roughness", "label":"Roughness", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"normal":{"id":"normal", "label":"Normal", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true},
"height":{"id":"height", "label":"Height", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"emissive":{"id":"emissive", "label":"Emissive Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"opacity":{"id":"opacity", "label":"Opacity", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"ambientOcclusion":{"id":"ambientOcclusion", "label":"Ambient Occlusion", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"anisotropyLevel":{"id":"anisotropyLevel", "label":"Anisotropy Level", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"anisotropyAngle":{"id":"anisotropyAngle", "label":"Anisotropy Angle", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"IOR":{"id":"IOR", "label":"IOR", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"specularColor":{"id":"specularColor", "label":"Specular Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"scattering":{"id":"scattering", "label":"Scattering", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"scatteringColor":{"id":"scatteringColor", "label":"Scattering Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"coatWeight":{"id":"coatWeight", "label":"Coat Weight", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatRoughness":{"id":"coatRoughness", "label":"Coat Roughness", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatNormal":{"id":"coatNormal", "label":"Coat Normal", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true}
},
"nodes":[
{"id":"OUT", "path":"root", "type":"ShaderNodeOutputMaterial", "name":"Output", "location":[300,0]},
{"id":"MAT", "path":"root", "type":"ShaderNodeBsdfPrincipled", "name":"Material", "location":[0,0]},
{"id":"tx_coord", "path":"root", "type":"ShaderNodeTexCoord", "name":"Tx Coords", "location":[-1200,0]},
{"id":"mapping", "path":"root", "type":"ShaderNodeMapping", "name":"Mapping", "location":[-900,0]},
{"id":"mapping_frame", "path":"root", "type":"NodeFrame", "name":"Mapping Frame", "label":"Mapping", "children":["tx_coord", "mapping"]},
{"id":"SBSAR", "path":"root", "type":"ShaderNodeGroup", "name":"$matname_sbsar", "location":[-600,0]},
{"id":"NODE_GROUP_OUT", "path":"root/SBSAR", "type":"NodeGroupOutput", "name":"Outputs", "location":[0,0]},
{"id":"NODE_GROUP_IN", "path":"root/SBSAR", "type":"NodeGroupInput", "name":"Inputs", "location":[-900,0]},
{"id":"displacement", "path":"root", "type":"ShaderNodeDisplacement", "name":"Displacement", "location":[0,-700], "dependency":["tx_height"]},
{"id":"ao_mix", "path":"root", "type":"ShaderNodeMixRGB", "name":"AO Mix", "location":[-300,0], "dependency":["tx_ambientOcclusion", "tx_baseColor"]}
],
"properties":[
{"id":"MAT", "type":"string", "name":"distribution", "value":"GGX"},
{"id":"mapping", "type":"tiling", "input":3, "name":"default_value"},
{"id":"ao_mix", "type":"string", "name":"blend_type", "value":"MULTIPLY"},
{"id":"ao_mix", "type":"ao_mix", "input":0, "name":"default_value"},
{"id":"MAT", "type":"emissive_intensity", "input":27, "name":"default_value"},
{"id":"displacement", "type":"disp_midlevel", "input":1, "name":"default_value", "dependency":["tx_height"]},
{"id":"displacement", "type":"disp_scale", "input":2, "name":"default_value", "dependency":["tx_height"]},
{"id":"tx_baseColor", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_baseColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_metallic", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_metallic", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_roughness", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_roughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_normal", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_normal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_height", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_height", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_emissive", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_emissive", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_opacity", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_opacity", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_ambientOcclusion", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_ambientOcclusion", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyLevel", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_anisotropyLevel", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyAngle", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_anisotropyAngle", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_IOR", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_IOR", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_specularColor", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_specularColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scattering", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_scattering", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scatteringColor", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_scatteringColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatWeight", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_coatWeight", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatRoughness", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_coatRoughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatNormal", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_coatNormal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_", "type":"projection_blend", "name":"projection_blend"}
],
"sockets":[
{"id":"SBSAR", "source":"input", "type":"NodeSocketVector", "name":"UV"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"baseColor", "dependency":"tx_baseColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"metallic", "dependency":"tx_metallic"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"roughness", "dependency":"tx_roughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"normal", "dependency":"tx_normal"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"height", "dependency":"tx_height"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"emissive", "dependency":"tx_emissive"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"opacity", "dependency":"tx_opacity"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"ambientOcclusion", "dependency":"tx_ambientOcclusion"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"anisotropyLevel", "dependency":"tx_anisotropyLevel"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"anisotropyAngle", "dependency":"tx_anisotropyAngle"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"IOR", "dependency":"tx_IOR"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"specularColor", "dependency":"tx_specularColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"scattering", "dependency":"tx_scattering"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"scatteringColor", "dependency":"tx_scatteringColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatWeight", "dependency":"tx_coatWeight"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatRoughness", "dependency":"tx_coatRoughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"coatNormal", "dependency":"tx_coatNormal"}
],
"links":[
{"from":"tx_coord", "to":"mapping", "output":"Generated", "input":"Vector", "path":"root"},
{"from":"mapping", "to":"SBSAR", "output":"Vector", "input":"UV", "path":"root"},
{"from":"NODE_GROUP_IN", "to":"tx_baseColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_metallic", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_roughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_normal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_height", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_emissive", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_opacity", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_ambientOcclusion", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyLevel", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyAngle", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_IOR", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_specularColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scattering", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scatteringColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatWeight", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatRoughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatNormal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"tx_baseColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"baseColor", "path":"root/SBSAR"},
{"from":"tx_metallic", "to":"NODE_GROUP_OUT", "output":"Color", "input":"metallic", "path":"root/SBSAR"},
{"from":"tx_roughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"roughness", "path":"root/SBSAR"},
{"from":"tx_normal", "to":"normal_normal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_normal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"normal", "path":"root/SBSAR"},
{"from":"tx_height", "to":"NODE_GROUP_OUT", "output":"Color", "input":"height", "path":"root/SBSAR"},
{"from":"tx_emissive", "to":"NODE_GROUP_OUT", "output":"Color", "input":"emissive", "path":"root/SBSAR"},
{"from":"tx_opacity", "to":"NODE_GROUP_OUT", "output":"Color", "input":"opacity", "path":"root/SBSAR"},
{"from":"tx_ambientOcclusion", "to":"NODE_GROUP_OUT", "output":"Color", "input":"ambientOcclusion", "path":"root/SBSAR"},
{"from":"tx_anisotropyLevel", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyLevel", "path":"root/SBSAR"},
{"from":"tx_anisotropyAngle", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyAngle", "path":"root/SBSAR"},
{"from":"tx_IOR", "to":"NODE_GROUP_OUT", "output":"Color", "input":"IOR", "path":"root/SBSAR"},
{"from":"tx_specularColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"specularColor", "path":"root/SBSAR"},
{"from":"tx_scattering", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scattering", "path":"root/SBSAR"},
{"from":"tx_scatteringColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scatteringColor", "path":"root/SBSAR"},
{"from":"tx_coatWeight", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatWeight", "path":"root/SBSAR"},
{"from":"tx_coatRoughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatRoughness", "path":"root/SBSAR"},
{"from":"tx_coatNormal", "to":"normal_coatNormal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_coatNormal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"coatNormal", "path":"root/SBSAR"},
{"from":"SBSAR", "to":"MAT", "output":"baseColor", "input":"Base Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"metallic", "input":"Metallic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"roughness", "input":"Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"normal", "input":"Normal", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"emissive", "input":"Emission Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"opacity", "input":"Alpha", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyLevel", "input":"Anisotropic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyAngle", "input":"Anisotropic Rotation", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"IOR", "input":"IOR", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"specularColor", "input":"Specular Tint", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scattering", "input":"Subsurface", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scatteringColor", "input":"Subsurface Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatWeight", "input":"Clearcoat", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatRoughness", "input":"Clearcoat Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatNormal", "input":"Clearcoat Normal", "path":"root"},
{"from":"SBSAR", "to":"displacement", "output":"height", "input":"Height", "path":"root"},
{"from":"displacement", "to":"OUT", "output":"Displacement", "input":"Displacement", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"baseColor", "input":"Color1", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"ambientOcclusion", "input":"Color2", "path":"root"},
{"from":"ao_mix", "to":"MAT", "output":"Color", "input":"Base Color", "path":"root", "force":true},
{"from":"MAT", "to":"OUT", "output":"BSDF", "input":"Surface", "path":"root"}
]
}
@@ -0,0 +1,167 @@
{
"label":"Cycles/Eevee Projection Sphere",
"inputs":{
"disp_midlevel":{"id":"disp_midlevel", "label":"Displacement Midlevel","type":"float_slider", "default":0.5, "min":0, "max":1},
"disp_scale":{"id":"disp_scale", "label":"Displacement Scale","type":"float_maxmin", "default":0.1, "min":0, "max":1000},
"emissive_intensity":{"id":"emissive_intensity", "label":"Emissive Intensity","type":"float_maxmin", "default":2.0, "min":0, "max":9999},
"projection_blend":{"id":"projection_blend", "label":"Projection Blend","type":"float_slider", "default":0.5, "min":0, "max":1},
"ao_mix":{"id":"ao_mix", "label":"AO Mix","type":"float_slider", "default":0.5, "min":0, "max":1}
},
"outputs":{
"baseColor":{"id":"baseColor", "label":"Base Color", "enabled":true, "optional":false, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"metallic":{"id":"metallic", "label":"Metallic", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"roughness":{"id":"roughness", "label":"Roughness", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"normal":{"id":"normal", "label":"Normal", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true},
"height":{"id":"height", "label":"Height", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"emissive":{"id":"emissive", "label":"Emissive Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"opacity":{"id":"opacity", "label":"Opacity", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"ambientOcclusion":{"id":"ambientOcclusion", "label":"Ambient Occlusion", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"anisotropyLevel":{"id":"anisotropyLevel", "label":"Anisotropy Level", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"anisotropyAngle":{"id":"anisotropyAngle", "label":"Anisotropy Angle", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"IOR":{"id":"IOR", "label":"IOR", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"specularColor":{"id":"specularColor", "label":"Specular Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"scattering":{"id":"scattering", "label":"Scattering", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"scatteringColor":{"id":"scatteringColor", "label":"Scattering Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"coatWeight":{"id":"coatWeight", "label":"Coat Weight", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatRoughness":{"id":"coatRoughness", "label":"Coat Roughness", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatNormal":{"id":"coatNormal", "label":"Coat Normal", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true}
},
"nodes":[
{"id":"OUT", "path":"root", "type":"ShaderNodeOutputMaterial", "name":"Output", "location":[300,0]},
{"id":"MAT", "path":"root", "type":"ShaderNodeBsdfPrincipled", "name":"Material", "location":[0,0]},
{"id":"tx_coord", "path":"root", "type":"ShaderNodeTexCoord", "name":"Tx Coords", "location":[-1200,0]},
{"id":"mapping", "path":"root", "type":"ShaderNodeMapping", "name":"Mapping", "location":[-900,0]},
{"id":"mapping_frame", "path":"root", "type":"NodeFrame", "name":"Mapping Frame", "label":"Mapping", "children":["tx_coord", "mapping"]},
{"id":"SBSAR", "path":"root", "type":"ShaderNodeGroup", "name":"$matname_sbsar", "location":[-600,0]},
{"id":"NODE_GROUP_OUT", "path":"root/SBSAR", "type":"NodeGroupOutput", "name":"Outputs", "location":[0,0]},
{"id":"NODE_GROUP_IN", "path":"root/SBSAR", "type":"NodeGroupInput", "name":"Inputs", "location":[-900,0]},
{"id":"displacement", "path":"root", "type":"ShaderNodeDisplacement", "name":"Displacement", "location":[0,-700], "dependency":["tx_height"]},
{"id":"ao_mix", "path":"root", "type":"ShaderNodeMixRGB", "name":"AO Mix", "location":[-300,0], "dependency":["tx_ambientOcclusion", "tx_baseColor"]}
],
"properties":[
{"id":"MAT", "type":"string", "name":"distribution", "value":"GGX"},
{"id":"mapping", "type":"tiling", "input":3, "name":"default_value"},
{"id":"ao_mix", "type":"string", "name":"blend_type", "value":"MULTIPLY"},
{"id":"ao_mix", "type":"ao_mix", "input":0, "name":"default_value"},
{"id":"MAT", "type":"emissive_intensity", "input":27, "name":"default_value"},
{"id":"displacement", "type":"disp_midlevel", "input":1, "name":"default_value", "dependency":["tx_height"]},
{"id":"displacement", "type":"disp_scale", "input":2, "name":"default_value", "dependency":["tx_height"]},
{"id":"tx_baseColor", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_baseColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_metallic", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_metallic", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_roughness", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_roughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_normal", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_normal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_height", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_height", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_emissive", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_emissive", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_opacity", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_opacity", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_ambientOcclusion", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_ambientOcclusion", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyLevel", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_anisotropyLevel", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyAngle", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_anisotropyAngle", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_IOR", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_IOR", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_specularColor", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_specularColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scattering", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_scattering", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scatteringColor", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_scatteringColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatWeight", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_coatWeight", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatRoughness", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_coatRoughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatNormal", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_coatNormal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_", "type":"string", "name":"projection", "value":"SPHERE"},
{"id":"tx_", "type":"projection_blend", "name":"projection_blend"}
],
"sockets":[
{"id":"SBSAR", "source":"input", "type":"NodeSocketVector", "name":"UV"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"baseColor", "dependency":"tx_baseColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"metallic", "dependency":"tx_metallic"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"roughness", "dependency":"tx_roughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"normal", "dependency":"tx_normal"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"height", "dependency":"tx_height"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"emissive", "dependency":"tx_emissive"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"opacity", "dependency":"tx_opacity"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"ambientOcclusion", "dependency":"tx_ambientOcclusion"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"anisotropyLevel", "dependency":"tx_anisotropyLevel"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"anisotropyAngle", "dependency":"tx_anisotropyAngle"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"IOR", "dependency":"tx_IOR"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"specularColor", "dependency":"tx_specularColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"scattering", "dependency":"tx_scattering"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"scatteringColor", "dependency":"tx_scatteringColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatWeight", "dependency":"tx_coatWeight"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatRoughness", "dependency":"tx_coatRoughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"coatNormal", "dependency":"tx_coatNormal"}
],
"links":[
{"from":"tx_coord", "to":"mapping", "output":"Generated", "input":"Vector", "path":"root"},
{"from":"mapping", "to":"SBSAR", "output":"Vector", "input":"UV", "path":"root"},
{"from":"NODE_GROUP_IN", "to":"tx_baseColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_metallic", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_roughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_normal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_height", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_emissive", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_opacity", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_ambientOcclusion", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyLevel", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyAngle", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_IOR", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_specularColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scattering", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scatteringColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatWeight", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatRoughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatNormal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"tx_baseColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"baseColor", "path":"root/SBSAR"},
{"from":"tx_metallic", "to":"NODE_GROUP_OUT", "output":"Color", "input":"metallic", "path":"root/SBSAR"},
{"from":"tx_roughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"roughness", "path":"root/SBSAR"},
{"from":"tx_normal", "to":"normal_normal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_normal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"normal", "path":"root/SBSAR"},
{"from":"tx_height", "to":"NODE_GROUP_OUT", "output":"Color", "input":"height", "path":"root/SBSAR"},
{"from":"tx_emissive", "to":"NODE_GROUP_OUT", "output":"Color", "input":"emissive", "path":"root/SBSAR"},
{"from":"tx_opacity", "to":"NODE_GROUP_OUT", "output":"Color", "input":"opacity", "path":"root/SBSAR"},
{"from":"tx_ambientOcclusion", "to":"NODE_GROUP_OUT", "output":"Color", "input":"ambientOcclusion", "path":"root/SBSAR"},
{"from":"tx_anisotropyLevel", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyLevel", "path":"root/SBSAR"},
{"from":"tx_anisotropyAngle", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyAngle", "path":"root/SBSAR"},
{"from":"tx_IOR", "to":"NODE_GROUP_OUT", "output":"Color", "input":"IOR", "path":"root/SBSAR"},
{"from":"tx_specularColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"specularColor", "path":"root/SBSAR"},
{"from":"tx_scattering", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scattering", "path":"root/SBSAR"},
{"from":"tx_scatteringColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scatteringColor", "path":"root/SBSAR"},
{"from":"tx_coatWeight", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatWeight", "path":"root/SBSAR"},
{"from":"tx_coatRoughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatRoughness", "path":"root/SBSAR"},
{"from":"tx_coatNormal", "to":"normal_coatNormal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_coatNormal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"coatNormal", "path":"root/SBSAR"},
{"from":"SBSAR", "to":"MAT", "output":"baseColor", "input":"Base Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"metallic", "input":"Metallic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"roughness", "input":"Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"normal", "input":"Normal", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"emissive", "input":"Emission Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"opacity", "input":"Alpha", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyLevel", "input":"Anisotropic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyAngle", "input":"Anisotropic Rotation", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"IOR", "input":"IOR", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"specularColor", "input":"Specular Tint", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scattering", "input":"Subsurface", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scatteringColor", "input":"Subsurface Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatWeight", "input":"Clearcoat", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatRoughness", "input":"Clearcoat Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatNormal", "input":"Clearcoat Normal", "path":"root"},
{"from":"SBSAR", "to":"displacement", "output":"height", "input":"Height", "path":"root"},
{"from":"displacement", "to":"OUT", "output":"Displacement", "input":"Displacement", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"baseColor", "input":"Color1", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"ambientOcclusion", "input":"Color2", "path":"root"},
{"from":"ao_mix", "to":"MAT", "output":"Color", "input":"Base Color", "path":"root", "force":true},
{"from":"MAT", "to":"OUT", "output":"BSDF", "input":"Surface", "path":"root"}
]
}
@@ -0,0 +1,167 @@
{
"label":"Cycles/Eevee Projection Tube",
"inputs":{
"disp_midlevel":{"id":"disp_midlevel", "label":"Displacement Midlevel","type":"float_slider", "default":0.5, "min":0, "max":1},
"disp_scale":{"id":"disp_scale", "label":"Displacement Scale","type":"float_maxmin", "default":0.1, "min":0, "max":1000},
"emissive_intensity":{"id":"emissive_intensity", "label":"Emissive Intensity","type":"float_maxmin", "default":2.0, "min":0, "max":9999},
"projection_blend":{"id":"projection_blend", "label":"Projection Blend","type":"float_slider", "default":0.5, "min":0, "max":1},
"ao_mix":{"id":"ao_mix", "label":"AO Mix","type":"float_slider", "default":0.5, "min":0, "max":1}
},
"outputs":{
"baseColor":{"id":"baseColor", "label":"Base Color", "enabled":true, "optional":false, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"metallic":{"id":"metallic", "label":"Metallic", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"roughness":{"id":"roughness", "label":"Roughness", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"normal":{"id":"normal", "label":"Normal", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true},
"height":{"id":"height", "label":"Height", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"emissive":{"id":"emissive", "label":"Emissive Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"opacity":{"id":"opacity", "label":"Opacity", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"ambientOcclusion":{"id":"ambientOcclusion", "label":"Ambient Occlusion", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"anisotropyLevel":{"id":"anisotropyLevel", "label":"Anisotropy Level", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"anisotropyAngle":{"id":"anisotropyAngle", "label":"Anisotropy Angle", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"IOR":{"id":"IOR", "label":"IOR", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"specularColor":{"id":"specularColor", "label":"Specular Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"scattering":{"id":"scattering", "label":"Scattering", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"scatteringColor":{"id":"scatteringColor", "label":"Scattering Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"coatWeight":{"id":"coatWeight", "label":"Coat Weight", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatRoughness":{"id":"coatRoughness", "label":"Coat Roughness", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatNormal":{"id":"coatNormal", "label":"Coat Normal", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true}
},
"nodes":[
{"id":"OUT", "path":"root", "type":"ShaderNodeOutputMaterial", "name":"Output", "location":[300,0]},
{"id":"MAT", "path":"root", "type":"ShaderNodeBsdfPrincipled", "name":"Material", "location":[0,0]},
{"id":"tx_coord", "path":"root", "type":"ShaderNodeTexCoord", "name":"Tx Coords", "location":[-1200,0]},
{"id":"mapping", "path":"root", "type":"ShaderNodeMapping", "name":"Mapping", "location":[-900,0]},
{"id":"mapping_frame", "path":"root", "type":"NodeFrame", "name":"Mapping Frame", "label":"Mapping", "children":["tx_coord", "mapping"]},
{"id":"SBSAR", "path":"root", "type":"ShaderNodeGroup", "name":"$matname_sbsar", "location":[-600,0]},
{"id":"NODE_GROUP_OUT", "path":"root/SBSAR", "type":"NodeGroupOutput", "name":"Outputs", "location":[0,0]},
{"id":"NODE_GROUP_IN", "path":"root/SBSAR", "type":"NodeGroupInput", "name":"Inputs", "location":[-900,0]},
{"id":"displacement", "path":"root", "type":"ShaderNodeDisplacement", "name":"Displacement", "location":[0,-700], "dependency":["tx_height"]},
{"id":"ao_mix", "path":"root", "type":"ShaderNodeMixRGB", "name":"AO Mix", "location":[-300,0], "dependency":["tx_ambientOcclusion", "tx_baseColor"]}
],
"properties":[
{"id":"MAT", "type":"string", "name":"distribution", "value":"GGX"},
{"id":"mapping", "type":"tiling", "input":3, "name":"default_value"},
{"id":"ao_mix", "type":"string", "name":"blend_type", "value":"MULTIPLY"},
{"id":"ao_mix", "type":"ao_mix", "input":0, "name":"default_value"},
{"id":"MAT", "type":"emissive_intensity", "input":27, "name":"default_value"},
{"id":"displacement", "type":"disp_midlevel", "input":1, "name":"default_value", "dependency":["tx_height"]},
{"id":"displacement", "type":"disp_scale", "input":2, "name":"default_value", "dependency":["tx_height"]},
{"id":"tx_baseColor", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_baseColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_metallic", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_metallic", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_roughness", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_roughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_normal", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_normal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_height", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_height", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_emissive", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_emissive", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_opacity", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_opacity", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_ambientOcclusion", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_ambientOcclusion", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyLevel", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_anisotropyLevel", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyAngle", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_anisotropyAngle", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_IOR", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_IOR", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_specularColor", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_specularColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scattering", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_scattering", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scatteringColor", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_scatteringColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatWeight", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_coatWeight", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatRoughness", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_coatRoughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatNormal", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_coatNormal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_", "type":"string", "name":"projection", "value":"TUBE"},
{"id":"tx_", "type":"projection_blend", "name":"projection_blend"}
],
"sockets":[
{"id":"SBSAR", "source":"input", "type":"NodeSocketVector", "name":"UV"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"baseColor", "dependency":"tx_baseColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"metallic", "dependency":"tx_metallic"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"roughness", "dependency":"tx_roughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"normal", "dependency":"tx_normal"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"height", "dependency":"tx_height"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"emissive", "dependency":"tx_emissive"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"opacity", "dependency":"tx_opacity"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"ambientOcclusion", "dependency":"tx_ambientOcclusion"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"anisotropyLevel", "dependency":"tx_anisotropyLevel"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"anisotropyAngle", "dependency":"tx_anisotropyAngle"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"IOR", "dependency":"tx_IOR"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"specularColor", "dependency":"tx_specularColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"scattering", "dependency":"tx_scattering"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"scatteringColor", "dependency":"tx_scatteringColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatWeight", "dependency":"tx_coatWeight"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatRoughness", "dependency":"tx_coatRoughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"coatNormal", "dependency":"tx_coatNormal"}
],
"links":[
{"from":"tx_coord", "to":"mapping", "output":"Generated", "input":"Vector", "path":"root"},
{"from":"mapping", "to":"SBSAR", "output":"Vector", "input":"UV", "path":"root"},
{"from":"NODE_GROUP_IN", "to":"tx_baseColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_metallic", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_roughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_normal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_height", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_emissive", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_opacity", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_ambientOcclusion", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyLevel", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyAngle", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_IOR", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_specularColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scattering", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scatteringColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatWeight", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatRoughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatNormal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"tx_baseColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"baseColor", "path":"root/SBSAR"},
{"from":"tx_metallic", "to":"NODE_GROUP_OUT", "output":"Color", "input":"metallic", "path":"root/SBSAR"},
{"from":"tx_roughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"roughness", "path":"root/SBSAR"},
{"from":"tx_normal", "to":"normal_normal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_normal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"normal", "path":"root/SBSAR"},
{"from":"tx_height", "to":"NODE_GROUP_OUT", "output":"Color", "input":"height", "path":"root/SBSAR"},
{"from":"tx_emissive", "to":"NODE_GROUP_OUT", "output":"Color", "input":"emissive", "path":"root/SBSAR"},
{"from":"tx_opacity", "to":"NODE_GROUP_OUT", "output":"Color", "input":"opacity", "path":"root/SBSAR"},
{"from":"tx_ambientOcclusion", "to":"NODE_GROUP_OUT", "output":"Color", "input":"ambientOcclusion", "path":"root/SBSAR"},
{"from":"tx_anisotropyLevel", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyLevel", "path":"root/SBSAR"},
{"from":"tx_anisotropyAngle", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyAngle", "path":"root/SBSAR"},
{"from":"tx_IOR", "to":"NODE_GROUP_OUT", "output":"Color", "input":"IOR", "path":"root/SBSAR"},
{"from":"tx_specularColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"specularColor", "path":"root/SBSAR"},
{"from":"tx_scattering", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scattering", "path":"root/SBSAR"},
{"from":"tx_scatteringColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scatteringColor", "path":"root/SBSAR"},
{"from":"tx_coatWeight", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatWeight", "path":"root/SBSAR"},
{"from":"tx_coatRoughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatRoughness", "path":"root/SBSAR"},
{"from":"tx_coatNormal", "to":"normal_coatNormal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_coatNormal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"coatNormal", "path":"root/SBSAR"},
{"from":"SBSAR", "to":"MAT", "output":"baseColor", "input":"Base Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"metallic", "input":"Metallic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"roughness", "input":"Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"normal", "input":"Normal", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"emissive", "input":"Emission Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"opacity", "input":"Alpha", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyLevel", "input":"Anisotropic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyAngle", "input":"Anisotropic Rotation", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"IOR", "input":"IOR", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"specularColor", "input":"Specular Tint", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scattering", "input":"Subsurface", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scatteringColor", "input":"Subsurface Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatWeight", "input":"Clearcoat", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatRoughness", "input":"Clearcoat Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatNormal", "input":"Clearcoat Normal", "path":"root"},
{"from":"SBSAR", "to":"displacement", "output":"height", "input":"Height", "path":"root"},
{"from":"displacement", "to":"OUT", "output":"Displacement", "input":"Displacement", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"baseColor", "input":"Color1", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"ambientOcclusion", "input":"Color2", "path":"root"},
{"from":"ao_mix", "to":"MAT", "output":"Color", "input":"Base Color", "path":"root", "force":true},
{"from":"MAT", "to":"OUT", "output":"BSDF", "input":"Surface", "path":"root"}
]
}
@@ -0,0 +1,167 @@
{
"label":"Cycles/Eevee Physical Size",
"inputs":{
"disp_midlevel":{"id":"disp_midlevel", "label":"Displacement Midlevel","type":"float_slider", "default":0.5, "min":0, "max":1},
"disp_scale":{"id":"disp_scale", "label":"Displacement Scale","type":"float_maxmin", "default":0.1, "min":0, "max":1000},
"emissive_intensity":{"id":"emissive_intensity", "label":"Emissive Intensity","type":"float_maxmin", "default":2.0, "min":0, "max":9999},
"projection_blend":{"id":"projection_blend", "label":"Projection Blend","type":"float_slider", "default":0.5, "min":0, "max":1},
"ao_mix":{"id":"ao_mix", "label":"AO Mix","type":"float_slider", "default":0.5, "min":0, "max":1}
},
"outputs":{
"baseColor":{"id":"baseColor", "label":"Base Color", "enabled":true, "optional":false, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"metallic":{"id":"metallic", "label":"Metallic", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"roughness":{"id":"roughness", "label":"Roughness", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"normal":{"id":"normal", "label":"Normal", "enabled":true, "optional":false, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true},
"height":{"id":"height", "label":"Height", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"emissive":{"id":"emissive", "label":"Emissive Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"opacity":{"id":"opacity", "label":"Opacity", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"ambientOcclusion":{"id":"ambientOcclusion", "label":"Ambient Occlusion", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"anisotropyLevel":{"id":"anisotropyLevel", "label":"Anisotropy Level", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"anisotropyAngle":{"id":"anisotropyAngle", "label":"Anisotropy Angle", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16"},
"IOR":{"id":"IOR", "label":"IOR", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"specularColor":{"id":"specularColor", "label":"Specular Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"scattering":{"id":"scattering", "label":"Scattering", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"scatteringColor":{"id":"scatteringColor", "label":"Scattering Color", "enabled":false, "optional":true, "colorspace":"sRGB", "format":"TGA", "bitdepth":"8"},
"coatWeight":{"id":"coatWeight", "label":"Coat Weight", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatRoughness":{"id":"coatRoughness", "label":"Coat Roughness", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"TGA", "bitdepth":"8"},
"coatNormal":{"id":"coatNormal", "label":"Coat Normal", "enabled":false, "optional":true, "colorspace":"Non-Color", "format":"PNG", "bitdepth":"16", "normal":true}
},
"nodes":[
{"id":"OUT", "path":"root", "type":"ShaderNodeOutputMaterial", "name":"Output", "location":[300,0]},
{"id":"MAT", "path":"root", "type":"ShaderNodeBsdfPrincipled", "name":"Material", "location":[0,0]},
{"id":"tx_coord", "path":"root", "type":"ShaderNodeTexCoord", "name":"Tx Coords", "location":[-1200,0]},
{"id":"mapping", "path":"root", "type":"ShaderNodeMapping", "name":"Mapping", "location":[-900,0]},
{"id":"mapping_frame", "path":"root", "type":"NodeFrame", "name":"Mapping Frame", "label":"Mapping", "children":["tx_coord", "mapping"]},
{"id":"SBSAR", "path":"root", "type":"ShaderNodeGroup", "name":"$matname_sbsar", "location":[-600,0]},
{"id":"NODE_GROUP_OUT", "path":"root/SBSAR", "type":"NodeGroupOutput", "name":"Outputs", "location":[0,0]},
{"id":"NODE_GROUP_IN", "path":"root/SBSAR", "type":"NodeGroupInput", "name":"Inputs", "location":[-900,0]},
{"id":"displacement", "path":"root", "type":"ShaderNodeDisplacement", "name":"Displacement", "location":[0,-700], "dependency":["tx_height"]},
{"id":"ao_mix", "path":"root", "type":"ShaderNodeMixRGB", "name":"AO Mix", "location":[-300,0], "dependency":["tx_ambientOcclusion", "tx_baseColor"]}
],
"properties":[
{"id":"MAT", "type":"string", "name":"distribution", "value":"GGX"},
{"id":"mapping", "type":"physical_size", "input":3, "name":"default_value"},
{"id":"ao_mix", "type":"string", "name":"blend_type", "value":"MULTIPLY"},
{"id":"ao_mix", "type":"ao_mix", "input":0, "name":"default_value"},
{"id":"MAT", "type":"emissive_intensity", "input":27, "name":"default_value"},
{"id":"displacement", "type":"disp_midlevel", "input":1, "name":"default_value", "dependency":["tx_height"]},
{"id":"displacement", "type":"disp_physical_scale", "input":2, "name":"default_value", "dependency":["tx_height"]},
{"id":"tx_baseColor", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_baseColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_metallic", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_metallic", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_roughness", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_roughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_normal", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_normal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_height", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_height", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_emissive", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_emissive", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_opacity", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_opacity", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_ambientOcclusion", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_ambientOcclusion", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyLevel", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_anisotropyLevel", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_anisotropyAngle", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_anisotropyAngle", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_IOR", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_IOR", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_specularColor", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_specularColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scattering", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_scattering", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_scatteringColor", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_scatteringColor", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatWeight", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_coatWeight", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatRoughness", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_coatRoughness", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_coatNormal", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_coatNormal", "type":"projection_blend", "name":"projection_blend"},
{"id":"tx_", "type":"string", "name":"projection", "value":"BOX"},
{"id":"tx_", "type":"projection_blend", "name":"projection_blend"}
],
"sockets":[
{"id":"SBSAR", "source":"input", "type":"NodeSocketVector", "name":"UV"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"baseColor", "dependency":"tx_baseColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"metallic", "dependency":"tx_metallic"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"roughness", "dependency":"tx_roughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"normal", "dependency":"tx_normal"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"height", "dependency":"tx_height"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"emissive", "dependency":"tx_emissive"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"opacity", "dependency":"tx_opacity"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"ambientOcclusion", "dependency":"tx_ambientOcclusion"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"anisotropyLevel", "dependency":"tx_anisotropyLevel"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"anisotropyAngle", "dependency":"tx_anisotropyAngle"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"IOR", "dependency":"tx_IOR"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"specularColor", "dependency":"tx_specularColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"scattering", "dependency":"tx_scattering"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketColor", "name":"scatteringColor", "dependency":"tx_scatteringColor"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatWeight", "dependency":"tx_coatWeight"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketFloat", "name":"coatRoughness", "dependency":"tx_coatRoughness"},
{"id":"SBSAR", "source":"output", "type":"NodeSocketVector", "name":"coatNormal", "dependency":"tx_coatNormal"}
],
"links":[
{"from":"tx_coord", "to":"mapping", "output":"Object", "input":"Vector", "path":"root"},
{"from":"mapping", "to":"SBSAR", "output":"Vector", "input":"UV", "path":"root"},
{"from":"NODE_GROUP_IN", "to":"tx_baseColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_metallic", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_roughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_normal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_height", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_emissive", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_opacity", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_ambientOcclusion", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyLevel", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_anisotropyAngle", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_IOR", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_specularColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scattering", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_scatteringColor", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatWeight", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatRoughness", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"NODE_GROUP_IN", "to":"tx_coatNormal", "output":"UV", "input":"Vector", "path":"root/SBSAR"},
{"from":"tx_baseColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"baseColor", "path":"root/SBSAR"},
{"from":"tx_metallic", "to":"NODE_GROUP_OUT", "output":"Color", "input":"metallic", "path":"root/SBSAR"},
{"from":"tx_roughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"roughness", "path":"root/SBSAR"},
{"from":"tx_normal", "to":"normal_normal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_normal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"normal", "path":"root/SBSAR"},
{"from":"tx_height", "to":"NODE_GROUP_OUT", "output":"Color", "input":"height", "path":"root/SBSAR"},
{"from":"tx_emissive", "to":"NODE_GROUP_OUT", "output":"Color", "input":"emissive", "path":"root/SBSAR"},
{"from":"tx_opacity", "to":"NODE_GROUP_OUT", "output":"Color", "input":"opacity", "path":"root/SBSAR"},
{"from":"tx_ambientOcclusion", "to":"NODE_GROUP_OUT", "output":"Color", "input":"ambientOcclusion", "path":"root/SBSAR"},
{"from":"tx_anisotropyLevel", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyLevel", "path":"root/SBSAR"},
{"from":"tx_anisotropyAngle", "to":"NODE_GROUP_OUT", "output":"Color", "input":"anisotropyAngle", "path":"root/SBSAR"},
{"from":"tx_IOR", "to":"NODE_GROUP_OUT", "output":"Color", "input":"IOR", "path":"root/SBSAR"},
{"from":"tx_specularColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"specularColor", "path":"root/SBSAR"},
{"from":"tx_scattering", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scattering", "path":"root/SBSAR"},
{"from":"tx_scatteringColor", "to":"NODE_GROUP_OUT", "output":"Color", "input":"scatteringColor", "path":"root/SBSAR"},
{"from":"tx_coatWeight", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatWeight", "path":"root/SBSAR"},
{"from":"tx_coatRoughness", "to":"NODE_GROUP_OUT", "output":"Color", "input":"coatRoughness", "path":"root/SBSAR"},
{"from":"tx_coatNormal", "to":"normal_coatNormal", "output":"Color", "input":"Color", "path":"root/SBSAR"},
{"from":"normal_coatNormal", "to":"NODE_GROUP_OUT", "output":"Normal", "input":"coatNormal", "path":"root/SBSAR"},
{"from":"SBSAR", "to":"MAT", "output":"baseColor", "input":"Base Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"metallic", "input":"Metallic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"roughness", "input":"Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"normal", "input":"Normal", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"emissive", "input":"Emission Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"opacity", "input":"Alpha", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyLevel", "input":"Anisotropic", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"anisotropyAngle", "input":"Anisotropic Rotation", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"IOR", "input":"IOR", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"specularColor", "input":"Specular Tint", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scattering", "input":"Subsurface", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"scatteringColor", "input":"Subsurface Color", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatWeight", "input":"Clearcoat", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatRoughness", "input":"Clearcoat Roughness", "path":"root"},
{"from":"SBSAR", "to":"MAT", "output":"coatNormal", "input":"Clearcoat Normal", "path":"root"},
{"from":"SBSAR", "to":"displacement", "output":"height", "input":"Height", "path":"root"},
{"from":"displacement", "to":"OUT", "output":"Displacement", "input":"Displacement", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"baseColor", "input":"Color1", "path":"root"},
{"from":"SBSAR", "to":"ao_mix", "output":"ambientOcclusion", "input":"Color2", "path":"root"},
{"from":"ao_mix", "to":"MAT", "output":"Color", "input":"Base Color", "path":"root", "force":true},
{"from":"MAT", "to":"OUT", "output":"BSDF", "input":"Surface", "path":"root"}
]
}
+527
View File
@@ -0,0 +1,527 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: api.py
# brief: Central API that connects the Remote engine operations with blender
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import time
import json
from .toolkit.manager import SRE_ToolkitManager
from .presets.manager import SUBSTANCE_PresetManager
from .network.manager import SUBSTANCE_ServerManager
from .sbsar.manager import SUBSTANCE_SbsarManager
from .shader.manager import SUBSTANCE_ShaderManager
from .render.manager import SUBSTANCE_RenderManager
from .utils import SUBSTANCE_Utils
from .common import (
TOOLKIT_EXPECTED_VERSION,
TOOLKIT_INSTALL_TIME,
TOOLKIT_LAG_TIME,
SERVER_HOST,
Code_Response,
Code_RequestType,
Code_RequestEndpoint,
Code_RequestOp,
Code_InputWidget,
Code_InputIdentifier,
Code_SbsarOp
)
class SUBSTANCE_Api():
currently_running = False
toolkit_manager = SRE_ToolkitManager()
server_manager = SUBSTANCE_ServerManager()
sbsar_manager = SUBSTANCE_SbsarManager()
shader_manager = SUBSTANCE_ShaderManager()
presets_manager = SUBSTANCE_PresetManager()
render_manager = SUBSTANCE_RenderManager()
listeners = {
"head": [],
"get": [],
"post": [],
"patch": []
}
temp_tx_files = []
temp_sbs_files = []
last_selection = None
# MAIN
@classmethod
def version(cls):
return (2, 1, 1)
@classmethod
def is_running(cls):
return cls.toolkit_manager.is_running()
@classmethod
def initialize(cls, delay=TOOLKIT_LAG_TIME):
# Time
_time_start = time.time()
SUBSTANCE_Utils.log_data("INFO", "Plugin initialization...")
# Initialize Substance Remote Engine
_result = cls.toolkit_start(delay)
if _result[0] != Code_Response.success and _result[0] != Code_Response.toolkit_already_started:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Toolkit failed to initialize...".format(_result[0]), display=True)
return _result
elif _result[0] == Code_Response.toolkit_already_started:
SUBSTANCE_Utils.log_data("INFO", "[{}] Toolkit is already in use by another client...".format(_result[0]))
else:
SUBSTANCE_Utils.log_data("INFO", "Toolkit Initialized...")
_result = cls.server_manager.server_start()
if _result[0] != Code_Response.success and _result[0] != Code_Response.server_already_running:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Server failed to initialize...".format(_result[0]), display=True)
return (_result[0], None)
elif _result[0] == Code_Response.server_already_running:
SUBSTANCE_Utils.log_data("INFO", "[{}] Server already running...".format(_result[0]))
else:
SUBSTANCE_Utils.log_data("INFO", "Server Initialized...")
_result = cls.server_manager.server_port()
_data = {
"app": {
"pid": os.getpid(),
"host": SERVER_HOST,
"port": _result[1],
"key": "BLD",
"name": "Blender"
}
}
_result = cls.msg_system(Code_RequestOp.add, _data)
# Time
_time_end = time.time()
_load_time = round(_time_end - _time_start, 3)
SUBSTANCE_Utils.log_data("INFO", "SRE Initialized sucessfully in [{}] seconds".format(_load_time), display=True)
cls.currently_running = cls.toolkit_manager.is_running()
return _result
@classmethod
def shutdown(cls):
_result = cls.toolkit_stop()
if _result[0] == Code_Response.toolkit_in_use:
SUBSTANCE_Utils.log_data("INFO", "Toolkit is still in use by another [{}] client(s)...".format(_result[1]))
return _result
elif _result[0] == Code_Response.toolkit_not_running or _result[0] == Code_Response.toolkit_not_installed:
SUBSTANCE_Utils.log_data("INFO", "[{}] Toolkit not active...".format(_result[0]))
elif _result[0] == Code_Response.success:
SUBSTANCE_Utils.log_data("INFO", "Toolkit terminated...")
else:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Toolkit failed to shutdown...".format(_result[0]))
return _result
return (Code_Response.success, None)
# LISTENERS
@classmethod
def listeners_add(cls, type, listener):
cls.listeners[type].append(listener)
return Code_Response.success
@classmethod
def listeners_remove(cls, type, listener):
try:
cls.listeners[type].remove(listener)
return Code_Response.success
except Exception:
return Code_Response.api_listener_remove_error
@classmethod
def listeners_call(cls, type, data):
for _listener in cls.listeners[type]:
_listener.execute(data)
# TOOLKIT
@classmethod
def toolkit_path_get(cls):
return cls.toolkit_manager.get_path()
@classmethod
def toolkit_version_get(cls):
if cls.toolkit_manager.is_installed():
_result = cls.toolkit_manager.version_get()
return _result
else:
return (Code_Response.toolkit_not_installed, None)
@classmethod
def toolkit_install(cls, filepath):
_result = cls.toolkit_uninstall()
if _result[0] != Code_Response.success:
return _result
_result = cls.toolkit_manager.install(filepath)
if _result[0] != Code_Response.success:
return _result
_result = cls.toolkit_version_get()
if _result[1] is not None and _result[1] in TOOLKIT_EXPECTED_VERSION:
_result = cls.initialize(TOOLKIT_INSTALL_TIME)
return _result
elif _result[1] is not None and _result[1] not in TOOLKIT_EXPECTED_VERSION:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Toolkit update needed. Please download and install a compatible version".format(_result[1]),
display=True)
return (Code_Response.toolkit_version_error, None)
@classmethod
def toolkit_uninstall(cls):
if cls.toolkit_manager.is_running():
_result = cls.shutdown()
if _result[0] != Code_Response.success:
_result = cls.msg_system(Code_RequestOp.kill, {})
if _result[0] != Code_Response.success:
_result = cls.toolkit_manager.stop()
if _result[0] != Code_Response.success:
return _result
if cls.toolkit_manager.is_installed():
time.sleep(TOOLKIT_INSTALL_TIME)
return cls.toolkit_manager.remove()
return (Code_Response.success, None)
@classmethod
def toolkit_start(cls, delay):
if cls.toolkit_manager.is_installed():
return cls.toolkit_manager.start(delay)
else:
return (Code_Response.toolkit_not_installed, None)
@classmethod
def toolkit_stop(cls):
if not cls.toolkit_manager.is_installed():
return (Code_Response.toolkit_not_installed, None)
if not cls.toolkit_manager.is_running():
return (Code_Response.toolkit_not_running, None)
_result = cls.msg_system(Code_RequestOp.remove, {
"app": {
"pid": os.getpid()
}
})
if _result[0] != Code_Response.success:
return _result
if _result[1]["result"] != Code_Response.success.value:
return _result
if _result[1]["data"]["active_apps"] > 0:
return (Code_Response.toolkit_in_use, _result[1]["data"]["active_apps"])
else:
return (Code_Response.success, 0)
# SBSAR
@classmethod
def sbsar_load(cls, data, operation=Code_SbsarOp.load):
_app_pid = os.getpid()
if operation == Code_SbsarOp.load:
_data = {
"app": {
"pid": _app_pid
},
"sbsar": {
"op": operation.value,
"file": data["filepath"],
"name": data["name"],
"$outputsize": data["$outputsize"],
"normal_format": data["normal_format"]
},
}
if "uuid" in data:
_data["sbsar"]["uuid"] = data["uuid"]
elif operation == Code_SbsarOp.reload:
_data = {
"app": {
"pid": _app_pid
},
"sbsar": {
"op": operation.value,
"uuid": data["uuid"],
"file": data["filepath"],
"name": data["name"],
"graph_idx": data["graph_idx"],
"preset": data["preset"]
}
}
elif operation == Code_SbsarOp.duplicate:
_data = {
"app": {
"pid": _app_pid
},
"sbsar": {
"op": operation.value,
"uuid": data["uuid"],
"file": data["filepath"],
"name": data["name"]
}
}
_result = cls.msg_sbsar(Code_RequestOp.add, _data)
if _result[0] != Code_Response.success:
return (_result[0], None)
return (Code_Response.success, _result[1])
@classmethod
def sbsar_remove(cls, uuid):
_data = {
"app": {
"pid": os.getpid()
},
"sbsar": {
"uuid": uuid
}
}
_result = cls.msg_sbsar(Code_RequestOp.remove, _data)
if _result[0] != Code_Response.success:
return (_result[0], None)
return (Code_Response.success, _result[1])
@classmethod
def sbsar_register(cls, sbsar):
_result = cls.sbsar_manager.register(sbsar)
return _result
@classmethod
def sbsar_unregister(cls, uuid):
_result = cls.sbsar_manager.unregister(uuid)
return _result
@classmethod
def sbsar_input_update(cls, context, sbsar, graph, input, value, callback):
_sync = False
if (input.guiWidget == Code_InputWidget.combobox.value or
input.guiWidget == Code_InputWidget.togglebutton.value or
input.guiWidget == Code_InputWidget.image.value or
input.identifier == Code_InputIdentifier.outputsize.value):
_sync = True
if _sync:
return callback(context, sbsar, graph, input, value)
else:
cls.render_manager.input_queue_add(
context,
sbsar,
graph,
input,
value,
callback
)
return (Code_Response.success, None)
@classmethod
def sbsar_input_set(cls, sbsar, graph, input, value):
_data = {
"app": {
"pid": os.getpid()
},
"sbsar": {
"uuid": sbsar.uuid,
"graph_idx": int(graph.index)
},
"input": {
"id": int(input.id),
"identifier": input.identifier,
"type": input.type,
"value": value
}
}
_result = cls.msg_sbsar(Code_RequestOp.update, _data)
if _result[0] != Code_Response.success:
return (_result[0], None)
return (Code_Response.success, _result[1])
# Presets
@classmethod
def sbsar_preset_add(cls, sbsar, graph, name):
_data = {
"app": {
"pid": os.getpid()
},
"sbsar": {
"uuid": sbsar.uuid,
"graph_idx": int(graph.index)
},
"preset": {
"name": name
}
}
_result = cls.msg_preset(Code_RequestOp.add, _data)
if _result[0] != Code_Response.success:
return (_result[0], None)
return (Code_Response.success, _result[1])
@classmethod
def sbsar_preset_load(cls, sbsar, graph, value):
_data = {
"app": {
"pid": os.getpid()
},
"sbsar": {
"uuid": sbsar.uuid,
"graph_idx": int(graph.index)
},
"preset": {
"value": value
}
}
_result = cls.msg_preset(Code_RequestOp.load, _data)
if _result[0] != Code_Response.success:
return (_result[0], None)
return (Code_Response.success, _result[1])
@classmethod
def sbsar_preset_write(cls, filepath, preset):
_result = cls.presets_manager.preset_write_file(filepath, preset)
return _result
@classmethod
def sbsar_preset_read(cls, filepath):
_result = cls.presets_manager.preset_read_file(filepath)
return _result
# Rendering
@classmethod
def sbsar_is_rendering(cls, sbsar_id):
if sbsar_id in cls.render_manager.render_current:
return 2
else:
for _key in cls.render_manager.render_queue:
if sbsar_id in _key:
return 1
return 0
@classmethod
def sbsar_render(cls, render_id, data, request_type=Code_RequestType.r_sync):
_result = cls.server_manager.server_port()
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Render Server not initialized...".format(_result[0]))
return
_data = {
"app": {
"pid": os.getpid(),
"host": SERVER_HOST,
"port": _result[1]
},
"sbsar": {
"uuid": data["uuid"],
"graph_idx": data["index"]
},
"render": {
"path": data["out_path"],
"outputs": data["outputs"]
}
}
cls.render_manager.graph_render(
render_id,
_data,
request_type,
cls.msg_sbsar
)
@classmethod
def sbsar_render_callback(cls, data):
cls.render_manager.render_finish(data)
# SHADER PRESETS
@classmethod
def shader_initialize(cls, addon_prefs):
addon_prefs.shaders.clear()
_result = cls.shader_manager.initialize(addon_prefs)
return _result
@classmethod
def shader_load(cls, filename):
_result = cls.shader_manager.load(filename)
return _result
@classmethod
def shader_register(cls, sbsar):
_result = cls.shader_manager.register(sbsar)
return _result
@classmethod
def shader_presets_remove(cls, shader_presets):
_result = cls.shader_manager.remove_presets(shader_presets)
return _result
@classmethod
def shader_presets_save(cls, shader_preset):
_result = cls.shader_manager.save_presets(shader_preset)
return _result
# MSG SYSTEM
@classmethod
def msg_system(cls, op, data, request_type=Code_RequestType.r_sync):
if cls.toolkit_manager.is_running():
_result = cls.server_manager.server_send_message(
request_type,
Code_RequestEndpoint.system.value,
op.value,
data
)
if _result[0] != Code_Response.success:
return _result
return (Code_Response.success, json.loads(_result[1]))
else:
return (Code_Response.toolkit_not_running, None)
# MSG SBSAR
@classmethod
def msg_sbsar(cls, op, data, request_type=Code_RequestType.r_sync):
if cls.toolkit_manager.is_running():
_result = cls.server_manager.server_send_message(
request_type,
Code_RequestEndpoint.sbsar.value,
op.value,
data
)
if _result[0] != Code_Response.success:
return _result
return (Code_Response.success, json.loads(_result[1]))
else:
return (Code_Response.toolkit_not_running, None)
# MSG PRESET
@classmethod
def msg_preset(cls, op, data, request_type=Code_RequestType.r_sync):
if cls.toolkit_manager.is_running():
_result = cls.server_manager.server_send_message(
request_type,
Code_RequestEndpoint.preset.value,
op.value,
data
)
if _result[0] != Code_Response.success:
return _result
return (Code_Response.success, json.loads(_result[1]))
else:
return (Code_Response.toolkit_not_running, None)
@@ -0,0 +1,57 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: dispatcher.py
# brief: Async comms handler
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import json
from ..utils import SUBSTANCE_Utils
from ..network.callback import SRE_CallbackInterface
from ..ops.common import load_sbsar, load_usdz
from ..common import Code_CallbackEndpoint as endpoint
from ..thread_ops import SUBSTANCE_Threads
class Server_POST_Link(SRE_CallbackInterface):
def execute(self, message):
if message["type"] != endpoint.link.value:
return
_pre_data = message["data"]["message"]
_data = json.loads(_pre_data)
_file_path = _data["path"]
_file_name = os.path.basename(_file_path)
_, _file_ext = os.path.splitext(_file_name)
if len(_data["path"]) > 0:
_uuid = _data["uuid"]
if _file_ext == ".sbsar":
load_sbsar(_file_name, _file_path, _uuid)
elif _file_ext == ".usdz":
load_usdz(_file_name, _file_path, _uuid)
else:
def send_message():
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance Connector file [{}] failed to load".format(_file_name),
display=True)
SUBSTANCE_Threads.main_thread_run(send_message)
@@ -0,0 +1,38 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: render.py
# brief: Async comms handler
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
from ..network.callback import SRE_CallbackInterface
from ..api import SUBSTANCE_Api
from ..common import Code_CallbackEndpoint as endpoint
class Server_POST_Render(SRE_CallbackInterface):
def execute(self, message):
if message["type"] != endpoint.render.value:
return
_data = message["data"]
for _output in _data["outputs"]:
if "path" in _output:
_new_path = _output["path"].replace("\\", "/")
_output["path"] = _new_path
SUBSTANCE_Api.sbsar_render_callback(_data)
@@ -0,0 +1,425 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: common.py
# brief: Global variables and Enumerators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import sys
import os
import pathlib
import math
import bpy
from bpy.utils import previews
from enum import Enum
# Substance Remote Engine
if sys.platform == "win32":
SRE_DIR = "AppData/Roaming/Adobe/Substance3DIntegrationTools"
SRE_BIN = "substance_remote_engine.exe"
elif sys.platform == "linux":
SRE_DIR = "Adobe/Substance3DIntegrationTools"
SRE_BIN = "substance_remote_engine"
elif sys.platform == "darwin":
SRE_DIR = "Library/Application Support/Adobe/Substance3DIntegrationTools"
SRE_BIN = "substance_remote_engine"
SRE_ENGINE_DICT = {
"WINDOWS":
[("DX", "DirectX", "DX"),
("OGL", "OpenGL", "OGL"),
("CPU", "CPU", "CPU"),
("VK", "Vulkan", "VK")],
"LINUX":
[("OGL", "OpenGL", "OGL"),
("CPU", "CPU", "CPU"),
("VK", "Vulkan", "VK")],
"DARWIN":
[("MTL", "Metal", "MTL"),
("OGL", "OpenGL", "OGL"),
("CPU", "CPU", "CPU"),
("VK", "Vulkan", "VK")]
}
# Addon
ADDON_PACKAGE = __package__
ADDON_ROOT = os.path.dirname(__file__)
# Draw
DRAW_DEFAULT_FACTOR = 0.3
# Path
PATH_DEFAULT = bpy.path.native_pathsep(os.path.join(pathlib.Path.home(), "Documents/Adobe/Substance3DInBlender/export"))
PATH_LIBARY_DEFAULT = bpy.path.native_pathsep(os.path.join(pathlib.Path.home(), "Desktop"))
# Substance Remote Engine
SRE_HOST = "127.0.0.1"
SRE_PORT = 41646
# Blender Addon Server
SERVER_HOST = "127.0.0.1"
SERVER_ALLOW_LIST = ['127.0.0.1', 'localhost']
SERVER_TIMEOUT_S = 5
# Client
CLIENT_THREAD_THROTTLE_MS = 5
CLIENT_BUFFER_SIZE = 2048
# Render
RENDER_MAX_RESOLUTION_SYNC = [10, 10]
RENDER_KEY = "{}_{}"
RENDER_IMG_UPDATE_DELAY_S = 0.0001
# Toolkit
TOOLKIT_NAME = "Substance3DIntegrationTools"
TOOLKIT_EXT = ".zip"
TOOLKIT_VERSION_FILE = "version.txt"
TOOLKIT_LAG_TIME = 2
TOOLKIT_INSTALL_TIME = 5
# Keep only the latest 3 compatible versions to avoid cluttering
TOOLKIT_EXPECTED_VERSION = ["2.1.1", "2.1.0", "2.0.0"]
# Web site links
WEB_SUBSTANCE_PRERELEASE = "https://www.adobeprerelease.com/beta/3DF9B9CB-7B2C-4B54-E279-86F9A93E82CD"
WEB_SUBSTANCE_TOOLS = "https://substance3d.adobe.com/plugins/substance-in-blender/#:~:text=The%20Substance%203D%20add-on,optimized%20features%20for%20enhanced%20productivity.&text=The%20add-on%20is%20in%20public%20" # noqa
WEB_SUBSTANCE_SHARE = "https://share-beta.substance3d.com/"
WEB_SUBSTANCE_SOURCE = "https://source.substance3d.com/"
WEB_SUBSTANCE_DOCS = "https://substance3d.adobe.com/documentation/integrations/blender-232292555.html"
WEB_SUBSTANCE_FORUMS = "https://community.adobe.com/t5/substance-3d-plugins/ct-p/ct-substance-3d-plugins?page=1&sort=latest_replies&lang=all&tabid=all" # noqa
WEB_SUBSTANCE_DISCORD = "https://discord.gg/substance3d"
# UI Panels
UI_SPACES = (
['3D View', 'VIEW_3D'],
['Node Editor', 'NODE_EDITOR'],
['Image Generic', 'IMAGE_EDITOR']
)
# SHORTCUTS
SHORTCUT_CLASS_NAME = 'SUBSTANCE_MT_MAIN_{}'
# APPLY TYPE
APPLY_TYPE_DICT = [
("INSERT", "INSERT", "Insert at the top"),
("APPEND", "APPEND", "Append at the bottom"),
]
# IMAGE EXPORT
IMAGE_EXPORT_FORMAT = [
("0", "BMP", "*.bmp"),
("1", "PNG", "*.png"),
("2", "JPEG", "*.jpeg"),
("3", "JPEG2000", "*.jp2"),
("4", "TARGA", "*.targa"),
("5", "TARGA_RAW", "*.targa"),
("6", "OPEN_EXR", "*.exr"),
("7", "HDR", "*.hdr"),
("8", "TIFF", "*.tiff")
]
IMAGE_FORMAT_DICT = [
("BMP", "bmp", "*.bmp"),
("EXR", "exr", "*.exr"),
("GIF", "gif", "*.gif"),
("HDR", "hdr", "*.hdr"),
("ICO", "ico", "*.ico"),
("J2K", "j2k", "*.j2k"),
("J2C", "j2c", "*.j2c"),
("JP2", "jp2", "*.jp2"),
("JPG", "jpg", "*.jpg"),
("JIF", "jif", "*.jif"),
("JPEG", "jpeg", "*.jpeg"),
("JPE", "jpe", "*.jpe"),
("JXR", "jxr", "*.jxr"),
("WDP", "wdp", "*.wdp"),
("HDP", "hdp", "*.hdp"),
("PBM", "pbm", "*.pbm"),
("PBMRAW", "pbm raw", "*.pbm"),
("PFM", "pfm", "*.pfm"),
("PGM", "pgm", "*.pgm"),
("PGMRAW", "pgm raw", "*.pgm"),
("PNG", "png", "*.png"),
("PPM", "ppm", "*.ppm"),
("TGA", "tga", "*.tga"),
("TARGA", "targa", "*.targa"),
("TIF", "tif", "*.tif"),
("TIFF", "tiff", "*.tiff"),
("WAP", "wap", "*.wap"),
("WBMP", "wbmp", "*.wbmp"),
("WBM", "wbm", "*.wbm"),
("WEBP", "webp", "*.webp"),
("XPM", "xpm", "*.xpm")
]
IMAGE_BITDEPTH_DICT = {
"BMP": [("8", "8", "8")],
"EXR": [("32", "32", "32")],
"GIF": [("8", "8", "8")],
"HDR": [("32", "32", "32")],
"ICO": [("8", "8", "8")],
"J2K": [("8", "8", "8"), ("16", "16", "16")],
"J2C": [("8", "8", "8"), ("16", "16", "16")],
"JP2": [("8", "8", "8"), ("16", "16", "16")],
"JPG": [("8", "8", "8")],
"JIF": [("8", "8", "8")],
"JPEG": [("8", "8", "8")],
"JPE": [("8", "8", "8")],
"JXR": [("8", "8", "8"), ("16", "16", "16"), ("32", "32", "32")],
"WDP": [("8", "8", "8"), ("16", "16", "16"), ("32", "32", "32")],
"HDP": [("8", "8", "8"), ("16", "16", "16"), ("32", "32", "32")],
"PBM": [("8", "8", "8")],
"PBMRAW": [("8", "8", "8")],
"PFM": [("32", "32", "32")],
"PGM": [("8", "8", "8"), ("16", "16", "16")],
"PGMRAW": [("8", "8", "8"), ("16", "16", "16")],
"PNG": [("8", "8", "8"), ("16", "16", "16")],
"PPM": [("8", "8", "8"), ("16", "16", "16")],
"TGA": [("8", "8", "8")],
"TARGA": [("8", "8", "8")],
"TIF": [("8", "8", "8"), ("16", "16", "16"), ("32", "32", "32")],
"TIFF": [("8", "8", "8"), ("16", "16", "16"), ("32", "32", "32")],
"WAP": [("8", "8", "8")],
"WBMP": [("8", "8", "8")],
"WBM": [("8", "8", "8")],
"WEBP": [("8", "8", "8")],
"XPM": [("8", "8", "8")]
}
# Icons
ICONS_DICT = previews.new()
ICONS_IMAGES = (
{"id": "share_icon", "filename": "share.png"},
{"id": "source_icon", "filename": "source.png"},
{"id": "random_icon", "filename": "random.png"},
{"id": "shuffle_icon", "filename": "shuffle.png"},
{"id": "loading", "filename": "loading.png"},
{"id": "loading_error", "filename": "loading_error.png"},
{"id": "render", "filename": "render.png"},
{"id": "render_queue", "filename": "render_queue.png"},
)
# Outputs Filter
OUTPUTS_FILTER_DICT = (
("enabled", "Enabled", "Show enabled outputs", "CHECKMARK", 1),
("shader", "Shader", "Show only shader outputs", "MATERIAL", 2),
("all", "All", "Show all available outputs", "COLLAPSEMENU", 3)
)
SHADER_OUTPUT_UNKNOWN_USAGE = "UNKNOWN"
# Parameters
INPUTS_MAX_RANDOM_SEED = 32767
INPUT_ANGLE_CONVERSION = math.pi * 2
INPUT_INT_MAX = 2 ** 31
INPUT_UPDATE_DELAY_S = 0.25
# GROUPS
INPUT_DEFAULT_GROUP = "General"
INPUT_CHANNELS_GROUP = "Channels"
INPUT_IMAGE_DEFAULT_GROUP = "Input Images"
INPUT_TECHINCAL_GROUP = "Technical parameters"
# RESOLUTIONS
RESOLUTIONS_DICT = (
('5', '32', ''),
('6', '64', ''),
('7', '128', ''),
('8', '256', ''),
('9', '512', ''),
('10', '1024', ''),
('11', '2048', ''),
('12', '4096', '')
)
# CLASS_NAME
CLASS_SHADER_INPUTS = "SUBSTANCE_SHP_{}"
CLASS_GRAPH_INPUTS = "SUBSTANCE_SGI_{}"
# PRESET_LABELS
PRESET_DEFAULT = "DEFAULT"
PRESET_CUSTOM = "CUSTOM"
# PRESET_EXTENSION
PRESET_EXTENSION = ".sbsprs"
class Code_RequestEndpoint(Enum):
system = "Lwnd-CHcT-uJlw-YSw3"
sbsar = "m7ef-7gYN-zTGu-4D3w"
preset = "S4Aa-CHHa-IHib-bpY3"
class Code_CallbackEndpoint(Enum):
render = "UNW4-UkJs-cxug-R2fK"
link = "cJiQ-IfbV-Tco8-JOaB"
class Code_RequestOp(Enum):
add = 0
remove = 1
update = 2
kill = 3
render = 4
load = 5
class Code_RequestType(Enum):
r_sync = 1
r_async = 2
class Code_SbsarOp(Enum):
load = 0
reload = 1
duplicate = 2
class Code_Response(Enum):
success = 0
toolkit_already_started = 1
toolkit_not_running = 2
toolkit_not_installed = 3
toolkit_in_use = 4
toolkit_stop_error = 5
toolkit_process_error = 6
toolkit_remove_error = 7
toolkit_version_error = 8
toolkit_version_get_error = 9
toolkit_version_empty_error = 10
toolkit_version_not_found_error = 11
toolkit_file_not_recognized_error = 12
toolkit_file_ext_error = 13
toolkit_install_error = 14
client_connection_error = 15
client_connection_refused_error = 16
server_request_type_error = 17
server_already_running = 18
server_not_running_error = 19
server_start_error = 20
server_stop_error = 21
sbsar_factory_register_error = 22
sbsar_factory_unregister_error = 23
sbsar_remove_not_found_error = 24
shader_preset_load_error = 25
input_image_empty = 26
preset_create_no_name_error = 27
preset_create_get_error = 28
preset_export_error = 29
preset_import_error = 30
preset_import_not_graph = 31
class Code_InputIdentifier(Enum):
outputsize = "$outputsize"
randomseed = "$randomseed"
pixelsize = "$pixelsize"
class Code_OutputSizeSuffix(Enum):
width = "_width"
height = "_height"
linked = "_linked"
class Code_InputType(Enum):
float = 0
float2 = 1
float3 = 2
float4 = 3
integer = 4
integer2 = 8
integer3 = 9
integer4 = 10
image = 5
string = 6
font = 7
other = -1
class Code_InputWidget(Enum):
combobox = "Combobox"
slider = "Slider"
color = "Color"
togglebutton = "Togglebutton"
image = "Image"
angle = "Angle"
position = "Position"
nowidget = "NoWidget"
class Code_Input(Enum):
combobox = "combobox"
slider_float = "slider_float"
slider_int = "slider_int"
other = "other"
class Code_ShaderInputType(Enum):
image = "image"
integer = "integer"
integer_maxmin = "integer_maxmin"
integer_slider = "integer_slider"
integer2 = "integer2"
integer2_maxmin = "integer2_maxmin"
integer2_slider = "integer2_slider"
integer3 = "integer3"
integer3_maxmin = "integer3_maxmin"
integer3_slider = "integer3_slider"
integer4 = "integer4"
integer4_maxmin = "integer4_maxmin"
integer4_slider = "integer4_slider"
float = "float"
float_maxmin = "float_maxmin"
float_slider = "float_slider"
float2 = "float2"
float2_maxmin = "float2_maxmin"
float2_slider = "float2_slider"
float3 = "float3"
float3_maxmin = "float3_maxmin"
float3_slider = "float3_slider"
float4 = "float4"
float4_maxmin = "float4_maxmin"
float4_slider = "float4_slider"
enum = "enum"
other = "other"
class Code_SbsarLoadSuffix(Enum):
loading = [" (loading...)", "loading"]
error = [" (error)", "loading_error"]
render = [" (rendering...)", "render"]
render_queue = [" (render_queue...)", "render_queue"]
success = ["", "NONE"]
@@ -0,0 +1,526 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: factory/sbsar.py
# brief: Dynamic class creation for sbsar objects
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from copy import deepcopy
import sys
import traceback
from ..utils import SUBSTANCE_Utils
from ..sbsar.callbacks import SUBSTANCE_SbsarCallbacks
from ..common import (
Code_InputWidget,
Code_InputType,
Code_InputIdentifier,
Code_OutputSizeSuffix,
Code_Response,
RESOLUTIONS_DICT,
INPUT_ANGLE_CONVERSION,
INPUT_INT_MAX
)
# Inputs functions
def _to_json(self):
pass
def _from_json(self, inputs, data):
for _item in data:
if Code_InputIdentifier.outputsize.value == _item["identifier"]:
_output_size = _item["value"]
_output_size_linked = _output_size[0] == _output_size[1]
setattr(
self,
Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.width.value,
str(_output_size[0]))
setattr(
self,
Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.height.value,
str(_output_size[1]))
setattr(
self,
Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.linked.value,
_output_size_linked)
continue
elif not hasattr(self, _item["identifier"]):
continue
_input = inputs[_item["identifier"]]
_value = _item["value"]
if _input.guiWidget == Code_InputWidget.combobox.value:
_value = str(_value)
elif _input.guiWidget == Code_InputWidget.slider.value:
pass
elif _input.guiWidget == Code_InputWidget.color.value:
pass
elif _input.guiWidget == Code_InputWidget.togglebutton.value:
_value = str(_value)
elif _input.guiWidget == Code_InputWidget.angle.value:
_value = _value * INPUT_ANGLE_CONVERSION
elif _input.guiWidget == Code_InputWidget.position.value:
pass
elif _input.guiWidget == Code_InputWidget.image.value:
pass
elif _input.identifier == Code_InputIdentifier.randomseed.value:
pass
else:
pass
setattr(self, _item["identifier"], _value)
class SUBSTANCE_SbsarFactory():
@staticmethod
def init_enum_values(values):
_items = []
for _item in values:
_items.append(
(str(_item.first), _item.second, "{}:{}".format(_item.first, _item.second))
)
return _items
@staticmethod
def init_toggle_values(values):
_items = []
for _idx, _item in enumerate(values):
_items.append(
(str(_idx), _item, "{}:{}".format(_idx, _item))
)
return _items
@staticmethod
def create_input_item(input, class_name):
if input.type == Code_InputType.string.name:
return bpy.props.StringProperty(
name=input.label,
description=input.guiDescription,
default=str(input.defaultValue),
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(self, context, input.identifier))
elif input.guiWidget == Code_InputWidget.combobox.value:
return bpy.props.EnumProperty(
name=input.label,
description=input.guiDescription,
default=str(input.defaultValue),
items=SUBSTANCE_SbsarFactory.init_enum_values(input.enumValues),
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(self, context, input.identifier))
elif input.guiWidget == Code_InputWidget.slider.value:
if input.type == Code_InputType.integer.name:
_max = input.maxValue
_min = input.minValue
if _max == _min:
_max = INPUT_INT_MAX
_min = INPUT_INT_MAX*-1
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.IntProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.IntProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif input.type == Code_InputType.float.name:
_max = input.maxValue
_min = input.minValue
if _max == _min:
_max = sys.float_info.max
_min = sys.float_info.min
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.FloatProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.FloatProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif (input.type == Code_InputType.integer2.name or
input.type == Code_InputType.integer3.name or
input.type == Code_InputType.integer4.name):
_dimension = len(input.defaultValue)
_max = input.maxValue[0]
_min = input.minValue[0]
if _max == _min:
_max = INPUT_INT_MAX
_min = INPUT_INT_MAX*-1
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.IntVectorProperty(
name=input.label,
description=input.guiDescription,
size=_dimension,
default=input.defaultValue,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.IntVectorProperty(
name=input.label,
description=input.guiDescription,
size=_dimension,
default=input.defaultValue,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif (input.type == Code_InputType.float2.name or
input.type == Code_InputType.float3.name or
input.type == Code_InputType.float4.name):
_dimension = len(input.defaultValue)
_max = input.maxValue[0]
_min = input.minValue[0]
if _max == _min:
_max = sys.float_info.max
_min = sys.float_info.min
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.FloatVectorProperty(
name=input.label,
description=input.guiDescription,
size=_dimension,
default=input.defaultValue,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.FloatVectorProperty(
name=input.label,
description=input.guiDescription,
size=_dimension,
default=input.defaultValue,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return None
elif input.guiWidget == Code_InputWidget.color.value:
if input.type == Code_InputType.float.name:
_max = input.maxValue
_min = input.minValue
if _max == _min:
_max = 1
_min = 0
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.FloatProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.FloatProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif input.type == Code_InputType.float3.name or input.type == Code_InputType.float4.name:
_dimension = len(input.defaultValue)
_max = input.maxValue[0]
_min = input.minValue[0]
if _max == _min:
_max = 1
_min = 0
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.FloatVectorProperty(
name=input.label,
description=input.guiDescription,
subtype="COLOR",
size=_dimension,
default=input.defaultValue,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.FloatVectorProperty(
name=input.label,
description=input.guiDescription,
subtype="COLOR",
size=_dimension,
default=input.defaultValue,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return None
elif input.guiWidget == Code_InputWidget.togglebutton.value:
_label_true = input.labelTrue if input.labelTrue != "" else "True"
_label_false = input.labelFalse if input.labelFalse != "" else "False"
_toggle_labels = [_label_false, _label_true]
return bpy.props.EnumProperty(
name=input.label,
description=input.guiDescription,
default=str(input.defaultValue),
items=SUBSTANCE_SbsarFactory.init_toggle_values(_toggle_labels),
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif input.guiWidget == Code_InputWidget.angle.value:
_max = input.maxValue * INPUT_ANGLE_CONVERSION
_min = input.minValue * INPUT_ANGLE_CONVERSION
_default = input.defaultValue * INPUT_ANGLE_CONVERSION
if _max == _min:
_max = sys.float_info.max
_min = sys.float_info.min
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.FloatProperty(
name=input.label,
description=input.guiDescription,
subtype="ANGLE",
default=_default,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.FloatProperty(
name=input.label,
description=input.guiDescription,
subtype="ANGLE",
default=_default,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif input.guiWidget == Code_InputWidget.position.value:
_dimension = len(input.defaultValue)
_max = input.maxValue[0]
_min = input.minValue[0]
if _max == _min:
_max = 1
_min = 0
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.FloatVectorProperty(
name=input.label,
description=input.guiDescription,
subtype="XYZ",
size=_dimension,
default=input.defaultValue,
max=_max,
min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.FloatVectorProperty(
name=input.label,
description=input.guiDescription,
subtype="XYZ",
size=_dimension,
default=input.defaultValue,
soft_max=_max,
soft_min=_min,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif input.guiWidget == Code_InputWidget.image.value:
return bpy.props.PointerProperty(
name=input.label,
description=input.guiDescription,
type=bpy.types.Image,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
elif input.guiWidget == Code_InputWidget.nowidget.value:
if input.identifier == Code_InputIdentifier.randomseed.value:
if hasattr(input, "sliderClamp") and input.sliderClamp:
return bpy.props.IntProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
max=input.maxValue,
min=input.minValue,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
else:
return bpy.props.IntProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue,
soft_max=input.maxValue,
soft_min=input.minValue,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_input_changed(
self,
context,
input.identifier))
if input.identifier == Code_InputIdentifier.outputsize.value:
return [
bpy.props.EnumProperty(
name=input.label,
description=input.guiDescription,
default=str(input.defaultValue[0]),
items=RESOLUTIONS_DICT,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_linked_changed(
self,
context,
input.identifier + Code_OutputSizeSuffix.width.value)),
bpy.props.EnumProperty(
name=input.label,
description=input.guiDescription,
default=str(input.defaultValue[1]),
items=RESOLUTIONS_DICT,
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_outputsize_changed(
self,
context,
input.identifier + Code_OutputSizeSuffix.height.value)),
bpy.props.BoolProperty(
name=input.label,
description=input.guiDescription,
default=input.defaultValue[0] == input.defaultValue[1],
update=lambda self, context: SUBSTANCE_SbsarCallbacks.on_linked_changed(
self,
context,
input.identifier + Code_OutputSizeSuffix.linked.value))
]
else:
return None
else:
return None
@staticmethod
def register_inputs_class(sbsar):
for _graph in sbsar.graphs:
_attributes = {}
for _key, _input in _graph.inputs.items():
_attribute = SUBSTANCE_SbsarFactory.create_input_item(_input, _graph.inputs_class_name)
if _attribute:
if _input.identifier == Code_InputIdentifier.outputsize.value:
_attributes[_input.identifier + Code_OutputSizeSuffix.width.value] = _attribute[0]
_attributes[_input.identifier + Code_OutputSizeSuffix.height.value] = _attribute[1]
_attributes[_input.identifier + Code_OutputSizeSuffix.linked.value] = _attribute[2]
else:
_attributes[_input.identifier] = _attribute
else:
SUBSTANCE_Utils.log_data("WARNING", "Input not created [{}]".format(_input.identifier))
_inputs_class = type(_graph.inputs_class_name, (bpy.types.PropertyGroup,), {
"__annotations__": _attributes,
"sbsar_uuid": sbsar.uuid,
"default": deepcopy(_graph),
"callback": {"enabled": True},
"to_json": _to_json,
"from_json": _from_json
})
bpy.utils.register_class(_inputs_class)
setattr(
bpy.types.Scene,
_graph.inputs_class_name,
bpy.props.PointerProperty(name=_graph.inputs_class_name, type=_inputs_class))
@staticmethod
def register_class(sbsar):
try:
SUBSTANCE_SbsarFactory.register_inputs_class(sbsar)
return (Code_Response.success, sbsar)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Susbtance register error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.sbsar_factory_register_error, None)
@staticmethod
def unregister_class(class_name):
if hasattr(bpy.context.scene, class_name):
_object = getattr(bpy.context.scene, class_name)
_class_type = type(_object)
delattr(bpy.types.Scene, class_name)
bpy.utils.unregister_class(_class_type)
@@ -0,0 +1,106 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: factory/shader.py
# brief: Dynamic class creation for shader objects
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
import traceback
from ..utils import SUBSTANCE_Utils
from ..shader.callbacks import SUBSTANCE_ShaderCallbacks
from ..common import (
Code_ShaderInputType,
Code_Response
)
class SUBSTANCE_ShaderFactory():
# Shader preset inputs
@staticmethod
def create_input_item(input):
if (input.type == Code_ShaderInputType.float_slider.value or
input.type == Code_ShaderInputType.float_maxmin.value):
return bpy.props.FloatProperty(
name=input.id,
default=input.default,
soft_max=input.max,
soft_min=input.min,
update=SUBSTANCE_ShaderCallbacks.on_input_changed)
else:
return None
@staticmethod
def register_inputs_class(shader_preset):
_attributes = {}
for _key, _input in shader_preset.inputs.items():
_attribute = SUBSTANCE_ShaderFactory.create_input_item(_input)
if _attribute:
_attributes[_key] = _attribute
def _on_reset(self):
for _attr_name in self.__annotations__:
_input = None
for _key, _i in self.shader_preset.inputs.items():
if _i.id == _attr_name:
_input = _i
break
if _input is not None:
setattr(self, _attr_name, _input.default)
def _get(self):
_obj = self.shader_preset.to_json()
for _key, _item in _obj["inputs"].items():
_item["default"] = getattr(self, _item["id"])
return _obj["inputs"]
_inputs_class = type(
shader_preset.inputs_class_name,
(bpy.types.PropertyGroup,),
{
"__annotations__": _attributes,
"shader_preset": shader_preset,
"reset": _on_reset,
"get": _get
})
bpy.utils.register_class(_inputs_class)
setattr(
bpy.types.Scene,
shader_preset.inputs_class_name,
bpy.props.PointerProperty(name=shader_preset.inputs_class_name, type=_inputs_class))
# General
@staticmethod
def register_class(shader_preset):
try:
SUBSTANCE_ShaderFactory.register_inputs_class(shader_preset)
return (Code_Response.success, shader_preset)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Shader register error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.sbsar_factory_register_error, None)
@staticmethod
def unregister_class(class_name):
if hasattr(bpy.context.scene, class_name):
_object = getattr(bpy.context.scene, class_name)
_class_type = type(_object)
delattr(bpy.types.Scene, class_name)
bpy.utils.unregister_class(_class_type)
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,710 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: material/manager.py
# brief: Material operations manager
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import bpy
import time
import traceback
from copy import deepcopy
from ..thread_ops import SUBSTANCE_Threads
from ..utils import SUBSTANCE_Utils
from ..common import RENDER_IMG_UPDATE_DELAY_S, ADDON_PACKAGE
class SUBSTANCE_MaterialManager():
@staticmethod
def get_image(name, filepath):
if name in bpy.data.images:
_image = bpy.data.images[name]
_image_filepath = bpy.path.abspath(_image.filepath)
_image_filepath = os.path.abspath(_image_filepath)
_image_filepath = _image_filepath.replace("\\", "/")
_new_filepath = filepath.replace("\\", "/")
if _image_filepath != _new_filepath:
_image.filepath = _new_filepath
_image.reload()
return _image
_image = bpy.data.images.load(filepath=filepath.replace("\\", "/"))
_image.name = name
return _image
@staticmethod
def get_existing_material(material_name):
if material_name in bpy.data.materials:
return bpy.data.materials[material_name]
return None
@staticmethod
def reset_image(node, image):
def _set_image():
node.image = image
SUBSTANCE_Threads.main_thread_run(_set_image)
@staticmethod
def auto_apply_material(context, data, material):
_selected_geo = SUBSTANCE_Utils.get_selected_geo(context.selected_objects)
if len(_selected_geo) > 0 and data["graph_idx"] == 0:
_selected_objects = [bpy.context.active_object]
SUBSTANCE_MaterialManager.apply_material(context, _selected_objects, material)
@staticmethod
def apply_material(context, objects, material):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
for _obj in objects:
if not hasattr(_obj.data, "materials"):
continue
if _addon_prefs.default_apply_type == "INSERT" and _obj.data.materials:
# _obj.data.materials.append(material)
_obj.active_material = material
else:
_obj.data.materials.append(material)
@staticmethod
def empty_material(material, graph):
material.use_nodes = True
try:
material.cycles.displacement_method = 'BOTH'
except Exception:
pass
# Cleanup graph
_mat_nodes = material.node_tree.nodes
for _node in _mat_nodes:
_mat_nodes.remove(_node)
# Cleanup Node groups
if graph.material.name in bpy.data.node_groups:
_subgroup = bpy.data.node_groups[graph.material.name]
for _node in _subgroup.nodes:
_subgroup.nodes.remove(_node)
if bpy.app.version >= (4, 0, 0):
for _item in _subgroup.interface.items_tree:
if _item.item_type == 'SOCKET':
if _item.in_out == 'INPUT' or _item.in_out == 'OUTPUT':
_subgroup.interface.remove(_item)
else:
for _input in _subgroup.inputs:
_subgroup.inputs.remove(_input)
for _output in _subgroup.outputs:
_subgroup.outputs.remove(_output)
@staticmethod
def init_nodes(material, graph, shader_graph):
_items = {}
for _node in shader_graph["nodes"]:
_name = _node["name"].replace("$matname", graph.material.name)
if _node["path"] == "root":
_nodes = material.node_tree.nodes
else:
_nodes = _items[_node["path"].replace("root/", "")].node_tree.nodes
if _name in _nodes:
_items[_node["id"]] = _nodes[_name]
else:
_items[_node["id"]] = _nodes.new(_node["type"])
_items[_node["id"]].name = _name
if _node["type"] == "NodeFrame":
_items[_node["id"]].label = _node["label"]
continue
_items[_node["id"]].location = (_node["location"][0], _node["location"][1])
if _node["type"] == "ShaderNodeGroup":
if graph.material.name in bpy.data.node_groups:
_node_tree = bpy.data.node_groups[graph.material.name]
else:
_node_tree = bpy.data.node_groups.new(
type='ShaderNodeTree',
name=graph.material.name)
_items[_node["id"]].node_tree = _node_tree
return _items
@staticmethod
def init_outputs(items, sbs_group, shader_prefs, shader_graph, addons_prefs, data, graph, new_nodes=None):
_location = [-600, 0]
for _output in graph.outputs:
if _output.name not in data["outputs"]:
continue
if not data["outputs"][_output.name]["enabled"]:
continue
if _output.type == "image":
if data["outputs"][_output.name]["path"] != "":
_filepath = data["outputs"][_output.name]["path"]
_filename = bpy.path.basename(data["outputs"][_output.name]["path"])
_output.filepath = _filepath
_output.filename = _filename
else:
_output.filepath = ""
_output.filename = ""
continue
_name = "Tx {}".format(_output.name)
_key = "tx_{}".format(_output.name)
if _name in sbs_group.node_tree.nodes:
items[_key] = sbs_group.node_tree.nodes[_name]
else:
if new_nodes is not None:
new_nodes.append(_key)
items[_key] = sbs_group.node_tree.nodes.new("ShaderNodeTexImage")
items[_key].name = "Tx {}".format(_output.name)
_img_name = "{}_{}".format(graph.material.name, _output.name)
_img = SUBSTANCE_MaterialManager.get_image(_img_name, _filepath)
items[_key].image = _img
if _output.name in shader_prefs["outputs"]:
_shader_output = shader_prefs["outputs"][_output.name]
_img.colorspace_settings.name = _shader_output["colorspace"]
else:
_img.colorspace_settings.name = addons_prefs.output_default_colorspace
if (_output.name in shader_graph["outputs"] and
"normal" in shader_graph["outputs"][_output.name]):
_nrm_key = "normal_{}".format(_output.name)
if new_nodes is not None:
new_nodes.append(_nrm_key)
items[_nrm_key] = sbs_group.node_tree.nodes.new("ShaderNodeNormalMap")
items[_nrm_key].name = "Normal {}".format(_output.name)
items[_nrm_key].location = (_location[0] + 300, _location[1])
# Add common properties to outputs that are not part of the shader
if _output.name not in shader_graph["outputs"]:
for _property in shader_graph["properties"]:
if _property["id"] == "tx_":
_new_propery = deepcopy(_property)
_new_propery["id"] = "tx_{}".format(_output.name)
shader_graph["properties"].append(_new_propery)
items[_key].location = (_location[0], _location[1])
_location[1] -= 300
else:
_name = "Val {}".format(_output.name)
_key = "val_{}".format(_output.name)
_value = data["outputs"][_output.name]["value"]
if _output.type == "integer2" or _output.type == "float2":
_value.append(0)
_value.append(0)
elif _output.type == "integer3" or _output.type == "float3":
_value.append(0)
if _name in sbs_group.node_tree.nodes:
items[_key] = sbs_group.node_tree.nodes[_name]
else:
if new_nodes is not None:
new_nodes.append(_key)
if _output.type == "integer" or _output.type == "float":
items[_key] = sbs_group.node_tree.nodes.new("ShaderNodeValue")
else:
items[_key] = sbs_group.node_tree.nodes.new("ShaderNodeCombineXYZ")
if _output.type == "integer" or _output.type == "float":
items[_key].outputs[0].default_value = _value
else:
items[_key].inputs[0].default_value = _value[0]
items[_key].inputs[1].default_value = _value[1]
items[_key].inputs[2].default_value = _value[2]
items[_key].location = (_location[0], _location[1])
_location[1] -= 300
@staticmethod
def init_sockets(items, shader_graph):
# Initialize shader sockets
for _socket in shader_graph["sockets"]:
if "dependency" in _socket:
if _socket["dependency"] not in items:
continue
if bpy.app.version >= (4, 0, 0):
if _socket["source"] == "input" and _socket["name"] not in items[_socket["id"]].inputs:
items[_socket["id"]].node_tree.interface.new_socket(
_socket["name"],
in_out="INPUT",
socket_type=_socket["type"])
elif _socket["source"] == "output" and _socket["name"] not in items[_socket["id"]].outputs:
items[_socket["id"]].node_tree.interface.new_socket(
_socket["name"],
in_out="OUTPUT",
socket_type=_socket["type"])
else:
if _socket["source"] == "input" and _socket["name"] not in items[_socket["id"]].inputs:
items[_socket["id"]].node_tree.inputs.new(_socket["type"], _socket["name"])
elif _socket["source"] == "output" and _socket["name"] not in items[_socket["id"]].outputs:
items[_socket["id"]].node_tree.outputs.new(_socket["type"], _socket["name"])
@staticmethod
def create_dyna_links(dyna_links, sbs_group, graph, data):
for _output in graph.outputs:
if _output.name not in data["outputs"]:
continue
if _output.name not in sbs_group.outputs and data["outputs"][_output.name]["enabled"]:
# Create links
if _output.type == "image":
dyna_links.append({
"from": "NODE_GROUP_IN",
"to": "tx_{}".format(_output.name),
"output": "UV",
"input": "Vector",
"path": "root/SBSAR"
})
dyna_links.append({
"from": "tx_{}".format(_output.name),
"to": "NODE_GROUP_OUT",
"output": "Color",
"input": _output.name,
"path": "root/SBSAR"
})
elif _output.type == "integer" or _output.type == "float":
dyna_links.append({
"from": "val_{}".format(_output.name),
"to": "NODE_GROUP_OUT",
"output": "Value",
"input": _output.name,
"path": "root/SBSAR"
})
else:
dyna_links.append({
"from": "val_{}".format(_output.name),
"to": "NODE_GROUP_OUT",
"output": "Vector",
"input": _output.name,
"path": "root/SBSAR"
})
# Create sockets
if bpy.app.version >= (4, 0, 0):
if _output.type == "image":
sbs_group.node_tree.interface.new_socket(
name=_output.name,
in_out="OUTPUT",
socket_type="NodeSocketColor")
elif _output.type == "integer":
sbs_group.node_tree.interface.new_socket(
name=_output.name,
in_out="OUTPUT",
socket_type="NodeSocketInt")
elif _output.type == "float":
sbs_group.node_tree.interface.new_socket(
name=_output.name,
in_out="OUTPUT",
socket_type="NodeSocketFloat")
else:
sbs_group.node_tree.interface.new_socket(
name=_output.name,
in_out="OUTPUT",
socket_type="NodeSocketVectorXYZ")
else:
if _output.type == "image":
sbs_group.node_tree.outputs.new("NodeSocketColor", _output.name)
elif _output.type == "integer":
sbs_group.node_tree.outputs.new("NodeSocketInt", _output.name)
elif _output.type == "float":
sbs_group.node_tree.outputs.new("NodeSocketFloat", _output.name)
else:
sbs_group.node_tree.outputs.new("NodeSocketVectorXYZ", _output.name)
@staticmethod
def init_links(material, items, shader_graph):
for _link in shader_graph["links"]:
if bpy.app.version >= (4, 0, 0):
pass
else:
if _link["input"] == "Emission Color":
_link["input"] = "Emission"
if (_link["from"] in items and
_link["to"] in items and
_link["output"] in items[_link["from"]].outputs and
_link["input"] in items[_link["to"]].inputs):
if _link["path"] == "root":
material.node_tree.links.new(
items[_link["from"]].outputs[_link["output"]],
items[_link["to"]].inputs[_link["input"]])
else:
items[_link["path"].replace("root/", "")].node_tree.links.new(
items[_link["from"]].outputs[_link["output"]],
items[_link["to"]].inputs[_link["input"]])
@staticmethod
def init_dyna_links(material, items, dyna_links):
for _link in dyna_links:
if (_link["from"] in items and
_link["to"] in items and
_link["output"] in items[_link["from"]].outputs and
_link["input"] in items[_link["to"]].inputs):
if _link["path"] == "root":
material.node_tree.links.new(
items[_link["from"]].outputs[_link["output"]],
items[_link["to"]].inputs[_link["input"]])
else:
items[_link["path"].replace("root/", "")].node_tree.links.new(
items[_link["from"]].outputs[_link["output"]],
items[_link["to"]].inputs[_link["input"]])
@staticmethod
def remove_unused_nodes(items, shader_graph, mat_nodes):
for _node in shader_graph["nodes"]:
if "dependency" in _node:
for _value in _node["dependency"]:
if _value not in items:
if _node["path"] == "root":
mat_nodes.remove(items[_node["id"]])
else:
_node_path = _node["path"].replace("root/", "")
items[_node_path].node_tree.nodes.remove(items[_node["id"]])
del items[_node["id"]]
break
if _node["type"] == "NodeFrame":
for _key in _node["children"]:
if _key in items:
items[_key].parent = items[_node["id"]]
items[_node["id"]].update()
@staticmethod
def init_properties(items, shader_graph, shader_prefs, graph, data, context, new_nodes=None):
if new_nodes is None:
new_nodes = []
for _item in items.keys():
new_nodes.append(_item)
for _property in shader_graph["properties"]:
if _property["type"] == "emissive_intensity":
if "input" in _property and "emissive" in data["outputs"]:
_value = getattr(shader_prefs["inputs"], _property["type"])
if bpy.app.version >= (4, 0, 0):
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], _value)
else:
setattr(items[_property["id"]].inputs[20], _property["name"], _value)
else:
if bpy.app.version >= (4, 0, 0):
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], 0.0)
else:
setattr(items[_property["id"]].inputs[20], _property["name"], 0.0)
else:
if _property["id"] not in items:
continue
if _property["id"] not in new_nodes:
continue
if "dependency" in _property:
for _value in _property["dependency"]:
if _value not in items:
continue
if _property["type"] == "string":
setattr(items[_property["id"]], _property["name"], _property["value"])
elif _property["type"] == "float":
setattr(items[_property["id"]], _property["name"], _property["value"])
elif _property["type"] == "tiling":
if "input" in _property:
_value = graph.tiling.get()
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], _value)
elif _property["type"] == "physical_size":
if "input" in _property:
_value = graph.physical_size.get()
_value = SUBSTANCE_Utils.get_physical_size(_value, context)
_value = [1/_value[0], 1/_value[1], 1/_value[0]]
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], _value)
elif _property["type"] == "ao_mix":
if "input" in _property:
_value = getattr(shader_prefs["inputs"], _property["type"])
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], _value)
elif _property["type"] == "disp_midlevel":
if "input" in _property:
_value = getattr(shader_prefs["inputs"], _property["type"])
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], _value)
elif _property["type"] == "disp_scale":
if "input" in _property:
_value = getattr(shader_prefs["inputs"], _property["type"])
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], _value)
elif _property["type"] == "disp_physical_scale":
if "input" in _property:
_value = graph.physical_size.get()[2]
setattr(items[_property["id"]].inputs[_property["input"]], _property["name"], _value)
elif _property["type"] == "projection_blend":
_value = getattr(shader_prefs["inputs"], _property["type"])
setattr(items[_property["id"]], _property["name"], _value)
else:
setattr(items[_property["id"]], _property["name"], _property["value"])
@staticmethod
def clean_sbsar_group(sbs_group, sbs_group_nodes, graph, data):
# Remove unused sockets
if bpy.app.version >= (4, 0, 0):
for _output in sbs_group.node_tree.interface.items_tree:
if _output.name not in data["outputs"]:
if _output.item_type == 'SOCKET':
if _output.in_out == 'OUTPUT':
sbs_group.node_tree.interface.remove(_output)
else:
for _output in sbs_group.node_tree.outputs:
if _output.name not in data["outputs"]:
sbs_group.node_tree.outputs.remove(_output)
# Remove disabled SBSAR nodes
for _node in sbs_group_nodes:
if (type(_node) is not bpy.types.ShaderNodeTexImage and
type(_node) is not bpy.types.ShaderNodeNormalMap and
type(_node) is not bpy.types.ShaderNodeValue and
type(_node) is not bpy.types.ShaderNodeCombineXYZ):
continue
_output = _node.name.replace("Tx ", "").replace("Normal ", "").replace("Val ", "")
if not graph.outputs[_output].shader_enabled:
sbs_group_nodes.remove(_node)
@staticmethod
def update_images(graph, data):
for _output in graph.outputs:
if _output.type == "image":
if _output.name in data["outputs"]:
_filepath = data["outputs"][_output.name]["path"]
_img_name = "{}_{}".format(graph.material.name, _output.name)
SUBSTANCE_MaterialManager.get_image(_img_name, _filepath)
@staticmethod
def get_current_nodes(items, new_nodes, mat_nodes, shader_graph, graph):
for _node in shader_graph["nodes"]:
_name = _node["name"].replace("$matname", graph.material.name)
if _node["path"] == "root":
_nodes = mat_nodes
else:
_nodes = items[_node["path"].replace("root/", "")].node_tree.nodes
if _name in _nodes:
items[_node["id"]] = _nodes[_name]
else:
new_nodes.append(_node["id"])
items[_node["id"]] = _nodes.new(_node["type"])
items[_node["id"]].name = _name
if _node["type"] == "NodeFrame":
items[_node["id"]].label = _node["label"]
continue
items[_node["id"]].location = (_node["location"][0], _node["location"][1])
if _node["type"] == "ShaderNodeGroup":
_node_tree = bpy.data.node_groups.new(
type='ShaderNodeTree',
name=graph.material.name)
items[_node["id"]].node_tree = _node_tree
@staticmethod
def cycles_update(items):
for _key in items:
if not hasattr(items[_key], "image"):
continue
_img = items[_key].image
items[_key].image = None
SUBSTANCE_Threads.timer_thread_run(
RENDER_IMG_UPDATE_DELAY_S,
SUBSTANCE_MaterialManager.reset_image,
(items[_key], _img))
@staticmethod
def create_shader_network(context, sbsar, graph, data):
try:
# Time
SUBSTANCE_Threads.cursor_push('WAIT')
_time_start = time.time()
_addons_prefs, _shader_idx, _shader = SUBSTANCE_Utils.get_selected_shader(context, int(graph.shaders_list))
_shader_file = SUBSTANCE_Utils.get_shader_file(_shader.filename)
_shader_graph = SUBSTANCE_Utils.get_json(_shader_file)
_shader_prefs = SUBSTANCE_Utils.get_shader_prefs(context, _shader)
_material = SUBSTANCE_MaterialManager.get_existing_material(graph.material.name)
if _material is None or _shader.name != graph.material.shader:
if _material is None:
_material = bpy.data.materials.new(name=graph.material.name)
if _addons_prefs.auto_apply_material:
SUBSTANCE_MaterialManager.auto_apply_material(context, data, _material)
SUBSTANCE_MaterialManager.empty_material(_material, graph)
_items = SUBSTANCE_MaterialManager.init_nodes(_material, graph, _shader_graph)
# Get the substance Node Group
_mat_nodes = _material.node_tree.nodes
_sbs_group = _material.node_tree.nodes["{}_sbsar".format(graph.material.name)]
_sbs_group_nodes = _sbs_group.node_tree.nodes
# Initialize Enabled outputs
SUBSTANCE_MaterialManager.init_outputs(
_items,
_sbs_group,
_shader_prefs,
_shader_graph,
_addons_prefs,
data,
graph)
# Initialize Sbsar NodeGroup socket
SUBSTANCE_MaterialManager.init_sockets(_items, _shader_graph)
# Create sockets & links for enabled outputs that are not part of the shader
_dyna_links = []
SUBSTANCE_MaterialManager.create_dyna_links(_dyna_links, _sbs_group, graph, data)
# Remove unused Nodes
SUBSTANCE_MaterialManager.remove_unused_nodes(_items, _shader_graph, _mat_nodes)
# Initialize shader properties
SUBSTANCE_MaterialManager.init_properties(
_items,
_shader_graph,
_shader_prefs,
graph,
data,
context)
# Initialize links
SUBSTANCE_MaterialManager.init_links(_material, _items, _shader_graph)
# Initialize dynamic links
SUBSTANCE_MaterialManager.init_dyna_links(_material, _items, _dyna_links)
graph.material.shader = _shader.name
_material.use_fake_user = _addons_prefs.auto_fake_usr
_out_message_type = "INFO"
_out_message = "Material [{}] create in [{}]seconds"
else:
# Reload image files and update file format
SUBSTANCE_MaterialManager.update_images(graph, data)
# Get the substance Node Group
_mat_nodes = _material.node_tree.nodes
_sbs_group = _material.node_tree.nodes["{}_sbsar".format(graph.material.name)]
_sbs_group_nodes = _sbs_group.node_tree.nodes
if graph.update_tx_only:
_items = {}
# Add all SBSAR texture nodes
for _node in _sbs_group_nodes:
if (type(_node) is not bpy.types.ShaderNodeTexImage):
continue
_output = _node.name.replace("Tx ", "")
_items[_output] = _node
_out_message_type = "INFO"
_out_message = "Textures [{}] updated in [{}]seconds"
else:
# Cleanup SBSAR group
SUBSTANCE_MaterialManager.clean_sbsar_group(_sbs_group, _sbs_group_nodes, graph, data)
# Get all graph items
_new_nodes = []
_items = {}
SUBSTANCE_MaterialManager.get_current_nodes(
_items,
_new_nodes,
_mat_nodes,
_shader_graph,
graph)
SUBSTANCE_MaterialManager.init_outputs(
_items,
_sbs_group,
_shader_prefs,
_shader_graph,
_addons_prefs,
data,
graph,
_new_nodes)
# Remove unused Nodes
SUBSTANCE_MaterialManager.remove_unused_nodes(_items, _shader_graph, _mat_nodes)
# Initialize shader properties
SUBSTANCE_MaterialManager.init_properties(
_items,
_shader_graph,
_shader_prefs,
graph,
data,
context,
_new_nodes)
# Initialize Sbsar NodeGroup socket
SUBSTANCE_MaterialManager.init_sockets(_items, _shader_graph)
# Create sockets & links for enabled outputs that are not part of the shader
_dyna_links = []
SUBSTANCE_MaterialManager.create_dyna_links(_dyna_links, _sbs_group, graph, data)
# Sort sockets
if bpy.app.version >= (4, 0, 0):
pass
else:
_n = len(_sbs_group.node_tree.outputs)
for _idx in range(_n):
_sorted = True
for _jdx in range(_n - _idx - 1):
_a_key = _sbs_group.node_tree.outputs[_jdx].name
_b_key = _sbs_group.node_tree.outputs[_jdx + 1].name
_a_weight = graph.outputs[_a_key].index
_b_weight = graph.outputs[_b_key].index
if _a_weight > _b_weight:
_sbs_group.node_tree.outputs.move(_jdx, _jdx + 1)
_sorted = False
if _sorted:
break
# Initialize links
SUBSTANCE_MaterialManager.init_links(_material, _items, _shader_graph)
# Initialize dynamic links
SUBSTANCE_MaterialManager.init_dyna_links(_material, _items, _dyna_links)
_out_message_type = "INFO"
_out_message = "Material [{}] updated in [{}]seconds"
# Hack to autoupdate images in cycles
if _addons_prefs.cycles_autoupdate_enabled:
SUBSTANCE_MaterialManager.cycles_update(_items)
except Exception:
_out_message_type = "ERROR"
_out_message = "An error ocurred while setting the material [{}]. [{}]seconds"
SUBSTANCE_Utils.log_data("ERROR", "Exception - Susbtance material creation error")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
# Time
_time_end = time.time()
_load_time = round(_time_end - _time_start, 3)
SUBSTANCE_Utils.log_data(
_out_message_type,
_out_message.format(graph.material.name, _load_time),
display=True)
# REDRAW
# _idx = context.scene.sbsar_index
# context.scene.sbsar_index = _idx
SUBSTANCE_Utils.toggle_redraw(context)
SUBSTANCE_Threads.cursor_pop()
@@ -0,0 +1,25 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: network/callback.py
# brief: Callback interface for async operations
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
class SRE_CallbackInterface():
def execute(self, message):
pass
@@ -0,0 +1,106 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: network/client.py
# brief: Client requests
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import traceback
import socket
import threading
import json
from time import sleep
from ..utils import SUBSTANCE_Utils
from ..common import (
Code_Response,
SRE_HOST,
SRE_PORT,
CLIENT_THREAD_THROTTLE_MS,
CLIENT_BUFFER_SIZE
)
class SRE_Client():
def __init__(self):
self.next_thread_start = SUBSTANCE_Utils.get_current_time_in_ms() + CLIENT_THREAD_THROTTLE_MS
def async_request(self, endpoint, op, data={}):
_throttle_ms = 0
_current_ms = SUBSTANCE_Utils.get_current_time_in_ms()
if _current_ms > self.next_thread_start:
self.next_thread_start = _current_ms + CLIENT_THREAD_THROTTLE_MS
else:
_throttle_ms = self.next_thread_start - _current_ms
self.next_thread_start = self.next_thread_start + CLIENT_THREAD_THROTTLE_MS
threading.Thread(
target=self._process_threaded_request,
args=(endpoint, op, data, _throttle_ms/1000)).start()
def _process_threaded_request(self, endpoint, op, data={}, throttle=0):
if throttle > 0:
sleep(throttle)
_result = self.sync_request(endpoint, op, data=data)
if _result[0] is not Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Threaded request fail: {}".format(_result, endpoint))
def sync_request(
self,
endpoint,
op,
data={}):
try:
_client_socket = socket.socket()
_client_socket.connect((SRE_HOST, SRE_PORT))
_message = {
"type": endpoint,
"op": op,
"data": data
}
_data = json.dumps(_message)
_client_socket.send(_data.encode())
_raw_response = b""
while True:
_buffer = _client_socket.recv(CLIENT_BUFFER_SIZE)
_raw_response += _buffer
if len(_buffer) < CLIENT_BUFFER_SIZE:
break
_response = _raw_response.decode()
_client_socket.close()
return (Code_Response.success, _response)
except ConnectionRefusedError:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Refused connection error")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.client_connection_refused_error, endpoint)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Client connection error: {}".format(endpoint))
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.client_connection_error, endpoint)
@@ -0,0 +1,56 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: network/manager.py
# brief: Network operations manager
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
from .server import SRE_Server
from ..common import Code_Response
class SUBSTANCE_ServerManager():
def __init__(self):
self.server = SRE_Server()
# SERVER
def server_start(self):
if not self.server.is_running():
return self.server.start()
else:
return (Code_Response.server_already_running, None)
def server_port(self):
if self.server.is_running():
return (Code_Response.success, self.server.get_port())
else:
return (Code_Response.server_not_running_error, None)
def server_stop(self):
if self.server.is_running():
return self.server.stop()
else:
return (Code_Response.server_not_running_error, None)
def server_send_message(self, type, endpoint, op, data={}):
return self.server.send_message(
type,
endpoint,
op,
data=data
)
@@ -0,0 +1,159 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: network/server.py
# brief: Web server
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import http.server
import traceback
import threading
import json
from ..utils import SUBSTANCE_Utils
from .client import SRE_Client
from ..common import (
Code_Response,
Code_RequestType,
SERVER_HOST,
SERVER_ALLOW_LIST
)
class SRE_HTTPServer(http.server.HTTPServer):
def run(self):
try:
self.serve_forever()
except KeyboardInterrupt:
pass
finally:
self.server_close()
class SRE_Handler(http.server.BaseHTTPRequestHandler):
def _call_listeners(self, type, data):
if data is not None:
from ..api import SUBSTANCE_Api
SUBSTANCE_Api.listeners_call(type, data)
def _set_response(self, value):
try:
self.send_response(value)
self.send_header("Content-type", "text/html")
self.end_headers()
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Http response fail:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
def handle(self):
try:
http.server.BaseHTTPRequestHandler.handle(self)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Http handle fail:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
def validateRequest(self, headers):
_host = headers.get('Host').split(':')[0]
return _host in SERVER_ALLOW_LIST
def do_HEAD(self, s):
if self.validateRequest(self.headers):
self._set_response(200)
def do_GET(self):
if self.validateRequest(self.headers):
self._call_listeners("get", self.path)
self._set_response(200)
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>This is a test.</p></body></html>", "utf-8"))
def do_POST(self):
if self.validateRequest(self.headers):
_content_len = int(self.headers.get('Content-Length'))
_data = self.rfile.read(_content_len)
self._set_response(200)
if _data is not None:
_json_data = json.loads(_data)
self._call_listeners("post", _json_data)
def do_PATCH(self):
if self.validateRequest(self.headers):
self._set_response(200)
def log_message(self, format, *args):
# Override this function to prevent log spam
pass
class SRE_Server():
def __init__(self):
self.server = None
self.thread = None
self.host = SERVER_HOST
self.port = None
self.client = SRE_Client()
def is_running(self):
if self.server:
return True
else:
return False
def get_port(self):
return self.port
def start(self):
if self.server is None:
self.server = SRE_HTTPServer((self.host, 0), SRE_Handler)
self.port = self.server.server_port
self.thread = threading.Thread(None, self.server.run)
self.thread.daemon = True
self.thread.start()
return (Code_Response.success, None)
return (Code_Response.server_start_error, None)
def stop(self):
if self.server is not None:
self.server.shutdown()
self.thread.join()
self.server = None
self.thread = None
self.port = None
return (Code_Response.success, None)
return (Code_Response.server_stop_error, None)
def send_message(self, type, endpoint, op, data={}):
if type == Code_RequestType.r_sync:
_result = self.client.sync_request(
endpoint,
op,
data=data)
return _result
elif type == Code_RequestType.r_async:
self.client.async_request(
endpoint,
op,
data=data)
return (Code_Response.success, None)
else:
return (Code_Response.server_request_type_error, None)
@@ -0,0 +1,137 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/material.py
# brief: Material operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..api import SUBSTANCE_Api
from ..utils import SUBSTANCE_Utils
from ..common import Code_Response, Code_RequestType
from ..sbsar.sbsar import SBSAR
from ..thread_ops import SUBSTANCE_Threads
from ..sbsar.async_ops import _render_sbsar
class SUBSTANCE_OT_Version(bpy.types.Operator):
bl_idname = 'substance.version'
bl_label = 'Version'
bl_description = 'Get the current plugin version'
def execute(self, context):
_version = SUBSTANCE_Api.version()
SUBSTANCE_Utils.log_data(
"INFO",
"Substance Addon version {}.{}.{}".format(_version[0], _version[1], _version[2]),
display=True)
return {'FINISHED'}
class SUBSTANCE_OT_Message(bpy.types.Operator):
bl_idname = 'substance.send_message'
bl_label = 'Message'
bl_description = "Send the user a message"
type: bpy.props.StringProperty(default="INFO") # noqa
message: bpy.props.StringProperty(default="") # noqa
_timer = None
def modal(self, context, event):
if event.type == 'TIMER':
self.cancel(context)
self.report({self.type}, self.message)
return {'FINISHED'}
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
self._timer = wm.event_timer_add(time_step=1, window=context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
def load_sbsar(filename, filepath, uuid=None, type=Code_RequestType.r_async):
_addon_prefs, _selected_shader_idx, _selected_shader_preset = SUBSTANCE_Utils.get_selected_shader(bpy.context)
_normal_format = _addon_prefs.default_normal_format
_output_size = _addon_prefs.default_resolution.get()
_unique_name = SUBSTANCE_Utils.get_unique_name(filename, bpy.context)
SUBSTANCE_Utils.log_data("INFO", "Begin loading substance from file [{}]".format(filename), display=True)
if uuid:
_data = {
"uuid": uuid,
"filepath": filepath,
"name": _unique_name,
"$outputsize": _output_size,
"normal_format": 0 if _normal_format == "DirectX" else 1
}
else:
_data = {
"filepath": filepath,
"name": _unique_name,
"$outputsize": _output_size,
"normal_format": 0 if _normal_format == "DirectX" else 1
}
# Load the sbsar to the SRE
_result = SUBSTANCE_Api.sbsar_load(_data)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] located at [{}] could not be loaded".format(filename, filepath),
display=True)
return
if _result[1]["result"] != Code_Response.success.value:
SUBSTANCE_Utils.log_data(
"ERROR",
"An error ocurred while loading Substance file [{}]. Failed with error [{}]".format(
filepath, _result[1]["result"]),
display=True)
return
_sbsar = SBSAR(_unique_name, filename, _result[1]["data"], _addon_prefs)
_loaded_sbsar = bpy.context.scene.loaded_sbsars.add()
_loaded_sbsar.init(_sbsar)
_loaded_sbsar.init_shader(_selected_shader_idx, _selected_shader_preset, _addon_prefs.get_default_output())
SUBSTANCE_Api.sbsar_register(_sbsar)
bpy.context.scene.sbsar_index = len(bpy.context.scene.loaded_sbsars) - 1
if type == Code_RequestType.r_async:
for _idx, _graph in enumerate(_loaded_sbsar.graphs):
SUBSTANCE_Threads.alt_thread_run(_render_sbsar, (bpy.context, _loaded_sbsar, _idx))
SUBSTANCE_Utils.log_data("INFO", "Substance from file [{}] loaded".format(filename))
def load_usdz(filename, filepath, uuid=None):
def load_file():
bpy.ops.wm.usd_import(filepath=filepath, relative_path=True, set_material_blend=False)
SUBSTANCE_Utils.log_data(
"INFO",
"Substance Connector file [{}] loaded".format(filename),
display=True)
SUBSTANCE_Threads.main_thread_run(load_file)
@@ -0,0 +1,70 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/inputs.py
# brief: Parameter Operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from random import randint
from ..utils import SUBSTANCE_Utils
from ..common import INPUTS_MAX_RANDOM_SEED, Code_InputIdentifier
class SUBSTANCE_OT_RandomizeSeed(bpy.types.Operator):
bl_idname = 'substance.randomize_seed'
bl_label = 'Randomize'
bl_description = 'Generate a new random value for the current SBSAR randomseed parameter'
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_parms = getattr(context.scene, _selected_graph.inputs_class_name)
_value = randint(0, INPUTS_MAX_RANDOM_SEED)
setattr(_parms, Code_InputIdentifier.randomseed.value, _value)
return {'FINISHED'}
class SUBSTANCE_OT_InputGroupsCollapse(bpy.types.Operator):
bl_idname = 'substance.input_groups_collapse'
bl_label = 'Collapse Groups'
bl_description = 'Collapse all groups'
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
for _group in _selected_graph.input_groups:
_group.collapsed = True
return {'FINISHED'}
class SUBSTANCE_OT_InputGroupsExpand(bpy.types.Operator):
bl_idname = 'substance.input_groups_expand'
bl_label = 'Expand Groups'
bl_description = 'Expand all groups'
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
for _group in _selected_graph.input_groups:
_group.collapsed = False
return {'FINISHED'}
@@ -0,0 +1,85 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/material.py
# brief: Material operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
import json
import traceback
from ..utils import SUBSTANCE_Utils
from ..common import Code_SbsarLoadSuffix
from ..material.manager import SUBSTANCE_MaterialManager
class SUBSTANCE_OT_SetMaterial(bpy.types.Operator):
bl_idname = 'substance.set_material'
bl_label = 'Set material'
bl_description = "Set the material shader network"
data: bpy.props.StringProperty(default="") # noqa
def execute(self, context):
_data = json.loads(self.data)
if len(_data["outputs"]) == 0:
SUBSTANCE_Utils.log_data("INFO", "No render changes")
return {'FINISHED'}
_sbsar = None
for _item in context.scene.loaded_sbsars:
if _item.uuid == _data["uuid"]:
_sbsar = _item
if _sbsar is None:
SUBSTANCE_Utils.log_data("ERROR", "Substance file cannot be found", display=True)
return {'FINISHED'}
try:
_graph = None
for _item in _sbsar.graphs:
_uid = str(_data["graph_uid"])
if _uid == _item.uid:
_graph = _item
break
if _graph is None:
SUBSTANCE_Utils.log_data("ERROR", "Substance graph cannot be found", display=True)
return {'FINISHED'}
_graph.set_thumbnail(_data)
_outputs = {}
for _output in _data["outputs"]:
if _output["usage"] == "UNKNOWN":
_outputs[_output["identifier"]] = _output
else:
_outputs[_output["usage"]] = _output
_data["outputs"] = _outputs
SUBSTANCE_MaterialManager.create_shader_network(context, _sbsar, _graph, _data)
except Exception:
_sbsar.suffix = Code_SbsarLoadSuffix.error.value[0]
_sbsar.icon = Code_SbsarLoadSuffix.error.value[1]
SUBSTANCE_Utils.log_data("ERROR", "Exception - Susbtance material creation error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return {'FINISHED'}
@@ -0,0 +1,301 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/presets.py
# brief:Presets Operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import bpy
from bpy_extras.io_utils import ImportHelper
from ..common import PRESET_DEFAULT, PRESET_CUSTOM, PRESET_EXTENSION, Code_Response
from ..utils import SUBSTANCE_Utils
from ..api import SUBSTANCE_Api
from ..sbsar.sbsar import SBS_Preset
class SUBSTANCE_OT_AddPreset(bpy.types.Operator):
bl_idname = 'substance.add_preset'
bl_label = 'New Preset'
bl_description = "Set the current parameters as a new preset"
preset_name: bpy.props.StringProperty(name="Preset Name") # noqa
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
_layout = self.layout
_row = _layout.row()
_row.label(text="Preset Name: ")
_row.prop(self, 'preset_name', text="")
def execute(self, context):
if len(self.preset_name) > 0:
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_graph = SUBSTANCE_Utils.get_selected_graph(context)
_result = SUBSTANCE_Api.sbsar_preset_add(_sbsar, _graph, self.preset_name)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while creating the preset".format(Code_Response.preset_create_get_error))
return {'FINISHED'}
if _result[1]["result"] != Code_Response.success.value:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while getting the newly created preset".format(
Code_Response.preset_create_get_error))
return {'FINISHED'}
_preset_value = _result[1]["data"]["value"]
_obj = {
"index": len(_graph.presets),
"label": self.preset_name,
"embedded": False,
"icon": "LOCKED",
"value": _preset_value
}
_preset = SBS_Preset(_obj)
_new_preset = _graph.presets.add()
_new_preset.init(_preset)
_graph.preset_callback = False
_graph.presets_list = _preset.index
_graph.preset_callback = True
SUBSTANCE_Utils.log_data("INFO", "Preset [{}] created".format(self.preset_name), display=True)
self.preset_name = ""
else:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while creating new preset, please set a name for the preset".format(
Code_Response.preset_create_no_name_error),
display=True)
return {'FINISHED'}
class SUBSTANCE_OT_DeletePreset(bpy.types.Operator):
bl_idname = 'substance.delete_preset'
bl_label = 'Delete selected preset?'
bl_description = "Delete the current preset"
@classmethod
def poll(cls, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_selected_preset_idx = int(_selected_graph.presets_list)
_selected_preset = _selected_graph.presets[_selected_preset_idx]
return not _selected_preset.embedded and _selected_preset.icon != "UNLOCKED"
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_selected_preset_idx = int(_selected_graph.presets_list)
_selected_graph.presets_list = "0"
_selected_graph.presets.remove(_selected_preset_idx)
SUBSTANCE_Utils.log_data("INFO", "Preset deleted", display=True)
return {'FINISHED'}
class SUBSTANCE_OT_DeletePresetModal(bpy.types.Operator):
bl_idname = 'substance.delete_preset_modal'
bl_label = 'Delete selected preset?'
bl_description = "Delete the current preset"
@classmethod
def poll(cls, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_selected_preset_idx = int(_selected_graph.presets_list)
_selected_preset = _selected_graph.presets[_selected_preset_idx]
return not _selected_preset.embedded and _selected_preset.icon != "UNLOCKED"
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
_layout = self.layout
_row = _layout.row()
_row.label(text="")
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_selected_preset_idx = int(_selected_graph.presets_list)
_selected_graph.presets_list = "0"
_selected_graph.presets.remove(_selected_preset_idx)
SUBSTANCE_Utils.log_data("INFO", "Preset deleted", display=True)
return {'FINISHED'}
class SUBSTANCE_OT_ImportPreset(bpy.types.Operator, ImportHelper):
bl_idname = 'substance.import_preset'
bl_label = 'Import preset'
bl_description = "Import a preset from a file"
filter_glob: bpy.props.StringProperty(default='*' + PRESET_EXTENSION, options={'HIDDEN'}) # noqa
files: bpy.props.CollectionProperty(name='SBSAR Presets Files', type=bpy.types.OperatorFileListElement) # noqa
directory: bpy.props.StringProperty(subtype="DIR_PATH") # noqa
def __init__(self):
self.filepath = ''
def execute(self, context):
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
for _f in self.files:
_filepath = os.path.join(self.directory, _f.name)
_result = SUBSTANCE_Api.sbsar_preset_read(_filepath)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Error while reading preset from file".format(_result))
continue
_obj = _result[1]
_not_found = len(_sbsar.graphs)
for _graph in _sbsar.graphs:
if _graph.identifier not in _obj:
_not_found -= 1
continue
for _preset in _obj[_graph.identifier]:
if _preset["label"] in _graph.presets:
if _preset["label"] == PRESET_CUSTOM or _preset["label"] == PRESET_DEFAULT:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error [{}] cannot be overwritten".format(
Code_Response.preset_import_protected_error,
_preset["label"]),
display=True)
continue
for _existing_preset in _graph.presets:
if _preset["label"] != _existing_preset.name:
continue
if _existing_preset.embedded:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error [{}] cannot be overwritten".format(
Code_Response.preset_import_protected_error,
_preset["label"]),
display=True)
continue
_existing_preset.value = _preset["value"]
SUBSTANCE_Utils.log_data(
"INFO",
"Preset [{}] updated.".format(_preset["label"]),
display=True)
else:
_obj = {
"index": len(_graph.presets),
"label": _preset["label"],
"embedded": False,
"icon": "LOCKED",
"value": _preset["value"]
}
_preset = SBS_Preset(_obj)
_new_preset = _graph.presets.add()
_new_preset.init(_preset)
SUBSTANCE_Utils.log_data(
"INFO",
"Preset [{}] imported.".format(_preset.label),
display=True)
if _not_found == 0:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error Preset [{}] cannot be imported in this substance".format(
Code_Response.preset_import_not_graph,
_f.name),
display=True)
return {'FINISHED'}
return {'FINISHED'}
class SUBSTANCE_OT_ExportPreset(bpy.types.Operator, ImportHelper):
bl_idname = 'substance.export_preset'
bl_label = 'Export preset'
bl_description = "Export current preset to a file"
preset_name: bpy.props.StringProperty(name="Preset Name") # noqa
def __init__(self):
self.filepath = ''
@classmethod
def poll(cls, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_selected_preset_idx = int(_selected_graph.presets_list)
_selected_preset = _selected_graph.presets[_selected_preset_idx]
return _selected_preset.name != PRESET_DEFAULT and _selected_preset.name != PRESET_CUSTOM
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_selected_preset_idx = int(_selected_graph.presets_list)
_selected_preset = _selected_graph.presets[_selected_preset_idx]
_result = SUBSTANCE_Api.sbsar_preset_write(
self.filepath,
_selected_preset)
if _result != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while writting the current preset".format(_result),
display=True)
else:
SUBSTANCE_Utils.log_data("INFO", "Preset exported", display=True)
return {'FINISHED'}
class SUBSTANCE_OT_ExportAll(bpy.types.Operator, ImportHelper):
bl_idname = 'substance.export_all'
bl_label = 'Export all custom presets'
bl_description = "Export all custom presets"
def __init__(self):
self.filepath = ''
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
for _preset in _selected_graph.presets:
if _preset.embedded or _preset.name == PRESET_CUSTOM:
continue
_result = SUBSTANCE_Api.sbsar_preset_write(
self.filepath,
_preset)
if _result != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while writting the current preset".format(_result),
display=True)
else:
SUBSTANCE_Utils.log_data("INFO", "Preset {} exported".format(_preset.label), display=True)
return {'FINISHED'}
@@ -0,0 +1,378 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/sbsar.py
# brief: Sinstance Operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import bpy
from bpy_extras.io_utils import ImportHelper
from ..api import SUBSTANCE_Api
from ..material.manager import SUBSTANCE_MaterialManager
from ..utils import SUBSTANCE_Utils
from ..thread_ops import SUBSTANCE_Threads
from ..sbsar.sbsar import SBSAR
from ..sbsar.async_ops import _render_sbsar
from .common import load_sbsar
from ..common import (
Code_SbsarOp,
Code_Response,
ADDON_PACKAGE,
TOOLKIT_EXPECTED_VERSION
)
class SUBSTANCE_OT_LoadSBSAR(bpy.types.Operator, ImportHelper):
bl_idname = 'substance.load_sbsar'
bl_label = 'Load Substance Material'
bl_description = 'Open file browser to select a Substance 3D material'
bl_options = {'REGISTER'}
filename_ext = '.sbsar'
filter_glob: bpy.props.StringProperty(default='*.sbsar', options={'HIDDEN'}) # noqa
files: bpy.props.CollectionProperty(name='Substance 3D material files', type=bpy.types.OperatorFileListElement) # noqa
directory: bpy.props.StringProperty(subtype="DIR_PATH") # noqa
def __init__(self):
self.filepath = ''
@classmethod
def poll(cls, context):
_, _toolkit_version = SUBSTANCE_Api.toolkit_version_get()
return _toolkit_version is not None and _toolkit_version in TOOLKIT_EXPECTED_VERSION
def invoke(self, context, event):
if not SUBSTANCE_Api.currently_running:
# Initialize SUBSTANCE_Api
_result = SUBSTANCE_Api.initialize()
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] The SRE cannot initialize...".format(_result))
return {'RUNNING_MODAL'}
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
self.filepath = _addon_prefs.path_library
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
def execute(self, context):
SUBSTANCE_Threads.cursor_push('WAIT')
for _f in self.files:
if _f.name.endswith('.sbsar'):
if len(_f.name) > 0:
_filepath = os.path.join(self.directory, _f.name)
load_sbsar(_f.name, _filepath)
else:
SUBSTANCE_Utils.log_data("ERROR", "[{}] is not a valid sbsar file".format(_f.name), display=True)
SUBSTANCE_Threads.cursor_pop()
return {'FINISHED'}
class SUBSTANCE_OT_ApplySBSAR(bpy.types.Operator):
bl_idname = 'substance.apply_sbsar'
bl_label = 'Apply the Substance 3D material'
@classmethod
def description(cls, context, properties):
_selected_geo = SUBSTANCE_Utils.get_selected_geo(context.selected_objects)
if len(context.scene.loaded_sbsars) > 0 and len(_selected_geo) > 0:
_selected_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
if _selected_sbsar.load_success:
return "Applies the selected Substance 3D material to the selected object(s)"
else:
return "This Substance 3D material loaded incorrectly"
else:
return "Please load at least one Substance file and select an object in the scene"
@classmethod
def poll(cls, context):
_selected_geo = SUBSTANCE_Utils.get_selected_geo(context.selected_objects)
if len(context.scene.loaded_sbsars) > 0 and len(_selected_geo) > 0:
_selected_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
return _selected_sbsar.load_success
return False
def execute(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_material = SUBSTANCE_MaterialManager.get_existing_material(_selected_graph.material.name)
if _material is None:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance Material needs to finish rendering before applying",
display=True)
return {'FINISHED'}
_selected_objects = context.selected_objects
if len(_selected_objects) == 0:
SUBSTANCE_Utils.log_data(
"ERROR",
"Material [{}] cannot be added, there are no selected objects".format(_material.name),
display=True)
return {'FINISHED'}
SUBSTANCE_MaterialManager.apply_material(context, _selected_objects, _material)
SUBSTANCE_Utils.log_data(
"INFO",
"Material slot with substance [{}] added to the object".format(_material.name),
display=True)
return {'FINISHED'}
class SUBSTANCE_OT_RemoveSBSAR(bpy.types.Operator):
bl_idname = 'substance.remove_sbsar'
bl_label = 'Remove the Substance 3D material'
@classmethod
def description(cls, context, properties):
if len(context.scene.loaded_sbsars) > 0:
return "Remove the selected Substance 3D material"
else:
return "Please load at least one Substance file"
@classmethod
def poll(cls, context):
if len(context.scene.loaded_sbsars) > 0:
return True
return False
def execute(self, context):
_idx = context.scene.sbsar_index
_selected_sbsar = context.scene.loaded_sbsars[_idx]
_sbsar_uuid = _selected_sbsar.uuid
_sbsar_name = _selected_sbsar.name
context.scene.loaded_sbsars.remove(_idx)
if context.scene.sbsar_index != 0 and context.scene.sbsar_index >= len(context.scene.loaded_sbsars):
context.scene.sbsar_index = len(context.scene.loaded_sbsars) - 1
_result = SUBSTANCE_Api.sbsar_remove(_sbsar_uuid)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance [{}] could not be removed".format(_sbsar_name),
display=True)
if _result[1]["result"] != Code_Response.success.value:
SUBSTANCE_Utils.log_data(
"ERROR",
"An error ocurred while removing Substance [{}]. Failed with error [{}]".format(
_sbsar_name, _result[1]["result"]),
display=True)
_result = SUBSTANCE_Api.sbsar_unregister(_sbsar_uuid)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Classes of Substance [{}] could not be removed".format(_sbsar_name),
display=True)
context.area.tag_redraw()
SUBSTANCE_Utils.log_data("INFO", "Substance [{}] was removed correctly".format(_sbsar_name), display=True)
return {'FINISHED'}
class SUBSTANCE_OT_ReloadSBSAR(bpy.types.Operator):
bl_idname = 'substance.reload_sbsar'
bl_label = 'Reload the Substance 3D material'
@classmethod
def description(cls, context, properties):
if len(context.scene.loaded_sbsars) > 0:
return "Reload the selected Substance 3D material"
else:
return "Please load at least one Substance file"
@classmethod
def poll(cls, context):
if len(context.scene.loaded_sbsars) > 0:
return True
return False
def execute(self, context):
_idx = context.scene.sbsar_index
_selected_sbsar = context.scene.loaded_sbsars[_idx]
_sbsar_uuid = _selected_sbsar.uuid
_sbsar_name = _selected_sbsar.name
_sbsar_filename = _selected_sbsar.filename
_sbsar_filepath = _selected_sbsar.filepath
_addon_prefs, _selected_shader_idx, _selected_shader_preset = SUBSTANCE_Utils.get_selected_shader(context)
_normal_format = _addon_prefs.default_normal_format
_output_size = _addon_prefs.default_resolution.get()
# REMOVE OLD SBSAR
context.scene.loaded_sbsars.remove(_idx)
if context.scene.sbsar_index != 0 and context.scene.sbsar_index >= len(context.scene.loaded_sbsars):
context.scene.sbsar_index = len(context.scene.loaded_sbsars) - 1
_result = SUBSTANCE_Api.sbsar_remove(_sbsar_uuid)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance [{}] could not be removed".format(_sbsar_name),
display=True)
return {'FINISHED'}
if _result[1]["result"] != Code_Response.success.value:
SUBSTANCE_Utils.log_data(
"ERROR",
"An error ocurred while removing Substance [{}]. Failed with error [{}]".format(
_sbsar_name, _result[1]["result"]),
display=True)
return {'FINISHED'}
_result = SUBSTANCE_Api.sbsar_unregister(_sbsar_uuid)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Classes of Substance [{}] could not be removed".format(_sbsar_name),
display=True)
return {'FINISHED'}
# LOAD NEW SBSAR
SUBSTANCE_Utils.log_data("INFO", "Begin loading substance from file [{}]".format(_sbsar_filename))
_data = {
"filepath": _sbsar_filepath,
"name": _sbsar_name,
"$outputsize": _output_size,
"normal_format": 0 if _normal_format == "DirectX" else 1
}
# Load the sbsar to the SRE
_result = SUBSTANCE_Api.sbsar_load(_data)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] located at [{}] could not be loaded".format(_sbsar_filename, _sbsar_filepath),
display=True)
return {'FINISHED'}
if _result[1]["result"] != Code_Response.success.value:
SUBSTANCE_Utils.log_data(
"ERROR",
"An error ocurred while loading Substance file [{}]. Failed with error [{}]".format(
_sbsar_filepath, _result[1]["result"]),
display=True)
return {'FINISHED'}
_sbsar = SBSAR(_sbsar_name, _sbsar_filename, _result[1]["data"], _addon_prefs)
_loaded_sbsar = context.scene.loaded_sbsars.add()
_loaded_sbsar.init(_sbsar)
_loaded_sbsar.init_shader(_selected_shader_idx, _selected_shader_preset, _addon_prefs.get_default_output())
SUBSTANCE_Api.sbsar_register(_sbsar)
context.scene.sbsar_index = len(context.scene.loaded_sbsars) - 1
for _idx, _graph in enumerate(_loaded_sbsar.graphs):
SUBSTANCE_Threads.alt_thread_run(_render_sbsar, (context, _loaded_sbsar, _idx))
SUBSTANCE_Utils.log_data("INFO", "Substance from file [{}] loaded".format(_sbsar_filename))
context.area.tag_redraw()
SUBSTANCE_Utils.log_data("INFO", "Substance [{}] was removed correctly".format(_sbsar_name), display=True)
return {'FINISHED'}
class SUBSTANCE_OT_DuplicateSBSAR(bpy.types.Operator):
bl_idname = 'substance.duplicate_sbsar'
bl_label = 'Duplicate the Substance 3D material'
@classmethod
def description(cls, context, properties):
if len(context.scene.loaded_sbsars) > 0:
_selected_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
if _selected_sbsar.load_success:
return "Duplicate the selected Substance 3D material"
else:
return "This Substance 3D material loaded incorrectly"
else:
return "Please load at least one Substance file"
@classmethod
def poll(cls, context):
if len(context.scene.loaded_sbsars) > 0:
return True
return False
def execute(self, context):
SUBSTANCE_Threads.cursor_push('WAIT')
_tmp_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_sbsar_name = _tmp_sbsar.name
_sbsar = context.scene.loaded_sbsars[_sbsar_name]
_unique_name = SUBSTANCE_Utils.get_unique_name(_sbsar.name, context)
_data = {
"filepath": _sbsar.filepath,
"uuid": _sbsar.uuid,
"name": _unique_name
}
# Load the sbsar to the SRE
_result = SUBSTANCE_Api.sbsar_load(_data, operation=Code_SbsarOp.duplicate)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] located at [{}] could not be loaded".format(_sbsar.filename, _sbsar.filepath),
display=True)
return {'FINISHED'}
if _result[1]["result"] != Code_Response.success.value:
SUBSTANCE_Utils.log_data(
"ERROR",
"An error ocurred while loading Substance file [{}]. Failed with error [{}]".format(
_sbsar.filepath, _result[1]["result"]),
display=True)
return {'FINISHED'}
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_new_sbsar = SBSAR(_unique_name, _sbsar.filename, _result[1]["data"], _addon_prefs)
for _graph_obj in _new_sbsar.graphs:
_presets = []
_preset_list = _sbsar.graphs[int(_graph_obj.index)].presets
for _item in _preset_list:
_obj = {
"index": int(_item.index),
"label": _item.label,
"value": _item.value,
"icon": _item.icon,
"embedded": _item.embedded
}
_presets.append(_obj)
_graph_obj.reset_presets(_presets)
_loaded_sbsar = context.scene.loaded_sbsars.add()
# Reset _sbsar reference otherwise we get a memory error
_sbsar = context.scene.loaded_sbsars[_sbsar_name]
_loaded_sbsar.init(_new_sbsar)
_loaded_sbsar.init_shader_duplicate(_sbsar)
_loaded_sbsar.init_tiling(_sbsar)
_loaded_sbsar.init_outputs(_sbsar)
_loaded_sbsar.init_presets(_sbsar)
SUBSTANCE_Api.sbsar_register(_new_sbsar)
context.scene.sbsar_index = len(context.scene.loaded_sbsars) - 1
for _idx, _graph in enumerate(_loaded_sbsar.graphs):
SUBSTANCE_Threads.alt_thread_run(_render_sbsar, (context, _loaded_sbsar, _idx))
SUBSTANCE_Utils.log_data(
"INFO",
"Substance [{}] duplicated succesfully".format(_sbsar.name),
display=True)
SUBSTANCE_Threads.cursor_pop()
return {'FINISHED'}
@@ -0,0 +1,151 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/shader.py
# brief: Shader Operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
import os
from ..common import ADDON_ROOT, ADDON_PACKAGE, Code_Response
from ..api import SUBSTANCE_Api
from ..utils import SUBSTANCE_Utils
from ..shader.shader import ShaderPreset
class SUBSTANCE_OT_LoadShaderPresets(bpy.types.Operator):
bl_idname = 'substance.load_shader_presets'
bl_label = 'Initialize shader preset'
bl_description = "Initialize the shader presets"
def execute(self, context):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
_addon_prefs.shaders.clear()
_shaders_dir = os.path.join(ADDON_ROOT, "_presets/default").replace('\\', '/')
for _filepath in os.listdir(_shaders_dir):
# Load the shader presets
_result = SUBSTANCE_Api.shader_load(_filepath)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] could not be loaded".format(
_filepath),
display=True)
continue
_shader_preset = ShaderPreset(_filepath, _result[1])
_new_shader = _addon_prefs.shaders.add()
_new_shader.init(_shader_preset)
SUBSTANCE_Api.shader_register(_shader_preset)
SUBSTANCE_Utils.log_data("INFO", "Shader Presets [{}] initialized...".format(_filepath))
return {'FINISHED'}
class SUBSTANCE_OT_RemoveShaderPresets(bpy.types.Operator):
bl_idname = 'substance.remove_shader_presets'
bl_label = 'Remove shader preset'
bl_description = "Remove the shader presets"
def execute(self, context):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
_result = SUBSTANCE_Api.shader_presets_remove(_addon_prefs.shaders)
if _result != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "Shader Presets could not be removed...")
_addon_prefs.shader_presets.clear()
return {'FINISHED'}
SUBSTANCE_Utils.log_data("INFO", "Shader Presets fully removed...")
_addon_prefs.shaders.clear()
return {'FINISHED'}
class SUBSTANCE_OT_SaveShaderPresets(bpy.types.Operator):
bl_idname = 'substance.save_shader_presets'
bl_label = 'Save shader preset'
bl_description = "Save the shader presets"
def execute(self, context):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
for _shader_preset in _addon_prefs.shaders:
if _shader_preset.modified:
_inputs = getattr(context.scene, _shader_preset.inputs_class_name)
_outputs = {}
for _output in _shader_preset.outputs:
_outputs[_output.id] = _output.to_json()
_obj = {
"label": _shader_preset.label,
"filename": _shader_preset.filename,
"inputs": _inputs.get(),
"outputs": _outputs,
}
_result = SUBSTANCE_Api.shader_presets_save(_obj)
if _result != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Shader Presets [{}] could not be saved...[{}]".format(_obj["label"], _result))
SUBSTANCE_Utils.log_data("INFO", "Shader Presets [{}] saved...".format(_obj["label"]))
return {'FINISHED'}
class SUBSTANCE_OT_ResetShaderPreset(bpy.types.Operator):
bl_idname = 'substance.reset_shader_preset'
bl_label = 'Reset shader preset'
bl_description = "Reset the shader preset"
@classmethod
def poll(cls, context):
_addons_prefs, _shader_idx, _shader = SUBSTANCE_Utils.get_selected_shader(context)
return _shader.modified
def execute(self, context):
_addons_prefs, _shader_idx, _shader = SUBSTANCE_Utils.get_selected_shader(context)
_inputs = getattr(context.scene, _shader.inputs_class_name)
_inputs.reset()
# Load the shader presets
_result = SUBSTANCE_Api.shader_load(_shader.filename)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] could not be loaded".format(
_shader.filename),
display=True)
return {'FINISHED'}
_outputs = _result[1]["outputs"]
for _output in _shader.outputs:
_output.enabled = _outputs[_output.id]["enabled"]
_output.colorspace = _outputs[_output.id]["colorspace"]
_output.format = _outputs[_output.id]["format"]
_output.bitdepth = _outputs[_output.id]["bitdepth"]
_shader.modified = False
SUBSTANCE_Utils.log_data(
"INFO",
"Shader Presets [{}] is back to default values".format(_shader.label),
display=True)
return {'FINISHED'}
@@ -0,0 +1,62 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/sync.py
# brief: Sinstance Operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import bpy
from ..api import SUBSTANCE_Api
from ..utils import SUBSTANCE_Utils
from .common import load_sbsar, Code_RequestType, Code_Response
class SUBSTANCE_OT_SyncInitTools(bpy.types.Operator):
bl_idname = 'substance.init_tools_sync'
bl_label = 'Initialize Substance Tools'
def execute(self, context):
if not SUBSTANCE_Api.currently_running:
# Initialize SUBSTANCE_Api
_result = SUBSTANCE_Api.initialize()
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] The SRE cannot initialize...".format(_result))
return {'FINISHED'}
class SUBSTANCE_OT_SyncLoadSBSAR(bpy.types.Operator):
bl_idname = 'substance.load_sbsar_sync'
bl_label = 'Load a Substance 3D file'
filepath: bpy.props.StringProperty(name="filepath", default="") # noqa
def execute(self, context):
if len(self.filepath) > 0:
if self.filepath.endswith('.sbsar'):
_filename = os.path.basename(self.filepath)
_filename = _filename.replace(".sbsar", "")
load_sbsar(_filename, self.filepath, type=Code_RequestType.r_sync)
else:
SUBSTANCE_Utils.log_data("ERROR", "[{}] is not a valid sbsar file".format(self.filepath))
else:
SUBSTANCE_Utils.log_data("ERROR", "[{}] is empty, is not a valid sbsar file".format(self.filepath))
return {'FINISHED'}
@@ -0,0 +1,142 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/toolkit.py
# brief:SRE Toolkit Operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import bpy
import pathlib
import subprocess
import platform
from bpy_extras.io_utils import ImportHelper
from ..api import SUBSTANCE_Api
from ..common import TOOLKIT_EXT, Code_Response, ADDON_PACKAGE, SRE_DIR
from ..thread_ops import SUBSTANCE_Threads
from ..utils import SUBSTANCE_Utils
class SUBSTANCE_OT_OpenTools(bpy.types.Operator):
bl_idname = 'substance.open_tools'
bl_label = 'Open tools folder'
bl_options = {'REGISTER'}
def execute(self, context):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
_result = _addon_prefs.path_tools
if platform.system() == "Windows":
os.startfile(_result)
elif platform.system() == "Darwin":
subprocess.Popen(["open", _result])
SUBSTANCE_Utils.log_data(
"INFO",
"Substance 3D Integration Tools folder [{}] opened correctly".format(_result),
display=True)
return {'FINISHED'}
class SUBSTANCE_OT_ResetTools(bpy.types.Operator):
bl_idname = 'substance.reset_tools'
bl_label = 'Reset tools folder'
bl_options = {'REGISTER'}
def execute(self, context):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
_home = pathlib.Path.home()
_result = os.path.join(_home, SRE_DIR)
_addon_prefs.path_tools = _result
SUBSTANCE_Utils.log_data(
"INFO",
"Substance 3D Integration Tools folder [{}] reset correctly".format(_result),
display=True)
return {'FINISHED'}
class SUBSTANCE_OT_InstallTools(bpy.types.Operator, ImportHelper):
bl_idname = 'substance.install_tools'
bl_label = 'Install tools'
bl_options = {'REGISTER'}
filter_glob: bpy.props.StringProperty(default='*{}'.format(TOOLKIT_EXT), options={'HIDDEN'}) # noqa
def __init__(self):
self.filepath = ''
def execute(self, context):
SUBSTANCE_Threads.cursor_push('WAIT')
_result = SUBSTANCE_Api.toolkit_install(self.filepath)
SUBSTANCE_Threads.cursor_pop()
if _result[0] == Code_Response.success:
SUBSTANCE_Utils.log_data("INFO", "Substance 3D Integration Tools installed correctly", display=True)
else:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while installing the Substance 3D Integration Tools".format(_result[0]),
display=True)
return {'FINISHED'}
class SUBSTANCE_OT_UpdateTools(bpy.types.Operator, ImportHelper):
bl_idname = 'substance.update_tools'
bl_label = 'Update tools'
bl_options = {'REGISTER'}
filter_glob: bpy.props.StringProperty(default='*{}'.format(TOOLKIT_EXT), options={'HIDDEN'}) # noqa
def __init__(self):
self.filepath = ''
def execute(self, context):
SUBSTANCE_Threads.cursor_push('WAIT')
_result = SUBSTANCE_Api.toolkit_install(self.filepath)
SUBSTANCE_Threads.cursor_pop()
if _result[0] == Code_Response.success:
SUBSTANCE_Utils.log_data("INFO", "Substance 3D Integration Tools updated correctly", display=True)
else:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while updating the Substance 3D Integration Tools".format(_result[0]),
display=True)
return {'FINISHED'}
class SUBSTANCE_OT_UninstallTools(bpy.types.Operator):
bl_idname = 'substance.uninstall_tools'
bl_label = 'UnInstall tools'
bl_options = {'REGISTER'}
def execute(self, context):
SUBSTANCE_Threads.cursor_push('WAIT')
_result = SUBSTANCE_Api.toolkit_uninstall()
SUBSTANCE_Threads.cursor_pop()
if _result[0] == Code_Response.success:
SUBSTANCE_Utils.log_data("INFO", "Substance 3D Integration Tools fully removed", display=True)
else:
SUBSTANCE_Utils.log_data(
"ERROR",
"[{}] Error while removing the Substance 3D Integration Tools".format(_result[0]),
display=True)
return {'FINISHED'}
@@ -0,0 +1,90 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ops/web.py
# brief: Web Operators
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..common import (
WEB_SUBSTANCE_TOOLS,
WEB_SUBSTANCE_SHARE,
WEB_SUBSTANCE_SOURCE,
WEB_SUBSTANCE_DOCS,
WEB_SUBSTANCE_FORUMS,
WEB_SUBSTANCE_DISCORD
)
class SUBSTANCE_OT_GoToWebsite(bpy.types.Operator):
bl_idname = 'substance.goto_web'
bl_label = 'Substance 3D Open Website'
bl_description = 'Go to Website'
bl_options = {'REGISTER'}
url: bpy.props.StringProperty()
def execute(self, context):
bpy.ops.wm.url_open(url=self.url)
return {'FINISHED'}
def invoke(self, context, event):
return self.execute(context)
class SUBSTANCE_OT_GetTools(SUBSTANCE_OT_GoToWebsite):
bl_idname = 'substance.goto_tools'
bl_label = 'Substance 3D Integration Tools'
bl_description = 'Go to Substance 3D Integration Tools'
url: bpy.props.StringProperty(default=WEB_SUBSTANCE_TOOLS)
class SUBSTANCE_OT_GoToShare(SUBSTANCE_OT_GoToWebsite):
bl_idname = 'substance.goto_share'
bl_label = 'Substance 3D Community Assets'
bl_description = 'Go to Substance 3D Community Assets'
url: bpy.props.StringProperty(default=WEB_SUBSTANCE_SHARE)
class SUBSTANCE_OT_GoToSource(SUBSTANCE_OT_GoToWebsite):
bl_idname = 'substance.goto_source'
bl_label = 'Substance 3D Assets'
bl_description = 'Go to Substance 3D Assets'
url: bpy.props.StringProperty(default=WEB_SUBSTANCE_SOURCE)
class SUBSTANCE_OT_GoToDocs(SUBSTANCE_OT_GoToWebsite):
bl_idname = 'substance.goto_docs'
bl_label = 'Substance Plugin for Blender Documentation'
bl_description = 'Go to Substance Plugin for Blender Documentation'
url: bpy.props.StringProperty(default=WEB_SUBSTANCE_DOCS)
class SUBSTANCE_OT_GoToForums(SUBSTANCE_OT_GoToWebsite):
bl_idname = 'substance.goto_forums'
bl_label = 'Substance 3D Forums'
bl_description = 'Go to Substance 3D Forums'
url: bpy.props.StringProperty(default=WEB_SUBSTANCE_FORUMS)
class SUBSTANCE_OT_GoToDiscord(SUBSTANCE_OT_GoToWebsite):
bl_idname = 'substance.goto_discord'
bl_label = 'Substance 3D Discord Server'
bl_description = 'Go to Substance 3D Discord Server'
url: bpy.props.StringProperty(default=WEB_SUBSTANCE_DISCORD)
@@ -0,0 +1,269 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: persistance.py
# brief: Persistance handlers for blender
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import shutil
import traceback
import bpy
from bpy.app.handlers import persistent
from .api import SUBSTANCE_Api
from .sbsar.sbsar import SBSAR
from .thread_ops import SUBSTANCE_Threads
from .utils import SUBSTANCE_Utils
from .material.manager import SUBSTANCE_MaterialManager
from .common import (
Code_SbsarOp,
Code_Response,
ADDON_PACKAGE
)
class SUBSTANCE_Persistance():
@staticmethod
@persistent
def sbs_load_pre_handler(dummy):
pass
@staticmethod
@persistent
def sbs_load_post_handler(dummy):
try:
# Add main thread listener
if not bpy.app.timers.is_registered(SUBSTANCE_Threads.exec_queued_function):
bpy.app.timers.register(SUBSTANCE_Threads.exec_queued_function)
# Get current scene
_scene = bpy.context.scene
if hasattr(_scene, "loaded_sbsars") and len(_scene.loaded_sbsars) > 0:
if not SUBSTANCE_Api.currently_running:
# Initialize SUBSTANCE_Api
_result = SUBSTANCE_Api.initialize()
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] The SRE cannot initialize...".format(_result))
return
for _sbsar in _scene.loaded_sbsars:
try:
_graph_idx = int(_sbsar.graphs_list)
_graph = _sbsar.graphs[_graph_idx]
_preset_idx = int(_graph.presets_list)
_preset = _graph.presets[_preset_idx]
_filepath = bpy.path.abspath(_sbsar.filepath)
_filepath = os.path.abspath(_filepath)
_filepath = _filepath.replace("\\", "/")
if not os.path.exists(_filepath):
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] doesn't exist".format(_sbsar.filepath))
continue
_data = {
"filepath": _filepath,
"name": _sbsar.name,
"uuid": _sbsar.uuid,
"graph_idx": _graph_idx,
"preset": _preset.value
}
# Load the sbsar to the SRE
_result = SUBSTANCE_Api.sbsar_load(_data, operation=Code_SbsarOp.reload)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] located at [{}] could not be loaded".format(
_sbsar.filename, _sbsar.filepath),
display=True)
continue
if _result[1]["result"] != Code_Response.success.value:
SUBSTANCE_Utils.log_data(
"ERROR",
"An error ocurred while loading Substance file [{}]. Failed with error [{}]".format(
_sbsar.filepath, _result[1]["result"]),
display=True)
continue
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_new_sbsar = SBSAR(_sbsar.name, _sbsar.filename, _result[1]["data"], _addon_prefs)
for _graph_obj in _new_sbsar.graphs:
_sbsar.graphs[int(_graph_obj.index)].uid = _graph_obj.uid
_presets = []
_preset_list = _sbsar.graphs[int(_graph_obj.index)].presets
for _item in _preset_list:
_obj = {
"index": int(_item.index),
"label": _item.label,
"value": _item.value,
"icon": _item.icon,
"embedded": _item.embedded
}
_presets.append(_obj)
_graph_obj.reset_presets(_presets)
SUBSTANCE_Api.sbsar_register(_new_sbsar)
except Exception:
# TODO: Change the sbsar icon to error if load fails
print("change sbsar icon to error")
SUBSTANCE_Utils.log_data("INFO", "Scene Substances loaded correctly", display=True)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Substance load failed")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
@staticmethod
@persistent
def sbs_save_pre_handler(dummy):
try:
SUBSTANCE_Api.temp_sbs_files.clear()
SUBSTANCE_Api.temp_tx_files.clear()
_addons_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_relative_tx_path = _addons_prefs.path_relative_tx
_scene = bpy.context.scene
for _sbsar in _scene.loaded_sbsars:
if not _sbsar.load_success:
continue
if _addons_prefs.path_relative_sbsar_enabled:
_original_filepath = bpy.path.abspath(_sbsar.filepath)
_original_filepath = os.path.abspath(_original_filepath)
_original_filepath = _original_filepath.replace("\\", "/")
_sbsar_path = _addons_prefs.path_relative_sbsar
_sbsar_path = _sbsar_path[2:] if _sbsar_path.startswith("//") else _sbsar_path
_sbsar_path = _sbsar_path[:-1] if _sbsar_path.endswith("/") else _sbsar_path
_sbsar.filepath = "//{}/{}".format(_sbsar_path, _sbsar.filename)
SUBSTANCE_Api.temp_sbs_files.append({
"sbsar_path": _sbsar_path,
"original_path": _original_filepath,
"filename": _sbsar.filename
})
for _graph in _sbsar.graphs:
if SUBSTANCE_MaterialManager.get_existing_material(_graph.material.name) is None:
continue
for _output in _graph.outputs:
if _output.filename == "":
continue
_original_filepath = bpy.path.abspath(_output.filepath)
_original_filepath = os.path.abspath(_original_filepath)
_original_filepath = _original_filepath.replace("\\", "/")
_mat_path = _relative_tx_path.replace("$matname", _graph.material.name)
_mat_path = _mat_path[2:] if _mat_path.startswith("//") else _mat_path
_mat_path = _mat_path[:-1] if _mat_path.endswith("/") else _mat_path
_output.filepath = "//{}/{}".format(_mat_path, _output.filename)
_item = {
"img": "{}_{}".format(_graph.material.name, _output.name),
"mat_path": _mat_path,
"filepath": _original_filepath,
"filename": _output.filename,
"new_path": _output.filepath,
"mat_name": _graph.material.name
}
SUBSTANCE_Api.temp_tx_files.append(_item)
if _item["img"] in bpy.data.images:
bpy.data.images[_item["img"]].filepath = _item["new_path"]
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Susbtance pre save data error")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
@staticmethod
@persistent
def sbs_save_post_handler(dummy):
try:
_filepath = bpy.data.filepath.replace("\\", "/")
_filedir = os.path.dirname(_filepath)
for _item in SUBSTANCE_Api.temp_sbs_files:
_sbs_dir = "{}/{}".format(_filedir, _item["sbsar_path"])
if not os.path.exists(_sbs_dir):
os.makedirs(_sbs_dir)
_src = _item["original_path"]
_dst = "{}/{}".format(_sbs_dir, _item["filename"])
if _src != _dst and os.path.exists(_src) and os.path.isfile(_src):
shutil.copyfile(_src, _dst)
SUBSTANCE_Utils.log_data(
"INFO",
"Susbtance [{}] moved to relative path".format(_item["filename"]))
for _item in SUBSTANCE_Api.temp_tx_files:
SUBSTANCE_Utils.log_data("INFO", "Moved to Tx relative path [{}]".format(_item["img"]))
_tx_dir = "{}/{}".format(_filedir, _item["mat_path"])
if not os.path.exists(_tx_dir):
os.makedirs(_tx_dir)
_new_filepath = os.path.join(_tx_dir, _item["filename"]).replace("\\", "/")
try:
if (_item["filepath"] != _new_filepath and
os.path.exists(_item["filepath"]) and
os.path.isfile(_item["filepath"])):
shutil.move(_item["filepath"], _new_filepath)
except Exception:
SUBSTANCE_Utils.log_data(
"ERROR",
"Error while moving [{}] file to relative path".format(_item["filepath"]))
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
if _item["img"] in bpy.data.images:
bpy.data.images[_item["img"]].reload()
SUBSTANCE_Api.temp_sbs_files.clear()
SUBSTANCE_Api.temp_tx_files.clear()
SUBSTANCE_Utils.log_data("INFO", "Susbtance textures saved")
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Susbtance post save data error")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
@staticmethod
@persistent
def sbs_undo_post_handler(dummy):
pass
@staticmethod
@persistent
def sbs_depsgraph_update_post(dummy):
_addons_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
if not _addons_prefs.auto_highlight_sbsar:
return
_selected_objects = bpy.context.selected_objects
if len(_selected_objects) == 0:
return
if SUBSTANCE_Api.last_selection == _selected_objects:
return
SUBSTANCE_Api.last_selection = _selected_objects
for _obj in _selected_objects:
if not hasattr(_obj.data, "materials"):
continue
for _idx, _key in enumerate(bpy.context.scene.loaded_sbsars):
for _graph in bpy.context.scene.loaded_sbsars[_idx].graphs:
if _graph.material.name in _obj.data.materials:
bpy.context.scene.loaded_sbsars[_idx].graphs_list = _graph.index
bpy.context.scene.sbsar_index = _idx
return
@@ -0,0 +1,657 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: preferences.py
# brief: Addon Preferences
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import pathlib
import bpy
import sys
from .api import SUBSTANCE_Api
from .props.utils import get_shaders
from .props.shader import SUBSTANCE_PG_ShaderPreset
from .props.common import SUBSTANCE_PG_Tiling, SUBSTANCE_PG_Resolution
from .props.shortcuts import SUBSTANCE_PG_Shortcuts
from .utils import SUBSTANCE_Utils
from .ops.toolkit import (
SUBSTANCE_OT_UninstallTools,
SUBSTANCE_OT_UpdateTools,
SUBSTANCE_OT_InstallTools,
SUBSTANCE_OT_OpenTools,
SUBSTANCE_OT_ResetTools
)
from .ops.web import SUBSTANCE_OT_GetTools, SUBSTANCE_OT_GoToDocs, SUBSTANCE_OT_GoToForums, SUBSTANCE_OT_GoToDiscord
from .ops.shader import SUBSTANCE_OT_ResetShaderPreset
from .common import (
ADDON_PACKAGE,
PATH_LIBARY_DEFAULT,
TOOLKIT_EXPECTED_VERSION,
DRAW_DEFAULT_FACTOR,
IMAGE_EXPORT_FORMAT,
PATH_DEFAULT,
Code_ShaderInputType,
APPLY_TYPE_DICT,
IMAGE_FORMAT_DICT,
IMAGE_BITDEPTH_DICT,
SRE_ENGINE_DICT,
SRE_DIR
)
def get_toolkit_path():
_home = pathlib.Path.home()
return os.path.join(_home, SRE_DIR)
def get_colorspace_dict(self, context):
return SUBSTANCE_Utils.get_colorspaces()
def get_shader_bitdepths(self, context):
return IMAGE_BITDEPTH_DICT[self.output_default_format]
def get_engine_options(self, context):
if sys.platform == "win32":
return SRE_ENGINE_DICT["WINDOWS"]
elif sys.platform == "linux":
return SRE_ENGINE_DICT["LINUX"]
elif sys.platform == "darwin":
return SRE_ENGINE_DICT["DARWIN"]
class SUBSTANCE_AddonPreferences(bpy.types.AddonPreferences):
bl_idname = ADDON_PACKAGE
default_tiling: bpy.props.PointerProperty(
name="default_tiling",
description="The default tiling to be used in the shader network", # noqa
type=SUBSTANCE_PG_Tiling)
default_resolution: bpy.props.PointerProperty(
name="default_resolution",
description="The default resolution to be used in the substance", # noqa
type=SUBSTANCE_PG_Resolution)
default_normal_format: bpy.props.EnumProperty(
name="default_normal_format",
default="OpenGL", # noqa
description="The default normal format", # noqa
items=[("OpenGL", "OpenGL", ""), ("DirectX", "DirectX", "")]) # noqa
default_apply_type: bpy.props.EnumProperty(
name="default_apply_type",
default="INSERT", # noqa
description="Append the material to the object, or Insert it as top material", # noqa
items=APPLY_TYPE_DICT)
default_export_format: bpy.props.EnumProperty(
name="default_export_format",
default="1", # noqa
description="The image export format for input parameters", # noqa
items=IMAGE_EXPORT_FORMAT)
default_export_format: bpy.props.EnumProperty(
name="default_export_format",
default="1", # noqa
description="The image export format for input parameters", # noqa
items=IMAGE_EXPORT_FORMAT)
default_group_collapse: bpy.props.BoolProperty(
name='Input groups collapsed by default', # noqa
default=False,
description='Automatically collapse the substance material input groups when loaded') # noqa
default_tx_update: bpy.props.BoolProperty(
name='Only update textures by default', # noqa
default=False,
description='Only update the textures without modifing the shader network when updating a substance material') # noqa
auto_apply_material: bpy.props.BoolProperty(
name='Automatically apply the material', # noqa
default=False,
description='Automatically apply the substance material to the selected object(s) when loaded') # noqa
auto_highlight_sbsar: bpy.props.BoolProperty(
name='Automatically highlight the material for selected objects', # noqa
default=True,
description='When an object is selected in the 3D view automatically update the loaded Substance 3D Material') # noqa
cycles_autoupdate_enabled: bpy.props.BoolProperty(
name='Cycles Auto-update textures', # noqa
default=False,
description='Force reload textures when updated in cycles') # noqa
auto_start_sre: bpy.props.BoolProperty(
name='Automatically start the Substance Remote Engine', # noqa
default=False,
description='Automatically start the Substance Remote Engine.') # noqa
auto_fake_usr: bpy.props.BoolProperty(
name='Create materials with fake user enabled.', # noqa
default=True,
description='Automatically enable the fake user when creating Substance materials.') # noqa
path_relative_sbsar_enabled: bpy.props.BoolProperty(
name='Auto-package sbsar files on save', # noqa
default=False,
description='Copy the loaded sbsar files to the defined relative path when you save the blend file') # noqa
path_tools: bpy.props.StringProperty(
name='Integration Tools path', # noqa
default=get_toolkit_path(),
subtype='DIR_PATH', # noqa
description='Open by default this path when loading an Substance file (*.sbsar)') # noqa
path_library: bpy.props.StringProperty(
name='Sbsar library path', # noqa
default=PATH_LIBARY_DEFAULT,
subtype='DIR_PATH', # noqa
description='Open by default this path when loading an Substance file (*.sbsar)') # noqa
path_default: bpy.props.StringProperty(
name='Temporary Path', # noqa
default=PATH_DEFAULT,
subtype='DIR_PATH', # noqa
description='Path used for temporary exports of the material texture maps') # noqa
path_relative_sbsar: bpy.props.StringProperty(
name='Relative path for Substance files', # noqa
default="sbsar/", # noqa
description='When saved, copy the substance file to this relative path in order to pack the project') # noqa
path_relative_tx: bpy.props.StringProperty(
name='Relative path for texture files', # noqa
default="substance tx/$matname", # noqa
description='When saved copy the texture files to this relative path in order to pack the project') # noqa
output_default_enabled: bpy.props.BoolProperty(
name="output_default_colorspace",
default=False, # noqa
description="The default enabled status to be used when creating the shader network") # noqa
output_default_colorspace: bpy.props.EnumProperty(
name="output_default_colorspace",
default=0, # noqa
description="The default colorspace to be used when creating the shader network", # noqa
items=get_colorspace_dict)
output_default_format: bpy.props.EnumProperty(
name="output_default_format",
default="TGA", # noqa
description="The default file format to be used by the Output", # noqa
items=IMAGE_FORMAT_DICT)
output_default_bitdepth: bpy.props.EnumProperty(
name="output_default_bitdepth",
default=0,
description="The default bitdepth of the Output", # noqa
items=get_shader_bitdepths)
shortcuts: bpy.props.PointerProperty(type=SUBSTANCE_PG_Shortcuts)
shader_list: bpy.props.EnumProperty(
name="shader_list",
description="The available shader network presets", # noqa
items=get_shaders)
shaders: bpy.props.CollectionProperty(type=SUBSTANCE_PG_ShaderPreset)
collapse_shader_inputs: bpy.props.BoolProperty(default=True)
collapse_shader_outputs: bpy.props.BoolProperty(default=True)
collapse_shortcuts: bpy.props.BoolProperty(default=True)
preset_auto_delete_enabled: bpy.props.BoolProperty(
name="Remove preset delete confirmation", # noqa
default=False, # noqa
description="Remove delete preset confimation window") # noqa
engine: bpy.props.EnumProperty(
name="engine",
description="The engine use on the Substance Remote Engine", # noqa
items=get_engine_options)
def get_default_output(self):
return {
"enabled": self.output_default_enabled,
"colorspace": self.output_default_colorspace,
"format": self.output_default_format,
"bitdepth": self.output_default_bitdepth
}
def draw(self, context):
_col = self.layout.column(align=True)
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Integration Tools Install Path")
_row = _col_2.row()
_row.prop(self, "path_tools", text='')
_row.operator(SUBSTANCE_OT_OpenTools.bl_idname, text='Open Tools')
_row.operator(SUBSTANCE_OT_ResetTools.bl_idname, text='Reset Path')
_result = SUBSTANCE_Api.toolkit_version_get()
if _result[1] is not None and _result[1] in TOOLKIT_EXPECTED_VERSION:
_col.label(text='Thank you for installing the Substance 3D Integration Tools. {}'.format(_result[1]))
_row = _col.row()
_row.operator(SUBSTANCE_OT_UninstallTools.bl_idname, text='Uninstall Tools', icon='TRASH')
_row.operator(SUBSTANCE_OT_UpdateTools.bl_idname, text='Update Tools', icon='FILE_REFRESH')
elif _result[1] is not None and _result[1] not in TOOLKIT_EXPECTED_VERSION:
_col.alert = True
_msg = 'Update Needed! Please download and install a compatible Integration tool version: [{}] '.format(
" , ".join(TOOLKIT_EXPECTED_VERSION))
_col.label(text=_msg)
_col.alert = False
_row = _col.row()
_row.operator(SUBSTANCE_OT_GetTools.bl_idname, text='Download', icon='URL')
_row.operator(SUBSTANCE_OT_UpdateTools.bl_idname, text='Update Tools', icon='FILEBROWSER')
return
else:
_col.alert = True
_msg = 'Please download and install Integration Tools, a separate module for Adobe Substance 3D'
_col.label(text=_msg)
_col.alert = False
_row = _col.row()
_row.operator(SUBSTANCE_OT_GetTools.bl_idname, text='Download', icon='URL')
_row.operator(SUBSTANCE_OT_InstallTools.bl_idname, text='Install from disk', icon='FILEBROWSER')
return
_row = _col.row()
_row.label(text="")
# Docs
_row = _col.row()
_row.label(text="")
_row = _col.row()
_row.label(text="Help & Resources:")
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_col_1.alignment = "RIGHT"
_col_1.label(text="Documentation")
_col_2.operator(SUBSTANCE_OT_GoToDocs.bl_idname, text='Documentation', icon='URL')
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_col_1.alignment = "RIGHT"
_col_1.label(text="Forums")
_col_2.operator(SUBSTANCE_OT_GoToForums.bl_idname, text='Forums', icon='URL')
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_col_1.alignment = "RIGHT"
_col_1.label(text="Discord Sever")
_col_2.operator(SUBSTANCE_OT_GoToDiscord.bl_idname, text='Discord Server', icon='URL')
# Options
_row = _col.row()
_row.label(text="")
_row = _col.row()
_row.label(text="Defaults:")
# Tiling
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Tiling")
_row = _col_2.row()
_row.prop(self.default_tiling, "x", text='')
_row_2 = _row.column()
_row_2.prop(self.default_tiling, "y", text='')
_row_2.enabled = not self.default_tiling.linked
_row_3 = _row.column()
_row_3.prop(self.default_tiling, "z", text='')
_row_3.enabled = not self.default_tiling.linked
_row.prop(self.default_tiling, "linked", text='', icon='LOCKED')
# Resolution
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Resolution")
_row = _col_2.row()
_row.prop(self.default_resolution, "width", text='')
_row_2 = _row.column()
_row_2.prop(self.default_resolution, "height", text='')
_row_2.enabled = not self.default_resolution.linked
_row.prop(self.default_resolution, "linked", text='', icon='LOCKED')
# Normal Format
# _row = _col.row()
# _split = _row.split(factor=DRAW_DEFAULT_FACTOR)
# _col_1 = _split.column()
# _col_2 = _split.column()
# _row = _col_1.row()
# _row.alignment = "RIGHT"
# _row.label(text="Normal Format")
# _row = _col_2.row()
# _row.prop(self, "default_normal_format", text='')
# APPLY TYPE Format
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Apply Type")
_row = _col_2.row()
_row.prop(self, "default_apply_type", text='')
# Export Image Format
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Export Image Format")
_row = _col_2.row()
_row.prop(self, "default_export_format", text='')
_row = _col_2.row()
_row.prop(self, 'default_group_collapse')
_row = _col_2.row()
_row.prop(self, 'default_tx_update')
# SRE Engine
_row = _col.row()
_row.label(text="")
_row = _col.row()
_row.label(text="Substance Remote Engine:")
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Engine")
_row = _col_2.row()
_row.prop(self, "engine", text='')
# Automations
_row = _col.row()
_row.label(text="")
_row = _col.row()
_row.label(text="Automations:")
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_2.row()
_col_2.prop(self, 'auto_apply_material')
_row = _col_2.row()
_row.prop(self, 'auto_highlight_sbsar')
_row = _col_2.row()
_row.prop(self, 'cycles_autoupdate_enabled')
_row = _col_2.row()
_row.prop(self, 'preset_auto_delete_enabled')
_row = _col_2.row()
_row.prop(self, 'auto_fake_usr')
_row = _col_2.row()
_row.prop(self, 'auto_start_sre')
# Paths
_row = _col.row()
_row.label(text="")
_row = _col.row()
_row.label(text="Paths:")
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="SBSAR Library Path")
_row = _col_2.row()
_row.prop(self, "path_library", text='')
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Temporary Folder")
_row = _col_2.row()
_row.prop(self, "path_default", text='')
_row = _col.row()
_row.label(text="")
_row = _col.row()
_row.label(text="Relative Paths:")
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Copy [*.sbsar] files on save to")
_row = _col_2.row()
_row.prop(self, 'path_relative_sbsar_enabled', text="")
_row = _row.row()
_row.enabled = self.path_relative_sbsar_enabled
_row.prop(self, "path_relative_sbsar", text="")
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="On save, copy textures to")
_row = _col_2.row()
_row.prop(self, "path_relative_tx", text='')
_row = _col.row()
_row.label(text="")
# Options
_row = _col.row()
_row.label(text="")
_row = _col.row()
_row.label(text="Shader Networks:")
# Show current shader preset
_selected_preset_idx = int(self.shader_list)
_selected_preset = self.shaders[_selected_preset_idx]
_modified = "(*)" if _selected_preset.modified else ""
# Shader Presets
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Shader Preset" + _modified)
_row = _col_2.row()
_row.prop(self, "shader_list", text="")
_row.operator(SUBSTANCE_OT_ResetShaderPreset.bl_idname, text="", icon="LOOP_BACK")
_row = _col.row()
_row.label(text="")
# Shader preset parameters
if len(_selected_preset.inputs) != 0:
_row = _col.row()
_row.alignment = "LEFT"
_row.prop(
self,
"collapse_shader_inputs",
icon='TRIA_DOWN' if self.collapse_shader_inputs else 'TRIA_RIGHT',
text="Parameters:",
emboss=False)
if self.collapse_shader_inputs:
_inputs = getattr(context.scene, _selected_preset.inputs_class_name)
for _idx, _input in enumerate(_selected_preset.inputs):
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text=_input.label)
_row = _col_2.row()
if _input.type == Code_ShaderInputType.float_maxmin.value:
_row.prop(_inputs, _input.id, text="")
elif _input.type == Code_ShaderInputType.float_slider.value:
_row.prop(_inputs, _input.id, text="", slider=True)
else:
_row.label(text="Parameter not supported yet")
_row = _col.row()
_row.label(text="")
# Shader preset outputs
_row = _col.row()
_row.alignment = "LEFT"
_row.prop(
self,
"collapse_shader_outputs",
icon='TRIA_DOWN' if self.collapse_shader_outputs else 'TRIA_RIGHT',
text="Outputs:",
emboss=False)
if self.collapse_shader_outputs:
for _idx, _output in enumerate(_selected_preset.outputs):
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text=_output.label)
_row = _col_2.row()
_row.prop(_output, "enabled", text="")
_row.prop(_output, "colorspace", text="")
_row.prop(_output, "format", text="")
_row.prop(_output, "bitdepth", text="")
_row = _col.row()
_row.label(text="")
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Generic Output")
_row = _col_2.row()
_row.prop(self, "output_default_enabled", text="")
_row.prop(self, "output_default_colorspace", text="")
_row.prop(self, "output_default_format", text="")
_row.prop(self, "output_default_bitdepth", text="")
# Shortcuts
_row = _col.row()
_row.alignment = "LEFT"
_row.prop(
self,
"collapse_shortcuts",
icon='TRIA_DOWN' if self.collapse_shortcuts else 'TRIA_RIGHT',
text="Shortcuts:",
emboss=False)
if self.collapse_shortcuts:
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="")
_row = _col_2.row()
_row.label(text="CTRL")
_row.label(text="SHIFT")
_row.label(text="ALT")
_row.label(text="KEY")
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text=self.shortcuts.menu_name)
_row = _col_2.row()
_split = _row.split(factor=0.25)
_col_3 = _split.column()
_row = _col_3.row()
_row.prop(self.shortcuts, 'menu_ctrl', text="")
_col_4 = _split.column()
_row = _col_4.row()
_row.prop(self.shortcuts, 'menu_shift', text="")
_col_5 = _split.column()
_row = _col_5.row()
_row.prop(self.shortcuts, 'menu_alt', text="")
_col_6 = _split.column()
_row = _col_6.row()
_row.prop(self.shortcuts, 'menu_key', text="")
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text=self.shortcuts.load_name)
_row = _col_2.row()
_split = _row.split(factor=0.25)
_col_3 = _split.column()
_row = _col_3.row()
_row.prop(self.shortcuts, 'load_ctrl', text="")
_col_4 = _split.column()
_row = _col_4.row()
_row.prop(self.shortcuts, 'load_shift', text="")
_col_5 = _split.column()
_row = _col_5.row()
_row.prop(self.shortcuts, 'load_alt', text="")
_col_6 = _split.column()
_row = _col_6.row()
_row.prop(self.shortcuts, 'load_key', text="")
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text=self.shortcuts.apply_name)
_row = _col_2.row()
_split = _row.split(factor=0.25)
_col_3 = _split.column()
_row = _col_3.row()
_row.prop(self.shortcuts, 'apply_ctrl', text="")
_col_4 = _split.column()
_row = _col_4.row()
_row.prop(self.shortcuts, 'apply_shift', text="")
_col_5 = _split.column()
_row = _col_5.row()
_row.prop(self.shortcuts, 'apply_alt', text="")
_col_6 = _split.column()
_row = _col_6.row()
_row.prop(self.shortcuts, 'apply_key', text="")
_row = _col_2.row()
_row.label(text="*Shortcut updates need a restart in order to be applied.")
_row = _col.row()
_row.label(text="")
@@ -0,0 +1,86 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: presets/manager.py
# brief: Manager for preset related operations
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import xml.etree.ElementTree as ET
import traceback
from ..utils import SUBSTANCE_Utils
from ..common import Code_Response, PRESET_EXTENSION
class SUBSTANCE_PresetManager():
def __init__(self):
pass
def preset_write_file(self, filepath, preset):
try:
_dir_path = filepath + preset.name + PRESET_EXTENSION
_root = ET.Element('sbspresets')
_root.set('formatversion', '1.1')
_root.set('count', '1')
_preset_xml = ET.fromstring(preset.value)
_root.append(_preset_xml)
_tree = ET.ElementTree(_root)
ET.indent(_tree, space=" ", level=0)
_tree.write(_dir_path)
return Code_Response.success
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Writing preset error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return Code_Response.preset_export_error
def preset_read_file(self, filepath):
try:
with open(filepath) as _f:
_preset_file = _f.read()
_root = ET.fromstring(_preset_file)
_obj = {}
for _child in _root.findall('sbspreset'):
_preset_value = ET.tostring(_child, encoding='unicode')
_graph = _child.attrib['pkgurl'].split('?')[0]
_graph = _graph.replace("pkg:///", "")
_graph = _graph.replace("pkg://", "")
if _graph not in _obj:
_obj[_graph] = []
_obj[_graph].append({
"label": _child.attrib['label'],
"value": _preset_value
})
return (Code_Response.success, _obj)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Reading preset error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.preset_import_error, None)
@@ -0,0 +1,122 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/common.py
# brief: Common Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..common import RESOLUTIONS_DICT
class SUBSTANCE_PG_SbsarPhysicalSize(bpy.types.PropertyGroup):
x: bpy.props.FloatProperty(
name="x",
default=1.0,
description="The X physical size to be used") # noqa
y: bpy.props.FloatProperty(
name="y",
default=1.0,
description="The Y physical size to be used") # noqa
z: bpy.props.FloatProperty(
name="z",
default=1.0,
description="The Z physical size to be used") # noqa
def init(self, value):
self.x = value[0]
self.y = value[1]
self.z = value[2]
def get(self):
return [self.x, self.y, self.z]
def on_linked_tiling_changed(self, context):
if self.linked:
self.y = self.x
self.z = self.x
else:
on_tiling_changed(self, context)
def on_tiling_changed(self, context):
pass
class SUBSTANCE_PG_Tiling(bpy.types.PropertyGroup):
x: bpy.props.FloatProperty(
name="x",
default=2.0,
description="The X tiling to be used", # noqa
update=on_linked_tiling_changed)
y: bpy.props.FloatProperty(
name="y",
default=2.0,
description="The Y tiling to be used", # noqa
update=on_tiling_changed)
z: bpy.props.FloatProperty(
name="z",
default=2.0,
description="The Z tiling to be used", # noqa
update=on_tiling_changed)
linked: bpy.props.BoolProperty(
name="linked",
default=True,
description='Lock/Unlock the tiling', # noqa
update=on_linked_tiling_changed)
def init(self, value):
self.x = value[0]
self.y = value[1]
self.z = value[2]
def get(self):
return [self.x, self.y, self.z]
def on_update_resolution(self, context):
if self.linked:
self.height = self.width
class SUBSTANCE_PG_Resolution(bpy.types.PropertyGroup):
width: bpy.props.EnumProperty(
name="width",
default="10",
description="The width of the exported map", # noqa
items=RESOLUTIONS_DICT,
update=on_update_resolution)
height: bpy.props.EnumProperty(
name="height",
default="10",
description="The height of the exported map", # noqa
items=RESOLUTIONS_DICT)
linked: bpy.props.BoolProperty(
name="linked",
default=True,
description='Lock/Unlock the resolution', # noqa
update=on_update_resolution)
def init(self, value):
self.width = value[0]
self.height = value[1]
def get(self):
return [int(self.width), int(self.height)]
@@ -0,0 +1,135 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/sbsar.py
# brief: Substance Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from .sbsar_graph import SUBSTANCE_PG_SbsarGraph
from ..common import (
Code_SbsarLoadSuffix,
ADDON_PACKAGE
)
def get_graph_items(self, context):
_graphs = []
for _idx, _graph in enumerate(self.graphs):
_item = (_graph.index, _graph.label, "{}:{}:{}".format(_graph.index, _graph.label, _graph.uid))
_graphs.append(_item)
if len(_graphs) == 0:
return [("0", "NONE", "NONE:NONE:NONE")]
return _graphs
def on_graph_update(self, context):
pass
def on_suffix_update(self, context):
if self.suffix == Code_SbsarLoadSuffix.success.value[0]:
self.loading = Code_SbsarLoadSuffix.success.value[1]
self.load_success = True
elif self.suffix == Code_SbsarLoadSuffix.error.value[0]:
self.loading = Code_SbsarLoadSuffix.error.value[1]
self.load_success = False
class SUBSTANCE_PG_Sbsar(bpy.types.PropertyGroup):
uuid: bpy.props.StringProperty(
name="uuid",
description="The ID of the Substance 3D *.sbsar file") # noqa
version: bpy.props.IntProperty(
name="version",
description="The Version of the Substance Engine used by the .sbsar file") # noqa
name: bpy.props.StringProperty(
name="name",
description="The name of the Substance *.sbsar file") # noqa
filename: bpy.props.StringProperty(
name='filename',
description='The name of the *.sbsar file') # noqa
filepath: bpy.props.StringProperty(
name='filepath',
description='The path to the *.sbsar file') # noqa
graphs: bpy.props.CollectionProperty(type=SUBSTANCE_PG_SbsarGraph)
graphs_list: bpy.props.EnumProperty(
name="graphs",
description="The available graphs of the Substance 3D material", # noqa
items=get_graph_items,
update=on_graph_update)
suffix: bpy.props.StringProperty(
name="suffix",
default=Code_SbsarLoadSuffix.loading.value[0],
update=on_suffix_update)
icon: bpy.props.StringProperty(
name="icon",
default=Code_SbsarLoadSuffix.loading.value[1],
update=on_suffix_update)
loading: bpy.props.StringProperty(name="loading", default="TEMP") # noqa
load_success: bpy.props.BoolProperty(default=False)
def init(self, sbsar):
self.uuid = sbsar.uuid
self.version = sbsar.version
self.name = sbsar.name
self.filename = sbsar.filename
self.filepath = sbsar.filepath
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
for _graph in sbsar.graphs:
_new_graph = self.graphs.add()
_new_graph.init(_graph, _addon_prefs)
def init_shader(self, shader_idx, shader, default_output):
for _graph in self.graphs:
_graph.init_shader(shader_idx, shader, default_output)
def init_tiling(self, sbsar):
for _idx, _graph in enumerate(self.graphs):
_graph.init_tiling(sbsar.graphs[_idx].tiling.get(), sbsar.graphs[_idx].tiling.linked)
def init_shader_duplicate(self, sbsar):
for _idx, _graph in enumerate(self.graphs):
_graph.init_shader_duplicate(sbsar.graphs[_idx].shaders_list)
def init_outputs(self, sbsar):
for _idx, _graph in enumerate(self.graphs):
_graph.init_outputs(sbsar.graphs[_idx].outputs)
def init_presets(self, sbsar):
for _idx, _graph in enumerate(self.graphs):
_graph.init_preset(sbsar.graphs[_idx].presets_list)
def get(self):
_obj = {
"uuid": self.uuid,
"version": self.version,
"name": self.name,
"filename": self.filename,
"filepath": self.filepath,
"graphs": []
}
for _graph in self.graphs:
_obj["graphs"].append(_graph.get())
return _obj
@@ -0,0 +1,361 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/sbsar_graph.py
# brief: Substance Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import bpy
from .utils import get_shaders
from ..sbsar.async_ops import _render_sbsar, _set_input_visibility
from ..api import SUBSTANCE_Api
from ..thread_ops import SUBSTANCE_Threads
from ..material.manager import SUBSTANCE_MaterialManager
from ..utils import SUBSTANCE_Utils
from .common import SUBSTANCE_PG_SbsarPhysicalSize
from .sbsar_input import SUBSTANCE_PG_SbsarInput, SUBSTANCE_PG_SbsarInputGroup
from .sbsar_output import SUBSTANCE_PG_SbsarOutput
from .sbsar_preset import SUBSTANCE_PG_SbsarPreset
from ..common import OUTPUTS_FILTER_DICT, Code_InputIdentifier, Code_Response
class SUBSTANCE_PG_SbsarMaterial(bpy.types.PropertyGroup):
name: bpy.props.StringProperty(name="name", description="The ID of the Substance 3D shader material") # noqa
shader: bpy.props.StringProperty(name="shader", default="") # noqa
def on_linked_tiling_changed(self, context):
if self.linked:
self.y = self.x
self.z = self.x
else:
on_tiling_changed(self, context)
def on_tiling_changed(self, context):
if not self.callback:
return
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_graph = _sbsar.graphs[int(_sbsar.graphs_list)]
_addons_prefs, _selected_shader_idx, _selected_shader_preset = SUBSTANCE_Utils.get_selected_shader(
context,
int(_graph.shaders_list))
_shader_filepath = SUBSTANCE_Utils.get_shader_file(_selected_shader_preset.filename)
_shader_graph = SUBSTANCE_Utils.get_json(_shader_filepath)
_material = SUBSTANCE_MaterialManager.get_existing_material(_graph.material.name)
if _material is None:
return
for _property in _shader_graph["properties"]:
if _property["type"] == "tiling":
_node_name = None
for _node in _shader_graph["nodes"]:
if _node["id"] == _property["id"]:
_node_name = _node["name"]
break
if _node_name is None:
continue
if _node_name in _material.node_tree.nodes:
_node = _material.node_tree.nodes[_node_name]
_value = self.get()
if "input" in _property:
setattr(_node.inputs[_property["input"]], _property["name"], _value)
class SUBSTANCE_PG_SbsarTiling(bpy.types.PropertyGroup):
x: bpy.props.FloatProperty(
name="x",
default=2.0,
description="The X tiling to be used", # noqa
update=on_linked_tiling_changed)
y: bpy.props.FloatProperty(
name="y",
default=2.0,
description="The Y tiling to be used", # noqa
update=on_tiling_changed)
z: bpy.props.FloatProperty(
name="z",
default=2.0,
description="The Z tiling to be used", # noqa
update=on_tiling_changed)
linked: bpy.props.BoolProperty(
name="linked",
default=True,
description='Lock/Unlock the tiling', # noqa
update=on_linked_tiling_changed)
callback: bpy.props.BoolProperty(default=True)
def init(self, value):
self.callback = False
self.x = value[0]
self.y = value[1]
self.z = value[2]
self.callback = True
def set(self, value, linked):
self.callback = False
self.x = value[0]
self.y = value[1]
self.z = value[2]
self.linked = linked
self.callback = True
def get(self):
return [self.x, self.y, self.z]
def on_shader_update(self, context):
if not self.shader_callback:
return
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_graph_idx = int(_sbsar.graphs_list)
_addons_prefs, _selected_shader_idx, _selected_shader = SUBSTANCE_Utils.get_selected_shader(
context,
int(self.shaders_list))
for _output in self.outputs:
_output.shader_callback_enabled = False
if _output.name in _selected_shader.outputs:
_shader_output = _selected_shader.outputs[_output.name]
_output.shader_enabled = _shader_output.enabled
_output.shader_format = _shader_output.format
_output.shader_bitdepth = _shader_output.bitdepth
else:
_output.shader_enabled = _addons_prefs.output_default_enabled
_output.shader_format = _addons_prefs.output_default_format
_output.shader_bitdepth = _addons_prefs.output_default_bitdepth
_output.shader_callback_enabled = True
SUBSTANCE_Threads.alt_thread_run(_render_sbsar, (context, _sbsar, _graph_idx))
def on_preset_update(self, context):
if not self.preset_callback:
return
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_preset_idx = int(self.presets_list)
_preset = self.presets[_preset_idx]
_result = SUBSTANCE_Api.sbsar_preset_load(
_sbsar,
self,
_preset.value)
if _result[0] != Code_Response.success:
return
_data = _result[1]["data"]["inputs"]
SUBSTANCE_Threads.alt_thread_run(_set_input_visibility, (
_sbsar,
self,
_data))
SUBSTANCE_Threads.alt_thread_run(_render_sbsar, (
context,
_sbsar,
int(self.index)))
_input_class = getattr(context.scene, self.inputs_class_name)
_input_class.callback["enabled"] = False
_input_class.from_json(self.inputs, _data)
_input_class.callback["enabled"] = True
def get_preset_items(self, context):
_presets = []
for _preset in self.presets:
_item = (
_preset.index,
_preset.label,
"{}:{}".format(_preset.index, _preset.label),
int(_preset.index)
)
_presets.append(_item)
return _presets
class SUBSTANCE_PG_SbsarGraph(bpy.types.PropertyGroup):
index: bpy.props.StringProperty(
name="index",
description="The index of the graph in the Substance 3D material") # noqa
uid: bpy.props.StringProperty(
name="uid",
description="The ID of the Substance 3D graph") # noqa
name: bpy.props.StringProperty(name="name")
label: bpy.props.StringProperty(
name="label",
description="The name of the Substance 3D graph") # noqa
identifier: bpy.props.StringProperty(
name="identifier",
description="The identifier of the Substance 3D graph") # noqa
packageUrl: bpy.props.StringProperty(
name="packageUrl",
description="The package URL of the Substance 3D graph") # noqa
material: bpy.props.PointerProperty(type=SUBSTANCE_PG_SbsarMaterial)
tiling: bpy.props.PointerProperty(
name="tiling",
description="The default tiling to be used in the shader network", # noqa
type=SUBSTANCE_PG_SbsarTiling)
physical_size: bpy.props.PointerProperty(
name="physical_size",
description="The physical size of the material", # noqa
type=SUBSTANCE_PG_SbsarPhysicalSize)
presets: bpy.props.CollectionProperty(type=SUBSTANCE_PG_SbsarPreset)
presets_list: bpy.props.EnumProperty(
name="presets",
description="The available presets on ths SBSAR file", # noqa
items=get_preset_items,
update=on_preset_update)
preset_callback: bpy.props.BoolProperty(name="preset_callback", default=True)
outputs_filter: bpy.props.EnumProperty(
name="outputs_filter",
description="Filter the outputs displayed", # noqa
items=OUTPUTS_FILTER_DICT)
inputs_class_name: bpy.props.StringProperty(name="inputs_class_name")
input_groups: bpy.props.CollectionProperty(type=SUBSTANCE_PG_SbsarInputGroup)
inputs: bpy.props.CollectionProperty(type=SUBSTANCE_PG_SbsarInput)
outputs: bpy.props.CollectionProperty(type=SUBSTANCE_PG_SbsarOutput)
outputsize_exists: bpy.props.BoolProperty(
name="outputsize_exists",
default=False)
randomseed_exists: bpy.props.BoolProperty(
name="randomseed_exists",
default=False)
shaders_list: bpy.props.EnumProperty(
name="shaders_list",
description="The available shader network presets", # noqa
items=get_shaders,
update=on_shader_update)
shader_callback: bpy.props.BoolProperty(name="shader_callback", default=True)
update_tx_only: bpy.props.BoolProperty(name="update_tx_only", default=False)
thumbnail: bpy.props.StringProperty(name="thumbnail")
def init(self, graph, addon_prefs):
self.index = graph.index
self.uid = graph.uid
self.name = graph.identifier
self.identifier = graph.identifier
self.packageUrl = graph.packageUrl
self.label = graph.label
self.material.name = graph.material
self.physical_size.init(graph.physicalSize)
self.tiling.init(graph.tiling)
self.inputs_class_name = graph.inputs_class_name
self.update_tx_only = addon_prefs.default_tx_update
for _preset in graph.presets:
_new_preset = self.presets.add()
_new_preset.init(_preset)
for _idx, _group in enumerate(graph.inputs_groups):
new_group = self.input_groups.add()
new_group.init(_idx, _group, addon_prefs)
for _key, _input in graph.inputs.items():
_new_input = self.inputs.add()
_new_input.init(_input)
if _input.identifier == Code_InputIdentifier.outputsize.value:
self.outputsize_exists = True
if _input.identifier == Code_InputIdentifier.randomseed.value:
self.randomseed_exists = True
for _key, _outputs in graph.outputs.items():
_new_output = self.outputs.add()
_new_output.init(_outputs)
def init_shader(self, shader_idx, shader, default_output):
self.shader_callback = False
self.shaders_list = shader_idx
self.shader_callback = True
for _output in self.outputs:
_output.init_shader(shader, default_output)
def init_shader_duplicate(self, shader_index):
_shader_idx = int(shader_index)
_addon_prefs, _selected_shader_idx, _selected_shader_preset = SUBSTANCE_Utils.get_selected_shader(
bpy.context, _shader_idx)
self.shader_callback = False
self.shaders_list = _selected_shader_idx
self.shader_callback = True
for _output in self.outputs:
_output.init_shader(_selected_shader_preset, _addon_prefs.get_default_output())
def init_tiling(self, value, linked):
self.tiling.set(value, linked)
def init_outputs(self, outputs):
for _output in self.outputs:
if _output.name in outputs:
_output.init_output(outputs[_output.name])
def init_preset(self, preset_value):
self.preset_callback = False
self.presets_list = preset_value
self.preset_callback = True
def set_thumbnail(self, data):
if "graph_thumb" not in data:
return
_file = data["graph_thumb"]
if os.path.exists(_file):
_thumbnail_img = bpy.data.images.load(_file, check_existing=True)
_thumbnail_txt = bpy.data.textures.new(name=_thumbnail_img.name, type="IMAGE")
_thumbnail_txt.image = _thumbnail_img
_thumbnail_txt.extension = "EXTEND"
self.thumbnail = _thumbnail_img.name
else:
self.thumbnail = ""
def get(self):
_obj = {
"index": self.index,
"uid": self.uid,
"identifier": self.identifier,
"packagrUrl": self.packageUrl,
"label": self.label,
"physical_size": self.physical_size.get(),
"tiling": self.tiling.get(),
"presets": [],
"inputs": [],
"outputs": [],
"thumbnail": self.thumbnail
}
for _preset in self.presets:
_obj["presets"].append(_preset.get())
for _input in self.inputs:
_obj["inputs"].append(_input.get())
for _output in self.outputs:
_obj["outputs"].append(_output.get())
return _obj
@@ -0,0 +1,95 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/sbsar_input.py
# brief: Substance Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
class SUBSTANCE_PG_SbsarInput(bpy.types.PropertyGroup):
id: bpy.props.StringProperty(name="id")
name: bpy.props.StringProperty(name="name")
graphID: bpy.props.StringProperty(name="graphID")
identifier: bpy.props.StringProperty(name="identifier")
label: bpy.props.StringProperty(name="label")
guiDescription: bpy.props.StringProperty(name="label")
guiGroup: bpy.props.StringProperty(name="guiGroup")
guiVisibleIf: bpy.props.StringProperty(name="guiVisibleIf")
userTag: bpy.props.StringProperty(name="userTag")
type: bpy.props.StringProperty(name="type")
guiWidget: bpy.props.StringProperty(name="guiWidget")
showAsPin: bpy.props.BoolProperty(name="showAsPin", default=False)
useCache: bpy.props.BoolProperty(name="useCache", default=False)
visibleIf: bpy.props.BoolProperty(name="visibleIf", default=False)
isHeavyDuty: bpy.props.BoolProperty(name="isHeavyDuty", default=False)
def init(self, input):
self.id = str(input.id)
self.name = input.identifier
self.graphID = str(input.graphID)
self.identifier = input.identifier
self.label = input.label
self.guiDescription = input.guiDescription
self.guiGroup = input.guiGroup
self.guiVisibleIf = input.guiVisibleIf
self.userTag = input.userTag
self.type = input.type
self.guiWidget = input.guiWidget
self.showAsPin = input.showAsPin
self.useCache = input.useCache
self.visibleIf = input.visibleIf
self.isHeavyDuty = input.isHeavyDuty
def get(self):
_obj = {
"id": int(self.id),
"graphID": int(self.graphID),
"identifier": self.identifier,
"label": self.label,
"guiDescription": self.guiDescription,
"guiGroup": self.guiGroup,
"guiVisibleIf": self.guiVisibleIf,
"userTag": self.userTag,
"type": self.type,
"guiWidget": self.guiWidget,
"showAsPin": self.showAsPin,
"useCache": self.useCache,
"visibleIf": self.visibleIf,
"isHeavyDuty": self.isHeavyDuty
}
return _obj
class SUBSTANCE_PG_SbsarInputGroup(bpy.types.PropertyGroup):
index: bpy.props.IntProperty(name="index")
label: bpy.props.StringProperty(name="label")
collapsed: bpy.props.BoolProperty(default=False)
def init(self, index, value, addon_prefs):
self.index = index
self.label = value
self.collapsed = addon_prefs.default_group_collapse
def get(self):
_obj = {
"label": self.label,
"collapsed": self.collapsed
}
return _obj
@@ -0,0 +1,169 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/sbsar_output.py
# brief: Substance Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..thread_ops import SUBSTANCE_Threads
from ..sbsar.async_ops import _render_sbsar
from ..utils import SUBSTANCE_Utils
from ..common import (
IMAGE_FORMAT_DICT,
IMAGE_BITDEPTH_DICT
)
class SUBSTANCE_PG_SbsarOutputChannelUse(bpy.types.PropertyGroup):
value: bpy.props.StringProperty(name="value")
def on_output_update(self, context):
if not self.shader_callback_enabled:
return
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_graph = SUBSTANCE_Utils.get_selected_graph(context)
SUBSTANCE_Threads.alt_thread_run(_render_sbsar, (context, _sbsar, int(_graph.index)))
def get_colorspace_dict(self, context):
return SUBSTANCE_Utils.get_colorspaces()
def get_bitdepths(self, context):
return IMAGE_BITDEPTH_DICT[self.shader_format]
class SUBSTANCE_PG_SbsarOutput(bpy.types.PropertyGroup):
id: bpy.props.StringProperty(name="id")
index: bpy.props.IntProperty(name="index")
name: bpy.props.StringProperty(name="name")
graphID: bpy.props.StringProperty(name="graphID")
format: bpy.props.IntProperty(name="format")
mipmaps: bpy.props.IntProperty(name="mipmaps")
identifier: bpy.props.StringProperty(name="identifier")
label: bpy.props.StringProperty(name="label")
guiDescription: bpy.props.StringProperty(name="guiDescription")
group: bpy.props.StringProperty(name="group")
guiVisibleIf: bpy.props.StringProperty(name="guiVisibleIf")
userTag: bpy.props.StringProperty(name="userTag")
type: bpy.props.StringProperty(name="type")
guiType: bpy.props.StringProperty(name="guiType")
defaultChannelUse: bpy.props.StringProperty(name="defaultChannelUse")
enabled: bpy.props.BoolProperty(name="enabled")
channelUseSpecified: bpy.props.BoolProperty(name="channelUseSpecified")
channelUse: bpy.props.CollectionProperty(type=SUBSTANCE_PG_SbsarOutputChannelUse)
shader_callback_enabled: bpy.props.BoolProperty(name="shader_callback_enabled", default=False)
shader_enabled: bpy.props.BoolProperty(
name="shader_enabled",
default=False,
update=on_output_update)
shader_colorspace: bpy.props.EnumProperty(
name="shader_colorspace",
description="The available colorspaces to be applied to this map", # noqa
items=get_colorspace_dict,
update=on_output_update)
shader_format: bpy.props.EnumProperty(
name="shader_format",
description="The available colorspaces to be applied to this map", # noqa
items=IMAGE_FORMAT_DICT,
update=on_output_update)
shader_bitdepth: bpy.props.EnumProperty(
name="shader_bitdepth",
description="The available colorspaces to be applied to this map", # noqa
items=get_bitdepths,
update=on_output_update)
filepath: bpy.props.StringProperty(name="filepath", default="") # noqa
filename: bpy.props.StringProperty(name="filename", default="") # noqa
def init(self, output):
self.id = str(output.id)
self.index = output.index
self.name = output.defaultChannelUse if output.defaultChannelUse != "UNKNOWN" else output.identifier
self.graphID = str(output.graphID)
self.format = output.format
self.mipmaps = output.mipmaps
self.identifier = output.identifier
self.label = output.label
self.guiDescription = output.guiDescription
self.group = output.group
self.guiVisibleIf = output.guiVisibleIf
self.userTag = output.userTag
self.type = output.type
self.guiType = output.guiType
self.defaultChannelUse = output.defaultChannelUse
self.enabled = output.enabled
self.channelUseSpecified = output.channelUseSpecified
for _use in output.channelUse:
_new_use = self.channelUse.add()
_new_use.value = _use
def init_shader(self, shader, default_output):
if self.name not in shader.outputs:
self.shader_enabled = default_output["enabled"]
self.shader_format = default_output["format"]
self.shader_bitdepth = default_output["bitdepth"]
else:
for _output in shader.outputs:
if _output.id == self.name:
self.shader_enabled = _output.enabled
self.shader_format = _output.format
self.shader_bitdepth = _output.bitdepth
self.shader_callback_enabled = True
def init_output(self, default_output):
self.shader_callback_enabled = False
self.shader_enabled = default_output.shader_enabled
self.shader_format = default_output.shader_format
self.shader_bitdepth = default_output.shader_bitdepth
self.shader_callback_enabled = True
def get(self):
_obj = {
"id": int(self.id),
"graphID": int(self.graphID),
"format": self.format,
"mipmaps": self.mipmaps,
"identifier": self.identifier,
"label": self.label,
"guiDescription": self.guiDescription,
"group": self.group,
"guiVisibleIf": self.guiVisibleIf,
"userTag": self.userTag,
"type": self.type,
"guiType": self.guiType,
"defaultChannelUse": self.defaultChannelUse,
"enabled": self.enabled,
"channelUseSpecified": self.channelUseSpecified,
"channelUse": [],
"shader_enabled": self.shader_enabled,
"shader_colorspace": self.shader_colorspace,
"shader_format": self.shader_format,
"shader_bitdepth": self.shader_bitdepth
}
for _use in self.channelUse:
_obj["channelUse"].append(_use.value)
return _obj
@@ -0,0 +1,59 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/sbsar_preset.py
# brief: Substance Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
class SUBSTANCE_PG_SbsarPreset(bpy.types.PropertyGroup):
name: bpy.props.StringProperty(name="name")
index: bpy.props.StringProperty(
name="index",
description="The index of the preset in the Substance 3D graph") # noqa
label: bpy.props.StringProperty(
name="label",
description="The preset name of the Substance 3D graph") # noqa
value: bpy.props.StringProperty(
name="value",
description="The preset value of the Substance 3D graph") # noqa
icon: bpy.props.StringProperty(
name="icon",
description="The preset icon that shows if a preset is editable") # noqa
embedded: bpy.props.BoolProperty(
name="embedded",
description="The preset origin") # noqa
def init(self, preset):
self.name = preset.label
self.index = preset.index
self.label = preset.label
self.value = preset.value
self.icon = preset.icon
self.embedded = preset.embedded
def get(self):
return {
"index": self.index,
"label": self.label,
"value": self.value,
"icon": self.icon,
"embedded": self.embedded
}
@@ -0,0 +1,160 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/shader.py
# brief: Shader Preset Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..shader.callbacks import SUBSTANCE_ShaderCallbacks
from ..common import IMAGE_FORMAT_DICT, IMAGE_BITDEPTH_DICT
from ..utils import SUBSTANCE_Utils
class SUBSTANCE_PG_ShaderInput(bpy.types.PropertyGroup):
id: bpy.props.StringProperty(name="id")
label: bpy.props.StringProperty(name="label")
type: bpy.props.StringProperty(name="type")
def init(self, input):
self.id = input.id
self.label = input.label
self.type = input.type
def on_enabled_update(self, context):
if not self.callback_enabled:
return
SUBSTANCE_ShaderCallbacks.on_output_changed(self, context)
def on_shader_colorspace_update(self, context):
if not self.callback_enabled:
return
SUBSTANCE_ShaderCallbacks.on_output_changed(self, context)
def on_shader_format_update(self, context):
if not self.callback_enabled:
return
_callback_enabled = self.callback_enabled
self.callback_enabled = False
self.bitdepth = IMAGE_BITDEPTH_DICT[self.format][0][0]
self.callback_enabled = _callback_enabled
SUBSTANCE_ShaderCallbacks.on_output_changed(self, context)
def on_shader_bitdepth_update(self, context):
if not self.callback_enabled:
return
SUBSTANCE_ShaderCallbacks.on_output_changed(self, context)
def get_colorspace_dict(self, context):
return SUBSTANCE_Utils.get_colorspaces()
def get_shader_bitdepths(self, context):
return IMAGE_BITDEPTH_DICT[self.format]
class SUBSTANCE_PG_ShaderOutput(bpy.types.PropertyGroup):
id: bpy.props.StringProperty(name="id")
name: bpy.props.StringProperty(name="name")
label: bpy.props.StringProperty(name="label")
optional: bpy.props.BoolProperty(name="optional")
enabled: bpy.props.BoolProperty(
name="enabled",
update=on_enabled_update)
colorspace: bpy.props.EnumProperty(
name="colorspace",
description="The default colorspace to be used when creating the shader network", # noqa
items=get_colorspace_dict,
update=on_shader_colorspace_update)
format: bpy.props.EnumProperty(
name="format",
description="The default format to be used when exporting this maps", # noqa
items=IMAGE_FORMAT_DICT,
update=on_shader_format_update)
bitdepth: bpy.props.EnumProperty(
name="bitdepth",
description="The default bitdepth to be applied to this map", # noqa
items=get_shader_bitdepths,
update=on_shader_bitdepth_update)
normal: bpy.props.BoolProperty(name="normal", default=False)
callback_enabled: bpy.props.BoolProperty(name="callback_enabled", default=False)
def init(self, output):
self.id = output.id
self.name = output.id
self.label = output.label
self.enabled = output.enabled
self.optional = output.optional
self.format = output.format
self.bitdepth = output.bitdepth
self.normal = output.normal
self.callback_enabled = True
self.colorspace = output.colorspace
def to_json(self):
_object = {
"id": self.id,
"label": self.label,
"enabled": self.enabled,
"optional": self.optional,
"colorspace": self.colorspace,
"format": self.format,
"bitdepth": self.bitdepth,
}
if self.normal:
_object["normal"] = self.normal
return _object
class SUBSTANCE_PG_ShaderPreset(bpy.types.PropertyGroup):
filename: bpy.props.StringProperty(name="filename")
name: bpy.props.StringProperty(name="name")
label: bpy.props.StringProperty(name="label")
modified: bpy.props.BoolProperty(name="modified", default=False)
inputs: bpy.props.CollectionProperty(type=SUBSTANCE_PG_ShaderInput)
outputs: bpy.props.CollectionProperty(type=SUBSTANCE_PG_ShaderOutput)
inputs_class_name: bpy.props.StringProperty(name="inputs_class_name")
def init(self, shader):
self.filename = shader.filename
self.name = shader.name
self.label = shader.label
self.inputs_class_name = shader.inputs_class_name
for _key, _input in shader.inputs.items():
_parm_item = self.inputs.add()
_parm_item.init(_input)
for _key, _output in shader.outputs.items():
_output_item = self.outputs.add()
_output_item.init(_output)
def to_json(self):
_data = []
for _output in self.outputs:
_data.append(_output.to_json())
return _data
@@ -0,0 +1,54 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/shortcuts.py
# brief: Shortcuts Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
def _on_shortcut_update(self, context):
_ctrl = "Ctrl+" if self.menu_ctrl else ""
_shift = "Shift+" if self.menu_shift else ""
_alt = "Alt+" if self.menu_alt else ""
self.menu_label = _ctrl + _shift + _alt + self.menu_key
class SUBSTANCE_PG_Shortcuts(bpy.types.PropertyGroup):
# Floating Menu
menu_name: bpy.props.StringProperty(default="Floating Menu") # noqa
menu_ctrl: bpy.props.BoolProperty(default=True, update=_on_shortcut_update)
menu_shift: bpy.props.BoolProperty(default=True, update=_on_shortcut_update)
menu_alt: bpy.props.BoolProperty(default=False, update=_on_shortcut_update)
menu_key: bpy.props.StringProperty(default='U', update=_on_shortcut_update) # noqa
menu_label: bpy.props.StringProperty(default="Ctrl+Shift+U") # noqa
# Load SBSAR
load_name: bpy.props.StringProperty(default="Load SBSAR") # noqa
load_ctrl: bpy.props.BoolProperty(default=True)
load_shift: bpy.props.BoolProperty(default=True)
load_alt: bpy.props.BoolProperty(default=False)
load_key: bpy.props.StringProperty(default='L') # noqa
# Apply Material
apply_name: bpy.props.StringProperty(default="Apply Current Material") # noqa
apply_ctrl: bpy.props.BoolProperty(default=True)
apply_shift: bpy.props.BoolProperty(default=True)
apply_alt: bpy.props.BoolProperty(default=False)
apply_key: bpy.props.StringProperty(default='M') # noqa
@@ -0,0 +1,33 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: props/utils.py
# brief: Auxiliary functions for Property Groups
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
from ..common import ADDON_PACKAGE
def get_shaders(self, context):
_shader_presets = []
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
for _idx, _shader_preset in enumerate(_addon_prefs.shaders):
_shader_presets.append(
(str(_idx), _shader_preset.label, _shader_preset.filename)
)
return _shader_presets
@@ -0,0 +1,112 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: render/manager.py
# brief: Render operations manager
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
import json
import threading
from ..thread_ops import SUBSTANCE_Threads
from ..common import Code_SbsarLoadSuffix, Code_RequestOp, INPUT_UPDATE_DELAY_S, RENDER_KEY
class SUBSTANCE_RenderManager():
def __init__(self):
self.input_lock = threading.Lock()
self.render_lock = threading.Lock()
self.render_current = ""
self.render_queue = {}
self.input_change_queue = {}
# Inputs render call
def _input_render_update(self, context, sbsar, graph, input, value, callback):
with self.input_lock:
_render_id = RENDER_KEY.format(sbsar.uuid, graph.index)
self.input_change_queue.pop(_render_id)
callback(context, sbsar, graph, input, value)
def input_queue_add(self, context, sbsar, graph, input, value, callback):
with self.input_lock:
_render_id = RENDER_KEY.format(sbsar.uuid, graph.index)
if _render_id in self.input_change_queue:
self.input_change_queue[_render_id].cancel()
self.input_change_queue.pop(_render_id)
self.input_change_queue[_render_id] = SUBSTANCE_Threads.timer_thread_run(
INPUT_UPDATE_DELAY_S,
self._input_render_update,
(context, sbsar, graph, input, value, callback)
)
# Render call
def graph_render(self, render_id, data, request_type, callback):
def _set_render_tag():
for _item in bpy.context.scene.loaded_sbsars:
if _item.uuid == data["sbsar"]["uuid"]:
_item.suffix = Code_SbsarLoadSuffix.render.value[0]
_item.icon = Code_SbsarLoadSuffix.render.value[1]
break
with self.render_lock:
if self.render_current == "":
self.render_current = render_id
callback(Code_RequestOp.render, data, request_type)
SUBSTANCE_Threads.main_thread_run(_set_render_tag)
else:
if render_id not in self.render_queue:
self.render_queue[render_id] = {
"render_id": render_id,
"data": data,
"request_type": request_type,
"callback": callback
}
def render_finish(self, data):
_current_sbsar_id = None
_next_render = None
with self.render_lock:
if self.render_current != "":
_current_sbsar_id = self.render_current.split("_")[0]
self.render_current = ""
if len(self.render_queue.keys()) > 0:
_keys = self.render_queue.keys()
_key = list(_keys)[0]
_next_render = self.render_queue.pop(_key, None)
if _next_render is not None:
self.graph_render(
_next_render["render_id"],
_next_render["data"],
_next_render["request_type"],
_next_render["callback"]
)
def _set_material_info():
import bpy
str_data = json.dumps(data)
bpy.ops.substance.set_material(data=str_data)
for _item in bpy.context.scene.loaded_sbsars:
if _current_sbsar_id is not None and _item.uuid == _current_sbsar_id:
_item.suffix = Code_SbsarLoadSuffix.success.value[0]
_item.icon = Code_SbsarLoadSuffix.success.value[1]
SUBSTANCE_Threads.main_thread_run(_set_material_info)
@@ -0,0 +1,81 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: sbsar/async_ops.py
# brief: Asynchronous substance operations
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import bpy
import traceback
from ..utils import SUBSTANCE_Utils
from ..thread_ops import SUBSTANCE_Threads
from ..common import RENDER_KEY, ADDON_PACKAGE
def _render_sbsar(context, sbsar, index):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
if not os.path.exists(_addon_prefs.path_default):
os.makedirs(_addon_prefs.path_default)
from ..api import SUBSTANCE_Api
_render_id = RENDER_KEY.format(sbsar.uuid, sbsar.graphs[index].index)
_graph = sbsar.graphs[index]
_outputs = []
for _output in _graph.outputs:
_item = {
"identifier": _output.identifier,
"enabled": _output.shader_enabled,
"format": _output.shader_format,
"bitdepth": _output.shader_bitdepth
}
_outputs.append(_item)
_data = {
"uuid": sbsar.uuid,
"index": index,
"out_path": _addon_prefs.path_default,
"outputs": _outputs
}
SUBSTANCE_Api.sbsar_render(_render_id, _data)
def _set_input_visibility(sbsar, graph, inputs):
try:
def _callback_visibility():
_selected_sbsar = None
for _item in bpy.context.scene.loaded_sbsars:
if _item.uuid == sbsar.uuid:
_selected_sbsar = _item
break
if _selected_sbsar is None:
return
_graph = _selected_sbsar.graphs[int(graph.index)]
for _input in inputs:
if _input["identifier"] in _graph.inputs:
_graph.inputs[_input["identifier"]].visibleIf = _input["visibleIf"]
SUBSTANCE_Threads.main_thread_run(_callback_visibility)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Unknown Error while setting parameter visibility:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
@@ -0,0 +1,139 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: shader/callbacks.py
# brief: Callbacks for susbtance outputs and properties
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..thread_ops import SUBSTANCE_Threads
from ..sbsar.async_ops import _render_sbsar, _set_input_visibility
from ..utils import SUBSTANCE_Utils
from ..common import (
PRESET_CUSTOM,
Code_InputType,
Code_InputIdentifier,
Code_InputWidget,
Code_OutputSizeSuffix,
Code_Response
)
class SUBSTANCE_SbsarCallbacks():
# Output Size
@staticmethod
def on_linked_changed(self, context, parm_identifier):
if not hasattr(self, Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.linked.value):
return
_linked = getattr(self, Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.linked.value)
_new_width_width = getattr(self, Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.width.value)
if _linked:
setattr(self, Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.height.value, _new_width_width)
else:
SUBSTANCE_SbsarCallbacks.on_outputsize_changed(self, context, parm_identifier)
@staticmethod
def on_outputsize_changed(self, context, identifier):
if not self.callback["enabled"]:
return
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_graph = SUBSTANCE_Utils.get_selected_graph(context)
_preset = int(_graph.presets_list)
if not _graph.outputsize_exists:
return
_input = _graph.inputs[Code_InputIdentifier.outputsize.value]
_output_size_x = getattr(self, Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.width.value)
_output_size_y = getattr(self, Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.height.value)
_new_value = [int(_output_size_x), int(_output_size_y)]
from ..api import SUBSTANCE_Api
_result = SUBSTANCE_Api.sbsar_input_update(
context,
_sbsar,
_graph,
_input,
_new_value,
SUBSTANCE_SbsarCallbacks.on_input_update
)
if _result[0] == Code_Response.success:
_new_preset_value = SUBSTANCE_Utils.update_preset_outputsize(
_graph.presets[_preset].value,
_input,
Code_InputType.integer2.value,
_new_value
)
_graph.presets[_preset].value = _new_preset_value
# Parameters
@staticmethod
def on_input_update(context, sbsar, graph, input, value):
_value = SUBSTANCE_Utils.value_fix_type(input.identifier, input.guiWidget, input.type, value)
if input.guiWidget == Code_InputWidget.image.value:
if _value == "":
_value = "NONE"
else:
_filepath = bpy.data.images[_value].filepath
if _filepath == "":
_filepath = SUBSTANCE_Utils.render_image_input(bpy.data.images[_value], bpy.context)
_value = _filepath
from ..api import SUBSTANCE_Api
_result = SUBSTANCE_Api.sbsar_input_set(sbsar, graph, input, _value)
if context is not None and _result[0] == Code_Response.success:
SUBSTANCE_Threads.alt_thread_run(_set_input_visibility, (
sbsar,
graph,
_result[1]["data"]["inputs"]))
SUBSTANCE_Threads.alt_thread_run(_render_sbsar, (
context,
sbsar,
int(graph.index)))
graph.presets[PRESET_CUSTOM].value = _result[1]["data"]["preset"]
return _result
@staticmethod
def on_input_changed(self, context, identifier):
if not self.callback["enabled"]:
return
_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_graph = SUBSTANCE_Utils.get_selected_graph(context)
_preset = int(_graph.presets_list)
if _graph.presets[_preset].name != PRESET_CUSTOM:
_graph.preset_callback = False
_graph.presets_list = _graph.presets[PRESET_CUSTOM].index
_graph.preset_callback = True
_input = _graph.inputs[identifier]
_new_value = getattr(self, identifier)
from ..api import SUBSTANCE_Api
SUBSTANCE_Api.sbsar_input_update(
context,
_sbsar,
_graph,
_input,
_new_value,
SUBSTANCE_SbsarCallbacks.on_input_update
)
@@ -0,0 +1,57 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: sbsar/manager.py
# brief: Substance operations manager
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import traceback
from ..factory.sbsar import SUBSTANCE_SbsarFactory
from ..common import Code_Response
from ..utils import SUBSTANCE_Utils
class SUBSTANCE_SbsarManager():
def __init__(self):
self.sbsars = {}
def get(self, uuid):
if uuid not in self.sbsars:
return None
return self.sbsars[uuid]
def register(self, sbsar):
self.sbsars[sbsar.uuid] = sbsar
_result = SUBSTANCE_SbsarFactory.register_class(sbsar)
return _result
def unregister(self, uuid):
try:
if uuid in self.sbsars:
_sbsar = self.sbsars[uuid]
for _graph in _sbsar.graphs:
SUBSTANCE_SbsarFactory.unregister_class(_graph.inputs_class_name)
del self.sbsars[uuid]
return (Code_Response.success, None)
else:
return (Code_Response.sbsar_remove_not_found_error, None)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Substance removal error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.sbsar_factory_unregister_error, None)
@@ -0,0 +1,344 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: sbsar/sbsar.py
# brief: Substance class object definition
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
from ..utils import SUBSTANCE_Utils
from ..common import (
Code_InputType,
Code_InputWidget,
INPUT_DEFAULT_GROUP,
INPUT_IMAGE_DEFAULT_GROUP,
PRESET_CUSTOM,
CLASS_GRAPH_INPUTS
)
class SBS_EnumValue():
def __init__(self, enum):
self.first = enum["first"]
self.second = enum["second"]
def to_json(self):
_obj = {
"first": self.first,
"second": self.second,
}
return _obj
class SBS_Input():
def __init__(self, index, input):
if "index" in input:
self.index = input["index"]
else:
self.index = index
self.id = input["id"]
self.graphID = input["graphID"]
self.identifier = input["identifier"]
self.label = input["label"]
self.guiDescription = input["guiDescription"]
if input["type"] == Code_InputType.image.name:
self.guiGroup = INPUT_IMAGE_DEFAULT_GROUP
elif len(input["guiGroup"]) == 0:
self.guiGroup = INPUT_DEFAULT_GROUP
else:
self.guiGroup = input["guiGroup"]
self.guiVisibleIf = input["guiVisibleIf"]
self.userTag = input["userTag"]
self.type = input["type"]
self.guiWidget = input["guiWidget"]
self.showAsPin = input["showAsPin"]
self.useCache = input["useCache"]
self.visibleIf = input["visibleIf"]
self.isHeavyDuty = input["isHeavyDuty"]
self.enumValues = []
if "labelFalse" in input:
self.labelFalse = input["labelFalse"]
if "labelTrue" in input:
self.labelTrue = input["labelTrue"]
if "sliderClamp" in input:
self.sliderClamp = input["sliderClamp"]
if "sliderStep" in input:
self.sliderStep = input["sliderStep"]
if "maxValue" in input:
self.maxValue = input["maxValue"]
if "minValue" in input:
self.minValue = input["minValue"]
if "defaultValue" in input:
self.defaultValue = input["defaultValue"]
if "value" in input:
self.value = input["value"]
if "channelUse" in input:
self.channelUse = input["channelUse"]
if "enumValues" in input:
for _enum in input["enumValues"]:
_new_enum = SBS_EnumValue(_enum)
self.enumValues.append(_new_enum)
def to_json(self):
_obj = {
"id": self.id,
"graphID": self.graphID,
"identifier": self.identifier,
"label": self.label,
"guiDescription": self.guiDescription,
"guiGroup": self.guiGroup,
"guiVisibleIf": self.guiVisibleIf,
"userTag": self.userTag,
"type": self.type,
"guiWidget": self.guiWidget,
"showAsPin": self.showAsPin,
"useCache": self.useCache,
"visibleIf": self.visibleIf,
"isHeavyDuty": self.isHeavyDuty
}
if hasattr(self, "labelFalse"):
_obj["labelFalse"] = self.labelFalse
if hasattr(self, "labelTrue"):
_obj["labelTrue"] = self.labelTrue
if hasattr(self, "sliderClamp"):
_obj["sliderClamp"] = self.sliderClamp
if hasattr(self, "sliderStep"):
_obj["sliderStep"] = self.sliderStep
if hasattr(self, "maxValue"):
_obj["maxValue"] = self.maxValue
if hasattr(self, "minValue"):
_obj["minValue"] = self.minValue
if hasattr(self, "defaultValue"):
_obj["defaultValue"] = self.defaultValue
if hasattr(self, "value"):
_obj["value"] = self.value
if hasattr(self, "channelUse"):
_obj["channelUse"] = self.channelUse
if hasattr(self, "enumValues"):
_obj["enumValues"] = self.enumValues
return _obj
class SBS_Output():
def __init__(self, output, index):
self.id = output["id"]
self.index = index
self.graphID = output["graphID"]
self.format = output["format"]
self.mipmaps = output["mipmaps"]
self.identifier = output["identifier"]
self.label = output["label"]
self.guiDescription = output["guiDescription"]
self.group = output["group"]
self.guiVisibleIf = output["guiVisibleIf"]
self.userTag = output["userTag"]
self.type = output["type"]
self.guiType = output["guiType"]
self.defaultChannelUse = output["defaultChannelUse"]
self.enabled = output["enabled"]
self.channelUseSpecified = output["channelUseSpecified"]
self.channelUse = output["channelUse"]
def to_json(self):
_obj = {
"id": self.id,
"graphID": self.graphID,
"format": self.format,
"mipmaps": self.mipmaps,
"identifier": self.identifier,
"label": self.label,
"guiDescription": self.guiDescription,
"group": self.group,
"guiVisibleIf": self.guiVisibleIf,
"userTag": self.userTag,
"type": self.type,
"guiType": self.guiType,
"defaultChannelUse": self.defaultChannelUse,
"enabled": self.enabled,
"channelUseSpecified": self.channelUseSpecified,
"channelUse": self.channelUse
}
return _obj
class SBS_Preset():
def __init__(self, preset, addon_prefs=None, inputs=None):
self.index = str(preset["index"])
self.label = preset["label"]
self.value = preset["value"]
if "icon" in preset:
self.icon = preset["icon"]
else:
self.icon = "LOCKED" if self.label != PRESET_CUSTOM else "UNLOCKED"
if "embedded" in preset:
self.embedded = preset["embedded"]
else:
self.embedded = True if self.label != PRESET_CUSTOM else False
if addon_prefs is not None and inputs is not None:
if "$outputsize" in inputs:
self.value = SUBSTANCE_Utils.update_preset_outputsize(
self.value,
inputs["$outputsize"],
Code_InputType.integer2.value,
addon_prefs.default_resolution.get())
if "normal_format" in inputs:
self.value = SUBSTANCE_Utils.update_preset_outputsize(
self.value,
inputs["normal_format"],
Code_InputType.integer.value,
0 if addon_prefs.default_normal_format == "DirectX" else 1)
def to_json(self):
_obj = {
"index": int(self.index),
"label": self.label,
"value": self.value,
"icon": self.icon,
"embedded": self.embedded
}
return _obj
class SBS_Graph():
def __init__(self, unique_name, uuid, index, graph, multi_graph, addon_prefs=None):
self.index = str(index)
self.uid = str(graph["uid"])
self.label = graph["label"]
self.identifier = graph["packageUrl"].replace("pkg://", "")
self.packageUrl = graph["packageUrl"]
if graph["physicalSize"][0] == 0 or graph["physicalSize"][1] == 0:
self.physicalSize = (1/100, 1/100, 1/100)
else:
self.physicalSize = (graph["physicalSize"][0]/100,
graph["physicalSize"][1]/100,
graph["physicalSize"][2]/100)
self.tiling = addon_prefs.default_tiling.get()
self.inputs = {}
self.inputs_groups = {}
self.outputs = {}
self.presets = []
if multi_graph:
_material_name = "{}-{}".format(unique_name, graph["label"]).replace(" ", "_")
_class_name = "{}-{}".format(uuid, self.uid)
else:
_material_name = "{}".format(unique_name).replace(" ", "_")
_class_name = "{}".format(uuid)
self.material = _material_name
self.inputs_class_name = CLASS_GRAPH_INPUTS.format(_class_name)
if len(graph["inputs"]) > 0 and "index" in graph["inputs"][0]:
_sorted_inputs = sorted(graph["inputs"], key=lambda d: d['index'])
else:
_sorted_inputs = graph["inputs"]
_input_index = 0
for _input in _sorted_inputs:
if _input["guiWidget"] != Code_InputWidget.nowidget.value or _input["type"] != Code_InputType.string.name:
if _input["type"] == Code_InputType.image.name:
_group = INPUT_IMAGE_DEFAULT_GROUP
else:
_group = _input["guiGroup"] if len(_input["guiGroup"]) > 0 else INPUT_DEFAULT_GROUP
if _group not in self.inputs_groups:
self.inputs_groups[_group] = [_input["identifier"]]
else:
self.inputs_groups[_group].append(_input["identifier"])
_new_input = SBS_Input(_input_index, _input)
_input_index += 1
self.inputs[_input["identifier"]] = _new_input
for _idx, _output in enumerate(graph["outputs"]):
_new_output = SBS_Output(_output, _idx)
self.outputs[_output["identifier"]] = _new_output
_pre_sort_presets = []
for _preset in graph["presets"]:
_new_preset = SBS_Preset(_preset, addon_prefs, self.inputs)
_pre_sort_presets.append(_new_preset)
self.presets = sorted(_pre_sort_presets, key=lambda _preset: _preset.index, reverse=False)
def to_json(self):
_obj = {
"uid": self.uid,
"label": self.label,
"physicalSize": self.physicalSize,
"inputs": [],
"outputs": [],
"presets": []
}
for _preset in self.presets:
_obj["presets"].append(_preset.to_json())
for _key, _output in self.outputs.items():
_obj["outputs"].append(_output.to_json())
for _key, _input in self.inputs.items():
_obj["inputs"].append(_input.to_json())
return _obj
def reset_presets(self, presets):
self.presets = []
_pre_sort_presets = []
for _preset in presets:
_new_preset = SBS_Preset(_preset)
_pre_sort_presets.append(_new_preset)
self.presets = sorted(_pre_sort_presets, key=lambda _preset: _preset.index, reverse=False)
class SBSAR():
def __init__(self, unique_name, filename, data, addon_prefs=None):
self.uuid = data["uuid"]
self.version = data["version"]
self.name = unique_name
self.filename = filename
self.filepath = data["filename"]
self.graphs = []
_multi_graph = len(data["graphs"]) > 1
for _idx, _graph in enumerate(data["graphs"]):
_new_graph = SBS_Graph(unique_name, self.uuid, _idx, _graph, _multi_graph, addon_prefs)
self.graphs.append(_new_graph)
def to_json(self):
_obj = {
"uuid": self.uuid,
"name": self.name,
"filename": self.filename,
"filepath": self.filepath,
"graphs": []
}
for _graph in self.graphs:
_obj["graphs"].append(_graph.to_json())
return _obj
@@ -0,0 +1,38 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: shader/callbacks.py
# brief: Callbacks for shader presets parameters and outputs
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
from ..utils import SUBSTANCE_Utils
class SUBSTANCE_ShaderCallbacks():
@staticmethod
def on_shader_changed(self, context):
_, _, _selected_preset = SUBSTANCE_Utils.get_selected_shader(context)
_selected_preset.modified = True
@staticmethod
def on_input_changed(self, context):
SUBSTANCE_ShaderCallbacks.on_shader_changed(self, context)
@staticmethod
def on_output_changed(self, context):
SUBSTANCE_ShaderCallbacks.on_shader_changed(self, context)
@@ -0,0 +1,113 @@
"""
Copyright (C) 2023 Adobe.
This program is free software: you can redistribute it and/or modify
it under theshad 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/>.
"""
# file: shader/manager.py
# brief: Shader presets operation manager
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import os
import traceback
from .shader import ShaderPreset
from ..utils import SUBSTANCE_Utils
from ..factory.shader import SUBSTANCE_ShaderFactory
from ..common import (
Code_Response,
ADDON_ROOT
)
class SUBSTANCE_ShaderManager():
def __init__(self):
self.shaders = {}
def initialize(self, addon_prefs):
_shaders_dir = os.path.join(ADDON_ROOT, "_presets/default").replace('\\', '/')
for _filepath in os.listdir(_shaders_dir):
# Load the shader presets
_result = self.load(_filepath)
if _result[0] != Code_Response.success:
SUBSTANCE_Utils.log_data(
"ERROR",
"Substance file [{}] could not be loaded".format(
_filepath),
display=True)
continue
_shader_preset = ShaderPreset(_filepath, _result[1])
_new_shader = addon_prefs.shaders.add()
_new_shader.init(_shader_preset)
self.register(_shader_preset)
SUBSTANCE_Utils.log_data("INFO", "Shader Presets [{}] initialized...".format(_filepath))
return (Code_Response.success, None)
def load(self, filename):
try:
_path = SUBSTANCE_Utils.get_shader_file(filename)
_data = SUBSTANCE_Utils.get_json(_path)
return (Code_Response.success, _data)
except Exception:
return (Code_Response.shader_preset_load_error, None)
def register(self, shader):
self.shaders[shader.filename] = shader
_result = SUBSTANCE_ShaderFactory.register_class(shader)
return _result
def remove_presets(self, shader_presets):
try:
return Code_Response.success
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Shader Preset removal error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return Code_Response.shader_preset_remove_error
def save_presets(self, shader_preset):
try:
_default_shader_file = os.path.join(
ADDON_ROOT,
"_presets/default/" + shader_preset["filename"]).replace('\\', '/')
_custom_shader_file = os.path.join(
ADDON_ROOT,
"_presets/custom/" + shader_preset["filename"]).replace('\\', '/')
_custom_shader_path = os.path.join(
ADDON_ROOT,
"_presets/custom").replace('\\', '/')
# Read Original Shader Preset
if not os.path.exists(_default_shader_file):
return Code_Response.shader_preset_default_not_exist_error
_data = SUBSTANCE_Utils.get_json(_default_shader_file)
_data["inputs"] = shader_preset["inputs"]
_data["outputs"] = shader_preset["outputs"]
# Write Custom Shader Preset
if not os.path.exists(_custom_shader_path):
os.mkdir(_custom_shader_path)
SUBSTANCE_Utils.set_json(_custom_shader_file, _data)
return Code_Response.success
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Shader Preset saving error:")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return Code_Response.shader_preset_save_error
@@ -0,0 +1,106 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: shader/shader.py
# brief: Shader preset class object definition
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
from ..common import CLASS_SHADER_INPUTS
class ShaderPreset_Output():
def __init__(self, output):
self.id = output["id"]
self.label = output["label"]
self.enabled = output["enabled"]
self.optional = output["optional"]
self.colorspace = output["colorspace"]
self.format = output["format"]
self.bitdepth = output["bitdepth"]
self.normal = output["normal"] if "normal" in output else False
def to_json(self):
_obj = {
"id": self.id,
"label": self.label,
"enabled": self.enabled,
"optional": self.optional,
"colorspace": self.colorspace,
"format": self.format,
"bitdepth": self.bitdepth
}
if self.normal:
_obj["normal"] = True
return _obj
class ShaderPreset_Input():
def __init__(self, input):
self.id = input["id"]
self.label = input["label"]
self.type = input["type"]
self.default = input["default"]
self.min = input["min"] if "min" in input else None
self.max = input["max"] if "max" in input else None
def to_json(self):
_obj = {
"id": self.id,
"label": self.label,
"type": self.type,
"default": self.default
}
if self.min is not None:
_obj["min"] = self.min
if self.max is not None:
_obj["max"] = self.max
return _obj
class ShaderPreset():
def __init__(self, filename, data):
self.filename = filename
self.name = filename.replace(".json", "")
self.label = data["label"]
self.inputs = {}
self.outputs = {}
self.inputs_class_name = CLASS_SHADER_INPUTS.format(filename.replace(".json", "").replace(" ", "_"))
for _key, _input in data["inputs"].items():
_item = ShaderPreset_Input(_input)
self.inputs[_key] = _item
for _key, _output in data["outputs"].items():
_item = ShaderPreset_Output(_output)
self.outputs[_key] = _item
def to_json(self):
_obj = {
"label": self.label,
"inputs": {},
"outputs": {},
"inputs_class_name": self.inputs_class_name
}
for _key, _input in self.inputs.items():
_obj["inputs"][_key] = _input.to_json()
for _key, _output in self.outputs.items():
_obj["outputs"][_key] = _output.to_json()
return _obj
@@ -0,0 +1,81 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: thread_ops.py
# brief: Threading operations
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
import queue
import threading
QUEUE_MAIN_THREAD = queue.Queue()
QUEUE_CURSOR = queue.Queue()
QUEUE_CURSOR_ACTIVE = False
class SUBSTANCE_Threads():
@staticmethod
def alt_thread_run(function, args):
_new_thead = threading.Thread(target=function, args=args)
_new_thead.start()
return _new_thead
@staticmethod
def timer_thread_run(delay_time, function, args):
_new_thead = threading.Timer(delay_time, function, args=args)
_new_thead.start()
return _new_thead
@staticmethod
def main_thread_run(function):
QUEUE_MAIN_THREAD.put(function)
@staticmethod
def exec_queued_function():
while not QUEUE_MAIN_THREAD.empty():
function = QUEUE_MAIN_THREAD.get()
function()
return 0.1
@staticmethod
def cursor_push(cursor_name):
if threading.current_thread() is threading.main_thread():
global QUEUE_CURSOR_ACTIVE
if QUEUE_CURSOR_ACTIVE:
QUEUE_CURSOR.put(cursor_name)
QUEUE_CURSOR_ACTIVE = True
bpy.context.window.cursor_modal_set(cursor_name)
else:
SUBSTANCE_Threads.main_thread_run(lambda: SUBSTANCE_Threads.cursor_push(cursor_name))
@staticmethod
def cursor_pop():
if threading.current_thread() is threading.main_thread():
try:
_cursorName = QUEUE_CURSOR.get(False)
bpy.context.window.cursor_modal_set(_cursorName)
except Exception:
global QUEUE_CURSOR_ACTIVE
QUEUE_CURSOR_ACTIVE = False
if bpy.context and bpy.context.window:
bpy.context.window.cursor_modal_restore()
else:
SUBSTANCE_Threads.main_thread_run(lambda: SUBSTANCE_Threads.cursor_pop())
@@ -0,0 +1,230 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: toolkit/manager.py
# brief: SRE toolkit operations manager
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import sys
import os
import time
import zipfile
import shutil
import stat
import subprocess
import traceback
import bpy
from ..utils import SUBSTANCE_Utils
from ..common import (
Code_Response,
TOOLKIT_VERSION_FILE,
TOOLKIT_EXT,
TOOLKIT_NAME,
SRE_DIR,
SRE_BIN,
SRE_PORT,
ADDON_PACKAGE
)
def find_between(s, first, last):
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return ""
class SRE_ToolkitManager():
def __init__(self):
self.process = None
self.version = None
self.toolkit_dir = SRE_DIR
self.toolkit_bin = SRE_BIN
def get_path(self):
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
return _addon_prefs.path_tools
def is_installed(self):
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_toolkit_path = _addon_prefs.path_tools
_path = os.path.join(_toolkit_path, self.toolkit_bin)
return os.path.isfile(_path)
def is_running(self):
if sys.platform.startswith('win'):
# command to get the process ID of the remote engine
_command = "wmic process where name='" + self.toolkit_bin + "' get ProcessId"
_output = os.popen(_command).read()
_lines = _output.splitlines()
# check specifically for the remote engine process ID
for _line in _lines:
if _line != 'ProcessId':
if len(_line) > 1:
return True
else:
# command to enumerate all of the running processes
_command = 'ps -Af'
_tmp = os.popen(_command).read()
# check if the remote engine name is in the running process list
if self.toolkit_bin in _tmp[:]:
return True
return False
# Version
def version_get(self):
if self.version is None:
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_toolkit_path = _addon_prefs.path_tools
_path = os.path.join(_toolkit_path, TOOLKIT_VERSION_FILE)
if os.path.exists(_path):
try:
with open(_path, 'r') as _f:
self.version = _f.read()
except Exception:
return (Code_Response.toolkit_version_get_error, None)
else:
return (Code_Response.toolkit_version_not_found_error, None)
return (Code_Response.success, self.version)
# Toolkit
def start(self, delay):
if not self.is_running():
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_toolkit_path = _addon_prefs.path_tools
_path = os.path.join(_toolkit_path, self.toolkit_bin)
if not sys.platform.startswith("win"):
_st = os.stat(_path)
# set the remote engine to executable
os.chmod(_path, _st.st_mode | stat.S_IEXEC)
_args = []
_args.append(_path)
_args.append("--port={}".format(SRE_PORT))
_args.append("-e={}".format(_addon_prefs.engine))
self.process = subprocess.Popen(
_args,
cwd=_toolkit_path,
shell=False,
start_new_session=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT,
close_fds=True
)
time.sleep(delay)
return (Code_Response.success, None)
else:
return (Code_Response.toolkit_already_started, None)
def stop(self):
if self.process is not None:
try:
if sys.platform.startswith('win'):
self.process.kill()
else:
self.process.terminate()
self.process.wait()
self.process = None
return (Code_Response.success, None)
except Exception:
return (Code_Response.toolkit_stop_error, None)
else:
return (Code_Response.toolkit_process_error, None)
def _clear_quarantine(self, filepath):
if sys.platform == "darwin":
# clearing the apple's quarantine flag
_cmd = ["xattr", "-d", "com.apple.quarantine", filepath]
try:
subprocess.call(_cmd)
except Exception:
# quarantine flag doesn't exist
pass
def _verify(self, filepath):
_filename, _extension = os.path.splitext(filepath)
_basename = os.path.basename(_filename)
if _extension == TOOLKIT_EXT:
if _basename.startswith(TOOLKIT_NAME):
return (Code_Response.success, _basename)
else:
return (Code_Response.toolkit_file_not_recognized_error, None)
else:
return (Code_Response.toolkit_file_ext_error, None)
def remove(self):
try:
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_toolkit_path = _addon_prefs.path_tools
# remove all subfolders except resourcepooldb
for _root, _dirs, _files in os.walk(_toolkit_path):
for _dir in _dirs:
if _dir != "resourcepooldb":
shutil.rmtree(os.path.join(_root, _dir))
# remove all files in the toolkit dir
for _f in os.listdir(_toolkit_path):
_filepath = os.path.join(_toolkit_path, _f)
if os.path.isfile(_filepath):
os.remove(_filepath)
self.version = None
return (Code_Response.success, None)
except Exception:
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.toolkit_remove_error, None)
def install(self, filepath):
try:
_addon_prefs = bpy.context.preferences.addons[ADDON_PACKAGE].preferences
_toolkit_path = _addon_prefs.path_tools
_result = self._verify(filepath)
if _result[0] != Code_Response.success:
return _result
self._clear_quarantine(filepath)
with zipfile.ZipFile(filepath, 'r') as _zip_ref:
_zip_ref.extractall(_toolkit_path)
_version = find_between(_result[1], 'Substance3DIntegrationTools-', '+')
if _version == "":
_version = find_between(_result[1], 'Substance3DIntegrationTools-', '-')
if _version == "":
return (Code_Response.toolkit_version_empty_error, None)
_version_path = os.path.join(_toolkit_path, TOOLKIT_VERSION_FILE)
if os.path.exists(_version_path):
os.remove(_version_path)
with open(_version_path, 'w') as _fp:
_fp.write(_version)
self.version = None
return (Code_Response.success, None)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Toolkit install failed")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.toolkit_install_error, None)
@@ -0,0 +1,45 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ui/presets.py
# brief: Presets UI
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..ops.presets import (
SUBSTANCE_OT_ImportPreset,
SUBSTANCE_OT_ExportPreset,
SUBSTANCE_OT_ExportAll
)
class SUBSTANCE_MT_PresetOptions(bpy.types.Menu):
bl_idname = 'SUBSTANCE_MT_PresetOptions'
bl_label = ""
bl_description = 'Additional Preset Options'
# bl_options = {'REGISTER'}
def draw(self, context):
_col = self.layout.column()
_row = _col.row()
_row.operator(SUBSTANCE_OT_ExportPreset.bl_idname, icon='EXPORT')
_row = _col.row()
_row.operator(SUBSTANCE_OT_ExportAll.bl_idname, icon='EXPORT')
_row = _col.row()
_row.operator(SUBSTANCE_OT_ImportPreset.bl_idname, icon='IMPORT')
@@ -0,0 +1,486 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ui/sbsar.py
# brief: Substance UI
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..ops.web import SUBSTANCE_OT_GoToShare, SUBSTANCE_OT_GoToSource
from ..ops.sbsar import (
SUBSTANCE_OT_LoadSBSAR,
SUBSTANCE_OT_ApplySBSAR,
SUBSTANCE_OT_RemoveSBSAR,
SUBSTANCE_OT_ReloadSBSAR,
SUBSTANCE_OT_DuplicateSBSAR
)
from ..ops.inputs import (
SUBSTANCE_OT_RandomizeSeed,
SUBSTANCE_OT_InputGroupsCollapse,
SUBSTANCE_OT_InputGroupsExpand
)
from ..ops.presets import SUBSTANCE_OT_AddPreset, SUBSTANCE_OT_DeletePreset, SUBSTANCE_OT_DeletePresetModal
from .presets import SUBSTANCE_MT_PresetOptions
from ..api import SUBSTANCE_Api
from ..utils import SUBSTANCE_Utils
from ..common import (
ADDON_PACKAGE,
ICONS_DICT,
DRAW_DEFAULT_FACTOR,
Code_InputIdentifier,
Code_OutputSizeSuffix,
Code_InputWidget,
Code_InputType,
INPUT_CHANNELS_GROUP,
OUTPUTS_FILTER_DICT,
INPUT_TECHINCAL_GROUP,
INPUT_DEFAULT_GROUP,
INPUT_IMAGE_DEFAULT_GROUP,
Code_SbsarLoadSuffix
)
class SUBSTANCE_UL_SbsarList(bpy.types.UIList):
bl_idname = 'SUBSTANCE_UL_SbsarList'
bl_label = 'Loaded Substance 3D Materials'
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
_suffix = item.suffix
_is_rendering = SUBSTANCE_Api.sbsar_is_rendering(item.uuid)
if item.icon == Code_SbsarLoadSuffix.render.value[1] or _is_rendering == 2:
_icon = ICONS_DICT["render"].icon_id
_suffix = Code_SbsarLoadSuffix.render.value[0]
elif _is_rendering == 1:
_icon = ICONS_DICT["render_queue"].icon_id
_suffix = Code_SbsarLoadSuffix.render_queue.value[0]
elif item.icon != Code_SbsarLoadSuffix.success.value[1]:
_icon = ICONS_DICT[item.icon].icon_id
else:
_icon = 0
_name = item.name + " " + _suffix
# draw the item in the layout
if self.layout_type in {'DEFAULT', 'COMPACT'}:
layout.label(text=_name, icon_value=_icon)
elif self.layout_type in {'GRID'}:
layout.alignment = 'CENTER'
layout.label(text='', icon_value=_icon)
def SubstanceMainPanelFactory(space):
class SUBSTANCE_PT_MAIN(bpy.types.Panel):
bl_idname = 'SUBSTANCE_PT_MAIN_{}'.format(space)
bl_space_type = space
bl_label = 'Substance 3D Panel'
bl_region_type = 'UI'
bl_category = 'Substance 3D'
def draw(self, context):
# Shortcut
_shortcut = context.preferences.addons[ADDON_PACKAGE].preferences.shortcuts
self.layout.label(text="(Quick Access: " + _shortcut.menu_label + ")")
_row = self.layout.row(align=True)
# Buttons (Operators)
_row.operator(SUBSTANCE_OT_LoadSBSAR.bl_idname, text="Load")
_row.separator()
_row.operator(SUBSTANCE_OT_ApplySBSAR.bl_idname, text="Apply")
_row.separator()
_row.operator(SUBSTANCE_OT_GoToShare.bl_idname, text="", icon_value=ICONS_DICT["share_icon"].icon_id)
_row.separator()
_row.operator(SUBSTANCE_OT_GoToSource.bl_idname, text="", icon_value=ICONS_DICT["source_icon"].icon_id)
_row.separator()
_row.operator(SUBSTANCE_OT_DuplicateSBSAR.bl_idname, text="", icon='DUPLICATE')
_row.separator()
_row.operator(SUBSTANCE_OT_ReloadSBSAR.bl_idname, text="", icon='FILE_REFRESH')
_row.separator()
_row.operator(SUBSTANCE_OT_RemoveSBSAR.bl_idname, text="", icon='TRASH')
_row.separator()
# SBSAR List
if len(context.scene.loaded_sbsars) > 0:
_col = self.layout.column()
_col.label(text="Loaded 3D Substance Materials")
_col.template_list(
SUBSTANCE_UL_SbsarList.bl_idname,
'Loaded 3D Substance Materials',
context.scene,
'loaded_sbsars',
context.scene,
'sbsar_index')
_selected_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
if len(_selected_sbsar.graphs) > 1:
_row = _col.row()
_split = _row.split(factor=0.25)
_col_1 = _split.column()
_col_2 = _split.column()
_col_1.label(text="Graph")
_col_2.prop(_selected_sbsar, "graphs_list", text="")
return SUBSTANCE_PT_MAIN
def SubstancePreviewFactory(space):
class SUBSTANCE_PT_PREVIEW(bpy.types.Panel):
bl_idname = 'SUBSTANCE_PT_PREVIEW_{}'.format(space)
bl_space_type = space
bl_label = 'Preview'
bl_region_type = 'UI'
bl_category = 'Substance 3D'
@classmethod
def poll(cls, context):
return len(context.scene.loaded_sbsars) > 0
def draw(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_col = self.layout.column(align=True)
if context.scene.sbsar_redraw == 0:
_col.scale_y = 0.99
elif context.scene.sbsar_redraw == 1:
_col.scale_y = 1.0
else:
_col.scale_y = 1.01
# Thumbnail
if _selected_graph.material.name in bpy.data.materials:
_grid = _col.grid_flow(columns=1, align=True)
if _selected_graph.material.name in bpy.data.materials:
_grid.template_preview(bpy.data.materials[_selected_graph.material.name], show_buttons=False)
# if _selected_graph.thumbnail in bpy.data.textures:
# _grid.template_ID_preview(bpy.data.textures[_selected_graph.thumbnail], "image")
return SUBSTANCE_PT_PREVIEW
def SubstanceGraphPanelFactory(space):
class SUBSTANCE_PT_GRAPH(bpy.types.Panel):
bl_idname = 'SUBSTANCE_PT_GRAPH_{}'.format(space)
bl_space_type = space
bl_label = 'Graph Parameters'
bl_region_type = 'UI'
bl_category = 'Substance 3D'
@classmethod
def poll(cls, context):
return len(context.scene.loaded_sbsars) > 0
def draw(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
_col = self.layout.column(align=True)
# Presets
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Preset")
_row = _col_2.row()
_row.prop(_selected_graph, "presets_list", text='')
_row.operator(SUBSTANCE_OT_AddPreset.bl_idname, text='', icon='ADD')
if _addon_prefs.preset_auto_delete_enabled:
_row.operator(SUBSTANCE_OT_DeletePreset.bl_idname, text='', icon='TRASH')
else:
_row.operator(SUBSTANCE_OT_DeletePresetModal.bl_idname, text='', icon='TRASH')
_row.menu(SUBSTANCE_MT_PresetOptions.bl_idname, icon='TRIA_DOWN')
# Phyisical Size
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Physical Size")
_row = _col_2.row()
_row.prop(_selected_graph.physical_size, "x", text='')
_row.enabled = False
_row_2 = _row.column()
_row_2.prop(_selected_graph.physical_size, "y", text='')
_row_2.enabled = False
_row_3 = _row.column()
_row_3.prop(_selected_graph.physical_size, "z", text='')
_row_3.enabled = False
# Tiling
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Tiling")
_row = _col_2.row()
_row.prop(_selected_graph.tiling, "x", text='')
_row_2 = _row.column()
_row_2.prop(_selected_graph.tiling, "y", text='')
_row_2.enabled = not _selected_graph.tiling.linked
_row_3 = _row.column()
_row_3.prop(_selected_graph.tiling, "z", text='')
_row_3.enabled = not _selected_graph.tiling.linked
_row.prop(_selected_graph.tiling, "linked", text='', icon='LOCKED')
_inputs = getattr(context.scene, _selected_graph.inputs_class_name)
if _selected_graph.outputsize_exists:
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Resolution")
_row = _col_2.row()
_row.prop(
_inputs,
Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.width.value,
text='')
_row_2 = _row.column()
_row_2.prop(
_inputs,
Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.height.value,
text='')
_linked = getattr(_inputs, Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.linked.value)
_row_2.enabled = not _linked
_row.prop(
_inputs,
Code_InputIdentifier.outputsize.value + Code_OutputSizeSuffix.linked.value,
text='',
icon='LOCKED')
if _selected_graph.randomseed_exists:
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Random Seed")
_row = _col_2.row()
_row.prop(
_inputs,
Code_InputIdentifier.randomseed.value,
text="")
_row.operator(
SUBSTANCE_OT_RandomizeSeed.bl_idname,
text="",
icon_value=ICONS_DICT["random_icon"].icon_id)
# Update textures only
_row = _col.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="")
_row = _col_2.row()
_row.prop(_selected_graph, "update_tx_only", text="Only update texture images")
return SUBSTANCE_PT_GRAPH
def SubstanceOutputsPanelFactory(space):
class SUBSTANCE_PT_OUTPUTS(bpy.types.Panel):
bl_idname = 'SUBSTANCE_PT_OUTPUTS_{}'.format(space)
bl_space_type = space
bl_label = 'Outputs'
bl_region_type = 'UI'
bl_category = 'Substance 3D'
@classmethod
def poll(cls, context):
if len(context.scene.loaded_sbsars) > 0:
return True
return False
def draw(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_col = self.layout.column(align=True)
_box = _col.box()
_row = _box.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text="Shader")
_row = _col_2.row()
_row.prop(_selected_graph, 'shaders_list', text="")
_row.prop(_selected_graph, 'outputs_filter', text="", expand=True)
# Show current outputs
_selected_preset_idx = int(_selected_graph.shaders_list)
_, _, _selected_shader_preset = SUBSTANCE_Utils.get_selected_shader(context, _selected_preset_idx)
_shader_outputs = _selected_shader_preset.outputs
for _output in _selected_graph.outputs:
if _selected_graph.outputs_filter == OUTPUTS_FILTER_DICT[0][0] and not _output.shader_enabled:
continue
if (_selected_graph.outputs_filter == OUTPUTS_FILTER_DICT[1][0] and
_output.defaultChannelUse not in _shader_outputs):
continue
_row = _box.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text=_output.label)
_row = _col_2.row()
_row.prop(_output, "shader_enabled", text="")
if _output.type == "image":
_row.prop(_output, "shader_format", text="")
_row.prop(_output, "shader_bitdepth", text="")
return SUBSTANCE_PT_OUTPUTS
def SubstanceInputsPanelFactory(space):
class SUBSTANCE_PT_INPUTS(bpy.types.Panel):
bl_idname = 'SUBSTANCE_PT_INPUTS_{}'.format(space)
bl_space_type = space
bl_label = 'Parameters'
bl_region_type = 'UI'
bl_category = 'Substance 3D'
@classmethod
def poll(cls, context):
if len(context.scene.loaded_sbsars) > 0:
return True
return False
def draw(self, context):
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_col = self.layout.column(align=True)
_row = _col.row()
_row.operator(SUBSTANCE_OT_InputGroupsExpand.bl_idname, text='Expand Groups', icon='TRIA_DOWN')
_row.operator(SUBSTANCE_OT_InputGroupsCollapse.bl_idname, text='Collapse Groups', icon='TRIA_RIGHT')
if SUBSTANCE_Utils.inputs_empty(_selected_graph.inputs):
_row = _col.row()
_row.label(text="No parameters available")
else:
_group_labels = []
for _group in _selected_graph.input_groups:
if _group.label == INPUT_IMAGE_DEFAULT_GROUP:
_group_labels.append(_group)
for _group in _selected_graph.input_groups:
if _group.label == INPUT_DEFAULT_GROUP:
_group_labels.append(_group)
for _group in _selected_graph.input_groups:
if (_group.label != INPUT_TECHINCAL_GROUP and
_group.label != INPUT_DEFAULT_GROUP and
_group.label != INPUT_IMAGE_DEFAULT_GROUP):
_group_labels.append(_group)
for _group in _selected_graph.input_groups:
if _group.label == INPUT_TECHINCAL_GROUP:
_group_labels.append(_group)
for _group in _group_labels:
if _group.label == INPUT_CHANNELS_GROUP:
continue
_empty = True
for _idx, _input in enumerate(_selected_graph.inputs):
if (_group.label == _input.guiGroup and
_input.visibleIf and
_input.identifier != Code_InputIdentifier.randomseed.value and
_input.identifier != Code_InputIdentifier.outputsize.value):
_empty = False
break
if _empty:
continue
_box = _col.box()
_row = _box.row()
_row.alignment = "LEFT"
_row.prop(
_group,
"collapsed",
icon='TRIA_DOWN' if not _group.collapsed else 'TRIA_RIGHT',
text=_group.label+":",
emboss=False)
if not _group.collapsed:
_inputs = getattr(context.scene, _selected_graph.inputs_class_name)
for _idx, _input in enumerate(_selected_graph.inputs):
if _input.guiGroup != _group.label:
continue
if (_input.guiWidget == Code_InputWidget.nowidget.value and
_input.type != Code_InputType.string.name):
continue
if not _input.visibleIf:
continue
_row = _box.row()
_split = _row.split(factor=DRAW_DEFAULT_FACTOR)
_col_1 = _split.column()
_col_2 = _split.column()
_row = _col_1.row()
_row.alignment = "RIGHT"
_row.label(text=_input.label)
_row = _col_2.row()
if _input.type == Code_InputType.string.name:
_row.prop(_inputs, _input.identifier, text="")
elif _input.guiWidget == Code_InputWidget.combobox.value:
_row.prop(_inputs, _input.identifier, text="")
elif _input.guiWidget == Code_InputWidget.slider.value:
_row.prop(_inputs, _input.identifier, text="", slider=True)
elif _input.guiWidget == Code_InputWidget.togglebutton.value:
_row.prop(_inputs, _input.identifier, expand=True)
elif _input.guiWidget == Code_InputWidget.color.value:
if _input.type == Code_InputType.float.name:
_row.prop(_inputs, _input.identifier, text="", slider=True)
else:
_row.prop(_inputs, _input.identifier, text="")
elif _input.guiWidget == Code_InputWidget.angle.value:
_row.prop(_inputs, _input.identifier, text="", slider=True)
elif _input.guiWidget == Code_InputWidget.position.value:
_row.prop(_inputs, _input.identifier, text="", slider=True)
elif _input.guiWidget == Code_InputWidget.image.value:
_row.template_ID(_inputs, _input.identifier, open="image.open")
else:
_row.alert = True
_row.label(text="Parameter type [{}] not supported yet".format(
_input.guiWidget))
_row.alert = False
return SUBSTANCE_PT_INPUTS
@@ -0,0 +1,78 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: ui/shortcut.py
# brief: Shortcuts UI
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
from ..utils import SUBSTANCE_Utils
from ..common import SHORTCUT_CLASS_NAME
from ..ops.sbsar import (
SUBSTANCE_OT_LoadSBSAR,
SUBSTANCE_OT_ApplySBSAR,
SUBSTANCE_OT_RemoveSBSAR,
SUBSTANCE_OT_DuplicateSBSAR,
SUBSTANCE_OT_ReloadSBSAR
)
def SubstanceShortcutMenuFactory(space):
class SUBSTANCE_MT_Main(bpy.types.Menu):
bl_idname = SHORTCUT_CLASS_NAME.format(space)
bl_label = 'Substance 3D Menu'
def draw(self, context):
self.layout.operator_context = 'INVOKE_REGION_WIN'
_row = self.layout.row(align=True)
_row.operator(SUBSTANCE_OT_LoadSBSAR.bl_idname, text="Load New Substance File(s)")
_row = self.layout.row()
_row.separator()
if len(context.scene.loaded_sbsars) > 0:
_selected_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_selected_graph = SUBSTANCE_Utils.get_selected_graph(context)
_sbsar_name = _selected_sbsar.name + " - " + _selected_graph.name
_row = self.layout.row()
_row.operator(
SUBSTANCE_OT_ApplySBSAR.bl_idname,
text="Apply " + _sbsar_name,
icon='MATERIAL')
_row = self.layout.row()
_row.operator(
SUBSTANCE_OT_DuplicateSBSAR.bl_idname,
text="Duplicate " + _selected_sbsar.name,
icon='DUPLICATE')
_row = self.layout.row()
_row.operator(
SUBSTANCE_OT_ReloadSBSAR.bl_idname,
text="Refresh " + _selected_sbsar.name,
icon='FILE_REFRESH')
_row = self.layout.row()
_row.operator(SUBSTANCE_OT_RemoveSBSAR.bl_idname, text="Remove " + _selected_sbsar.name, icon='TRASH')
return SUBSTANCE_MT_Main
@@ -0,0 +1,283 @@
"""
Copyright (C) 2023 Adobe.
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/>.
"""
# file: utils.py
# brief: General utility functions
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import bpy
import os
import json
from time import time
import xml.etree.ElementTree as ET
from .common import (
ICONS_DICT,
ICONS_IMAGES,
ADDON_ROOT,
ADDON_PACKAGE,
INPUT_ANGLE_CONVERSION,
IMAGE_EXPORT_FORMAT,
Code_InputWidget,
Code_InputType,
Code_InputIdentifier
)
class SUBSTANCE_Utils():
# Preview Update FIX
@staticmethod
def toggle_redraw(context):
if context.scene.sbsar_redraw < 2:
context.scene.sbsar_redraw += 1
else:
context.scene.sbsar_redraw = 0
# IMAGE COLORSPACES
@staticmethod
def get_colorspaces():
_colorspaces = []
_items = bpy.types.Image.bl_rna.properties['colorspace_settings'].fixed_type.properties['name'].enum_items
for _item in _items:
_colorspaces.append((_item.identifier, _item.name, _item.description))
return _colorspaces
# JSON
@staticmethod
def get_json(filepath):
_json_obj = None
with open(filepath, encoding="utf8") as _json_file:
_json_obj = json.load(_json_file)
return _json_obj
@staticmethod
def set_json(filepath, obj):
with open(filepath, "w", encoding="utf8") as _json_file:
json.dump(obj, _json_file, ensure_ascii=False)
# Time
@staticmethod
def get_current_time_in_ms():
return int(round(time() * 1000))
# Icons
@staticmethod
def init_icons():
_icons_dir = os.path.join(ADDON_ROOT, "_icons").replace("\\", "/")
for _image in ICONS_IMAGES:
if _image["id"] not in ICONS_DICT:
ICONS_DICT.load(_image["id"], os.path.join(_icons_dir, _image["filename"]), 'IMAGE')
# Log
@staticmethod
def log_data(type, message, display=False):
if display:
try:
bpy.ops.substance.send_message(type=type, message="Substance 3D in Blender: "+message)
except Exception:
print("Substance 3D in Blender: {} - {}".format(type, message))
else:
print("Substance 3D in Blender: {} - {}".format(type, message))
@staticmethod
def log_traceback(message):
print("Substance 3D in Blender: ERROR - TRACEBACK:\n")
print(message)
# Geo
@staticmethod
def get_selected_geo(selected_objects):
_filtered = []
for _item in selected_objects:
if hasattr(_item.data, 'materials'):
_filtered.append(_item)
return _filtered
# Graph
@staticmethod
def get_selected_graph(context=bpy.context):
_selected_sbsar = context.scene.loaded_sbsars[context.scene.sbsar_index]
_selected_graph_idx = int(_selected_sbsar.graphs_list)
_selected_graph = _selected_sbsar.graphs[_selected_graph_idx]
return _selected_graph
# Shader
@staticmethod
def get_selected_shader(context=bpy.context, idx=-1):
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
_selected_preset_idx = idx
if _selected_preset_idx < 0:
_selected_preset_idx = int(_addon_prefs.shader_list)
_selected_shader_preset = _addon_prefs.shaders[_selected_preset_idx]
return _addon_prefs, "{}".format(_selected_preset_idx), _selected_shader_preset
@staticmethod
def get_shader_file(filename):
_custom_shaders_dir = os.path.join(ADDON_ROOT, "_presets/custom").replace('\\', '/')
_shaders_dir = os.path.join(ADDON_ROOT, "_presets/default").replace('\\', '/')
_path = os.path.join(_custom_shaders_dir, filename)
if not os.path.exists(_path):
_path = os.path.join(_shaders_dir, filename)
return _path
@staticmethod
def get_shader_prefs(context, shader):
_temp_inputs = getattr(context.scene, shader.inputs_class_name)
_temp_outputs = {}
for _output in shader.outputs:
_temp_outputs[_output.id] = _output.to_json()
return {
"inputs": _temp_inputs,
"outputs": _temp_outputs,
}
# SBSAR
@staticmethod
def get_unique_name(filename, context):
_unique_name = filename.replace(".sbsar", "")
_temp_name = _unique_name
_counter = 0
while _temp_name in context.scene.loaded_sbsars:
_counter += 1
_temp_name = _unique_name + "_{}".format(_counter)
if _counter:
return _unique_name + "_{}".format(_counter)
return _unique_name
# SBSAR INPUTS
@staticmethod
def inputs_empty(inputs):
for _input in inputs:
if _input.guiWidget != Code_InputWidget.nowidget.value or _input.type == Code_InputType.string.name:
return False
return True
@staticmethod
def value_fix_type(identifier, widget, type, new_value):
if widget == Code_InputWidget.combobox.value:
return int(new_value)
elif widget == Code_InputWidget.slider.value:
if type == Code_InputType.integer.name:
return int(new_value)
elif type == Code_InputType.float.name:
return float(new_value)
elif (type == Code_InputType.integer2.name or
type == Code_InputType.integer3.name or
type == Code_InputType.integer4.name):
return list(new_value)
elif (type == Code_InputType.float2.name or
type == Code_InputType.float3.name or
type == Code_InputType.float4.name):
return list(new_value)
else:
return 0
elif widget == Code_InputWidget.color.value:
if type == Code_InputType.float.name:
return float(new_value)
elif type == Code_InputType.float3.name or type == Code_InputType.float4.name:
return list(new_value)
else:
return 0
elif widget == Code_InputWidget.togglebutton.value:
return int(new_value)
elif widget == Code_InputWidget.angle.value:
return float(new_value) / INPUT_ANGLE_CONVERSION
elif widget == Code_InputWidget.position.value:
return list(new_value)
elif widget == Code_InputWidget.image.value:
if isinstance(new_value, bpy.types.Image):
return new_value.name
else:
return ""
elif widget == Code_InputWidget.nowidget.value:
if identifier == Code_InputIdentifier.outputsize.value:
return list(new_value)
elif identifier == Code_InputIdentifier.randomseed.value:
return int(new_value)
elif type == Code_InputType.string.name:
return str(new_value)
else:
return 0
else:
return 0
# Render
@staticmethod
def render_image_input(img, context):
if not context:
context = bpy.context
_addon_prefs = context.preferences.addons[ADDON_PACKAGE].preferences
_default_path = _addon_prefs.path_default
_format_idx = int(_addon_prefs.default_export_format)
_file_extension = IMAGE_EXPORT_FORMAT[_format_idx][2].replace("*", "")
img.file_format = IMAGE_EXPORT_FORMAT[_format_idx][1]
_image_filepath = os.path.join(_default_path, img.name + _file_extension).replace("\\", "/")
img.save_render(_image_filepath)
return _image_filepath
# Physical Size
@staticmethod
def get_physical_size(physical_size, context):
_scale = context.scene.unit_settings.scale_length
_new_physical_size = [
physical_size[0] * _scale,
physical_size[1] * _scale,
physical_size[2] * _scale
]
return _new_physical_size
# Output Size
@staticmethod
def update_preset_outputsize(preset_value, input, type, value):
_preset_xml = ET.fromstring(preset_value)
_input_item = None
for _preset_input in _preset_xml:
if _preset_input.attrib["uid"] == str(input.id):
_input_item = _preset_input
if _input_item is not None:
if type == Code_InputType.integer.value:
_input_item.attrib["value"] = "{}".format(value)
elif type == Code_InputType.integer2.value:
_input_item.attrib["value"] = "{},{}".format(value[0], value[1])
else:
_attrib = {
"identifier": input.identifier,
"uid": "{}".format(input.id),
"type": "{}".format(type)
}
if type == Code_InputType.integer.value:
_attrib["value"] = "{}".format(value)
elif type == Code_InputType.integer2.value:
_attrib["value"] = "{},{}".format(value[0], value[1])
_el = ET.SubElement(_preset_xml, "presetinput", attrib=_attrib)
_el.tail = "\n"
_new_preset_value = ET.tostring(_preset_xml, encoding='unicode')
return _new_preset_value