Skip to content
Snippets Groups Projects
mesh_bsurfaces.py 179 KiB
Newer Older
# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; version 2
#  of the License.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

Eclectiel L's avatar
Eclectiel L committed
    "name": "Bsurfaces GPL Edition",
    "author": "Eclectiel",
    "version": (1,5),
    "blender": (2, 6, 3),
    "api": 45996,
Eclectiel L's avatar
Eclectiel L committed
    "location": "View3D > EditMode > ToolShelf",
    "description": "Modeling and retopology tool.",
    "wiki_url": "http://www.bsurfaces.info",
    "tracker_url": "http://projects.blender.org/tracker/index.php?"\
        "func=detail&aid=26642",
    "category": "Mesh"}
import bmesh
import mathutils
import operator



class VIEW3D_PT_tools_SURFSK_mesh(bpy.types.Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_context = "mesh_edit"
Eclectiel L's avatar
Eclectiel L committed
    bl_label = "Bsurfaces"
    @classmethod
    def poll(cls, context):
        return context.active_object
    def draw(self, context):
        layout = self.layout
        
        scn = context.scene
        ob = context.object
        
        col = layout.column(align=True)
        row = layout.row()
        row.separator()
Eclectiel L's avatar
Eclectiel L committed
        col.operator("gpencil.surfsk_add_surface", text="Add Surface")
        col.operator("gpencil.surfsk_edit_strokes", text="Edit Strokes")
        col.prop(scn, "SURFSK_cyclic_cross")
        col.prop(scn, "SURFSK_cyclic_follow")
        col.prop(scn, "SURFSK_loops_on_strokes")
        col.prop(scn, "SURFSK_automatic_join")
        col.prop(scn, "SURFSK_keep_strokes")
        
        
        
class VIEW3D_PT_tools_SURFSK_curve(bpy.types.Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_context = "curve_edit"
    bl_label = "Bsurfaces"
    
    @classmethod
    def poll(cls, context):
        return context.active_object
    
    
    def draw(self, context):
        layout = self.layout
        
        scn = context.scene
        ob = context.object
        
        col = layout.column(align=True)
        row = layout.row()
        row.separator()
        col.operator("curve.surfsk_first_points", text="Set First Points")
        col.operator("curve.switch_direction", text="Switch Direction")
        col.operator("curve.surfsk_reorder_splines", text="Reorder Splines")
        



#### Returns the type of strokes used.
def get_strokes_type(main_object):
    strokes_type = ""
    strokes_num = 0
    
    # Check if they are grease pencil
    try:
        #### Get the active grease pencil layer.
        strokes_num = len(main_object.grease_pencil.layers.active.active_frame.strokes)
        
        if strokes_num > 0:
            strokes_type = "GP_STROKES"
    except:
        pass
    
    
    # Check if they are curves, if there aren't grease pencil strokes.
    if strokes_type == "":
        if len(bpy.context.selected_objects) == 2:
            for ob in bpy.context.selected_objects:
                if ob != bpy.context.scene.objects.active and ob.type == "CURVE":
                    strokes_type = "EXTERNAL_CURVE"
                    strokes_num = len(ob.data.splines)
                    
                    # Check if there is any non-bezier spline.
                    for i in range(len(ob.data.splines)):
                        if ob.data.splines[i].type != "BEZIER":
                            strokes_type = "CURVE_WITH_NON_BEZIER_SPLINES"
                            break
                            
                elif ob != bpy.context.scene.objects.active and ob.type != "CURVE":
                    strokes_type = "EXTERNAL_NO_CURVE"
        elif len(bpy.context.selected_objects) > 2:
            strokes_type = "MORE_THAN_ONE_EXTERNAL"
    
    
    # Check if there is a single stroke without any selection in the object.
    if strokes_num == 1 and main_object.data.total_vert_sel == 0:
        if strokes_type == "EXTERNAL_CURVE":
            strokes_type = "SINGLE_CURVE_STROKE_NO_SELECTION"
        elif strokes_type == "GP_STROKES":
            strokes_type = "SINGLE_GP_STROKE_NO_SELECTION"
    if strokes_num == 0 and main_object.data.total_vert_sel > 0:
        strokes_type = "SELECTION_ALONE"
        
    if strokes_type == "":
        strokes_type = "NO_STROKES"
    
    
    
    return strokes_type



# Surface generator operator.
Eclectiel L's avatar
Eclectiel L committed
class GPENCIL_OT_SURFSK_add_surface(bpy.types.Operator):
    bl_idname = "gpencil.surfsk_add_surface"
Eclectiel L's avatar
Eclectiel L committed
    bl_label = "Bsurfaces add surface"
    bl_description = "Generates surfaces from grease pencil strokes, bezier curves or loose edges."
Eclectiel L's avatar
Eclectiel L committed
    bl_options = {'REGISTER', 'UNDO'}
    edges_U = bpy.props.IntProperty(name = "Cross",
                        description = "Number of face-loops crossing the strokes.",
                        default = 1,
                        min = 1,
                        max = 200)
                        
    edges_V = bpy.props.IntProperty(name = "Follow",
                        description = "Number of face-loops following the strokes.",
                        default = 1,
                        min = 1,
                        max = 200)
    
    cyclic_cross = bpy.props.BoolProperty(name = "Cyclic Cross",
                        description = "Make cyclic the face-loops crossing the strokes.",
                        default = False)
                        
    cyclic_follow = bpy.props.BoolProperty(name = "Cyclic Follow",
                        description = "Make cyclic the face-loops following the strokes.",
                        default = False)
                        
    loops_on_strokes = bpy.props.BoolProperty(name = "Loops on strokes",
                        description = "Make the loops match the paths of the strokes.",
                        default = False)
    
    automatic_join = bpy.props.BoolProperty(name = "Automatic join",
                        description = "Join automatically vertices of either surfaces generated by crosshatching, or from the borders of closed shapes.",
                        default = False)
                        
    join_stretch_factor = bpy.props.FloatProperty(name = "Stretch",
                        description = "Amount of stretching or shrinking allowed for edges when joining vertices automatically.",
                        default = 1,
                        min = 0,
                        max = 3,
                        subtype = 'FACTOR')
    
    
    
    
    def draw(self, context):
        layout = self.layout
        
        scn = context.scene
        ob = context.object
        
        col = layout.column(align=True)
        row = layout.row()
        
        if not self.is_fill_faces:
            row.separator()
            if not self.is_crosshatch:
                if not self.selection_U_exists:
                    col.prop(self, "edges_U")
                    row.separator()
                    
                if not self.selection_V_exists:
                    col.prop(self, "edges_V")
                    row.separator()
                
                row.separator()
                
                if not self.selection_U_exists:
                    if not ((self.selection_V_exists and not self.selection_V_is_closed) or (self.selection_V2_exists and not self.selection_V2_is_closed)):
                        col.prop(self, "cyclic_cross")
                    
                if not self.selection_V_exists:
                    if not ((self.selection_U_exists and not self.selection_U_is_closed) or (self.selection_U2_exists and not self.selection_U2_is_closed)):
                        col.prop(self, "cyclic_follow")
                
                
                col.prop(self, "loops_on_strokes")
            
            col.prop(self, "automatic_join")    
                
            if self.automatic_join:
                row.separator()
                col.separator()
                row.separator()
                col.prop(self, "join_stretch_factor")
            
    
    
    #### Get an ordered list of a chain of vertices.
    def get_ordered_verts(self, ob, all_selected_edges_idx, all_selected_verts_idx, first_vert_idx, middle_vertex_idx, closing_vert_idx):
        # Order selected vertices.
        verts_ordered = []
        if closing_vert_idx != None:
            verts_ordered.append(ob.data.vertices[closing_vert_idx])
            
        verts_ordered.append(ob.data.vertices[first_vert_idx])
        prev_v = first_vert_idx
        prev_ed = None
        finish_while = False
        while True:
            edges_non_matched = 0
            for i in all_selected_edges_idx:
                if ob.data.edges[i] != prev_ed and ob.data.edges[i].vertices[0] == prev_v and ob.data.edges[i].vertices[1] in all_selected_verts_idx:
                    verts_ordered.append(ob.data.vertices[ob.data.edges[i].vertices[1]])
                    prev_v = ob.data.edges[i].vertices[1]
                    prev_ed = ob.data.edges[i]
                elif ob.data.edges[i] != prev_ed and ob.data.edges[i].vertices[1] == prev_v and ob.data.edges[i].vertices[0] in all_selected_verts_idx:
                    verts_ordered.append(ob.data.vertices[ob.data.edges[i].vertices[0]])
                    prev_v = ob.data.edges[i].vertices[0]
                    prev_ed = ob.data.edges[i]
                else:
                    edges_non_matched += 1
                    
                    if edges_non_matched == len(all_selected_edges_idx):
                        finish_while = True
                    
            if finish_while:
                break
        
        if closing_vert_idx != None:
            verts_ordered.append(ob.data.vertices[closing_vert_idx])
        
        if middle_vertex_idx != None:
            verts_ordered.append(ob.data.vertices[middle_vertex_idx])
            verts_ordered.reverse()
        
        return tuple(verts_ordered)
    
    
    #### Calculates length of a chain of points.
Eclectiel L's avatar
Eclectiel L committed
    def get_chain_length(self, object, verts_ordered):
        matrix = object.matrix_world
Eclectiel L's avatar
Eclectiel L committed
        
        edges_lengths = []
        edges_lengths_sum = 0
        for i in range(0, len(verts_ordered)):
            if i == 0:
                prev_v_co = matrix * verts_ordered[i].co
                v_co = matrix * verts_ordered[i].co
Eclectiel L's avatar
Eclectiel L committed
                v_difs = [prev_v_co[0] - v_co[0], prev_v_co[1] - v_co[1], prev_v_co[2] - v_co[2]]
                edge_length = abs(sqrt(v_difs[0] * v_difs[0] + v_difs[1] * v_difs[1] + v_difs[2] * v_difs[2]))
                
                edges_lengths.append(edge_length)
                edges_lengths_sum += edge_length
                
Eclectiel L's avatar
Eclectiel L committed
                prev_v_co = v_co
        return edges_lengths, edges_lengths_sum
    
    
    #### Calculates the proportion of the edges of a chain of edges, relative to the full chain length.
    def get_edges_proportions(self, edges_lengths, edges_lengths_sum, use_boundaries, fixed_edges_num):
        edges_proportions = []
        if use_boundaries:
            verts_count = 1
            for l in edges_lengths:
                edges_proportions.append(l / edges_lengths_sum)
                verts_count += 1
        else:
            verts_count = 1
            for n in range(0, fixed_edges_num):
                edges_proportions.append(1 / fixed_edges_num)
                verts_count += 1
        
        return edges_proportions
    
    
    #### Calculates the angle between two pairs of points in space.
    def orientation_difference(self, points_A_co, points_B_co): # each parameter should be a list with two elements, and each element should be a x,y,z coordinate.
        vec_A = points_A_co[0] - points_A_co[1]
        vec_B = points_B_co[0] - points_B_co[1]
        
        angle = vec_A.angle(vec_B)
        
        if angle > 0.5 * math.pi:
            angle = abs(angle - math.pi)
        
        return angle
    
    #### Calculate the which vert of verts_idx list is the nearest one to the point_co coordinates, and the distance.
    def shortest_distance(self, object, point_co, verts_idx):
        matrix = object.matrix_world
        for i in range(0, len(verts_idx)):
            dist = (point_co - matrix * object.data.vertices[verts_idx[i]].co).length
            if i == 0:
                prev_dist = dist
                nearest_vert_idx = verts_idx[i]
                shortest_dist = dist
            if dist < prev_dist:
                prev_dist = dist
                nearest_vert_idx = verts_idx[i]
                shortest_dist = dist
        return nearest_vert_idx, shortest_dist
    #### Returns the index of the opposite vert tip in a chain, given a vert tip index as parameter, and a multidimentional list with all pairs of tips.
    def opposite_tip(self, vert_tip_idx, all_chains_tips_idx):
        opposite_vert_tip_idx = None
        for i in range(0, len(all_chains_tips_idx)):
            if vert_tip_idx == all_chains_tips_idx[i][0]:
                opposite_vert_tip_idx = all_chains_tips_idx[i][1]
            if vert_tip_idx == all_chains_tips_idx[i][1]:
                opposite_vert_tip_idx = all_chains_tips_idx[i][0]
        return opposite_vert_tip_idx
    #### Simplifies a spline and returns the new points coordinates.
    def simplify_spline(self, spline_coords, segments_num):
        simplified_spline = []
        points_between_segments = round(len(spline_coords) / segments_num)
        simplified_spline.append(spline_coords[0])
        for i in range(1, segments_num):
            simplified_spline.append(spline_coords[i * points_between_segments])
                    
        simplified_spline.append(spline_coords[len(spline_coords) - 1])
        return simplified_spline
    
    
    
    #### Cleans up the scene and gets it the same it was at the beginning, in case the script is interrupted in the middle of the execution.
    def cleanup_on_interruption(self):
        # If the original strokes curve comes from conversion from grease pencil and wasn't made by hand, delete it.
        if not self.using_external_curves:
            try:
                bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
                bpy.data.objects[self.original_curve.name].select = True
                bpy.context.scene.objects.active = bpy.data.objects[self.original_curve.name]
                
                bpy.ops.object.delete()
            except:
                pass
            
            bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.data.objects[self.main_object.name].select = True
            bpy.context.scene.objects.active = bpy.data.objects[self.main_object.name]
            bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.data.objects[self.original_curve.name].select = True
            bpy.data.objects[self.main_object.name].select = True
            bpy.context.scene.objects.active = bpy.data.objects[self.main_object.name]
        
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
    
    
    
    #### Returns a list with the coords of the points distributed over the splines passed to this method according to the proportions parameter.
    def distribute_pts(self, surface_splines, proportions):
        # Calculate the length of each final surface spline.
        surface_splines_lengths = []
        surface_splines_parsed = []
        for sp_idx in range(0, len(surface_splines)):
            # Calculate spline length
            surface_splines_lengths.append(0)
            for i in range(0, len(surface_splines[sp_idx].bezier_points)):
                if i == 0:
                    prev_p = surface_splines[sp_idx].bezier_points[i]
                else:
                    p = surface_splines[sp_idx].bezier_points[i]
                    
                    edge_length = (prev_p.co - p.co).length
                    
                    surface_splines_lengths[sp_idx] += edge_length
                    
                    prev_p = p
        # Calculate vertex positions with appropriate edge proportions, and ordered, for each spline.
        for sp_idx in range(0, len(surface_splines)):
            surface_splines_parsed.append([])
            surface_splines_parsed[sp_idx].append(surface_splines[sp_idx].bezier_points[0].co)
            prev_p_co = surface_splines[sp_idx].bezier_points[0].co
            p_idx = 0
            for prop_idx in range(len(proportions) - 1):
                target_length = surface_splines_lengths[sp_idx] * proportions[prop_idx]
Eclectiel L's avatar
Eclectiel L committed
                
                partial_segment_length = 0
                
                
                finish_while = False
                while True:
                    p_co = surface_splines[sp_idx].bezier_points[p_idx].co
                    
                    new_dist = (prev_p_co - p_co).length
                    
                    potential_segment_length = partial_segment_length + new_dist # The new distance that could have the partial segment if it is still shorter than the target length.
                    
                    
                    if potential_segment_length < target_length: # If the potential is still shorter, keep adding.
                        partial_segment_length = potential_segment_length
                        
                        p_idx += 1
                        prev_p_co = p_co
                        
                    elif potential_segment_length > target_length: # If the potential is longer than the target, calculate the target (a point between the last two points), and assign.
                        remaining_dist = target_length - partial_segment_length
                        vec = p_co - prev_p_co
                        vec.normalize()
                        intermediate_co = prev_p_co + (vec * remaining_dist)
                        
                        surface_splines_parsed[sp_idx].append(intermediate_co)
                        
                        partial_segment_length += remaining_dist
                        prev_p_co = intermediate_co
                        
                        finish_while = True
                        
                    elif potential_segment_length == target_length: # If the potential is equal to the target, assign.
                        surface_splines_parsed[sp_idx].append(p_co)
                        
                        prev_p_co = p_co
                        
                        finish_while = True
                        
                    if finish_while:
                        break
            # last point of the spline
            surface_splines_parsed[sp_idx].append(surface_splines[sp_idx].bezier_points[len(surface_splines[sp_idx].bezier_points) - 1].co)
        
        
        return surface_splines_parsed
    
    
    
    #### Counts the number of faces that belong to each edge.
    def edge_face_count(self, ob):
        ed_keys_count_dict = {}
        
        for face in ob.data.polygons:
            for ed_keys in face.edge_keys:
                if not ed_keys in ed_keys_count_dict:
                    ed_keys_count_dict[ed_keys] = 1
                else:
                    ed_keys_count_dict[ed_keys] += 1
        
        
        edge_face_count = []
        for i in range(len(ob.data.edges)):
            edge_face_count.append(0)
        
        for i in range(len(ob.data.edges)):
            ed = ob.data.edges[i]
            v1 = ed.vertices[0]
            v2 = ed.vertices[1]
            if (v1, v2) in ed_keys_count_dict:
                edge_face_count[i] = ed_keys_count_dict[(v1, v2)]
            elif (v2, v1) in ed_keys_count_dict:
                edge_face_count[i] = ed_keys_count_dict[(v2, v1)]
        return edge_face_count
    
    
    
    #### Fills with faces all the selected vertices which form empty triangles or quads.
    def fill_with_faces(self, object):
        all_selected_verts_count = self.main_object_selected_verts_count
        bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
        #### Calculate average length of selected edges.
        all_selected_verts = []
        original_sel_edges_count = 0
        for ed in object.data.edges:
            if object.data.vertices[ed.vertices[0]].select and object.data.vertices[ed.vertices[1]].select:
                coords = []
                coords.append(object.data.vertices[ed.vertices[0]].co)
                coords.append(object.data.vertices[ed.vertices[1]].co)
                
                original_sel_edges_count += 1
                
                if not ed.vertices[0] in all_selected_verts:
                    all_selected_verts.append(ed.vertices[0])
                    
                if not ed.vertices[1] in all_selected_verts:
                    all_selected_verts.append(ed.vertices[1])
                
        tuple(all_selected_verts)
        
        #### Check if there is any edge selected. If not, interrupt the script.
        if original_sel_edges_count == 0 and all_selected_verts_count > 0:
            return 0
        
        
        
        #### Get all edges connected to selected verts.
        all_edges_around_sel_verts = []
        edges_connected_to_sel_verts = {}
        verts_connected_to_every_vert = {}
        for ed_idx in range(len(object.data.edges)):
            ed = object.data.edges[ed_idx]
            include_edge = False
            if ed.vertices[0] in all_selected_verts:
                if not ed.vertices[0] in edges_connected_to_sel_verts:
                    edges_connected_to_sel_verts[ed.vertices[0]] = []
                
                edges_connected_to_sel_verts[ed.vertices[0]].append(ed_idx)
                include_edge = True
            if ed.vertices[1] in all_selected_verts:
                if not ed.vertices[1] in edges_connected_to_sel_verts:
                    edges_connected_to_sel_verts[ed.vertices[1]] = []
                
                edges_connected_to_sel_verts[ed.vertices[1]].append(ed_idx)
                include_edge = True
            if include_edge == True:
                all_edges_around_sel_verts.append(ed_idx)
            # Get all connected verts to each vert.
            if not ed.vertices[0] in verts_connected_to_every_vert:
                verts_connected_to_every_vert[ed.vertices[0]] = []
            
            if not ed.vertices[1] in verts_connected_to_every_vert:
                verts_connected_to_every_vert[ed.vertices[1]] = []
            verts_connected_to_every_vert[ed.vertices[0]].append(ed.vertices[1])
            verts_connected_to_every_vert[ed.vertices[1]].append(ed.vertices[0])
        
        
        
        #### Get all verts connected to faces.
        all_verts_part_of_faces = []
        all_edges_faces_count = []
        all_edges_faces_count += self.edge_face_count(object)
        
        # Get only the selected edges that have faces attached.
        count_faces_of_edges_around_sel_verts = {}
        selected_verts_with_faces = []
        for ed_idx in all_edges_around_sel_verts:
            count_faces_of_edges_around_sel_verts[ed_idx] = all_edges_faces_count[ed_idx]
            if all_edges_faces_count[ed_idx] > 0:
                ed = object.data.edges[ed_idx]
                
                if not ed.vertices[0] in selected_verts_with_faces:
                    selected_verts_with_faces.append(ed.vertices[0])
                
                if not ed.vertices[1] in selected_verts_with_faces:
                    selected_verts_with_faces.append(ed.vertices[1])
        
                all_verts_part_of_faces.append(ed.vertices[0])
                all_verts_part_of_faces.append(ed.vertices[1])
        
        tuple(selected_verts_with_faces)
        
        
        
        #### Discard unneeded verts from calculations.
        participating_verts = []
        movable_verts = []
        for v_idx in all_selected_verts:
            vert_has_edges_with_one_face = False
            
            for ed_idx in edges_connected_to_sel_verts[v_idx]: # Check if the actual vert has at least one edge connected to only one face.
                if count_faces_of_edges_around_sel_verts[ed_idx] == 1:
                    vert_has_edges_with_one_face = True
            
            # If the vert has two or less edges connected and the vert is not part of any face. Or the vert is part of any face and at least one of the connected edges has only one face attached to it.
            if (len(edges_connected_to_sel_verts[v_idx]) == 2 and not v_idx in all_verts_part_of_faces) or len(edges_connected_to_sel_verts[v_idx]) == 1 or (v_idx in all_verts_part_of_faces and vert_has_edges_with_one_face):
                participating_verts.append(v_idx)
                
                if not v_idx in all_verts_part_of_faces:
                    movable_verts.append(v_idx)
        
        
        
        #### Remove from movable verts list those that are part of closed geometry (ie: triangles, quads)
        for mv_idx in movable_verts:
            freeze_vert = False
            mv_connected_verts = verts_connected_to_every_vert[mv_idx]
            
            for actual_v_idx in all_selected_verts:
                count_shared_neighbors = 0
                checked_verts = []
                
                for mv_conn_v_idx in mv_connected_verts:
                    if mv_idx != actual_v_idx:
                        if mv_conn_v_idx in verts_connected_to_every_vert[actual_v_idx] and not mv_conn_v_idx in checked_verts:
                            count_shared_neighbors += 1
                            checked_verts.append(mv_conn_v_idx)
                            
                            
                            if actual_v_idx in mv_connected_verts:
                                freeze_vert = True
                                break
                            
                        if count_shared_neighbors == 2:
                            freeze_vert = True
                            break
                
                if freeze_vert:
                    break
            
            if freeze_vert:
                movable_verts.remove(mv_idx)
        
        
        #### Calculate merge distance for participating verts.
        shortest_edge_length = None
        for ed in object.data.edges:
            if ed.vertices[0] in movable_verts and ed.vertices[1] in movable_verts:
                v1 = object.data.vertices[ed.vertices[0]]
                v2 = object.data.vertices[ed.vertices[1]]
                
                length = (v1.co - v2.co).length
                
                if shortest_edge_length == None:
                    shortest_edge_length = length
                else:
                    if length < shortest_edge_length:
                        shortest_edge_length = length
            
        if shortest_edge_length != None:
            edges_merge_distance = shortest_edge_length * 0.5
        else:
            edges_merge_distance = 0
        
        
        
        
        #### Get together the verts near enough. They will be merged later.
        remaining_verts = []
        remaining_verts += participating_verts
        for v1_idx in participating_verts:
            if v1_idx in remaining_verts and v1_idx in movable_verts:
                verts_to_merge = []
                coords_verts_to_merge = {}
                
                verts_to_merge.append(v1_idx)
                
                v1_co = object.data.vertices[v1_idx].co
                coords_verts_to_merge[v1_idx] = (v1_co[0], v1_co[1], v1_co[2])
                
                
                for v2_idx in remaining_verts:
                    if v1_idx != v2_idx:
                        v2_co = object.data.vertices[v2_idx].co
                        dist = (v1_co - v2_co).length
                        if dist <= edges_merge_distance: # Add the verts which are near enough.
                            verts_to_merge.append(v2_idx)
                            
                            coords_verts_to_merge[v2_idx] = (v2_co[0], v2_co[1], v2_co[2])
                            
                
                for vm_idx in verts_to_merge:
                    remaining_verts.remove(vm_idx)
                
                
                if len(verts_to_merge) > 1:
                    # Calculate middle point of the verts to merge.
                    sum_x_co = 0
                    sum_y_co = 0
                    sum_z_co = 0
                    movable_verts_to_merge_count = 0
                    for i in range(len(verts_to_merge)):
                        if verts_to_merge[i] in movable_verts:
                            v_co = object.data.vertices[verts_to_merge[i]].co
                            
                            sum_x_co += v_co[0]
                            sum_y_co += v_co[1]
                            sum_z_co += v_co[2]
                            
                            movable_verts_to_merge_count += 1
                    
                    middle_point_co = [sum_x_co / movable_verts_to_merge_count, sum_y_co / movable_verts_to_merge_count, sum_z_co / movable_verts_to_merge_count]
                    
                    
                    # Check if any vert to be merged is not movable.
                    shortest_dist = None
                    are_verts_not_movable = False
                    verts_not_movable = []
                    for v_merge_idx in verts_to_merge:
                        if v_merge_idx in participating_verts and not v_merge_idx in movable_verts:
                            are_verts_not_movable = True
                            verts_not_movable.append(v_merge_idx)
                    
                    if are_verts_not_movable:
                        # Get the vert connected to faces, that is nearest to the middle point of the movable verts.
                        shortest_dist = None
                        for vcf_idx in verts_not_movable:
                                dist = abs((object.data.vertices[vcf_idx].co - mathutils.Vector(middle_point_co)).length)
                                
                                if shortest_dist == None:
                                    shortest_dist = dist
                                    nearest_vert_idx = vcf_idx
                                else:
                                    if dist < shortest_dist:
                                        shortest_dist = dist
                                        nearest_vert_idx = vcf_idx
                                    
                        coords = object.data.vertices[nearest_vert_idx].co
                        target_point_co = [coords[0], coords[1], coords[2]]                                    
                    else:
                         target_point_co = middle_point_co
                       
                    
                    # Move verts to merge to the middle position.
                    for v_merge_idx in verts_to_merge:
                        if v_merge_idx in movable_verts: # Only move the verts that are not part of faces.
                            object.data.vertices[v_merge_idx].co[0] = target_point_co[0]
                            object.data.vertices[v_merge_idx].co[1] = target_point_co[1]
                            object.data.vertices[v_merge_idx].co[2] = target_point_co[2]
                
                
        
        #### Perform "Remove Doubles" to weld all the disconnected verts
        bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='EDIT')
        bpy.ops.mesh.remove_doubles(mergedist = 0.0001)
        
        bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
        
        
        #### Get all the definitive selected edges, after weldding.
        selected_edges = []
        edges_per_vert = {} # Number of faces of each selected edge.
        for ed in object.data.edges:
            if object.data.vertices[ed.vertices[0]].select and object.data.vertices[ed.vertices[1]].select:
                selected_edges.append(ed.index)
                
                # Save all the edges that belong to each vertex.
                if not ed.vertices[0] in edges_per_vert:
                    edges_per_vert[ed.vertices[0]] = []
                
                if not ed.vertices[1] in edges_per_vert:
                    edges_per_vert[ed.vertices[1]] = []
                
                edges_per_vert[ed.vertices[0]].append(ed.index)
                edges_per_vert[ed.vertices[1]].append(ed.index)
        
        # Check if all the edges connected to each vert have two faces attached to them. To discard them later and make calculations faster.
        a = []
        a += self.edge_face_count(object)
        tuple(a)
        verts_surrounded_by_faces = {}
        for v_idx in edges_per_vert:
            edges = edges_per_vert[v_idx]
            edges_with_two_faces_count = 0
            for ed_idx in edges_per_vert[v_idx]:
                if a[ed_idx] == 2:
                    edges_with_two_faces_count += 1
            if edges_with_two_faces_count == len(edges_per_vert[v_idx]):
                verts_surrounded_by_faces[v_idx] = True
            else:
                verts_surrounded_by_faces[v_idx] = False
                
                
        #### Get all the selected vertices.
        selected_verts_idx = []
        for v in object.data.vertices:
            if v.select:
                selected_verts_idx.append(v.index)
        
        
        #### Get all the faces of the object.
        all_object_faces_verts_idx = []
        for face in object.data.polygons:
            face_verts = []
            face_verts.append(face.vertices[0])
            face_verts.append(face.vertices[1])
            face_verts.append(face.vertices[2])
            
            if len(face.vertices) == 4:
                face_verts.append(face.vertices[3])
                
            all_object_faces_verts_idx.append(face_verts)
                        
            
        #### Deselect all vertices.
        bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='EDIT')
        bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
        
        
        
        #### Make a dictionary with the verts related to each vert.
        related_key_verts = {}
        for ed_idx in selected_edges:
            ed = object.data.edges[ed_idx]
            
            if not verts_surrounded_by_faces[ed.vertices[0]]:
                if not ed.vertices[0] in related_key_verts:
                    related_key_verts[ed.vertices[0]] = []
                
                if not ed.vertices[1] in related_key_verts[ed.vertices[0]]:
                    related_key_verts[ed.vertices[0]].append(ed.vertices[1])
            
            if not verts_surrounded_by_faces[ed.vertices[1]]:
                if not ed.vertices[1] in related_key_verts:
                    related_key_verts[ed.vertices[1]] = []
                
                if not ed.vertices[0] in related_key_verts[ed.vertices[1]]:
                    related_key_verts[ed.vertices[1]].append(ed.vertices[0])
        
        
            
        #### Get groups of verts forming each face.
        faces_verts_idx = [] 
        for v1 in related_key_verts: # verts-1 .... 
            for v2 in related_key_verts: # verts-2
                if v1 != v2:
                    related_verts_in_common = []
                    v2_in_rel_v1 = False
                    v1_in_rel_v2 = False
                    for rel_v1 in related_key_verts[v1]:
                        if rel_v1 in related_key_verts[v2]: # Check if related verts of verts-1 are related verts of verts-2.
                            related_verts_in_common.append(rel_v1)
                        
                    if v2 in related_key_verts[v1]:
                        v2_in_rel_v1 = True
                            
                    if v1 in related_key_verts[v2]:
                        v1_in_rel_v2 = True
                    
                    
                    repeated_face = False
                    # If two verts have two related verts in common, they form a quad.
                    if len(related_verts_in_common) == 2:
                        # Check if the face is already saved.
                        all_faces_to_check_idx = faces_verts_idx + all_object_faces_verts_idx
                        
                        
                        for f_verts in all_faces_to_check_idx:
                            repeated_verts = 0
                            
                            if len(f_verts) == 4:
                                if v1 in f_verts: repeated_verts += 1
                                if v2 in f_verts: repeated_verts += 1
                                if related_verts_in_common[0] in f_verts: repeated_verts += 1
                                if related_verts_in_common[1] in f_verts: repeated_verts += 1
                                
                                if repeated_verts == len(f_verts):
                                    repeated_face = True
                                    break
                        
                        if not repeated_face:
                            faces_verts_idx.append([v1, related_verts_in_common[0], v2, related_verts_in_common[1]])
                        
                    elif v2_in_rel_v1 and v1_in_rel_v2 and len(related_verts_in_common) == 1: # If Two verts have one related vert in common and they are related to each other, they form a triangle.
                        # Check if the face is already saved.
                        all_faces_to_check_idx = faces_verts_idx + all_object_faces_verts_idx
                        for f_verts in all_faces_to_check_idx:
                            repeated_verts = 0
                            
                            if len(f_verts) == 3:
                                if v1 in f_verts: repeated_verts += 1
                                if v2 in f_verts: repeated_verts += 1
                                if related_verts_in_common[0] in f_verts: repeated_verts += 1
                                
                                if repeated_verts == len(f_verts):
                                    repeated_face = True
                                    break
                        
                        if not repeated_face:
                            faces_verts_idx.append([v1, related_verts_in_common[0], v2])
                
        #### Keep only the faces that don't overlap by ignoring quads that overlap with two adjacent triangles.
        faces_to_not_include_idx = [] # Indices of faces_verts_idx to eliminate.
        all_faces_to_check_idx = faces_verts_idx + all_object_faces_verts_idx
        for i in range(len(faces_verts_idx)):
            for t in range(len(all_faces_to_check_idx)):
                if i != t:
                    verts_in_common = 0
                    
                    if len(faces_verts_idx[i]) == 4 and len(all_faces_to_check_idx[t]) == 3:
                        for v_idx in all_faces_to_check_idx[t]:
                            if v_idx in faces_verts_idx[i]:
                                verts_in_common += 1
                                
                        if verts_in_common == 3: # If it doesn't have all it's vertices repeated in the other face.
                            if not i in faces_to_not_include_idx:
                                faces_to_not_include_idx.append(i)
        
        
        #### Build faces discarding the ones in faces_to_not_include.
        me = object.data
        bm = bmesh.new()
        bm.from_mesh(me)
        
        num_faces_created = 0
        for i in range(len(faces_verts_idx)):
            if not i in faces_to_not_include_idx:
                bm.faces.new([ bm.verts[v] for v in faces_verts_idx[i] ])
                
                num_faces_created += 1
        
        bm.to_mesh(me)
        bm.free()
        
        
        
        for v_idx in selected_verts_idx:
            self.main_object.data.vertices[v_idx].select = True
        
        
        bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='EDIT')
        bpy.ops.mesh.normals_make_consistent(inside=False)
        bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
        
        return num_faces_created
        
        
    
    #### Crosshatch skinning.
    def crosshatch_surface_invoke(self, ob_original_splines):
        self.is_crosshatch = False
        self.crosshatch_merge_distance = 0
        
        
        objects_to_delete = [] # duplicated strokes to be deleted.
        
        # If the main object uses modifiers deactivate them temporarily until the surface is joined. (without this the surface verts merging with the main object doesn't work well)
        self.modifiers_prev_viewport_state = []
        if len(self.main_object.modifiers) > 0:
            for m_idx in range(len(self.main_object.modifiers)):
                self.modifiers_prev_viewport_state.append(self.main_object.modifiers[m_idx].show_viewport)
                
                self.main_object.modifiers[m_idx].show_viewport = False
        
        
        bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.data.objects[ob_original_splines.name].select = True
        bpy.context.scene.objects.active = bpy.data.objects[ob_original_splines.name]
        
        
        if len(ob_original_splines.data.splines) >= 2:
            bpy.ops.object.duplicate('INVOKE_REGION_WIN')
            ob_splines = bpy.context.object
            ob_splines.name = "SURFSKIO_NE_STR"
            
            
            #### Get estimative merge distance (sum up the distances from the first point to all other points, then average them and then divide them).
            first_point_dist_sum = 0
            first_dist = 0
            second_dist = 0
            coords_first_pt = ob_splines.data.splines[0].bezier_points[0].co
            for i in range(len(ob_splines.data.splines)):
                sp = ob_splines.data.splines[i]
                
                if coords_first_pt != sp.bezier_points[0].co:
                    first_dist = (coords_first_pt - sp.bezier_points[0].co).length
                    
                if coords_first_pt != sp.bezier_points[len(sp.bezier_points) - 1].co:
                    second_dist = (coords_first_pt - sp.bezier_points[len(sp.bezier_points) - 1].co).length
                
                first_point_dist_sum += first_dist + second_dist
                
                
                if i == 0:
                    if first_dist != 0:
                        shortest_dist = first_dist
                    elif second_dist != 0:
                        shortest_dist = second_dist
                    
                if shortest_dist > first_dist and first_dist != 0:
                    shortest_dist = first_dist
                
                if shortest_dist > second_dist and second_dist != 0:
                    shortest_dist = second_dist
                
            self.crosshatch_merge_distance = shortest_dist / 20
            #### Recalculation of merge distance.
            
            bpy.ops.object.duplicate('INVOKE_REGION_WIN')
            
            ob_calc_merge_dist = bpy.context.object
            ob_calc_merge_dist.name = "SURFSKIO_CALC_TMP"
            
            objects_to_delete.append(ob_calc_merge_dist)
            
            
            
            #### Smooth out strokes a little to improve crosshatch detection.
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='SELECT')
            
            for i in range(4):
                bpy.ops.curve.smooth('INVOKE_REGION_WIN')
            
            bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            #### Convert curves into mesh.
            ob_calc_merge_dist.data.resolution_u = 12
            bpy.ops.object.convert(target='MESH', keep_original=False)
            
            # Find "intersection-nodes".
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='SELECT')
            bpy.ops.mesh.remove_doubles('INVOKE_REGION_WIN', mergedist=self.crosshatch_merge_distance)
            bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            # Remove verts with less than three edges.
            verts_edges_count = {}
            for ed in ob_calc_merge_dist.data.edges:
                v = ed.vertices
                if v[0] not in verts_edges_count:
                    verts_edges_count[v[0]] = 0
                if v[1] not in verts_edges_count:
                    verts_edges_count[v[1]] = 0
                verts_edges_count[v[0]] += 1
                verts_edges_count[v[1]] += 1
            
            nodes_verts_coords = []
            for v_idx in verts_edges_count:
                v = ob_calc_merge_dist.data.vertices[v_idx]
                
                if verts_edges_count[v_idx] < 3:
                    v.select = True
            
            # Remove them.
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            bpy.ops.mesh.delete('INVOKE_REGION_WIN', type='VERT')
            bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='SELECT')
            
            # Remove doubles to discard very near verts from calculations of distance.
            bpy.ops.mesh.remove_doubles('INVOKE_REGION_WIN', mergedist=self.crosshatch_merge_distance * 4)
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            # Get all coords of the resulting nodes.
            nodes_verts_coords = [(v.co[0], v.co[1], v.co[2]) for v in ob_calc_merge_dist.data.vertices]
            
            #### Check if the strokes are a crosshatch.
            if len(nodes_verts_coords) >= 3:
                self.is_crosshatch = True
                shortest_dist = None
                for co_1 in nodes_verts_coords:
                    for co_2 in nodes_verts_coords:
                        if co_1 != co_2:
                            dist = (mathutils.Vector(co_1) - mathutils.Vector(co_2)).length
                            
                            if shortest_dist != None:
                                if dist < shortest_dist:
                                    shortest_dist = dist
                            else:
                                shortest_dist = dist
                self.crosshatch_merge_distance = shortest_dist / 3
            
            
            bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.data.objects[ob_splines.name].select = True
            bpy.context.scene.objects.active = bpy.data.objects[ob_splines.name]
            
            #### Deselect all points.
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            
            
            #### Smooth splines in a localized way, to eliminate "saw-teeth" like shapes when there are many points.
            for sp in ob_splines.data.splines:
                angle_sum = 0
                angle_limit = 2 # Degrees
                for t in range(len(sp.bezier_points)):
                    if t <= len(sp.bezier_points) - 3: # Because on each iteration it checks the "next two points" of the actual. This way it doesn't go out of range.
                        p1 = sp.bezier_points[t]
                        p2 = sp.bezier_points[t + 1]
                        p3 = sp.bezier_points[t + 2]
                        
                        vec_1 = p1.co - p2.co
                        vec_2 = p2.co - p3.co
                        
                        if p2.co != p1.co and p2.co != p3.co:
                            angle = vec_1.angle(vec_2)
                            angle_sum += degrees(angle)
                            
                            if angle_sum >= angle_limit: # If sum of angles is grater than the limit.
                                if (p1.co - p2.co).length <= self.crosshatch_merge_distance:
                                    p1.select_control_point = True; p1.select_left_handle = True; p1.select_right_handle = True
                                    p2.select_control_point = True; p2.select_left_handle = True; p2.select_right_handle = True
                                
                                if (p1.co - p2.co).length <= self.crosshatch_merge_distance:
                                    p3.select_control_point = True; p3.select_left_handle = True; p3.select_right_handle = True
                                
                                angle_sum = 0
                sp.bezier_points[0].select_control_point = False
                sp.bezier_points[0].select_left_handle = False
                sp.bezier_points[0].select_right_handle = False
                sp.bezier_points[len(sp.bezier_points) - 1].select_control_point = False
                sp.bezier_points[len(sp.bezier_points) - 1].select_left_handle = False
                sp.bezier_points[len(sp.bezier_points) - 1].select_right_handle  = False
            
            
            #### Smooth out strokes a little to improve crosshatch detection.
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            for i in range(15):
                bpy.ops.curve.smooth('INVOKE_REGION_WIN')
            
            bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            
            
            
            #### Simplify the splines.
            for sp in ob_splines.data.splines:
                angle_sum = 0
                
                sp.bezier_points[0].select_control_point = True
                sp.bezier_points[0].select_left_handle = True
                sp.bezier_points[0].select_right_handle = True
                
                sp.bezier_points[len(sp.bezier_points) - 1].select_control_point = True
                sp.bezier_points[len(sp.bezier_points) - 1].select_left_handle = True
                sp.bezier_points[len(sp.bezier_points) - 1].select_right_handle  = True
                
                
                angle_limit = 15 # Degrees
                for t in range(len(sp.bezier_points)):
                    if t <= len(sp.bezier_points) - 3: # Because on each iteration it checks the "next two points" of the actual. This way it doesn't go out of range.
                        p1 = sp.bezier_points[t]
                        p2 = sp.bezier_points[t + 1]
                        p3 = sp.bezier_points[t + 2]
                        
                        vec_1 = p1.co - p2.co
                        vec_2 = p2.co - p3.co
                        
                        if p2.co != p1.co and p2.co != p3.co:
                            angle = vec_1.angle(vec_2)
                            angle_sum += degrees(angle)
                            
                            if angle_sum >= angle_limit: # If sum of angles is grater than the limit.
                                p1.select_control_point = True; p1.select_left_handle = True; p1.select_right_handle = True
                                p2.select_control_point = True; p2.select_left_handle = True; p2.select_right_handle = True
                                p3.select_control_point = True; p3.select_left_handle = True; p3.select_right_handle = True
                                
                                angle_sum = 0
                            
                            
            
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            bpy.ops.curve.select_all(action = 'INVERT')
            
            bpy.ops.curve.delete(type='SELECTED')
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            
            
            objects_to_delete.append(ob_splines)
            
            
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            
            
            #### Check if the strokes are a crosshatch.
            if self.is_crosshatch:
                all_points_coords = []
                for i in range(len(ob_splines.data.splines)):
                    all_points_coords.append([])
                    all_points_coords[i] = [mathutils.Vector((x, y, z)) for x, y, z in [bp.co for bp in ob_splines.data.splines[i].bezier_points]]
                
                all_intersections = []
                checked_splines = []
                for i in range(len(all_points_coords)):
                        
                    for t in range(len(all_points_coords[i]) - 1):
                        bp1_co = all_points_coords[i][t]
                        bp2_co = all_points_coords[i][t + 1]
                        
                        for i2 in range(len(all_points_coords)):
                            if i != i2 and not i2 in checked_splines:
                                for t2 in range(len(all_points_coords[i2]) - 1):
                                    bp3_co = all_points_coords[i2][t2]
                                    bp4_co = all_points_coords[i2][t2 + 1]
                                    
                                    
                                    intersec_coords = mathutils.geometry.intersect_line_line(bp1_co, bp2_co, bp3_co, bp4_co)
                                    
                                    if intersec_coords != None:
                                        dist = (intersec_coords[0] - intersec_coords[1]).length
                                        
                                        if dist <= self.crosshatch_merge_distance * 1.5:
                                            temp_co, percent1 = mathutils.geometry.intersect_point_line(intersec_coords[0], bp1_co, bp2_co)
                                            
                                            if (percent1 >= -0.02 and percent1 <= 1.02):
                                                temp_co, percent2 = mathutils.geometry.intersect_point_line(intersec_coords[1], bp3_co, bp4_co)
                                                if (percent2 >= -0.02 and percent2 <= 1.02):
                                                    all_intersections.append((i, t, percent1, ob_splines.matrix_world * intersec_coords[0])) # Format: spline index, first point index from corresponding segment, percentage from first point of actual segment, coords of intersection point.
                                                    all_intersections.append((i2, t2, percent2, ob_splines.matrix_world * intersec_coords[1]))
                                            
                                            
                        
                        checked_splines.append(i)        
                
                
                all_intersections.sort(key = operator.itemgetter(0,1,2)) # Sort list by spline, then by corresponding first point index of segment, and then by percentage from first point of segment: elements 0 and 1 respectively.
                
                
                
                self.crosshatch_strokes_coords = {}
                for i in range(len(all_intersections)):
                    if not all_intersections[i][0] in self.crosshatch_strokes_coords:
                        self.crosshatch_strokes_coords[all_intersections[i][0]] = []
                        
                    self.crosshatch_strokes_coords[all_intersections[i][0]].append(all_intersections[i][3]) # Save intersection coords.
                
            else:
                self.is_crosshatch = False
                
        
        #### Delete all duplicates.
        for o in objects_to_delete:
            bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
            bpy.data.objects[o.name].select = True
            bpy.context.scene.objects.active = bpy.data.objects[o.name]
            bpy.ops.object.delete()
            
            
        #### If the main object has modifiers, turn their "viewport view status" to what it was before the forced deactivation above.
        if len(self.main_object.modifiers) > 0:
            for m_idx in range(len(self.main_object.modifiers)):
                self.main_object.modifiers[m_idx].show_viewport = self.modifiers_prev_viewport_state[m_idx]
        return
    
    
    
    #### Part of the Crosshatch process that is repeated when the operator is tweaked.
    def crosshatch_surface_execute(self):
        # If the main object uses modifiers deactivate them temporarily until the surface is joined. (without this the surface verts merging with the main object doesn't work well)
        self.modifiers_prev_viewport_state = []
        if len(self.main_object.modifiers) > 0:
            for m_idx in range(len(self.main_object.modifiers)):
                self.modifiers_prev_viewport_state.append(self.main_object.modifiers[m_idx].show_viewport)
                
                self.main_object.modifiers[m_idx].show_viewport = False
                
                
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        me_name = "SURFSKIO_STK_TMP"
        me = bpy.data.meshes.new(me_name)
        all_verts_coords = []
        all_edges = []
        for st_idx in self.crosshatch_strokes_coords:
            for co_idx in range(len(self.crosshatch_strokes_coords[st_idx])):
                coords = self.crosshatch_strokes_coords[st_idx][co_idx]
                
                all_verts_coords.append(coords)
                
                if co_idx > 0:
                    all_edges.append((len(all_verts_coords) - 2, len(all_verts_coords) - 1))
                    
        me.from_pydata(all_verts_coords, all_edges, [])
        ob = bpy.data.objects.new(me_name, me)
        ob.data = me
        bpy.context.scene.objects.link(ob)
        
        
        bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.data.objects[ob.name].select = True
        bpy.context.scene.objects.active = bpy.data.objects[ob.name]
        
        
        #### Get together each vert and its nearest, to the middle position.
        verts = ob.data.vertices
        checked_verts = []
        for i in range(len(verts)):
            shortest_dist = None
            
            if not i in checked_verts:
                for t in range(len(verts)):
                    if i != t and not t in checked_verts:
                        dist = (verts[i].co - verts[t].co).length
                        
                        if shortest_dist != None:
                            if dist < shortest_dist:
                                shortest_dist = dist
                                nearest_vert = t
                        else:
                            shortest_dist = dist
                            nearest_vert = t
                
                middle_location = (verts[i].co + verts[nearest_vert].co) / 2
                
                verts[i].co = middle_location
                verts[nearest_vert].co = middle_location
                
                checked_verts.append(i)
                checked_verts.append(nearest_vert)
        
        
        
        
        #### Calculate average length between all the generated edges.
        ob = bpy.context.object
        lengths_sum = 0
        for ed in ob.data.edges:
            v1 = ob.data.vertices[ed.vertices[0]]
            v2 = ob.data.vertices[ed.vertices[1]]
            
            lengths_sum += (v1.co - v2.co).length
        
        edges_count = len(ob.data.edges)
        
        average_edge_length = lengths_sum / edges_count
Eclectiel L's avatar
Eclectiel L committed
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='SELECT')
        bpy.ops.mesh.remove_doubles('INVOKE_REGION_WIN', mergedist=average_edge_length / 15)
Eclectiel L's avatar
Eclectiel L committed
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        final_points_ob = bpy.context.scene.objects.active
        
        
        #### Make a dictionary with the verts related to each vert.
        related_key_verts = {}
        for ed in final_points_ob.data.edges:
            if not ed.vertices[0] in related_key_verts:
                related_key_verts[ed.vertices[0]] = []
                
            if not ed.vertices[1] in related_key_verts:
                related_key_verts[ed.vertices[1]] = []
            
            
            if not ed.vertices[1] in related_key_verts[ed.vertices[0]]:
                related_key_verts[ed.vertices[0]].append(ed.vertices[1])
                
            if not ed.vertices[0] in related_key_verts[ed.vertices[1]]:
                related_key_verts[ed.vertices[1]].append(ed.vertices[0])
        
        
        
        #### Get groups of verts forming each face.
        faces_verts_idx = [] 
        for v1 in related_key_verts: # verts-1 .... 
            for v2 in related_key_verts: # verts-2
                if v1 != v2:
                    related_verts_in_common = []
                    v2_in_rel_v1 = False
                    v1_in_rel_v2 = False
                    for rel_v1 in related_key_verts[v1]:
                        if rel_v1 in related_key_verts[v2]: # Check if related verts of verts-1 are related verts of verts-2.
                            related_verts_in_common.append(rel_v1)
                        
                    if v2 in related_key_verts[v1]:
                        v2_in_rel_v1 = True
                            
                    if v1 in related_key_verts[v2]:
                        v1_in_rel_v2 = True
                    
                    
                    repeated_face = False
                    # If two verts have two related verts in common, they form a quad.
                    if len(related_verts_in_common) == 2:
                        # Check if the face is already saved.
                        for f_verts in faces_verts_idx:
                            repeated_verts = 0
                            
                            if len(f_verts) == 4:
                                if v1 in f_verts: repeated_verts += 1
                                if v2 in f_verts: repeated_verts += 1
                                if related_verts_in_common[0] in f_verts: repeated_verts += 1
                                if related_verts_in_common[1] in f_verts: repeated_verts += 1
                                
                                if repeated_verts == len(f_verts):
                                    repeated_face = True
                                    break
                        
                        if not repeated_face:
                            faces_verts_idx.append([v1, related_verts_in_common[0], v2, related_verts_in_common[1]])
                        
                    elif v2_in_rel_v1 and v1_in_rel_v2 and len(related_verts_in_common) == 1: # If Two verts have one related vert in common and they are related to each other, they form a triangle.
                        # Check if the face is already saved.
                        for f_verts in faces_verts_idx:
                            repeated_verts = 0
                            
                            if len(f_verts) == 3:
                                if v1 in f_verts: repeated_verts += 1
                                if v2 in f_verts: repeated_verts += 1
                                if related_verts_in_common[0] in f_verts: repeated_verts += 1
                                
                                if repeated_verts == len(f_verts):
                                    repeated_face = True
                                    break
                        
                        if not repeated_face:
                            faces_verts_idx.append([v1, related_verts_in_common[0], v2])
                
        
        #### Keep only the faces that don't overlap by ignoring quads that overlap with two adjacent triangles.
        faces_to_not_include_idx = [] # Indices of faces_verts_idx to eliminate.
        for i in range(len(faces_verts_idx)):
            for t in range(len(faces_verts_idx)):
                if i != t:
                    verts_in_common = 0
                    
                    if len(faces_verts_idx[i]) == 4 and len(faces_verts_idx[t]) == 3:
                        for v_idx in faces_verts_idx[t]:
                            if v_idx in faces_verts_idx[i]:
                                verts_in_common += 1
                                
                        if verts_in_common == 3: # If it doesn't have all it's vertices repeated in the other face.
                            if not i in faces_to_not_include_idx:
                                faces_to_not_include_idx.append(i)
        
        
        #### Build surface.
        all_surface_verts_co = []
        verts_idx_translation = {}
        for i in range(len(final_points_ob.data.vertices)):
            coords = final_points_ob.data.vertices[i].co
            all_surface_verts_co.append([coords[0], coords[1], coords[2]])
            
        # Verts of each face.
        all_surface_faces = []
        for i in range(len(faces_verts_idx)):
            if not i in faces_to_not_include_idx:
                face = []
                for v_idx in faces_verts_idx[i]:
                    face.append(v_idx)
                
                all_surface_faces.append(face)
        
        # Build the mesh.
        surf_me_name = "SURFSKIO_surface"
        me_surf = bpy.data.meshes.new(surf_me_name)
        
        me_surf.from_pydata(all_surface_verts_co, [], all_surface_faces)
        
        me_surf.update()
        
        ob_surface = bpy.data.objects.new(surf_me_name, me_surf)
        bpy.context.scene.objects.link(ob_surface)
        
        # Delete final points temporal object
        bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.data.objects[final_points_ob.name].select = True
        bpy.context.scene.objects.active = bpy.data.objects[final_points_ob.name]
        
        bpy.ops.object.delete()
        
        
        # Delete isolated verts if there are any.
        bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.data.objects[ob_surface.name].select = True
        bpy.context.scene.objects.active = bpy.data.objects[ob_surface.name]
        
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        bpy.ops.mesh.select_all(action='DESELECT')
        bpy.ops.mesh.select_face_by_sides(type='NOTEQUAL')
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
        bpy.ops.mesh.delete()
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        
        
        
        #### Join crosshatch results with original mesh.
        
        # Calculate a distance to merge the verts of the crosshatch surface to the main object.
        edges_length_sum = 0
        for ed in ob_surface.data.edges:
            edges_length_sum += (ob_surface.data.vertices[ed.vertices[0]].co - ob_surface.data.vertices[ed.vertices[1]].co).length
        
        if len(ob_surface.data.edges) > 0:
            average_surface_edges_length = edges_length_sum / len(ob_surface.data.edges)
        else:
            average_surface_edges_length = 0.0001
        
        # Make dictionary with all the verts connected to each vert, on the new surface object.
        surface_connected_verts = {}
        for ed in ob_surface.data.edges:
            if not ed.vertices[0] in surface_connected_verts:
                surface_connected_verts[ed.vertices[0]] = []
                
            surface_connected_verts[ed.vertices[0]].append(ed.vertices[1])
            
            
            if not ed.vertices[1] in surface_connected_verts:
                surface_connected_verts[ed.vertices[1]] = []
                
            surface_connected_verts[ed.vertices[1]].append(ed.vertices[0])
            
        
        
        # Duplicate the new surface object, and use shrinkwrap to calculate later the nearest verts to the main object.
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        
        bpy.ops.object.duplicate('INVOKE_REGION_WIN')
        
        final_ob_duplicate = bpy.context.scene.objects.active
        
        bpy.ops.object.modifier_add('INVOKE_REGION_WIN', type='SHRINKWRAP')
        final_ob_duplicate.modifiers["Shrinkwrap"].wrap_method = "NEAREST_VERTEX"
        final_ob_duplicate.modifiers["Shrinkwrap"].target = self.main_object
        
        bpy.ops.object.modifier_apply('INVOKE_REGION_WIN', apply_as='DATA', modifier='Shrinkwrap')
        
        
        # Make list with verts of original mesh as index and coords as value.
        main_object_verts_coords = []
        for v in self.main_object.data.vertices:
            coords = self.main_object.matrix_world * v.co
            
            for c in range(len(coords)): # To avoid problems when taking "-0.00" as a different value as "0.00".
                if "%.3f" % coords[c] == "-0.00":
                    coords[c] = 0
                        
            main_object_verts_coords.append(["%.3f" % coords[0], "%.3f" % coords[1], "%.3f" % coords[2]])
        
        tuple(main_object_verts_coords)
        
        
        # Determine which verts will be merged, snap them to the nearest verts on the original verts, and get them selected.
        crosshatch_verts_to_merge = []
        if self.automatic_join:
            for i in range(len(ob_surface.data.vertices)):
                # Calculate the distance from each of the connected verts to the actual vert, and compare it with the distance they would have if joined. If they don't change much, that vert can be joined.
                merge_actual_vert = True
                if len(surface_connected_verts[i]) < 4:
                    for c_v_idx in surface_connected_verts[i]:
                        points_original = []
                        points_original.append(ob_surface.data.vertices[c_v_idx].co)
                        points_original.append(ob_surface.data.vertices[i].co)
                        
                        points_target = []
                        points_target.append(ob_surface.data.vertices[c_v_idx].co)
                        points_target.append(final_ob_duplicate.data.vertices[i].co)
                        
                        vec_A = points_original[0] - points_original[1]
                        vec_B = points_target[0] - points_target[1]
                        
                        dist_A = (points_original[0] - points_original[1]).length
                        dist_B = (points_target[0] - points_target[1]).length
                        
                        
                        if not (points_original[0] == points_original[1] or points_target[0] == points_target[1]): # If any vector's length is zero.
                            angle = vec_A.angle(vec_B) / math.pi
                        else:
                            angle= 0
                        
                        
                        if dist_B > dist_A * 1.7 * self.join_stretch_factor or dist_B < dist_A / 2 / self.join_stretch_factor or angle >= 0.15 * self.join_stretch_factor: # Set a range of acceptable variation in the connected edges.
                            merge_actual_vert = False
                            break
                else:
                    merge_actual_vert = False
                    
                    
                if merge_actual_vert:
                    coords = final_ob_duplicate.data.vertices[i].co
                    
                    for c in range(len(coords)): # To avoid problems when taking "-0.000" as a different value as "0.00".
                        if "%.3f" % coords[c] == "-0.00":
                            coords[c] = 0
                        
                    comparison_coords = ["%.3f" % coords[0], "%.3f" % coords[1], "%.3f" % coords[2]]
                    
                    
                    if comparison_coords in main_object_verts_coords:
                        main_object_related_vert_idx = main_object_verts_coords.index(comparison_coords) # Get the index of the vert with those coords in the main object.
                        
                        if self.main_object.data.vertices[main_object_related_vert_idx].select == True or self.main_object_selected_verts_count == 0:
                            ob_surface.data.vertices[i].co = final_ob_duplicate.data.vertices[i].co
                            ob_surface.data.vertices[i].select = True
                            crosshatch_verts_to_merge.append(i)
                            
                            # Make sure the vert in the main object is selected, in case it wasn't selected and the "join crosshatch" option is active.
                            self.main_object.data.vertices[main_object_related_vert_idx].select = True
        
        
        
        
        # Delete duplicated object.
        bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.data.objects[final_ob_duplicate.name].select = True
        bpy.context.scene.objects.active = bpy.data.objects[final_ob_duplicate.name]
        bpy.ops.object.delete()
        
        
        # Join crosshatched surface and main object.
        bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.data.objects[ob_surface.name].select = True
        bpy.data.objects[self.main_object.name].select = True
        bpy.context.scene.objects.active = bpy.data.objects[self.main_object.name]
        
        bpy.ops.object.join('INVOKE_REGION_WIN')
        
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        # Perform Remove doubles to merge verts.
        if not (self.automatic_join == False and self.main_object_selected_verts_count == 0):
            bpy.ops.mesh.remove_doubles(mergedist=0.0001)
        
        bpy.ops.mesh.select_all(action='DESELECT')
        
        
        #### If the main object has modifiers, turn their "viewport view status" to what it was before the forced deactivation above.
        if len(self.main_object.modifiers) > 0:
            for m_idx in range(len(self.main_object.modifiers)):
                self.main_object.modifiers[m_idx].show_viewport = self.modifiers_prev_viewport_state[m_idx]
            
            
        
        return{'FINISHED'}
        
        
    
    def rectangular_surface(self):
        #### Selected edges.
        all_selected_edges_idx = []
        all_selected_verts = []
        all_verts_idx = []
        for ed in self.main_object.data.edges:
            if ed.select:
                all_selected_edges_idx.append(ed.index)
                
                # Selected vertices.
                if not ed.vertices[0] in all_selected_verts:
                    all_selected_verts.append(self.main_object.data.vertices[ed.vertices[0]])
                if not ed.vertices[1] in all_selected_verts:
                    all_selected_verts.append(self.main_object.data.vertices[ed.vertices[1]])
                    
                # All verts (both from each edge) to determine later which are at the tips (those not repeated twice).
                all_verts_idx.append(ed.vertices[0])
                all_verts_idx.append(ed.vertices[1])
        
        
        
        #### Identify the tips and "middle-vertex" that separates U from V, if there is one.
        all_chains_tips_idx = []
        for v_idx in all_verts_idx:
            if all_verts_idx.count(v_idx) < 2:
                all_chains_tips_idx.append(v_idx)
        
        
        
        edges_connected_to_tips = []
        for ed in self.main_object.data.edges:
            if (ed.vertices[0] in all_chains_tips_idx or ed.vertices[1] in all_chains_tips_idx) and not (ed.vertices[0] in all_verts_idx and ed.vertices[1] in all_verts_idx):
                edges_connected_to_tips.append(ed)
        
        
        #### Check closed selections.
        single_unselected_verts_and_neighbors = [] # List with groups of three verts, where the first element of the pair is the unselected vert of a closed selection and the other two elements are the selected neighbor verts (it will be useful to determine which selection chain the unselected vert belongs to, and determine the "middle-vertex")
        
        # To identify a "closed" selection (a selection that is a closed chain except for one vertex) find the vertex in common that have the edges connected to tips. If there is a vertex in common, that one is the unselected vert that closes the selection or is a "middle-vertex".
        single_unselected_verts = []
        for ed in edges_connected_to_tips:
            for ed_b in edges_connected_to_tips:
                if ed != ed_b:
                    if ed.vertices[0] == ed_b.vertices[0] and not self.main_object.data.vertices[ed.vertices[0]].select and ed.vertices[0] not in single_unselected_verts:
                        single_unselected_verts_and_neighbors.append([ed.vertices[0], ed.vertices[1], ed_b.vertices[1]]) # The second element is one of the tips of the selected vertices of the closed selection.
                        single_unselected_verts.append(ed.vertices[0])
                        break
                    elif ed.vertices[0] == ed_b.vertices[1] and not self.main_object.data.vertices[ed.vertices[0]].select and ed.vertices[0] not in single_unselected_verts:
                        single_unselected_verts_and_neighbors.append([ed.vertices[0], ed.vertices[1], ed_b.vertices[0]])
                        single_unselected_verts.append(ed.vertices[0])
                        break
                    elif ed.vertices[1] == ed_b.vertices[0] and not self.main_object.data.vertices[ed.vertices[1]].select and ed.vertices[1] not in single_unselected_verts:
                        single_unselected_verts_and_neighbors.append([ed.vertices[1], ed.vertices[0], ed_b.vertices[1]])
                        single_unselected_verts.append(ed.vertices[1])
                        break
                    elif ed.vertices[1] == ed_b.vertices[1] and not self.main_object.data.vertices[ed.vertices[1]].select and ed.vertices[1] not in single_unselected_verts:
                        single_unselected_verts_and_neighbors.append([ed.vertices[1], ed.vertices[0], ed_b.vertices[0]])
                        single_unselected_verts.append(ed.vertices[1])
                        break
        
        
        middle_vertex_idx = None
        tips_to_discard_idx = []
        # Check if there is a "middle-vertex", and get its index.
        for i in range(0, len(single_unselected_verts_and_neighbors)):
            actual_chain_verts = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, single_unselected_verts_and_neighbors[i][1], None, None)
            
            if single_unselected_verts_and_neighbors[i][2] != actual_chain_verts[len(actual_chain_verts) - 1].index:
                middle_vertex_idx = single_unselected_verts_and_neighbors[i][0]
                tips_to_discard_idx.append(single_unselected_verts_and_neighbors[i][1])
                tips_to_discard_idx.append(single_unselected_verts_and_neighbors[i][2])
            
            
        #### List with pairs of verts that belong to the tips of each selection chain (row).
        verts_tips_same_chain_idx = []
        if len(all_chains_tips_idx) >= 2:
            checked_v = []
            for i in range(0, len(all_chains_tips_idx)):
                if all_chains_tips_idx[i] not in checked_v:
                    v_chain = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, all_chains_tips_idx[i], middle_vertex_idx, None)
                    
                    verts_tips_same_chain_idx.append([v_chain[0].index, v_chain[len(v_chain) - 1].index])
                    
                    checked_v.append(v_chain[0].index)
                    checked_v.append(v_chain[len(v_chain) - 1].index)
        
        
        #### Selection tips (vertices).
        verts_tips_parsed_idx = []
        if len(all_chains_tips_idx) >= 2:
            for spec_v_idx in all_chains_tips_idx:
                if (spec_v_idx not in tips_to_discard_idx):
                    verts_tips_parsed_idx.append(spec_v_idx)
        
    
        #### Identify the type of selection made by the user.
        if middle_vertex_idx != None:
            if len(all_chains_tips_idx) == 4 and len(single_unselected_verts_and_neighbors) == 1: # If there are 4 tips (two selection chains), and there is only one single unselected vert (the middle vert).
                selection_type = "TWO_CONNECTED"
            else:
                # The type of the selection was not identified, the script stops.
                self.report({'WARNING'}, "The selection isn't valid.")
                bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
                self.cleanup_on_interruption()
                self.stopping_errors = True
                
                return{'CANCELLED'}
        else:
            if len(all_chains_tips_idx) == 2: # If there are 2 tips
                selection_type = "SINGLE"
            elif len(all_chains_tips_idx) == 4: # If there are 4 tips
                selection_type = "TWO_NOT_CONNECTED"
            elif len(all_chains_tips_idx) == 0:
                if len(self.main_splines.data.splines) > 1:
                    selection_type = "NO_SELECTION"
                else:
                    # If the selection was not identified and there is only one stroke, there's no possibility to build a surface, so the script is interrupted.
                    self.report({'WARNING'}, "The selection isn't valid.")
                    bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
                    self.cleanup_on_interruption()
                    self.stopping_errors = True
                    
                    return{'CANCELLED'}
            else:
                # The type of the selection was not identified, the script stops.
                self.report({'WARNING'}, "The selection isn't valid.")
                
                bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
                self.cleanup_on_interruption()
                
                self.stopping_errors = True
                
                return{'CANCELLED'}
        
        
        
        #### If the selection type is TWO_NOT_CONNECTED and there is only one stroke, stop the script.
        if selection_type == "TWO_NOT_CONNECTED" and len(self.main_splines.data.splines) == 1:
            self.report({'WARNING'}, "At least two strokes are needed when there are two not connected selections.")
            bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
            self.cleanup_on_interruption()
            self.stopping_errors = True
            
            return{'CANCELLED'}
        
        
        
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        
        bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
        bpy.data.objects[self.main_splines.name].select = True
        bpy.context.scene.objects.active = bpy.context.scene.objects[self.main_splines.name]
        
        
        #### Enter editmode for the new curve (converted from grease pencil strokes), to smooth it out.
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        bpy.ops.curve.smooth('INVOKE_REGION_WIN')
        bpy.ops.curve.smooth('INVOKE_REGION_WIN')
        bpy.ops.curve.smooth('INVOKE_REGION_WIN')
        bpy.ops.curve.smooth('INVOKE_REGION_WIN')
        bpy.ops.curve.smooth('INVOKE_REGION_WIN')
        bpy.ops.curve.smooth('INVOKE_REGION_WIN')
        bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
        
        
        self.selection_U_exists = False
        self.selection_U2_exists = False
        self.selection_V_exists = False
        self.selection_V2_exists = False
        
        self.selection_U_is_closed = False
        self.selection_U2_is_closed = False
        self.selection_V_is_closed = False
        self.selection_V2_is_closed = False
        
        #### Define what vertices are at the tips of each selection and are not the middle-vertex.
        if selection_type == "TWO_CONNECTED":
            self.selection_U_exists = True
            self.selection_V_exists = True
            
            closing_vert_U_idx = None
            closing_vert_V_idx = None
            closing_vert_U2_idx = None
            closing_vert_V2_idx = None
            
            # Determine which selection is Selection-U and which is Selection-V.
            points_A = []
            points_B = []
            points_first_stroke_tips = []
            
            points_A.append(self.main_object.matrix_world * self.main_object.data.vertices[verts_tips_parsed_idx[0]].co)
            points_A.append(self.main_object.matrix_world * self.main_object.data.vertices[middle_vertex_idx].co)
            
            points_B.append(self.main_object.matrix_world * self.main_object.data.vertices[verts_tips_parsed_idx[1]].co)
            points_B.append(self.main_object.matrix_world * self.main_object.data.vertices[middle_vertex_idx].co)
            
            points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[0].co)
            points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[len(self.main_splines.data.splines[0].bezier_points) - 1].co)
            
            angle_A = self.orientation_difference(points_A, points_first_stroke_tips)
            angle_B = self.orientation_difference(points_B, points_first_stroke_tips)
            
            if angle_A < angle_B:
                first_vert_U_idx = verts_tips_parsed_idx[0]
                first_vert_V_idx = verts_tips_parsed_idx[1]
            else:
                first_vert_U_idx = verts_tips_parsed_idx[1]
                first_vert_V_idx = verts_tips_parsed_idx[0]
                
        elif selection_type == "SINGLE" or selection_type == "TWO_NOT_CONNECTED":
            first_sketched_point_first_stroke_co = self.main_splines.data.splines[0].bezier_points[0].co
            last_sketched_point_first_stroke_co = self.main_splines.data.splines[0].bezier_points[len(self.main_splines.data.splines[0].bezier_points) - 1].co
            first_sketched_point_last_stroke_co = self.main_splines.data.splines[len(self.main_splines.data.splines) - 1].bezier_points[0].co
            if len(self.main_splines.data.splines) > 1:
                first_sketched_point_second_stroke_co = self.main_splines.data.splines[1].bezier_points[0].co
                last_sketched_point_second_stroke_co = self.main_splines.data.splines[1].bezier_points[len(self.main_splines.data.splines[1].bezier_points) - 1].co
            
            
            single_unselected_neighbors = [] # Only the neighbors of the single unselected verts.
            for verts_neig_idx in single_unselected_verts_and_neighbors:
                single_unselected_neighbors.append(verts_neig_idx[1])
                single_unselected_neighbors.append(verts_neig_idx[2])
            
            
            all_chains_tips_and_middle_vert = []
            for v_idx in all_chains_tips_idx:
                if v_idx not in single_unselected_neighbors:
                    all_chains_tips_and_middle_vert.append(v_idx)
                    
            
            all_chains_tips_and_middle_vert += single_unselected_verts
            
            all_participating_verts = all_chains_tips_and_middle_vert + all_verts_idx
            
            # The tip of the selected vertices nearest to the first point of the first sketched stroke.
            nearest_tip_to_first_st_first_pt_idx, shortest_distance_to_first_stroke = self.shortest_distance(self.main_object, first_sketched_point_first_stroke_co, all_chains_tips_and_middle_vert)
            # If the nearest tip is not from a closed selection, get the opposite tip vertex index.
            if nearest_tip_to_first_st_first_pt_idx not in single_unselected_verts or nearest_tip_to_first_st_first_pt_idx == middle_vertex_idx:
                nearest_tip_to_first_st_first_pt_opposite_idx = self.opposite_tip(nearest_tip_to_first_st_first_pt_idx, verts_tips_same_chain_idx)
            
            # The tip of the selected vertices nearest to the last point of the first sketched stroke.
            nearest_tip_to_first_st_last_pt_idx, temp_dist = self.shortest_distance(self.main_object, last_sketched_point_first_stroke_co, all_chains_tips_and_middle_vert)
            
            # The tip of the selected vertices nearest to the first point of the last sketched stroke.
            nearest_tip_to_last_st_first_pt_idx, shortest_distance_to_last_stroke = self.shortest_distance(self.main_object, first_sketched_point_last_stroke_co, all_chains_tips_and_middle_vert)
            
            if len(self.main_splines.data.splines) > 1:
                # The selected vertex nearest to the first point of the second sketched stroke. (This will be useful to determine the direction of the closed selection V when extruding along strokes)
                nearest_vert_to_second_st_first_pt_idx, temp_dist = self.shortest_distance(self.main_object, first_sketched_point_second_stroke_co, all_verts_idx)
                
                # The selected vertex nearest to the first point of the second sketched stroke. (This will be useful to determine the direction of the closed selection V2 when extruding along strokes)
                nearest_vert_to_second_st_last_pt_idx, temp_dist = self.shortest_distance(self.main_object, last_sketched_point_second_stroke_co, all_verts_idx)
            
            
            
            # Determine if the single selection will be treated as U or as V.
            edges_sum = 0
            for i in all_selected_edges_idx:
                edges_sum += ((self.main_object.matrix_world * self.main_object.data.vertices[self.main_object.data.edges[i].vertices[0]].co) - (self.main_object.matrix_world * self.main_object.data.vertices[self.main_object.data.edges[i].vertices[1]].co)).length
                
            average_edge_length = edges_sum / len(all_selected_edges_idx)
            
            
            # Get shortest distance from the first point of the last stroke to any participating vertex.
            temp_idx, shortest_distance_to_last_stroke = self.shortest_distance(self.main_object, first_sketched_point_last_stroke_co, all_participating_verts)
            
            
            if shortest_distance_to_first_stroke < average_edge_length / 4 and shortest_distance_to_last_stroke < average_edge_length and len(self.main_splines.data.splines) > 1: # If the beginning of the first stroke is near enough, and its orientation difference with the first edge of the nearest selection chain is not too high, interpret things as an "extrude along strokes" instead of "extrude through strokes"
                self.selection_U_exists = False
                self.selection_V_exists = True
                if nearest_tip_to_first_st_first_pt_idx not in single_unselected_verts or nearest_tip_to_first_st_first_pt_idx == middle_vertex_idx: # If the first selection is not closed.
                    self.selection_V_is_closed = False
                    first_neighbor_V_idx = None
                    closing_vert_U_idx = None
                    closing_vert_U2_idx = None
                    closing_vert_V_idx = None
                    closing_vert_V2_idx = None
                    
                    first_vert_V_idx = nearest_tip_to_first_st_first_pt_idx
                    
                    if selection_type == "TWO_NOT_CONNECTED":
                        self.selection_V2_exists = True
                        
                        first_vert_V2_idx = nearest_tip_to_first_st_last_pt_idx
                else:
                    self.selection_V_is_closed = True
                    closing_vert_V_idx = nearest_tip_to_first_st_first_pt_idx
                    
                    # Get the neighbors of the first (unselected) vert of the closed selection U.
                    vert_neighbors = []
                    for verts in single_unselected_verts_and_neighbors:
                        if verts[0] == nearest_tip_to_first_st_first_pt_idx:
                            vert_neighbors.append(verts[1])
                            vert_neighbors.append(verts[2])
                            break
                    
                    verts_V = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, vert_neighbors[0], middle_vertex_idx, None)
                    
                    for i in range(0, len(verts_V)):
                        if verts_V[i].index == nearest_vert_to_second_st_first_pt_idx:
                            if i >= len(verts_V) / 2: # If the vertex nearest to the first point of the second stroke is in the first half of the selected verts.
                                first_vert_V_idx = vert_neighbors[1]
                                break
                            else:
                                first_vert_V_idx = vert_neighbors[0]
                                break
                    
                    
                    
                if selection_type == "TWO_NOT_CONNECTED":
                    self.selection_V2_exists = True
                    
                    if nearest_tip_to_first_st_last_pt_idx not in single_unselected_verts or nearest_tip_to_first_st_last_pt_idx == middle_vertex_idx: # If the second selection is not closed.
                        self.selection_V2_is_closed = False
                        first_neighbor_V2_idx = None
                        closing_vert_V2_idx = None
                        
                        first_vert_V2_idx = nearest_tip_to_first_st_last_pt_idx
                        
                    else:
                        self.selection_V2_is_closed = True
                        closing_vert_V2_idx = nearest_tip_to_first_st_last_pt_idx
                        
                        # Get the neighbors of the first (unselected) vert of the closed selection U.
                        vert_neighbors = []
                        for verts in single_unselected_verts_and_neighbors:
                            if verts[0] == nearest_tip_to_first_st_last_pt_idx:
                                vert_neighbors.append(verts[1])
                                vert_neighbors.append(verts[2])
                                break
                            
                        
                        verts_V2 = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, vert_neighbors[0], middle_vertex_idx, None)
                        
                        for i in range(0, len(verts_V2)):
                            if verts_V2[i].index == nearest_vert_to_second_st_last_pt_idx:
                                if i >= len(verts_V2) / 2: # If the vertex nearest to the first point of the second stroke is in the first half of the selected verts.
                                    first_vert_V2_idx = vert_neighbors[1]
                                    break
                                else:
                                    first_vert_V2_idx = vert_neighbors[0]
                                    break
                        
                else:
                    self.selection_V2_exists = False
                
            else:
                self.selection_U_exists = True
                self.selection_V_exists = False
                if nearest_tip_to_first_st_first_pt_idx not in single_unselected_verts or nearest_tip_to_first_st_first_pt_idx == middle_vertex_idx: # If the first selection is not closed.
                    self.selection_U_is_closed = False
                    first_neighbor_U_idx = None
                    closing_vert_U_idx = None
                    
                    points_tips = []
                    points_tips.append(self.main_object.matrix_world * self.main_object.data.vertices[nearest_tip_to_first_st_first_pt_idx].co)
                    points_tips.append(self.main_object.matrix_world * self.main_object.data.vertices[nearest_tip_to_first_st_first_pt_opposite_idx].co)
                    
                    points_first_stroke_tips = []
                    points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[0].co)
                    points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[len(self.main_splines.data.splines[0].bezier_points) - 1].co)
                    
                    vec_A = points_tips[0] - points_tips[1]
                    vec_B = points_first_stroke_tips[0] - points_first_stroke_tips[1]
                    
                    # Compare the direction of the selection and the first grease pencil stroke to determine which is the "first" vertex of the selection.
                    if vec_A.dot(vec_B) < 0:
                        first_vert_U_idx = nearest_tip_to_first_st_first_pt_opposite_idx
                    else:
                        first_vert_U_idx = nearest_tip_to_first_st_first_pt_idx
                        
                else:
                    self.selection_U_is_closed = True
                    closing_vert_U_idx = nearest_tip_to_first_st_first_pt_idx
                    
                    # Get the neighbors of the first (unselected) vert of the closed selection U.
                    vert_neighbors = []
                    for verts in single_unselected_verts_and_neighbors:
                        if verts[0] == nearest_tip_to_first_st_first_pt_idx:
                            vert_neighbors.append(verts[1])
                            vert_neighbors.append(verts[2])
                            break
                    
                    points_first_and_neighbor = []
                    points_first_and_neighbor.append(self.main_object.matrix_world * self.main_object.data.vertices[nearest_tip_to_first_st_first_pt_idx].co)
                    points_first_and_neighbor.append(self.main_object.matrix_world * self.main_object.data.vertices[vert_neighbors[0]].co)
                    
                    points_first_stroke_tips = []
                    points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[0].co)
                    points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[1].co)
                    
                    vec_A = points_first_and_neighbor[0] - points_first_and_neighbor[1]
                    vec_B = points_first_stroke_tips[0] - points_first_stroke_tips[1]
                    
                    # Compare the direction of the selection and the first grease pencil stroke to determine which is the vertex neighbor to the first vertex (unselected) of the closed selection. This will determine the direction of the closed selection.
                    if vec_A.dot(vec_B) < 0:
                        first_vert_U_idx = vert_neighbors[1]
                    else:
                        first_vert_U_idx = vert_neighbors[0]
                
                
                
                if selection_type == "TWO_NOT_CONNECTED":
                    self.selection_U2_exists = True
                    
                    if nearest_tip_to_last_st_first_pt_idx not in single_unselected_verts or nearest_tip_to_last_st_first_pt_idx == middle_vertex_idx: # If the second selection is not closed.
                        self.selection_U2_is_closed = False
                        first_neighbor_U2_idx = None
                        closing_vert_U2_idx = None
                        
                        first_vert_U2_idx = nearest_tip_to_last_st_first_pt_idx
                        
                    else:
                        self.selection_U2_is_closed = True
                        closing_vert_U2_idx = nearest_tip_to_last_st_first_pt_idx
                        
                        # Get the neighbors of the first (unselected) vert of the closed selection U.
                        vert_neighbors = []
                        for verts in single_unselected_verts_and_neighbors:
                            if verts[0] == nearest_tip_to_last_st_first_pt_idx:
                                vert_neighbors.append(verts[1])
                                vert_neighbors.append(verts[2])
                                break
                        
                        points_first_and_neighbor = []
                        points_first_and_neighbor.append(self.main_object.matrix_world * self.main_object.data.vertices[nearest_tip_to_last_st_first_pt_idx].co)
                        points_first_and_neighbor.append(self.main_object.matrix_world * self.main_object.data.vertices[vert_neighbors[0]].co)
                        
                        points_last_stroke_tips = []
                        points_last_stroke_tips.append(self.main_splines.data.splines[len(self.main_splines.data.splines) - 1].bezier_points[0].co)
                        points_last_stroke_tips.append(self.main_splines.data.splines[len(self.main_splines.data.splines) - 1].bezier_points[1].co)
                        
                        vec_A = points_first_and_neighbor[0] - points_first_and_neighbor[1]
                        vec_B = points_last_stroke_tips[0] - points_last_stroke_tips[1]
                        
                        # Compare the direction of the selection and the last grease pencil stroke to determine which is the vertex neighbor to the first vertex (unselected) of the closed selection. This will determine the direction of the closed selection.
                        if vec_A.dot(vec_B) < 0:
                            first_vert_U2_idx = vert_neighbors[1]
                        else:
                            first_vert_U2_idx = vert_neighbors[0]
                            
                else:
                    self.selection_U2_exists = False
                
        elif selection_type == "NO_SELECTION":
            self.selection_U_exists = False
            self.selection_V_exists = False
        
        
        
        #### Get an ordered list of the vertices of Selection-U.
        verts_ordered_U = []
        if self.selection_U_exists:
            verts_ordered_U = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, first_vert_U_idx, middle_vertex_idx, closing_vert_U_idx)
            verts_ordered_U_indices = [x.index for x in verts_ordered_U]
            
        #### Get an ordered list of the vertices of Selection-U2.
        verts_ordered_U2 = []
        if self.selection_U2_exists:
            verts_ordered_U2 = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, first_vert_U2_idx, middle_vertex_idx, closing_vert_U2_idx)
            verts_ordered_U2_indices = [x.index for x in verts_ordered_U2]
        
        #### Get an ordered list of the vertices of Selection-V.
        verts_ordered_V = []
        if self.selection_V_exists:
            verts_ordered_V = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, first_vert_V_idx, middle_vertex_idx, closing_vert_V_idx)
            verts_ordered_V_indices = [x.index for x in verts_ordered_V]
        
        #### Get an ordered list of the vertices of Selection-V2.
        verts_ordered_V2 = []
        if self.selection_V2_exists:
            verts_ordered_V2 = self.get_ordered_verts(self.main_object, all_selected_edges_idx, all_verts_idx, first_vert_V2_idx, middle_vertex_idx, closing_vert_V2_idx)
            verts_ordered_V2_indices = [x.index for x in verts_ordered_V2]
        
        
        
        #### Check if when there are two-not-connected selections both have the same number of verts. If not terminate the script.
        if ((self.selection_U2_exists and len(verts_ordered_U) != len(verts_ordered_U2)) or (self.selection_V2_exists and len(verts_ordered_V) != len(verts_ordered_V2))):
            # Display a warning.
Loading
Loading full blame...