コード例 #1
0
ファイル: export_obj.py プロジェクト: Neconspictor/Euclid
def write_file(
        filepath,
        objects,
        scene,
        EXPORT_TRI=False,
        EXPORT_EDGES=False,
        EXPORT_SMOOTH_GROUPS=False,
        EXPORT_SMOOTH_GROUPS_BITFLAGS=False,
        EXPORT_NORMALS=False,
        EXPORT_UV=True,
        EXPORT_MTL=True,
        EXPORT_APPLY_MODIFIERS=True,
        EXPORT_BLEN_OBS=True,
        EXPORT_GROUP_BY_OB=False,
        EXPORT_GROUP_BY_MAT=False,
        EXPORT_KEEP_VERT_ORDER=False,
        EXPORT_POLYGROUPS=False,
        EXPORT_CURVE_AS_NURBS=True,
        EXPORT_GLOBAL_MATRIX=None,
        EXPORT_RELATIVE_PATH="",
        EXPORT_PATH_MODE='AUTO',
        progress=ProgressReport(),
):
    """
    Basic write function. The context and options must be already set
    This can be accessed externaly
    eg.
    write( 'c:\\test\\foobar.obj', Blender.Object.GetSelected() ) # Using default options.
    """
    if EXPORT_GLOBAL_MATRIX is None:
        EXPORT_GLOBAL_MATRIX = mathutils.Matrix()

    def veckey3d(v):
        return round(v.x, 4), round(v.y, 4), round(v.z, 4)

    def veckey2d(v):
        return round(v[0], 4), round(v[1], 4)

    def findVertexGroupName(face, vWeightMap):
        """
        Searches the vertexDict to see what groups is assigned to a given face.
        We use a frequency system in order to sort out the name because a given vetex can
        belong to two or more groups at the same time. To find the right name for the face
        we list all the possible vertex group names with their frequency and then sort by
        frequency in descend order. The top element is the one shared by the highest number
        of vertices is the face's group
        """
        weightDict = {}
        for vert_index in face.vertices:
            vWeights = vWeightMap[vert_index]
            for vGroupName, weight in vWeights:
                weightDict[vGroupName] = weightDict.get(vGroupName,
                                                        0.0) + weight

        if weightDict:
            return max((weight, vGroupName)
                       for vGroupName, weight in weightDict.items())[1]
        else:
            return '(null)'

    with ProgressReportSubstep(progress, 2, "OBJ Export path: %r" % filepath,
                               "OBJ Export Finished") as subprogress1:
        with open(filepath, "w", encoding="utf8", newline="\n") as f:
            fw = f.write

            # Write Header
            fw('# Blender v%s OBJ File: %r\n' %
               (bpy.app.version_string, os.path.basename(bpy.data.filepath)))
            fw('# www.blender.org\n')

            # Tell the obj file what material file to use.
            if EXPORT_MTL:
                mtlfilepath = os.path.splitext(filepath)[0] + ".mtl"
                # filepath can contain non utf8 chars, use repr
                fw('mtllib %s\n' % repr(os.path.basename(mtlfilepath))[1:-1])

            # Initialize totals, these are updated each object
            totverts = totuvco = totno = 1

            face_vert_index = 1

            # A Dict of Materials
            # (material.name, image.name):matname_imagename # matname_imagename has gaps removed.
            mtl_dict = {}
            # Used to reduce the usage of matname_texname materials, which can become annoying in case of
            # repeated exports/imports, yet keeping unique mat names per keys!
            # mtl_name: (material.name, image.name)
            mtl_rev_dict = {}

            copy_set = set()

            # Get all meshes
            subprogress1.enter_substeps(len(objects))
            for i, ob_main in enumerate(objects):
                # ignore dupli children
                if ob_main.parent and ob_main.parent.dupli_type in {
                        'VERTS', 'FACES'
                }:
                    # XXX
                    subprogress1.step("Ignoring %s, dupli child..." %
                                      ob_main.name)
                    continue

                obs = [(ob_main, ob_main.matrix_world)]
                if ob_main.dupli_type != 'NONE':
                    # XXX
                    print('creating dupli_list on', ob_main.name)
                    ob_main.dupli_list_create(scene)

                    obs += [(dob.object, dob.matrix)
                            for dob in ob_main.dupli_list]

                    # XXX debug print
                    print(ob_main.name, 'has', len(obs) - 1, 'dupli children')

                subprogress1.enter_substeps(len(obs))
                for ob, ob_mat in obs:
                    with ProgressReportSubstep(subprogress1,
                                               6) as subprogress2:
                        uv_unique_count = no_unique_count = 0

                        # Nurbs curve support
                        if EXPORT_CURVE_AS_NURBS and test_nurbs_compat(ob):
                            ob_mat = EXPORT_GLOBAL_MATRIX * ob_mat
                            totverts += write_nurb(fw, ob, ob_mat)
                            continue
                        # END NURBS

                        try:
                            me = ob.to_mesh(scene,
                                            EXPORT_APPLY_MODIFIERS,
                                            'PREVIEW',
                                            calc_tessface=False)
                        except RuntimeError:
                            me = None

                        if me is None:
                            continue

                        me.transform(EXPORT_GLOBAL_MATRIX * ob_mat)

                        if EXPORT_TRI:
                            # _must_ do this first since it re-allocs arrays
                            mesh_triangulate(me)

                        if EXPORT_UV:
                            faceuv = len(me.uv_textures) > 0
                            if faceuv:
                                uv_texture = me.uv_textures.active.data[:]
                                uv_layer = me.uv_layers.active.data[:]
                        else:
                            faceuv = False

                        me_verts = me.vertices[:]

                        # Make our own list so it can be sorted to reduce context switching
                        face_index_pairs = [
                            (face, index)
                            for index, face in enumerate(me.polygons)
                        ]
                        # faces = [ f for f in me.tessfaces ]

                        if EXPORT_EDGES:
                            edges = me.edges
                        else:
                            edges = []

                        if not (len(face_index_pairs) + len(edges) +
                                len(me.vertices)
                                ):  # Make sure there is something to write
                            # clean up
                            bpy.data.meshes.remove(me)
                            continue  # dont bother with this mesh.

                        if EXPORT_NORMALS and face_index_pairs:
                            me.calc_normals_split()
                            # No need to call me.free_normals_split later, as this mesh is deleted anyway!

                        loops = me.loops

                        if (EXPORT_SMOOTH_GROUPS
                                or EXPORT_SMOOTH_GROUPS_BITFLAGS
                            ) and face_index_pairs:
                            smooth_groups, smooth_groups_tot = me.calc_smooth_groups(
                                EXPORT_SMOOTH_GROUPS_BITFLAGS)
                            if smooth_groups_tot <= 1:
                                smooth_groups, smooth_groups_tot = (), 0
                        else:
                            smooth_groups, smooth_groups_tot = (), 0

                        materials = me.materials[:]
                        material_names = [
                            m.name if m else None for m in materials
                        ]

                        # avoid bad index errors
                        if not materials:
                            materials = [None]
                            material_names = [name_compat(None)]

                        # Sort by Material, then images
                        # so we dont over context switch in the obj file.
                        if EXPORT_KEEP_VERT_ORDER:
                            pass
                        else:
                            if faceuv:
                                if smooth_groups:
                                    sort_func = lambda a: (
                                        a[0].material_index,
                                        hash(uv_texture[a[1]].image
                                             ), smooth_groups[a[1]]
                                        if a[0].use_smooth else False)
                                else:
                                    sort_func = lambda a: (a[0].material_index,
                                                           hash(uv_texture[a[
                                                               1]].image), a[0]
                                                           .use_smooth)
                            elif len(materials) > 1:
                                if smooth_groups:
                                    sort_func = lambda a: (a[
                                        0].material_index, smooth_groups[a[
                                            1]] if a[0].use_smooth else False)
                                else:
                                    sort_func = lambda a: (a[0].material_index,
                                                           a[0].use_smooth)
                            else:
                                # no materials
                                if smooth_groups:
                                    sort_func = lambda a: smooth_groups[a[
                                        1] if a[0].use_smooth else False]
                                else:
                                    sort_func = lambda a: a[0].use_smooth

                            face_index_pairs.sort(key=sort_func)

                            del sort_func

                        # Set the default mat to no material and no image.
                        contextMat = 0, 0  # Can never be this, so we will label a new material the first chance we get.
                        contextSmooth = None  # Will either be true or false,  set bad to force initialization switch.

                        if EXPORT_BLEN_OBS or EXPORT_GROUP_BY_OB:
                            name1 = ob.name
                            name2 = ob.data.name
                            if name1 == name2:
                                obnamestring = name_compat(name1)
                            else:
                                obnamestring = '%s_%s' % (name_compat(name1),
                                                          name_compat(name2))

                            if EXPORT_BLEN_OBS:
                                fw('o %s\n' %
                                   obnamestring)  # Write Object name
                            else:  # if EXPORT_GROUP_BY_OB:
                                fw('g %s\n' % obnamestring)

                        subprogress2.step()

                        # Vert
                        for v in me_verts:
                            fw('v %.6f %.6f %.6f\n' % v.co[:])

                        subprogress2.step()

                        # UV
                        if faceuv:
                            # in case removing some of these dont get defined.
                            uv = f_index = uv_index = uv_key = uv_val = uv_ls = None

                            uv_face_mapping = [None] * len(face_index_pairs)

                            uv_dict = {}
                            uv_get = uv_dict.get
                            for f, f_index in face_index_pairs:
                                uv_ls = uv_face_mapping[f_index] = []
                                for uv_index, l_index in enumerate(
                                        f.loop_indices):
                                    uv = uv_layer[l_index].uv
                                    # include the vertex index in the key so we don't share UV's between vertices,
                                    # allowed by the OBJ spec but can cause issues for other importers, see: T47010.

                                    # this works too, shared UV's for all verts
                                    #~ uv_key = veckey2d(uv)
                                    uv_key = loops[
                                        l_index].vertex_index, veckey2d(uv)

                                    uv_val = uv_get(uv_key)
                                    if uv_val is None:
                                        uv_val = uv_dict[
                                            uv_key] = uv_unique_count
                                        fw('vt %.4f %.4f\n' % uv[:])
                                        uv_unique_count += 1
                                    uv_ls.append(uv_val)

                            del uv_dict, uv, f_index, uv_index, uv_ls, uv_get, uv_key, uv_val
                            # Only need uv_unique_count and uv_face_mapping

                        subprogress2.step()

                        # NORMAL, Smooth/Non smoothed.
                        if EXPORT_NORMALS:
                            no_key = no_val = None
                            normals_to_idx = {}
                            no_get = normals_to_idx.get
                            loops_to_normals = [0] * len(loops)
                            for f, f_index in face_index_pairs:
                                for l_idx in f.loop_indices:
                                    no_key = veckey3d(loops[l_idx].normal)
                                    no_val = no_get(no_key)
                                    if no_val is None:
                                        no_val = normals_to_idx[
                                            no_key] = no_unique_count
                                        fw('vn %.4f %.4f %.4f\n' % no_key)
                                        no_unique_count += 1
                                    loops_to_normals[l_idx] = no_val
                            del normals_to_idx, no_get, no_key, no_val
                        else:
                            loops_to_normals = []

                        if not faceuv:
                            f_image = None

                        subprogress2.step()

                        # XXX
                        if EXPORT_POLYGROUPS:
                            # Retrieve the list of vertex groups
                            vertGroupNames = ob.vertex_groups.keys()
                            if vertGroupNames:
                                currentVGroup = ''
                                # Create a dictionary keyed by face id and listing, for each vertex, the vertex groups it belongs to
                                vgroupsMap = [[]
                                              for _i in range(len(me_verts))]
                                for v_idx, v_ls in enumerate(vgroupsMap):
                                    v_ls[:] = [(vertGroupNames[g.group],
                                                g.weight)
                                               for g in me_verts[v_idx].groups]

                        for f, f_index in face_index_pairs:
                            f_smooth = f.use_smooth
                            if f_smooth and smooth_groups:
                                f_smooth = smooth_groups[f_index]
                            f_mat = min(f.material_index, len(materials) - 1)

                            if faceuv:
                                tface = uv_texture[f_index]
                                f_image = tface.image

                            # MAKE KEY
                            if faceuv and f_image:  # Object is always true.
                                key = material_names[f_mat], f_image.name
                            else:
                                key = material_names[
                                    f_mat], None  # No image, use None instead.

                            # Write the vertex group
                            if EXPORT_POLYGROUPS:
                                if vertGroupNames:
                                    # find what vertext group the face belongs to
                                    vgroup_of_face = findVertexGroupName(
                                        f, vgroupsMap)
                                    if vgroup_of_face != currentVGroup:
                                        currentVGroup = vgroup_of_face
                                        fw('g %s\n' % vgroup_of_face)

                            # CHECK FOR CONTEXT SWITCH
                            if key == contextMat:
                                pass  # Context already switched, dont do anything
                            else:
                                if key[0] is None and key[1] is None:
                                    # Write a null material, since we know the context has changed.
                                    if EXPORT_GROUP_BY_MAT:
                                        # can be mat_image or (null)
                                        fw("g %s_%s\n" %
                                           (name_compat(ob.name),
                                            name_compat(ob.data.name)))
                                    if EXPORT_MTL:
                                        fw("usemtl (null)\n")  # mat, image

                                else:
                                    mat_data = mtl_dict.get(key)
                                    if not mat_data:
                                        # First add to global dict so we can export to mtl
                                        # Then write mtl

                                        # Make a new names from the mat and image name,
                                        # converting any spaces to underscores with name_compat.

                                        # If none image dont bother adding it to the name
                                        # Try to avoid as much as possible adding texname (or other things)
                                        # to the mtl name (see [#32102])...
                                        mtl_name = "%s" % name_compat(key[0])
                                        if mtl_rev_dict.get(
                                                mtl_name,
                                                None) not in {key, None}:
                                            if key[1] is None:
                                                tmp_ext = "_NONE"
                                            else:
                                                tmp_ext = "_%s" % name_compat(
                                                    key[1])
                                            i = 0
                                            while mtl_rev_dict.get(
                                                    mtl_name + tmp_ext,
                                                    None) not in {key, None}:
                                                i += 1
                                                tmp_ext = "_%3d" % i
                                            mtl_name += tmp_ext
                                        mat_data = mtl_dict[
                                            key] = mtl_name, materials[
                                                f_mat], f_image
                                        mtl_rev_dict[mtl_name] = key

                                    if EXPORT_GROUP_BY_MAT:
                                        # can be mat_image or (null)
                                        fw("g %s_%s_%s\n" % (name_compat(
                                            ob.name), name_compat(
                                                ob.data.name), mat_data[0]))
                                    if EXPORT_MTL:
                                        fw("usemtl %s\n" % mat_data[0]
                                           )  # can be mat_image or (null)

                            contextMat = key
                            if f_smooth != contextSmooth:
                                if f_smooth:  # on now off
                                    if smooth_groups:
                                        f_smooth = smooth_groups[f_index]
                                        fw('s %d\n' % f_smooth)
                                    else:
                                        fw('s 1\n')
                                else:  # was off now on
                                    fw('s off\n')
                                contextSmooth = f_smooth

                            f_v = [(vi, me_verts[v_idx], l_idx)
                                   for vi, (v_idx, l_idx) in enumerate(
                                       zip(f.vertices, f.loop_indices))]

                            fw('f')
                            if faceuv:
                                if EXPORT_NORMALS:
                                    for vi, v, li in f_v:
                                        fw(" %d/%d/%d" % (
                                            totverts + v.index,
                                            totuvco +
                                            uv_face_mapping[f_index][vi],
                                            totno + loops_to_normals[li],
                                        ))  # vert, uv, normal
                                else:  # No Normals
                                    for vi, v, li in f_v:
                                        fw(" %d/%d" % (
                                            totverts + v.index,
                                            totuvco +
                                            uv_face_mapping[f_index][vi],
                                        ))  # vert, uv

                                face_vert_index += len(f_v)

                            else:  # No UV's
                                if EXPORT_NORMALS:
                                    for vi, v, li in f_v:
                                        fw(" %d//%d" %
                                           (totverts + v.index,
                                            totno + loops_to_normals[li]))
                                else:  # No Normals
                                    for vi, v, li in f_v:
                                        fw(" %d" % (totverts + v.index))

                            fw('\n')

                        subprogress2.step()

                        # Write edges.
                        if EXPORT_EDGES:
                            for ed in edges:
                                if ed.is_loose:
                                    fw('l %d %d\n' %
                                       (totverts + ed.vertices[0],
                                        totverts + ed.vertices[1]))

                        # Make the indices global rather then per mesh
                        totverts += len(me_verts)
                        totuvco += uv_unique_count
                        totno += no_unique_count

                        # clean up
                        bpy.data.meshes.remove(me)

                if ob_main.dupli_type != 'NONE':
                    ob_main.dupli_list_clear()

                subprogress1.leave_substeps(
                    "Finished writing geometry of '%s'." % ob_main.name)
            subprogress1.leave_substeps()

        subprogress1.step(
            "Finished exporting geometry, now exporting materials")

        # Now we have all our materials, save them
        if EXPORT_MTL:
            write_mtl(scene, mtlfilepath, EXPORT_PATH_MODE, copy_set, mtl_dict,
                      EXPORT_RELATIVE_PATH)

        # copy all collected files.
        bpy_extras.io_utils.path_reference_copy(copy_set)
コード例 #2
0
    def write_object(self, progress, ob, ob_mat):
        log = self.log
        fw = self.fw_objex
        scene = self.context.scene
        
        with ProgressReportSubstep(progress, 6) as subprogress2:

            if self.options['EXPORT_SKEL'] and ob.type == 'ARMATURE':
                if self.options['EXPORT_ANIM']:
                    objex_data = ob.data.objex_bonus
                    if objex_data.export_all_actions:
                        actions = bpy.data.actions
                    else:
                        if blender_version_compatibility.no_ID_PointerProperty:
                            actions = [bpy.data.actions[item.action] for item in objex_data.export_actions if item.action]
                        else:
                            actions = [item.action for item in objex_data.export_actions if item.action]
                else:
                    actions = []
                self.armatures.append((util.quote(ob.name), ob, ob_mat, actions))

            rigged_to_armature = ob.find_armature()

            apply_modifiers = self.options['APPLY_MODIFIERS']
            using_depsgraph = hasattr(self.context, 'evaluated_depsgraph_get') # True in 2.80+
            # disable armature deform modifiers
            user_show_armature_modifiers = []
            if apply_modifiers:
                found_armature_deform = False
                for modifier in ob.modifiers:
                    disable_modifier = False
                    if found_armature_deform and not self.options['APPLY_MODIFIERS_AFTER_ARMATURE_DEFORM']:
                        log.info('Skipped modifier {} which is down of the armature deform modifier', modifier.name)
                        disable_modifier = True
                    if modifier.type == 'ARMATURE' and rigged_to_armature and (
                        # don't apply armature deform (aka disable modifier) if armature is exported,
                        # or if the armature deform should be applied for armatures that aren't exported ("UNUSED")
                        rigged_to_armature in self.objects or not self.options['APPLY_UNUSED_ARMATURE_DEFORM']
                    ):
                        if modifier.object == rigged_to_armature:
                            if found_armature_deform:
                                log.warning('Found several armature deform modifiers on object {} using armature {}',
                                    ob.name, rigged_to_armature.name)
                            found_armature_deform = True
                            disable_modifier = True
                        else:
                            log.warning('Object {} was found to be rigged to {} but it also has an armature deform modifier using {}',
                                ob.name, rigged_to_armature.name, modifier.object.name if modifier.object else None)
                    modifier_show = None
                    if disable_modifier:
                        modifier_show = False
                    elif using_depsgraph:
                        modifier_show = modifier.show_render if self.options['APPLY_MODIFIERS_RENDER'] else modifier.show_viewport
                    if modifier_show is not None:
                        user_show_armature_modifiers.append((modifier, modifier.show_viewport, modifier.show_render))
                        modifier.show_viewport = modifier_show
                        modifier.show_render = modifier_show

            if using_depsgraph: # 2.80+
                depsgraph = self.context.evaluated_depsgraph_get()
                ob_for_convert = ob.evaluated_get(depsgraph) if apply_modifiers else ob.original
                del depsgraph
            else:
                ob_for_convert = None

            try:
                if not ob_for_convert: # < 2.80
                    me = ob.to_mesh(scene, apply_modifiers, calc_tessface=False,
                                    settings='RENDER' if self.options['APPLY_MODIFIERS_RENDER'] else 'PREVIEW')
                else: # 2.80+
                    # 421fixme should preserve_all_data_layers=True be used?
                    me = ob_for_convert.to_mesh()
            except RuntimeError:
                me = None
            finally:
                # restore modifiers properties
                for modifier, user_show_viewport, user_show_render in user_show_armature_modifiers:
                    modifier.show_viewport = user_show_viewport
                    modifier.show_render = user_show_render

            if me is None:
                return

            # _must_ do this before applying transformation, else tessellation may differ
            if self.options['TRIANGULATE']:
                if not all(len(polygon.vertices) == 3 for polygon in me.polygons):
                    notes = []
                    if any(modifier.type == 'TRIANGULATE' for modifier in ob.modifiers):
                        notes.append('mesh has a triangulate modifier')
                        if apply_modifiers:
                            notes.append('even after applying modifiers')
                        else:
                            notes.append('modifiers are not being applied (check export options)')
                        if rigged_to_armature and not self.options['APPLY_MODIFIERS_AFTER_ARMATURE_DEFORM']:
                            notes.append('mesh is rigged and only modifiers before armature deform are used\n'
                                '(move the triangulate modifier up, or check export options)')
                    else:
                        notes.append('mesh has no triangulate modifier')
                    log.warning('Mesh {} is not triangulated and will be triangulated automatically (for exporting only).\n'
                        'Preview accuracy (UVs, shading, vertex colors) is improved by using a triangulated mesh.'
                        '{}', ob.name, ''.join('\nNote: %s' % note for note in notes))
                    # _must_ do this first since it re-allocs arrays
                    mesh_triangulate(me)
                else:
                    log.debug('Skipped triangulating {}, mesh only has triangles', ob.name)

            me.transform(blender_version_compatibility.matmul(self.options['GLOBAL_MATRIX'], ob_mat))
            # If negative scaling, we have to invert the normals...
            if ob_mat.determinant() < 0.0:
                me.flip_normals()

            if self.options['EXPORT_UV']:
                if hasattr(me, 'uv_textures'): # < 2.80
                    has_uvs = len(me.uv_textures) > 0
                    has_uv_textures = has_uvs
                    if has_uv_textures:
                        uv_texture = me.uv_textures.active.data[:]
                else: # 2.80+
                    has_uvs = len(me.uv_layers) > 0
                    has_uv_textures = False
            else:
                has_uvs = False
            
            vertices = me.vertices[:]

            # Make our own list so it can be sorted to reduce context switching
            face_index_pairs = [(face, index) for index, face in enumerate(me.polygons)]
            # faces = [ f for f in me.tessfaces ]

            if not (len(face_index_pairs) + len(vertices)):  # Make sure there is something to write
                # clean up
                if not ob_for_convert: # < 2.80
                    bpy.data.meshes.remove(me)
                else: # 2.80+
                    ob_for_convert.to_mesh_clear()
                return  # dont bother with this mesh.

            if self.options['EXPORT_NORMALS'] and face_index_pairs:
                me.calc_normals_split()
                # No need to call me.free_normals_split later, as this mesh is deleted anyway!

            if self.options['EXPORT_SMOOTH_GROUPS'] and face_index_pairs:
                smooth_groups, smooth_groups_tot = me.calc_smooth_groups(self.options['EXPORT_SMOOTH_GROUPS_BITFLAGS'])
                if smooth_groups_tot <= 1:
                    smooth_groups, smooth_groups_tot = (), 0
            else:
                smooth_groups, smooth_groups_tot = (), 0

            materials = me.materials[:]
            use_materials = materials and self.options['EXPORT_MTL']

            # Sort by Material, then images
            # so we dont over context switch in the obj file.
            if self.options['KEEP_VERTEX_ORDER']:
                pass
            else:
                if has_uv_textures:
                    if smooth_groups:
                        sort_func = lambda a: (a[0].material_index,
                                               hash(uv_texture[a[1]].image),
                                               smooth_groups[a[1]] if a[0].use_smooth else False)
                    else:
                        sort_func = lambda a: (a[0].material_index,
                                               hash(uv_texture[a[1]].image),
                                               a[0].use_smooth)
                elif len(materials) > 1:
                    if smooth_groups:
                        sort_func = lambda a: (a[0].material_index,
                                               smooth_groups[a[1]] if a[0].use_smooth else False)
                    else:
                        sort_func = lambda a: (a[0].material_index,
                                               a[0].use_smooth)
                else:
                    # no materials
                    if smooth_groups:
                        sort_func = lambda a: smooth_groups[a[1] if a[0].use_smooth else False]
                    else:
                        sort_func = lambda a: a[0].use_smooth

                face_index_pairs.sort(key=sort_func)

                del sort_func

            util.detect_zztag(log, ob.name)
            fw('g %s\n' % util.quote(ob.name))

            # rig_is_exported is used to avoid referencing a skeleton or bones which aren't exported
            rig_is_exported = self.options['EXPORT_SKEL'] and (rigged_to_armature in self.objects)

            if ob.type == 'MESH':
                objex_data = ob.data.objex_bonus # ObjexMeshProperties
                if objex_data.priority != 0:
                    fw('priority %d\n' % objex_data.priority)
                if objex_data.write_origin == 'YES' or (
                    objex_data.write_origin == 'AUTO'
                    and objex_data.attrib_billboard != 'NONE'
                ):
                    fw('origin %.6f %.6f %.6f\n'
                        % tuple(blender_version_compatibility.matmul(self.options['GLOBAL_MATRIX'], ob.location)))
                if objex_data.attrib_billboard != 'NONE':
                    fw('attrib %s\n' % objex_data.attrib_billboard)
                for attrib in ('POSMTX', 'PROXY'):
                    if getattr(objex_data, 'attrib_%s' % attrib):
                        fw('attrib %s\n' % attrib)
                # export those attributes when the properties are shown in the ui, that is when the mesh is rigged
                if rigged_to_armature:
                    for attrib in ('LIMBMTX', 'NOSPLIT', 'NOSKEL'):
                        if getattr(objex_data, 'attrib_%s' % attrib):
                            if rig_is_exported:
                                fw('attrib %s\n' % attrib)
                            else:
                                log.warning('Mesh {} is rigged to armature {} and sets {},\n'
                                    'but that armature is not being exported. Skipped exporting the attribute.\n'
                                    '(you are likely exporting Selection Only, unchecked Used armatures, and did not select the armature)',
                                    ob.name, rigged_to_armature.name, attrib)

            subprogress2.step()

            if self.options['EXPORT_WEIGHTS']:
                # Retrieve the list of vertex groups
                vertGroupNames = ob.vertex_groups.keys()
                vertex_groups = None
                if vertGroupNames:
                    # Create a dictionary keyed by vertex id and listing, for each vertex, the name of the vertex groups it belongs to, and its associated weight
                    vertex_groups = [[] for _i in range(len(vertices))]
                    for v_idx, v_ls in enumerate(vertex_groups):
                        v_ls[:] = [(vertGroupNames[g.group], util.quote(vertGroupNames[g.group]), g.weight) for g in vertices[v_idx].groups]
                del vertGroupNames

            # Vert
            if rigged_to_armature and rig_is_exported:
                fw('useskel %s\n' % util.quote(rigged_to_armature.name))
            if self.options['EXPORT_WEIGHTS'] and vertex_groups and rigged_to_armature and rig_is_exported:
                # only write vertex groups named after actual bones
                bone_names = [bone.name for bone in rigged_to_armature.data.bones]
                bone_vertex_groups = [
                    [(group_name_q, weight) for group_name, group_name_q, weight in vertex_vertex_groups if group_name in bone_names]
                    for vertex_vertex_groups in vertex_groups
                ]
                # only group of maximum weight, with weight 1
                if self.options['UNIQUE_WEIGHTS']:
                    for v in vertices:
                        groups = bone_vertex_groups[v.index] # list of (group_name_q, group_weight) tuples for that vertex
                        if groups:
                            group_name_q, weight = max(groups, key=lambda _g: _g[1])
                            fw('%s %s\n' % (
                                'v %.6f %.6f %.6f' % v.co[:],
                                'weight %s 1' % group_name_q
                            ))
                        else:
                            fw('v %.6f %.6f %.6f\n' % v.co[:])
                # all (non-zero) weights
                else:
                    for v in vertices:
                        fw('%s%s\n' % (
                            'v %.6f %.6f %.6f' % v.co[:],
                            ','.join([' weight %s %.3f' % (group_name_q, weight) for group_name_q, weight in bone_vertex_groups[v.index] if weight != 0])
                        ))
            # no weights
            else:
                for v in vertices:
                    fw('v %.6f %.6f %.6f\n' % v.co[:])

            subprogress2.step()

            # UV
            if has_uvs:
                uv_face_mapping, uv_unique_count = self.write_uvs(me, face_index_pairs)
            else:
                uv_unique_count = 0
            
            subprogress2.step()

            # NORMAL, Smooth/Non smoothed.
            if self.options['EXPORT_NORMALS']:
                loops_to_normals, no_unique_count = self.write_normals(me, face_index_pairs)
                has_normals = True
            else:
                no_unique_count = 0
                has_normals = False
            
            if self.options['EXPORT_VERTEX_COLORS']:
                loops_to_vertex_colors, vc_unique_count = self.write_vertex_colors(me, face_index_pairs)
                has_vertex_colors = loops_to_vertex_colors is not None
            else:
                has_vertex_colors = False
                vc_unique_count = 0

            subprogress2.step()

            # those context_* variables are used to keep track of the last g/usemtl/s directive written, according to options
            # Set the default mat to no material and no image.
            context_material = context_face_image = 0  # Can never be this, so we will label a new material the first chance we get. used for usemtl directives if EXPORT_MTL
            context_smooth = None  # Will either be true or false,  set bad to force initialization switch. with EXPORT_SMOOTH_GROUPS, has effects on writing the s directive

            for f, f_index in face_index_pairs:
                f_smooth = f.use_smooth
                if f_smooth and smooth_groups:
                    f_smooth = smooth_groups[f_index]

                face_material = materials[f.material_index] if use_materials else None
                face_image = uv_texture[f_index].image if has_uv_textures else None

                # we do not need to switch context when the face image changes if
                # the (objex) material doesn't change, as the face image is completely ignored
                # when using objex materials
                if face_material and face_material.objex_bonus.is_objex_material:
                    face_image = None

                # if context hasn't changed, do nothing
                if context_material == face_material and context_face_image == face_image:
                    pass
                else:
                    # update context
                    context_material = face_material
                    context_face_image = face_image

                    # clear context
                    if face_material is None and face_image is None:
                        if self.options['EXPORT_MTL']:
                            fw('clearmtl\n')
                    # new context
                    else:
                        # mtl_dict is {(material, image): (name, name_q, material, face_image)}
                        data = self.mtl_dict.get((face_material, face_image))
                        if data:
                            name_q = data[1]
                        else:
                            # new (material, image) pair, find a new unique name for it
                            name_base = face_material.name if face_material else 'None'
                            if face_image:
                                name_base = '%s %s' % (name_base, face_image.name)
                            name = name_base
                            i = 0
                            while name in (_name for (_name, _name_q, _material, _face_image) in self.mtl_dict.values()):
                                i += 1
                                name = '%s %d' % (name_base, i)
                            name_q = util.quote(name)
                            # remember the pair
                            self.mtl_dict[(face_material, face_image)] = name, name_q, face_material, face_image

                            if self.options['EXPORT_MTL']:
                                objectUseCollision = ob.name.startswith('collision.')
                                # 421fixme
                                # if the export is done right after material initialization, material properties
                                # are for some reason still reading the old values. They update at least
                                # when modifying objex_bonus properties in the UI or renaming the material
                                # context.view_layer.update() doesn't help
                                if objectUseCollision and not face_material.objex_bonus.is_objex_material:
                                    raise util.ObjexExportAbort(
                                        'Object {} is for collision (has "collision." prefix) '
                                        'but material {} used by this object is not for collision '
                                        '(not even initialized as an objex material)'
                                        .format(ob.name, face_material.name)
                                    )
                                if objectUseCollision and not face_material.objex_bonus.use_collision:
                                    raise util.ObjexExportAbort(
                                        'Object {} is for collision (has "collision." prefix) '
                                        'but material {} used by this object is not for collision'
                                        .format(ob.name, face_material.name)
                                    )
                                if not objectUseCollision and face_material.objex_bonus.use_collision:
                                    raise util.ObjexExportAbort(
                                        'Object {} is not for collision (does not have "collision." prefix) '
                                        'but material {} used by this object is for collision'
                                        .format(ob.name, face_material.name)
                                    )

                        if self.options['EXPORT_MTL']:
                            fw('usemtl %s\n' % name_q)

                if f_smooth != context_smooth:
                    if f_smooth:  # on now off
                        if smooth_groups:
                            f_smooth = smooth_groups[f_index]
                            fw('s %d\n' % f_smooth)
                        else:
                            fw('s 1\n')
                    else:  # was off now on
                        fw('s off\n')
                    context_smooth = f_smooth

                f_v = [(vi, vertices[v_idx], l_idx)
                       for vi, (v_idx, l_idx) in enumerate(zip(f.vertices, f.loop_indices))]

                fw('f')
                for vi, v, li in f_v:
                    f_v_data = []
                    f_v_data.append(self.total_vertex + v.index)
                    if has_uvs:
                        f_v_data.append(self.total_uv + uv_face_mapping[f_index][vi])
                    if has_normals:
                        f_v_data += [None] * (2 - len(f_v_data))
                        f_v_data.append(self.total_normal + loops_to_normals[li])
                    if has_vertex_colors:
                        f_v_data += [None] * (3 - len(f_v_data))
                        f_v_data.append(self.total_vertex_color + loops_to_vertex_colors[li])
                    # v[/vt[/vn[/vc]]] coordinates/uv/normal/color
                    fw(' %s' % '/'.join(['' if _i is None else ('%d' % _i) for _i in f_v_data]))
                fw('\n')

            subprogress2.step()

            # Make the indices global rather then per mesh
            self.total_vertex += len(vertices)
            self.total_uv += uv_unique_count
            self.total_normal += no_unique_count
            self.total_vertex_color += vc_unique_count
            
            # clean up
            if not ob_for_convert: # < 2.80
                bpy.data.meshes.remove(me)
            else: # 2.80+
                ob_for_convert.to_mesh_clear()
コード例 #3
0
    def write(self, filepath):
        """
        This function starts the exporting. It defines a few "globals" as class members, notably the total_* variables
        It loops through objects, writing each to .objex (with the write_object method), and collecting materials/armatures/animations as it goes.
        Once the .objex is finished being written, write_mtl is called to write the .mtl and same thing with write_anim which writes .anim and itself calls .skel which writes .skel
        """
        log = self.log
        self.filepath = filepath
        with ProgressReport(self.context.window_manager) as progress:
            scene = self.context.scene

            # Exit edit mode before exporting, so current object states are exported properly.
            if bpy.ops.object.mode_set.poll():
                bpy.ops.object.mode_set(mode='OBJECT')

            # EXPORT THE FILE.
            progress.enter_substeps(1)
            
            with ProgressReportSubstep(progress, 3, "Objex Export path: %r" % filepath, "Objex Export Finished") as subprogress1:
                with open(filepath, "w", encoding="utf8", newline="\n") as f:
                    self.fw_objex = f.write

                    # write leading comments, mtllib/animlib/skellib directives, and defines filepath_* to write .mtl/... to
                    self.write_header()

                    # Initialize totals, these are updated each object
                    self.total_vertex = self.total_uv = self.total_normal = self.total_vertex_color = 1

                    # A Dict of Materials
                    # "materials" here refer to a material + face image pair, where either or both may be unset
                    # (material, image): (name, name_q, material, face_image)
                    # name_q = util.quote(name)
                    self.mtl_dict = {}

                    copy_set = set()

                    self.armatures = []
                    
                    # Get all meshes
                    subprogress1.enter_substeps(len(self.objects))
                    for ob_main in self.objects:
                        # 421todo I don't know what this dupli stuff is about
                        # ("instancer" stuff in 2.80+)
                        use_old_dupli = hasattr(ob_main, 'dupli_type') # True in < 2.80
                        # ignore dupli children
                        if (ob_main.parent
                            and (ob_main.parent.dupli_type if use_old_dupli else ob_main.parent.instance_type)
                                    in {'VERTS', 'FACES'}
                        ):
                            subprogress1.step("Ignoring %s, dupli child..." % ob_main.name)
                            continue

                        obs = [(ob_main, ob_main.matrix_world)]
                        added_dupli_children = True
                        if use_old_dupli and ob_main.dupli_type != 'NONE':
                            # XXX
                            log.info('creating dupli_list on {}', ob_main.name)
                            ob_main.dupli_list_create(scene)

                            obs += [(dob.object, dob.matrix) for dob in ob_main.dupli_list]
                        elif not use_old_dupli and ob_main.is_instancer:
                            # evaluated_depsgraph_get may be called in-between this line executing,
                            # ie in write_object when evaluating mesh data, so call it again every time here
                            depsgraph = self.context.evaluated_depsgraph_get()
                            obs += [(dup.instance_object.original, dup.matrix_world.copy())
                                    for dup in depsgraph.object_instances
                                    if dup.parent and dup.parent.original == ob_main]
                            del depsgraph
                        else:
                            added_dupli_children = False
                        if added_dupli_children:
                            log.debug('{} has {:d} dupli children', ob_main.name, len(obs) - 1)

                        subprogress1.enter_substeps(len(obs))
                        for ob, ob_mat in obs:
                            self.write_object(subprogress1, ob, ob_mat)

                        if use_old_dupli and ob_main.dupli_type != 'NONE':
                            ob_main.dupli_list_clear()
                        elif not use_old_dupli:
                            pass # no clean-up needed

                        subprogress1.leave_substeps("Finished writing geometry of '%s'." % ob_main.name)
                    subprogress1.leave_substeps()

                del self.fw_objex
                
                subprogress1.step("Finished exporting geometry, now exporting materials")

                # Now we have all our materials, save them
                if self.options['EXPORT_MTL']:
                    def append_header_mtl(fw_mtl):
                        fw_mtl(self.export_id_line)
                    export_objex_mtl.write_mtl(scene, self.filepath_mtl, append_header_mtl, self.options, copy_set, self.mtl_dict)
                
                subprogress1.step("Finished exporting materials, now exporting skeletons/animations")

                # save gathered skeletons and animations
                if self.options['EXPORT_SKEL']:
                    log.info('now exporting skeletons')
                    skelfile = None
                    animfile = None
                    try:
                        skelfile = open(self.filepath_skel, "w", encoding="utf8", newline="\n")
                        skelfile_write = skelfile.write
                        skelfile_write(self.export_id_line)
                        link_anim_basepath = None
                        if self.options['EXPORT_ANIM']:
                            log.info(' ... and animations')
                            animfile = open(self.filepath_anim, "w", encoding="utf8", newline="\n")
                            animfile_write = animfile.write
                            animfile_write(self.export_id_line)
                            if self.options['EXPORT_LINK_ANIM_BIN']:
                                log.info(' ... and Link animation binaries')
                                link_anim_basepath = self.filepath_linkbase
                        else:
                            animfile_write = None
                        export_objex_anim.write_armatures(skelfile_write, animfile_write, 
                            scene, self.options['GLOBAL_MATRIX'], self.armatures, 
                            link_anim_basepath, self.options['LINK_BIN_SCALE'])
                    finally:
                        if skelfile:
                            skelfile.close()
                        if animfile:
                            animfile.close()
                
                # copy all collected files.
                bpy_extras.io_utils.path_reference_copy(copy_set)

            progress.leave_substeps()
コード例 #4
0
def write_file(context,
               filepath,
               objects,
               scene,
               provides_mtl,
               progress=ProgressReport()):
    # bpy.ops.object.select_all(action='DESELECT')

    with ProgressReportSubstep(progress, 2, "JSON export path: %r" % filepath,
                               "JSON export finished") as subprogress1:
        with open(filepath, "w", encoding="utf8", newline="\n") as f:
            limbs = {'anchor': {'opacity': 0}}
            pose = {}

            for obj in objects:
                if obj.type != "MESH":
                    continue

                name1 = obj.name
                name2 = obj.data.name

                if name1 == name2:
                    name = name_compat(name1)
                else:
                    name = '%s_%s' % (name_compat(name1), name_compat(name2))

                cursor = obj.matrix_world.translation
                x = cursor[0]
                y = cursor[2]
                z = cursor[1]

                limb = {
                    'origin': [x, y, -z],
                    'smooth': True,
                    'parent': 'anchor'
                }

                transform = {'translate': [x * 16, y * 16, z * 16]}

                # Some automatic setup of limbs based on name
                if name1 == 'head':
                    limb['looking'] = True
                elif name1 == 'left_arm':
                    limb['holding'] = 'left'
                    limb['swinging'] = True
                    limb['idle'] = True
                    limb['invert'] = True
                elif name1 == 'right_arm':
                    limb['holding'] = 'right'
                    limb['swinging'] = True
                    limb['idle'] = True
                    limb['swiping'] = True
                elif name1 == 'right_leg':
                    limb['swinging'] = True
                    limb['invert'] = True
                elif name1 == 'left_leg':
                    limb['swinging'] = True

                limbs[name] = limb
                pose[name] = transform

            # Write JSON to the file
            pose = {'size': [0.6, 1.8, 0.6], 'limbs': pose}

            data = {
                'scheme': "1.3",
                'providesObj': True,
                'providesMtl': provides_mtl,
                'name': path_leaf(filepath),
                'limbs': limbs,
                'poses': {
                    'standing': pose,
                    'sneaking': pose,
                    'sleeping': pose,
                    'flying': pose
                }
            }

            f.write(json.dumps(data, indent=4))

        subprogress1.step("Finished exporting JSON")