def execute(self, context): for i, fact in enumerate(GetPreferences().FactoryRefs): if fact.name == context.current_factory.name: GetPreferences().FactoryRefs.remove(i) break return {'FINISHED'}
def execute(self, context): for i, mat in enumerate(GetPreferences().MaterialRefs): if mat.name == context.current_material.name: GetPreferences().MaterialRefs.remove(i) break return {'FINISHED'}
def execute(self, context): prefs = GetPreferences() script = prefs.postExportScripts.add() script.name = "Unnamed_" + str(len(prefs.postExportScripts)) prefs.active_postExportScripts_index = len(prefs.postExportScripts) - 1 return {'FINISHED'}
def execute(self, context): prefs = GetPreferences() if prefs.active_postExportScripts_index >= 0: prefs.postExportScripts.remove( prefs.active_postExportScripts_index) prefs.active_postExportScripts_index = len( prefs.postExportScripts) - 1 return {'FINISHED'}
def execute(self, context): ob = context.scene.objects.active if int(self.select_factory) != -1: ob.b2cs.csFactoryName = GetPreferences().FactoryRefs[int( self.select_factory)].name ob.b2cs.csFactoryVfs = GetPreferences().FactoryRefs[int( self.select_factory)].vfs else: ob.b2cs.csFactoryName = '' ob.b2cs.csFactoryVfs = '' return {'FINISHED'}
def execute(self, context): mat = context.material if int(self.select_material) != -1: mat.b2cs.csMaterialName = GetPreferences().MaterialRefs[int( self.select_material)].name mat.b2cs.csMaterialVfs = GetPreferences().MaterialRefs[int( self.select_material)].vfs else: mat.b2cs.csMaterialName = 'None' mat.b2cs.csMaterialVfs = '' return {'FINISHED'}
def Export(path): # Clean cached data Hierarchy.exportedFactories = [] # Set interaction mode to 'OBJECT' mode editMode = False for ob in bpy.data.objects: if ob.mode == 'EDIT': if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') editMode = True break # Export Blender data to Crystal Space format exportAsLibrary = GetPreferences().library if exportAsLibrary: print("\nEXPORTING: " + Join(path, 'library') + " ====================================") print( " All objects of the world are exported as factories in 'library' file.\n" ) ExportLibrary(path) else: print("\nEXPORTING: " + Join(path, 'world') + " ====================================") print( " All scenes composing this world are exported as sectors in the 'world' file ;\n", " all objects of these scenes are exported as separated libraries.\n" ) ExportWorld(path) # Restore interaction mode if editMode: if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='EDIT') # Launch post export scripts import shlex import subprocess for script in GetPreferences().postExportScripts: if script.valid and script.enabled: exportPath = GetExportPath() args = shlex.split(script.abspath + ' ' + exportPath) print(args) output = subprocess.call(args) print(output)
def execute(self, context): prefs = GetPreferences() print(self.type) print(prefs.active_postExportScripts_index) direction = 1 if self.type == 'DOWN' else -1 if prefs.active_postExportScripts_index >= 0: newpos = prefs.active_postExportScripts_index + direction if newpos < len(prefs.postExportScripts) and newpos > -1: prefs.postExportScripts.move( prefs.active_postExportScripts_index, newpos) prefs.active_postExportScripts_index = newpos return {'FINISHED'}
def WorldAsCS(self, func, depth=0): """ Write an xml decription of this world: mainly physics settings """ scenes = [bpy.context.scene ] if GetPreferences().exportOnlyCurrentScene else [ scene for scene in bpy.data.scenes if scene.b2cs.export ] engine = None for scene in scenes: print('ENGINE: ' + scene.game_settings.physics_engine) if scene.game_settings.physics_engine == 'BULLET': engine = 'crystalspace.physics.bullet' break if engine: func(' ' * depth + '<addon plugin="crystalspace.physics.loader">') func(' ' * depth + ' <collisionsystem plugin="%s">' % (engine)) func(' ' * depth + ' <simulationspeed speed="1.0" />') # TODO func( ' ' * depth + ' <stepparams timestep="0.0166" maxstep="1" iterations="10" />') #TODO func(' ' * depth + ' <internalscale scale="1.0" />') # TODO func(' ' * depth + ' <softbodyenabled enabled="true" />') # TODO func(' ' * depth + ' <damping linear="0.1" angular="0.1" />') # TODO func(' ' * depth + ' </collisionsystem>') func(' ' * depth + '</addon>')
def GetExportableScenes(context): scenes = [bpy.context.scene] if GetPreferences().exportOnlyCurrentScene else [ scene for scene in bpy.data.scenes if scene.b2cs.export] if len(scenes) == 0: # If no scenes are exported, atleast export the current scene, for # those schmucks that disable the export of the only scene. scenes = [bpy.context.scene] return scenes
def execute(self, context): exportPath = GetExportPath() Export(exportPath) options = " " if GetPreferences().console: options += "-console " if GetPreferences().verbose: options += "-verbose=-scf " if GetPreferences().silent: options += "-silent " if GetPreferences().bugplug: options += "-plugin=bugplug " # import commands # output = commands.getstatusoutput(WalkTestPath() + options + path) # print(output) import shlex import subprocess physics = False for object in bpy.data.objects: if object.hasSupportedPhysicsEnabled(): physics = True break if not physics or not context.scene.HasBulletPhysicsEnabled(): print(WalkTestPath()) args = shlex.split(WalkTestPath() + options + exportPath) print(args) output = subprocess.call(args) print(output) else: exe = WalkTestPath().replace('walktest', 'phystut2') args = shlex.split(exe + options + '--mapfile=' + exportPath + 'world') print(args) output = subprocess.call(args) print(output) return {'FINISHED'}
def INFO_HT_header_prepend_draw(self, context): if context.scene.render.engine == 'CRYSTALSPACE': layout = self.layout layout.operator("io_scene_cs.export", text="", icon='SCENE_DATA') if not GetPreferences().library: if HasCrystalSpace(): layout.operator("io_scene_cs.export_run", text="", icon='GAME') if context.active_object and context.active_object.type == 'MESH': layout.operator("io_scene_cs.export_view", text="", icon='RENDER_STILL') layout.separator()
def draw(self, context): layout = self.layout ob = bpy.context.scene split = layout.split() col1 = split.column(align=True) box1 = col1.box() row = box1.row() row.prop(ob.b2cs, "export") if GetPreferences().exportOnlyCurrentScene: row = box1.row() row.label( text="exportOnlyCurrentScene enabled so this won't have any effect.")
def draw(self, context): ob = context.active_object if ob.type == 'MESH': # Draw a checkbox to define current mesh object as a CS factory # reference layout = self.layout row = layout.row() row.prop(ob.b2cs, "type") layout.template_object_ref(ob.b2cs, 'viscull_mesh', name='Viscull mesh') # if ob.game.use_collision_bounds and ob.game.collision_bounds_type=='TRIANGLE_MESH': # layout.template_object_ref(ob.b2cs, 'collission_mesh', # name='Collision mesh') if not ob.data.b2cs.no_shadow_cast: layout.template_object_ref(ob.b2cs, 'shadow_mesh', name='Shadow mesh') row = layout.row() row.prop(ob.b2cs, "csFactRef") if ob.b2cs.csFactRef: # Let the user select a CS factory row = layout.row() if ob.b2cs.csFactoryName == '': row.operator_menu_enum("object.select_fact_ref", "select_factory", text=SelectFactoryRef.bl_label) else: row.operator_menu_enum("object.select_fact_ref", "select_factory", text=ob.b2cs.csFactoryName) # Verify that factory reference still exists factories = [f.name for f in GetPreferences().FactoryRefs] if not ob.b2cs.csFactoryName in factories: row = layout.row() row.label( text= "WARNING: this factory reference has been deleted!", icon='ERROR')
def draw(self, context): layout = self.layout row = layout.row(align=True) row.operator("io_scene_cs.add_factory", text="Add factory reference") for fact in GetPreferences().FactoryRefs: col = layout.column() col.context_pointer_set("current_factory", fact) box = col.box() row = box.row() row.prop(fact, "name", text="Factory name") row.operator( "io_scene_cs.rmv_factory", text="", icon='X', emboss=False) row = box.row() row.prop(fact, "vfs", text="VFS path")
def draw(self, context): layout = self.layout row = layout.row(align=True) row.operator("io_scene_cs.add_material", text="Add material reference") for mat in GetPreferences().MaterialRefs: col = layout.column() col.context_pointer_set("current_material", mat) box = col.box() row = box.row() row.prop(mat, "name", text="Material name") row.operator( "io_scene_cs.rmv_material", text="", icon='X', emboss=False) row = box.row() row.prop(mat, "vfs", text="VFS path")
def GroupAsCSLib(self, path=''): """ Export a group of Blender objects as a CS library entitled '<group name>' in the '<path>/factories' folder; objects are exported as instances or submeshes of a general mesh """ def Write(fi): def write(data): fi.write(data + '\n') return write # Export group fa = open(Join(path, 'factories/', self.uname), 'w') self.WriteCSLibHeader(Write(fa)) use_imposter = self.HasImposter() if not GetPreferences().sharedMaterial: groupDeps = self.GetDependencies() ExportMaterials(Write(fa), 2, groupDeps) self.WriteCSGroup(Write(fa), 2, use_imposter, dontClose=False) fa.close()
def draw(self, context): layout = self.layout row = layout.row(align=True) row.template_list( "UI_UL_list", "scripts", GetPreferences(), "postExportScripts", GetPreferences(), "active_postExportScripts_index", rows=5, maxrows=5, type='DEFAULT') sub = row.column(align=True) sub.operator( "preferences.post_export_script_add", icon='ZOOMIN', text="") sub.operator( "preferences.post_export_script_remove", icon='ZOOMOUT', text="") sub.operator("preferences.post_export_script_move", text="", icon='TRIA_UP').type = 'UP' sub.operator("preferences.post_export_script_move", text="", icon='TRIA_DOWN').type = 'DOWN' if len(GetPreferences().postExportScripts) > GetPreferences().active_postExportScripts_index >= 0: slave = GetPreferences().postExportScripts[ GetPreferences().active_postExportScripts_index] row = layout.row(align=True) box = row.box() row = box.row() row.label('Name: ' + slave.name) row = box.row() if not slave.valid: row.alert = True row.prop(slave, 'path') row = box.row() row.prop(slave, 'enabled') if not slave.valid: row = box.row() row.label('Script file does not exist or is not executable!') row = layout.row(align=True) row.label( 'Scripts are executed with the first argument the set export directory path.')
def GetBoneInfluences(self, **kwargs): """ Generate a list of bone influences (4 per vertex) for each vertex of the mesh animated by this armature. param kwargs: mapping buffers of this armature """ # Recover mapping buffers from kwargs meshData = kwargs.get('meshData', []) mappingVertices = kwargs.get('mappingVertices', []) # Get bone influences per vertex (max 4) boneNames = GetBoneNames(self.bones) epsilon = 1e-8 influences = [] lostInfluences = False undefinedGroups = False lostGroups = [] for index, ob in enumerate(meshData): # For each mesh depending of the armature for indexV in mappingVertices[index]: # For each vertex of the mesh weights = [] for groupEl in ob.data.vertices[indexV].groups: # For each vertex group if groupEl.weight > epsilon: # Get the bone and its influence (weight) on the vertex groupIndex = find(lambda gr: gr.index == groupEl.group, ob.vertex_groups) if groupIndex == None: undefinedGroups = True continue group = ob.vertex_groups[groupIndex] if group.name not in boneNames: if group.name not in lostGroups: lostGroups.append(group.name) continue boneIndex = boneNames[group.name] weights.append([boneIndex, groupEl.weight]) # TODO: treat all armatures, not only the root one # Sort bone influences of the vertex by descending order weights.sort(key=lambda el: el[1], reverse=True) # Add the 4 largest influences of the vertex countBones = 0 sumWeights = 0 for influence in weights: if countBones < 4: countBones += 1 sumWeights += influence[1] else: lostInfluences = True break # Normalize the bone influences to 1 vertexInfluence = [] for i in range(countBones): if sumWeights > epsilon: weights[i][1] = weights[i][1] / sumWeights vertexInfluence.append(weights[i]) # Fill vertex influences with null values if less then 4 non null # influences have been found for this vertex if countBones < 4: for i in range(4 - countBones): vertexInfluence.append([0, 0.0]) # Add bone influences to the list for i in range(4): influences.append(vertexInfluence[i]) if GetPreferences( ).enableDoublesided and ob.data.show_double_sided: # Duplicate the influences in case of a double sided mesh for i in range(4): influences.append(vertexInfluence[i]) if undefinedGroups: print( "ERROR: undefined vertex group index; corresponding bone influences have been lost!" ) if len(lostGroups): print( "WARNING: vertex groups defined on unknown bones; corresponding bone influences have been lost!", lostGroups) if lostInfluences: print("WARNING: some bone influences have been lost (max=4/vertex)") return influences
def GetSubMeshesRaw(self, name, indexV, indexGroups, mappingBuffer=[]): """ Compute the CS submeshes of this Blender mesh by remapping Blender vertices to CS vertices, triangulating the faces and duplicating the double sided faces param name: name of the mesh param indexV: starting index of the CS vertices param indexGroups: buffer defining for each submesh (identified by the mesh name, the material and the texture) its CS faces, composed by three vertices param mappingBuffer: mapping buffer defining a CS vertex for each face vertex of the Blender mesh """ # Starting index of the cs vertices composing this submesh firstIndex = indexV # Active UV texture tface = self.all_uv_textures.active.data if self.all_uv_textures.active else None # For each face composing this mesh for index, face in enumerate(self.all_faces): im = tface[index].image if tface else None # Identify the submesh by the mesh name, material and texture triplet = (name, self.GetMaterial(face.material_index), im) if triplet not in indexGroups: indexGroups[triplet] = [] # Triangulate the mesh face indices = [v for v in face.vertices] tt = [2, 1, 0] if len(indices) == 3 else [2, 1, 0, 3, 2, 0] if len(mappingBuffer) == 0: # No mapping buffer => directly copy the index of Blender vertices for i in tt: indexGroups[triplet].append(face.vertices[i]) indexV += 1 else: # Mapping buffer => use the corresponding cs index of these # vertices if not GetPreferences( ).enableDoublesided or not self.show_double_sided: # Single sided mesh for i in tt: # Add vertices composing the triangle to submesh for mapV in mappingBuffer[face.vertices[i]]: if mapV['face'] == index and mapV['vertex'] == i: # cs index = firstIndex + j # (where j is the index of this vertex in the submesh) indexGroups[triplet].append(firstIndex + mapV['csVertex']) indexV += 1 break else: # Double sided mesh # Search for CS indices of the vertices composing the face frontFaceIndices = [] tt = [0, 1, 2] if len(indices) == 3 else [0, 1, 2, 3] for i in tt: for mapV in mappingBuffer[face.vertices[i]]: if mapV['face'] == index and mapV['vertex'] == i: # front face: cs index = firstIndex + 2*j # back face: cs index = firstIndex + 2*j + 1 # (where j is the cs index of the vertex for a single sided face) frontFaceIndices.append(firstIndex + 2 * mapV['csVertex']) break # Add vertices composing the triangle for j in [2, 1, 0]: # front side of the mesh indexGroups[triplet].append(frontFaceIndices[j]) indexV += 1 for j in [0, 1, 2]: # back side of the mesh indexGroups[triplet].append(frontFaceIndices[j] + 1) indexV += 1 # The face is not a triangle => triangulation if len(indices) != 3: # Add vertices composing the second triangle for j in [3, 2, 0]: # front side of the mesh indexGroups[triplet].append(frontFaceIndices[j]) indexV += 1 for j in [3, 0, 2]: # back side of the mesh indexGroups[triplet].append(frontFaceIndices[j] + 1) indexV += 1 return indexV, indexGroups
def draw(self, context): layout = self.layout mat = context.material if mat: #------------------------------------------------------------------ textures = {} for i, slot in enumerate(mat.texture_slots): if slot: for p in PROPS: if getattr(slot, p): if slot.texture.type == 'IMAGE': textures[p] = (i, slot.texture) box = layout.box() row = box.row() row.label("Textures") row.menu('MATERIAL_OT_textures_menu', text="", icon='DOWNARROW_HLT') for p in PROPS: i, tex = textures.get(p, (None, None)) if tex: row = box.row() col1 = row.column(align=True) col1.label('', icon_value=layout.icon(tex)) col2 = row.column(align=True).row() # col2.alignment = 'RIGHT' c = col2.column(align=True) c.prop(tex, 'image', text=NAMES[p]) c = col2.column(align=True) op = c.operator('material.texture_remove', text="", icon='ZOOMOUT') op.index = i #------------------------------------------------------------------ box = layout.box() row = box.row() for prop in ['diffuse_color', 'specular_color']: row = box.row() col1 = row.column(align=True) col1.label(prop) col2 = row.column(align=True).row() col2.prop(mat, prop, text='') #------------------------------------------------------------------ box = layout.box() row = box.row() row.label("Custom shader variables") row.menu('MATERIAL_OT_shadervars_menu', text="", icon='DOWNARROW_HLT') for sv in mat.b2cs.shadervars: row = box.row() col1 = row.column(align=True) col1.prop(sv, 'name', text='') col2 = row.column(align=True).row() if sv.type == 'texture': if sv.value: col2.label('', icon_value=layout.icon(sv.value)) draw_idref(col2, sv, 'value') else: col2.prop(sv, 'value', text='') i = list(getattr(mat.b2cs.shadervars, sv.__type__)).index(sv) op = col2.operator('material.shadervar_remove', text="", icon='ZOOMOUT') op.index = i op.type = sv.__type__ #------------------------------------------------------------------ layout = self.layout row = layout.row() row.prop(mat.b2cs, "priority") row = layout.row() row.prop(mat.b2cs, "zbuf_mode") # Draw a checkbox to define current material as a CS material # reference layout.separator() row = layout.row() row.prop(mat.b2cs, "csMatRef") if mat.b2cs.csMatRef: # Let the user select a CS material row = layout.row() if mat.b2cs.csMaterialName == 'None': row.operator_menu_enum("material.select_mat_ref", "select_material", text=SelectMaterialRef.bl_label) else: row.operator_menu_enum("material.select_mat_ref", "select_material", text=mat.b2cs.csMaterialName) # Verify that factory reference still exists materials = [m.name for m in GetPreferences().MaterialRefs] if not mat.b2cs.csMaterialName in materials: row = layout.row() row.label( text= "WARNING: this material reference has been deleted!", icon='ERROR') else: # CS material properties (used if this material is not replaced by # a reference to an existing CS material) layout.separator() row = layout.row() row.prop(mat.b2cs, "shaderset") name = GetShaderSetName(mat.b2cs.shaderset) if name == 'water_plane': row = layout.row() row.prop(mat.water, "water_fog_color") row = layout.row() row.prop(mat.water, "water_perturb_scale") row = layout.row() row.prop(mat.water, "water_fog_density")
def GetMorphTargets(numVertices, **kwargs): """ Generate a list of MorphTarget objects for the meshes passed in kwargs """ # Recover buffers from kwargs meshData = kwargs.get('meshData', []) mappingVertices = [] if 'mappingVertices' in kwargs: mappingVertices = kwargs['mappingVertices'] else: print("ERROR: GetMorphTargets - mapping buffers are not defined") scales = kwargs.get('scales', []) # Generate an offset buffer for each morph target defined # on the mesh object epsilon = 1e-8 shapes = [] morphTargets = [] startIndex = 0 # For each mesh composing the object for index, ob in enumerate(meshData): if ob.data.shape_keys: mtCount = 0 scale = scales[index] # Get the original coordinates of mesh vertices originalCo = [tuple(v.co) for v in ob.data.vertices] # For each morph target defined on this mesh for j, block in enumerate(ob.data.shape_keys.key_blocks): # Skip the 'Basis' morph target which corresponds to the reference pose # (i.e. the 'rest' pose) if j == 0 and block.name == "Basis": continue # Create an offset buffer for the new morph target if block.name not in shapes: shapes.append(block.name) # Get the blended coordinates of mesh vertices if ob.parent and ob.parent.type == 'ARMATURE' and ob.parent_type != 'BONE': blendedCo = [tuple(ob.relative_matrix * v.co) for v in block.data] else: blendedCo = [tuple(v.co) for v in block.data] nonNullOffset = False # Calculate the offset of each vertex offsets = [] for v in mappingVertices[index]: offset = [] for j in range(3): offset.append( scale[j] * (blendedCo[v][j] - originalCo[v][j])) if abs(offset[j]) > epsilon: nonNullOffset = True offsets.append(offset) # Duplicate vertex offset if the mesh is double sided # and 'double sided' option is enable if GetPreferences().enableDoublesided and ob.data.show_double_sided: offsets.append(offset) # Add the morph target to the list if it contains non null # offsets if nonNullOffset: mt = MorphTarget( block.name, offsets, numVertices, startIndex) morphTargets.append(mt) mtCount += 1 else: print( 'WARNING: morph target "%s" not exported (all offsets are null)' % (block.name)) if mtCount: print('INFO: %s morph target(s) exported for mesh "%s"' % (mtCount, ob.name[:-4])) startIndex += len(mappingVertices[index]) return morphTargets
def ExportWorld(path): """ Export scenes composing the world as sectors in the 'world' file, saved in the directory specified by 'path'. All objects of these scenes are exported as separated libraries in the 'factories' subfolder. """ # Create the export directory for textures if not os.path.exists(Join(path, 'textures/')): os.makedirs(Join(path, 'textures/')) # Create the export directory for factories if not os.path.exists(Join(path, 'factories/')): os.makedirs(Join(path, 'factories/')) scenes = bpy.data.exportable_scenes # Get data about all objects composing this world deps = util.EmptyDependencies() cameras = {} for scene in scenes: MergeDependencies(deps, scene.GetDependencies()) cameras.update(scene.GetCameras()) # Create a 'world' file containing the xml description of the scenes f = open(Join(path, 'world'), 'w') Write(f)('<?xml version="1.0" encoding="UTF-8"?>') Write(f)('<world xmlns=\"http://crystalspace3d.org/xml/library\">') if bpy.context.scene and bpy.context.scene.world: bpy.context.scene.world.AsCS(Write(f), 2) # Export shared materials and textures in world file if GetPreferences().sharedMaterial: fmt = open(Join(path, 'materials'), 'w') Write(fmt)('<?xml version="1.0" encoding="UTF-8"?>') Write(fmt)('<library xmlns=\"http://crystalspace3d.org/xml/library\">') ExportMaterials(Write(fmt), 2, deps) Write(fmt)('</library>') fmt.close() Write(f)(' ' * 2 + '<library>%s</library>' % ('materials')) # Export the objects composing the world for typ in deps: if typ == 'A': # Animated meshes for name, fact in deps[typ].items(): print('\nEXPORT OBJECT "%s" AS A CS ANIMATED MESH\n' % (fact.object.uname)) print('Writing fact', fact.uname, ':', Join(path, 'factories/', fact.object.uname)) fact.AsCSRef(Write(f), 2, 'factories/', animesh=True) # Export animesh factory fact.AsCSLib(path, animesh=True) elif typ == 'F': # General meshes for name, fact in deps[typ].items(): print('\nEXPORT OBJECT "%s" AS A CS %s\n' % (fact.object.uname, fact.object.b2cs.type)) print('Writing fact', fact.uname, ':', Join(path, 'factories/', fact.object.uname)) fact.AsCSRef(Write(f), 2, 'factories/', animesh=False) # Export genmesh factory if not fact.object.b2cs.csFactRef: fact.AsCSLib(path, animesh=False) elif typ == 'G': # Groups of objects for name, group in deps[typ].items(): print('\nEXPORT GROUP "%s" AS A CS GENERAL MESH\n' % (group.uname)) print('Writing group', Join(path, 'factories/', group.uname)) group.AsCSRef(Write(f), 2, 'factories/') # Export group of genmeshes group.AsCSLib(path) elif typ == 'M': # Materials for name, mat in deps[typ].items(): if mat.b2cs.csMatRef and mat.b2cs.csMaterialName != 'None' and mat.b2cs.csMaterialVfs != '': if mat.b2cs.csMaterialVfs not in Hierarchy.libraryReferences: # Export references to CS libraries defining materials Hierarchy.libraryReferences.append( mat.b2cs.csMaterialVfs) Write(f)(' ' * 2 + '<library>%s</library>' % (mat.b2cs.csMaterialVfs)) # Export cameras if cameras: ExportCameras(Write(f), 2, cameras) else: # Set a default camera if none is defined bpy.types.Object.CameraAsCS(None, Write(f), 2, bpy.context.scene) # Export scenes as CS sectors in the 'world' file print("\nEXPORT SCENES:") for scene in scenes: scene.AsCS(Write(f), 2) Write(f)('</world>') f.close() Hierarchy.exportedFactories = [] Hierarchy.libraryReferences = [] print( "\nEXPORTING complete ==================================================" )
def execute(self, context): new_fact = GetPreferences().FactoryRefs.add() return {'FINISHED'}
def WriteCSGroup(self, func, depth=0, use_imposter=False, dontClose=False): """ Write an xml description of the meshes composing this group: objects are exported as instances or submeshes of a general mesh """ # Get mapping buffers and submeshes for the objects composing the group meshData = [] subMeshess = [] mappingBuffers = [] mappingVertices = [] mappingNormals = [] indexV = 0 for m, ob in self.allObjects(): numCSVertices = 0 indexObject = find(lambda obCpy: obCpy.name[ :-4] == ob.name[:len(obCpy.name[:-4])], meshData) if indexObject == None: # Export group objects as instances of the general mesh if self.b2cs.groupedInstances: # Get a deep copy of the object obCpy = ob.GetTransformedCopy() # Export group objects as submeshes of the general mesh else: # Get the world transformation of this object matrix = ob.matrix_world if m: matrix = matrix * m # Get a deep copy of this object, transformed to its world # position obCpy = ob.GetTransformedCopy(matrix) # Tessellate the copied object obCpy.data.update_faces() meshData.append(obCpy) # Generate mapping buffers mapVert, mapBuf, norBuf = obCpy.data.GetCSMappingBuffers() numCSVertices = len(mapVert) if GetPreferences().enableDoublesided and obCpy.data.show_double_sided: numCSVertices = 2 * len(mapVert) # Generate submeshes subMeshess.append( obCpy.data.GetSubMeshes(obCpy.name, mapBuf, indexV)) mappingBuffers.append(mapBuf) mappingVertices.append(mapVert) mappingNormals.append(norBuf) indexV += numCSVertices warning = "(WARNING: double sided mesh implies duplication of its vertices)" \ if GetPreferences().enableDoublesided and obCpy.data.show_double_sided else "" print('number of CS vertices for mesh "%s" = %s %s' % (obCpy.name, numCSVertices, warning)) # Export the group of objects as a general mesh factory func(' ' * depth + '<meshfact name=\"%s\">' % (self.uname)) if self.b2cs.groupedInstances: # EXPORT OBJECTS AS INSTANCES OF THE GENERAL MESH print("The objects composing group '%s' are exported as instances of a general mesh" % (self.uname)) func(' ' * depth + ' <instances>') # Export first object of the group as a basic general mesh m, ob = self.allObjects()[0] func(' ' * depth + ' <meshfact name=\"%s-instance\">' % (self.uname)) func( ' ' * depth + ' <plugin>crystalspace.mesh.loader.factory.genmesh</plugin>') # if use_imposter: # func(' '*depth + ' <imposter range="10.0" tolerance="45.0" # camera_tolerance="45.0" shader="lighting_imposter"/>') mat = ob.GetDefaultMaterial() if mat != None and mat.b2cs.priority != 'object': func(' ' * depth + ' <priority>%s</priority>' % (mat.b2cs.priority)) if mat != None and mat.b2cs.zbuf_mode != 'zuse': func(' ' * depth + ' <%s/>' % (mat.b2cs.zbuf_mode)) if ob.data and ob.data.b2cs.no_shadow_receive: func(' ' * depth + ' <noshadowreceive />') if ob.data and ob.data.b2cs.no_shadow_cast: func(' ' * depth + ' <noshadowcast />') if ob.data and ob.data.b2cs.limited_shadow_cast: func(' ' * depth + ' <limitedshadowcast />') if ob.data.b2cs.lighter2_vertexlight: func( ' ' * depth + ' <key name="lighter2" editoronly="yes" vertexlight="yes" />') if ob.data.b2cs.lighter2_selfshadow: func( ' ' * depth + ' <key name="lighter2" editoronly="yes" noselfshadow="yes" />') if ob.data.b2cs.lighter2_lmscale > 0.0: func(' ' * depth + ' <key name="lighter2" editoronly="yes" lmscale="%f" />' % (ob.data.b2cs.lighter2_lmscale)) func(' ' * depth + ' <params>') # Export render buffers indexObject = find(lambda obCpy: obCpy.name[ :-4] == ob.name[:len(obCpy.name[:-4])], meshData) args = {} args['meshData'] = [meshData[indexObject]] args['mappingBuffers'] = [mappingBuffers[indexObject]] args['mappingVertices'] = [mappingVertices[indexObject]] args['mappingNormals'] = [mappingNormals[indexObject]] for buf in GetRenderBuffers(**args): buf.AsCS(func, depth + 8) # Export submeshes for sub in ob.data.GetSubMeshes(ob.name, mappingBuffers[indexObject]): sub.AsCS(func, depth + 8) func(' ' * depth + ' </params>') func(' ' * depth + ' </meshfact>') # Export objects of the group as instances of the basic general mesh min_corner = mathutils.Vector((0.0, 0.0, 0.0)) max_corner = mathutils.Vector((0.0, 0.0, 0.0)) for m, ob in self.allObjects(): # Define an instance of the general mesh func(' ' * depth + ' <instance>') matrix = ob.matrix_world if m: matrix = matrix * m MatrixAsCS(matrix, func, depth + 4, noMove=True) func(' ' * depth + ' </instance>') # Determine object's bounding box for corner in ob.bound_box: corner = matrix * mathutils.Vector(corner) for i in range(3): if corner[i] < min_corner[i]: min_corner[i] = corner[i] elif corner[i] > max_corner[i]: max_corner[i] = corner[i] func(' ' * depth + ' </instances>') # Export group's bounding box func(' ' * depth + ' <bbox>') func(' ' * depth + ' <v x="%s" y="%s" z="%s" />' % (min_corner[0], min_corner[2], min_corner[1])) func(' ' * depth + ' <v x="%s" y="%s" z="%s" />' % (max_corner[0], max_corner[2], max_corner[1])) func(' ' * depth + ' </bbox>') func(' ' * depth + '</meshfact>') else: # EXPORT OBJECTS AS SUBMESHES OF THE GENERAL MESH print("The objects composing group '%s' are exported as submeshes of a general mesh" % (self.uname)) func( ' ' * depth + ' <plugin>crystalspace.mesh.loader.factory.genmesh</plugin>') # if use_imposter: # func(' '*depth + ' <imposter range="10.0" tolerance="45.0" # camera_tolerance="45.0" shader="lighting_imposter"/>') for m, ob in self.allObjects(): mat = ob.GetDefaultMaterial(notifications=False) if mat != None and mat.b2cs.priority != 'object': func(' ' * depth + ' <priority>%s</priority>' % (mat.b2cs.priority)) if mat != None and mat.b2cs.zbuf_mode != 'zuse': func(' ' * depth + ' <%s/>' % (mat.b2cs.zbuf_mode)) if ob.data and ob.data.b2cs.no_shadow_receive: func(' ' * depth + ' <noshadowreceive />') if ob.data and ob.data.b2cs.no_shadow_cast: func(' ' * depth + ' <noshadowcast />') if ob.data and ob.data.b2cs.limited_shadow_cast: func(' ' * depth + ' <limitedshadowcast />') if ob.data.b2cs.lighter2_vertexlight: func( ' ' * depth + ' <key name="lighter2" editoronly="yes" vertexlight="yes" />') if ob.data.b2cs.lighter2_selfshadow: func( ' ' * depth + ' <key name="lighter2" editoronly="yes" noselfshadow="yes" />') if ob.data.b2cs.lighter2_lmscale > 0.0: func(' ' * depth + ' <key name="lighter2" editoronly="yes" lmscale="%f" />' % (ob.data.b2cs.lighter2_lmscale)) func(' ' * depth + ' <params>') def SubmeshesLackMaterial(subMeshess): for submeshes in subMeshess: for sub in submeshes: if not sub.material: return True return False # There is a submesh without a material if SubmeshesLackMaterial(subMeshess): mat = None for m, ob in self.allObjects(): mat = ob.GetDefaultMaterial(notifications=False) if mat != None: break if mat == None: print('WARNING: Factory "%s" has no material!' % (self.name)) func(' ' * depth + ' <material>%s</material>' % (mat.uname if mat != None else 'None')) # Export the render buffers of all objects composing the group args = {} args['meshData'] = meshData args['mappingBuffers'] = mappingBuffers args['mappingVertices'] = mappingVertices args['mappingNormals'] = mappingNormals for buf in GetRenderBuffers(**args): buf.AsCS(func, depth + 4) # Export the submeshes composing the group's objects for submeshes in subMeshess: for sub in submeshes: sub.AsCS(func, 6) func(' ' * depth + ' </params>') func(' ' * depth + '</meshfact>') if not dontClose: func("</library>") # Delete working copies of objects for obCpy in meshData: bpy.data.objects.remove(obCpy)
def avail_factories(self, context): items = [(str(i), f.name, f.vfs) for i, f in enumerate(GetPreferences().FactoryRefs)] items.append((str(-1), ' NONE', 'None')) return sorted(items, key=operator.itemgetter(1))
def execute(self, context): new_mat = GetPreferences().MaterialRefs.add() return {'FINISHED'}
def avail_materials(self, context): items = [(str(i), m.name, m.vfs) for i, m in enumerate(GetPreferences().MaterialRefs)] items.append((str(-1), ' NONE', 'None')) return sorted(items, key=operator.itemgetter(1))
def draw(self, context): layout = self.layout physics = False for object in bpy.data.objects: if object.hasSupportedPhysicsEnabled(): physics = True break rd = context.scene.render row = layout.row(align=True) row.operator("io_scene_cs.export", text="Export", icon='SCENE_DATA') if not GetPreferences().library: if HasCrystalSpace(): row.operator("io_scene_cs.export_run", text="Play", icon='GAME') if context.active_object and context.active_object.type in [ 'MESH', 'ARMATURE' ] and context.active_object.parent is None: row.operator("io_scene_cs.export_view", text="View", icon='RENDER_STILL') row = layout.row() row.prop(GetPreferences(), "console") row.prop(GetPreferences(), "verbose") row.prop(GetPreferences(), "silent") row.prop(GetPreferences(), "bugplug") if physics: gs = context.scene.game_settings layout.prop(gs, "physics_engine", text="Physics Engine") else: row.label(text="'walktest' isn't available!") row = layout.row(align=True) box = row.box() row = box.row() row.prop(GetPreferences(), "exportOnlyCurrentScene") row = box.row() row.prop(GetPreferences(), "library") row = box.row() if not GetPreferences().library: row.prop(GetPreferences(), "sharedMaterial") row = box.row() row.prop(GetPreferences(), "enableDoublesided") row = box.row() row.prop(GetPreferences(), "exportPath")