def reproject(self, rot): self.prj = Matrix4() self.prj.scale(self.tile_size, self.tile_size, 1.0) self.prj.rotate_axis(math.radians(60), Vector3(1, 0, 0)) self.prj.rotate_axis(rot, Vector3(0, 0, 1)) self.inv_prj = Matrix4() self.inv_prj.scale(self.tile_size, self.tile_size / 2, 1.0) self.inv_prj.rotate_axis(rot, Vector3(0, 0, 1)) self.inv_prj = self.inv_prj.inverse()
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if platform.system() != 'Darwin': dy = -dy if keys[key.SPACE] or modifiers & pyglet.window.key.MOD_ALT: if buttons & mouse.LEFT: s = 0.0075 m = self.camera.matrix mi = self.camera.matrixinv globaly = Vector3(*mi[4:7]) xaxis = Vector3(1, 0, 0) d = abs(Vector3(*m[12:15]) - self.camera.center) offs = Vector3(0, 0, d) m *= Matrix4.new_translate(*(-offs)).rotate_axis( s * -dx, globaly).rotate_axis(s * -dy, xaxis).translate(*(offs)) if buttons & mouse.RIGHT: s = -0.05 m = self.camera.matrix dist = (Point3(*m[12:15]) - self.camera.center) * 0.1 # dist = abs(dist) zaxis = Vector3(0, 0, 1) tx = zaxis * s * dx + zaxis * s * dx * dist m.translate(*tx) #self.camera.center -= zaxis*s*dx if buttons & mouse.MIDDLE: s = -0.01 m = self.camera.matrix dist = (Point3(*m[12:15]) - self.camera.center) * 0.3 dist = abs(dist) xaxis = Vector3(1, 0, 0) yaxis = Vector3(0, 1, 0) trans = Matrix4.new_translate(*(xaxis * s * dx * dist)).translate(*(yaxis * s * -dy * dist)) m *= trans self.camera.center = trans * self.camera.center self.camera.update()
def do_transformation_matrix(self): if self.view.up.y == 1.: # Obj's are exported with z axis up (0,0,1), so we need to # rotate x for -90 degrees to align with view's y up axis (0,1,0) self.orient.rotatex(pi / -2.) ''' Apply transformations in following order (translation -> -pivot -> orientation -> pivot) in order to rotate around arbitrary pivot point and properly position the model. TODO: Optimize matrix concatenation (rewrite in compact form) ''' self.mtransform = Matrix4.new_translate(*self.position) * Matrix4.new_translate(*(self.pivot * -1.)) * \ self.morient * Matrix4.new_translate(*self.pivot) # Create ctype array of the matrix self.m = (GLfloat * 16)(*self.mtransform)
def __init__(self, bidMapper, mid, first, count_inner_rings, count_spokes, bid, flip_face_def=False ): self.color = bidMapper.getColor(bid) self.mid = mid self.first = first self.count_inner_rings = count_inner_rings self.count_spokes = count_spokes self.boundaryId = bid self.alpha = math.radians( 360. / (self.count_spokes ) ) self.alpha_half = self.alpha / 2.0 self.simplices = [] self.outer_vertices_idx = [] self.inner_vertices_idx = [] self.vertices = PLCPointList( 3 ) self.spokes = [] self.mid_idx = self.vertices.appendVert( self.mid, self.color ) rot_mat = Matrix4.new_rotatez( self.alpha ) L = Vector3(self.first.x, self.first.y, self.first.z) z_offset = Vector3(0, 0, self.first.z) for i in range( 0, self.count_spokes ): if i != 0: L -= z_offset L = rot_mat * L L += z_offset L_idx = self.vertices.appendVert( L, self.color ) self.outer_vertices_idx.append( L_idx ) spoke_direction = self.mid - L assert self.mid.z == L.z spoke_vertex_idx = [] spoke_vertex_idx.append( L_idx ) spoke_add = spoke_direction / float( self.count_inner_rings ) for i in range( 1, self.count_inner_rings ): p = L + ( i * spoke_add ) spoke_vertex_idx.append( self.vertices.appendVert( p, self.color ) ) self.inner_vertices_idx.append( spoke_vertex_idx[-1] ) self.spokes.append( spoke_vertex_idx ) for i in range( 0, self.count_spokes ): current_spoke = self.spokes[i-1] left_spoke = self.spokes[i-2] right_spoke = self.spokes[i] for j in range( 0, self.count_inner_rings - 1 ): #print 'current spoke j,j+1, left spoke j: %f - %f - %f '%(current_spoke[j], current_spoke[j+1], left_spoke[j]) if flip_face_def: self.simplices.append( Simplex( current_spoke[j], current_spoke[j+1], left_spoke[j] ) ) self.simplices.append( Simplex( right_spoke[j+1], current_spoke[j+1], current_spoke[j] ) ) else: self.simplices.append( Simplex( left_spoke[j], current_spoke[j+1], current_spoke[j] ) ) self.simplices.append( Simplex( current_spoke[j], current_spoke[j+1], right_spoke[j+1] ) ) for i in range( 0, len(self.inner_vertices_idx) ): if flip_face_def: self.simplices.append( Simplex( self.inner_vertices_idx[i-1], self.inner_vertices_idx[i], self.mid_idx ) ) else: self.simplices.append( Simplex( self.mid_idx, self.inner_vertices_idx[i],self.inner_vertices_idx[i-1] ) ) #this is exposed to FullGrid self.vertex_idx = self.outer_vertices_idx
def rotate_point_rotation(self, point, axis, magnitude): m = Matrix4.new_rotate_axis(magnitude, axis) pos = Vector3(self.position.x - point.x, self.position.y - point.y, self.position.z - point.z) pos = m.transform( pos) return pos + point
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if platform.system() != 'Darwin': dy = -dy if keys[key.SPACE] or modifiers & pyglet.window.key.MOD_ALT: if buttons & mouse.LEFT: s = 0.0075 m = self.camera.matrix mi = self.camera.matrixinv globaly = Vector3(*mi[4:7]) xaxis = Vector3(1,0,0) d = abs(Vector3(*m[12:15]) - self.camera.center) offs = Vector3(0,0,d) m *= Matrix4.new_translate(*(-offs)).rotate_axis(s*-dx, globaly).rotate_axis(s*-dy, xaxis).translate(*(offs)) if buttons & mouse.RIGHT: s = -0.05 m = self.camera.matrix dist = (Point3(*m[12:15]) - self.camera.center) * 0.1 # dist = abs(dist) zaxis = Vector3(0,0,1) tx = zaxis*s*dx + zaxis*s*dx*dist m.translate(*tx) #self.camera.center -= zaxis*s*dx if buttons & mouse.MIDDLE: s = -0.01 m = self.camera.matrix dist = (Point3(*m[12:15]) - self.camera.center) * 0.3 dist = abs(dist) xaxis = Vector3(1,0,0) yaxis = Vector3(0,1,0) trans = Matrix4.new_translate(*(xaxis*s*dx*dist)).translate(*(yaxis*s*-dy*dist)) m *= trans self.camera.center = trans * self.camera.center self.camera.update()
def on_draw(): a = 1.6 b = a * sqrt(3) / 3 r = sqrt(1 - b*b) R = Vector3(a, a, a).normalized() * b cs = Matrix4.new_translate(R[0], R[1], R[2]) * Matrix4.new_look_at(Vector3(0, 0, 0), R, Vector3(0, 1, 0)) glDisable(GL_DEPTH_TEST) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() draw_coords(Matrix4.new_identity(), 2) draw_line((0, 0, 0), R, (1, 1, 0)) draw_coords(cs, r, 3) glEnable(GL_DEPTH_TEST) draw_triangle((a, 0, 0), (0, a, 0), (0, 0, a), (.5, .5, 1), .2) draw_sphere(1, (1, .5, .5), .2)
def add(self, shape, position=(0, 0, 0), orientation=None): matrix = Matrix4.new_translate(*position) if orientation is not None: matrix *= orientation child_offset = len(self.vertices) self.vertices.extend(self.child_vertices(shape, matrix)) self.faces.extend(self.child_faces(shape, child_offset))
def view_update(self, width, height): glViewport(0, 0, width, height) # match openGL format self.persp_matrix = Matrix4.new_perspective(self.fov, width / float(height), self.clipnear, self.clipfar)
def get_view_matrix(self): """Get the view matrix as a euclid.Matrix4.""" f = (v3(self.look_at) - v3(self.pos)).normalized() #print "f=", f up = Vector3(0, 1, 0) s = f.cross(up).normalize() #print abs(f), abs(up), abs(s) #print "s=", s u = s.cross(f) m = Matrix4.new( *itertools.chain(s, [0], u, [0], -f, [0], [0, 0, 0, 1])) #print m xlate = Matrix4.new_translate(*(-self.pos)) #print xlate mat = m.inverse() * xlate #print mat return mat
def __init__(self, window): self.fov = math.radians(50) self.clipnear = 0.1 self.clipfar = 100000 self.needs_update = True self.params = {} self.window = window handlers = CameraHandler(window, self) window.push_handlers(handlers) self.center = Point3(0, 0, 0) self.matrix = Matrix4().new_rotate_axis(math.pi * -0.1, Vector3( 1, 0, 0)).translate(0, 0.0, 6) self.matrixinv = self.matrix.inverse() self.persp_matrix = Matrix4()
def on_draw(): a = 1.6 b = a * sqrt(3) / 3 r = sqrt(1 - b * b) R = Vector3(a, a, a).normalized() * b cs = Matrix4.new_translate(R[0], R[1], R[2]) * Matrix4.new_look_at( Vector3(0, 0, 0), R, Vector3(0, 1, 0)) glDisable(GL_DEPTH_TEST) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() draw_coords(Matrix4.new_identity(), 2) draw_line((0, 0, 0), R, (1, 1, 0)) draw_coords(cs, r, 3) glEnable(GL_DEPTH_TEST) draw_triangle((a, 0, 0), (0, a, 0), (0, 0, a), (.5, .5, 1), .2) draw_sphere(1, (1, .5, .5), .2)
def internal_tick_callback(self, timeStep): if self._cue_ball_rest(): disp = self.world.getDispatcher() n = disp.getNumManifolds() for i in xrange(n): cm = disp.getManifoldByIndexInternal(i) contacts = cm.getNumContacts() for c in xrange(contacts): obA = cm.getBody0().getUserPointer() obB = cm.getBody1().getUserPointer() if obA == 'Cue' and obB == 'Cue Ball' \ or obA == 'Cue Ball' and obB == 'Cue': p = cm.getContactPoint(c) if p.getDistance() < 0.0: # test for penetration # The cue's strike force is calculated from actual # linear velocity applied to the cues orientation vector b = self.cue.body.getLinearVelocity() v = eVector3(b.x, b.y, b.z) d = self.cue.direction if hasattr(self.cue, 'direction') \ else self.view.dir # get force impuls = v.magnitude() * SCALE_FACTOR * 25. force = bVector3(d.x * impuls, d.y * impuls, 0.0) # span offset to [0..1] offset = eVector3(self.cue.dx * 4., 0., self.cue.dy * 4.) # calculate offset from cue's position [convert from eye into object space] # TODO: (rewrite this in compact form of vector vs. matrix multiplication) moffset = self.view.orient.inverse() * Matrix4.new_translate(*offset) offset = eVector3(moffset.d, moffset.h, moffset.l) cue = self.ball['cue'] cue.body.clearForces() cue.body.applyGravity() cue.body.applyForce(force, bVector3(offset.x, offset.y, offset.z)) # Restore cue self._reset_cue() def ball_cant_fly(ball): # check for flying pos = ball.motion.getWorldTransform().getOrigin() if pos.z > ball.radius: ball.body.applyCentralForce(bVector3(0, 0, -15 * SCALE_FACTOR)) # check for ball speed v = ball.body.getLinearVelocity() vel = eVector3(v.x, v.y, v.z) if vel.magnitude_squared() > PoolWindow.BALL_MAX_SPEED: ball.body.setLinearVelocity(v * 0.9) for ball in self.ball.values(): ball_cant_fly(ball)
def SetProjectionInfo(self, width, height): self.zoomWidth = self.zoomWidth * width / self.width self.zoomHeight = self.zoomHeight * height / self.height self.width = width self.height = height if self.mode == self.MODE_PERSPECTIVE: self.projectionMatrix = Matrix4.new_perspective(math.pi / 2.0, max(width, 1.0) / max(height, 1.0), self.nearPlane, self.farPlane) else: self.SetOrthogonalInfo(self.zoomWidth, self.zoomHeight) self.projectionMatrix.transpose()
def getPosition(lerpParameter): A = getClothoidConstant() signY = 1 # flip clothoid vertical if clockwise or endCurvature<startCurvature if (clockwise and startCurvature < endCurvature) or ( not clockwise and endCurvature < startCurvature): signY = -1 else: signY = 1 # calculate length on clothoid at start- and endpoint smallerLength = A * A * startCurvature greaterLength = A * A * endCurvature # calculate length on clothoid at interpolation point currentLength = lerp(smallerLength, greaterLength, lerpParameter) # calculate clothoid coordinates in local system localX = computeX(currentLength, A) - computeX(smallerLength, A) localY = signY * (computeY(currentLength, A) - computeY(smallerLength, A)) # calculate the global rotation angle and create rotation matrix rotation = Matrix4() rotation = rotation.rotatez(calculateGlobalRotation()) #print("python: " + str(calculateGlobalRotation())) # rotate point with global rotation angle tP_3 = rotation.transform(Vector3(localX, localY, 0)) tP = Vector2(tP_3.x, tP_3.y) # output global coordinates on clothoid intersection point if startCurvature < endCurvature: return tP + start elif endCurvature < startCurvature: return start - tP else: raise (-66)
def __init__(self, *args, **kwargs): super(Raw, self).__init__(*args, **kwargs) import import_raw self.vertices, self.indices = import_raw.readMeshRAW('trim.raw') verts = np.array(self.vertices).reshape(-1,3) idx = np.array(self.indices).reshape(-1,3) verts = self.transform_verts(verts, Matrix4.new_rotate_axis(math.pi*-0.5, Vector3(1,0,0)) ) vn = self.calculate_normals(verts, idx) self.vertices = tuple(verts.flat) self.normals = tuple(vn.flat) self.indices = tuple(idx.flat) self.vertex_list = self.batch.add_indexed(len(self.vertices)//3, GL_TRIANGLES, None, self.indices, ('v3f/static', self.vertices), ('n3f/static', self.normals) ) self.color = Parameter(default=Color3(0.9, 0.3, 0.4), vmin=0.0, vmax=1.0)
def draw(program,w,h): # Set the viewport. glViewport(0, 0, width, height) # Clear the color buffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(tri_program) loc = glGetUniformLocation(tri_program,"uPerspective") p = Matrix4.new_perspective(pi/6,4.0/3.0,0.1,10.0) glUniformMatrix4fv(loc, False, matToList(p)) loc = glGetUniformLocation(tri_program,"uLightDir") glUniform3f(loc,-1.0,0.4,0.7) loc = glGetUniformLocation(tri_program,"uFogDensity") glUniform1f(loc,fog_density) loc = glGetUniformLocation(tri_program,"uFogColor") glUniform4f(loc,0.3,0.3,0.35,1.0) draw_invader(1.0,-0.7,-4.0) draw_invader(0.1,0.2,-8.0) draw_invader(0.35,0.7,-9.0) # Use the text program object. glUseProgram(text_program) for slot in slots: slot.update() slot.draw_text_slot()
def matrix(self): # stupid rotate_euler taking coords out of order! return Matrix4.new_translate(*self.translate.value).rotate_euler(*self.rotate.value.yzx).scale(*self.scale.value)
def get_matrix(self): r = self.rot.get_matrix() t = Matrix4.new_translate(*self.pos) return t * r
glUniform1i(l,self.idx); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, vIndices) slots = [] def matToList(m): m = m.transposed() return [m.a,m.b,m.c,m.d, m.e,m.f,m.g,m.h, m.i,m.j,m.k,m.l, m.m,m.n,m.o,m.p] translation = Vector3() zstamp = time.time() invrots = [Matrix4.new_identity(), Matrix4.new_rotatex(pi/2), Matrix4.new_rotatex(-pi/2), Matrix4.new_rotatey(pi/2), Matrix4.new_rotatey(-pi/2), Matrix4.new_rotatez(pi/2), Matrix4.new_rotatex(pi)] def add_flat_tri(p, vertices, normals, indices): n = (p[1]-p[0]).cross(p[2]-p[0]).normalize() for i in range(3): vertices += array('f',[p[i].x, p[i].y, p[i].z]) normals += array('f',[n.x, n.y, n.z]) next = len(indices) indices += array('H',[next, next+1, next+2])
def update_projection(self): width, height = self.window.get_size() self.persp_matrix = Matrix4.new_perspective(self.fov, width / float(height), self.clipnear, self.clipfar)
def test_sphere_transform(): """We can transform a sphere.""" m = Matrix4.new_translate(0, 0, 5) assert Sphere(radius=2).transformed(m) == Sphere(Point3(0, 0, 5), 2)
def get_view_matrix_gl(self): from ctypes import c_double mat = (c_double * 16)() glGetDoublev(GL_MODELVIEW_MATRIX, mat) return Matrix4.new(*mat)
def rotate_point_rotation(self, point, axis, magnitude): m = Matrix4.new_rotate_axis(magnitude, axis) pos = Vector3(self.position.x - point.x, self.position.y - point.y, self.position.z - point.z) pos = m.transform(pos) return pos + point