Exemplo n.º 1
0
    def update(self):
        for name in ['vertices1', 'vertices2', 'matrix1', 'matrix2']:
            if name not in self.inputs:
                return

        if self.inputs['vertices1'].links and self.inputs['vertices2'].links:
            prop1_ = SvGetSocketAnyType(self, self.inputs['vertices1'])
            prop1 = Vector_generate(prop1_)
            prop2_ = SvGetSocketAnyType(self, self.inputs['vertices2'])
            prop2 = Vector_generate(prop2_)

        elif self.inputs['matrix1'].links and self.inputs['matrix2'].links:
            propa = SvGetSocketAnyType(self, self.inputs['matrix1'])
            prop1 = Matrix_location(Matrix_generate(propa))
            propb = SvGetSocketAnyType(self, self.inputs['matrix2'])
            prop2 = Matrix_location(Matrix_generate(propb))
        else:
            prop1, prop2 = [], []

        if prop1 and prop2:
            if self.outputs['distances'].links:
                #print ('distances input', str(prop1), str(prop2))
                if self.Cross_dist:
                    output = self.calcM(prop1, prop2)
                else:
                    output = self.calcV(prop1, prop2)
                SvSetSocketAnyType(self, 'distances', output)

                #print ('distances out' , str(output))
        else:
            SvSetSocketAnyType(self, 'distances', [])
Exemplo n.º 2
0
    def update(self):
        # inputs
        A = []
        B = []
        factor = []  # 0 is valid value so I use [] as placeholder

        if 'A' in self.inputs and self.inputs['A'].links and \
           type(self.inputs['A'].links[0].from_socket) == MatrixSocket:

            A = Matrix_generate(SvGetSocketAnyType(self, self.inputs['A']))
        if not A:
            A = [Matrix.Identity(4)]

        if 'B' in self.inputs and self.inputs['B'].links and \
           type(self.inputs['B'].links[0].from_socket) == MatrixSocket:

            B = Matrix_generate(SvGetSocketAnyType(self, self.inputs['B']))
        if not B:
            B = [Matrix.Identity(4)]

        if 'Factor' in self.inputs and self.inputs['Factor'].links and \
           type(self.inputs['Factor'].links[0].from_socket) == StringsSocket:

            factor = SvGetSocketAnyType(self, self.inputs['Factor'])

        if not factor:
            factor = [[self.factor_]]

        if 'C' in self.outputs and self.outputs['C'].links:

            matrixes_ = []
            # match inputs, first matrix A and B using fullList
            # then extend the factor list if necessary,
            # A and B should control length of list, not interpolation lists
            max_l = max(len(A), len(B))
            fullList(A, max_l)
            fullList(B, max_l)
            if len(factor) < max_l:
                fullList(factor, max_l)
            for i in range(max_l):
                for k in range(len(factor[i])):
                    matrixes_.append(A[i].lerp(B[i], factor[i][k]))

            if not matrixes_:
                return

            matrixes = Matrix_listing(matrixes_)
            SvSetSocketAnyType(self, 'C', matrixes)
Exemplo n.º 3
0
    def update(self):
        # inputs
        if 'Vectors' in self.outputs and len(
                self.outputs['Vectors'].links) > 0:
            if self.inputs['Vectors'].links and \
                    type(self.inputs['Vectors'].links[0].from_socket) == VerticesSocket \
                    and self.inputs['Matrixes'] and \
                    type(self.inputs['Matrixes'].links[0].from_socket) == MatrixSocket:

                vecs_ = SvGetSocketAnyType(self, self.inputs['Vectors'])

                vecs = Vector_generate(vecs_)
                #print (vecs)

                mats_ = dataCorrect(
                    SvGetSocketAnyType(self, self.inputs['Matrixes']))
                mats = Matrix_generate(mats_)
            else:
                vecs = [[]]
                mats = [Matrix()]

            # outputs

            vectors_ = self.vecscorrect(vecs, mats)
            vectors = Vector_degenerate(vectors_)
            SvSetSocketAnyType(self, 'Vectors', vectors)
Exemplo n.º 4
0
    def update(self):
        if 'Matrix' in self.inputs and self.inputs['Matrix'].links:
            matrixes_ = SvGetSocketAnyType(self, self.inputs['Matrix'])
            matrixes = Matrix_generate(matrixes_)

            if 'Location' in self.outputs and self.outputs['Location'].links:
                locs = Matrix_location(matrixes, list=True)
                SvSetSocketAnyType(self, 'Location', locs)

            if 'Scale' in self.outputs and self.outputs['Scale'].links:
                locs = Matrix_scale(matrixes, list=True)
                SvSetSocketAnyType(self, 'Scale', locs)

            if ('Rotation' in self.outputs and self.outputs['Rotation'].links) \
               or ('Angle' in self.outputs and self.outputs['Angle'].links):

                locs = Matrix_rotation(matrixes, list=True)
                rots = []
                angles = []
                for lists in locs:
                    rots.append([pair[0] for pair in lists])
                    for pair in lists:
                        angles.append(degrees(pair[1]))
                SvSetSocketAnyType(self, 'Rotation', rots)
                SvSetSocketAnyType(self, 'Angle', [angles])
        else:
            matrixes = [[]]
Exemplo n.º 5
0
    def makeobjects(self, vers, edg_pol, mats):
        # inception
        # fht = предохранитель от перебора рёбер и полигонов.
        fht = []
        if len(edg_pol[0][0]) == 2:
            pols = []
            for edgs in edg_pol:
                maxi = max(max(a) for a in edgs)
                fht.append(maxi)
                #print (maxi)
        elif len(edg_pol[0][0]) > 2:
            edgs = []
            for pols in edg_pol:
                maxi = max(max(a) for a in pols)
                fht.append(maxi)
                #print (maxi)
        #print (fht)
        vertices = Vector_generate(vers)
        matrixes = Matrix_generate(mats)
        #print('mats' + str(matrixes))
        objects = {}
        fhtagn = []
        for u, f in enumerate(fht):
            fhtagn.append(min(len(vertices[u]), fht[u]))
        #lenmesh = len(vertices) - 1
        #print ('запекание вершин ', vertices, " матрицы запекашка ", matrixes, " полиглоты ", edg_pol)
        #print (matrixes)
        for i, m in enumerate(matrixes):
            k = i
            lenver = len(vertices) - 1
            if i > lenver:
                v = vertices[-1]
                k = lenver
            else:
                v = vertices[k]
            #print (fhtagn, len(v)-1)
            if (len(v)-1) < fhtagn[k]:
                continue
            # возможно такая сложность не нужна, но пусть лежит тут. Удалять лишние точки не обязательно.
            elif fhtagn[k] < (len(v)-1):
                nonneed = (len(v)-1) - fhtagn[k]
                for q in range(nonneed):
                    v.pop((fhtagn[k]+1))
                #print (fhtagn[k], (len(v)-1))

            e = edg_pol[k] if edgs else []
            p = edg_pol[k] if pols else []

            objects[str(i)] = self.makemesh(i, v, e, p, m)
        for ite in objects.values():
            me = ite[1]
            ob = ite[0]
            calcedg = True
            if edgs:
                calcedg = False
            me.update(calc_edges=calcedg)
            bpy.context.scene.objects.link(ob)
Exemplo n.º 6
0
 def get_data(name, fallback=[]):
     TypeSocket = get_socket_type(name)
     if has_good_link(name, TypeSocket):
         d = dataCorrect(SvGetSocketAnyType(node, inputs[name]))
         if name == 'matrix':
             d = Matrix_generate(d) if d else []
         elif name == 'vertices':
             d = Vector_generate(d) if d else []
         return d
     return fallback
Exemplo n.º 7
0
    def update(self):
        # inputs
        if 'Matrix' in self.outputs and self.outputs['Matrix'].links:
            if self.inputs['Original'].links and \
               type(self.inputs['Original'].links[0].from_socket) == MatrixSocket:

                orig_ = SvGetSocketAnyType(self, self.inputs['Original'])
                orig = Matrix_generate(orig_)
            else:
                return

            if 'Location' in self.inputs and self.inputs['Location'].links and \
               type(self.inputs['Location'].links[0].from_socket) == VerticesSocket:

                loc_ = SvGetSocketAnyType(self, self.inputs['Location'])
                loc = Vector_generate(loc_)
            else:
                loc = [[]]

            if 'Scale' in self.inputs and self.inputs['Scale'].links and \
               type(self.inputs['Scale'].links[0].from_socket) == VerticesSocket:

                scale_ = SvGetSocketAnyType(self, self.inputs['Scale'])
                scale = Vector_generate(scale_)
            else:
                scale = [[]]

            if 'Rotation' in self.inputs and self.inputs['Rotation'].links and \
               type(self.inputs['Rotation'].links[0].from_socket) == VerticesSocket:

                rot_ = SvGetSocketAnyType(self, self.inputs['Rotation'])
                rot = Vector_generate(rot_)
                #print ('matrix_def', str(rot_))
            else:
                rot = [[]]

            rotA = [[]]
            angle = [[0.0]]
            if 'Angle' in self.inputs and self.inputs['Angle'].links:

                if type(self.inputs['Angle'].links[0].from_socket
                        ) == StringsSocket:
                    angle = SvGetSocketAnyType(self, self.inputs['Angle'])

                elif type(self.inputs['Angle'].links[0].from_socket
                          ) == VerticesSocket:
                    rotA_ = SvGetSocketAnyType(self, self.inputs['Angle'])
                    rotA = Vector_generate(rotA_)

            # outputs
            #print(loc)
            matrixes_ = matrixdef(orig, loc, scale, rot, angle, rotA)
            matrixes = Matrix_listing(matrixes_)
            SvSetSocketAnyType(self, 'Matrix', matrixes)
Exemplo n.º 8
0
    def makeobjects(self, vers, edg_pol, mats):
        try:
            num_keys = len(edg_pol[0][0])
        except:
            num_keys = 0

        vertices = Vector_generate(vers)
        matrixes = Matrix_generate(mats)
        edgs, pols, max_vert_index, fht = [], [], [], []

        if num_keys >= 2:
            for k in edg_pol:
                maxi = max(max(a) for a in k)
                fht.append(maxi)

        for u, f in enumerate(fht):
            max_vert_index.append(min(len(vertices[u]), fht[u]))

        objects = {}
        for i, m in enumerate(matrixes):
            k = i
            lenver = len(vertices) - 1
            if i > lenver:
                v = vertices[-1]
                k = lenver
            else:
                v = vertices[k]

            if max_vert_index:
                if (len(v) - 1) < max_vert_index[k]:
                    continue

                elif max_vert_index[k] < (len(v) - 1):
                    nonneed = (len(v) - 1) - max_vert_index[k]
                    for q in range(nonneed):
                        v.pop((max_vert_index[k] + 1))

            e, p = [], []
            if num_keys == 2:
                e = edg_pol[k]
            elif num_keys > 2:
                p = edg_pol[k]

            objects[str(i)] = self.makemesh(i, v, e, p, m)

        for ob, me in objects.values():
            calcedg = False if (num_keys == 2) else True
            me.update(calc_edges=calcedg)
            bpy.context.scene.objects.link(ob)
Exemplo n.º 9
0
    def input_mode(self):
        inputs = self.inputs
        if (len(inputs) == 0) or (not inputs[0].links):
            print('has no link!')
            return

        # then morph default socket type to whatever we plug into it.
        from_socket = inputs[0].links[0].from_socket
        incoming_socket_type = type(from_socket)
        stype = {
            VerticesSocket: 'VerticesSocket',
            MatrixSocket: 'MatrixSocket',
            StringsSocket: 'StringsSocket'
        }.get(incoming_socket_type, None)

        # print(incoming_socket_type, from_socket, stype)

        if not stype:
            print('unidentified flying input')
            return

        # if the current self.input socket is different to incoming
        if not (stype == self.inputs[0].bl_idname):
            self.morph_input_socket_type(stype)

        # only one nesting level supported, for types other than matrix.
        # else x gets complicated. x is complex already, this forces
        # simplicity
        tvar = None
        if stype == 'MatrixSocket':
            prop = SvGetSocketAnyType(self, inputs[0])
            tvar = Matrix_generate(prop)[0]
            # print('---repr-\n', repr(tvar))
        else:
            tvar = SvGetSocketAnyType(self, inputs[0])[0][0]

        # input can still be empty or []
        if not tvar:
            return

        if self.eval_str.endswith("with x"):
            process_input_dofunction(self, tvar)
        else:
            process_input_to_bpy(self, tvar, stype)
Exemplo n.º 10
0
    def update(self):
        if not "Matrix" in self.inputs:
            return
        # startup safety net
        try:
            l = bpy.data.node_groups[self.id_data.name]
        except:
            print(self.name, "cannot run during startup, press update.")
            return
        empty = self.find_empty()
        if not empty:
            empty = self.create_empty()
            print("created new empty")

        if self.inputs['Matrix'].links:
            mats = SvGetSocketAnyType(self, self.inputs['Matrix'])
            mat = Matrix_generate(mats)[0]
        else:
            mat = Matrix()
        self.label = empty.name
        empty.matrix_world = mat
Exemplo n.º 11
0
    def update(self):
        # inputs
        if 'Vectors' in self.outputs and self.outputs['Vectors'].links:
            if not ('Vectors' in self.inputs and self.inputs['Vectors'].links):
                return
            if not ('Matrixes' in self.inputs
                    and self.inputs['Matrixes'].links):
                return
            if type(self.inputs['Vectors'].links[0].from_socket) == VerticesSocket and \
               type(self.inputs['Matrixes'].links[0].from_socket) == MatrixSocket:

                vecs_ = SvGetSocketAnyType(self, self.inputs['Vectors'])
                vecs = Vector_generate(vecs_)

                mats_ = SvGetSocketAnyType(self, self.inputs['Matrixes'])
                mats = Matrix_generate(mats_)
            else:
                vecs = [[]]
                mats = [Matrix()]

            # outputs
            vectors_ = self.vecscorrect(vecs, mats)
            vectors = Vector_degenerate(vectors_)
            SvSetSocketAnyType(self, 'Vectors', vectors)
Exemplo n.º 12
0
def draw_callback_view(handle, sl1, sl2, sl3, vs, colo, tran, shade):
    context = bpy.context
    from bgl import glEnable, glDisable, glColor3f, glVertex3f, glPointSize, \
                glLineWidth, glBegin, glEnd, glLineStipple, GL_POINTS, \
                GL_LINE_STRIP, GL_LINES, GL_LINE, GL_LINE_STIPPLE, GL_POLYGON, \
                GL_POLYGON_STIPPLE, GL_POLYGON_SMOOTH, glPolygonStipple, \
                GL_TRIANGLES, GL_QUADS, glColor4f
    # define globals, separate edgs from pols
    if tran:
        polyholy = GL_POLYGON_STIPPLE
        edgeholy = GL_LINE_STIPPLE
        edgeline = GL_LINE_STRIP
    else:
        polyholy = GL_POLYGON
        edgeholy = GL_LINE
        edgeline = GL_LINES

    if sl1:
        data_vector = Vector_generate(sl1)
        verlen = len(data_vector) - 1
        verlen_every = [len(d) - 1 for d in data_vector]
    else:
        data_vector = []
        verlen = 0

    if sl2:
        if sl2[0]:
            if len(sl2[0][0]) == 2:
                data_edges = sl2
                data_polygons = []
            elif len(sl2[0][0]) > 2:
                data_polygons = sl2
                data_edges = []
        else:
            data_polygons = []
            data_edges = []

    else:
        data_edges, data_polygons = [], []

    if sl3:
        data_matrix = Matrix_generate(sl3)
    else:
        data_matrix = [Matrix() for i in range(verlen + 1)]

    coloa = colo[0]
    colob = colo[1]
    coloc = colo[2]

    if (data_vector, data_polygons, data_matrix, data_edges) == (0, 0, 0, 0):
        callback_disable(handle)
    #print ('вход', sl1, sl2, sl3)
    #print ('преобраз', data_vector)

    # draw_matrix vars
    zero = Vector((0.0, 0.0, 0.0))
    x_p = Vector((0.5, 0.0, 0.0))
    x_n = Vector((-0.5, 0.0, 0.0))
    y_p = Vector((0.0, 0.5, 0.0))
    y_n = Vector((0.0, -0.5, 0.0))
    z_p = Vector((0.0, 0.0, 0.5))
    z_n = Vector((0.0, 0.0, -0.5))
    bb = [Vector() for i in range(24)]

    def draw_matrix(mat):
        zero_tx = mat * zero

        glLineWidth(2.0)
        # x
        glColor3f(1.0, 0.2, 0.2)
        glBegin(GL_LINES)
        glVertex3f(*(zero_tx))
        glVertex3f(*(mat * x_p))
        glEnd()

        glColor3f(0.6, 0.0, 0.0)
        glBegin(GL_LINES)
        glVertex3f(*(zero_tx))
        glVertex3f(*(mat * x_n))
        glEnd()

        # y
        glColor3f(0.2, 1.0, 0.2)
        glBegin(GL_LINES)
        glVertex3f(*(zero_tx))
        glVertex3f(*(mat * y_p))
        glEnd()

        glColor3f(0.0, 0.6, 0.0)
        glBegin(GL_LINES)
        glVertex3f(*(zero_tx))
        glVertex3f(*(mat * y_n))
        glEnd()

        # z
        glColor3f(0.2, 0.2, 1.0)
        glBegin(GL_LINES)
        glVertex3f(*(zero_tx))
        glVertex3f(*(mat * z_p))
        glEnd()

        glColor3f(0.0, 0.0, 0.6)
        glBegin(GL_LINES)
        glVertex3f(*(zero_tx))
        glVertex3f(*(mat * z_n))
        glEnd()

        # bounding box vertices
        i = 0
        glColor3f(1.0, 1.0, 1.0)
        series1 = (-0.5, -0.3, -0.1, 0.1, 0.3, 0.5)
        series2 = (-0.5, 0.5)
        z = 0
        for x in series1:
            for y in series2:
                bb[i][:] = x, y, z
                bb[i] = mat * bb[i]
                i += 1
        for y in series1:
            for x in series2:
                bb[i][:] = x, y, z
                bb[i] = mat * bb[i]
                i += 1

        # bounding box drawing
        glLineWidth(1.0)
        glLineStipple(1, 0xAAAA)
        glEnable(GL_LINE_STIPPLE)

        for i in range(0, 24, 2):
            glBegin(GL_LINE_STRIP)
            glVertex3f(*bb[i])
            glVertex3f(*bb[i + 1])
            glEnd()

    # MAYBE WE SHOULD CONNECT ITERATION FOR ALL PROCESS TO DECREASE
    # TIME?
    ########
    # points
    if vs:
        if data_vector:
            glPointSize(3.0)
            glColor3f(0.8, 0.9, 1.0)

            for i, matrix in enumerate(data_matrix):
                glBegin(GL_POINTS)
                k = i
                if i > verlen:
                    k = verlen
                for vert in data_vector[k]:
                    vec_corrected = data_matrix[i] * vert
                    glVertex3f(*vec_corrected)
                    #print ('рисовальня', matrix, vec_corrected)
                glEnd()
                glPointSize(3.0)

    #######
    # lines
    if data_edges and data_vector:
        glColor3f(coloa, colob, coloc)
        glLineWidth(1.0)
        glEnable(edgeholy)

        for i, matrix in enumerate(data_matrix):  # object
            k = i
            if i > verlen:  # filter to share objects
                k = verlen
            for line in data_edges[k]:  # line
                if max(line) > verlen_every[k]:
                    line = data_edges[k][-1]
                glBegin(edgeline)
                for point in line:  # point
                    vec_corrected = data_matrix[i] * data_vector[k][int(point)]
                    glVertex3f(*vec_corrected)
                glEnd()
                glPointSize(1.75)
                glLineWidth(1.0)
        glDisable(edgeholy)

    #######
    # polygons
    vectorlight = Vector((-0.66, -0.66, -0.66))
    if data_polygons and data_vector:
        glLineWidth(1.0)
        glEnable(polyholy)

        for i, matrix in enumerate(data_matrix):  # object
            k = i
            if i > verlen:
                k = verlen
            oblen = len(data_polygons[k])
            for j, pol in enumerate(data_polygons[k]):
                if max(pol) > verlen_every[k]:
                    pol = data_edges[k][-1]
                    j = len(data_edges[k]) - 1
                if shade:
                    normal_no_ = mathutils.geometry.normal(
                        data_vector[k][pol[0]], data_vector[k][pol[1]],
                        data_vector[k][pol[2]])
                    normal_no = (normal_no_.angle(vectorlight, 0)) / math.pi
                    randa = (normal_no * coloa) - 0.1
                    randb = (normal_no * colob) - 0.1
                    randc = (normal_no * coloc) - 0.1
                else:
                    randa = ((j / oblen) + coloa) / 2.5
                    randb = ((j / oblen) + colob) / 2.5
                    randc = ((j / oblen) + coloc) / 2.5
                if len(pol) > 4:
                    glBegin(GL_TRIANGLES)
                    glColor4f(randa + 0.2, randb + 0.2, randc + 0.2, 0.5)
                    #glColor3f(randa+0.2, randb+0.2, randc+0.2)
                    v = [data_vector[k][i] for i in pol]
                    tess_poly = mathutils.geometry.tessellate_polygon([v])
                    for a, b, c in tess_poly:
                        glVertex3f(*(data_matrix[i] * v[a]))
                        glVertex3f(*(data_matrix[i] * v[b]))
                        glVertex3f(*(data_matrix[i] * v[c]))
                elif len(pol) == 4:
                    glBegin(GL_POLYGON)
                    glColor3f(randa + 0.2, randb + 0.2, randc + 0.2)
                    for point in pol:
                        vec_corrected = data_matrix[i] * data_vector[k][int(
                            point)]
                        glVertex3f(*vec_corrected)
                else:
                    glBegin(GL_TRIANGLES)
                    glColor3f(randa + 0.2, randb + 0.2, randc + 0.2)
                    for point in pol:
                        vec_corrected = data_matrix[i] * data_vector[k][int(
                            point)]
                        glVertex3f(*vec_corrected)
                glEnd()
                glPointSize(1.75)
                glLineWidth(1.0)
        glDisable(polyholy)

    # for future bezier drawing - to remake
    #if data_edges and data_vector and bezier:
    # here 3 lines that i must understand
    #from bpy_extras.view3d_utils import location_3d_to_region_2d
    #region = context.region
    #region_data = context.region_data

    #glEnable(GL_BLEND)
    #glColor4f(1, 0, 0, 0.5)
    #glLineWidth(1.0)
    #glBegin(GL_LINE_STRIP)
    #for i in range(current_frame):
    #glVertex2f(*location_3d_to_region_2d(region, region_data, (math.sin(i / 10), 0, i / 10)).to_tuple())
    #glEnd()
    #glDisable(GL_BLEND)

    #######
    # matrix
    if data_matrix and not data_vector:
        for mat in data_matrix:
            draw_matrix(mat)
Exemplo n.º 13
0
    def update(self):

        if 'Vertices' in self.inputs and self.inputs['Vertices'].links:
            verts = SvGetSocketAnyType(self, self.inputs['Vertices'])

            if 'PolyEdge' in self.inputs and self.inputs['PolyEdge'].links:
                poly_edge = SvGetSocketAnyType(self, self.inputs['PolyEdge'])
                polyIn = True
            else:
                polyIn = False
                poly_edge = repeat_last([[]])

            verts_out = []
            poly_edge_out = []
            item_order = []

            polyOutput = bool(polyIn and 'PolyEdge' in self.outputs
                              and self.outputs['PolyEdge'].links)
            orderOutput = bool('Item order' in self.outputs
                               and self.outputs['Item order'].links)
            vertOutput = bool('Vertices' in self.outputs
                              and self.outputs['Vertices'].links)

            if not any((vertOutput, orderOutput, polyOutput)):
                return

            if self.mode == 'XYZ':
                # should be user settable
                op_order = [(0, False), (1, False), (2, False)]

                for v, p in zip(verts, poly_edge):
                    s_v = ((e[0], e[1], e[2], i) for i, e in enumerate(v))

                    for item_index, rev in op_order:
                        s_v = sorted(s_v,
                                     key=itemgetter(item_index),
                                     reverse=rev)

                    verts_out.append([v[:3] for v in s_v])

                    if polyOutput:
                        v_index = {item[-1]: j for j, item in enumerate(s_v)}
                        poly_edge_out.append(
                            [list(map(lambda n: v_index[n], pe)) for pe in p])
                    if orderOutput:
                        item_order.append([i[-1] for i in s_v])

            if self.mode == 'DIST':
                if 'Base Point' in self.inputs and self.inputs[
                        'Base Point'].links:
                    base_points = SvGetSocketAnyType(self,
                                                     self.inputs['Base Point'])
                    bp_iter = repeat_last(base_points[0])
                else:
                    bp = [(0, 0, 0)]
                    bp_iter = repeat_last(bp)

                for v, p, v_base in zip(verts, poly_edge, bp_iter):
                    s_v = sorted(((v_c, i) for i, v_c in enumerate(v)),
                                 key=lambda v: distK(v[0], v_base))
                    verts_out.append([vert[0] for vert in s_v])

                    if polyOutput:
                        v_index = {item[-1]: j for j, item in enumerate(s_v)}
                        poly_edge_out.append(
                            [list(map(lambda n: v_index[n], pe)) for pe in p])
                    if orderOutput:
                        item_order.append([i[-1] for i in s_v])

            if self.mode == 'AXIS':
                if 'Mat' in self.inputs and self.inputs['Mat'].links:
                    mat = Matrix_generate(
                        SvGetSocketAnyType(self, self.inputs['Mat']))
                else:
                    mat = [Matrix.Identity(4)]
                mat_iter = repeat_last(mat)

                def f(axis, q):
                    if axis.dot(q.axis) > 0:
                        return q.angle
                    else:
                        return -q.angle

                for v, p, m in zip(Vector_generate(verts), poly_edge,
                                   mat_iter):
                    axis = m * Vector((0, 0, 1))
                    axis_norm = m * Vector((1, 0, 0))
                    base_point = m * Vector((0, 0, 0))
                    intersect_d = [
                        intersect_point_line(v_c, base_point, axis)
                        for v_c in v
                    ]
                    rotate_d = [
                        f(axis, (axis_norm + v_l[0]).rotation_difference(v_c))
                        for v_c, v_l in zip(v, intersect_d)
                    ]
                    s_v = (
                        (data[0][1], data[1], i)
                        for i, data in enumerate(zip(intersect_d, rotate_d)))
                    s_v = sorted(s_v, key=itemgetter(0, 1))

                    verts_out.append([v[i[-1]].to_tuple() for i in s_v])

                    if polyOutput:
                        v_index = {item[-1]: j for j, item in enumerate(s_v)}
                        poly_edge_out.append(
                            [list(map(lambda n: v_index[n], pe)) for pe in p])
                    if orderOutput:
                        item_order.append([i[-1] for i in s_v])

            if self.mode == 'USER':
                if 'Index Data' in self.inputs and self.inputs[
                        'Index Data'].links:
                    index = SvGetSocketAnyType(self, self.inputs['Index Data'])
                else:
                    return

                for v, p, i in zip(verts, poly_edge, index):

                    s_v = sorted([(data[0], data[1], i)
                                  for i, data in enumerate(zip(i, v))],
                                 key=itemgetter(0))

                    verts_out.append([obj[1] for obj in s_v])

                    if polyOutput:
                        v_index = {item[-1]: j for j, item in enumerate(s_v)}
                        poly_edge_out.append([[v_index[k] for k in pe]
                                              for pe in p])
                    if orderOutput:
                        item_order.append([i[-1] for i in s_v])

            if vertOutput:
                SvSetSocketAnyType(self, 'Vertices', verts_out)
            if polyOutput:
                SvSetSocketAnyType(self, 'PolyEdge', poly_edge_out)
            if orderOutput:
                SvSetSocketAnyType(self, 'Item order', item_order)
Exemplo n.º 14
0
def draw_callback_view(n_id, cached_view, options):
    def Vector_generate2(prop):
        # try:
        #     return [[Vector(v[:3]) for v in obj] for obj in prop]
        # except ValueEror:
        #     return []
        return [[Vector(v[:3]) for v in obj] for obj in prop]

    # context = bpy.context
    if options["timings"]:
        start = time.perf_counter()

    if options['draw_list'] == 0:

        sl1 = cached_view[n_id + 'v']
        sl2 = cached_view[n_id + 'ep']
        sl3 = cached_view[n_id + 'm']

        if sl1:
            data_vector = Vector_generate2(sl1)
            verlen = len(data_vector) - 1
        else:
            if not sl3:
                # end early: no matrix and no vertices
                callback_disable(n_id)
                return

            # display matrix repr only.
            data_vector = []
            verlen = 0

        options['verlen'] = verlen
        data_polygons = []
        data_edges = []

        if sl2 and sl2[0]:
            if isinstance(sl2[0], int):
                callback_disable(n_id)
                return

            len_sl2 = len(sl2[0][0])
            if len_sl2 == 2:
                data_edges = sl2
            elif len_sl2 > 2:
                data_polygons = sl2

        if sl3:
            data_matrix = Matrix_generate(sl3)
        else:
            data_matrix = [Matrix() for i in range(verlen + 1)]

        if (data_vector, data_polygons, data_matrix, data_edges) == (0, 0, 0,
                                                                     0):
            callback_disable(n_id)
            return

        the_display_list = glGenLists(1)
        glNewList(the_display_list, GL_COMPILE)
        draw_geometry(n_id, options, data_vector, data_polygons, data_matrix,
                      data_edges)
        glEndList()

        options['genlist'] = the_display_list

    elif options['draw_list'] == 1:
        the_display_list = options['genlist']

    glCallList(the_display_list)
    glFlush()

    # restore to system state
    glLineWidth(1)

    if options["timings"]:
        stop = time.perf_counter()
        print("callback drawn in {:4f}".format(stop - start))

    # has drawn once with success.
    options['draw_list'] = 1
Exemplo n.º 15
0
def draw_callback_px(n_id, draw_verts, draw_edges, draw_faces, draw_matrix, draw_bg, settings, text):
    context = bpy.context

    # ensure data or empty lists.
    data_vector = Vector_generate(draw_verts) if draw_verts else []
    data_edges = draw_edges
    data_faces = draw_faces
    data_matrix = Matrix_generate(draw_matrix) if draw_matrix else []
    data_text = text

    if (data_vector, data_matrix) == (0, 0):
    #    callback_disable(n_id)
    #   not sure that it is safe to disable the callback in callback
    #   just return instead.
        return

    region = context.region
    region3d = context.space_data.region_3d

    vert_idx_color = settings['numid_verts_col']
    edge_idx_color = settings['numid_edges_col']
    face_idx_color = settings['numid_faces_col']
    vert_bg_color = settings['bg_verts_col']
    edge_bg_color = settings['bg_edges_col']
    face_bg_color = settings['bg_faces_col']
    display_vert_index = settings['display_vert_index']
    display_edge_index = settings['display_edge_index']
    display_face_index = settings['display_face_index']

    font_id = 0
    text_height = 13
    blf.size(font_id, text_height, 72)  # should check prefs.dpi

    region_mid_width = region.width / 2.0
    region_mid_height = region.height / 2.0

    # vars for projection
    perspective_matrix = region3d.perspective_matrix.copy()

    def draw_index(rgb, rgb2, index, vec, text=''):

        vec_4d = perspective_matrix * vec.to_4d()
        if vec_4d.w <= 0.0:
            return

        x = region_mid_width + region_mid_width * (vec_4d.x / vec_4d.w)
        y = region_mid_height + region_mid_height * (vec_4d.y / vec_4d.w)
        if text:
            index = str(text[0])
        else:
            index = str(index)

        if draw_bg:
            polyline = get_points(index)

            ''' draw polygon '''
            bgl.glColor4f(*rgb2)
            bgl.glBegin(bgl.GL_POLYGON)
            for pointx, pointy in polyline:
                bgl.glVertex2f(pointx+x, pointy+y)
            bgl.glEnd()

        ''' draw text '''
        txt_width, txt_height = blf.dimensions(0, index)
        bgl.glColor4f(*rgb)
        blf.position(0, x - (txt_width / 2), y - (txt_height / 2), 0)
        blf.draw(0, index)

    ########
    # points
    def calc_median(vlist):
        a = Vector((0, 0, 0))
        for v in vlist:
            a += v
        return a / len(vlist)

    for obj_index, verts in enumerate(data_vector):
        final_verts = verts
        if data_text:
            text_obj = data_text[obj_index]
        else:
            text_obj = ''

        # quicklt apply matrix if necessary
        if draw_matrix:
            matrix = data_matrix[obj_index]
            final_verts = [matrix * v for v in verts]

        if display_vert_index:
            for idx, v in enumerate(final_verts):
                if text_obj:
                    draw_index(vert_idx_color, vert_bg_color, idx, v, text_obj[idx])
                else:
                    draw_index(vert_idx_color, vert_bg_color, idx, v)

        if data_edges and display_edge_index:
            for edge_index, (idx1, idx2) in enumerate(data_edges[obj_index]):
                
                v1 = Vector(final_verts[idx1])
                v2 = Vector(final_verts[idx2])
                loc = v1 + ((v2 - v1) / 2)
                if text_obj:
                    draw_index(edge_idx_color, edge_bg_color, edge_index, loc, text_obj[edge_index])
                else:
                    draw_index(edge_idx_color, edge_bg_color, edge_index, loc)

        if data_faces and display_face_index:
            for face_index, f in enumerate(data_faces[obj_index]):
                verts = [Vector(final_verts[idx]) for idx in f]
                median = calc_median(verts)
                if text_obj:
                    draw_index(face_idx_color, face_bg_color, face_index, median, text_obj[face_index])
                else:
                    draw_index(face_idx_color, face_bg_color, face_index, median)
Exemplo n.º 16
0
    def makeobjects(self, vers, edg_pol, mats):
        # fht = предохранитель от перебора рёбер и полигонов.
        fht = []
        if len(edg_pol[0][0]) == 2:
            pols = []
            for edgs in edg_pol:
                maxi = max(max(a) for a in edgs)
                fht.append(maxi)
        elif len(edg_pol[0][0]) > 2:
            edgs = []
            for pols in edg_pol:
                maxi = max(max(a) for a in pols)
                fht.append(maxi)
        vertices = Vector_generate(vers)
        matrixes = Matrix_generate(mats)
        objects = {}
        fhtagn = []
        for u, f in enumerate(fht):
            fhtagn.append(min(len(vertices[u]), fht[u]))
        #lenmesh = len(vertices) - 1

        # name space for particular bakery node
        # defined only by matrices count (without .001 etc)
        global sverchok_bakery_cache
        try:
            cache = sverchok_bakery_cache[self.name]
        except:
            cache = []
        names = ['Sv_' + self.name + str(i) for i, t in enumerate(mats)]
        #print('bakery'+str(names)+str(cache))

        # delete previous objects удаляет предыдущие объекты, если есть, если надо.
        bpy.ops.object.select_all(action='DESELECT')
        for i, obj in enumerate(bpy.context.scene.objects):
            nam = 'Sv_' + self.name
            if nam in obj.name:
                if obj.name not in names:
                    bpy.context.scene.objects[obj.name].select = True
                    bpy.ops.object.delete(use_global=False)

        for i, m in enumerate(matrixes):
            # solution to reduce number of vertices respect to edges/pols
            ########
            k = i
            lenver = len(vertices) - 1
            if i > lenver:
                v = vertices[-1]
                k = lenver
            else:
                v = vertices[k]
            if (len(v)-1) < fhtagn[k]:
                continue
            elif fhtagn[k] < (len(v)-1):
                nonneed = (len(v)-1) - fhtagn[k]
                for q in range(nonneed):
                    v.pop((fhtagn[k]+1))
            #########
            # end of solution to reduce vertices

            e = edg_pol[k] if edgs else []
            p = edg_pol[k] if pols else []

            # to change old, create new separately
            if names[i] not in cache:
                objects[str(i)] = self.makemesh(names[i], v, e, p, m)
            elif bpy.context.scene.objects.find(names[i]) >= 0:
                objects[str(i)] = self.makemesh_exist(names[i], v, e, p, m)
            else:
                objects[str(i)] = self.makemesh(names[i], v, e, p, m)

        for i, ite in enumerate(objects.values()):
            me = ite[1]
            ob = ite[0]
            calcedg = True
            if edgs:
                calcedg = False
            me.update(calc_edges=calcedg)
            if ob.name not in cache:
                bpy.context.scene.objects.link(ob)

        # save cache
        sverchok_bakery_cache[self.name] = names