def rect_from_line(line): """ Creates a rectangle from a line primitive by thickening it according to the primitive's aperture size. Treats rectangular apertures as square because otherwise the maths becomes too hard for my brain. """ r = get_aperture_size(line.aperture) / 2.0 start_v = V.from_tuple(line.start) end_v = V.from_tuple(line.end) dir_v = end_v - start_v # normalize direction vector abs_dir_v = abs(dir_v) if abs_dir_v: dir_v = dir_v / abs_dir_v else: dir_v = V(0, 0) # 45 degree angle means the vector pointing to the new rectangle edges has to be sqrt(2)*r long v_len = math.sqrt(2)*r # Give the direction vector the appropriate length dir_v *= v_len v1 = (start_v + dir_v.rotate(135, as_degrees=True)).as_tuple() v2 = (start_v + dir_v.rotate(-135, as_degrees=True)).as_tuple() v3 = (end_v + dir_v.rotate(-45, as_degrees=True)).as_tuple() v4 = (end_v + dir_v.rotate(45, as_degrees=True)).as_tuple() return [v1, v2, v3, v4]
def rect_from_line(line): """ Creates a rectangle from a line primitive by thickening it according to the primitive's aperture size. Treats rectangular apertures as square because otherwise the maths becomes too hard for my brain. """ r = get_aperture_size(line.aperture) / 2.0 start_v = V.from_tuple(line.start) end_v = V.from_tuple(line.end) dir_v = end_v - start_v # normalize direction vector abs_dir_v = abs(dir_v) if abs_dir_v: dir_v = dir_v / abs_dir_v else: dir_v = V(0, 0) # 45 degree angle means the vector pointing to the new rectangle edges has to be sqrt(2)*r long v_len = math.sqrt(2)*r # Give the direction vector the appropriate length dir_v *= v_len v1 = (start_v + dir_v.rotate(135, as_degrees=True)).as_tuple() v2 = (start_v + dir_v.rotate(-135, as_degrees=True)).as_tuple() v3 = (end_v + dir_v.rotate(-45, as_degrees=True)).as_tuple() v4 = (end_v + dir_v.rotate(45, as_degrees=True)).as_tuple() return [v1, v2, v3, v4]
def goal_coordinate(self): """Randomly choose the goal in the field so that the distance from the current coordinate follows Pareto distribution.""" length = pareto(self.scale, self.shape) theta = random.uniform(0, 2 * math.pi) goal = self.current + length * V(math.cos(theta), math.sin(theta)) # FIXME: the goal coordinate is simply limited by the field boundaries. # A node should *bounce back* with the boundaries. x = max(0, min(goal[0], self.width)) y = max(0, min(goal[1], self.height)) return V(x, y)
def setGravityDirection(self, stringDirection): """ A direction is set through direction naming: X, Y, Z """ if stringDirection.lower() == "x": self.gravityDirection = V(-1, 0, 0) pass if stringDirection.lower() == "y": self.gravityDirection = V(0, -1, 0) pass if stringDirection.lower() == "z": self.gravityDirection = V(0, 0, -1) pass return self.gravityDirection
def quiz10(): v1 = V([-7.579, -7.88]) w1 = V([22.737, 23.64]) v2 = V([-2.029, 9.97, 4.172]) w2 = V([-9.231, -6.639, -7.245]) v3 = V([-2.328, -7.284, -1.214]) w3 = V([-1.821, 1.072, -2.94]) v4 = V([2.118, 4.827]) w4 = V([0, 0]) if v1.is_orthogonal(w1): print("v1 is orthogonal with w1") if v1.is_parallel(w1): print("v1 is parallel with w1") if v2.is_orthogonal(w2): print("v2 is orthogonal with w2") if v2.is_parallel(w2): print("v2 is parallel with w2") if v3.is_orthogonal(w3): print("v3 is orthogonal with w3") if v3.is_parallel(w3): print("v3 is parallel with w3") if v4.is_orthogonal(w4): print("v4 is orthogonal with w4") if v4.is_parallel(w4): print("v4 is parallel with w4")
def mesh_from_obj(filename): vertices = [] texcoords = [] normals = [] indices = [] materials = [] ignore = False current_mtl = None for line in open(filename): line = line.strip('\r\n') if '#' in line: line = line[:line.index("#")] if not line: continue line = line.split(' ') if line[0] == "o": if line[1].startswith('background_') or line[1].startswith( 'marker_'): ignore = True else: ignore = False elif line[0] == "v": vertices.append(V(float(x) for x in line[1:])) elif line[0] == "vt": texcoords.append(V(float(x) for x in line[1:])) elif line[0] == "vn": normals.append(V(float(x) for x in line[1:])) elif line[0] == "mtllib": mtllib = parse_mtl( os.path.join(os.path.dirname(os.path.abspath(filename)), line[1])) elif line[0] == 'usemtl': current_mtl = line[1] elif line[0] == "f": if not ignore: indices.append( tuple( tuple( int(y) - 1 if y else None for y in (x.split('/') + ['', ''])[:3]) for x in line[1:])) materials.append(mtllib[current_mtl]) else: print line return Mesh(vertices, texcoords, normals, indices, materials)
def mesh_from_obj(file): vertices = [] texcoords = [] normals = [] indices = [] for line in file: line = line.strip() if '#' in line: line = line[:line.index("#")] if not line: continue line = line.split(' ') if line[0] == "v": vertices.append(V(float(x) for x in line[1:])) if line[0] == "vt": texcoords.append(V(float(x) for x in line[1:])) if line[0] == "vn": normals.append(V(float(x) for x in line[1:])) elif line[0] == "f": indices.append( tuple( tuple(int(y) - 1 if y else None for y in x.split('/')) for x in line[1:])) return Mesh(vertices, texcoords, normals, indices)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # create a grid topology g = graphtools.Graph(directed=False) self.graph = g g.create_graph('lattice', 2, self.size) # save the positions of vertices as Vector object for j in range(1, self.size + 1): for i in range(1, self.size + 1): v = g._lattice_vertex(2, self.size, i, j) x, y = ((0.5 + i - 1) / self.size * self.width, (0.5 + j - 1) / self.size * self.height) g.set_vertex_attribute(v, 'xy', V(x, y)) self.compute_edge_lengths()
def __init__(self, size=5, *args, **kwargs): self.size = size super().__init__(*args, **kwargs) # create a linear topology g = graphtools.Graph(directed=False) self.graph = g g.create_graph('lattice', 1, self.size) # save the positions of vertices as Vector object for v in range(1, self.size + 1): x, y = ((v - 0.5) / self.size * self.width, 0.5 * self.height) g.set_vertex_attribute(v, 'xy', V(x, y)) self.compute_edge_lengths()
def __init__(self, npoints=100, *args, **kwargs): self.npoints = npoints super().__init__(*args, **kwargs) # create a Voronoi topology g = graphtools.Graph(directed=False) self.graph = g g.create_graph('voronoi', self.npoints, self.width, self.height) # save the positions of vertices as Vector object for v in g.vertices(): x, y = g.get_vertex_attribute(v, 'pos').split(',') x, y = float(x), float(y) g.set_vertex_attribute(v, 'xy', V(x, y)) self.compute_edge_lengths()
def quiz8(): v1 = V([7.887, 4.138]) w1 = V([-8.802, 6.776]) v2 = V([3.183, -7.627]) w2 = V([-2.668, 5.319]) v3 = V([-5.955, -4.904, -1.874]) w3 = V([-4.496, -8.755, 7.103]) v4 = V([7.35, 0.221, 5.188]) w4 = V([2.751, 8.259, 3.985]) print(v1.dot_product(w1)) print(v2.angle_with(w2)) print(v3.dot_product(w3)) print(v4.angle_with(w4, True))
def quiz14(): try: v1 = V([8.462, 7.893, -8.187]) b1 = V([6.984, -5.975, 4.778]) v2 = V([-8.987, -9.838, 5.031]) b2 = V([-4.268, -1.861, -8.866]) v3 = V([1.5, 9.547, 3.691]) b3 = V([-6.007, 0.124, 5.772]) print("Cross prod of v1 and b1:") print(v1.cross_product_with(b1)) print("area of paralelogram:") print(v2.area_of_paralelogram_with(b2)) print("area of triangle:") print(v3.area_of_triangle_with(b3)) except Exception as e: print(e)
def quiz12(): v1 = V([3.039, 1.879]) b1 = V([0.825, 2.036]) v2 = V([-9.88, -3.264, -8.159]) b2 = V([-2.155, -9.353, -9.473]) v3 = V([3.009, -6.172, 3.692, -2.51]) b3 = V([6.404, -9.144, 2.759, 8.718]) print("Proj_b1 of v1 aka v1 parralel component:") print(v1.component_parallel_to(b1)) print("v2 orthogonal component:") print(v2.component_orthogonal_to(b2)) proj_b_v3 = v3.component_parallel_to(b3) print("v3 parallel component") print(proj_b_v3) orthogonal_v3 = v3.component_orthogonal_to(b3) print("v3 orthogonal component:") print(orthogonal_v3)
def random_coordinate(self): """Pick a random coordinate on the field.""" return V(random.uniform(0, self.width), random.uniform(0, self.height))
def rotate_vec(vec, m): x = numpy.dot((vec[0], vec[1], vec[2], 1), m) return V(x[:3]) / x[3]
def random_coordinate(self): """Pick a random coordinate on the field.""" x = random.uniform(self.xmin, self.xmax) y = random.uniform(self.ymin, self.ymax) return V(x, y)
def coordinate_for(self, n): """Return the coordinate of N-th agent. Agents are placed such that any pair of agents are not reachable.""" return V(n * NODE_SEPERATION, self.height / 2)
def update_velocity(self): """Update agent's velocity using the velocity function.""" vel = self.vel_func() theta = random.uniform(0, 2 * math.pi) self.velocity = vel * V(math.cos(theta), math.sin(theta)) self.wait = False
def draw(self): t = time.time() pos = V(numpy.linalg.inv(glGetFloatv(GL_MODELVIEW_MATRIX))[3, 0:3]) glClearColor(0, 0, 1, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_COLOR_MATERIAL) glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, [0, 0, 0, 1]) glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, [0, 0, 0, 1]) glLightfv(GL_LIGHT0, GL_POSITION, [math.sin(t / 5) * 100, math.cos(t / 5) * 100, 100, 1]) glLightfv(GL_LIGHT0, GL_AMBIENT, [0, 0, 0, 1]) glLightfv(GL_LIGHT0, GL_DIFFUSE, [.5, .5, .5, 1]) glLightfv(GL_LIGHT0, GL_SPECULAR, [.5, .5, .5, 1]) glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [.5, .5, .5]) glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) for obj in self.objs: obj.draw() ''' q = gluNewQuadric() for i in xrange(100): with GLMatrix: glColor3d(random.random(), random.random(), random.random()) glTranslate(*pos+5*V(random.gauss(0, 1) for i in xrange(3))) gluSphere(q, .5, 10, 5) ''' # sun with GLMatrix: glTranslate(math.sin(t / 5) * 100, math.cos(t / 5) * 100, 100) q = gluNewQuadric() glDisable(GL_LIGHTING) glColor3f(1, 1, 1) gluSphere(q, 10, 20, 20) glEnable(GL_LIGHTING) # water glDisable(GL_LIGHTING) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if pos[2] > 0: glBegin(GL_TRIANGLE_FAN) glNormal3f(0, 0, 1) glColor4f(0, 0, 0.5, 0.5) glVertex4f(pos[0], pos[1], min(0, pos[2] - 0.2), 1) glVertex4f(-1, -1, 0, 0) glVertex4f(+1, -1, 0, 0) glVertex4f(+1, +1, 0, 0) glVertex4f(-1, +1, 0, 0) glVertex4f(-1, -1, 0, 0) glEnd() else: glBegin(GL_TRIANGLE_FAN) glNormal3f(0, 0, -1) glColor4f(0, 0, 0.5, 0.5) glVertex4f(pos[0], pos[1], max(0, pos[2] + 0.2), 1) glVertex4f(-1, -1, 0, 0) glVertex4f(-1, +1, 0, 0) glVertex4f(+1, +1, 0, 0) glVertex4f(+1, -1, 0, 0) glVertex4f(-1, -1, 0, 0) glEnd() glDisable(GL_BLEND) glEnable(GL_LIGHTING) # underwater color if pos[2] < 0: glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glBegin(GL_QUADS) glColor4f(0, 0, 1, 0.1) glVertex3f(-1, -1, 0) glVertex3f(+1, -1, 0) glVertex3f(+1, +1, 0) glVertex3f(-1, +1, 0) glEnd() glDisable(GL_BLEND) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix()