Пример #1
0
 def build_displaylist(self, width, height):
     cls = Card
     width, height = width / 2.0, height / 2.0
     vertlist = [
         euclid.Point3(-width, -height, 0),
         euclid.Point3(width, -height, 0),
         euclid.Point3(width, height, 0),
         euclid.Point3(-width, height, 0)
     ]
     cls.vertlist = vertlist
     tc = self._texture.tex_coords
     cardlist = glGenLists(1)
     glNewList(cardlist, GL_COMPILE)
     glBegin(GL_QUADS)
     glTexCoord2f(tc[0], tc[1])
     glVertex3f(*tuple(vertlist[0]))
     glTexCoord2f(tc[3], tc[4])
     glVertex3f(*tuple(vertlist[1]))
     glTexCoord2f(tc[6], tc[7])
     glVertex3f(*tuple(vertlist[2]))
     glTexCoord2f(tc[9], tc[10])
     glVertex3f(*tuple(vertlist[3]))
     glEnd()
     glEndList()
     return cardlist
Пример #2
0
 def build_borderedlist(self):
     cls = StackCard
     width = self.border.width / 2.0
     height = self.border.height / 2.0
     vertlist = [
         euclid.Point3(-width, -height, 0),
         euclid.Point3(width, -height, 0),
         euclid.Point3(width, height, 0),
         euclid.Point3(-width, height, 0)
     ]
     tc = self.border.tex_coords
     cardlist = glGenLists(1)
     cls.borderedlist = cardlist
     glNewList(cardlist, GL_COMPILE)
     glBegin(GL_QUADS)
     glTexCoord2f(tc[0], tc[1])
     glVertex3f(*tuple(vertlist[0]))
     glTexCoord2f(tc[3], tc[4])
     glVertex3f(*tuple(vertlist[1]))
     glTexCoord2f(tc[6], tc[7])
     glVertex3f(*tuple(vertlist[2]))
     glTexCoord2f(tc[9], tc[10])
     glVertex3f(*tuple(vertlist[3]))
     glEnd()
     glEndList()
Пример #3
0
    def add_to(self, batch):
        '''Add the meshes to a batch applying model transformations'''
        for mesh in self.mesh_list:
            for group in mesh.groups:
                vertices = []
                normals = []
                for index in xrange(0, len(group.vertices), 3):
                    tv = self.transforms * euclid.Point3(
                        group.vertices[index], group.vertices[index + 1],
                        group.vertices[index + 2])
                    vertices.extend(tv[:])
                    tn = self.transforms * euclid.Point3(
                        group.normals[index], group.normals[index + 1],
                        group.normals[index + 2])
                    if self.normalize:
                        tn = tn.normalized()
                    normals.extend(tn[:])

                batch.add(
                    len(vertices) // 3,
                    GL_TRIANGLES,
                    group.material,
                    ('v3f/static', tuple(vertices)),
                    ('n3f/static', tuple(normals)),
                    ('t2f/static', tuple(group.tex_coords)),
                )
Пример #4
0
 def multicolored_border(self):
     width = self.border.width / 2.0
     height = self.border.height / 2.0
     vertlist = [
         euclid.Point3(-width, -height, 0),
         euclid.Point3(width, -height, 0),
         euclid.Point3(width, height, 0),
         euclid.Point3(-width, height, 0)
     ]
     tc = self.border.tex_coords
     color1, color2 = self.color
     glBegin(GL_QUADS)
     glColor4f(color1[0], color1[1], color1[2], self.alpha)
     glTexCoord2f(tc[0], tc[1])
     glVertex3f(*tuple(vertlist[0]))
     glColor4f(color2[0], color2[1], color2[2], self.alpha)
     glTexCoord2f(tc[3], tc[4])
     glVertex3f(*tuple(vertlist[1]))
     glColor4f(color2[0], color2[1], color2[2], self.alpha)
     glTexCoord2f(tc[6], tc[7])
     glVertex3f(*tuple(vertlist[2]))
     glColor4f(color1[0], color1[1], color1[2], self.alpha)
     glTexCoord2f(tc[9], tc[10])
     glVertex3f(*tuple(vertlist[3]))
     glEnd()
Пример #5
0
    def __init__(self,
                 focus=(1, 0, 0),
                 FoV=90,
                 width=180,
                 height=180,
                 rotation=(0, 0, 0),
                 translation=P3(0, 0, 0),
                 zoom=1.0):
        if len(focus) != 3 or type(focus) != tuple:
            raise TypeError("'focus' must be a tuple of length 3.")
        self.focus = euclid.Point3(focus[0], focus[1], focus[2])
        self.FoV = float(FoV)
        self.LRAngle = math.radians(self.FoV)
        self.width = int(width)
        self.height = int(height)
        self.aspectRatio = float(self.width) / self.height
        if len(rotation) != 3 or type(rotation) != tuple:
            raise TypeError("'rotation' must be a tuple of length 3.")
        self.rotation = (math.radians(rotation[0]), math.radians(rotation[1]),
                         math.radians(rotation[2]))
        if len(translation) != 3:
            raise TypeError("'translation' must be a Point3 or Vector3.")
        self.translation = translation
        self.zoom = float(zoom)

        self.calculateRepr()  # calculate representation
Пример #6
0
 def build_ray(self, mouse_x, mouse_y, button, w, h):
     """
         build ray: from mouse position to a 3D ray (in world coordinate) starting from camera eye position
     """
     #viewport coordinates to normalized device coordinates
     x = 2 * mouse_x / w - 1
     y = 2 * mouse_y / h - 1
     #call projection matrix and model view matrix
     M_proj = (gl.GLfloat * 16)()
     M_modelview = (gl.GLfloat * 16)()
     gl.glGetFloatv(gl.GL_PROJECTION_MATRIX, M_proj)
     gl.glGetFloatv(gl.GL_MODELVIEW_MATRIX, M_modelview)
     M_proj = euclid.Matrix4.new(*(list(M_proj)))
     M_modelview = euclid.Matrix4.new(*(list(M_modelview)))
     M_proj_inversed = M_proj.inverse()
     M_modelview_inversed = M_modelview.inverse()
     #homogeneous clip coordinates
     vector_clip = euclid.Vector3(x, y, -1)
     #eye coordinates
     vector_eye = M_proj_inversed * vector_clip
     vector_eye = euclid.Vector3(vector_eye[0], vector_eye[1], -1)
     #world coordinates
     vector_world = M_modelview_inversed * vector_eye
     vector_world.normalize()
     #        print(vector_world);
     #        print(M_modelview_inversed);
     #build ray, starting point is camera eye position
     ray = euclid.Ray3(
         euclid.Point3(M_modelview_inversed[12], M_modelview_inversed[13],
                       M_modelview_inversed[14]), vector_world)
     return ray
Пример #7
0
 def __init__(self,
              origin=euclid.Point3(0., 0., 0.),
              squaresize=4,
              normal=euclid.Vector3(0., 0., 1.),
              roughness=1.0,
              transparency=0.0,
              refractionIndex=1.0):
     super().__init__(color=(255, 255, 255),
                      roughness=roughness,
                      transparency=transparency,
                      refractionIndex=refractionIndex)
     self.shape = euclid.Plane(origin, normal)
     normal = normal.normalized()
     self.squaresize = squaresize
     # let's find the unit vectors
     ux = euclid.Vector3(0., 1., 0.)
     uy = euclid.Vector3(0., 0., 1.)
     un = euclid.Vector3(1., 0., 0.)  # 'original' normal
     # rotation axis
     axis = un.cross(normal)
     # cos(angle) between normal and unit normal
     angle = normal.dot(un)
     angle = math.acos(angle)
     rotation = euclid.Quaternion.new_rotate_axis(angle, axis)
     self.unitx = rotation * ux
     self.unity = rotation * uy
Пример #8
0
def render_tree(n=10, r=False):
    glLineWidth(2.)
    glColor4f(.5, .5, .5, .5)
    glBegin(GL_LINES)
    _tree_branch(n - 1, euclid.Line3(euclid.Point3(0., 0., 0.),
                                     euclid.Vector3(0., 1., 0.), 1.), r)
    glEnd()
Пример #9
0
 def init(self):
     self.camera = Camera(euclid.Point3(0,15, 0))
     self.mainplayer_status = StatusView()
     self.otherplayer_status = StatusView(is_opponent=True)
     self.mana_controller = ManaController(self.mainplayer_status.manapool, self.otherplayer_status.manapool, self)
     self.x_controller = XSelector(self.mainplayer_status.manapool, self.otherplayer_status.manapool, self)
     self.card_selector = CardSelector(self.mainplayer_status, self.otherplayer_status, self)
     #self.game_status = GameStatus()
     self.phase_status = PhaseStatus()
     self.phase_bar = PhaseBar()
     self.phase_controller = PhaseController(self.phase_status, self)
     self.status_controller = StatusController(self.mainplayer_status, self.otherplayer_status, self.phase_status, self)
     self.selection = SelectionList()
     self.list_selector = SelectController(self.selection, self)
     self.msg_dialog = MessageDialog()
     self.msg_controller = MessageController(self.msg_dialog, self)
     self.table = Table()
     self.mainplay = PlayView(z=3)
     self.otherplay = PlayView(z=-3, is_opponent_view=True)
     self.play_controller = PlayController(self.mainplay, self.otherplay, self)
     self.damage_assignment = DamageSelector(self.mainplay, self.otherplay, self)
     self.distribution_assignment = DistributionSelector(self.mainplay, self.otherplay, self)
     self.player_hand = HandView()
     self.hand_controller = HandController(self.player_hand, self)
     self.otherplayer_hand = HandView(is_opponent=True)
     self.otherhand_controller = HandController(self.otherplayer_hand, self)
     self.stack = StackView()
     self.stack_controller = StackController(self.stack, self)
     self.zone_animator = ZoneAnimator(self)
     self._keep_priority = False
     self.finish_turn = False
     self.p1_stop_next = False
     self.p2_stop_next = False
Пример #10
0
def rot(x, y, z, rx, ry, rz, c):
    cx, cy, cz = c[:3]
    x = x - cx
    y = y - cy
    z = z - cz
    my = euclid.Matrix4.new_rotatey(ry * math.pi / 180.0)
    mz = euclid.Matrix4.new_rotatez(rz * math.pi / 180.0)
    if rz:
        mx = euclid.Matrix4.new_rotatez(rz * math.pi / 180.0)
        x, y, z = mx * euclid.Point3(x, y, z)
    if rx:
        mx = euclid.Matrix4.new_rotatex(rx * math.pi / 180.0)
        x, y, z = mx * euclid.Point3(x, y, z)
    if ry:
        mx = euclid.Matrix4.new_rotatey(ry * math.pi / 180.0)
        x, y, z = mx * euclid.Point3(x, y, z)
    return [x + cx, y + cy, z + cz]
Пример #11
0
def draw_lathe(point_fn, slices, texr=RING_TEXTURE_RADIUS):
    vertices = []
    normals = []
    tex_coords = []

    a = 0
    incr = 2 * pi / slices
    lastslice = [(r, 0, z, r) for (r, z) in point_fn(slices)]
    for i in range(slices + 1):
        ca, sa = cos(a), sin(a)
        newslice = [(ca * r, sa * r, z, r) for (r, z) in point_fn(i)]
        lastp = None
        for ((x1, y1, z1, r1), (x2, y2, z2, r2)) in zip(lastslice, newslice):
            p = euclid.Point3(x1, y1, z1)
            if lastp:
                t1 = euclid.Vector3(x2 - x1, y2 - y1, z2 - z1)
                t2 = p - lastp
                n = t1.cross(t2)
                normal = (n.x, n.y, n.z)
            else:
                normal = (0, 0, -1)
            lastp = p
            r1 = (r1 + abs(z1)) / texr / 2
            r2 = (r2 + abs(z2)) / texr / 2
            normals.extend(normal)
            tex_coords.extend((ca * r2 + .5, sa * r2 + .5))
            vertices.extend((x2, y2, z2))
            normals.extend(normal)
            tex_coords.extend((ca * r1 + .5, sa * r1 + .5))
            vertices.extend((x1, y1, z1))
        lastslice = newslice
        a += incr

    vertices = (GLfloat * len(vertices))(*vertices)
    normals = (GLfloat * len(normals))(*normals)
    tex_coords = (GLfloat * len(tex_coords))(*tex_coords)
    count = 2 * len(lastslice)
    counts = [count for i in range(slices + 1)]
    counts = (GLint * len(counts))(*counts)
    firsts = range(0, (slices + 1) * count, count)
    firsts = (GLint * len(firsts))(*firsts)
    glPushAttrib(GL_ENABLE_BIT)
    glEnable(GL_NORMALIZE)
    glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
    glEnableClientState(GL_VERTEX_ARRAY)
    glEnableClientState(GL_NORMAL_ARRAY)
    glEnableClientState(GL_TEXTURE_COORD_ARRAY)
    glVertexPointer(3, GL_FLOAT, 0, vertices)
    glNormalPointer(GL_FLOAT, 0, normals)
    glTexCoordPointer(2, GL_FLOAT, 0, tex_coords)
    if gl_info.have_version(1, 4):
        glMultiDrawArrays(GL_QUAD_STRIP, firsts, counts, slices + 1)
    else:
        for first in firsts:
            glDrawArrays(GL_QUAD_STRIP, first, count)
    glPopClientAttrib()
    glPopAttrib()
Пример #12
0
    def selection_ray(self, x, y):
        self.setup()
        model_view = (GLdouble * 16)()
        glGetDoublev(GL_MODELVIEW_MATRIX, model_view)
        projection = (GLdouble * 16)()
        glGetDoublev(GL_PROJECTION_MATRIX, projection)
        viewport = (GLint * 4)()
        glGetIntegerv(GL_VIEWPORT, viewport)

        x1, y1, z1 = GLdouble(), GLdouble(), GLdouble()
        x2, y2, z2 = GLdouble(), GLdouble(), GLdouble()
        gluUnProject(x, y, 0, model_view, projection, viewport, x1, y1, z1)
        gluUnProject(x, y, 1, model_view, projection, viewport, x2, y2, z2)
        ray = euclid.Ray3(euclid.Point3(x1.value, y1.value, z1.value),
                          euclid.Point3(x2.value, y2.value, z2.value))
        ray.v.normalize()
        self.reset()
        return ray
Пример #13
0
    def collide_floor(self, segment):
        # aabox for line segment
        q1 = segment.p
        q2 = segment.p + segment.v
        p1 = euclid.Point3(min(q1.x, q2.x), min(q1.y, q2.y), min(q1.z, q2.z))
        p2 = euclid.Point3(max(q1.x, q2.x), max(q1.y, q2.y), max(q1.z, q2.z))

        best = None
        best_poly = None
        for poly in self.get_polygons_within_aabox(p1, p2):
            if poly.plane.n.dot(up) < 0.7:  # 45 degree or less only
                continue
            p = poly.intersect_line3(segment)
            if p is not None:
                if best is None or p.y > best.y:
                    best = p
                    best_poly = poly
        return best, best_poly
Пример #14
0
 def __init__(self, cwidth=180, cheight=180):
     self.BackgroundColor = (255, 0, 255)
     self.objects = []
     self.camera = Camera(zoom=0.15,
                          rotation=(0, 16, -4),
                          width=cwidth,
                          height=cheight)
     # light source is a single point for now
     self.light = euclid.Point3(0.0, 0.0, 0.0)
Пример #15
0
    def test_add(self):
        a = (3.0, 7.0, 11.0)
        b = (1.0, 2.0, 3.0)
        va = eu.Vector3(*a)
        vb = eu.Vector3(*b)

        self.assertTrue(isinstance(va + vb, eu.Vector3))
        self.assertEqual(repr(va + vb),
                         'Vector3(%.2f, %.2f, %.2f)' % (4.0, 9.0, 14.0))

        c = (13.0, 17.0, 23.0)
        pc = eu.Point3(*c)
        d = (31.0, 37.0, 41.0)
        pd = eu.Point3(*d)

        self.assertTrue(isinstance(va + pc, eu.Point3))
        self.assertTrue(isinstance(pc + pd, eu.Vector3))

        self.assertTrue(isinstance(va + b, eu.Vector3))
        self.assertEqual(va + vb, va + b)
Пример #16
0
def main():
    T = int(raw_input())
    for case in xrange(T):
        N = int(raw_input())
        position = euclid.Vector3()
        velocity = euclid.Vector3()
        for _ in xrange(N):
            x, y, z, vx, vy, vz = map(float, raw_input().split())
            position += euclid.Vector3(x, y, z)
            velocity += euclid.Vector3(vx, vy, vz)
        position /= N
        velocity /= N
        if velocity == euclid.Vector3():
            d_min = abs(position - euclid.Point3())
            t_min = 0.
        else:
            position = euclid.Point3(position.x, position.y, position.z)
            ray = euclid.Ray3(position, velocity)
            connection = ray.connect(euclid.Point3())
            d_min = abs(connection)
            t_min = abs(connection.p1 - position) / abs(velocity)
        print 'Case #%d: %1.8f %1.8f' % (case + 1, d_min, t_min)
Пример #17
0
    def set_c(self, c):
        '''Set the extents based on the center value and our dimensions.
        '''
        if isinstance(c, euclid.Point3):
            pass
        elif isinstance(c, euclid.Vector3):
            c = euclid.Point3(c.x, c.y, c.z)
        else:
            c = euclid.Point3(*c)
        c = self.__c = c
 
        x = (c.x - self.dx/2, c.x + self.dx/2)
        self.xmin = min(x)
        self.xmax = max(x)
 
        y = (c.y - self.dy/2, c.y + self.dy/2)
        self.ymin = min(y)
        self.ymax = max(y)
 
        z = (c.z - self.dz/2, c.z + self.dz/2)
        self.zmin = min(z)
        self.zmax = max(z)
Пример #18
0
def parseconfig(config):
    data = json.loads(config)
    objectlist, lights = [], []
    for conf in data["objects"]:
        if conf["type"] == "sphere":
            posx, posy, posz = conf["position"]
            r = conf["radius"]
            col = conf["color"]
            roughness = conf["roughness"]
            obj = objects.CollidableSphere(position=euclid.Point3(
                posx, posy, posz),
                                           radius=r,
                                           color=col,
                                           roughness=roughness)
        elif conf["type"] == "plane":
            orix, oriy, oriz = conf["origin"]
            normx, normy, normz = conf["normal"]
            roughness = conf["roughness"]
            obj = objects.CollidablePlane(
                origin=euclid.Point3(orix, oriy, oriz),
                normal=euclid.Vector3(normx, normy, normz),
                roughness=roughness)
        objectlist.append(obj)
    for conf in data["lights"]:
        x, y, z = conf
        lights.append(objects.Light(position=euclid.Point3(x, y, z)))
    conf = data["camera"]
    imgw, imgh = conf["imageDim"]
    scrw, scrh = conf["screenDim"]
    focal = conf["focallength"]
    camera = Camera(imageDim=(imgw, imgh),
                    focallength=focal,
                    screenDim=(scrw, scrh))
    scene = Scene(camera=camera, objects=objectlist, lights=lights)
    scene.skycolor = tuple(data["skycolor"])
    depth = data["depth"]

    return camera, depth, lights, objectlist, scene
Пример #19
0
 def __init__(self,
              position=euclid.Point3(0., 0., 0.),
              color=(255, 255, 0),
              radius=1.,
              roughness=1.0,
              transparency=0.0,
              refractionIndex=1.0):
     super().__init__(color=color,
                      roughness=roughness,
                      transparency=transparency,
                      refractionIndex=refractionIndex)
     self.position = position
     self.radius = radius
     self.shape = euclid.Sphere(self.position, self.radius)
Пример #20
0
 def __init__(self,
              screenDim=(4, 4),
              imageDim=(64, 64),
              translation=euclid.Point3(0., 0., 0.),
              rotation=euclid.Quaternion(),
              focallength=1.0):
     self.translation = translation
     self.rotation = rotation
     self.focallength = focallength  # distance from camera to screen
     # Screen width is the real-world width/height of the screen
     self.screenw = screenDim[0]
     self.screenh = screenDim[1]
     # Image width is the number of pixels in the screen
     self.imagew = imageDim[0]
     self.imageh = imageDim[1]
Пример #21
0
    def test_swizzle_get(self):
        xyz = (1.0, 2.0, 3.0)
        v3 = eu.Point3(*xyz)
        self.assertEqual(v3.x, xyz[0])
        self.assertEqual(v3.y, xyz[1])
        self.assertEqual(v3.z, xyz[2])

        self.assertEqual(v3.xy, (xyz[0], xyz[1]))
        self.assertEqual(v3.xz, (xyz[0], xyz[2]))
        self.assertEqual(v3.yz, (xyz[1], xyz[2]))

        self.assertEqual(v3.yx, (xyz[1], xyz[0]))
        self.assertEqual(v3.zx, (xyz[2], xyz[0]))
        self.assertEqual(v3.zy, (xyz[2], xyz[1]))

        self.assertEqual(v3.xyz, xyz)
        self.assertEqual(v3.xzy, (xyz[0], xyz[2], xyz[1]))
        self.assertEqual(v3.zyx, (xyz[2], xyz[1], xyz[0]))
        self.assertEqual(v3.zxy, (xyz[2], xyz[0], xyz[1]))
        self.assertEqual(v3.yxz, (xyz[1], xyz[0], xyz[2]))
        self.assertEqual(v3.yzx, (xyz[1], xyz[2], xyz[0]))
Пример #22
0
def process_rule(rule, rules, depth, verts, faces, matrix = euclid.Matrix4.new_identity()):
    if (depth < 1):
        return
    for statement in rule:
        xform = parse_xform(statement["transforms"])
        count = statement["count"]
        for n in xrange(count):
            matrix *= xform
            if "call" in statement:
                next_rule = pick_rule(statment["call"]["rules"], rules)
                cloned_matrix = matrix.copy()
                process_rule(rules[next_rule], rules, depth - 1, verts, faces, cloned_matrix)
            elif "instance" in statment:
                shape_name = statement["instance"]["shape"]
                shape_verts, shape_faces = shapes[shape_name]
                n  = len(verts)
                for v in shape_verts:
                    transformed_vert = matrix * euclid.Point3(*v)
                    verts.append(transformed_vert[:])
                for i, j, k in shape_faces:
                    faces.append((i+n, j+n, k+n))
                else:
                    print "Malformed statement"
                    return
Пример #23
0
#        elif data[0] == 'f':
#            vi_1, vi_2, vi_3 = data[1:4]
#            faces.extend((vi_1,vi_2,vi_3))
#point1=[0,0];
#point2=[0,1];
#point3=[1,1];
#point4=[1,0];
#
#x=np.arange(4);
#y=np.array([point1,point2,point3,point4]);
#cs=interpolate.CubicSpline(x,y);
#plt.plot(y[:,0],y[:,1]);
#plt.plot(cs(xs)[:,0],cs(xs)[:,1])
#plt.show()

ray1 = euclid.Ray3(euclid.Point3(0, 0, 0), euclid.Point3(1, 1, 1))
ray2 = euclid.Ray3(euclid.Point3(1, 1, 0), euclid.Point3(1, 1, -0.5))


def line_intersect(ray1, ray2):
    """
        find intersection point between two lines
    """
    small_num = 0.000001
    den = ray2.v.cross(ray1.v)
    d = den.magnitude()
    t = -1
    #if not paralleled
    if d > small_num:
        g = ray2.p - ray1.p
        num = ray2.v.cross(g)
    def load(self, path):
        self.clear()

        with open(path) as obj_file:
            for line in obj_file.readlines():
                # reads the file line by line
                data = line.split()
                #print(data);
                if len(data) == 0 or data[0] not in ['v', 'vn', 'vt', 'f']:
                    continue
                # every line that begins with a 'v' is a vertex
                if data[0] == 'v':
                    x, y, z = data[1:4]
                    self.vertices.extend(
                        (float(x) * 10, float(y) * 10, float(z) * 10))
                # every line that begins with a 'vn' is a vertex normal
                if data[0] == 'vn':
                    x_n, y_n, z_n = data[1:4]
                    self.vertex_nomals.extend(
                        (float(x_n), float(y_n), float(z_n)))
                # every line that begins with a 'vt' is a text coordinate
                if data[0] == 'vt':
                    t_u, t_v = data[1:3]
                    self.text_coord.extend((float(t_u), float(t_v)))
                # every line that begins with an 'f' is a face
                # loads the faces
                elif data[0] == 'f':
                    # quads
                    # Note: in obj files the first index is 1, so we must subtract one for each
                    # retrieved value
                    if len(data) == 5:
                        vi_1, vi_2, vi_3, vi_4 = data[1:5]
                        self.quad_indices.extend(
                            (int(vi_1) - 1, int(vi_2) - 1, int(vi_3) - 1,
                             int(vi_4) - 1))
                    # triangles
                    # Note: in obj files the first index is 1, so we must subtract one for each
                    # retrieved value
                    elif len(data) == 4:
                        #triangles with complete info
                        vi_1, vi_2, vi_3 = data[1:4]
                        if '//' in data[1]:
                            vi_1 = vi_1.split('//')
                            vi_2 = vi_2.split('//')
                            vi_3 = vi_3.split('//')
                            self.triangle_indices.extend(
                                (int(vi_1[0]) - 1, int(vi_2[0]) - 1,
                                 int(vi_3[0]) - 1))
                            self.normal_indices.extend(
                                (int(vi_1[1]) - 1, int(vi_2[1]) - 1,
                                 int(vi_3[1]) - 1))

                        elif '/' in data[1]:
                            vi_1 = vi_1.split('/')
                            vi_2 = vi_2.split('/')
                            vi_3 = vi_3.split('/')
                            self.triangle_indices.extend(
                                (int(vi_1[0]) - 1, int(vi_2[0]) - 1,
                                 int(vi_3[0]) - 1))
                            self.text_indices.extend(
                                (int(vi_1[1]) - 1, int(vi_2[1]) - 1,
                                 int(vi_3[1]) - 1))
                            self.normal_indices.extend(
                                (int(vi_1[2]) - 1, int(vi_2[2]) - 1,
                                 int(vi_3[2]) - 1))

                        else:
                            self.triangle_indices.extend(
                                (int(vi_1) - 1, int(vi_2) - 1, int(vi_3) - 1))
        points_indices = []
        for i in range(len(self.quad_indices) // 4):
            #put all indices for a quad into points-indices, and then separate it into 2 triangles
            points_indices.extend(
                (self.quad_indices[4 * i], self.quad_indices[4 * i + 1],
                 self.quad_indices[4 * i + 2], self.quad_indices[4 * i + 3]))
            p1 = euclid.Point3(self.vertices[3 * points_indices[0]],
                               self.vertices[3 * points_indices[0] + 1],
                               self.vertices[3 * points_indices[0] + 2])
            p2 = euclid.Point3(self.vertices[3 * points_indices[1]],
                               self.vertices[3 * points_indices[1] + 1],
                               self.vertices[3 * points_indices[1] + 2])
            p3 = euclid.Point3(self.vertices[3 * points_indices[2]],
                               self.vertices[3 * points_indices[2] + 1],
                               self.vertices[3 * points_indices[2] + 2])
            p4 = euclid.Point3(self.vertices[3 * points_indices[3]],
                               self.vertices[3 * points_indices[3] + 1],
                               self.vertices[3 * points_indices[3] + 2])
            self.triangles.append(Triangle(points_indices[0],points_indices[1],points_indices[2],\
                                           p1,p2,p3))
            self.triangles.append(Triangle(points_indices[2],points_indices[3],points_indices[0],\
                                           p3,p4,p1))
            points_indices.clear()
        points_indices.clear()
        for i in range(len(self.triangle_indices) // 3):
            #put all indices for a triangle into points_indices
            points_indices.extend((self.triangle_indices[3 * i],
                                   self.triangle_indices[3 * i + 1],
                                   self.triangle_indices[3 * i + 2]))
            p1 = euclid.Point3(self.vertices[3 * points_indices[0]],
                               self.vertices[3 * points_indices[0] + 1],
                               self.vertices[3 * points_indices[0] + 2])
            p2 = euclid.Point3(self.vertices[3 * points_indices[1]],
                               self.vertices[3 * points_indices[1] + 1],
                               self.vertices[3 * points_indices[1] + 2])
            p3 = euclid.Point3(self.vertices[3 * points_indices[2]],
                               self.vertices[3 * points_indices[2] + 1],
                               self.vertices[3 * points_indices[2] + 2])
            self.triangles.append(Triangle(points_indices[0],points_indices[1],points_indices[2],\
                                           p1,p2,p3))
            points_indices.clear()
Пример #25
0
# Note that this changes em1, but not nm1!
em1_copy = em1.copy()
aseq(
    em1.pre_translate(8, 7) * ev1,
    nm1.pre_translate(8, 7) * nv1, '5 translate apply')
em1 = em1_copy
aseq(em1, nm1, 'foo')

# Test that Vec2Array application works
rvals = [(np.random.random(), np.random.random()) for i in range(6)]
nmv = nm1 * npeuclid.Vec2Array(rvals)
for i, v in enumerate(rvals):
    aseq(em1 * euclid.Point2(*v), nmv[i], 'Vec2 array apply: Point %d' % i)

ev1 = euclid.Point3(1, 2, 3)
nv1 = npeuclid.Vec3(1, 2, 3)
aseq(ev1, nv1, 'Point3')

et1 = euclid.Matrix4.new_scale(1, 2, 3)
nt1 = npeuclid.Affine3.new_scale(1, 2, 3)
aseq(et1, nt1, 'Scale3')

ev2 = et1 * ev1
nv2 = nt1 * nv1
aseq(ev2, nv2, 'Scaled3 point')

heading, attitude, bank = [math.degrees(v) for v in (10, 20, 30)]
et2 = euclid.Matrix4.new_rotate_euler(heading, attitude, bank)
nt2 = npeuclid.Affine3.new_rotate_euler(heading, attitude, bank)
ev3 = et2 * ev1
Пример #26
0
def make_spline(p0, p1, p2, p3, roll0, roll1, width, segments):
    verts = []
    colors = []
    uvs = []
    trackColor = (255, 255, 255)
    width = width * 0.5
    for i in range(0, segments):
        t = i / float(segments)
        color = (255 * t, 0, 255 - (255 * t))
        (x0, dx0) = spline(t, p0.x, p1.x, p2.x, p3.x)
        (y0, dy0) = spline(t, p0.y, p1.y, p2.y, p3.y)
        (z0, dz0) = spline(t, p0.z, p1.z, p2.z, p3.z)
        at0 = euclid.Point3(x0, y0, z0)
        d0 = euclid.Vector3(dx0, dy0, dz0)
        d0.normalize()
        up = euclid.Vector3(0.0, 0.0, 1.0)
        roll = roll0 + (roll1 - roll0) * (3.0 * t * t - 2.0 * t * t * t)
        (forward, normal, perp) = project(d0, up)
        print(forward, perp, normal)

        # left back
        leftOffset = perp * -width
        rollTransform = euclid.Matrix4.new_rotate_axis(roll * math.pi / 180.0,
                                                       forward)
        leftOffset = rollTransform * leftOffset
        pos = at0 + leftOffset
        verts.append(pos)
        colors.append(color)
        uvs.append((0.0, 0.0))

        # right back
        rightOffset = perp * width
        rollTransform = euclid.Matrix4.new_rotate_axis(roll * math.pi / 180.0,
                                                       forward)
        rightOffset = rollTransform * rightOffset
        pos = at0 + rightOffset
        verts.append(pos)
        colors.append(color)
        uvs.append((1.0, 0.0))

        t = (i + 1) / float(segments)
        color = (255 * t, 0, 255 - (255 * t))
        (x1, dx1) = spline(t, p0.x, p1.x, p2.x, p3.x)
        (y1, dy1) = spline(t, p0.y, p1.y, p2.y, p3.y)
        (z1, dz1) = spline(t, p0.z, p1.z, p2.z, p3.z)
        at1 = euclid.Point3(x1, y1, z1)
        d1 = euclid.Vector3(dx1, dy1, dz1)
        d1.normalize()
        roll = roll0 + (roll1 - roll0) * (3.0 * t * t - 2.0 * t * t * t)
        (forward, normal, perp) = project(d1, up)

        # left front
        leftOffset = perp * -width
        rollTransform = euclid.Matrix4.new_rotate_axis(roll * math.pi / 180.0,
                                                       d1)
        leftOffset = rollTransform * leftOffset
        pos = at1 + leftOffset
        verts.append(pos)
        colors.append(color)
        uvs.append((0.0, 1.0))

        # right front
        rightOffset = perp * width
        rollTransform = euclid.Matrix4.new_rotate_axis(roll * math.pi / 180.0,
                                                       d1)
        rightOffset = rollTransform * rightOffset
        pos = at1 + rightOffset
        verts.append(pos)
        colors.append(color)
        uvs.append((1.0, 1.0))

    faces = []
    for i in range(0, segments):
        faces.append(((i * 4), (i * 4 + 1), (i * 4 + 2)))
        faces.append(((i * 4 + 2), (i * 4 + 1), (i * 4 + 3)))

    return {"vertices": verts, "faces": faces, "colors": colors, "uvs": uvs}
Пример #27
0
def make_vertex(point):
    return euclid.Point3(point["x"], point["y"], point["z"])
Пример #28
0
 def getViewMatrix(self):
     translate = -1 * euclid.Point3(*self.group.translate)
     scale = euclid.Point3(1.0 / self.group.scale[0],
                           1.0 / self.group.scale[1], 0)
     return euclid.Matrix4.new_scale(*scale).translate(*translate)
Пример #29
0
 def worldPosFromMouse(self, mousePos):
     a, b = self.screenToAmbient(*mousePos)
     x1, y1, z1 = self.getViewMatrix() * euclid.Point3(a, b, 0)
     return x1, y1
Пример #30
0
 def __init__(self, position=euclid.Point3(0., 0., 0.), size=1.):
     self.position = position  # a Point3
     self.size = size