def object_colors_calc(rules, objects):
    from mathutils import Color

    rules_cb = [getattr(rule_test, rule.type) for rule in rules]
    rules_blend = [(1.0 - rule.factor, rule.factor) for rule in rules]
    rules_color = [Color(rule.color) for rule in rules]
    rules_cache = [{} for i in range(len(rules))]
    rules_inv = [rule.use_invert for rule in rules]

    for obj in objects:
        is_set = False
        obj_color = Color(obj.color[0:3])

        for (rule, test_cb, color, blend, cache, use_invert) \
             in zip(rules, rules_cb, rules_color, rules_blend, rules_cache, rules_inv):

            if test_cb(obj, rule, cache) is not use_invert:
                if is_set is False:
                    obj_color = color
                else:
                    # prevent mixing colors loosing saturation
                    obj_color_s = obj_color.s
                    obj_color = (obj_color * blend[0]) + (color * blend[1])
                    obj_color.s = (obj_color_s * blend[0]) + (color.s * blend[1])

                is_set = True

        if is_set:
            obj.show_wire_color = True
            obj.color[0:3] = obj_color
def create_materials(c_model):
    ret = []
    for material in Materials:
        ret.append(bpy.data.materials.new(material.name))
        for i in ret:
            if 'plot' in i.name:
                base = Color()
                base.hsv = c_model['base']
                color = base
                base_color(i, color)
            elif 'street' in i.name:
                color1 = Color()
                color1.hsv = c_model['color1']
                color = color1
                base_color(i, color)
            elif 'river' in i.name:
                color2 = Color()
                color2.hsv = c_model['color2']
                color = color2
                base_color(i, color)
            elif 'building' in i.name:
                color3 = Color()
                color3.hsv = c_model['color3']
                color = color3
                base_color(i, color)
            elif 'park' in i.name:
                color4 = Color()
                color4.hsv = c_model['color4']
                color = color4
                base_color(i, color)
    return ret
Beispiel #3
0
def getRandomColor(seed = None, hue = None, saturation = None, value = None):
    if seed is None: random.seed()
    else: random.seed(seed)

    if hue is None: hue = random.random()
    if saturation is None: saturation = random.random()
    if value is None: value = random.random()

    color = Color()
    color.hsv = hue, saturation, value
    return color
def convert(value, method):
    if method == 'BW2W':
        return  (value.r + value.g+ value.b)/3
    elif method == 'W2BW':
        col = Color((value, value, value))
        return col
    elif method == 'HSV2W':
        return  1-(value.h / 0.66)
    elif method == 'W2HSV':
        col = Color()
        col.hsv = (0.66*(1-value), 1, 1)
        return  col
Beispiel #5
0
    def set_diffuse(node_tree, color):
        """Set diffuse color to shader.

        :param node_tree: node tree of current shader
        :type node_tree: bpy.types.NodeTree
        :param color: diffuse color
        :type color: Color or tuple
        """

        hsv_col = Color(color[:3])
        # force diffuse color to be rendered so ambient color can be simulated!
        if hsv_col.v == 0:
            hsv_col.v = 0.000001  # this is the smallest value Blender still uses for rendering

        color = tuple(hsv_col) + (1,)

        node_tree.nodes[UnlitVcolTex.DIFF_COL_NODE].outputs['Color'].default_value = color
Beispiel #6
0
def mouse_op(direction):
    if G.mode == "Aspect":
        factor = 1.1
        if direction == "down":
            factor = 1.0 / factor
        G.hole.worldScale = Vector(
            (G.hole.worldScale.x * factor, G.hole.worldScale.y * 1.0 / factor, G.hole.worldScale.z)
        )
    elif G.mode == "Scale":
        factor = 1.1
        if direction == "down":
            factor = 1.0 / factor
        G.hole.worldScale = G.hole.worldScale * factor
    elif G.mode == "Rotate":
        factor = 3.1415926 * 2 / 360 * 10  # last is degrees per click
        if direction == "down":
            factor *= -1.0
        G.stim.applyRotation([0.0, 0.0, factor])
    elif G.mode == "Temporal":
        factor = 1.3
        if direction == "down":
            factor = 1.0 / factor
        G.stim.worldScale = G.stim.worldScale * factor
    elif G.mode == "Color":
        factor = 1.1
        if direction == "down":
            factor = 1.0 / factor
        print("sun", G.sun.color)
        # G.sun.color[0] *= factor
        # G.sun.color[1] = 0.5
        hsv = Color(G.sun.color)
        hsv.h *= factor
        hsv.s = 0.5
        hsv.v = 1.0
        G.sun.color = (255, 0, 0)
        print(hsv)
    elif G.mode == "Mask":
        factor = 3.1415926 * 2 / 360 * 10  # last is degrees per click
        if direction == "down":
            factor *= -1.0
        G.hole.applyRotation([0.0, 0.0, factor])
    elif G.mode == GK.ZKEY:
        G.stim.worldPosition = [0, 0, G.stim.worldPosition[2]]
        G.hole.worldPosition = [0, 0, G.hole.worldPosition[2]]
Beispiel #7
0
def to_node_color(color):
    """Gets color ready for assigning to Blender nodes.
    1. Sets minimal HSV value attribute for rendering
    2. Applies pre gamma correction
    3. Returns it as tuple of 4 floats RGBA

    :param color: color to be converted for usage in node
    :type color: mathutils.Color | collections.Iterable[float]
    :return: RGBA as tuple of floats
    :rtype: tuple[float]
    """

    c = Color(color[:3])  # copy color so changes won't reflect on original passed color object

    c = pre_gamma_corrected_col(c)

    # set minimal value for Blender to use it in rendering
    if c.v == 0:
        c.v = 0.000001  # this is the smallest value Blender still uses for rendering

    return tuple(c) + (1,)
Beispiel #8
0
    def set_diffuse(node_tree, color):
        """Set diffuse color to shader.

        :param node_tree: node tree of current shader
        :type node_tree: bpy.types.NodeTree
        :param color: diffuse color
        :type color: Color or tuple
        """

        hsv_col = Color(color[:3])
        # force diffuse color to be rendered so ambient color can be simulated!
        if hsv_col.v == 0:
            hsv_col.v = 0.000001  # this is the smallest value Blender still uses for rendering

        color = tuple(hsv_col) + (1,)

        node_tree.nodes[Dif.DIFF_COL_NODE].outputs['Color'].default_value = color
        node_tree.nodes[Dif.OUT_MAT_NODE].material.diffuse_intensity = hsv_col.v * 0.7

        # fix emit color representing ambient.
        # NOTE: because emit works upon diffuse light we need to fake factors if diffuse drops
        ambient = node_tree.nodes[Dif.OUT_MAT_NODE].material.scs_props.shader_attribute_add_ambient
        node_tree.nodes[Dif.OUT_MAT_NODE].material.emit = (ambient / 10) * (1 / hsv_col.v)
Beispiel #9
0
    
    # Link new object to the given scene and select it
    scene.objects.link(ob_new)
    ob_new.select = True
 
    return ob_new

# delete all pre-existing orbs besides the original
for obj in bpy.context.scene.objects:
    obj.select = ( obj.name[:3] == "Orb" or obj.name[:5] == "Glass") and ( obj.name != "Orb" and obj.name != "Glass")
    bpy.ops.object.delete()

orb = bpy.data.objects['Orb']
glass = bpy.data.objects['Glass']
scene = bpy.data.scenes['Scene']
c = Color()
numorb = 150
random.seed(0)
for i in range(1, numorb+1):
    name = 'Orb' + str(i)
    glassname = 'Glass' + str(i)
    neworb = duplicateObject(scene, name, orb)
    neworb.location = Vector((-20+40*random.random(), -20+40*random.random(), 20*random.random()))
    newglass = duplicateObject(scene, glassname, glass)
    newglass.location = neworb.location
    matname = 'OrbMat' + str(i)
    newmat = bpy.data.materials.new(matname)
    c.hsv = random.random(), 1.0, 0.735
    newmat.diffuse_color = c.r, c.g, c.b
    newmat.emit = 0.
    neworb.active_material = newmat
Beispiel #10
0
def write_mtl(scene, filepath, path_mode, copy_set, mtl_dict):
    from mathutils import Color, Vector

    world = scene.world
    if world:
        world_amb = world.ambient_color
    else:
        world_amb = Color((0.0, 0.0, 0.0))

    source_dir = os.path.dirname(bpy.data.filepath)
    dest_dir = os.path.dirname(filepath)

    with open(filepath, "w", encoding="utf8", newline="\n") as f:
        fw = f.write

        fw('# Blender MTL File: %r\n' % (os.path.basename(bpy.data.filepath) or "None"))
        fw('# Material Count: %i\n' % len(mtl_dict))

        mtl_dict_values = list(mtl_dict.values())
        mtl_dict_values.sort(key=lambda m: m[0])

        # Write material/image combinations we have used.
        # Using mtl_dict.values() directly gives un-predictable order.
        for mtl_mat_name, mat, face_img in mtl_dict_values:
            # Get the Blender data for the material and the image.
            # Having an image named None will make a bug, dont do it :)

            fw('\nnewmtl %s\n' % mtl_mat_name)  # Define a new material: matname_imgname

            if mat:
                use_mirror = mat.raytrace_mirror.use and mat.raytrace_mirror.reflect_factor != 0.0

                # convert from blenders spec to 0 - 1000 range.
                if mat.specular_shader == 'WARDISO':
                    tspec = (0.4 - mat.specular_slope) / 0.0004
                else:
                    tspec = (mat.specular_hardness - 1) / 0.51
                fw('Ns %.6f\n' % tspec)
                del tspec

                # Ambient
                if use_mirror:
                    fw('Ka %.6f %.6f %.6f\n' % (mat.raytrace_mirror.reflect_factor * mat.mirror_color)[:])
                else:
                    fw('Ka %.6f %.6f %.6f\n' % (mat.ambient, mat.ambient, mat.ambient))  # Do not use world color!
                fw('Kd %.6f %.6f %.6f\n' % (mat.diffuse_intensity * mat.diffuse_color)[:])  # Diffuse
                fw('Ks %.6f %.6f %.6f\n' % (mat.specular_intensity * mat.specular_color)[:])  # Specular
                # Emission, not in original MTL standard but seems pretty common, see T45766.
                # XXX Blender has no color emission, it's using diffuse color instead...
                fw('Ke %.6f %.6f %.6f\n' % (mat.emit * mat.diffuse_color)[:])
                if hasattr(mat, "raytrace_transparency") and hasattr(mat.raytrace_transparency, "ior"):
                    fw('Ni %.6f\n' % mat.raytrace_transparency.ior)  # Refraction index
                else:
                    fw('Ni %.6f\n' % 1.0)
                fw('d %.6f\n' % mat.alpha)  # Alpha (obj uses 'd' for dissolve)

                # See http://en.wikipedia.org/wiki/Wavefront_.obj_file for whole list of values...
                # Note that mapping is rather fuzzy sometimes, trying to do our best here.
                if mat.use_shadeless:
                    fw('illum 0\n')  # ignore lighting
                elif mat.specular_intensity == 0:
                    fw('illum 1\n')  # no specular.
                elif use_mirror:
                    if mat.use_transparency and mat.transparency_method == 'RAYTRACE':
                        if mat.raytrace_mirror.fresnel != 0.0:
                            fw('illum 7\n')  # Reflection, Transparency, Ray trace and Fresnel
                        else:
                            fw('illum 6\n')  # Reflection, Transparency, Ray trace
                    elif mat.raytrace_mirror.fresnel != 0.0:
                        fw('illum 5\n')  # Reflection, Ray trace and Fresnel
                    else:
                        fw('illum 3\n')  # Reflection and Ray trace
                elif mat.use_transparency and mat.transparency_method == 'RAYTRACE':
                    fw('illum 9\n')  # 'Glass' transparency and no Ray trace reflection... fuzzy matching, but...
                else:
                    fw('illum 2\n')  # light normaly

            else:
                # Write a dummy material here?
                fw('Ns 0\n')
                fw('Ka %.6f %.6f %.6f\n' % world_amb[:])  # Ambient, uses mirror color,
                fw('Kd 0.8 0.8 0.8\n')
                fw('Ks 0.8 0.8 0.8\n')
                fw('d 1\n')  # No alpha
                fw('illum 2\n')  # light normaly

            # Write images!
            if face_img:  # We have an image on the face!
                filepath = face_img.filepath
                if filepath:  # may be '' for generated images
                    # write relative image path
                    filepath = bpy_extras.io_utils.path_reference(filepath, source_dir, dest_dir,
                                                                  path_mode, "", copy_set, face_img.library)
                    fw('map_Kd %s\n' % filepath)  # Diffuse mapping image
                    del filepath
                else:
                    # so we write the materials image.
                    face_img = None

            if mat:  # No face image. if we havea material search for MTex image.
                image_map = {}
                # backwards so topmost are highest priority
                for mtex in reversed(mat.texture_slots):
                    if mtex and mtex.texture and mtex.texture.type == 'IMAGE':
                        image = mtex.texture.image
                        if image:
                            # texface overrides others
                            if (mtex.use_map_color_diffuse and (face_img is None) and
                                (mtex.use_map_warp is False) and (mtex.texture_coords != 'REFLECTION')):
                                image_map["map_Kd"] = (mtex, image)
                            if mtex.use_map_ambient:
                                image_map["map_Ka"] = (mtex, image)
                            # this is the Spec intensity channel but Ks stands for specular Color
                            '''
                            if mtex.use_map_specular:
                                image_map["map_Ks"] = (mtex, image)
                            '''
                            if mtex.use_map_color_spec:  # specular color
                                image_map["map_Ks"] = (mtex, image)
                            if mtex.use_map_hardness:  # specular hardness/glossiness
                                image_map["map_Ns"] = (mtex, image)
                            if mtex.use_map_alpha:
                                image_map["map_d"] = (mtex, image)
                            if mtex.use_map_translucency:
                                image_map["map_Tr"] = (mtex, image)
                            if mtex.use_map_normal:
                                image_map["map_Bump"] = (mtex, image)
                            if mtex.use_map_displacement:
                                image_map["disp"] = (mtex, image)
                            if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
                                image_map["refl"] = (mtex, image)
                            if mtex.use_map_emit:
                                image_map["map_Ke"] = (mtex, image)

                for key, (mtex, image) in sorted(image_map.items()):
                    filepath = bpy_extras.io_utils.path_reference(image.filepath, source_dir, dest_dir,
                                                                  path_mode, "", copy_set, image.library)
                    options = []
                    if key == "map_Bump":
                        if mtex.normal_factor != 1.0:
                            options.append('-bm %.6f' % mtex.normal_factor)
                    if mtex.offset != Vector((0.0, 0.0, 0.0)):
                        options.append('-o %.6f %.6f %.6f' % mtex.offset[:])
                    if mtex.scale != Vector((1.0, 1.0, 1.0)):
                        options.append('-s %.6f %.6f %.6f' % mtex.scale[:])
                    if options:
                        fw('%s %s %s\n' % (key, " ".join(options), repr(filepath)[1:-1]))
                    else:
                        fw('%s %s\n' % (key, repr(filepath)[1:-1]))
Beispiel #11
0
    def invoke(self, context, event):
        if bpy.context.mode == 'SCULPT':
            self.brush = context.tool_settings.sculpt.brush
        elif bpy.context.mode == 'PAINT_TEXTURE':
            self.brush = context.tool_settings.image_paint.brush
        elif bpy.context.mode == 'PAINT_VERTEX':
            self.brush = context.tool_settings.vertex_paint.brush
        elif bpy.context.mode == 'PAINT_WEIGHT':
            self.brush = context.tool_settings.weight_paint.brush
        else:
            self.report({'WARNING'}, "Mode invalid - only paint or sculpt")
            return {'CANCELLED'}

        self.hotkey = event.type
        if self.hotkey == 'NONE':
            self.keyaction = 'IGNORE'
        self.action = 0
        unify_settings = context.tool_settings.unified_paint_settings
        self.uni_size = unify_settings.use_unified_size
        self.uni_str = unify_settings.use_unified_strength

        self.doingrad = False
        self.doingstr = False
        self.start = (event.mouse_region_x, event.mouse_region_y)
        self.prev = self.start
        self.radmod_total = 0.0
        self.strmod_total = 0.0
        self.radmod = 0.0
        self.strmod = 0.0

        # self._handle = context.space_data.draw_handler_add(draw_callback_px, (self, context), 'WINDOW', 'POST_PIXEL')

        if self.graphic:
            if not hasattr(self, '_handle'):
                self._handle = context.space_data.draw_handler_add(
                    draw_callback_px, (self, context), 'WINDOW', 'POST_PIXEL')

            self.brushcolor = self.brush.cursor_color_add
            if self.brush.sculpt_capabilities.has_secondary_color and self.brush.direction in {
                    'SUBTRACT', 'DEEPEN', 'MAGNIFY', 'PEAKS', 'CONTRAST',
                    'DEFLATE'
            }:
                self.brushcolor = self.brush.cursor_color_subtract

            self.circlepoints = ((0.000000, 1.000000), (-0.195090, 0.980785),
                                 (-0.382683, 0.923880), (-0.555570, 0.831470),
                                 (-0.707107, 0.707107), (-0.831470, 0.555570),
                                 (-0.923880, 0.382683), (-0.980785, 0.195090),
                                 (-1.000000, 0.000000), (-0.980785, -0.195090),
                                 (-0.923880, -0.382683), (-0.831470,
                                                          -0.555570),
                                 (-0.707107,
                                  -0.707107), (-0.555570,
                                               -0.831470), (-0.382683,
                                                            -0.923880),
                                 (-0.195090, -0.980785), (0.000000, -1.000000),
                                 (0.195091, -0.980785), (0.382684, -0.923879),
                                 (0.555571, -0.831469), (0.707107, -0.707106),
                                 (0.831470, -0.555570), (0.923880, -0.382683),
                                 (0.980785, -0.195089), (1.000000, 0.000001),
                                 (0.980785, 0.195091), (0.923879, 0.382684),
                                 (0.831469, 0.555571), (0.707106, 0.707108),
                                 (0.555569, 0.831470), (0.382682,
                                                        0.923880), (0.195089,
                                                                    0.980786))

        if self.text != 'NONE':
            if not hasattr(self, '_handle'):
                self._handle = context.space_data.draw_handler_add(
                    draw_callback_px, (self, context), 'WINDOW', 'POST_PIXEL')

            self.offset = (30, -37)

            self.backcolor = Color(
                (1.0, 1.0, 1.0)) - context.user_preferences.themes[
                    'Default'].view_3d.space.text_hi

            self.rectpoints = ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0))

        if self.slider != 'NONE':
            if not hasattr(self, '_handle'):
                self._handle = context.space_data.draw_handler_add(
                    draw_callback_px, (self, context), 'WINDOW', 'POST_PIXEL')

            if self.slider == 'LARGE':
                self.sliderheight = 16
                self.sliderwidth = 180
            elif self.slider == 'MEDIUM':
                self.sliderheight = 8
                self.sliderwidth = 80
            else:
                self.sliderheight = 3
                self.sliderwidth = 60

            if not hasattr(self, 'offset'):
                self.offset = (30, -37)

            if not hasattr(self, 'backcolor'):
                self.backcolor = Color(
                    (1.0, 1.0, 1.0)) - context.user_preferences.themes[
                        'Default'].view_3d.space.text_hi

            self.frontcolor = context.user_preferences.themes[
                'Default'].view_3d.space.text_hi

            if not hasattr(self, 'rectpoints'):
                self.rectpoints = ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0,
                                                                        1.0))

        # enter modal operation
        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}
Beispiel #12
0
    def execute(self, context):
        coll = bpy.context.view_layer.active_layer_collection.collection

        total_polygons = 0
        results = {}
        for obj in coll.objects:
            if hasattr(obj.data, 'polygons') and obj.hide_get() is False:
                if 'Decimate' in obj.modifiers:
                    results[obj.name] = obj.modifiers["Decimate"].face_count
                    total_polygons += obj.modifiers["Decimate"].face_count
                else:
                    results[obj.name] = len(obj.data.polygons)
                    total_polygons += len(obj.data.polygons)

        sorted_results = sorted(results.items(),
                                key=operator.itemgetter(1),
                                reverse=True)

        if sorted_results == []:
            print('No objects with polygons')
            return {'FINISHED'}

        top_result = sorted_results[0][1]
        last_result = sorted_results[-1][1]

        if top_result == last_result:
            self.report({'INFO'},
                        "All objects have the same number of polygons")
            return {'FINISHED'}

        for result in sorted_results:
            obj = bpy.context.scene.objects[result[0]]

            if obj.active_material is None:
                obj.original_material.add().add_material(None)
            elif "PKHG" not in obj.active_material.name:
                obj.original_material.clear()
                if (len(obj.material_slots) > 1):
                    for index, material_slot in enumerate(obj.material_slots):
                        original_material = obj.original_material.add()
                        original_material.add_material(material_slot.material)
                        for face in obj.data.polygons:
                            if (face.material_index == index):
                                original_material.add_face(face.index)
                else:
                    obj.original_material.add().add_material(
                        obj.material_slots[0].material)
                obj.data.materials.clear()
            else:
                active_material = obj.active_material
                obj.data.materials.clear()
                bpy.data.materials.remove(active_material)

            c = Color()
            c.hsv = (0.0,
                     (result[1] - last_result) / (top_result - last_result),
                     1.0)

            mat = bpy.data.materials.new("PKHG")
            mat.diffuse_color = (c.r, c.g, c.b, 1.0)
            obj.active_material = mat

        bpy.ops.object.select_all(action='DESELECT')
        bpy.data.objects[sorted_results[0][0]].select_set(True)
        bpy.ops.view3d.view_selected()

        return {'FINISHED'}
class B2PMXEM_OT_CreateWeightType(bpy.types.Operator):

    '''Create WeightType vertex group'''
    bl_idname = "b2pmxem.create_weight_type"
    bl_label = "Create WeightType"
    bl_options = {'REGISTER', 'UNDO'}

    color_dict = {
        0: Color((1.0, 0.0, 0.0)),                 # BDEF0 - red
        1: Color((0.784314, 1.0, 0.392157)),       # BDEF1 - light green
        2: Color((0.14902, 0.6, 1.0)),             # BDEF2 - light blue
        3: Color((0.196078, 0.509804, 0.478431)),  # BDEF3 - deep green
        4: Color((0.196078, 0.509804, 0.478431)),  # BDEF4 - deep green
    }                                              # other - red

    def execute(self, context):
        for obj in bpy.data.objects:
            if obj.users == 0:
                continue
            if obj.type != 'MESH':
                continue
            if obj.hide_viewport:
                continue

            mesh = obj.data

            # get armature
            arm_obj = obj.find_armature()

            if arm_obj is None:
                continue

            # get vertex_color group
            color_map = mesh.vertex_colors.get(GV.WeightTypeName)

            # create new vertex_color group
            if color_map is None:
                color_map = mesh.vertex_colors.new(name=GV.WeightTypeName)

            # Set active group
            color_map.active = True

            bone_names = arm_obj.data.bones.keys()
            color_list = []

            # Get vertex WeightType
            for v in mesh.vertices:
                count = 0

                for n in v.groups:
                    if len(obj.vertex_groups) > n.group:
                        if obj.vertex_groups[n.group].name in bone_names:
                            if n.weight > 0.0:
                                count += 1

                color_list.append(count)

            # Set Color
            i = 0
            for poly in mesh.polygons:
                for idx in poly.loop_indices:
                    loop = mesh.loops[idx]
                    v = loop.vertex_index

                    c = self.color_dict.get(color_list[v], Color((1.0, 0.0, 0.0)))
                    color_map.data[i].color = (c.r, c.g, c.b, 1.0)
                    i += 1

        return {'FINISHED'}
Beispiel #14
0
def gamma_correct(color):

    corrected_color = Color()
    for i, component in enumerate(color):
        corrected_color[i] = linsrgb_to_srgb(color[i])
    return corrected_color
Beispiel #15
0
 def update_value_hsv(self, context):
     col = Color()
     col.hsv = self.value_hsv
     self["value"] = col
Beispiel #16
0
    def __init__(self, exporter, mesh, recipe):
        super().__init__(mesh.data.checkReadyOnlyOnce,
                         mesh.data.maxSimultaneousLights)
        nameSpace = exporter.nameSpace if mesh.data.materialNameSpace == DEFAULT_MATERIAL_NAMESPACE or len(
            mesh.data.materialNameSpace) == 0 else mesh.data.materialNameSpace
        self.name = nameSpace + '.' + mesh.name
        Logger.log('processing begun of baked material:  ' + mesh.name, 2)

        # changes to cycles & smart_project occurred in 2.77; need to know what we are running
        bVersion = blenderMajorMinorVersion()

        # any baking already took in the values. Do not want to apply them again, but want shadows to show.
        # These are the default values from StandardMaterials
        self.ambient = Color((0, 0, 0))
        self.diffuse = Color(
            (0.8, 0.8,
             0.8))  # needed for shadows, but not change anything else
        self.specular = Color((1, 1, 1))
        self.emissive = Color((0, 0, 0))
        self.specularPower = 64
        self.alpha = 1.0

        self.backFaceCulling = recipe.backFaceCulling

        # texture is baked from selected mesh(es), need to insure this mesh is only one selected
        bpy.ops.object.select_all(action='DESELECT')
        mesh.select = True

        # store setting to restore
        engine = exporter.scene.render.engine

        # mode_set's only work when there is an active object
        exporter.scene.objects.active = mesh

        # UV unwrap operates on mesh in only edit mode, procedurals can also give error of 'no images to be found' when not done
        # select all verticies of mesh, since smart_project works only with selected verticies
        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.select_all(action='SELECT')

        # you need UV on a mesh in order to bake image.  This is not reqd for procedural textures, so may not exist
        # need to look if it might already be created, if so use the first one
        uv = mesh.data.uv_textures[0] if len(
            mesh.data.uv_textures) > 0 else None

        if uv == None or recipe.forceBaking:
            mesh.data.uv_textures.new('BakingUV')
            uv = mesh.data.uv_textures['BakingUV']
            uv.active = True
            uv.active_render = not recipe.forceBaking  # want the other uv's for the source when combining

            if bVersion <= 2.76:
                bpy.ops.uv.smart_project(angle_limit=66.0,
                                         island_margin=0.0,
                                         user_area_weight=1.0,
                                         use_aspect=True)
            else:
                bpy.ops.uv.smart_project(angle_limit=66.0,
                                         island_margin=0.0,
                                         user_area_weight=1.0,
                                         use_aspect=True,
                                         stretch_to_bounds=True)

            # syntax for using unwrap enstead of smar project
#            bpy.ops.uv.unwrap(margin = 1.0) # defaulting on all
            uvName = 'BakingUV'  # issues with cycles when not done this way
        else:
            uvName = uv.name

        format = 'PNG' if recipe.usePNG else 'JPEG'

        # create a temporary image & link it to the UV/Image Editor so bake_image works
        bpy.data.images.new(name=mesh.name + '_BJS_BAKE',
                            width=recipe.bakeSize,
                            height=recipe.bakeSize,
                            alpha=False,
                            float_buffer=False)
        image = bpy.data.images[mesh.name + '_BJS_BAKE']
        image.file_format = format
        image.mapping = 'UV'  # default value

        image_settings = exporter.scene.render.image_settings
        image_settings.file_format = format
        image_settings.color_mode = 'RGBA' if recipe.usePNG else 'RGB'
        image_settings.quality = recipe.bakeQuality  # for lossy compression formats
        image_settings.compression = recipe.bakeQuality  # Amount of time to determine best compression: 0 = no compression with fast file output, 100 = maximum lossless compression with slow file output

        # now go thru all the textures that need to be baked
        if recipe.diffuseBaking:
            cycles_type = 'DIFFUSE_COLOR' if bVersion <= 2.76 else 'DIFFUSE'
            self.bake('diffuseTexture', cycles_type, 'TEXTURE', image, mesh,
                      uvName, exporter, recipe)

        if recipe.ambientBaking:
            self.bake('ambientTexture', 'AO', 'AO', image, mesh, uvName,
                      exporter, recipe)

        if recipe.opacityBaking:  # no eqivalent found for cycles
            self.bake('opacityTexture', None, 'ALPHA', image, mesh, uvName,
                      exporter, recipe)

        if recipe.reflectionBaking:  # no eqivalent found for cycles
            self.bake('reflectionTexture', None, 'MIRROR_COLOR', image, mesh,
                      uvName, exporter, recipe)

        if recipe.emissiveBaking:
            self.bake('emissiveTexture', 'EMIT', 'EMIT', image, mesh, uvName,
                      exporter, recipe)

        if recipe.bumpBaking:
            self.bake('bumpTexture', 'NORMAL', 'NORMALS', image, mesh, uvName,
                      exporter, recipe)

        if recipe.specularBaking:
            cycles_type = 'SPECULAR' if bVersion <= 2.76 else 'GLOSSY'
            self.bake('specularTexture', cycles_type, 'SPEC_COLOR', image,
                      mesh, uvName, exporter, recipe)

        # Toggle vertex selection & mode, if setting changed their value
        bpy.ops.mesh.select_all(
            action='TOGGLE'
        )  # still in edit mode toggle select back to previous
        bpy.ops.object.mode_set(toggle=True)  # change back to Object

        bpy.ops.object.select_all(
            action='TOGGLE'
        )  # change scene selection back, not seeming to work

        exporter.scene.render.engine = engine
Beispiel #17
0
# This file is part of project Sverchok. It's copyrighted by the contributors
# recorded in the version control history of the file, available from
# its original location https://github.com/nortikin/sverchok/commit/master
#
# SPDX-License-Identifier: GPL3
# License-Filename: LICENSE
# pylint: disable=C0326

from mathutils import Color

color_channels = {
    'Red': (1, lambda x: x[0]),
    'Green': (2, lambda x: x[1]),
    'Blue': (3, lambda x: x[2]),
    'Hue': (4, lambda x: Color(x[:3]).h),
    'Saturation': (5, lambda x: Color(x[:3]).s),
    'Value': (6, lambda x: Color(x[:3]).v),
    'Alpha': (7, lambda x: x[3]),
    'RGB Average': (8, lambda x: sum(x[:3]) / 3),
    'Luminosity': (9, lambda x: 0.21 * x[0] + 0.72 * x[1] + 0.07 * x[2]),
    'Color': (10, lambda x: x[:3]),
    'RGBA': (11, lambda x: x[:]),
}
Beispiel #18
0
 
    # Copy data block from the old object into the new object
    ob_new.data = copyobj.data.copy()
    ob_new.scale = copyobj.scale
    ob_new.location = copyobj.location
    
    # Link new object to the given scene and select it
    scene.objects.link(ob_new)
    ob_new.select = True
 
    return ob_new


torus = bpy.data.objects['Torus']
scene = bpy.data.scenes['Scene']
c = Color()
numtor = 50
for i in range(1,numtor+1):
    name = 'Torus' + str(i)
    newtorus = duplicateObject(scene, name, torus)
    newtorus.location = Vector((0, 0, -20*i))
    matname = 'TorMat' + str(i)
    newmat = bpy.data.materials.new(matname)
    c.hsv = float(i-1) / float(numtor), 1.0, 0.735
    newmat.diffuse_color = c.r, c.g, c.b
    newmat.emit = 1.
    newtorus.active_material = newmat
    newconstraint = newtorus.constraints.new('CHILD_OF')
    newconstraint.target = torus
    newconstraint.use_scale_x = False
    newconstraint.use_scale_y = False
    def data_process(self, ReportData):
        self.gems_raw = []
        self.gems_fmt = []
        gems_fmt_temp = []
        col_stone = 0
        col_cut = 0
        col_size = 0
        color_var = Color((0.85, 0.35, 0.35))
        _ = gettext.GetText(self.lang).gettext
        _pcs = _("pcs")
        _mm = _("mm")

        for (stone, cut, size), qty in sorted(
                ReportData.gems.items(),
                key=lambda x: (x[0][1], -x[0][2][1], -x[0][2][0], x[0][0]),
        ):
            # Color
            # ---------------------------

            color = (*color_var, 1.0)

            color_var.h += 0.15

            if color_var.h == 0.0:
                color_var.s += 0.1
                color_var.v -= 0.15

            # Format
            # ---------------------------

            l = asset.to_int(size[1])
            w = asset.to_int(size[0])

            try:
                stone_fmt = _(var.STONES[stone].name)
                cut_fmt = _(var.CUTS[cut].name)
                xy_symmetry = var.CUTS[cut].xy_symmetry
            except KeyError:
                stone_fmt = stone
                cut_fmt = cut
                xy_symmetry = False

            if xy_symmetry:
                size_raw_fmt = str(l)
                size_fmt = f"{l} {_mm}"
            else:
                size_raw_fmt = f"{l}×{w}"
                size_fmt = f"{l} × {w} {_mm}"

            qty_fmt = f"{qty} {_pcs}"

            self.gems_raw.append((stone, cut, size, size_raw_fmt, color))
            gems_fmt_temp.append(
                (stone_fmt, cut_fmt, size_fmt, qty_fmt, color))

            # Columns width
            # ---------------------------

            col_stone = max(col_stone, len(stone_fmt))
            col_cut = max(col_cut, len(cut_fmt))
            col_size = max(col_size, len(size_fmt))

        for stone, cut, size, qty, color in gems_fmt_temp:
            row = f"{cut:{col_cut}}   {size:{col_size}}   {stone:{col_stone}}   {qty}"
            self.gems_fmt.append((row, color))
Beispiel #20
0
def write_mtl(scene, filepath, path_mode, copy_set, mtl_dict):
    from mathutils import Color

    world = scene.world
    if world:
        world_amb = world.ambient_color
    else:
        world_amb = Color((0.0, 0.0, 0.0))

    source_dir = os.path.dirname(bpy.data.filepath)
    dest_dir = os.path.dirname(filepath)

    file = open(filepath, "w", encoding="utf8", newline="\n")
    fw = file.write

    fw('# Blender MTL File: %r\n' %
       (os.path.basename(bpy.data.filepath) or "None"))
    fw('# Material Count: %i\n' % len(mtl_dict))

    mtl_dict_values = list(mtl_dict.values())
    mtl_dict_values.sort(key=lambda m: m[0])

    # Write material/image combinations we have used.
    # Using mtl_dict.values() directly gives un-predictable order.
    for mtl_mat_name, mat, face_img in mtl_dict_values:

        # Get the Blender data for the material and the image.
        # Having an image named None will make a bug, dont do it :)

        fw('newmtl %s\n' %
           mtl_mat_name)  # Define a new material: matname_imgname

        if mat:
            # convert from blenders spec to 0 - 1000 range.
            if mat.specular_shader == 'WARDISO':
                tspec = (0.4 - mat.specular_slope) / 0.0004
            else:
                tspec = (mat.specular_hardness - 1) * 1.9607843137254901
            fw('Ns %.6f\n' % tspec)
            del tspec

            fw('Ka %.6f %.6f %.6f\n' %
               (mat.ambient * world_amb)[:])  # Ambient, uses mirror color,
            fw('Kd %.6f %.6f %.6f\n' %
               (mat.diffuse_intensity * mat.diffuse_color)[:])  # Diffuse
            fw('Ks %.6f %.6f %.6f\n' %
               (mat.specular_intensity * mat.specular_color)[:])  # Specular
            if hasattr(mat, "ior"):
                fw('Ni %.6f\n' % mat.ior)  # Refraction index
            else:
                fw('Ni %.6f\n' % 1.0)
            fw('d %.6f\n' % mat.alpha)  # Alpha (obj uses 'd' for dissolve)

            # 0 to disable lighting, 1 for ambient & diffuse only (specular color set to black), 2 for full lighting.
            if mat.use_shadeless:
                fw('illum 0\n')  # ignore lighting
            elif mat.specular_intensity == 0:
                fw('illum 1\n')  # no specular.
            else:
                fw('illum 2\n')  # light normaly

        else:
            #write a dummy material here?
            fw('Ns 0\n')
            fw('Ka %.6f %.6f %.6f\n' %
               world_amb[:])  # Ambient, uses mirror color,
            fw('Kd 0.8 0.8 0.8\n')
            fw('Ks 0.8 0.8 0.8\n')
            fw('d 1\n')  # No alpha
            fw('illum 2\n')  # light normaly

        # Write images!
        if face_img:  # We have an image on the face!
            # write relative image path
            rel = bpy_extras.io_utils.path_reference(face_img.filepath,
                                                     source_dir, dest_dir,
                                                     path_mode, "", copy_set,
                                                     face_img.library)
            fw('map_Kd %s\n' % rel)  # Diffuse mapping image

        if mat:  # No face image. if we havea material search for MTex image.
            image_map = {}
            # backwards so topmost are highest priority
            for mtex in reversed(mat.texture_slots):
                if mtex and mtex.texture.type == 'IMAGE':
                    image = mtex.texture.image
                    if image:
                        # texface overrides others
                        if mtex.use_map_color_diffuse and face_img is None:
                            image_map["map_Kd"] = image
                        if mtex.use_map_ambient:
                            image_map["map_Ka"] = image
                        if mtex.use_map_specular:
                            image_map["map_Ks"] = image
                        if mtex.use_map_alpha:
                            image_map["map_d"] = image
                        if mtex.use_map_translucency:
                            image_map["map_Tr"] = image
                        if mtex.use_map_normal:
                            image_map["map_Bump"] = image
                        if mtex.use_map_hardness:
                            image_map["map_Ns"] = image

            for key, image in image_map.items():
                filepath = bpy_extras.io_utils.path_reference(
                    image.filepath, source_dir, dest_dir, path_mode, "",
                    copy_set, image.library)
                fw('%s %s\n' % (key, repr(filepath)[1:-1]))

        fw('\n\n')

    file.close()
Beispiel #21
0
    def __init__(self, particle_sys, mesh, bjsMesh, exporter):
        self.name = particle_sys.name
        self.legalName = legal_js_identifier(self.name)
        Logger.log('processing begun of particle hair:  ' + self.name, 2)

        self.bjsMesh = bjsMesh

        # make a child of the emitter in export
        self.parentId = bjsMesh.name

        # allow the parent mesh to declare this child correctly in .d.ts file
        self.userSuppliedBaseClass = 'QI.Hair'

        # since materials of mesh have already been processed, just need to assign it here
        bjsMaterial = exporter.getMaterial(particle_sys.settings.material_slot,
                                           True)
        if bjsMaterial is not None and hasattr(bjsMaterial, 'diffuse'):
            self.color = bjsMaterial.diffuse
        else:
            self.color = Color((1, 1, 1))

        # find the modifier name & temporarily convert it
        for mod in [m for m in mesh.modifiers if m.type == 'PARTICLE_SYSTEM']:
            bpy.ops.object.modifier_convert(modifier=mod.name)
            break

        scene = exporter.scene
        # get the new active mesh is the converted hair
        hairMesh = scene.objects.active
        nVertsBefore = len(hairMesh.data.vertices)
        #        verts = hairMesh.data.vertices
        #        edges = hairMesh.data.edges
        #        for idx, vert in enumerate(verts):
        #            print('vert: ' + str(idx) + ' location: ' + format_vector(vert.co) )

        #        for idx, edge in enumerate(edges):
        #            print('edge: ' + str(idx) + ' locations: ' + str(edge.vertices[0]) + ' and ' + str(edge.vertices[1]))

        # perform a limited Dissolve
        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.dissolve_limited(angle_limit=0.087)  # 5%
        bpy.ops.object.mode_set(mode='OBJECT')

        verts = hairMesh.data.vertices
        edges = hairMesh.data.edges

        self.strandNumVerts = []
        self.rootRelativePositions = []
        longestStrand = -1

        # determine the number of verts per stand after the dissolve & save rootRelative Positions
        nVerts = 0
        tailVertIdx = -1
        root = None
        self.longestStrand = -1
        for idx, edge in enumerate(edges):
            if tailVertIdx != edge.vertices[0]:
                # write out the stand length unless first strand
                if tailVertIdx != -1:
                    self.strandNumVerts.append(nVerts)
                    strandLength = self.length(tail.x - root.x,
                                               tail.z - root.z,
                                               tail.y - root.y)
                    if self.longestStrand < strandLength:
                        self.longestStrand = strandLength

                root = verts[edge.vertices[0]].co
                nVerts = 2

                # need to write both vertices at the beginning of a strand
                self.rootRelativePositions.append(root.x)
                self.rootRelativePositions.append(root.z)
                self.rootRelativePositions.append(root.y)

            else:
                nVerts += 1

            # always write the tail vertex
            tail = verts[edge.vertices[1]].co
            self.rootRelativePositions.append(tail.x - root.x)
            self.rootRelativePositions.append(tail.z - root.z)
            self.rootRelativePositions.append(tail.y - root.y)

            # always record tail vertex index for next test
            tailVertIdx = edge.vertices[1]

        # write out the last strand length
        self.strandNumVerts.append(nVerts)

        bpy.ops.object.delete(use_global=False)

        nStrands = len(self.strandNumVerts)
        nVerts = len(verts)
        Logger.log(
            '# of Strands: ' + str(nStrands) + ', reduced from ' +
            str(nVertsBefore) + ' to ' + str(nVerts), 3)
        Logger.log(
            'Avg # verts per strand reduced from ' +
            str(nVertsBefore / nStrands) + ' to ' + str(nVerts / nStrands), 3)
Beispiel #22
0
def get_vector(space, x):
    if space == 'RGB':
        return np.array(x[:3])
    elif space == 'HSV':
        return np.array(Color(x[:3]).hsv)
Beispiel #23
0
def pick_verts_by_AO_color(obj, min_threshold = 0.00, max_threshold = .95):
    """Paints a single vertex where vert is the index of the vertex
    and color is a tuple with the RGB values."""

    mesh = obj.data 
    
    vcol_layer = mesh.vertex_colors.get("AO")
    if vcol_layer == None:
        return
    
    #select and add color
    if "AO_select" not in obj.data.vertex_colors:
        vcol = obj.data.vertex_colors.new(name = "AO_select")
    else:
        vcol = obj.data.vertex_colors.get("AO_select")
    
    bme = bmesh.new()
    bme.from_mesh(obj.data)
    bme.verts.ensure_lookup_table()
    bme.faces.ensure_lookup_table() 
    bme.edges.ensure_lookup_table()
    
    ao_select_color_layer = bme.loops.layers.color["AO_select"]
    ao_bake_color_layer = bme.loops.layers.color["AO"]
    
    to_select = set()  
    for f in bme.faces: 
        for loop in f.loops:
            col = loop[ao_bake_color_layer]
            if any([(col[0] < max_threshold and col[0] > min_threshold),
                    (col[1] < max_threshold and col[1] > min_threshold),
                    (col[2] < max_threshold and col[2] > min_threshold)]):
                #loop.vert.select_set(True)  #actually select the vert
                to_select.add(loop.vert)
                loop[ao_select_color_layer] = Color((1,.2, .2))  #set the color so that it can be viewed in object mode, yay
    
    for f in bme.faces:
        f.select_set(False)
    for ed in bme.edges:
        ed.select_set(False)
        
    for v in bme.verts:
        if v in to_select:
            v.select_set(True)
        else:
            v.select_set(False)   
            
    bme.select_flush_mode()
    bme.to_mesh(obj.data)
    bme.free()
    
    if "AO" not in bpy.data.materials:
        mat = bpy.data.materials.new("AO")
        mat.use_shadeless = True
        mat.use_vertex_color_paint = True
    else:
        mat = bpy.data.materials.get("AO")
        mat.use_shadeless = True
        mat.use_vertex_color_paint = True
        
        
    #obj.data.vertex_colors.active = vcol
    print('setting the active vertex color')
    obj.data.vertex_colors.active = vcol
    for ind, v_color in enumerate(obj.data.vertex_colors):
        if v_color == vcol:
            break
    obj.data.vertex_colors.active_index = ind
    obj.data.vertex_colors.active = vcol
    
    print(vcol.name)
    print(obj.data.vertex_colors.active.name)
    # activate "Col" layer
    if m.vertex_colors.get("Col"):
        vc = m.vertex_colors["Col"]
        m.vertex_colors["Col"].active = True
    else:
        vc = None

    # select polygons that vertex colors are not used yet
    m.use_paint_mask = False
    if vc:
        i = 0
        for p in m.polygons:
            n = len(p.vertices)
            p.select = False
            for v in range(i, i + n):
                if vc.data[v].color != Color((1.0, 1.0, 1.0)):
                    m.use_paint_mask = True
                    break
            else:
                p.select = True
            i += n

    # create palette for the mesh if not existing
    try:
        C.tool_settings.vertex_paint.palette = D.palettes[m.name]
    except KeyError:
        C.tool_settings.vertex_paint.palette = D.palettes.new(m.name)

    # create "Diffuse" layer
    if m.vertex_colors.get("Diffuse"):
        m.vertex_colors.remove(
Beispiel #25
0
def avg_col(cols):
    avg_col = Color((0.0, 0.0, 0.0))
    for col in cols:
        avg_col += col / len(cols)
    return avg_col
def freestyle_to_gpencil_strokes(
        strokes, frame, lineset,
        options):  # draw_mode='3DSPACE', color_extraction='BASE'):
    mat = bpy.context.scene.camera.matrix_local.copy()

    # pick the active palette or create a default one
    grease_pencil = bpy.context.scene.grease_pencil
    palette = grease_pencil.palettes.active or grease_pencil.palettes.new(
        "GP_Palette")

    # can we tag the colors the script adds, to remove them when they are not used?
    cache = {color_to_hex(color.color): color for color in palette.colors}

    # keep track of which colors are used (to remove unused ones)
    used = []

    for fstroke in strokes:

        # the color object can be "owned", so use Color to clone it
        if options.color_extraction:
            if options.color_extraction_mode == 'FIRST':
                base_color = Color(fstroke[0].attribute.color)
            elif options.color_extraction_mode == 'FINAL':
                base_color = Color(fstroke[-1].attribute.color)
            else:
                base_color = Color(lineset.linestyle.color)

        # color has to be frozen (immutable) for it to be stored
        base_color.freeze()

        colorname = get_colorname(palette.colors, base_color, palette).name

        # append the current color, so it is kept
        used.append(colorname)

        gpstroke = frame.strokes.new(colorname=colorname)
        gpstroke.draw_mode = options.draw_mode
        gpstroke.points.add(count=len(fstroke), pressure=1, strength=1)

        # the max width gets pressure 1.0. Smaller widths get a pressure 0 <= x < 1
        base_width = functools.reduce(max, (sum(svert.attribute.thickness)
                                            for svert in fstroke),
                                      lineset.linestyle.thickness)

        # set the default (pressure == 1) width for the gpstroke
        gpstroke.line_width = base_width

        if options.draw_mode == '3DSPACE':
            for svert, point in zip(fstroke, gpstroke.points):
                point.co = mat * svert.point_3d
                # print(point.co, svert.point_3d)

                if options.thickness_extraction:
                    point.pressure = sum(svert.attribute.thickness) / max(
                        1e-6, base_width)

                if options.alpha_extraction:
                    point.strength = svert.attribute.alpha

        elif options.draw_mode == 'SCREEN':
            width, height = render_dimensions(bpy.context.scene)
            for svert, point in zip(fstroke, gpstroke.points):
                x, y = svert.point
                point.co = Vector((abs(x / width), abs(y / height), 0.0)) * 100

                if options.thickness_extraction:
                    point.pressure = sum(svert.attribute.thickness) / max(
                        1e-6, base_width)

                if options.alpha_extraction:
                    point.strength = svert.attribute.alpha

        else:
            raise NotImplementedError()
Beispiel #27
0
                                            z_eq="0.5*u",
                                            range_u_min=-2 * pi,
                                            range_u_max=2 * pi,
                                            range_u_step=256,
                                            wrap_u=False,
                                            range_v_min=-2,
                                            range_v_max=2,
                                            range_v_step=128,
                                            wrap_v=False)
bpy.context.object.name = 'surface'
surface = bpy.data.objects['surface']

# add material for surface
bpy.ops.material.new()
surf_mat = bpy.data.materials['Material']
surf_mat.diffuse_color = Color([x / 255 for x in (46, 125, 50)])
surf_mat.diffuse_intensity = 1
surf_mat.specular_intensity = 1
surf_mat.specular_hardness = 30
surf_mat.raytrace_mirror.use = True
surf_mat.raytrace_mirror.reflect_factor = 0.3
surface.data.materials.append(surf_mat)

# add lamps
for i in [-10, 10]:
    for j in [-10, 10]:
        for k in [-10, 10]:
            bpy.ops.object.lamp_add(type='POINT', location=(i, j, k))

for lamp in bpy.data.lamps:
    lamp.energy = 2.0
 def element_iterated(matrix, theta, index):
     return matrix, Color(vcol_start.lerp(vcol_end, index * theta))[:]
Beispiel #29
0
def create(obj):
    # generated by rigify.utils.write_metarig
    bpy.ops.object.mode_set(mode='EDIT')
    arm = obj.data

    for i in range(6):
        arm.rigify_colors.add()

    arm.rigify_colors[0].name = "Root"
    arm.rigify_colors[0].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.rigify_colors[0].normal = Color(
        (0.4352940022945404, 0.18431399762630463, 0.4156860113143921))
    arm.rigify_colors[0].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.rigify_colors[0].standard_colors_lock = True
    arm.rigify_colors[1].name = "IK"
    arm.rigify_colors[1].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.rigify_colors[1].normal = Color((0.6039220094680786, 0.0, 0.0))
    arm.rigify_colors[1].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.rigify_colors[1].standard_colors_lock = True
    arm.rigify_colors[2].name = "Specials"
    arm.rigify_colors[2].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.rigify_colors[2].normal = Color(
        (0.9568629860877991, 0.7882350087165833, 0.04705899953842163))
    arm.rigify_colors[2].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.rigify_colors[2].standard_colors_lock = True
    arm.rigify_colors[3].name = "Tweak"
    arm.rigify_colors[3].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.rigify_colors[3].normal = Color(
        (0.03921600058674812, 0.21176500618457794, 0.5803920030593872))
    arm.rigify_colors[3].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.rigify_colors[3].standard_colors_lock = True
    arm.rigify_colors[4].name = "FK"
    arm.rigify_colors[4].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.rigify_colors[4].normal = Color(
        (0.11764699965715408, 0.5686269998550415, 0.035294000059366226))
    arm.rigify_colors[4].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.rigify_colors[4].standard_colors_lock = True
    arm.rigify_colors[5].name = "Extra"
    arm.rigify_colors[5].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.rigify_colors[5].normal = Color(
        (0.9686279892921448, 0.2509799897670746, 0.09411799907684326))
    arm.rigify_colors[5].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.rigify_colors[5].standard_colors_lock = True

    for i in range(29):
        arm.rigify_layers.add()

    arm.rigify_layers[0].name = "Face"
    arm.rigify_layers[0].row = 1
    arm.rigify_layers[0].set = False
    arm.rigify_layers[0].group = 5
    arm.rigify_layers[1].name = "Face (Tweak)"
    arm.rigify_layers[1].row = 2
    arm.rigify_layers[1].set = False
    arm.rigify_layers[1].group = 4
    arm.rigify_layers[2].name = " "
    arm.rigify_layers[2].row = 1
    arm.rigify_layers[2].set = False
    arm.rigify_layers[2].group = 0
    arm.rigify_layers[3].name = "Spine"
    arm.rigify_layers[3].row = 3
    arm.rigify_layers[3].set = False
    arm.rigify_layers[3].group = 3
    arm.rigify_layers[4].name = "Spine (Tweak)"
    arm.rigify_layers[4].row = 4
    arm.rigify_layers[4].set = False
    arm.rigify_layers[4].group = 4
    arm.rigify_layers[5].name = "Tail"
    arm.rigify_layers[5].row = 5
    arm.rigify_layers[5].set = False
    arm.rigify_layers[5].group = 6
    arm.rigify_layers[6].name = "Fins.L"
    arm.rigify_layers[6].row = 6
    arm.rigify_layers[6].set = False
    arm.rigify_layers[6].group = 5
    arm.rigify_layers[7].name = "Fins.L (Tweak)"
    arm.rigify_layers[7].row = 7
    arm.rigify_layers[7].set = False
    arm.rigify_layers[7].group = 4
    arm.rigify_layers[8].name = "Fins.R"
    arm.rigify_layers[8].row = 6
    arm.rigify_layers[8].set = False
    arm.rigify_layers[8].group = 5
    arm.rigify_layers[9].name = "Fins.R (Tweak)"
    arm.rigify_layers[9].row = 7
    arm.rigify_layers[9].set = False
    arm.rigify_layers[9].group = 4
    arm.rigify_layers[10].name = "Fins"
    arm.rigify_layers[10].row = 8
    arm.rigify_layers[10].set = False
    arm.rigify_layers[10].group = 3
    arm.rigify_layers[11].name = "Fins (Tweak)"
    arm.rigify_layers[11].row = 9
    arm.rigify_layers[11].set = False
    arm.rigify_layers[11].group = 4
    arm.rigify_layers[12].name = " "
    arm.rigify_layers[12].row = 1
    arm.rigify_layers[12].set = False
    arm.rigify_layers[12].group = 0
    arm.rigify_layers[13].name = " "
    arm.rigify_layers[13].row = 1
    arm.rigify_layers[13].set = False
    arm.rigify_layers[13].group = 6
    arm.rigify_layers[14].name = " "
    arm.rigify_layers[14].row = 1
    arm.rigify_layers[14].set = False
    arm.rigify_layers[14].group = 0
    arm.rigify_layers[15].name = " "
    arm.rigify_layers[15].row = 1
    arm.rigify_layers[15].set = False
    arm.rigify_layers[15].group = 0
    arm.rigify_layers[16].name = " "
    arm.rigify_layers[16].row = 1
    arm.rigify_layers[16].set = False
    arm.rigify_layers[16].group = 0
    arm.rigify_layers[17].name = " "
    arm.rigify_layers[17].row = 1
    arm.rigify_layers[17].set = False
    arm.rigify_layers[17].group = 0
    arm.rigify_layers[18].name = " "
    arm.rigify_layers[18].row = 1
    arm.rigify_layers[18].set = False
    arm.rigify_layers[18].group = 0
    arm.rigify_layers[19].name = " "
    arm.rigify_layers[19].row = 1
    arm.rigify_layers[19].set = False
    arm.rigify_layers[19].group = 0
    arm.rigify_layers[20].name = " "
    arm.rigify_layers[20].row = 1
    arm.rigify_layers[20].set = False
    arm.rigify_layers[20].group = 0
    arm.rigify_layers[21].name = " "
    arm.rigify_layers[21].row = 1
    arm.rigify_layers[21].set = False
    arm.rigify_layers[21].group = 0
    arm.rigify_layers[22].name = " "
    arm.rigify_layers[22].row = 1
    arm.rigify_layers[22].set = False
    arm.rigify_layers[22].group = 0
    arm.rigify_layers[23].name = " "
    arm.rigify_layers[23].row = 1
    arm.rigify_layers[23].set = False
    arm.rigify_layers[23].group = 0
    arm.rigify_layers[24].name = " "
    arm.rigify_layers[24].row = 1
    arm.rigify_layers[24].set = False
    arm.rigify_layers[24].group = 0
    arm.rigify_layers[25].name = " "
    arm.rigify_layers[25].row = 1
    arm.rigify_layers[25].set = False
    arm.rigify_layers[25].group = 0
    arm.rigify_layers[26].name = " "
    arm.rigify_layers[26].row = 1
    arm.rigify_layers[26].set = False
    arm.rigify_layers[26].group = 0
    arm.rigify_layers[27].name = " "
    arm.rigify_layers[27].row = 1
    arm.rigify_layers[27].set = False
    arm.rigify_layers[27].group = 0
    arm.rigify_layers[28].name = "Root"
    arm.rigify_layers[28].row = 14
    arm.rigify_layers[28].set = False
    arm.rigify_layers[28].group = 1

    bones = {}

    bone = arm.edit_bones.new('spine')
    bone.head[:] = -0.0000, 1.3362, 0.4776
    bone.tail[:] = -0.0000, 1.0816, 0.4540
    bone.roll = 0.0000
    bone.use_connect = False
    bones['spine'] = bone.name
    bone = arm.edit_bones.new('spine.001')
    bone.head[:] = -0.0000, 1.0816, 0.4540
    bone.tail[:] = -0.0000, 0.7152, 0.4305
    bone.roll = -0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine']]
    bones['spine.001'] = bone.name
    bone = arm.edit_bones.new('back_fin.T.Bk')
    bone.head[:] = 0.0000, 1.2501, 0.5345
    bone.tail[:] = 0.0000, 1.5211, 0.7594
    bone.roll = 0.0000
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine']]
    bones['back_fin.T.Bk'] = bone.name
    bone = arm.edit_bones.new('back_fin.B.Bk')
    bone.head[:] = 0.0000, 1.2305, 0.4158
    bone.tail[:] = 0.0000, 1.3289, 0.2452
    bone.roll = 0.0000
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine']]
    bones['back_fin.B.Bk'] = bone.name
    bone = arm.edit_bones.new('spine.002')
    bone.head[:] = -0.0000, 0.7152, 0.4305
    bone.tail[:] = -0.0000, 0.3182, 0.4031
    bone.roll = -0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine.001']]
    bones['spine.002'] = bone.name
    bone = arm.edit_bones.new('mid_fin.Top')
    bone.head[:] = 0.0000, 0.7296, 0.5396
    bone.tail[:] = 0.0000, 0.7709, 0.6351
    bone.roll = 0.0000
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.001']]
    bones['mid_fin.Top'] = bone.name
    bone = arm.edit_bones.new('mid_fin.Bot')
    bone.head[:] = 0.0000, 0.7296, 0.3505
    bone.tail[:] = 0.0000, 0.8233, 0.2684
    bone.roll = 1.5708
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.001']]
    bones['mid_fin.Bot'] = bone.name
    bone = arm.edit_bones.new('back_fin.T.001.Bk')
    bone.head[:] = 0.0000, 1.5211, 0.7594
    bone.tail[:] = 0.0000, 1.7667, 0.9633
    bone.roll = 0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['back_fin.T.Bk']]
    bones['back_fin.T.001.Bk'] = bone.name
    bone = arm.edit_bones.new('back_fin.B.001.Bk')
    bone.head[:] = 0.0000, 1.3289, 0.2452
    bone.tail[:] = 0.0000, 1.3818, 0.1513
    bone.roll = 0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['back_fin.B.Bk']]
    bones['back_fin.B.001.Bk'] = bone.name
    bone = arm.edit_bones.new('spine.003')
    bone.head[:] = -0.0000, 0.3182, 0.4031
    bone.tail[:] = -0.0000, 0.0152, 0.3904
    bone.roll = 0.0001
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine.002']]
    bones['spine.003'] = bone.name
    bone = arm.edit_bones.new('back_fin.T.002.Bk')
    bone.head[:] = 0.0000, 1.7667, 0.9633
    bone.tail[:] = 0.0000, 1.9489, 1.1145
    bone.roll = 0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['back_fin.T.001.Bk']]
    bones['back_fin.T.002.Bk'] = bone.name
    bone = arm.edit_bones.new('spine.008')
    bone.head[:] = -0.0000, 0.0152, 0.3904
    bone.tail[:] = 0.0000, -0.3259, 0.3967
    bone.roll = 0.0001
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine.003']]
    bones['spine.008'] = bone.name
    bone = arm.edit_bones.new('spine.004')
    bone.head[:] = 0.0000, -0.3259, 0.3967
    bone.tail[:] = 0.0000, -0.5947, 0.4044
    bone.roll = -0.0001
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine.008']]
    bones['spine.004'] = bone.name
    bone = arm.edit_bones.new('chest_fin.Bot.L')
    bone.head[:] = 0.0889, 0.2605, 0.2866
    bone.tail[:] = 0.1731, 0.3299, 0.1901
    bone.roll = -2.3171
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.008']]
    bones['chest_fin.Bot.L'] = bone.name
    bone = arm.edit_bones.new('chest_fin.Bot.R')
    bone.head[:] = -0.0889, 0.2605, 0.2866
    bone.tail[:] = -0.1731, 0.3299, 0.1901
    bone.roll = 2.3171
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.008']]
    bones['chest_fin.Bot.R'] = bone.name
    bone = arm.edit_bones.new('spine.005')
    bone.head[:] = 0.0000, -0.5947, 0.4044
    bone.tail[:] = 0.0000, -1.2084, 0.4328
    bone.roll = 0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine.004']]
    bones['spine.005'] = bone.name
    bone = arm.edit_bones.new('top_fin')
    bone.head[:] = 0.0000, -0.2777, 0.5550
    bone.tail[:] = 0.0000, -0.1962, 0.7053
    bone.roll = 0.0000
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.004']]
    bones['top_fin'] = bone.name
    bone = arm.edit_bones.new('spine.006')
    bone.head[:] = 0.0000, -1.2084, 0.4328
    bone.tail[:] = 0.0000, -1.5634, 0.4275
    bone.roll = -0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine.005']]
    bones['spine.006'] = bone.name
    bone = arm.edit_bones.new('shoulder.L')
    bone.head[:] = 0.0729, -0.9648, 0.3756
    bone.tail[:] = 0.2649, -0.9648, 0.3157
    bone.roll = 3.4558
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.005']]
    bones['shoulder.L'] = bone.name
    bone = arm.edit_bones.new('shoulder.R')
    bone.head[:] = -0.0729, -0.9648, 0.3756
    bone.tail[:] = -0.2649, -0.9648, 0.3157
    bone.roll = -3.4558
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.005']]
    bones['shoulder.R'] = bone.name
    bone = arm.edit_bones.new('top_fin.001')
    bone.head[:] = 0.0000, -0.1962, 0.7053
    bone.tail[:] = 0.0000, -0.1362, 0.8158
    bone.roll = 0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['top_fin']]
    bones['top_fin.001'] = bone.name
    bone = arm.edit_bones.new('spine.007')
    bone.head[:] = 0.0000, -1.5634, 0.4275
    bone.tail[:] = 0.0000, -2.0661, 0.4364
    bone.roll = 0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['spine.006']]
    bones['spine.007'] = bone.name
    bone = arm.edit_bones.new('side_fin.L')
    bone.head[:] = 0.2140, -0.9624, 0.2213
    bone.tail[:] = 0.5220, -0.9078, -0.1343
    bone.roll = -2.3170
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['shoulder.L']]
    bones['side_fin.L'] = bone.name
    bone = arm.edit_bones.new('side_fin.R')
    bone.head[:] = -0.2140, -0.9624, 0.2213
    bone.tail[:] = -0.5220, -0.9078, -0.1343
    bone.roll = 2.3170
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['shoulder.R']]
    bones['side_fin.R'] = bone.name
    bone = arm.edit_bones.new('eye.L')
    bone.head[:] = 0.1405, -1.6860, 0.4161
    bone.tail[:] = 0.3684, -1.6810, 0.4156
    bone.roll = 3.1352
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.007']]
    bones['eye.L'] = bone.name
    bone = arm.edit_bones.new('eye.R')
    bone.head[:] = -0.1405, -1.6860, 0.4161
    bone.tail[:] = -0.3684, -1.6810, 0.4156
    bone.roll = -3.1352
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.007']]
    bones['eye.R'] = bone.name
    bone = arm.edit_bones.new('jaw.master')
    bone.head[:] = -0.0000, -1.5791, 0.2788
    bone.tail[:] = 0.0000, -1.9421, 0.3386
    bone.roll = 0.0000
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['spine.007']]
    bones['jaw.master'] = bone.name
    bone = arm.edit_bones.new('side_fin.L.001')
    bone.head[:] = 0.5220, -0.9078, -0.1343
    bone.tail[:] = 0.7928, -0.7598, -0.4802
    bone.roll = -2.2826
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['side_fin.L']]
    bones['side_fin.L.001'] = bone.name
    bone = arm.edit_bones.new('side_fin.R.001')
    bone.head[:] = -0.5220, -0.9078, -0.1343
    bone.tail[:] = -0.7928, -0.7598, -0.4802
    bone.roll = 2.2826
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['side_fin.R']]
    bones['side_fin.R.001'] = bone.name
    bone = arm.edit_bones.new('jaw')
    bone.head[:] = -0.0000, -1.5791, 0.2788
    bone.tail[:] = 0.0000, -1.7326, 0.3041
    bone.roll = 0.0000
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['jaw.master']]
    bones['jaw'] = bone.name
    bone = arm.edit_bones.new('jaw.002.L')
    bone.head[:] = 0.0891, -1.5791, 0.2894
    bone.tail[:] = 0.1110, -1.7198, 0.3129
    bone.roll = 1.4894
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['jaw.master']]
    bones['jaw.002.L'] = bone.name
    bone = arm.edit_bones.new('jaw.002.R')
    bone.head[:] = -0.0891, -1.5791, 0.2894
    bone.tail[:] = -0.1110, -1.7198, 0.3129
    bone.roll = -1.4894
    bone.use_connect = False
    bone.parent = arm.edit_bones[bones['jaw.master']]
    bones['jaw.002.R'] = bone.name
    bone = arm.edit_bones.new('jaw.001')
    bone.head[:] = 0.0000, -1.7326, 0.3041
    bone.tail[:] = 0.0000, -1.8860, 0.3294
    bone.roll = 0.0000
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['jaw']]
    bones['jaw.001'] = bone.name
    bone = arm.edit_bones.new('jaw.003.L')
    bone.head[:] = 0.1110, -1.7198, 0.3129
    bone.tail[:] = 0.1260, -1.8159, 0.3326
    bone.roll = 1.2807
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['jaw.002.L']]
    bones['jaw.003.L'] = bone.name
    bone = arm.edit_bones.new('jaw.003.R')
    bone.head[:] = -0.1110, -1.7198, 0.3129
    bone.tail[:] = -0.1260, -1.8159, 0.3326
    bone.roll = -1.2807
    bone.use_connect = True
    bone.parent = arm.edit_bones[bones['jaw.002.R']]
    bones['jaw.003.R'] = bone.name

    bpy.ops.object.mode_set(mode='OBJECT')
    pbone = obj.pose.bones[bones['spine']]
    pbone.rigify_type = 'spines.super_spine'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, True, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.neck_pos = 8
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, True, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.tail_pos = 3
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.pivot_pos = 5
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.use_tail = True
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.copy_rotation_axes = [True, False, True]
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['spine.001']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, True, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['back_fin.T.Bk']]
    pbone.rigify_type = 'limbs.super_finger'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, False, False, False, True, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.primary_rotation_axis = "Z"
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['back_fin.B.Bk']]
    pbone.rigify_type = 'limbs.super_finger'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, False, False, False, True, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.primary_rotation_axis = "Z"
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['spine.002']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, True, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['mid_fin.Top']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['mid_fin.Bot']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, True, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['back_fin.T.001.Bk']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['back_fin.B.001.Bk']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['spine.003']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['back_fin.T.002.Bk']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['spine.008']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['spine.004']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['chest_fin.Bot.L']]
    pbone.rigify_type = 'basic.super_copy'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, True, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['chest_fin.Bot.R']]
    pbone.rigify_type = 'basic.super_copy'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, False, True, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['spine.005']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['top_fin']]
    pbone.rigify_type = 'limbs.simple_tentacle'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, False, False, False, False, False,
            False, False, True, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['spine.006']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['shoulder.L']]
    pbone.rigify_type = 'basic.super_copy'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.make_widget = False
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['shoulder.R']]
    pbone.rigify_type = 'basic.super_copy'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.make_widget = False
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['top_fin.001']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['spine.007']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, True, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['side_fin.L']]
    pbone.rigify_type = 'limbs.simple_tentacle'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, True, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, False, False, False, True, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.copy_rotation_axes = [True, False, False]
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['side_fin.R']]
    pbone.rigify_type = 'limbs.simple_tentacle'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, True, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.tweak_layers = [
            False, False, False, False, False, False, False, False, False,
            True, False, False, False, False, False, False, False, False,
            False, False, False, False, False, False, False, False, False,
            False, False, False, False, False
        ]
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.copy_rotation_axes = [True, False, False]
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['eye.L']]
    pbone.rigify_type = 'basic.super_copy'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['eye.R']]
    pbone.rigify_type = 'basic.super_copy'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['jaw.master']]
    pbone.rigify_type = 'basic.super_copy'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    try:
        pbone.rigify_parameters.make_widget = False
    except AttributeError:
        pass
    try:
        pbone.rigify_parameters.make_deform = False
    except AttributeError:
        pass
    pbone = obj.pose.bones[bones['side_fin.L.001']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, True, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['side_fin.R.001']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, True, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['jaw']]
    pbone.rigify_type = 'limbs.simple_tentacle'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['jaw.002.L']]
    pbone.rigify_type = 'limbs.simple_tentacle'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['jaw.002.R']]
    pbone.rigify_type = 'limbs.simple_tentacle'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['jaw.001']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['jaw.003.L']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]
    pbone = obj.pose.bones[bones['jaw.003.R']]
    pbone.rigify_type = ''
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        True, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False
    ]

    bpy.ops.object.mode_set(mode='EDIT')
    for bone in arm.edit_bones:
        bone.select = False
        bone.select_head = False
        bone.select_tail = False
    for b in bones:
        bone = arm.edit_bones[bones[b]]
        bone.select = True
        bone.select_head = True
        bone.select_tail = True
        arm.edit_bones.active = bone

    arm.layers = [(x in [0, 3, 5, 6, 8, 10]) for x in range(32)]
Beispiel #30
0
def write_mtl(scene, filepath, path_mode, copy_set, mtl_dict):
    world = scene.world
    world_amb = Color((0.8, 0.8, 0.8))

    source_dir = os.path.dirname(bpy.data.filepath)
    dest_dir = os.path.dirname(filepath)

    with open(filepath, "w", encoding="utf8", newline="\n") as f:
        fw = f.write

        fw('# Blender MTL File: %r\n' % (os.path.basename(bpy.data.filepath) or "None"))
        fw('# Material Count: %i\n' % len(mtl_dict))

        mtl_dict_values = list(mtl_dict.values())
        mtl_dict_values.sort(key=lambda m: m[0])

        # Write material/image combinations we have used.
        # Using mtl_dict.values() directly gives un-predictable order.
        for mtl_mat_name, mat in mtl_dict_values:
            # Get the Blender data for the material and the image.
            # Having an image named None will make a bug, dont do it :)

            fw('\nnewmtl %s\n' % mtl_mat_name)  # Define a new material: matname_imgname

            mat_wrap = node_shader_utils.PrincipledBSDFWrapper(mat) if mat else None

            if mat_wrap:
                use_mirror = mat_wrap.metallic != 0.0
                use_transparency = mat_wrap.alpha != 1.0

                # XXX Totally empirical conversion, trying to adapt it
                #     (from 1.0 - 0.0 Principled BSDF range to 0.0 - 900.0 OBJ specular exponent range)...
                spec = (1.0 - mat_wrap.roughness) * 30
                spec *= spec
                fw('Ns %.6f\n' % spec)

                # Ambient
                if use_mirror:
                    fw('Ka %.6f %.6f %.6f\n' % (mat_wrap.metallic, mat_wrap.metallic, mat_wrap.metallic))
                else:
                    fw('Ka %.6f %.6f %.6f\n' % (1.0, 1.0, 1.0))
                fw('Kd %.6f %.6f %.6f\n' % mat_wrap.base_color[:3])  # Diffuse
                # XXX TODO Find a way to handle tint and diffuse color, in a consistent way with import...
                fw('Ks %.6f %.6f %.6f\n' % (mat_wrap.specular, mat_wrap.specular, mat_wrap.specular))  # Specular
                # Emission, not in original MTL standard but seems pretty common, see T45766.
                # XXX Not supported by current Principled-based shader.
                fw('Ke 0.0 0.0 0.0\n')
                fw('Ni %.6f\n' % mat_wrap.ior)  # Refraction index
                fw('d %.6f\n' % mat_wrap.alpha)  # Alpha (obj uses 'd' for dissolve)
                
                fw('Pr %.6f\n' % mat_wrap.roughness) # Roughness
                fw('Pm %.6f\n' % mat_wrap.metallic) # Metallic
                fw('Ps %.6f\n' % mat_wrap.sheen)
                fw('Pc %.6f\n' % mat_wrap.clearcoat)
                fw('Pcr %.6f\n' % mat_wrap.clearcoat_roughness)
                fw('aniso %.6f\n' % mat_wrap.anisotropic)
                fw('anisor %.6f\n' % mat_wrap.anisotropic_rotation)

                # See http://en.wikipedia.org/wiki/Wavefront_.obj_file for whole list of values...
                # Note that mapping is rather fuzzy sometimes, trying to do our best here.
                if mat_wrap.specular == 0:
                    fw('illum 1\n')  # no specular.
                elif use_mirror:
                    if use_transparency:
                        fw('illum 6\n')  # Reflection, Transparency, Ray trace
                    else:
                        fw('illum 3\n')  # Reflection and Ray trace
                elif use_transparency:
                    fw('illum 9\n')  # 'Glass' transparency and no Ray trace reflection... fuzzy matching, but...
                else:
                    fw('illum 2\n')  # light normally

                #### And now, the image textures...
                image_map = {
                        "map_Kd": "base_color_texture",
                        "map_Ka": None,  # ambient...
                        "map_Ks": "specular_texture",
                        "map_Pr": "roughness_texture",
                        "map_d": "alpha_texture",
                        "map_Tr": None,  # transmission roughness?
                        "map_Bump": "normalmap_texture",
                        "disp": None,  # displacement...
                        "map_Pm": "metallic_texture",
                        "map_Ke": None,  # emission...
                        "map_Ps": "sheen_texture"
                        }

                for key, mat_wrap_key in sorted(image_map.items()):
                    if mat_wrap_key is None:
                        continue
                    tex_wrap = getattr(mat_wrap, mat_wrap_key, None)
                    if tex_wrap is None:
                        continue
                    image = tex_wrap.image
                    if image is None:
                        continue

                    filepath = io_utils.path_reference(image.filepath, source_dir, dest_dir,
                                                       path_mode, "", copy_set, image.library)
                    options = []
                    if key == "map_Bump":
                        if mat_wrap.normalmap_strength != 1.0:
                            options.append('-bm %.6f' % mat_wrap.normalmap_strength)
                    if tex_wrap.translation != Vector((0.0, 0.0, 0.0)):
                        options.append('-o %.6f %.6f %.6f' % tex_wrap.translation[:])
                    if tex_wrap.scale != Vector((1.0, 1.0, 1.0)):
                        options.append('-s %.6f %.6f %.6f' % tex_wrap.scale[:])
                    if options:
                        fw('%s %s %s\n' % (key, " ".join(options), repr(filepath)[1:-1]))
                    else:
                        fw('%s %s\n' % (key, repr(filepath)[1:-1]))

            else:
                # Write a dummy material here?
                fw('Ns 500\n')
                fw('Ka 0.8 0.8 0.8\n')
                fw('Kd 0.8 0.8 0.8\n')
                fw('Ks 0.8 0.8 0.8\n')
                fw('d 1\n')  # No alpha
                fw('illum 2\n')  # light normally
Beispiel #31
0
 def emission_color_get(self):
     if not self.use_nodes or self.node_principled_bsdf is None:
         return Color((0.0, 0.0, 0.0))
     return rgba_to_rgb(self.node_principled_bsdf.inputs["Emission"].default_value)
def remove_undercuts(context, ob, view, world = True, smooth = True, epsilon = .000001):
    '''
    args:
      ob - mesh object
      view - Mathutils Vector
      
    return:
       Bmesh with Undercuts Removed?
       
    best to make sure normals are consistent beforehand
    best for manifold meshes, however non-man works
    noisy meshes can be compensated for with island threhold
    '''
    
        
    #careful, this can get expensive with multires
    me = ob.to_mesh(context.scene, True, 'RENDER')    
    bme = bmesh.new()
    bme.from_mesh(me)
    bme.normal_update()
    bme.verts.ensure_lookup_table()
    bme.edges.ensure_lookup_table()
    bme.faces.ensure_lookup_table()
    
    bvh = BVHTree.FromBMesh(bme)
    
    #keep track of the world matrix
    mx = ob.matrix_world
    
    if world:
        #meaning the vector is in world coords
        #we need to take it back into local
        i_mx = mx.inverted()
        view = i_mx.to_quaternion() * view
            
    face_directions = [[0]] * len(bme.faces)
    
    up_faces = set()
    overhang_faces = set()  #all faces pointing away from view
    #precalc all the face directions and store in dict
    for f in bme.faces:
        direction = f.normal.dot(view)
        
        if direction <= -epsilon:
            overhang_faces.add(f)
        else:
            up_faces.add(f)
            
        face_directions[f.index] = direction
    
    print('there are %i up_faces' % len(up_faces))
    print('there are %i down_faces' % len(overhang_faces))
    
    
    #for f in bme.faces:
    #    if f in overhangs:
    #        f.select_set(True)
    #    else:
    #        f.select_set(False)
            
    overhang_islands = [] #islands bigger than a certain threshold (by surface area?
    upfacing_islands = []
    def face_neighbors_up(bmface):
        neighbors = []
        for ed in bmface.edges:
            neighbors += [f for f in ed.link_faces if f != bmface and f in up_faces]
            
        return neighbors
    #remove smal islands from up_faces and add to overhangs
    max_iters = len(up_faces)
    iters_0 = 0
    islands_removed = 0
    
    up_faces_copy = up_faces.copy()
    while len(up_faces_copy) and iters_0 < max_iters:
        iters_0 += 1
        max_iters_1 = len(up_faces)
        seed = up_faces_copy.pop()
        new_faces = set(face_neighbors_up(seed))
        up_faces_copy -= new_faces
        
        island = set([seed])
        island |= new_faces
        
        iters_1 = 0
        while iters_1 < max_iters_1 and new_faces:
            iters_1 += 1
            new_candidates = set()
            for f in new_faces:
                new_candidates.update(face_neighbors_up(f))
            
            new_faces = new_candidates - island
        
            if new_faces:
                island |= new_faces    
                up_faces_copy -= new_faces
        if len(island) < 75: #small patch surrounded by overhang, add to overhang area
            islands_removed += 1
            overhang_faces |= island
        else:
            upfacing_islands += [island]
            
    print('%i upfacing islands removed' % islands_removed)
    print('there are now %i down faces' % len(overhang_faces))
    
    def face_neighbors_down(bmface):
        neighbors = []
        for ed in bmface.edges:
            neighbors += [f for f in ed.link_faces if f != bmface and f in overhang_faces]
            
        return neighbors
    overhang_faces_copy = overhang_faces.copy()
    
    while len(overhang_faces_copy):
        seed = overhang_faces_copy.pop()
        new_faces = set(face_neighbors_down(seed))
        island = set([seed])
        island |= new_faces
        overhang_faces_copy -= new_faces
        iters = 0
        while iters < 100000 and new_faces:
            iters += 1
            new_candidates = set()
            for f in new_faces:
                new_candidates.update(face_neighbors_down(f))
            
            new_faces = new_candidates - island
        
            if new_faces:
                island |= new_faces    
                overhang_faces_copy -= new_faces
        if len(island) > 75: #TODO, calc overhang factor.  Surface area dotted with direction
            overhang_islands += [island]
    
    for f in bme.faces:
        f.select_set(False)   
    for ed in bme.edges:
        ed.select_set(False)
    for v in bme.verts:
        v.select_set(False)
            
    island_loops = []
    island_verts = []
    del_faces = set()
    for isl in overhang_islands:
        loop_eds = []
        loop_verts = []
        del_faces |= isl
        for f in isl:
            for ed in f.edges:
                if len(ed.link_faces) == 1:
                    loop_eds += [ed]
                    loop_verts += [ed.verts[0], ed.verts[1]]
                elif (ed.link_faces[0] in isl) and (ed.link_faces[1] not in isl):
                    loop_eds += [ed]
                    loop_verts += [ed.verts[0], ed.verts[1]]
                elif (ed.link_faces[1] in isl) and (ed.link_faces[0] not in isl):
                    loop_eds += [ed]
                    loop_verts += [ed.verts[0], ed.verts[1]]
                    
            #f.select_set(True) 
        island_verts += [list(set(loop_verts))]
        island_loops += [loop_eds]
    
    bme.faces.ensure_lookup_table()
    bme.edges.ensure_lookup_table()
    
    loop_edges = []
    for ed_loop in island_loops:
        loop_edges += ed_loop
        for ed in ed_loop:
            ed.select_set(True)
    
    loops_tools.relax_loops_util(bme, loop_edges, 5)
    
    for ed in bme.edges:
        ed.select_set(False)
        
    exclude_vs = set()
    for vs in island_verts:
        exclude_vs.update(vs)
    
    smooth_verts = []    
    for v in exclude_vs:
        smooth_verts += [ed.other_vert(v) for ed in v.link_edges if ed.other_vert(v) not in exclude_vs]
            
    ret = bmesh.ops.extrude_edge_only(bme, edges = loop_edges)
    
    
    new_fs = [ele for ele in ret['geom'] if isinstance(ele, bmesh.types.BMFace)]                
    new_vs = [ele for ele in ret['geom'] if isinstance(ele, bmesh.types.BMVert)]
    
    #TODO, ray cast down to base plane?
    for v in new_vs:
        v.co -= 10*view
    
    for f in new_fs:
        f.select_set(True)
        
    bmesh.ops.delete(bme, geom = list(del_faces), context = 3)
    
    del_verts = []
    for v in bme.verts:
        if all([f in del_faces for f in v.link_faces]):
            del_verts += [v]        
    bmesh.ops.delete(bme, geom = del_verts, context = 1)
    
    
    del_edges = []
    for ed in bme.edges:
        if len(ed.link_faces) == 0:
            del_edges += [ed]
    print('deleting %i edges' % len(del_edges))
    bmesh.ops.delete(bme, geom = del_edges, context = 4) 
    bmesh.ops.recalc_face_normals(bme, faces = new_fs)
    
    bme.normal_update()
    
    new_me = bpy.data.meshes.new(ob.name + '_blockout')
    
    obj = bpy.data.objects.new(new_me.name, new_me)
    context.scene.objects.link(obj)
    
    obj.select = True
    context.scene.objects.active = obj
    
    bme.to_mesh(obj.data)
    # Get material
    mat = bpy.data.materials.get("Model Material")
    if mat is None:
        # create material
        print('creating model material')
        mat = bpy.data.materials.new(name="Model Material")
        #mat.diffuse_color = Color((0.8, .8, .8))
    
    # Assign it to object
    obj.data.materials.append(mat)
    print('Model material added')
    
    mat2 = bpy.data.materials.get("Undercut Material")
    if mat2 is None:
        # create material
        mat2 = bpy.data.materials.new(name="Undercut Material")
        mat2.diffuse_color = Color((0.8, .2, .2))
    

    obj.data.materials.append(mat2)
    mat_ind = obj.data.materials.find("Undercut Material")
    print('Undercut material is %i' % mat_ind)
    
    for f in new_faces:
        obj.data.polygons[f.index].material_index = mat_ind
            
    if world:
        obj.matrix_world = mx

    bme.free()
    del bvh
        
    return
Beispiel #33
0
def random_color():
    return Color((random(), random(), random()))
Beispiel #34
0
def create(obj):
    # generated by gamerig.utils.write_metarig
    bpy.ops.object.mode_set(mode='EDIT')
    arm = obj.data

    arm.gamerig.rig_ui_template = 'ui_template'

    for i in range(6):
        arm.gamerig.colors.add()

    arm.gamerig.colors[0].name = "Root"
    arm.gamerig.colors[0].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.gamerig.colors[0].normal = Color(
        (0.4352940022945404, 0.18431399762630463, 0.4156860113143921))
    arm.gamerig.colors[0].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.gamerig.colors[0].standard_colors_lock = True
    arm.gamerig.colors[1].name = "IK"
    arm.gamerig.colors[1].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.gamerig.colors[1].normal = Color((0.6039220094680786, 0.0, 0.0))
    arm.gamerig.colors[1].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.gamerig.colors[1].standard_colors_lock = True
    arm.gamerig.colors[2].name = "Special"
    arm.gamerig.colors[2].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.gamerig.colors[2].normal = Color(
        (0.9568629860877991, 0.7882350087165833, 0.04705899953842163))
    arm.gamerig.colors[2].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.gamerig.colors[2].standard_colors_lock = True
    arm.gamerig.colors[3].name = "Tweak"
    arm.gamerig.colors[3].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.gamerig.colors[3].normal = Color(
        (0.03921600058674812, 0.21176500618457794, 0.5803920030593872))
    arm.gamerig.colors[3].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.gamerig.colors[3].standard_colors_lock = True
    arm.gamerig.colors[4].name = "FK"
    arm.gamerig.colors[4].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.gamerig.colors[4].normal = Color(
        (0.11764699965715408, 0.5686269998550415, 0.035294000059366226))
    arm.gamerig.colors[4].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.gamerig.colors[4].standard_colors_lock = True
    arm.gamerig.colors[5].name = "Extra"
    arm.gamerig.colors[5].active = Color((0.5490196347236633, 1.0, 1.0))
    arm.gamerig.colors[5].normal = Color(
        (0.9686279892921448, 0.2509799897670746, 0.09411799907684326))
    arm.gamerig.colors[5].select = Color(
        (0.31372547149658203, 0.7843138575553894, 1.0))
    arm.gamerig.colors[5].standard_colors_lock = True

    for i in range(30):
        arm.gamerig.layers.add()

    arm.gamerig.layers[0].name = "Face"
    arm.gamerig.layers[0].row = 1
    arm.gamerig.layers[0].selset = False
    arm.gamerig.layers[0].group = 5
    arm.gamerig.layers[1].name = "Face (Primary)"
    arm.gamerig.layers[1].row = 2
    arm.gamerig.layers[1].selset = False
    arm.gamerig.layers[1].group = 2
    arm.gamerig.layers[2].name = "Face (Secondary)"
    arm.gamerig.layers[2].row = 2
    arm.gamerig.layers[2].selset = False
    arm.gamerig.layers[2].group = 3
    arm.gamerig.layers[3].name = "Torso"
    arm.gamerig.layers[3].row = 3
    arm.gamerig.layers[3].selset = False
    arm.gamerig.layers[3].group = 3
    arm.gamerig.layers[4].name = "Torso (Tweak)"
    arm.gamerig.layers[4].row = 4
    arm.gamerig.layers[4].selset = False
    arm.gamerig.layers[4].group = 4
    arm.gamerig.layers[5].name = "Fingers"
    arm.gamerig.layers[5].row = 5
    arm.gamerig.layers[5].selset = False
    arm.gamerig.layers[5].group = 6
    arm.gamerig.layers[6].name = "Fingers (Tweak)"
    arm.gamerig.layers[6].row = 6
    arm.gamerig.layers[6].selset = False
    arm.gamerig.layers[6].group = 4
    arm.gamerig.layers[7].name = "Arm.L (IK)"
    arm.gamerig.layers[7].row = 7
    arm.gamerig.layers[7].selset = False
    arm.gamerig.layers[7].group = 2
    arm.gamerig.layers[8].name = "Arm.L (FK)"
    arm.gamerig.layers[8].row = 8
    arm.gamerig.layers[8].selset = False
    arm.gamerig.layers[8].group = 5
    arm.gamerig.layers[9].name = "Arm.L (Tweak)"
    arm.gamerig.layers[9].row = 9
    arm.gamerig.layers[9].selset = False
    arm.gamerig.layers[9].group = 4
    arm.gamerig.layers[10].name = "Arm.R (IK)"
    arm.gamerig.layers[10].row = 7
    arm.gamerig.layers[10].selset = False
    arm.gamerig.layers[10].group = 2
    arm.gamerig.layers[11].name = "Arm.R (FK)"
    arm.gamerig.layers[11].row = 8
    arm.gamerig.layers[11].selset = False
    arm.gamerig.layers[11].group = 5
    arm.gamerig.layers[12].name = "Arm.R (Tweak)"
    arm.gamerig.layers[12].row = 9
    arm.gamerig.layers[12].selset = False
    arm.gamerig.layers[12].group = 4
    arm.gamerig.layers[13].name = "Leg.L (IK)"
    arm.gamerig.layers[13].row = 10
    arm.gamerig.layers[13].selset = False
    arm.gamerig.layers[13].group = 2
    arm.gamerig.layers[14].name = "Leg.L (FK)"
    arm.gamerig.layers[14].row = 11
    arm.gamerig.layers[14].selset = False
    arm.gamerig.layers[14].group = 5
    arm.gamerig.layers[15].name = "Leg.L (Tweak)"
    arm.gamerig.layers[15].row = 12
    arm.gamerig.layers[15].selset = False
    arm.gamerig.layers[15].group = 4
    arm.gamerig.layers[16].name = "Leg.R (IK)"
    arm.gamerig.layers[16].row = 10
    arm.gamerig.layers[16].selset = False
    arm.gamerig.layers[16].group = 2
    arm.gamerig.layers[17].name = "Leg.R (FK)"
    arm.gamerig.layers[17].row = 11
    arm.gamerig.layers[17].selset = False
    arm.gamerig.layers[17].group = 5
    arm.gamerig.layers[18].name = "Leg.R (Tweak)"
    arm.gamerig.layers[18].row = 12
    arm.gamerig.layers[18].selset = False
    arm.gamerig.layers[18].group = 4
    arm.gamerig.layers[19].name = ""
    arm.gamerig.layers[19].row = 1
    arm.gamerig.layers[19].selset = False
    arm.gamerig.layers[19].group = 0
    arm.gamerig.layers[20].name = ""
    arm.gamerig.layers[20].row = 1
    arm.gamerig.layers[20].selset = False
    arm.gamerig.layers[20].group = 0
    arm.gamerig.layers[21].name = ""
    arm.gamerig.layers[21].row = 1
    arm.gamerig.layers[21].selset = False
    arm.gamerig.layers[21].group = 0
    arm.gamerig.layers[22].name = ""
    arm.gamerig.layers[22].row = 1
    arm.gamerig.layers[22].selset = False
    arm.gamerig.layers[22].group = 0
    arm.gamerig.layers[23].name = ""
    arm.gamerig.layers[23].row = 1
    arm.gamerig.layers[23].selset = False
    arm.gamerig.layers[23].group = 0
    arm.gamerig.layers[24].name = ""
    arm.gamerig.layers[24].row = 1
    arm.gamerig.layers[24].selset = False
    arm.gamerig.layers[24].group = 0
    arm.gamerig.layers[25].name = ""
    arm.gamerig.layers[25].row = 1
    arm.gamerig.layers[25].selset = False
    arm.gamerig.layers[25].group = 0
    arm.gamerig.layers[26].name = ""
    arm.gamerig.layers[26].row = 1
    arm.gamerig.layers[26].selset = False
    arm.gamerig.layers[26].group = 0
    arm.gamerig.layers[27].name = ""
    arm.gamerig.layers[27].row = 1
    arm.gamerig.layers[27].selset = False
    arm.gamerig.layers[27].group = 0
    arm.gamerig.layers[28].name = ""
    arm.gamerig.layers[28].row = 1
    arm.gamerig.layers[28].selset = False
    arm.gamerig.layers[28].group = 0
    arm.gamerig.layers[29].name = "Root"
    arm.gamerig.layers[29].row = 14
    arm.gamerig.layers[29].selset = False
    arm.gamerig.layers[29].group = 1

    bones = {}

    bone = arm.edit_bones.new('Bone')
    bone.head[:] = 0.0000, 0.0000, 0.0000
    bone.tail[:] = 0.0000, 1.0000, 0.0000
    bone.roll = 0.0000
    bone.use_connect = False
    bone.use_deform = False
    bones['Bone'] = bone.name

    bpy.ops.object.mode_set(mode='OBJECT')
    pbone = obj.pose.bones[bones['Bone']]
    pbone.gamerig.name = 'root'
    pbone.lock_location = (False, False, False)
    pbone.lock_rotation = (False, False, False)
    pbone.lock_rotation_w = False
    pbone.lock_scale = (False, False, False)
    pbone.rotation_mode = 'QUATERNION'
    pbone.bone.layers = [
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, True,
        False, False
    ]

    bpy.ops.object.mode_set(mode='EDIT')
    for bone in arm.edit_bones:
        bone.select = False
        bone.select_head = False
        bone.select_tail = False
    for b in bones:
        bone = arm.edit_bones[bones[b]]
        bone.select = True
        bone.select_head = True
        bone.select_tail = True
        arm.edit_bones.active = bone

    arm.layers = [(x in [29]) for x in range(32)]
Beispiel #35
0
 def convert_color(rna_prop):
     return Color(rna_prop.default_array)
Beispiel #36
0
def rgba_to_rgb(rgba):
    return Color((rgba[0], rgba[1], rgba[2]))
Beispiel #37
0
def write_mtl(scene, filepath, path_mode, copy_set, mtl_dict):
    from mathutils import Color

    world = scene.world
    if world:
        world_amb = world.ambient_color
    else:
        world_amb = Color((0.0, 0.0, 0.0))

    source_dir = os.path.dirname(bpy.data.filepath)
    dest_dir = os.path.dirname(filepath)

    file = open(filepath, "w", encoding="utf8", newline="\n")
    fw = file.write

    fw('# Blender MTL File: %r\n' %
       (os.path.basename(bpy.data.filepath) or "None"))
    fw('# Material Count: %i\n' % len(mtl_dict))

    ################### cracking #######################
    """
    fw('\n\n')
    for i in dir(scene.objects):
        # fw('%s: %s' % (str(i), str(getattr(scene.objects, str(i)))))
        fw(str(i))
        fw('\n')
    fw('\n\n')
    """
    """
    for o in scene.objects:
        fw(o.type)
        fw('\n')

        for i in dir(o):
            fw(str(i))
            fw('\n')
            """
    fw('\n\n')
    ################### end of cracking #######################

    mtl_dict_values = list(mtl_dict.values())
    mtl_dict_values.sort(key=lambda m: m[0])

    # Write material/image combinations we have used.
    # Using mtl_dict.values() directly gives un-predictable order.
    for mtl_mat_name, mat, face_img in mtl_dict_values:
        # Get the Blender data for the material and the image.
        # Having an image named None will make a bug, dont do it :)

        fw('\nnewmtl %s\n' %
           mtl_mat_name)  # Define a new material: matname_imgname

        if mat:
            # convert from blenders spec to 0 - 1000 range.
            if mat.specular_shader == 'WARDISO':
                tspec = (0.4 - mat.specular_slope) / 0.0004
            else:
                tspec = (mat.specular_hardness - 1) * 1.9607843137254901
            fw('Ns %.6f\n' % tspec)
            del tspec

            ################### cracking #######################
            """
            fw('\n\n')
            for i in dir(mat):
                fw(str(i))
                fw('\n')

            fw('\n\n')
            for i in dir(mat.raytrace_mirror):
                fw('%s: %s' % (str(i), str(getattr(mat.raytrace_mirror, str(i)))))
                fw('\n')
            fw('\n\n')

            fw('\n\n')
            ################### end of cracking #######################
            """

            fw('Ke %.6f\n' % mat.emit)
            fw('Ka %.6f %.6f %.6f\n' %
               (mat.ambient * world_amb)[:])  # Ambient, uses mirror color,
            fw('Kd %.6f %.6f %.6f\n' %
               (mat.diffuse_intensity * mat.diffuse_color)[:])  # Diffuse
            fw('Ks %.6f %.6f %.6f\n' %
               (mat.specular_intensity * mat.specular_color)[:])  # Specular

            ### cracking
            fw('Alpha %.6f\n' % mat.alpha)
            fw('IOR %.6f\n' % mat.raytrace_transparency.ior)
            fw('RefractGloss %.6f\n' % mat.raytrace_transparency.gloss_factor)
            fw('ReflectFactor %.6f\n' % mat.raytrace_mirror.reflect_factor)
            fw('ReflectGloss %.6f\n' % mat.raytrace_mirror.gloss_factor)
            ### end

            if hasattr(mat, "ior"):
                fw('Ni %.6f\n' % mat.ior)  # Refraction index
            else:
                fw('Ni %.6f\n' % 1.0)
            fw('d %.6f\n' % mat.alpha)  # Alpha (obj uses 'd' for dissolve)

            # 0 to disable lighting, 1 for ambient & diffuse only (specular color set to black), 2 for full lighting.
            if mat.use_shadeless:
                fw('illum 0\n')  # ignore lighting
            elif mat.specular_intensity == 0:
                fw('illum 1\n')  # no specular.
            else:
                fw('illum 2\n')  # light normaly

        else:
            #write a dummy material here?
            fw('Ns 0\n')
            fw('Ka %.6f %.6f %.6f\n' %
               world_amb[:])  # Ambient, uses mirror color,
            fw('Kd 0.8 0.8 0.8\n')
            fw('Ks 0.8 0.8 0.8\n')
            fw('d 1\n')  # No alpha
            fw('illum 2\n')  # light normaly

        # Write images!
        if face_img:  # We have an image on the face!
            filepath = face_img.filepath
            if filepath:  # may be '' for generated images
                # write relative image path
                filepath = bpy_extras.io_utils.path_reference(
                    filepath, source_dir, dest_dir, path_mode, "", copy_set,
                    face_img.library)
                fw('map_Kd %s\n' % filepath)  # Diffuse mapping image
                del filepath
            else:
                # so we write the materials image.
                face_img = None

        if mat:  # No face image. if we havea material search for MTex image.
            image_map = {}
            # backwards so topmost are highest priority
            for mtex in reversed(mat.texture_slots):
                if mtex and mtex.texture and mtex.texture.type == 'IMAGE':
                    image = mtex.texture.image
                    if image:
                        # texface overrides others
                        if (mtex.use_map_color_diffuse and (face_img is None)
                                and (mtex.use_map_warp is False)
                                and (mtex.texture_coords != 'REFLECTION')):
                            image_map["map_Kd"] = image
                        if mtex.use_map_ambient:
                            image_map["map_Ka"] = image
                        # this is the Spec intensity channel but Ks stands for specular Color
                        '''
                        if mtex.use_map_specular:
                            image_map["map_Ks"] = image
                        '''
                        if mtex.use_map_color_spec:  # specular color
                            image_map["map_Ks"] = image
                        if mtex.use_map_hardness:  # specular hardness/glossiness
                            image_map["map_Ns"] = image
                        if mtex.use_map_alpha:
                            image_map["map_d"] = image
                        if mtex.use_map_translucency:
                            image_map["map_Tr"] = image
                        if mtex.use_map_normal and (mtex.texture.use_normal_map
                                                    is True):
                            image_map["map_Bump"] = image
                        if mtex.use_map_normal and (mtex.texture.use_normal_map
                                                    is False):
                            image_map["map_Disp"] = image
                        if mtex.use_map_color_diffuse and (mtex.texture_coords
                                                           == 'REFLECTION'):
                            image_map["map_refl"] = image
                        if mtex.use_map_emit:
                            image_map["map_Ke"] = image

            for key, image in image_map.items():
                filepath = bpy_extras.io_utils.path_reference(
                    image.filepath, source_dir, dest_dir, path_mode, "",
                    copy_set, image.library)
                fw('%s %s\n' % (key, repr(filepath)[1:-1]))

    file.close()
Beispiel #38
0
def write(material):
    if object_map.has_mapped_indices(material):
        return

    for slot in material.texture_slots:
        if not is_slot_supported(slot):
            continue

        texture_exporter.write(slot.texture)

    material_id = data.start_object(ObjectType.BASIC_MATERIAL)
    # store the index where this material was written, since we need to grab it elsewhere
    object_map.map(material, material_id)

    data.write_string_prop(PropertyType.NAME, material.name)
    data.write_color_prop(PropertyType.COLOR, material.diffuse_color)

    roughness = math.pow(2.0 / (material.specular_hardness + 2.0), .25)
    data.write_float32_prop(PropertyType.ROUGHNESS, roughness)

    if material.use_transparency and material.game_settings.alpha_blend != "OPAQUE":
        if material.game_settings.alpha_blend == "ADD":
            data.write_uint8_prop(PropertyType.BLEND_STATE, 1)
        elif material.game_settings.alpha_blend == "CLIP":
            data.write_uint8_prop(PropertyType.ALPHA_THRESHOLD, .5)
        else:
            data.write_uint8_prop(PropertyType.BLEND_STATE, 3)

    if not material.game_settings.use_backface_culling:
        data.write_uint8_prop(PropertyType.CULL_MODE, 0)

    if material.use_vertex_color_paint:
        data.write_uint8_prop(PropertyType.USE_VERTEX_COLORS, 1)

    if material.alpha < 1.0:
        data.write_float32_prop(PropertyType.ALPHA, material.alpha)

    if material.emit > 0.0:
        data.write_color_prop(
            PropertyType.EMISSIVE_COLOR,
            Color((material.emit, material.emit, material.emit)))

    for slot in material.texture_slots:
        if not is_slot_supported(slot):
            continue

        tex_id = object_map.get_mapped_indices(slot.texture)[0]

        if slot.use_map_color_diffuse:
            object_map.link(material_id, tex_id, 0)
            write_tex_scale_offset(slot, PropertyType.COLOR_MAP_SCALE,
                                   PropertyType.COLOR_MAP_OFFSET)

        if slot.use_map_normal:
            object_map.link(material_id, tex_id, 1)
            write_tex_scale_offset(slot, PropertyType.NORMAL_MAP_SCALE,
                                   PropertyType.NORMAL_MAP_OFFSET)

        if slot.use_map_hardness:
            object_map.link(material_id, tex_id, 2)
            # assume this is a gloss map
            data.write_uint8_prop(PropertyType.SPECULAR_MAP_MODE, 1)
            write_tex_scale_offset(slot, PropertyType.SPECULAR_MAP_SCALE,
                                   PropertyType.SPECULAR_MAP_OFFSET)

        if slot.use_map_ambient:
            object_map.link(material_id, tex_id, 3)

        if slot.use_map_color_emission and material.emit > 0.0:
            object_map.link(material_id, tex_id, 4)
            write_tex_scale_offset(slot, PropertyType.EMISSION_MAP_SCALE,
                                   PropertyType.EMISSION_MAP_OFFSET)

        if slot.use_map_alpha:
            object_map.link(material_id, tex_id, 5)
            write_tex_scale_offset(slot, PropertyType.MASK_MAP_SCALE,
                                   PropertyType.MASK_MAP_OFFSET)

    data.end_object()
Beispiel #39
0
def build_material(bmodel, mat1, material, tex):

    currMaterial = None  # materials may not be defined
    stage = material.texStages[0]  # XCX multiples textures
    num = 0
    if stage != 0xffff:
        currMaterial = bpy.data.materials.new(
            "temp_name_whatsoever"
        )  # name will be erased afterwards, in a subcall
        # while stage != 0xffff:  # ONE texture for now
        textureName = ""
        v2 = mat1.texStageIndexToTextureIndex[
            stage]  # -- undefined if stage = 0xffff

        # -- v2 used latter. value is undefined if stage == 0xffff
        textureName = tex.stringtable[v2]

        # --self.textureName = matName
        fileName = OSPath.join(bmodel._texturePath, textureName + ".tga")
        bmpFound = OSPath.exists(fileName) or OSPath.exists(
            fileName[:-4] + '.dds')  # two image types!

        # -- messageBox fileName
        newtex_tslot(fileName, 'DIFFUSE', currMaterial)
        img = getTexImage(currMaterial, fileName)

        # --gc()
        bmp = None
        hasAlpha = False
        if bmpFound:
            alp = 0
            for p in range(3, len(img.pixels),
                           4):  # pixels stored as individual channels
                if True:  # img.pixels[p] != 1:  # only get alpha
                    # alp = img.pixels[p]
                    hasAlpha = True
                    break
                    # hasAlpha = (p == len(img.pixels)-1)
        else:
            # -- make it easier to see invalid textures
            currMaterial.diffuse_color = Color((1, 0, 0))

        if hasAlpha:
            # self._currMaterial.twoSided = True # -- anything with alpha is always two sided?
            newtex_tslot(fileName, 'ALPHA', currMaterial)

        showTextureMap(currMaterial)  # -- display texture in view

        # -- messageBox (matName + (self.tex.self.texHeaders[v2].wrapS as string) + "+" + (self.tex.self.texHeaders[v2].wrapT as string))
        # -- NOTE: check ash.bmd for case when wrapS=2 and wrap=2. u_offset = 0.5 and V_offset = -0.5 [note negative on v]

        if bmpFound:
            if tex.texHeaders[
                    v2].wrapS == 0:  # - clamp to edge? Needs testing. Cannot use .U_Mirror = False and .U_Tile = False. If WrapS == 0 then has Alpha?
                pass
            elif tex.texHeaders[v2].wrapS == 1:  # - repeat (default)
                pass
            elif tex.texHeaders[v2].wrapS == 2:
                currMaterial.name += "_U"  # -- add suffix to let the modeler know where mirror should be used
                if bmodel._allowTextureMirror:  # XCX remove this super old code!
                    getTexSlot(currMaterial, fileName).scale[0] = -1
                    # self._currMaterial.diffusemap.coords.U_Tile = False
                    # self._currMaterial.diffusemap.coords.U_offset = 0.5
                    # self._currMaterial.diffusemap.coords.U_Tiling = 0.5
            else:
                raise ValueError("Unknown wrapS " +
                                 str(tex.texHeaders[v2].wrapS))
            if tex.texHeaders[v2].wrapT == 0:  # - clamp to edge? Needs testing
                pass
            elif tex.texHeaders[v2].wrapT == 1:  # - repeat (default)
                pass
                #					self._currMaterial.diffusemap.coords.V_Mirror = False
                #					self._currMaterial.diffusemap.coords.V_Tile = True
                #
                #					if (hasAlpha) then
                #					(
                #						self._currMaterial.opacityMap.coords.V_Mirror = False
                #						self._currMaterial.opacityMap.coords.V_Tile = True
                #					)
            elif tex.texHeaders[v2].wrapT == 2:
                currMaterial.name += "_V"  # -- add suffix to let the modeler know where mirror should be used
                if bmodel._allowTextureMirror:
                    getTexSlot(currMaterial, fileName).scale[1] = -1
                    # self._currMaterial.diffusemap.coords.V_Tile = False
                    # self._currMaterial.diffusemap.coords.V_offset = 0.5
                    # self._currMaterial.diffusemap.coords.V_Tiling = 0.5
            else:
                raise ValueError("Unknown wrapT " +
                                 str(tex.texHeaders[v2].wrapS))
        num += 1
        stage = material.texStages[num]

    return currMaterial
def freestyle_to_gpencil_strokes(strokes, frame, lineset, options): # draw_mode='3DSPACE', color_extraction='BASE'):
    mat = bpy.context.scene.camera.matrix_local.copy()

    # pick the active palette or create a default one
    grease_pencil = bpy.context.scene.grease_pencil
    palette = grease_pencil.palettes.active or grease_pencil.palettes.new("GP_Palette")

    # can we tag the colors the script adds, to remove them when they are not used? 
    cache = { color_to_hex(color.color) : color for color in palette.colors } 

    # keep track of which colors are used (to remove unused ones)
    used = []

    for fstroke in strokes:

        # the color object can be "owned", so use Color to clone it
        if options.color_extraction:
            if options.color_extraction_mode == 'FIRST':
                base_color = Color(fstroke[0].attribute.color)
            elif options.color_extraction_mode == 'FINAL':
                base_color = Color(fstroke[-1].attribute.color)
            else:
                base_color = Color(lineset.linestyle.color)

        # color has to be frozen (immutable) for it to be stored
        base_color.freeze()

        colorname = get_colorname(palette.colors, base_color, palette).name

        # append the current color, so it is kept
        used.append(colorname)

        gpstroke = frame.strokes.new(colorname=colorname)
        gpstroke.draw_mode = options.draw_mode
        gpstroke.points.add(count=len(fstroke), pressure=1, strength=1)

        # the max width gets pressure 1.0. Smaller widths get a pressure 0 <= x < 1 
        base_width = functools.reduce(max, (sum(svert.attribute.thickness) for svert in fstroke), lineset.linestyle.thickness)

        # set the default (pressure == 1) width for the gpstroke
        gpstroke.line_width = base_width

        if options.draw_mode == '3DSPACE':
            for svert, point in zip (fstroke, gpstroke.points):
                point.co = mat * svert.point_3d
                # print(point.co, svert.point_3d)

                if options.thickness_extraction:
                    point.pressure = sum(svert.attribute.thickness) / max(1e-6, base_width)

                if options.alpha_extraction:
                    point.strength = svert.attribute.alpha

        elif options.draw_mode == 'SCREEN':
            width, height = render_dimensions(bpy.context.scene)
            for svert, point in zip (fstroke, gpstroke.points):
                x, y = svert.point
                point.co = Vector((abs(x / width), abs(y / height), 0.0)) * 100

                if options.thickness_extraction:
                    point.pressure = sum(svert.attribute.thickness) / max(1e-6, base_width)

                if options.alpha_extraction:
                    point.strength = svert.attribute.alpha

        else:
            raise NotImplementedError()
Beispiel #41
0
    rgb(56, 0, 128),  # CONVEYOR1
    rgb(51, 38, 61),  # CONVEYOR2
    rgb(135, 99, 73),  # DIRT1
    rgb(91, 66, 48),  # DIRT2
    rgb(66, 40, 25),  # DIRT3
    rgb(132, 181, 178),  # ICE2
    rgb(102, 136, 134),  # ICE3
    rgb(119, 76, 43),  # WOOD2
    rgb(0, 20, 56),  # CONVEYOR_MARKET1
    rgb(25, 33, 51),  # CONVEYOR_MARKET2
    rgb(142, 127, 114),  # PAVING
    rgb(255, 0, 0)  # NONE (-1)
)

# Colors for debug objects
COL_CUBE = Color(rgb(180, 20, 0))
COL_BBOX = Color(rgb(0, 0, 40))
COL_BCUBE = Color(rgb(0, 180, 20))
COL_SPHERE = Color(rgb(60, 60, 80))
COL_HULL = Color(rgb(0, 20, 180))
"""
Supported File Formats
"""
FORMAT_UNK = -1
FORMAT_BMP = 0
FORMAT_CAR = 1
FORMAT_TA_CSV = 2
FORMAT_FIN = 3
FORMAT_FOB = 4
FORMAT_HUL = 5
FORMAT_LIT = 6