def name_update(self, context): lprint("D SCS Look inventory name update: %s", (self.name, )) # convert name to game engine like name tokenized_name = _name_utils.tokenize_name(self.name) if self.name != tokenized_name: self.name = tokenized_name # always get scs root to have access to look inventory scs_root_obj = _object_utils.get_scs_root(context.active_object) # if there is more of variants with same name, make postfixed name (this will cause another name update) if len( _inventory.get_indices(scs_root_obj.scs_object_look_inventory, self.name)) == 2: # duplicate i = 1 new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) while _inventory.get_index(scs_root_obj.scs_object_look_inventory, new_name) != -1: new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) i += 1 if new_name != self.name: self.name = new_name
def name_update(self, context): lprint("D SCS Part inventory name update: %s", (self.name, )) # convert name to game engine like name tokenized_name = _name_utils.tokenize_name( self.name, default_name=_PART_consts.default_name) if self.name != tokenized_name: self.name = tokenized_name # always get scs root because we allow editing of parts in any child scs_root_obj = _object_utils.get_scs_root(context.active_object) # if there is more of parts with same name, make postfixed name (this will cause another name update) if len( _inventory.get_indices(scs_root_obj.scs_object_part_inventory, self.name)) == 2: # duplicate i = 1 new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) while _inventory.get_index(scs_root_obj.scs_object_part_inventory, new_name) != -1: new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) i += 1 if new_name != self.name: self.name = new_name if "scs_part_old_name" in self: if scs_root_obj: # fix part name in all children of current root children = _object_utils.get_children(scs_root_obj) for child in children: # fix part name in child with existing old name if child.scs_props.scs_part == self["scs_part_old_name"]: child.scs_props.scs_part = self.name # rename parts in all variants also variant_inventory = scs_root_obj.scs_object_variant_inventory for variant in variant_inventory: for part in variant.parts: if part.name == self["scs_part_old_name"]: part.name = self.name break # backup current name for checking children on next renaming self["scs_part_old_name"] = self.name
def name_update(self, context): lprint("D SCS Part inventory name update: %s", (self.name,)) # convert name to game engine like name tokenized_name = _name_utils.tokenize_name(self.name, default_name=_PART_consts.default_name) if self.name != tokenized_name: self.name = tokenized_name # always get scs root because we allow editing of parts in any child scs_root_obj = _object_utils.get_scs_root(context.active_object) # if there is more of parts with same name, make postfixed name (this will cause another name update) if len(_inventory.get_indices(scs_root_obj.scs_object_part_inventory, self.name)) == 2: # duplicate i = 1 new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) while _inventory.get_index(scs_root_obj.scs_object_part_inventory, new_name) != -1: new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) i += 1 if new_name != self.name: self.name = new_name if "scs_part_old_name" in self: if scs_root_obj: # fix part name in all children of current root children = _object_utils.get_children(scs_root_obj) for child in children: # fix part name in child with existing old name if child.scs_props.scs_part == self["scs_part_old_name"]: child.scs_props.scs_part = self.name # rename parts in all variants also variant_inventory = scs_root_obj.scs_object_variant_inventory for variant in variant_inventory: for part in variant.parts: if part.name == self["scs_part_old_name"]: part.name = self.name break # backup current name for checking children on next renaming self["scs_part_old_name"] = self.name
def _make_common_part(item, index, col_type): scs_root = _get_scs_root(item) if not item.scs_props.locator_collider_centered: if item.scs_props.locator_collider_type == 'Box': offset_matrix = (item.matrix_world * Matrix.Translation((0.0, -item.scs_props.locator_collider_box_y / 2, 0.0)) * (Matrix.Scale(item.scs_props.locator_collider_box_x, 4, (1.0, 0.0, 0.0)) * Matrix.Scale(item.scs_props.locator_collider_box_y, 4, (0.0, 1.0, 0.0)) * Matrix.Scale(item.scs_props.locator_collider_box_z, 4, (0.0, 0.0, 1.0)))) elif item.scs_props.locator_collider_type == 'Sphere': offset_matrix = (item.matrix_world * Matrix.Translation((0.0, -item.scs_props.locator_collider_dia / 2, 0.0)) * Matrix.Scale(item.scs_props.locator_collider_dia, 4)) elif item.scs_props.locator_collider_type in ('Capsule', 'Cylinder'): offset_matrix = (item.matrix_world * Matrix.Translation((0.0, -item.scs_props.locator_collider_len / 2, 0.0)) * Matrix.Scale(item.scs_props.locator_collider_dia, 4)) else: offset_matrix = item.matrix_world loc, qua, sca = _convert_utils.get_scs_transformation_components(scs_root.matrix_world.inverted() * offset_matrix) else: loc, qua, sca = _convert_utils.get_scs_transformation_components(scs_root.matrix_world.inverted() * item.matrix_world) section = _SectionData("Locator") section.props.append(("Name", _name_utils.tokenize_name(item.name))) section.props.append(("Index", index)) section.props.append(("Position", ["&&", loc])) section.props.append(("Rotation", ["&&", qua])) section.props.append(("Alias", "")) section.props.append(("Weight", ["&", (item.scs_props.locator_collider_mass,)])) section.props.append(("Type", col_type)) return section
def _fill_locator_sections(model_locator_list): """ Fills up "Locator" sections. :param model_locator_list: :return: """ locator_sections = [] locator_i = 0 for item in model_locator_list: # print('locator: "%s" - "%s"' % (item.name, str(item.scs_props.locator_model_hookup))) part_section = _SectionData("Locator") loc_name = _name_utils.tokenize_name(item.name) part_section.props.append(("Name", loc_name)) if item.scs_props.locator_model_hookup: part_section.props.append( ("Hookup", item.scs_props.locator_model_hookup.split(':', 1)[1].strip())) part_section.props.append(("Index", locator_i)) loc, qua, sca = _convert_utils.get_scs_transformation_components( item.matrix_world) part_section.props.append(("Position", ["&&", loc])) part_section.props.append(("Rotation", ["&&", qua])) part_section.props.append(("Scale", ["&&", sca])) locator_sections.append(part_section) locator_i += 1 return locator_sections
def _get_variant(section): """Receives a Variant section and returns its properties in its own variables. For any item that fails to be found, it returns None.""" variant_name = None variantparts = [] for prop in section.props: if prop[0] in ("", "#"): pass elif prop[0] == "Name": variant_name = prop[1] else: lprint('\nW Unknown property in "Variant" data: "%s"!', prop[0]) for sec in section.sections: if sec.type == "Part": part_name = None for sec_prop in sec.props: if sec_prop[0] in ("", "#"): pass elif sec_prop[0] == "Name": part_name = sec_prop[1] elif sec_prop[0] == "AttributeCount": ''' NOTE: skipped for now as no data needs to be readed attribute_count = sec_prop[1] ''' pass else: lprint( '\nW Unknown property in "Variant/Part" data: "%s"!', sec_prop[0]) var_part_format = var_part_tag = var_part_value = None for sec_section in sec.sections: if sec_section.type == "Attribute": for sec_section_prop in sec_section.props: if sec_section_prop[0] in ("", "#"): pass elif sec_section_prop[0] == "Format": var_part_format = sec_section_prop[1] elif sec_section_prop[0] == "Tag": var_part_tag = sec_section_prop[1] elif sec_section_prop[0] == "Value": var_part_value = sec_section_prop[1] else: lprint( '\nW Unknown property in "Variant/Part/Attribute" data: "%s"!', sec_section_prop[0]) if var_part_format == "INT" and var_part_tag == "visible": if var_part_value[0] == 1: variantparts.append( _name_utils.tokenize_name(part_name)) else: lprint('D ---var_part_value: %s', (str(var_part_value), )) return variant_name, variantparts
def _fill_spawn_point_sections(data_list): """Fills up "Spawn Point" sections.""" sections = [] for item_i, item in enumerate(data_list): section = _SectionData("SpawnPoint") section.props.append(("Name", _name_utils.tokenize_name(item.name))) loc, qua, sca = _convert_utils.get_scs_transformation_components(item.matrix_world) section.props.append(("Position", ["&&", loc])) section.props.append(("Rotation", ["&&", qua])) section.props.append(("Type", int(item.scs_props.locator_prefab_spawn_type))) sections.append(section) return sections
def _get_variant(section): """Receives a Variant section and returns its properties in its own variables. For any item that fails to be found, it returns None.""" variant_name = None variantparts = [] for prop in section.props: if prop[0] in ("", "#"): pass elif prop[0] == "Name": variant_name = prop[1] else: lprint('\nW Unknown property in "Variant" data: "%s"!', prop[0]) for sec in section.sections: if sec.type == "Part": part_name = None for sec_prop in sec.props: if sec_prop[0] in ("", "#"): pass elif sec_prop[0] == "Name": part_name = sec_prop[1] elif sec_prop[0] == "AttributeCount": ''' NOTE: skipped for now as no data needs to be readed attribute_count = sec_prop[1] ''' pass else: lprint('\nW Unknown property in "Variant/Part" data: "%s"!', sec_prop[0]) var_part_format = var_part_tag = var_part_value = None for sec_section in sec.sections: if sec_section.type == "Attribute": for sec_section_prop in sec_section.props: if sec_section_prop[0] in ("", "#"): pass elif sec_section_prop[0] == "Format": var_part_format = sec_section_prop[1] elif sec_section_prop[0] == "Tag": var_part_tag = sec_section_prop[1] elif sec_section_prop[0] == "Value": var_part_value = sec_section_prop[1] else: lprint('\nW Unknown property in "Variant/Part/Attribute" data: "%s"!', sec_section_prop[0]) if var_part_format == "INT" and var_part_tag == "visible": if var_part_value[0] == 1: variantparts.append(_name_utils.tokenize_name(part_name)) else: lprint('D ---var_part_value: %s', (str(var_part_value),)) return variant_name, variantparts
def name_update(self, context): lprint("D SCS Look inventory name update: %s", (self.name,)) # convert name to game engine like name tokenized_name = _name_utils.tokenize_name(self.name) if self.name != tokenized_name: self.name = tokenized_name # always get scs root to have access to look inventory scs_root_obj = _object_utils.get_scs_root(context.active_object) # if there is more of variants with same name, make postfixed name (this will cause another name update) if len(_inventory.get_indices(scs_root_obj.scs_object_look_inventory, self.name)) == 2: # duplicate i = 1 new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) while _inventory.get_index(scs_root_obj.scs_object_look_inventory, new_name) != -1: new_name = _name_utils.tokenize_name(self.name + "_" + str(i).zfill(2)) i += 1 if new_name != self.name: self.name = new_name
def _fill_spawn_point_sections(data_list): """Fills up "Spawn Point" sections.""" sections = [] for item_i, item in enumerate(data_list): section = _SectionData("SpawnPoint") section.props.append(("Name", _name_utils.tokenize_name(item.name))) loc, qua, sca = _convert_utils.get_scs_transformation_components( item.matrix_world) section.props.append(("Position", ["&&", loc])) section.props.append(("Rotation", ["&&", qua])) section.props.append( ("Type", int(item.scs_props.locator_prefab_spawn_type))) sections.append(section) return sections
def _fill_sign_sections(data_list, scs_sign_model_inventory): """Fills up "Sign" sections.""" sections = [] for item_i, item in enumerate(data_list): section = _SectionData("Sign") section.props.append(("Name", _name_utils.tokenize_name(item.name))) loc, qua, sca = _convert_utils.get_scs_transformation_components(item.matrix_world) section.props.append(("Position", ["&&", loc])) section.props.append(("Rotation", ["&&", qua])) if item.scs_props.locator_prefab_sign_model: model = scs_sign_model_inventory[item.scs_props.locator_prefab_sign_model].item_id else: model = "" section.props.append(("Model", model)) section.props.append(("Part", item.scs_props.scs_part)) sections.append(section) return sections
def _fill_sign_sections(data_list, scs_sign_model_inventory): """Fills up "Sign" sections.""" sections = [] for item_i, item in enumerate(data_list): section = _SectionData("Sign") section.props.append(("Name", _name_utils.tokenize_name(item.name))) loc, qua, sca = _convert_utils.get_scs_transformation_components( item.matrix_world) section.props.append(("Position", ["&&", loc])) section.props.append(("Rotation", ["&&", qua])) if item.scs_props.locator_prefab_sign_model: model = scs_sign_model_inventory[ item.scs_props.locator_prefab_sign_model].item_id else: model = "" section.props.append(("Model", model)) section.props.append(("Part", item.scs_props.scs_part)) sections.append(section) return sections
def _fill_locator_sections(model_locator_list): """ Fills up "Locator" sections. :param model_locator_list: :return: """ locator_sections = [] locator_i = 0 for item in model_locator_list: # print('locator: "%s" - "%s"' % (item.name, str(item.scs_props.locator_model_hookup))) part_section = _SectionData("Locator") loc_name = _name_utils.tokenize_name(item.name) part_section.props.append(("Name", loc_name)) if item.scs_props.locator_model_hookup: part_section.props.append(("Hookup", item.scs_props.locator_model_hookup.split(':', 1)[1].strip())) part_section.props.append(("Index", locator_i)) loc, qua, sca = _convert_utils.get_scs_transformation_components(item.matrix_world) part_section.props.append(("Position", ["&&", loc])) part_section.props.append(("Rotation", ["&&", qua])) part_section.props.append(("Scale", ["&&", sca])) locator_sections.append(part_section) locator_i += 1 return locator_sections
def execute(dirpath, name_suffix, root_object, armature_object, skeleton_filepath, mesh_objects, model_locators, used_parts, used_materials, used_bones, used_terrain_points): """Executes export of PIM file for given data. :param dirpath: directory path for PIM file :type dirpath: str :param name_suffix: file name suffix :type name_suffix: str :param root_object: Blender SCS Root empty object :type root_object: bpy.types.Object :param armature_object: Blender Aramture object belonging to this SCS game object :type armature_object: bpy.types.Object :param skeleton_filepath: relative file path of PIS file :type skeleton_filepath: str :param mesh_objects: all the meshes which should be exported for current game object :type mesh_objects: list of bpy.types.Object :param model_locators: all Blender empty objecs which represents model locators and should be exported for current game object :type model_locators: list of bpy.types.Object :param used_parts: parts transitional structure for storing used parts inside this PIM export :type used_parts: io_scs_tools.exp.transition_structs.parts.PartsTrans :param used_materials: materials transitional structure for storing used materials inside this PIM export :type used_materials: io_scs_tools.exp.transition_structs.materials.MaterialsTrans :param used_bones: bones transitional structure for storing used bones inside this PIM export :type used_bones: io_scs_tools.exp.transition_structs.bones.BonesTrans :param used_terrain_points: terrain points transitional structure for storing used terrain points :type used_terrain_points: io_scs_tools.exp.transition_structs.terrain_points.TerrainPntsTrans :return: True if export was successfull; False otherwise :rtype: bool """ print("\n************************************") print("** SCS PIM.EF Exporter **") print("** (c)2017 SCS Software **") print("************************************\n") scs_globals = _get_scs_globals() format_version = 1 is_skin_used = (armature_object and root_object.scs_props.scs_root_animated == "anim") pim_header = Header("", format_version, root_object.name) pim_global = Globall(used_parts.count(), skeleton_filepath) pim_materials = collections.OrderedDict() # dict of Material class instances representing used materials """:type: dict[str, Material]""" pim_pieces = [] # list of Piece class instances representing mesh pieces """:type: list[Piece]""" pim_parts = {} # list of Part class instances representing used parts """:type: dict[str, Part]""" pim_locators = [] # list of Locator class instances representing model locators """:type: list[Locator]""" objects_with_default_material = {} # stores object names which has no material set missing_mappings_data = {} # indicates if material doesn't have set any uv layer for export bones = skin = skin_stream = None if is_skin_used: # create bones data section bones = Bones() for bone in armature_object.data.bones: bones.add_bone(bone.name) used_bones.add(bone.name) # create skin data section skin_stream = SkinStream(SkinStream.Types.POSITION) skin = Skin(skin_stream) # create mesh object data sections for mesh_obj in mesh_objects: vert_groups = mesh_obj.vertex_groups # calculate faces flip state from all ancestors of current object scale_sign = 1 parent = mesh_obj while parent and parent.scs_props.empty_object_type != "SCS_Root": for scale_axis in parent.scale: scale_sign *= scale_axis parent = parent.parent winding_order = 1 if scale_sign < 0: winding_order = -1 # calculate transformation matrix for current object (root object transforms are always subtracted!) mesh_transf_mat = root_object.matrix_world.inverted() * mesh_obj.matrix_world """:type: mathutils.Matrix""" # calculate vertex position transformation matrix for this object pos_transf_mat = (Matrix.Scale(scs_globals.export_scale, 4) * _scs_to_blend_matrix().inverted()) """:type: mathutils.Matrix""" # calculate vertex normals transformation matrix for this object # NOTE: as normals will be read from none export prepared mesh we have to add rotation and scale from mesh transformation matrix _, rot, scale = mesh_transf_mat.decompose() scale_matrix_x = Matrix.Scale(scale.x, 3, Vector((1, 0, 0))).to_4x4() scale_matrix_y = Matrix.Scale(scale.y, 3, Vector((0, 1, 0))).to_4x4() scale_matrix_z = Matrix.Scale(scale.z, 3, Vector((0, 0, 1))).to_4x4() nor_transf_mat = (_scs_to_blend_matrix().inverted() * rot.to_matrix().to_4x4() * scale_matrix_x * scale_matrix_y * scale_matrix_z) """:type: mathutils.Matrix""" # get initial mesh and vertex groups for it mesh = _object_utils.get_mesh(mesh_obj) _mesh_utils.bm_prepare_mesh_for_export(mesh, mesh_transf_mat) # get extra mesh only for normals mesh_for_normals = _object_utils.get_mesh(mesh_obj) mesh_for_normals.calc_normals_split() missing_uv_layers = {} # stores missing uvs specified by materials of this object missing_vcolor = False # indicates if object is missing vertex color layer missing_vcolor_a = False # indicates if object is missing vertex color alpha layer missing_skinned_verts = set() # indicates if object is having only partial skin, which is not allowed in our models has_unnormalized_skin = False # indicates if object has vertices which bones weight sum is smaller then one hard_edges = set() mesh_piece = Piece(len(pim_pieces)) """:type: Piece""" for poly in mesh.polygons: mat_index = poly.material_index # check material existence and decide what material name and effect has to be used if mat_index >= len(mesh_obj.material_slots) or mesh_obj.material_slots[mat_index].material is None: # no material or invalid index material = None pim_mat_name = "_default_material_-_default_settings_" pim_mat_effect = "eut2.dif" objects_with_default_material[mesh_obj.name] = 1 else: material = mesh_obj.material_slots[mat_index].material pim_mat_name = material.name pim_mat_effect = material.scs_props.mat_effect_name # create new pim material if material with that name doesn't yet exists if pim_mat_name not in pim_materials: pim_material = Material(len(pim_materials), pim_mat_name, pim_mat_effect, material) pim_materials[pim_mat_name] = pim_material used_materials.add(pim_mat_name, material) piece_vert_indices = [] vert_normals = [] vert_uvs = [] uvs_aliases = [] uvs_names = collections.OrderedDict() vert_rgbas = [] rgbas_names = collections.OrderedDict() tex_coord_alias_map = pim_materials[pim_mat_name].get_tex_coord_map() for loop_i in poly.loop_indices: loop = mesh.loops[loop_i] """:type: bpy.types.MeshLoop""" vert_i = loop.vertex_index # as we are already looping first find out if edge is hard and put it to set if mesh.edges[loop.edge_index].use_edge_sharp: hard_edges.add(loop.edge_index) # get data of current vertex # 1. position -> mesh.vertices[loop.vertex_index].co position = tuple(pos_transf_mat * mesh.vertices[vert_i].co) # 2. normal -> loop.normal -> calc_normals_split() has to be called before normal = nor_transf_mat * mesh_for_normals.loops[loop_i].normal normal = tuple(Vector(normal).normalized()) vert_normals.append(normal) # 3. uvs -> uv_lay = mesh.uv_layers[0].data; uv_lay[loop_i].uv uvs = [] uvs_aliases = [] if len(tex_coord_alias_map) < 1: # no textures or none uses uv mapping in current material effect uvs.append((0.0, 0.0)) uvs_names["generated"] = True uvs_aliases.append(["_TEXCOORD0"]) # report missing mappings only on actual materials with textures using uv mappings if material and pim_materials[pim_mat_name].uses_textures_with_uv(): if material.name not in missing_mappings_data: missing_mappings_data[material.name] = {} if mesh_obj.name not in missing_mappings_data[material.name]: missing_mappings_data[material.name][mesh_obj.name] = 1 else: for uv_lay_name in mesh.uv_layers.keys(): uv_lay = mesh.uv_layers[uv_lay_name] uvs.append(_change_to_scs_uv_coordinates(uv_lay.data[loop_i].uv)) uvs_names[uv_lay_name] = True aliases = [] if uv_lay_name in tex_coord_alias_map: for alias_index in tex_coord_alias_map[uv_lay_name]: aliases.append("_TEXCOORD" + str(alias_index)) uvs_aliases.append(aliases) vert_uvs.append(uvs) # 4. vcol -> vcol_lay = mesh.vertex_colors[0].data; vcol_lay[loop_i].color rgbas = [] vcol_multi = mesh_obj.data.scs_props.vertex_color_multiplier if _MESH_consts.default_vcol not in mesh.vertex_colors: # get RGB component of RGBA vcol = (1.0,) * 3 missing_vcolor = True else: color = mesh.vertex_colors[_MESH_consts.default_vcol].data[loop_i].color vcol = (color[0] * 2 * vcol_multi, color[1] * 2 * vcol_multi, color[2] * 2 * vcol_multi) if _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix not in mesh.vertex_colors: # get A component of RGBA vcol += (1.0,) missing_vcolor_a = True else: alpha = mesh.vertex_colors[_MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix].data[loop_i].color vcol += ((alpha[0] + alpha[1] + alpha[2]) / 3.0 * 2 * vcol_multi,) # take avg of colors for alpha rgbas.append(vcol) rgbas_names[_MESH_consts.default_vcol] = True # export rest of the vertex colors too, but do not apply extra multiplies of SCS exporter # as rest of the layers are just artist layers for vcol_layer in mesh.vertex_colors: # we already computed thoose so ignore them if vcol_layer.name in [_MESH_consts.default_vcol, _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix]: continue color = vcol_layer.data[loop_i].color vcol = (color[0], color[1], color[2], 1.0) rgbas.append(vcol) rgbas_names[vcol_layer.name] = True vert_rgbas.append(rgbas) # save internal vertex index to array to be able to construct triangle afterwards piece_vert_index = mesh_piece.add_vertex(vert_i, position) piece_vert_indices.append(piece_vert_index) if is_skin_used: # get skinning data for vertex and save it to skin stream bone_weights = {} bone_weights_sum = 0 for v_group_entry in mesh.vertices[vert_i].groups: bone_indx = bones.get_bone_index(vert_groups[v_group_entry.group].name) bone_weight = v_group_entry.weight # proceed only if bone exists in our armature if bone_indx != -1: bone_weights[bone_indx] = bone_weight bone_weights_sum += bone_weight skin_entry = SkinStream.Entry(mesh_piece.get_index(), piece_vert_index, position, bone_weights, bone_weights_sum) skin_stream.add_entry(skin_entry) # report un-skinned vertices (no bones or zero sum weight) or badly skinned model if bone_weights_sum <= 0: missing_skinned_verts.add(vert_i) elif bone_weights_sum < 1: has_unnormalized_skin = True # save to terrain points storage if present in correct vertex group for group in mesh.vertices[vert_i].groups: # if current object doesn't have vertex group found in mesh data, then ignore that group # This can happen if multiple objects are using same mesh and # some of them have vertex groups, but others not. if group.group >= len(mesh_obj.vertex_groups): continue curr_vg_name = mesh_obj.vertex_groups[group.group].name # if vertex group name doesn't match prescribed one ignore this vertex group if not match(_OP_consts.TerrainPoints.vg_name_regex, curr_vg_name): continue # if node index is not in bounds ignore this vertex group node_index = int(curr_vg_name[-1]) if node_index >= _PL_consts.PREFAB_NODE_COUNT_MAX: continue # if no variants defined add globally (without variant block) if len(root_object.scs_object_variant_inventory) == 0: used_terrain_points.add(-1, node_index, position, normal) continue # finally iterate variant parts entries to find where this part is included # and add terrain points to transitional structure # # NOTE: variant index is donated by direct order of variants in inventory # so export in PIT has to use the same order otherwise variant # indices will be misplaced for variant_i, variant in enumerate(root_object.scs_object_variant_inventory): used_terrain_points.ensure_entry(variant_i, node_index) for variant_part in variant.parts: if variant_part.name == mesh_obj.scs_props.scs_part and variant_part.include: used_terrain_points.add(variant_i, node_index, position, normal) break assert mesh_piece.add_face(pim_materials[pim_mat_name], tuple(piece_vert_indices[::winding_order * -1]), # invert indices because of conversion to scs system tuple(vert_normals[::winding_order]), tuple(vert_uvs[::winding_order]), list(uvs_names.keys()), uvs_aliases, tuple(vert_rgbas[::winding_order]), list(rgbas_names.keys()) ) # as we captured all hard edges collect them now and put it into Piece for hard_edge in hard_edges: (vert1_i, vert2_i) = mesh.edges[hard_edge].vertices assert mesh_piece.add_edge(vert1_i, vert2_i, blender_mesh_indices=True) # free normals calculations and eventually remove mesh object _mesh_utils.cleanup_mesh(mesh) _mesh_utils.cleanup_mesh(mesh_for_normals) # create part if it doesn't exists yet part_name = mesh_obj.scs_props.scs_part if part_name not in pim_parts: pim_parts[part_name] = Part(part_name) # put pieces of current mesh to global list pim_pieces.append(mesh_piece) # add pieces of current mesh to part pim_part = pim_parts[part_name] pim_part.add_piece(mesh_piece) # report missing data for each object if len(missing_uv_layers) > 0: for uv_lay_name in missing_uv_layers: lprint("W Object '%s' is missing UV layer '%s' specified by materials: %s\n", (mesh_obj.name, uv_lay_name, missing_uv_layers[uv_lay_name])) if missing_vcolor: lprint("W Object %r is missing vertex color layer with name %r! Default RGB color will be exported (0.5, 0.5, 0.5)!", (mesh_obj.name, _MESH_consts.default_vcol)) if missing_vcolor_a: lprint("W Object %r is missing vertex color alpha layer with name %r! Default alpha will be exported (0.5)", (mesh_obj.name, _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix)) if len(missing_skinned_verts) > 0: lprint("E Object %r from SCS Root %r has %s vertices which are not skinned to any bone, expect errors during conversion!", (mesh_obj.name, root_object.name, len(missing_skinned_verts))) if has_unnormalized_skin: lprint("W Object %r from SCS Root %r has unormalized skinning, exporting normalized weights!\n\t " "You can normalize weights by selecting object & executing 'Normalize All Vertex Groups'.", (mesh_obj.name, root_object.name)) # report missing data for whole model if len(missing_mappings_data) > 0: for material_name in missing_mappings_data: lprint("W Material '%s' is missing mapping data! Objects using it are exported with default UV:\n\t %s", (material_name, list(missing_mappings_data[material_name].keys()))) if len(objects_with_default_material) > 0: lprint("W Some objects don't use any material. Default material and UV mapping is used on them:\n\t %s", (list(objects_with_default_material.keys()),)) # create locators data sections for loc_obj in model_locators: pos, qua, sca = _get_scs_transformation_components(root_object.matrix_world.inverted() * loc_obj.matrix_world) if sca[0] * sca[1] * sca[2] < 0: lprint("W Model locator %r inside SCS Root Object %r not exported because of invalid scale.\n\t " + "Model locators must have positive scale!", (loc_obj.name, root_object.name)) continue name = _name_utils.tokenize_name(loc_obj.name) hookup_string = loc_obj.scs_props.locator_model_hookup if hookup_string != "" and ":" in hookup_string: hookup = hookup_string.split(':', 1)[1].strip() else: if hookup_string != "": lprint("W The Hookup %r has no expected value!", hookup_string) hookup = None # create locator object for export locator = Locator(len(pim_locators), name, hookup) locator.set_position(pos) locator.set_rotation(qua) locator.set_scale(sca) # create part if it doesn't exists yet part_name = loc_obj.scs_props.scs_part if part_name not in pim_parts: assert used_parts.is_present(part_name) pim_parts[part_name] = Part(part_name) # add locator to part pim_part = pim_parts[part_name] pim_part.add_locator(locator) # add locator to locator list pim_locators.append(locator) # create container pim_container = [pim_header.get_as_section(), pim_global.get_as_section()] for mat_name in pim_materials: pim_container.append(pim_materials[mat_name].get_as_section()) for pim_piece in pim_pieces: pim_container.append(pim_piece.get_as_section()) for part_name in used_parts.get_as_list(): # export all parts even empty ones gathered from PIC and PIP if part_name in pim_parts: pim_container.append(pim_parts[part_name].get_as_section()) else: pim_container.append(Part(part_name).get_as_section()) for locator in pim_locators: pim_container.append(locator.get_as_section()) if is_skin_used: pim_container.append(bones.get_as_section()) pim_container.append(skin.get_as_section()) # write to file ind = " " pim_filepath = os.path.join(dirpath, root_object.name + ".pim" + name_suffix) return _pix_container.write_data_to_file(pim_container, pim_filepath, ind)
def execute(dirpath, root_object, armature_object, skeleton_filepath, mesh_objects, model_locators, used_parts, used_materials, used_bones, used_terrain_points): """Executes export of PIM file for given data. :param dirpath: directory path for PIM file :type dirpath: str :param root_object: Blender SCS Root empty object :type root_object: bpy.types.Object :param armature_object: Blender Aramture object belonging to this SCS game object :type armature_object: bpy.types.Object :param skeleton_filepath: relative file path of PIS file :type skeleton_filepath: str :param mesh_objects: all the meshes which should be exported for current game object :type mesh_objects: list of bpy.types.Object :param model_locators: all Blender empty objecs which represents model locators and should be exported for current game object :type model_locators: list of bpy.types.Object :param used_parts: parts transitional structure for storing used parts inside this PIM export :type used_parts: io_scs_tools.exp.transition_structs.parts.PartsTrans :param used_materials: materials transitional structure for storing used materials inside this PIM export :type used_materials: io_scs_tools.exp.transition_structs.materials.MaterialsTrans :param used_bones: bones transitional structure for storing used bones inside this PIM export :type used_bones: io_scs_tools.exp.transition_structs.bones.BonesTrans :param used_terrain_points: terrain points transitional structure for storing used terrain points :type used_terrain_points: io_scs_tools.exp.transition_structs.terrain_points.TerrainPntsTrans :return: True if export was successfull; False otherwise :rtype: bool """ print("\n************************************") print("** SCS PIM Exporter **") print("** (c)2015 SCS Software **") print("************************************\n") scs_globals = _get_scs_globals() if scs_globals.output_type == "5": format_version = 5 format_type = "" else: format_version = 1 format_type = "def" is_skin_used = (armature_object and root_object.scs_props.scs_root_animated == "anim") pim_header = Header(format_type, format_version, root_object.name) pim_global = Globall(skeleton_filepath) pim_materials = collections.OrderedDict() # dict of Material class instances representing used materials """:type: dict[str, Material]""" pim_pieces = [] # list of Piece class instances representing mesh pieces """:type: list[Piece]""" pim_parts = {} # list of Part class instances representing used parts """:type: dict[str, Part]""" pim_locators = [] # list of Locator class instances representing model locators """:type: list[Locator]""" objects_with_default_material = {} # stores object names which has no material set missing_mappings_data = {} # indicates if material doesn't have set any uv layer for export bones = skin = skin_stream = None if is_skin_used: # create bones data section bones = Bones() for bone in armature_object.data.bones: bones.add_bone(bone.name) used_bones.add(bone.name) # create skin data section skin_stream = SkinStream(SkinStream.Types.POSITION) skin = Skin(skin_stream) # create mesh object data sections for mesh_obj in mesh_objects: vert_groups = mesh_obj.vertex_groups mesh_pieces = collections.OrderedDict() # calculate faces flip state from all ancestors of current object scale_sign = 1 parent = mesh_obj while parent and parent.scs_props.empty_object_type != "SCS_Root": for scale_axis in parent.scale: scale_sign *= scale_axis parent = parent.parent face_flip = scale_sign < 0 # calculate transformation matrix for current object (root object transforms are always subtracted!) mesh_transf_mat = root_object.matrix_world.inverted() * mesh_obj.matrix_world # calculate transformation matrices for this object pos_transf_mat = (Matrix.Scale(scs_globals.export_scale, 4) * _scs_to_blend_matrix().inverted()) nor_transf_mat = _scs_to_blend_matrix().inverted() # get initial mesh and vertex groups for it mesh = _object_utils.get_mesh(mesh_obj) _mesh_utils.bm_prepare_mesh_for_export(mesh, mesh_transf_mat, face_flip) mesh.calc_normals_split() missing_uv_layers = {} # stores missing uvs specified by materials of this object missing_vcolor = False # indicates if object is missing vertex color layer missing_vcolor_a = False # indicates if object is missing vertex color alpha layer for poly in mesh.polygons: mat_index = poly.material_index # check material existence and decide what material name and effect has to be used if mat_index >= len(mesh_obj.material_slots) or mesh_obj.material_slots[mat_index].material is None: # no material or invalid index material = None pim_mat_name = "_not_existing_material_" pim_mat_effect = "eut2.dif" objects_with_default_material[mesh_obj.name] = 1 else: material = mesh_obj.material_slots[mat_index].material pim_mat_name = material.name pim_mat_effect = material.scs_props.mat_effect_name # create new pim material if material with that name doesn't yet exists if pim_mat_name not in pim_materials: pim_material = Material(len(pim_materials), pim_mat_name, pim_mat_effect, material) pim_materials[pim_mat_name] = pim_material used_materials.add(pim_mat_name, material) # create new piece if piece with this material doesn't exists yet -> split to pieces by material if pim_mat_name not in mesh_pieces: mesh_pieces[pim_mat_name] = Piece(len(pim_pieces) + len(mesh_pieces), pim_materials[pim_mat_name]) nmap_uv_layer = pim_materials[pim_mat_name].get_nmap_uv_name() if nmap_uv_layer: # if there is uv layer used for normal maps then calculate tangents on it mesh.calc_tangents(uvmap=nmap_uv_layer) mesh_piece = mesh_pieces[pim_mat_name] """:type: Piece""" piece_vert_indices = [] for loop_i in poly.loop_indices: loop = mesh.loops[loop_i] """:type: bpy.types.MeshLoop""" vert_i = loop.vertex_index # get data of current vertex # 1. position -> mesh.vertices[loop.vertex_index].co position = tuple(pos_transf_mat * mesh.vertices[vert_i].co) # 2. normal -> loop.normal -> calc_normals_split() has to be called before normal = nor_transf_mat * loop.normal normal = tuple(Vector(normal).normalized()) # 3. uvs -> uv_lay = mesh.uv_layers[0].data; uv_lay[loop_i].uv uvs = [] uvs_aliases = [] tex_coord_alias_map = pim_materials[pim_mat_name].get_tex_coord_map() if len(tex_coord_alias_map) < 1: # no textures or none uses uv mapping in current material effect uvs.append((0.0, 0.0)) uvs_aliases.append(["_TEXCOORD0"]) # report missing mappings only on actual materials with textures using uv mappings if material and pim_materials[pim_mat_name].uses_textures_with_uv(): if material.name not in missing_mappings_data: missing_mappings_data[material.name] = {} if mesh_obj.name not in missing_mappings_data[material.name]: missing_mappings_data[material.name][mesh_obj.name] = 1 else: for uv_lay_name in tex_coord_alias_map: if uv_lay_name not in mesh.uv_layers: uvs.append((0.0, 0.0)) # properly report missing uv layers where name of uv layout is key and materials that misses it are values if uv_lay_name not in missing_uv_layers: missing_uv_layers[uv_lay_name] = [] if pim_mat_name not in missing_uv_layers[uv_lay_name]: # add material if not already there missing_uv_layers[uv_lay_name].append(pim_mat_name) else: uv_lay = mesh.uv_layers[uv_lay_name] uvs.append(_change_to_scs_uv_coordinates(uv_lay.data[loop_i].uv)) aliases = [] for alias_index in tex_coord_alias_map[uv_lay_name]: aliases.append("_TEXCOORD" + str(alias_index)) uvs_aliases.append(aliases) # 4. vcol -> vcol_lay = mesh.vertex_colors[0].data; vcol_lay[loop_i].color vcol_multi = mesh_obj.data.scs_props.vertex_color_multiplier if _MESH_consts.default_vcol not in mesh.vertex_colors: # get RGB component of RGBA vcol = (1.0,) * 3 missing_vcolor = True else: color = mesh.vertex_colors[_MESH_consts.default_vcol].data[loop_i].color vcol = (color[0] * 2 * vcol_multi, color[1] * 2 * vcol_multi, color[2] * 2 * vcol_multi) if _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix not in mesh.vertex_colors: # get A component of RGBA vcol += (1.0,) missing_vcolor_a = True else: alpha = mesh.vertex_colors[_MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix].data[loop_i].color vcol += ((alpha[0] + alpha[1] + alpha[2]) / 3.0 * 2 * vcol_multi,) # take avg of colors for alpha # 5. tangent -> loop.tangent; loop.bitangent_sign -> calc_tangents() has to be called before if pim_materials[pim_mat_name].get_nmap_uv_name(): # calculate tangents only if needed tangent = tuple(nor_transf_mat * loop.tangent) tangent = tuple(Vector(tangent).normalized()) tangent = (tangent[0], tangent[1], tangent[2], loop.bitangent_sign) else: tangent = None # save internal vertex index to array to be able to construct triangle afterwards piece_vert_index = mesh_piece.add_vertex(vert_i, position, normal, uvs, uvs_aliases, vcol, tangent) piece_vert_indices.append(piece_vert_index) if is_skin_used: # get skinning data for vertex and save it to skin stream bone_weights = {} for v_group_entry in mesh.vertices[vert_i].groups: bone_indx = bones.get_bone_index(vert_groups[v_group_entry.group].name) bone_weight = v_group_entry.weight # proceed only if bone exists in our armature if bone_indx != -1: bone_weights[bone_indx] = bone_weight skin_entry = SkinStream.Entry(mesh_piece.get_index(), piece_vert_index, position, bone_weights) skin_stream.add_entry(skin_entry) # save to terrain points storage if present in correct vertex group for group in mesh.vertices[vert_i].groups: curr_vg_name = mesh_obj.vertex_groups[group.group].name # if vertex group name doesn't match prescribed one ignore this vertex group if not match(_OP_consts.TerrainPoints.vg_name_regex, curr_vg_name): continue # if node index is not in bounds ignore this vertex group node_index = int(curr_vg_name[-1]) if node_index >= _PL_consts.PREFAB_NODE_COUNT_MAX: continue # if no variants defined add globally (without variant block) if len(root_object.scs_object_variant_inventory) == 0: used_terrain_points.add(-1, node_index, position, normal) continue # finally iterate variant parts entries to find where this part is included # and add terrain points to transitional structure # # NOTE: variant index is donated by direct order of variants in inventory # so export in PIT has to use the same order otherwise variant # indices will be misplaced for variant_i, variant in enumerate(root_object.scs_object_variant_inventory): used_terrain_points.ensure_entry(variant_i, node_index) for variant_part in variant.parts: if variant_part.name == mesh_obj.scs_props.scs_part and variant_part.include: used_terrain_points.add(variant_i, node_index, position, normal) break mesh_piece.add_triangle(tuple(piece_vert_indices[::-1])) # invert indices because of normals flip # free normals calculations _mesh_utils.cleanup_mesh(mesh) # create part if it doesn't exists yet part_name = mesh_obj.scs_props.scs_part if part_name not in pim_parts: pim_parts[part_name] = Part(part_name) mesh_pieces = mesh_pieces.values() for piece in mesh_pieces: # put pieces of current mesh to global list pim_pieces.append(piece) # add pieces of current mesh to part pim_part = pim_parts[part_name] pim_part.add_piece(piece) # report missing data for each object if len(missing_uv_layers) > 0: for uv_lay_name in missing_uv_layers: lprint("W Object '%s' is missing UV layer '%s' specified by materials: %s\n", (mesh_obj.name, uv_lay_name, missing_uv_layers[uv_lay_name])) if missing_vcolor: lprint("W Object %r is missing vertex color layer with name %r! Default RGB color will be exported (0.5, 0.5, 0.5)!", (mesh_obj.name, _MESH_consts.default_vcol)) if missing_vcolor_a: lprint("W Object %r is missing vertex color alpha layer with name %r! Default alpha will be exported (0.5)", (mesh_obj.name, _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix)) # report missing data for whole model if len(missing_mappings_data) > 0: for material_name in missing_mappings_data: lprint("W Material '%s' is missing mapping data! Objects using it are exported with default UV:\n\t %s", (material_name, list(missing_mappings_data[material_name].keys()))) if len(objects_with_default_material) > 0: lprint("W Some objects don't use any material. Default material and UV mapping is used on them:\n\t %s", (list(objects_with_default_material.keys()),)) # create locators data sections for loc_obj in model_locators: pos, qua, sca = _get_scs_transformation_components(root_object.matrix_world.inverted() * loc_obj.matrix_world) if sca[0] * sca[1] * sca[2] < 0: lprint("W Model locator %r inside SCS Root Object %r not exported because of invalid scale.\n\t " + "Model locators must have positive scale!", (loc_obj.name, root_object.name)) continue name = _name_utils.tokenize_name(loc_obj.name) hookup_string = loc_obj.scs_props.locator_model_hookup if hookup_string != "" and ":" in hookup_string: hookup = hookup_string.split(':', 1)[1].strip() else: if hookup_string != "": lprint("W The Hookup %r has no expected value!", hookup_string) hookup = None # create locator object for export locator = Locator(len(pim_locators), name, hookup) locator.set_position(pos) locator.set_rotation(qua) locator.set_scale(sca) # create part if it doesn't exists yet part_name = loc_obj.scs_props.scs_part if part_name not in pim_parts: pim_parts[part_name] = Part(part_name) # add locator to part pim_part = pim_parts[part_name] pim_part.add_locator(locator) # add locator to locator list pim_locators.append(locator) # create container pim_container = [pim_header.get_as_section(), pim_global.get_as_section()] for mat_name in pim_materials: pim_container.append(pim_materials[mat_name].get_as_section()) for pim_piece in pim_pieces: pim_container.append(pim_piece.get_as_section()) for part_name in used_parts.get_as_list(): # export all parts even empty ones gathered from PIC and PIP if part_name in pim_parts: pim_container.append(pim_parts[part_name].get_as_section()) else: pim_container.append(Part(part_name).get_as_section()) for locator in pim_locators: pim_container.append(locator.get_as_section()) if is_skin_used: pim_container.append(bones.get_as_section()) pim_container.append(skin.get_as_section()) # write to file ind = " " pim_filepath = os.path.join(dirpath, root_object.name + ".pim") return _pix_container.write_data_to_file(pim_container, pim_filepath, ind)
def execute(dirpath, name_suffix, root_object, armature_object, skeleton_filepath, mesh_objects, model_locators, used_parts, used_materials, used_bones, used_terrain_points): """Executes export of PIM file for given data. :param dirpath: directory path for PIM file :type dirpath: str :param name_suffix: file name suffix :type name_suffix: str :param root_object: Blender SCS Root empty object :type root_object: bpy.types.Object :param armature_object: Blender Aramture object belonging to this SCS game object :type armature_object: bpy.types.Object :param skeleton_filepath: relative file path of PIS file :type skeleton_filepath: str :param mesh_objects: all the meshes which should be exported for current game object :type mesh_objects: list of bpy.types.Object :param model_locators: all Blender empty objecs which represents model locators and should be exported for current game object :type model_locators: list of bpy.types.Object :param used_parts: parts transitional structure for storing used parts inside this PIM export :type used_parts: io_scs_tools.exp.transition_structs.parts.PartsTrans :param used_materials: materials transitional structure for storing used materials inside this PIM export :type used_materials: io_scs_tools.exp.transition_structs.materials.MaterialsTrans :param used_bones: bones transitional structure for storing used bones inside this PIM export :type used_bones: io_scs_tools.exp.transition_structs.bones.BonesTrans :param used_terrain_points: terrain points transitional structure for storing used terrain points :type used_terrain_points: io_scs_tools.exp.transition_structs.terrain_points.TerrainPntsTrans :return: True if export was successfull; False otherwise :rtype: bool """ print("\n************************************") print("** SCS PIM Exporter **") print("** (c)2017 SCS Software **") print("************************************\n") scs_globals = _get_scs_globals() format_version = 5 is_skin_used = (armature_object and root_object.scs_props.scs_root_animated == "anim") pim_header = Header("", format_version, root_object.name) pim_global = Globall(used_parts.count(), skeleton_filepath) pim_materials = collections.OrderedDict( ) # dict of Material class instances representing used materials """:type: dict[str, Material]""" pim_pieces = [] # list of Piece class instances representing mesh pieces """:type: list[Piece]""" pim_parts = {} # list of Part class instances representing used parts """:type: dict[str, Part]""" pim_locators = [ ] # list of Locator class instances representing model locators """:type: list[Locator]""" objects_with_default_material = { } # stores object names which has no material set missing_mappings_data = { } # indicates if material doesn't have set any uv layer for export invalid_objects_for_tangents = set( ) # stores object names which tangents calculation failed because of N-gons existence bones = skin = skin_stream = None if is_skin_used: invalid_bone_names = set( ) # set for saving bones with invalid names, they are used for reporting to user # create bones data section bones = Bones() for bone in armature_object.data.bones: bones.add_bone(bone.name) used_bones.add(bone.name) # do bones name checks if _name_utils.tokenize_name(bone.name) != bone.name: invalid_bone_names.add(bone.name) # create skin data section skin_stream = SkinStream(SkinStream.Types.POSITION) skin = Skin(skin_stream) # report invalid bone names if len(invalid_bone_names) > 0: lprint( "W Invalid bone names detected, max. length of valid bone name is 12 and must consists from [a-z, 0-9 and _ ] characters.\n\t " "Conversion will generalize names, however expect problems by re-import! List of invalid bone names for %r:\n\t " "%r", (armature_object.name, list(invalid_bone_names))) # create mesh object data sections for mesh_obj in mesh_objects: lprint("I Preparing mesh object: %r ...", (mesh_obj.name, )) vert_groups = mesh_obj.vertex_groups mesh_pieces = collections.OrderedDict() # calculate faces flip state from all ancestors of current object scale_sign = 1 parent = mesh_obj while parent and parent.scs_props.empty_object_type != "SCS_Root": for scale_axis in parent.scale: scale_sign *= scale_axis parent = parent.parent face_flip = scale_sign < 0 # calculate transformation matrix for current object (root object transforms are always subtracted!) mesh_transf_mat = root_object.matrix_world.inverted( ) * mesh_obj.matrix_world """:type: mathutils.Matrix""" # calculate vertex position transformation matrix for this object pos_transf_mat = (Matrix.Scale(scs_globals.export_scale, 4) * _scs_to_blend_matrix().inverted()) """:type: mathutils.Matrix""" # calculate vertex normals transformation matrix for this object # NOTE: as normals will be read from none export prepared mesh we have to add rotation and scale from mesh transformation matrix _, rot, scale = mesh_transf_mat.decompose() scale_matrix_x = Matrix.Scale(scale.x, 3, Vector((1, 0, 0))).to_4x4() scale_matrix_y = Matrix.Scale(scale.y, 3, Vector((0, 1, 0))).to_4x4() scale_matrix_z = Matrix.Scale(scale.z, 3, Vector((0, 0, 1))).to_4x4() nor_transf_mat = (_scs_to_blend_matrix().inverted() * rot.to_matrix().to_4x4() * scale_matrix_x * scale_matrix_y * scale_matrix_z) """:type: mathutils.Matrix""" tangent_transf_mat = _scs_to_blend_matrix().inverted() """:type: mathutils.Matrix""" # get initial mesh & extra copy of the mesh for normals mesh = _object_utils.get_mesh(mesh_obj) mesh_for_normals = mesh.copy() # prepare meshes faces_mapping = _mesh_utils.bm_prepare_mesh_for_export( mesh, mesh_transf_mat, triangulate=True) mesh_for_normals.calc_normals_split() missing_uv_layers = { } # stores missing uvs specified by materials of this object missing_vcolor = False # indicates if object is missing vertex color layer missing_vcolor_a = False # indicates if object is missing vertex color alpha layer missing_skinned_verts = set( ) # indicates if object is having only partial skin, which is not allowed in our models has_unnormalized_skin = False # indicates if object has vertices which bones weight sum is smaller then one for poly in mesh.polygons: mat_index = poly.material_index # check material existence and decide what material name and effect has to be used if mat_index >= len( mesh_obj.material_slots ) or mesh_obj.material_slots[ mat_index].material is None: # no material or invalid index material = None pim_mat_name = "_default_material_-_default_settings_" pim_mat_effect = "eut2.dif" objects_with_default_material[mesh_obj.name] = 1 else: material = mesh_obj.material_slots[mat_index].material pim_mat_name = material.name pim_mat_effect = material.scs_props.mat_effect_name # create new pim material if material with that name doesn't yet exists if pim_mat_name not in pim_materials: pim_material = Material(len(pim_materials), pim_mat_name, pim_mat_effect, material) pim_materials[pim_mat_name] = pim_material used_materials.add(pim_mat_name, material) # create new piece if piece with this material doesn't exists yet -> split to pieces by material if pim_mat_name not in mesh_pieces: mesh_pieces[pim_mat_name] = Piece( len(pim_pieces) + len(mesh_pieces), pim_materials[pim_mat_name]) nmap_uv_layer = pim_materials[pim_mat_name].get_nmap_uv_name() # if there is uv layer used for normal maps and that uv layer exists on mesh then calculate tangents on it otherwise report warning if nmap_uv_layer: if nmap_uv_layer in mesh.uv_layers: try: mesh.calc_tangents(uvmap=nmap_uv_layer) except RuntimeError: invalid_objects_for_tangents.add(mesh_obj.name) else: lprint( "W Unable to calculate normal map tangents for object %r,\n\t " "as it's missing UV layer with name: %r, expect problems!", (mesh_obj.name, nmap_uv_layer)) mesh_piece = mesh_pieces[pim_mat_name] """:type: Piece""" # get polygon loop indices for normals depending on mapped triangulated face if poly.index in faces_mapping: normals_poly_loop_indices = list(mesh_for_normals.polygons[ faces_mapping[poly.index]].loop_indices) else: normals_poly_loop_indices = list( mesh_for_normals.polygons[poly.index].loop_indices) # vertex data triangle_pvert_indices = [ ] # storing vertex indices for this polygon triangle for loop_i in poly.loop_indices: loop = mesh.loops[loop_i] """:type: bpy.types.MeshLoop""" vert_i = loop.vertex_index # get data of current vertex # 1. position -> mesh.vertices[loop.vertex_index].co position = tuple(pos_transf_mat * mesh.vertices[vert_i].co) # 2. normal -> mesh_for_normals.loops[loop_i].normal -> calc_normals_split() has to be called before normal = (0, 0, 0) for i, normals_poly_loop_i in enumerate( normals_poly_loop_indices): normal_loop = mesh_for_normals.loops[normals_poly_loop_i] # match by vertex index as triangle will for sure have three unique vertices if vert_i == normal_loop.vertex_index: normal = nor_transf_mat * normal_loop.normal normal = tuple(Vector(normal).normalized()) del normals_poly_loop_indices[i] break else: lprint( "E Normals data gathering went wrong, expect corrupted mesh! Shouldn't happen..." ) # 3. uvs -> uv_lay = mesh.uv_layers[0].data; uv_lay[loop_i].uv uvs = [] uvs_aliases = [] tex_coord_alias_map = pim_materials[ pim_mat_name].get_tex_coord_map() if len( tex_coord_alias_map ) < 1: # no textures or none uses uv mapping in current material effect uvs.append((0.0, 0.0)) uvs_aliases.append(["_TEXCOORD0"]) # report missing mappings only on actual materials with textures using uv mappings if material and pim_materials[ pim_mat_name].uses_textures_with_uv(): if material.name not in missing_mappings_data: missing_mappings_data[material.name] = {} if mesh_obj.name not in missing_mappings_data[ material.name]: missing_mappings_data[material.name][ mesh_obj.name] = 1 else: for uv_lay_name in tex_coord_alias_map: if uv_lay_name not in mesh.uv_layers: uvs.append((0.0, 0.0)) # properly report missing uv layers where name of uv layout is key and materials that misses it are values if uv_lay_name not in missing_uv_layers: missing_uv_layers[uv_lay_name] = [] if pim_mat_name not in missing_uv_layers[ uv_lay_name]: # add material if not already there missing_uv_layers[uv_lay_name].append( pim_mat_name) else: uv_lay = mesh.uv_layers[uv_lay_name] uvs.append( _change_to_scs_uv_coordinates( uv_lay.data[loop_i].uv)) aliases = [] for alias_index in tex_coord_alias_map[uv_lay_name]: aliases.append("_TEXCOORD" + str(alias_index)) uvs_aliases.append(aliases) # 4. vcol -> vcol_lay = mesh.vertex_colors[0].data; vcol_lay[loop_i].color vcol_multi = mesh_obj.data.scs_props.vertex_color_multiplier if _MESH_consts.default_vcol not in mesh.vertex_colors: # get RGB component of RGBA vcol = (1.0, ) * 3 missing_vcolor = True else: color = mesh.vertex_colors[ _MESH_consts.default_vcol].data[loop_i].color vcol = (color[0] * 2 * vcol_multi, color[1] * 2 * vcol_multi, color[2] * 2 * vcol_multi) if _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix not in mesh.vertex_colors: # get A component of RGBA vcol += (1.0, ) missing_vcolor_a = True else: alpha = mesh.vertex_colors[ _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix].data[loop_i].color vcol += ((alpha[0] + alpha[1] + alpha[2]) / 3.0 * 2 * vcol_multi, ) # take avg of colors for alpha # 5. tangent -> loop.tangent; loop.bitangent_sign -> calc_tangents() has to be called before if pim_materials[pim_mat_name].get_nmap_uv_name( ): # calculate tangents only if needed tangent = tuple(tangent_transf_mat * loop.tangent) tangent = tuple(Vector(tangent).normalized()) tangent = (tangent[0], tangent[1], tangent[2], loop.bitangent_sign) else: tangent = None # 6. There we go, vertex data collected! Now create internal vertex index, for triangle and skin stream construction piece_vert_index = mesh_piece.add_vertex( vert_i, position, normal, uvs, uvs_aliases, vcol, tangent) # 7. Add vertex to triangle creation list triangle_pvert_indices.append(piece_vert_index) # 8. Get skinning data for vertex and save it to skin stream if is_skin_used: bone_weights = {} bone_weights_sum = 0 for v_group_entry in mesh.vertices[vert_i].groups: bone_indx = bones.get_bone_index( vert_groups[v_group_entry.group].name) bone_weight = v_group_entry.weight # proceed only if bone exists in our armature if bone_indx != -1: bone_weights[bone_indx] = bone_weight bone_weights_sum += bone_weight skin_entry = SkinStream.Entry(mesh_piece.get_index(), piece_vert_index, position, bone_weights, bone_weights_sum) skin_stream.add_entry(skin_entry) # report un-skinned vertices (no bones or zero sum weight) or badly skinned model if bone_weights_sum <= 0: missing_skinned_verts.add(vert_i) elif bone_weights_sum < 1: has_unnormalized_skin = True # Addition - Terrain Points: save vertex to terrain points storage, if present in correct vertex group for group in mesh.vertices[vert_i].groups: # if current object doesn't have vertex group found in mesh data, then ignore that group # This can happen if multiple objects are using same mesh and # some of them have vertex groups, but others not. if group.group >= len(mesh_obj.vertex_groups): continue curr_vg_name = mesh_obj.vertex_groups[group.group].name # if vertex group name doesn't match prescribed one ignore this vertex group if not match(_OP_consts.TerrainPoints.vg_name_regex, curr_vg_name): continue # if node index is not in bounds ignore this vertex group node_index = int(curr_vg_name[-1]) if node_index >= _PL_consts.PREFAB_NODE_COUNT_MAX: continue # if no variants defined add globally (without variant block) if len(root_object.scs_object_variant_inventory) == 0: used_terrain_points.add(-1, node_index, position, normal) continue # finally iterate variant parts entries to find where this part is included # and add terrain points to transitional structure # # NOTE: variant index is donated by direct order of variants in inventory # so export in PIT has to use the same order otherwise variant # indices will be misplaced for variant_i, variant in enumerate( root_object.scs_object_variant_inventory): used_terrain_points.ensure_entry(variant_i, node_index) for variant_part in variant.parts: if variant_part.name == mesh_obj.scs_props.scs_part and variant_part.include: used_terrain_points.add( variant_i, node_index, position, normal) break # triangles if face_flip: mesh_piece.add_triangle(tuple(triangle_pvert_indices)) else: mesh_piece.add_triangle( tuple(triangle_pvert_indices[::-1] )) # yep it's weird but it simply works vice versa # free normals calculations _mesh_utils.cleanup_mesh(mesh) _mesh_utils.cleanup_mesh(mesh_for_normals) # create part if it doesn't exists yet part_name = used_parts.ensure_part(mesh_obj) if part_name not in pim_parts: pim_parts[part_name] = Part(part_name) mesh_pieces = mesh_pieces.values() for piece in mesh_pieces: # now as pieces are created we can check for it's flaws if piece.get_vertex_count() > 65536: lprint( "E Object %r has exceeded maximum vertex count (65536), expect errors during conversion!", (mesh_obj.name, )) # put pieces of current mesh to global list pim_pieces.append(piece) # add pieces of current mesh to part pim_part = pim_parts[part_name] pim_part.add_piece(piece) # report missing data for each object if len(missing_uv_layers) > 0: for uv_lay_name in missing_uv_layers: lprint( "W Object %r is missing UV layer %r specified by materials: %r", (mesh_obj.name, uv_lay_name, missing_uv_layers[uv_lay_name])) if missing_vcolor: lprint( "W Object %r is missing vertex color layer with name %r! Default RGB color will be exported (0.5, 0.5, 0.5)!", (mesh_obj.name, _MESH_consts.default_vcol)) if missing_vcolor_a: lprint( "W Object %r is missing vertex color alpha layer with name %r! Default alpha will be exported (0.5)", (mesh_obj.name, _MESH_consts.default_vcol + _MESH_consts.vcol_a_suffix)) if len(missing_skinned_verts) > 0: lprint( "E Object %r from SCS Root %r has %s vertices which are not skinned to any bone, expect errors during conversion!", (mesh_obj.name, root_object.name, len(missing_skinned_verts))) if has_unnormalized_skin: lprint( "W Object %r from SCS Root %r has unormalized skinning, exporting normalized weights!\n\t " "You can normalize weights by selecting object & executing 'Normalize All Vertex Groups'.", (mesh_obj.name, root_object.name)) # report missing data for whole model if len(missing_mappings_data) > 0: for material_name in missing_mappings_data: lprint( "W Material '%s' is missing mapping data! Objects using it are exported with default UV:\n\t %s", (material_name, list(missing_mappings_data[material_name].keys()))) if len(objects_with_default_material) > 0: lprint( "W Some objects don't use any material. Default material and UV mapping is used on them:\n\t %s", (list(objects_with_default_material.keys()), )) if len(invalid_objects_for_tangents) > 0: lprint( "E N-gons present in some objects, thus normal map tangent calculation failed.\n\t " "Visualization in game will be distorted for this objects:\n\t %s", (list(invalid_objects_for_tangents), )) # create locators data sections for loc_obj in model_locators: pos, qua, sca = _get_scs_transformation_components( root_object.matrix_world.inverted() * loc_obj.matrix_world) if sca[0] * sca[1] * sca[2] < 0: lprint( "W Model locator %r inside SCS Root Object %r not exported because of invalid scale.\n\t " + "Model locators must have positive scale!", (loc_obj.name, root_object.name)) continue name = _name_utils.tokenize_name(loc_obj.name) hookup_string = loc_obj.scs_props.locator_model_hookup hookup_id = None if hookup_string != "": hookup_id = _hookup_name_to_hookup_id(hookup_string) if hookup_id is None: lprint("W Model locator %r has unexpected hookup value %r.", (loc_obj.name, loc_obj.scs_props.locator_model_hookup)) # create locator object for export locator = Locator(len(pim_locators), name, hookup_id) locator.set_position(pos) locator.set_rotation(qua) locator.set_scale(sca) # create part if it doesn't exists yet part_name = used_parts.ensure_part(loc_obj) if part_name not in pim_parts: pim_parts[part_name] = Part(part_name) # add locator to part pim_part = pim_parts[part_name] pim_part.add_locator(locator) # add locator to locator list pim_locators.append(locator) # create container pim_container = [pim_header.get_as_section(), pim_global.get_as_section()] for mat_name in pim_materials: pim_container.append(pim_materials[mat_name].get_as_section()) for pim_piece in pim_pieces: pim_container.append(pim_piece.get_as_section()) for part_name in used_parts.get_as_list(): # export all parts even empty ones used only in PIC and/or PIP if part_name in pim_parts: pim_container.append(pim_parts[part_name].get_as_section()) else: pim_container.append(Part(part_name).get_as_section()) for locator in pim_locators: pim_container.append(locator.get_as_section()) if is_skin_used: pim_container.append(bones.get_as_section()) pim_container.append(skin.get_as_section()) # write to file ind = " " pim_filepath = os.path.join(dirpath, root_object.name + ".pim" + name_suffix) return _pix_container.write_data_to_file(pim_container, pim_filepath, ind)
def _fill_nav_curve_sections(nav_point_list, offset_matrix): """Fills up (navigation) "Curve" sections.""" _INDEX = "index" _START = "start" _END = "end" _PREV_CURVES = "prev_curves" _NEXT_CURVES = "next_curves" curves_dict = _connections_group_wrapper.get_curves(nav_point_list, _INDEX, _START, _END, _NEXT_CURVES, _PREV_CURVES) # prepare empty sections for curves so it can be later placed directly on right index sections = [_SectionData("Dummy")] * len(curves_dict) for connection_key in curves_dict.keys(): curve = curves_dict[connection_key] start_loc = bpy.data.objects[curve[_START]] end_loc = bpy.data.objects[curve[_END]] section = _SectionData("Curve") section.props.append(("Index", curve[_INDEX])) section.props.append(("Name", _name_utils.tokenize_name(curve[_START]))) section.props.append(("", "")) section.props.append(("#", "Flags:")) section.props.append(("Flags", _get_np_flags(start_loc, end_loc))) section.props.append(("", "")) section.props.append(("LeadsToNodes", 0)) # TODO SIMON: make it happen when you know what it means speed_limit = _get_np_speed_limit(start_loc) if speed_limit: section.props.append(("", "")) section.props.append(("SpeedLimit", ["&", ])) traffic_light = _get_np_traffic_light_id(start_loc) if traffic_light != -1: section.props.append(("", "")) section.props.append(("TrafficLightID", )) section.props.append(("", "")) section.props.append(("NextCurves", ["ii", _get_np_prev_next_curves(curves_dict, curve[_NEXT_CURVES], _INDEX)])) section.props.append(("PrevCurves", ["ii", _get_np_prev_next_curves(curves_dict, curve[_PREV_CURVES], _INDEX)])) section.props.append(("", "")) section.props.append(("Length", ["&", (_get_np_length(start_loc, end_loc), )])) section.props.append(("", "")) bezier_section = _SectionData("Bezier") # START NODE start_section = _SectionData("Start") loc = _convert_utils.convert_location_to_scs(start_loc.location, offset_matrix) start_section.props.append(("Position", ["&&", loc])) direction_vector = _convert_utils.scs_to_blend_matrix().inverted() * (start_loc.matrix_world.to_quaternion() * Vector((0, 1, 0))) start_section.props.append(("Direction", ["&&", (direction_vector[0], direction_vector[1], direction_vector[2])])) # END NODE end_section = _SectionData("End") loc = _convert_utils.convert_location_to_scs(end_loc.location, offset_matrix) end_section.props.append(("Position", ["&&", loc])) direction_vector = _convert_utils.scs_to_blend_matrix().inverted() * (end_loc.matrix_world.to_quaternion() * Vector((0, 1, 0))) end_section.props.append(("Direction", ["&&", (direction_vector[0], direction_vector[1], direction_vector[2])])) bezier_section.sections.append(start_section) bezier_section.sections.append(end_section) section.sections.append(bezier_section) # make sure that current section is placed on right place sections[curve[_INDEX]] = section return sections
def _fill_nav_curve_sections(nav_point_list, offset_matrix): """Fills up (navigation) "Curve" sections.""" _INDEX = "index" _START = "start" _END = "end" _PREV_CURVES = "prev_curves" _NEXT_CURVES = "next_curves" curves_dict = _connections_group_wrapper.get_curves( nav_point_list, _INDEX, _START, _END, _NEXT_CURVES, _PREV_CURVES) # prepare empty sections for curves so it can be later placed directly on right index sections = [_SectionData("Dummy")] * len(curves_dict) for connection_key in curves_dict.keys(): curve = curves_dict[connection_key] start_loc = bpy.data.objects[curve[_START]] end_loc = bpy.data.objects[curve[_END]] section = _SectionData("Curve") section.props.append(("Index", curve[_INDEX])) section.props.append( ("Name", _name_utils.tokenize_name(curve[_START]))) section.props.append(("", "")) section.props.append(("#", "Flags:")) section.props.append(("Flags", _get_np_flags(start_loc, end_loc))) section.props.append(("", "")) section.props.append( ("LeadsToNodes", 0)) # TODO SIMON: make it happen when you know what it means speed_limit = _get_np_speed_limit(start_loc) if speed_limit: section.props.append(("", "")) section.props.append(("SpeedLimit", [ "&", ])) traffic_light = _get_np_traffic_light_id(start_loc) if traffic_light != -1: section.props.append(("", "")) section.props.append(("TrafficLightID", )) section.props.append(("", "")) section.props.append(("NextCurves", [ "ii", _get_np_prev_next_curves(curves_dict, curve[_NEXT_CURVES], _INDEX) ])) section.props.append(("PrevCurves", [ "ii", _get_np_prev_next_curves(curves_dict, curve[_PREV_CURVES], _INDEX) ])) section.props.append(("", "")) section.props.append( ("Length", ["&", (_get_np_length(start_loc, end_loc), )])) section.props.append(("", "")) bezier_section = _SectionData("Bezier") # START NODE start_section = _SectionData("Start") loc = _convert_utils.convert_location_to_scs(start_loc.location, offset_matrix) start_section.props.append(("Position", ["&&", loc])) direction_vector = _convert_utils.scs_to_blend_matrix().inverted() * ( start_loc.matrix_world.to_quaternion() * Vector((0, 1, 0))) start_section.props.append(("Direction", [ "&&", (direction_vector[0], direction_vector[1], direction_vector[2]) ])) # END NODE end_section = _SectionData("End") loc = _convert_utils.convert_location_to_scs(end_loc.location, offset_matrix) end_section.props.append(("Position", ["&&", loc])) direction_vector = _convert_utils.scs_to_blend_matrix().inverted() * ( end_loc.matrix_world.to_quaternion() * Vector((0, 1, 0))) end_section.props.append(("Direction", [ "&&", (direction_vector[0], direction_vector[1], direction_vector[2]) ])) bezier_section.sections.append(start_section) bezier_section.sections.append(end_section) section.sections.append(bezier_section) # make sure that current section is placed on right place sections[curve[_INDEX]] = section return sections
def execute(dirpath, root_object, mesh_objects, model_locators, used_parts, used_materials): """Executes export of PIM file for given data. :param dirpath: directory path for PIM file :type dirpath: str :param root_object: Blender SCS Root empty object :type root_object: bpy.types.Object :param mesh_objects: all the meshes which should be exported for current game object :type mesh_objects: list of bpy.types.Object :param model_locators: all Blender empty objecs which represents model locators and should be exported for current game object :type model_locators: list of bpy.types.Object :return: True if export was successfull; False otherwise :rtype: bool """ print("\n************************************") print("** SCS PIM Exporter **") print("** (c)2015 SCS Software **") print("************************************\n") scs_globals = _get_scs_globals() if scs_globals.output_type == "5": format_version = 5 format_type = "" else: format_version = 1 format_type = "def" pim_header = Header(format_type, format_version, root_object.name) pim_global = Globall(root_object.name + ".pis") pim_materials = collections.OrderedDict( ) # dict of Material class instances representing used materials """:type: dict of Material""" pim_pieces = [] # list of Piece class instances representing mesh pieces """:type: list of Piece""" pim_parts = collections.OrderedDict( ) # list of Part class instances representing used parts """:type: dict of Part""" pim_locators = [ ] # list of Locator class instances representing model locators """:type: list of Locator""" objects_with_default_material = { } # stores object names which has no material set missing_mappings_data = { } # indicates if material doesn't have set any uv layer for export # create mesh object data sections for mesh_obj in mesh_objects: mesh_pieces = collections.OrderedDict() # get initial mesh mesh = _object_utils.get_mesh(mesh_obj) _mesh_utils.bm_triangulate(mesh) mesh.calc_normals_split() # calculate transformation matrices for this object pos_transf_mat = (Matrix.Scale(scs_globals.export_scale, 4) * _scs_to_blend_matrix().inverted() * root_object.matrix_world.inverted() * mesh_obj.matrix_world) nor_transf_mat = ( _scs_to_blend_matrix().inverted() * root_object.matrix_world. inverted().to_quaternion().to_matrix().to_4x4() * mesh_obj.matrix_world.to_quaternion().to_matrix().to_4x4()) missing_uv_layers = { } # stores missing uvs specified by materials of this object missing_vcolor = False # indicates if object is missing vertex colors for poly in mesh.polygons: mat_index = poly.material_index # check material existance and decide what material name and effect has to be used if mat_index >= len( mesh_obj.material_slots ) or mesh_obj.material_slots[ mat_index].material is None: # no material or invalid index material = None pim_mat_name = "_not_existing_material_" pim_mat_effect = "eut2.dif" objects_with_default_material[mesh_obj.name] = 1 else: material = mesh_obj.material_slots[mat_index].material pim_mat_name = material.name pim_mat_effect = material.scs_props.mat_effect_name # create new pim material if material with that name doesn't yet exists if pim_mat_name not in pim_materials: pim_material = Material(len(pim_materials), pim_mat_name, pim_mat_effect, material) pim_materials[pim_mat_name] = pim_material used_materials.append(pim_mat_name) # create new piece if piece with this material doesn't exists yet -> split to pieces by material if pim_mat_name not in mesh_pieces: mesh_pieces[pim_mat_name] = Piece( len(pim_pieces) + len(mesh_pieces), pim_materials[pim_mat_name]) nmap_uv_layer = pim_materials[pim_mat_name].get_nmap_uv_name() if nmap_uv_layer: # if there is uv layer used for normal maps then calculate tangents on it mesh.calc_tangents(uvmap=nmap_uv_layer) mesh_piece = mesh_pieces[pim_mat_name] """:type: Piece""" piece_vert_indices = [] for loop_i in poly.loop_indices: loop = mesh.loops[loop_i] """:type: bpy.types.MeshLoop""" vert_i = loop.vertex_index # get data of current vertex # 1. position -> mesh.vertices[loop.vertex_index].co position = tuple(pos_transf_mat * mesh.vertices[vert_i].co) # 2. normal -> loop.normal -> calc_normals_split() has to be called before normal = nor_transf_mat * loop.normal normal = tuple(Vector(normal).normalized()) # 3. uvs -> uv_lay = mesh.uv_layers[0].data; uv_lay[loop_i].uv uvs = [] uvs_aliases = [] tex_coord_alias_map = pim_materials[ pim_mat_name].get_tex_coord_map() if len(tex_coord_alias_map ) < 1: # no textures for current material effect uvs.append((0.0, 0.0)) uvs_aliases.append(["_TEXCOORD0"]) # report missing mappings only on actual materials with texture entries if material and pim_materials[pim_mat_name].uses_textures( ): if material.name not in missing_mappings_data: missing_mappings_data[material.name] = {} if mesh_obj.name not in missing_mappings_data[ material.name]: missing_mappings_data[material.name][ mesh_obj.name] = 1 else: for uv_lay_name in tex_coord_alias_map: if uv_lay_name not in mesh.uv_layers: uvs.append((0.0, 0.0)) # properly report missing uv layers where name of uv layout is key and materials that misses it are values if uv_lay_name not in missing_uv_layers: missing_uv_layers[uv_lay_name] = [] if pim_mat_name not in missing_uv_layers[ uv_lay_name]: # add material if not already there missing_uv_layers[uv_lay_name].append( pim_mat_name) else: uv_lay = mesh.uv_layers[uv_lay_name] uvs.append( _change_to_scs_uv_coordinates( uv_lay.data[loop_i].uv)) aliases = [] for alias_index in tex_coord_alias_map[uv_lay_name]: aliases.append("_TEXCOORD" + str(alias_index)) uvs_aliases.append(aliases) # 4. vcol -> vcol_lay = mesh.vertex_colors[0].data; vcol_lay[loop_i].color if len(mesh.vertex_colors) < 1: vcol = (1.0, 1.0, 1.0, 1.0) missing_vcolor = True else: multiplier = mesh_obj.data.scs_props.vertex_color_multiplier color = mesh.vertex_colors[0].data[loop_i].color vcol = (color[0] * multiplier, color[1] * multiplier, color[2] * multiplier, 1.0) # 5. tangent -> loop.tangent; loop.bitangent_sign -> calc_tangents() has to be called before if pim_materials[pim_mat_name].get_nmap_uv_name( ): # calculate tangents only if needed tangent = tuple(nor_transf_mat * loop.tangent) tangent = tuple(Vector(tangent).normalized()) tangent = (tangent[0], tangent[1], tangent[2], loop.bitangent_sign) else: tangent = None # save internal vertex index to array to be able to construct triangle afterwards piece_vert_index = mesh_piece.add_vertex( vert_i, position, normal, uvs, uvs_aliases, vcol, tangent) piece_vert_indices.append(piece_vert_index) mesh_piece.add_triangle(tuple(piece_vert_indices[::-1]) ) # invert indices because of normals flip # create part if it doesn't exists yet part_name = mesh_obj.scs_props.scs_part if part_name not in pim_parts: pim_parts[part_name] = Part(part_name) used_parts[part_name] = 1 mesh_pieces = mesh_pieces.values() for piece in mesh_pieces: # put pieces of current mesh to global list pim_pieces.append(piece) # add pieces of current mesh to part pim_part = pim_parts[part_name] pim_part.add_piece(piece) # report missing data for each object if len(missing_uv_layers) > 0: for uv_lay_name in missing_uv_layers: lprint( "W Object '%s' is missing UV layer '%s' specified by materials: %s\n", (mesh_obj.name, uv_lay_name, missing_uv_layers[uv_lay_name])) if missing_vcolor: lprint( "W Object '%s' is missing vertex color layer! Default color will be exported (1, 1, 1, 1)!", (mesh_obj.name, )) # report mising data for whole model if len(missing_mappings_data) > 0: for material_name in missing_mappings_data: lprint( "W Material '%s' is missing mapping data! Objects using it are exported with default UV:\n\t %s", (material_name, list(missing_mappings_data[material_name].keys()))) if len(objects_with_default_material) > 0: lprint( "W Some objects don't use any material. Default material and UV mapping is used on them:\n\t %s", (list(objects_with_default_material.keys()), )) # create locators data sections for loc_obj in model_locators: name = _name_utils.tokenize_name(loc_obj.name) hookup_string = loc_obj.scs_props.locator_model_hookup if hookup_string != "" and ":" in hookup_string: hookup = hookup_string.split(':', 1)[1].strip() else: if hookup_string != "": lprint("W The Hookup %r has no expected value!", hookup_string) hookup = None pos, qua, sca = _get_scs_transformation_components( loc_obj.matrix_world) # create locator object for export locator = Locator(len(pim_locators), name, hookup) locator.set_position(pos) locator.set_rotation(qua) locator.set_scale(sca) # create part if it doesn't exists yet part_name = loc_obj.scs_props.scs_part if part_name not in pim_parts: pim_parts[part_name] = Part(part_name) used_parts[part_name] = 1 # add locator to part pim_part = pim_parts[part_name] pim_part.add_locator(locator) # add locator to locator list pim_locators.append(locator) # create container pim_container = [pim_header.get_as_section(), pim_global.get_as_section()] for mat_name in pim_materials: pim_container.append(pim_materials[mat_name].get_as_section()) for pim_piece in pim_pieces: pim_container.append(pim_piece.get_as_section()) for part_name in used_parts: pim_container.append(pim_parts[part_name].get_as_section()) for locator in pim_locators: pim_container.append(locator.get_as_section()) # write to file ind = " " pim_filepath = dirpath + os.sep + root_object.name + ".pim" return _pix_container.write_data_to_file(pim_container, pim_filepath, ind)