Exemple #1
0
    def execute(self,context):
        
        if bpy.context.mode == 'OBJECT':
            bme = bmesh.new()
            bme.from_mesh(bpy.context.object.data)
            bme.verts.ensure_lookup_table()
            bme.edges.ensure_lookup_table()
            bme.faces.ensure_lookup_table()
        
        elif context.mode == 'EDIT':
            bme = bmesh.from_edit_mesh(bpy.context.object.data)
            
        else:
            self.report({'ERROR'}, 'Must be in Object or Edit Mode')
        
        bme.verts.ensure_lookup_table()
        bme.edges.ensure_lookup_table()
        bme.faces.ensure_lookup_table()
        
        selected_verts = [v for v in bme.verts if v.select]     
        islands = bmesh_loose_parts_verts(bme, selected_verts, max_iters = 100)
        
        
        biggest = max(islands, key = len)
        
        
        if "AO_select" in bme.loops.layers.color:
            ao_select_color_layer = bme.loops.layers.color["AO_select"]
            red = Color((1,0,0))
            white = Color((1,1,1))
            
            for v in bme.verts:
                if v in biggest:
                    v.select_set(True)
                    for f in v.link_faces:
                        for loop in f.loops:
                            if loop.vert == v:
                                loop[ao_select_color_layer] = red

                else:
                    v.select_set(False)
                    for f in v.link_faces:
                        for loop in f.loops:
                            if loop.vert == v:
                                loop[ao_select_color_layer] = white

        if bpy.context.mode == 'OBJECT':
            bme.to_mesh(bpy.context.object.data)
            bme.free()
    
        else:
            bmesh.update_edit_mesh(bpy.context.object.data)
    
        return {'FINISHED'}
Exemple #2
0
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
Exemple #3
0
class Button(bge.types.KX_PythonComponent):
    args = {
        "Activate": True,
        "Pressed Message": "",
        "Released Message": "",
        "Normal Color": Color([0.7, 0.7, 0.7, 1.0]),
        "Highlighted Color": Color([1.0, 1.0, 1.0, 1.0]),
        "Pressed Color": Color([0.5, 0.5, 0.5, 1.0]),
        "Disabled Color": Color([0.2, 0.2, 0.2, 1.0]),
    }

    def start(self, args):
        self.active = args["Activate"]
        self.pressedFunction = None
        self.releasedFunction = None

        self.pressedMessage = args["Pressed Message"]
        self.releasedMessage = args["Released Message"]

        self.normalColor = args["Normal Color"]
        self.highlightedColor = args["Highlighted Color"]
        self.pressedColor = args["Pressed Color"]
        self.disabledColor = args["Disabled Color"]

        self.materials = []
        for mesh in self.object.meshes:
            for material in mesh.materials:
                self.materials.append(material)

        self.object["Button Component"] = True

    def __mouseOver(self):
        scene = bge.logic.getCurrentScene()
        cam = scene.active_camera
        mPos = bge.logic.mouse.position

        obj = cam.getScreenRay(mPos[0], mPos[1], 10000, "Button Component")
        return obj == self.object

    def update(self):
        over = self.__mouseOver()

        if self.active:
            if over:
                if bge.logic.mouse.inputs[bge.events.LEFTMOUSE].values[-1]:
                    self.object.color = self.pressedColor
                else:
                    self.object.color = self.highlightedColor
            else:
                self.object.color = self.normalColor
        else:
            self.object.color = self.disabledColor
Exemple #4
0
    def __init__(self, light, meshesAndNodes):
        if light.parent and light.parent.type != 'ARMATURE':
            self.parentId = light.parent.name

        self.name = light.name
        Logger.log('processing begun of light (' + light.data.type + '):  ' + self.name)
        self.define_animations(light, False, True, False)

        light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': POINT_LIGHT}
        self.light_type = light_type_items[light.data.type]

        if self.light_type == POINT_LIGHT:
            self.position = light.location
            if hasattr(light.data, 'use_sphere'):
                if light.data.use_sphere:
                    self.range = light.data.distance

        elif self.light_type == DIRECTIONAL_LIGHT:
            self.position = light.location
            self.direction = Light.get_direction(light.matrix_local)

        elif self.light_type == SPOT_LIGHT:
            self.position = light.location
            self.direction = Light.get_direction(light.matrix_local)
            self.angle = light.data.spot_size
            self.exponent = light.data.spot_blend * 2
            if light.data.use_sphere:
                self.range = light.data.distance

        else:
            # Hemi
            matrix_local = light.matrix_local.copy()
            matrix_local.translation = Vector((0, 0, 0))
            self.direction = (Vector((0, 0, -1)) * matrix_local)
            self.direction = scale_vector(self.direction, -1)
            self.groundColor = Color((0, 0, 0))

        self.intensity = light.data.energy
        self.diffuse   = light.data.color if light.data.use_diffuse  else Color((0, 0, 0))
        self.specular  = light.data.color if light.data.use_specular else Color((0, 0, 0))
        
        #code generated for cameraLight is done in js_exporter
        self.cameraLight = light.data.cameraLight

        # inclusion section
        if light.data.use_own_layer:
            lampLayer = getLayer(light)
            self.includedOnlyMeshesIds = []
            for mesh in meshesAndNodes:
                if mesh.layer == lampLayer:
                    self.includedOnlyMeshesIds.append(mesh.name)
def loadBasicMaterials():
  '''
  Define some basic materials for easy "coloring".
  '''
  if 'red' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('red')
    material.diffuse_color = Color((1, 0, 0))
  if 'green' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('green')
    material.diffuse_color = Color((0, 1, 0))
  if 'blue' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('blue')
    material.diffuse_color = Color((0, 0, 1))

  if 'cyan' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('cyan')
    material.diffuse_color = Color((0, 1, 1))
  if 'magenta' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('magenta')
    material.diffuse_color = Color((1, 0, 1))
  if 'yellow' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('yellow')
    material.diffuse_color = Color((1, 1, 0))

  if 'black' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('black')
    material.diffuse_color = Color((0, 0, 0))
  if 'white' not in [i.name for i in bpy.data.materials]:
    material = bpy.data.materials.new('white')
    material.diffuse_color = Color((1, 1, 1))
def vertex_color(context):

    threshold = .1

    if len(context.selected_objects) == 0:
        return
    obj = context.selected_objects[0]
    bpy.ops.object.mode_set(mode="OBJECT")

    colors = obj.data.vertex_colors.active.data
    #selected_polygons = list(filter(lambda p: p.select, obj.data.polygons))
    selected_polygons = [p for p in obj.data.polygons if p.select]
    if len(selected_polygons):
        p = selected_polygons[0]

        r = g = b = 0

        for i in p.loop_indices:
            c = colors[i].color
            r += c[0]
            g += c[1]
            b += c[2]
        r /= p.loop_total
        g /= p.loop_total
        b /= p.loop_total
        target = Color((r, g, b))

        for p in obj.data.polygons:
            r = g = b = 0
            for i in p.loop_indices:
                c = colors[i].color
                r += c[0]
                g += c[1]
                b += c[2]
            r /= p.loop_total
            g /= p.loop_total
            b /= p.loop_total
            source = Color((r, g, b))

            print(target, source)

            if (abs(source.r - target.r) < threshold
                    and abs(source.g - target.g) < threshold
                    and abs(source.b - target.b) < threshold):

                p.select = True

    bpy.ops.object.mode_set(mode="EDIT")
    def createOneFrame(self, f):
        if self.attach:
            self.createVoxel(self.size, Color())
            real = bpy.context.object
            real.name = self.obj.name + '_Voxels_Frame_' + str(f)
            real.location = self.obj.location
            bpy.ops.object.editmode_toggle()
            bpy.ops.mesh.delete(type='VERT')
            bpy.ops.object.editmode_toggle()

        self.doVoxel(bpy.context.scene)

        if self.attach:
            for o in bpy.data.objects:
                o.select_set(False)
            for color_str in self.cubes_map:
                for c in self.cubes_map[color_str]:
                    c.select_set(True)
            real.select_set(True)
            bpy.context.view_layer.objects.active = real
            bpy.ops.object.join()
            if self.bool_voxel_animation:
                self.addHideShowKey(real, f)

        self.cubes_map = {}
Exemple #8
0
    def get_vcolors(self, context, obj, n):
        vcolor_dict = defaultdict(list)
        mesh = obj.data
        color_layer = obj.data.vertex_colors[0]

        i = 0
        for poly in mesh.polygons:
            for idx in poly.loop_indices:
                loop = mesh.loops[idx]
                color = color_layer.data[i].color
                vcolor_dict[loop.vertex_index].append(color)
                i += 1

        avg_vcolors = {}
        for v in vcolor_dict:
            avg_vcolors[v] = Color(
                (sum([c.r for c in vcolor_dict[v]]) / len(vcolor_dict[v]),
                 sum([c.g for c in vcolor_dict[v]]) / len(vcolor_dict[v]),
                 sum([c.b for c in vcolor_dict[v]]) / len(vcolor_dict[v])))

        # Sort verts by value
        verts_sorted_by_value = sort_by_value(avg_vcolors, [], 1)

        start = len(avg_vcolors) - n
        culled_vert_list = verts_sorted_by_value[start:]

        vcolors = {v: avg_vcolors[v] for v in culled_vert_list}

        return vcolors
Exemple #9
0
    def draw_common_buttons(self, context, layout):
        layout.prop(self, "priority")

        emission_socket = self.inputs["Emission"]
        if emission_socket.is_linked or emission_socket.default_value != Color(
            (0.0, 0.0, 0.0)):
            lightgroups = context.scene.luxcore.lightgroups
            layout.prop_search(self,
                               "lightgroup",
                               lightgroups,
                               "custom",
                               icon=icons.LIGHTGROUP,
                               text="")

        layout.prop(self, "color_depth")

        # Warn the user if he tries to use a 2D texture in a volume because it doesn't work
        has_2D_input = False
        for socket in self.inputs:
            node = utils_node.get_linked_node(socket)
            if node and "2D Mapping" in node.inputs:
                has_2D_input = True
                break
        if has_2D_input:
            layout.label(text="Can't use 2D textures!", icon=icons.WARNING)
Exemple #10
0
def weight2vert_col(color):

    obj = bpy.context.active_object
    obj_data = obj.data
    vert_groups = obj.vertex_groups
    col = Color()
    for vert_g in vert_groups:
        group_name = vert_g.name

        #check for existing group with the same name
        if None == obj_data.vertex_colors.get(group_name):
            obj_data.vertex_colors.new(name=group_name)

        color_map = obj_data.vertex_colors[group_name]

        for poly in obj_data.polygons:
            for loop_ind in poly.loop_indices:
                vert_ind = obj_data.loops[loop_ind].vertex_index

                #check if the vertex belong to the group
                weight = 0
                for g in obj_data.vertices[vert_ind].groups:
                    if g.group == vert_groups[group_name].index:
                        weight = vert_groups[group_name].weight(vert_ind)

                #convert weight to vert_col
                if color == 'BW':
                    col = convert(weight, 'W2BW')
                else:
                    col = convert(weight, 'W2HSV')
                #assign to the color map
                color_map.data[loop_ind].color = col
Exemple #11
0
    def execute(self, context):
        from zlib import crc32

        objects = context.selected_objects
        if not objects:
            self.report({'ERROR'}, 'No objects selected')
            return {'CANCELLED'}

        seed = self.seed
        power = self.power
        materials = set()
        for obj in objects:
            for slot in obj.material_slots:
                materials.add(slot.material)

        for mat in materials:
            data = bytearray(mat.name, 'utf8')
            data.append(seed)
            hsh = crc32(data)
            color = Color()
            color.hsv = ((hsh & 0xFF) / 0xFF,
                         (((hsh >> 8) & 3) / 3 * 0.5 + 0.5) * power,
                         ((hsh >> 2) & 1) * (0.5 * power) + 0.5)
            color = [color.r, color.g, color.b]
            if IS_28:
                color.append(1.0)  # alpha
            mat.diffuse_color = color
        return {'FINISHED'}
Exemple #12
0
def create_vertex_color_map():
    # Find upper and lower z values.
    # there are many ways to skin this cat, but i'm going to be lazy
    z_list = []
    for i in bpy.context.active_object.data.vertices:
        z_list.append(i.co.z)

    z_list = sorted(z_list)

    lower_old = z_list[0]
    upper_old = z_list[len(z_list) - 1]
    lower_new = 0.0
    upper_new = 1.0

    my_object = bpy.context.active_object.data
    vert_list = my_object.vertices
    color_map = my_object.vertex_colors.new()

    i = 0
    for poly in my_object.polygons:
        for idx in poly.loop_indices:
            loop = my_object.loops[idx]
            v = loop.vertex_index
            zheight = vert_list[v].co.z
            remap_1 = remap(zheight, lower_old, upper_old, lower_new,
                            upper_new)

            color_map.data[i].color = Color((remap_1, remap_1, remap_1))
            i += 1
def RunCombineAO(context):
    obj = bpy.context.active_object
    mesh = obj.data

    # Set mode
    oldMode = bpy.context.object.mode
    if (bpy.context.mode != 'OBJECT'):
        bpy.ops.object.mode_set(mode='OBJECT')

    # Check layers exist
    CheckVertexColorLayer(context.scene.scn_inputVCLayer1, mesh)
    CheckVertexColorLayer(context.scene.scn_inputVCLayer2, mesh)
    CheckVertexColorLayer(context.scene.scn_targetVCLayer, mesh)

    # Get layers
    inputLayer1 = mesh.vertex_colors[context.scene.scn_inputVCLayer1]
    inputLayer2 = mesh.vertex_colors[context.scene.scn_inputVCLayer2]
    targetLayer = mesh.vertex_colors[context.scene.scn_targetVCLayer]
    color = Color()

    # Perform operation
    i = 0
    for poly in mesh.polygons:
        for loop in poly.loop_indices:
            color.r = inputLayer1.data[i].color.r * inputLayer2.data[i].color.r
            color.g = inputLayer1.data[i].color.g * inputLayer2.data[i].color.g
            color.b = inputLayer1.data[i].color.b * inputLayer2.data[i].color.b
            targetLayer.data[loop].color = color
            i += 1

    # Update mesh and revert to old mode
    mesh.update()
    bpy.ops.object.mode_set(mode=oldMode)
    print("Finished CombineAOOperator")
Exemple #14
0
def to_node_color(color, from_linear=False):
    """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]
    :param from_linear: should color first be converted from linear space?
    :type from_linear: bool
    :return: RGBA as tuple of floats
    :rtype: tuple[float]
    """

    srgb_color = color
    if from_linear:
        srgb_color = linear_to_srgb(color)

    c = Color(
        srgb_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, )
Exemple #15
0
    def timing_input_start(self, context):

        # standardise framerange display
        bpy.ops.time.view_all()

        # calculate margin and pixel per frame
        self._margin = ceil(context.region.width * 0.01)
        self._ppf = (context.region.width - self._margin * 2) / (
            context.scene.frame_end - context.scene.frame_start)

        # draw existing timeline marker in a less prominent colour
        self._marker_color_old = context.user_preferences.themes[
            0].timeline.frame_current.copy()
        context.user_preferences.themes[0].timeline.frame_current = Color(
            (0.5, 0.5, 0.5))

        # deactivate frame indicator
        self._show_frame_indicator = context.space_data.show_frame_indicator
        context.space_data.show_frame_indicator = False

        # register draw handle
        self._draw_handle = context.region.callback_add(
            draw_callback, (self, context), 'POST_PIXEL')

        PerformTimeOperator.timing_input_start(self, context)
Exemple #16
0
    def transfer_weight_to_vertex_color(self, obj):
        col = Color()
        col.r, col.g, col.b = 1, 1, 1
        col.h, col.s, col.v = 0, 1, 1

        for poly in obj.data.polygons:
            for loop in poly.loop_indices:
                weight = 0
                vertindex = obj.data.loops[loop].vertex_index
                try:
                    weight = obj.vertex_groups.active.weight(vertindex)
                    if self.colored:
                        col.h, col.s, col.v = 0.6666 * weight, 1, 1
                    else:
                        col.r = col.g = col.b = weight
                except:
                    if self.colored:
                        col.r, col.g, col.b = 1, 1, 1
                        col.h, col.s, col.v = 0.666, 1, 1
                    else:
                        col.h, col.s, col.v = 0, 1, 1
                        col.r, col.g, col.b = 0, 0, 0

                obj.data.vertex_colors.active.data[loop].color = (col.b, col.g,
                                                                  col.r, 1)
Exemple #17
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[
            Glass.DIFF_COL_NODE].outputs['Color'].default_value = color
        node_tree.nodes[
            Glass.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[
            Glass.OUT_MAT_NODE].material.scs_props.shader_attribute_add_ambient
        node_tree.nodes[Glass.OUT_MAT_NODE].material.emit = (ambient / 10) * (
            1 / hsv_col.v)
Exemple #18
0
    def brick_colour(self, brick_size, brick_name):
        height = brick_size[2]
        width = brick_size[0]
        depth = brick_size[1]

        if brick_name in bpy.data.materials:
            mat = bpy.data.materials[brick_name]

        else:
            colour = self.base_colours[depth]

            if height == 1:
                colour = [colour[0], colour[1] - 0.2, colour[2]]

            if width == 2:
                colour = [colour[0] + 0.028, colour[1], colour[2]]

            c = Color()
            c.hsv = colour[0], colour[1], colour[2]

            mat_name_string = brick_name
            mat = bpy.data.materials.new(name=mat_name_string)
            mat.diffuse_color = c

        return mat
Exemple #19
0
    def invoke(self, context, event):

        if context.area.type == 'VIEW_3D':

            if not context.active_object:
                self.report({'WARNING'}, "Nothing to time")
                return {'CANCELLED'}

            self.props = context.window_manager.sketch_time

            # source path
            global g_src_path
            if g_src_path:
                g_src_path.draw_end(context)

            src_path_props = self.props.path
            src_path_props.color = Color((0.7, 0.7, 0.7))
            src_path_props.features_shape = 'cross'
            self._source_path = MotionPath(src_path_props)
            self._source_path._is_2d = True
            self._source_path.draw_begin(context)

            ret_val = PerformTimeOperator.invoke(self, context, event)

            # target path
            global g_tgt_path
            g_tgt_path = self._target_path
            if not g_tgt_path.visible:
                g_tgt_path.draw_begin(context)

            return ret_val
        else:
            self.report({'WARNING'}, "View3D not found, cannot run SketchTime")
            return {'CANCELLED'}
def avg_col(cols):
    avg_col = Color((0.0, 0.0, 0.0))
    for col in cols:
        avg_col[0] += col[0] / len(cols)
        avg_col[1] += col[1] / len(cols)
        avg_col[2] += col[2] / len(cols)
    return avg_col
Exemple #21
0
def setup_materials(materials_array, materials):
    if materials is not None:
        material_count = len(set(materials.values()))
        c = Color()
        for i in range(material_count):
            c.hsv = (i / float(material_count), 0.7, 0.25)
            materials_array.append(make_material("CelticKnot", c))
    def _add_point_from_nvm_entry(point_cloud: PointCloud,
                                  args: List[str]) -> None:
        """Set a point of the cloud given the list of strings from the NVM file entry.
        Adds the point to the point cloud.

        Arguments:
            args {List[str]} -- List[<XYZ> <RBG> <number of measurements> List[<image index> <feature Index> <xy>]]

        Raises:
            RuntimeError: if called when trying to set more points than the cloud size
        """
        assert len(args) >= 7 and (len(args) == (7 + 4 * int(args[6])))

        # load vertex coordinates
        position = ReconstructionNvm.NVM_TO_BLENDER @ Vector(
            map(float, args[0:3]))
        #
        # load colors
        color = Color(map(int, args[3:6])) / 255.
        #
        # load measures
        # self.number_of_measures = int(args[6])
        # self.measures = []
        # for offset in range(self.number_of_measures):
        #     start_index = 7 + offset*4
        #     self.measures.append(ReconMeasure(args[start_index:start_index+4]))
        #
        point_cloud.add_point(position, color)
    def toggle_grayscale(self, context):
        brush = context.tool_settings.vertex_paint.brush

        if self.use_grayscale:
            self.brush_color = brush.color
            self.brush_secondary_color = brush.secondary_color

            v1 = self.brush_value_isolate
            v2 = self.brush_secondary_value_isolate
            brush.color = Color((v1, v1, v1))
            brush.secondary_color = Color((v2, v2, v2))
        else:
            brush.color = self.brush_color
            brush.secondary_color = self.brush_secondary_color

        return None
Exemple #24
0
    def __update_text(self, props):
        if not "Temperature_Text" in bpy.data.objects:
            bpy.ops.object.text_add()
            bpy.context.active_object.name = "Temperature_Text"
        text_obj = bpy.data.objects["Temperature_Text"]
        if text_obj.type == 'FONT':
            text_obj.data.body = "{0:.1f}".format(props.temperature)

        # make material slot
        if len(text_obj.material_slots) == 0:
            bpy.context.scene.objects.active = text_obj
            bpy.ops.object.material_slot_add()
            text_obj.material_slots[0].material = bpy.data.materials['Material']
        mtrl = text_obj.material_slots[0].material

        # change color
        min_temp = -10
        max_temp = 50
        temp_range = max_temp - min_temp
        color = Color()
        color.hsv = (
            1.0 - (((props.temperature-min_temp)/(temp_range-10))*270+90)/360,
            0.95,
            1.0
        )
        mtrl.diffuse_color = color
Exemple #25
0
    def vectorToColor(self, v, scale):
        print ("Encoding: x:%2.2f, y:%2.2f, z:%2.2f" % (v.x, v.y, v.z))

        # Convert vector v to a color of rgb using scale
        # Axis flipping here is annoying, basically we're swapping default
        # blender axis for default unity axis
        if scale.x == 0:
            xscale = 0
        else:
            xscale = 1.0 / scale.x

        if scale.z == 0:
            yscale = 0
        else:
            yscale = 1.0 / scale.z

        if scale.y == 0:
            zscale = 0
        else:
            zscale = 1.0 / scale.y

        out = Vector((((v.x * xscale) + 1.0) / 2.0,
                      ((v.y * yscale) + 1.0) / 2.0,
                      ((v.z * zscale) + 1.0) / 2.0))

        print ("Color will be: r:%2.2f, g:%2.2f, b:%2.2f" % (out.x, out.z, out.y))

        # FIXME: This must support the selected "direction" UP and FORWARD
        # Right now we're just swapping y and z ( x*-1 forward)
        return Color((out.x, out.z, out.y))
Exemple #26
0
def convert_to_color_group(obj, name):
    """ Convert a Weight vertex group to color """

    if name in obj.data.vertex_colors:
        group = obj.data.vertex_colors[name]
    else:
        group = obj.data.vertex_colors.new(name=name)

    source = obj.vertex_groups[name]
    polygons = obj.data.polygons

    inner_loop_index = 0

    for face in polygons:

        vertex_index = 0

        for index in face.loop_indices:

            weight = source.weight(face.vertices[vertex_index])
            vcolor = Color((weight, weight, weight))

            group.data[inner_loop_index].color = vcolor
            inner_loop_index += 1
            vertex_index += 1
Exemple #27
0
    def draw_common_buttons(self, context, layout):
        layout.prop(self, "priority")

        emission_socket = self.inputs["Emission"]
        if emission_socket.is_linked or emission_socket.default_value != Color((0.0, 0.0, 0.0)):
            lightgroups = context.scene.luxcore.lightgroups
            layout.prop_search(self, "lightgroup",
                               lightgroups, "custom",
                               icon=icons.LIGHTGROUP, text="")

        layout.prop(self, "color_depth")

        # Warn the user if he tries to use e.g. a 2D texture in a volume because it doesn't work
        def get_incompatible_inputs(node):
            if node.bl_idname in self.INCOMPATIBLE_TEXTURE_NODES:
                return node.name

            for socket in node.inputs:
                next_node = utils_node.get_linked_node(socket)
                if next_node:
                    name = get_incompatible_inputs(next_node)
                    if name:
                        return name
            return None

        incompatible_input = get_incompatible_inputs(self)
        if incompatible_input:
            col = layout.column()
            col.label(text="Incompatible texture!", icon=icons.WARNING)
            col.label(text=f"({incompatible_input})", icon=icons.WARNING)
Exemple #28
0
    def __update_suzanne(self, props):
        # make object
        if not "Temperature_Suzanne" in bpy.data.objects:
            bpy.ops.mesh.primitive_monkey_add()
            bpy.context.active_object.name = "Temperature_Suzanne"
        suzanne_obj = bpy.data.objects["Temperature_Suzanne"]

        # make material
        if len(bpy.data.materials) == 0:
            bpy.ops.material.new()

        # make material slot
        if len(suzanne_obj.material_slots) == 0:
            bpy.context.scene.objects.active = suzanne_obj
            bpy.ops.object.material_slot_add()
            suzanne_obj.material_slots[0].material = bpy.data.materials['Material']
        mtrl = suzanne_obj.material_slots[0].material

        # change color
        min_temp = -10
        max_temp = 50
        temp_range = max_temp - min_temp
        color = Color()
        color.hsv = (
            1.0 - (((props.temperature-min_temp)/(temp_range-10))*270+90)/360,
            0.95,
            0.85
        )
        mtrl.diffuse_color = color
Exemple #29
0
def applyColoringForMeshErrors(context, error_mesh, error_values, *, A = None, B = None, v_group_name = "lap_errors", use_weights=False, normalize_weights=True, use_histogram_preprocess=False, percent_min=0.1, percent_max=0.9): 
    if(use_histogram_preprocess):
        min_, max_ = getMinMax(error_values, percent_begin=percent_min, percent_end=percent_max);
#         error_values[np.where(error_values > max_)] = min_;
        error_values = np.clip(error_values, min_, max_);
    
    final_colors, final_weights = getInterpolatedColorValues(error_values, A, B, normalize=normalize_weights);
    
    colors = {};
    weights = {};
    
    iterator_model = [];    
    for_vertices = not (len(error_values) == len(error_mesh.data.polygons));
    
    if(for_vertices):
        iterator_model = error_mesh.data.vertices;
    else:
        iterator_model = error_mesh.data.polygons;
    
    for it_elem in iterator_model:            
        try:
            (r,g,b,a) = final_colors[it_elem.index];
        except ValueError:
            (r,g,b) = final_colors[it_elem.index];            
        color = Color((r,g,b));
        colors[it_elem.index] = color;
        weights[it_elem.index] = final_weights[it_elem.index];
    
    if(for_vertices and use_weights):
        applyVertexWeights(context, error_mesh, weights, v_group_name = v_group_name);
    
    applyVertexColors(context, error_mesh, colors, v_group_name=v_group_name, for_vertices=for_vertices);
Exemple #30
0
def get_color_id(index, count, jitter=False):
    # Get unique color
    color = Color()
    indexList = [
        0, 171, 64, 213, 32, 96, 160, 224, 16, 48, 80, 112, 144, 176, 208, 240,
        8, 24, 40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 216, 232,
        248, 4, 12, 20, 28, 36, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124,
        132, 140, 148, 156, 164, 172, 180, 188, 196, 204, 212, 220, 228, 236,
        244, 252, 2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62,
        66, 70, 74, 78, 82, 86, 90, 94, 98, 102, 106, 110, 114, 118, 122, 126,
        130, 134, 138, 142, 146, 150, 154, 158, 162, 166, 170, 174, 178, 182,
        186, 190, 194, 198, 202, 206, 210, 214, 218, 222, 226, 230, 234, 238,
        242, 246, 250, 254, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27,
        29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63,
        65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99,
        101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127,
        129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155,
        157, 159, 161, 163, 165, 167, 169, 128, 173, 175, 177, 179, 181, 183,
        185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211,
        192, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239,
        241, 243, 245, 247, 249, 251, 253, 255
    ]

    i = 0
    if index > 255:
        while index > 255:
            index -= 256
            i += 1

    if jitter:
        color.hsv = ((indexList[index] + 1 / (2**i)) / 256), 0.9, 1.0
    else:
        color.hsv = (index / (count)), 0.9, 1.0

    return color