Skip to content

Commit

Permalink
Merge pull request #65 from WolvenKit/Blender4Compat
Browse files Browse the repository at this point in the history
Blender 4 Compatability changes
  • Loading branch information
Simarilius-uk authored Nov 13, 2023
2 parents 13555c9 + 88de5b3 commit 48ac4ad
Show file tree
Hide file tree
Showing 30 changed files with 2,136 additions and 106 deletions.
145 changes: 142 additions & 3 deletions i_scene_cp77_gltf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,145 @@ def draw(self, context):
col.prop(self, "show_meshtools")
col.prop(self, "show_collisiontools")
col.prop(self, "show_animtools")


class CP77ScriptManager(bpy.types.Panel):
bl_label = "Script Manager"
bl_idname = "CP77_PT_ScriptManagerPanel"
bl_space_type = 'TEXT_EDITOR'
bl_region_type = 'UI'
bl_category = "CP77 Modding"

def draw(self, context):
layout = self.layout
box = layout.box()
col = box.column()
# Get the path to the "scripts" folder in the add-on's root directory
script_dir = os.path.join(os.path.dirname(__file__), "scripts")

# List available scripts
script_files = [f for f in os.listdir(script_dir) if f.endswith(".py")]


for script_file in script_files:
row = col.row(align=True)
row.operator("script_manager.save_script", text="", icon="APPEND_BLEND").script_file = script_file
row.operator("script_manager.load_script", text=script_file).script_file = script_file
row.operator("script_manager.delete_script", text="", icon="X").script_file = script_file

row = box.row(align=True)
row.operator("script_manager.create_script")


class CP77CreateScript(bpy.types.Operator):
bl_idname = "script_manager.create_script"
bl_label = "Create New Script"
bl_description = "create a new script in the cp77 modding scripts directory"

def execute(self, context):
script_dir = os.path.join(os.path.dirname(__file__), "scripts")
base_name = "new_script"
script_name = base_name + ".py"

# Check if a script with the default name already exists
i = 1
while os.path.exists(os.path.join(script_dir, script_name)):
script_name = f"{base_name}_{i}.py"
i += 1

script_path = os.path.join(script_dir, script_name)

with open(script_path, 'w') as f:
f.write("# New Script")

return {'FINISHED'}


class CP77LoadScript(bpy.types.Operator):
bl_idname = "script_manager.load_script"
bl_label = "Load Script"
bl_description = "Click to load or switch to this script, ctrl+click to rename"

script_file: bpy.props.StringProperty()
new_name: bpy.props.StringProperty(name="New name", default=".py")

def execute(self, context):
script_name = self.script_file

if self.new_name:
# Rename the script
script_path = os.path.join(os.path.dirname(__file__), "scripts", script_name)
new_script_path = os.path.join(os.path.dirname(__file__), "scripts", self.new_name)

if os.path.exists(script_path):
if not os.path.exists(new_script_path):
os.rename(script_path, new_script_path)
self.report({'INFO'}, f"Renamed '{script_name}' to '{self.new_name}'")
else:
self.report({'ERROR'}, f"A script with the name '{self.new_name}' already exists.")
else:
# Check if the script is already loaded
script_text = bpy.data.texts.get(script_name)
# Switch to the loaded script if present
if script_text is not None:
context.space_data.text = script_text
else:
# If the script is not loaded, load it
script_path = os.path.join(os.path.dirname(__file__), "scripts", script_name)

if os.path.exists(script_path):
with open(script_path, 'r') as f:
text_data = bpy.data.texts.new(name=script_name)
text_data.from_string(f.read())
# Set the loaded script as active
context.space_data.text = text_data

return {'FINISHED'}

def invoke(self, context, event):
if event.ctrl:
# Ctrl+Click to rename
return context.window_manager.invoke_props_dialog(self)
else:
self.new_name = ""
return self.execute(context)

def draw(self, context):
layout = self.layout
layout.prop(self, "new_name")


class CP77SaveScript(bpy.types.Operator):
bl_idname = "script_manager.save_script"
bl_label = "Save Script"
bl_description = "Press to save this script"

script_file: bpy.props.StringProperty()

def execute(self, context):
script_text = context.space_data.text
if script_text:
script_path = os.path.join(os.path.dirname(__file__), "scripts", self.script_file)
with open(script_path, 'w') as f:
f.write(script_text.as_string())

return {'FINISHED'}


class CP77DeleteScript(bpy.types.Operator):
bl_idname = "script_manager.delete_script"
bl_label = "Delete Script"
bl_description = "Press to delete this script"

script_file: bpy.props.StringProperty()

def execute(self, context):
script_path = os.path.join(os.path.dirname(__file__), "scripts", self.script_file)

if os.path.exists(script_path):
os.remove(script_path)

return {'FINISHED'}


def SetCyclesRenderer(use_cycles=True, set_gi_params=False):
Expand Down Expand Up @@ -532,9 +671,9 @@ def draw(self, context):
row = box.row(align=True)
row.prop(active_action, 'frame_start', text="")
row.prop(active_action, 'frame_end', text="")
else:
row.separator()
row.operator('reset_armature.cp77')

row.separator()
row.operator('reset_armature.cp77')

box = layout.box()
row = box.row(align=True)
Expand Down
10 changes: 6 additions & 4 deletions i_scene_cp77_gltf/importers/entity_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,11 +252,13 @@ def importEnt( filepath='', appearances=[], exclude_meshes=[], with_materials=Tr
# print(c['mesh']['DepotPath']['$value'])
meshname=''
if 'mesh' in c.keys() and isinstance( c['mesh']['DepotPath']['$value'], str):
meshname=os.path.basename(c['mesh']['DepotPath']['$value'])
meshpath=os.path.join(path, c['mesh']['DepotPath']['$value'][:-4]+'glb')
m=c['mesh']['DepotPath']['$value']
meshname=os.path.basename(m)
meshpath=os.path.join(path, m[:-1*len(os.path.splitext(m)[1])]+'.glb')
elif 'graphicsMesh' in c.keys() and isinstance( c['graphicsMesh']['DepotPath']['$value'], str):
meshname=os.path.basename(c['graphicsMesh']['DepotPath']['$value'])
meshpath=os.path.join(path, c['graphicsMesh']['DepotPath']['$value'][:-4]+'glb')
m=c['graphicsMesh']['DepotPath']['$value']
meshname=os.path.basename(m)
meshpath=os.path.join(path, m[:-1*len(os.path.splitext(m)[1])]+'.glb')
if meshname:
if meshname not in exclude_meshes:
if os.path.exists(meshpath):
Expand Down
17 changes: 14 additions & 3 deletions i_scene_cp77_gltf/importers/import_with_materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@
from io_scene_gltf2.blender.imp.gltf2_blender_gltf import BlenderGlTF
from ..main.setup import MaterialBuilder
from ..main.common import json_ver_validate
from ..main.common import UV_by_bounds
from .attribute_import import manage_garment_support

def objs_in_col(top_coll, objtype):
return sum([len([o for o in col.objects if o.type==objtype]) for col in top_coll.children_recursive])+len([o for o in top_coll.objects if o.type==objtype])

def CP77GLBimport(self, exclude_unused_mats=True, image_format='png', with_materials=True, filepath='', hide_armatures=True, update_gi=True, import_garmentsupport=False, files=[], directory='', appearances=[]):

context=bpy.context
Expand Down Expand Up @@ -42,6 +46,8 @@ def CP77GLBimport(self, exclude_unused_mats=True, image_format='png', with_mater
existingMaterials = bpy.data.materials.keys()
BlenderGlTF.create(gltf_importer)
imported= context.selected_objects #the new stuff should be selected
if f['name'][:7]=='terrain':
UV_by_bounds(imported)
collection = bpy.data.collections.new(os.path.splitext(f['name'])[0])
bpy.context.scene.collection.children.link(collection)
for o in imported:
Expand All @@ -52,6 +58,9 @@ def CP77GLBimport(self, exclude_unused_mats=True, image_format='png', with_mater
if 'Armature' in o.name:
o.hide_set(hide_armatures)
collection['orig_filepath']=filepath
collection['numMeshChildren']=objs_in_col(collection, 'MESH')
collection['numArmatureChildren']=objs_in_col(collection, 'ARMATURE')

for name in bpy.data.materials.keys():
if name not in existingMaterials:
bpy.data.materials.remove(bpy.data.materials[name], do_unlink=True, do_id_user=True, do_ui_user=True)
Expand Down Expand Up @@ -124,7 +133,9 @@ def CP77GLBimport(self, exclude_unused_mats=True, image_format='png', with_mater
#print('matname: ',matname, validmats[matname])
m=validmats[matname]
# Should create a list of mis that dont play nice with this and just check if the mat is using one.
if matname in bpy_mats.keys() and 'glass' not in matname and 'MaterialTemplate' not in matname and matname[:5]!='Atlas' and 'BaseMaterial' in bpy_mats[matname].keys() and bpy_mats[matname]['BaseMaterial']==m['BaseMaterial'] and bpy_mats[matname]['GlobalNormal']==m['GlobalNormal'] and bpy_mats[matname]['MultilayerMask']==m['MultilayerMask'] :

if matname in bpy_mats.keys() and 'glass' not in matname and 'MaterialTemplate' not in matname and 'Window' not in matname and matname[:5]!='Atlas' and 'BaseMaterial' in bpy_mats[matname].keys() and bpy_mats[matname]['BaseMaterial']==m['BaseMaterial'] and bpy_mats[matname]['GlobalNormal']==m['GlobalNormal'] and bpy_mats[matname]['MultilayerMask']==m['MultilayerMask'] :

bpy.data.meshes[name].materials.append(bpy_mats[matname])
elif matname in bpy_mats.keys() and matname[:5]=='Atlas' and bpy_mats[matname]['BaseMaterial']==m['BaseMaterial'] and bpy_mats[matname]['DiffuseMap']==m['DiffuseMap'] :
bpy.data.meshes[name].materials.append(bpy_mats[matname])
Expand All @@ -143,9 +154,9 @@ def CP77GLBimport(self, exclude_unused_mats=True, image_format='png', with_mater
bpy.data.meshes[name].materials.append(bpymat)
if 'no_shadows' in bpymat.keys() and bpymat['no_shadows']:
bpy.data.objects[name].visible_shadow=False
except FileNotFoundError as fnfe:
except:
#Kwek -- finally, even if the Builder couldn't find the materials, keep calm and carry on
#print(str(fnfe))
print(traceback.print_exc())
pass
index = index + 1
else:
Expand Down
7 changes: 5 additions & 2 deletions i_scene_cp77_gltf/importers/sector_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,12 @@ def importSectors( filepath='', want_collisions=False, am_modding=False, with_ma
print(len(apps))
impapps=','.join(apps)
#print(os.path.join(path, m[:-4]+'glb'),impapps)
meshpath=os.path.join(path, m[:-4]+'glb')

meshpath=os.path.join(path, m[:-1*len(os.path.splitext(m)[1])]+'.glb')
groupname = os.path.splitext(os.path.split(meshpath)[-1])[0]
while len(groupname) > 63:
groupname = groupname[:-1]
if groupname not in Masters.children.keys():
if groupname not in Masters.children.keys() and os.path.exists(meshpath):
try:
bpy.ops.io_scene_gltf.cp77(filepath=meshpath, appearances=impapps, update_gi=False, with_materials=with_materials)
objs = C.selected_objects
Expand All @@ -259,6 +260,8 @@ def importSectors( filepath='', want_collisions=False, am_modding=False, with_ma
coll_scene.children.unlink(move_coll)
except:
print('failed on ',os.path.basename(meshpath))
elif not os.path.exists(meshpath):
print('Mesh ', meshpath, ' does not exist')
empty=[]
for child in Masters.children:
if len(child.objects)<1:
Expand Down
4 changes: 2 additions & 2 deletions i_scene_cp77_gltf/main/bartmoss_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ def rotate_quat_180(self,context):

else:
return{'FINISHED'}
J!ELd1!@#



Loading

0 comments on commit 48ac4ad

Please sign in to comment.