def __init__(self, a=Point3D(), b=Point3D()): self.x = b.x - a.x self.y = b.y - a.y self.z = b.z - a.z if __debug__: print("# Vector3D constructor #")
def __init__(self, angle_X, angle_Y, angle_Z, win_width=1000, win_height=720): pygame.init() self.screen = pygame.display.set_mode((win_width, win_height)) pygame.display.set_caption( 'Simulation of rotating 3D Cube + Pyramid') self.screen.set_alpha(None) self.clock = pygame.time.Clock() move_to_center = 2 # Makes figure rotate over pyramid's top self.vertices = [ Point3D(move_to_center-1, 1, -1), Point3D(move_to_center+1, 1, -1), Point3D(move_to_center+1, -1, -1), Point3D(move_to_center-1, -1, -1), Point3D(move_to_center-1, 1, 1), Point3D(move_to_center+1, 1, 1), Point3D(move_to_center+1, -1, 1), Point3D(move_to_center-1, -1, 1), # Pyramid top Point Point3D(move_to_center-2, 0, 0), ] # Define the vertices that compose each of the 6 faces(sides). # These numbers are indices to the vertices list defined above self.faces = [ # Cube's sides (0, 1, 2, 3), (1, 5, 6, 2), (5, 4, 7, 6), (0, 4, 5, 1), (3, 2, 6, 7), # Pyramid's sides (8, 0, 4, 4), (8, 0, 3, 3), (8, 7, 3, 3), (8, 7, 4, 4) ] # Define colors for each face self.colors = [ # Pyramid's side colors (250, 0, 0), (210, 0, 0), (170, 0, 0), (130, 0, 0), (90, 0, 0), # Pyramid's side colors (0, 250, 0), (0, 180, 0), (0, 110, 0), (0, 30, 0), ] # Starting angles self.angleX = 0 self.angleY = 0 self.angleZ = 0 # Value which will update angle on each iteration self.angle_rotation_X = angle_X self.angle_rotation_Y = angle_Y self.angle_rotation_Z = angle_Z
def getColor(ray, originObject, recursionLimit): if recursionLimit <= 0: return Vector(0, 0, 0) [t, collisionObjectIndex] = hitDistance(ray, originObject) if collisionObjectIndex != -1: object = spheres[collisionObjectIndex] collisionPoint = Point3D.fromVector( ray.direction.toScaled(t).plus(camera.origin.vector)) normalDirection = collisionPoint.minus(object.center) normal = normalDirection.toNormalized() ambient = Vector(30, 30, 30) diffuse = Vector(0, 0, 0) for light in lights: lightDiffuse = Vector(0, 0, 0) toLight = light.direction.toScaled(-1) product = toLight.dot(normal) if product < 0: product = 0 lightDiffuse = light.color.toScaled(product) diffuse = diffuse.plus(lightDiffuse) color = ambient.plus(diffuse) return color else: return Vector(0, 0, 0)
def hang_operation(self, op): to_ = op[0].id reply = Oplist() loc_ = Location(self.id, Point3D(2.5,2.5,3)) reply.append(Operation("move",Entity(to_,location=loc_,mode="hanging"),to=to_)) reply.append(Operation("reveal",Entity(to_),to=to_)) # Send op to target which makes it reveal its true nature, and then die return reply
def __init__(self, material: Material, vertex1: Point3D, vertex2: Point3D, vertex3: Point3D): SceneObject.__init__(self, material) self.vertex1 = vertex1 self.vertex2 = vertex2 self.vertex3 = vertex3 self.center = Point3D((self.vertex1.vector.x + self.vertex2.vector.x + self.vertex3.vector.x) / 3, (self.vertex1.vector.y + self.vertex2.vector.y + self.vertex3.vector.y) / 3, (self.vertex1.vector.z + self.vertex2.vector.z + self.vertex3.vector.z) / 3)
def intersect(self, ray: Ray): # Finding the lines between points #U ab = Point3D.minus(self.vertex2, self.vertex1) #V ac = Point3D.minus(self.vertex3, self.vertex1) #Calc normal #n = Point3D(0, 0, 0) #a #n.x = (ab.y * ac.z) - (ab.z * ac.y) #b #n.y = (ab.z * ac.x) - (ab.x * ac.z) #c #n.z = (ab.x * ac.y) - (ab.y * ac.x) n = Vector.cross(ab, ac) #Calculating the intersection d = Vector.dot(n, self.vertex1.vector) #print(Vector.dot(n.vector, ray.direction)) if (Vector.dot(n, ray.direction) != 0): t = -(Vector.dot(n, ray.origin.vector) + d) / Vector.dot( n, ray.direction) else: return -999 if t < 0: return -999 else: p = Point3D(0, 0, 0) p.vector.x = ray.origin.vector.x + (t * d) p.vector.y = ray.origin.vector.y + (t * d) p.vector.z = ray.origin.vector.z + (t * d) #Find ABC by taking two of the lines formed from the triangle normalize them and take the cross product #Inside-Out #Checking left side newEdge1 = Point3D.minus(p, self.vertex1) E1 = Vector.cross(ab, newEdge1) if Vector.dot(n, E1) < 0: return -999 #Checking Right side newEdge2 = Point3D.minus(p, self.vertex2) E2 = Vector.cross(ac, newEdge2) if Vector.dot(n, E2) < 0: return -999 bc = Point3D.minus(self.vertex3, self.vertex2) newEdge3 = Point3D.minus(p, self.vertex3) E3 = Vector.cross(bc, newEdge3) if Vector.dot(n, E3) < 0: return -999 return t
def getColor(ray, originObject, recursionLimit): if recursionLimit <= 0: return Vector(0, 0, 0) [t, collisionObjectIndex] = hitDistance(ray, originObject) if collisionObjectIndex != -1: object = objects[collisionObjectIndex] collisionPoint = Point3D.fromVector( ray.direction.toScaled(t).plus(camera.origin.vector)) normalDirection = collisionPoint.minus(object.center) normal = normalDirection.toNormalized() ambient = Vector(30, 30, 30) diffuse = Vector(0, 0, 0) for light in lights: toLight = light.direction.toScaled(-1) [t2, shadowObjectIndex] = hitDistance(Ray(collisionPoint, toLight), object) if shadowObjectIndex == -1: lightDiffuse = Vector(0, 0, 0) product = toLight.dot(normal) if product < 0: product = 0 lightDiffuse = light.color.toScaled(product) lightDiffuse = lightDiffuse.simpleMultiply( object.material.diffuseColor) lightDiffuse = lightDiffuse.toScaled(1 / 255) diffuse = diffuse.plus(lightDiffuse) # Needs: # Normal # Incoming direction (ray.direction) # Want reflective direction reflectiveDirection = ray.direction.toScaled(-1).reflectAbout( normal) reflectionRay = Ray(collisionPoint, reflectiveDirection) reflectionColor = getColor(reflectionRay, object, recursionLimit - 1) color = ambient.plus( diffuse.toScaled(1 - object.material.reflectivity)).plus( reflectionColor.toScaled(object.material.reflectivity)) return color else: return sampleBackground(ray.direction)
def __init__(self, name, coords): self.name = name coord = re.findall(r'[-0-9]+', coords) self.position = Point3D(int(coord[0]), int(coord[1]), int(coord[2])) self.velocity = Point3D(0, 0, 0)
# https://stackoverflow.com/questions/138250/how-to-read-the-rgb-value-of-a-given-pixel-in-python/50894365 backgroundWidth, backgroundHeight, backgroundRows, backgroundMeta = background.read_flat() backgroundPixelByteWidth = 4 if backgroundMeta['alpha'] else 3 # Minimum for a ray tracer # A frame to render to # A camera # A light # An object to render frame = Frame(256, 256) cameraOrigin = Point3D(0, 0, 1) origin = Point3D(0, 0, 0) cameraLookAt = Point3D(0, 0, 0) cameraUp = Vector(0, 1, 0) cameraBackgroundColor = Vector(0, 0, 0) # convert 45 degrees to radians. Should result in pi/4 ~= .785 fov = 45 / 360 * math.pi * 2 raysPerPixel = 1 focusPoint = 0 camera = PerspectiveCamera(cameraOrigin, cameraLookAt, cameraUp, cameraBackgroundColor, raysPerPixel, focusPoint, fov) lightDirection = Vector(0, -1, 0) lightColor = Vector(255, 255, 255)
# Return the sign of x (0 if x is 0). if x > 0: # x positive return 1 elif x < 0: # x negative return -1 else: # x zero return 0 def get_random_point(x0, x1, y0, y1, z0, z1): # return a Point3D object with random coordinates within the given x,y,z intervals. return Point3D(randint(x0, x1), randint(y0, y1), randint(z0, z1)) if __name__ == "__main__": factory_size = Point3D(5, 5, 5) # people[0] = Person("Candice", (3, 4, 0), (2, 0, 1)) # people[1] = Person("Andy", (4, 3, 0), (4, 3, 1)) # people[2] = Person("Belle", (1, 3, 4), (3, 1, 1)) # people[3] = Person("Cecily", (1, 3, 4), (3, 0, 1)) # people[4] = Person("Angela", (1, 0, 1), (4, 2, 1)) # people[5] = Person("Thornton", (2, 3, 2), (0, 1, 4)) # people[6] = Person("Sheryl", (0, 1, 0), (1, 0, 1)) # people[7] = Person("Benny", (2, 1, 2), (2, 1, 3)) # create the elevator people = [ ("Name:Candice", "cur:" <4, 0, 2>, "dst:"<4, 0, 3>), ("Name:Murray", "cur:"<3, 2, 4>, "dst:"<4, 1, 4>), ('Name:Belle', 'cur:'<2, 2, 2>, 'dst:'<2, 2, 0>), ('Name:Cecily', 'cur:' <3, 0, 1>, 'dst:'<2, 1, 0>),
import pytest from Point3D import Point3D from Moons import Moons test_moons = [("test1.txt", [("Io", Point3D(-1, 0, 2)), ("Europa", Point3D(2, -10, -7)), ("Ganymede", Point3D(4, -8, 8)), ("Callisto", Point3D(3, 5, -1))]), ("test2.txt", [("Io", Point3D(-8, -10, 0)), ("Europa", Point3D(5, 5, 10)), ("Ganymede", Point3D(2, -7, 3)), ("Callisto", Point3D(9, -8, -3))])] total_energy_data = [("test1.txt", 10, 179), ("test2.txt", 100, 1940)] move_moons_data = [("test1.txt", 1, [ Point3D(2, -1, 1), Point3D(3, -7, -4), Point3D(1, -7, 5), Point3D(2, 2, 0) ]), ("test1.txt", 10, [ Point3D(2, 1, -3), Point3D(1, -8, 0), Point3D(3, -6, 1), Point3D(2, 0, 4) ]), ("test2.txt", 100, [ Point3D(8, -12, -9), Point3D(13, 16, -3), Point3D(-29, -11, -1),
print("Starting our ray tracer") # Minimum for a ray tracer # A frame to render to # A camera # A light # An object to render red = random.randrange(255) green = random.randrange(255) blue = random.randrange(255) frame = Frame(256, 256) cameraOrigin = Point3D(0, 0, 1) origin = Point3D(0, 0, 0) cameraLookAt = origin cameraUp = Vector(0, 1, 0) cameraBackgroundColor = Vector(0, 0, 0) fov = 45 / 360 * math.pi * 2 # convert 45 degrees to radians. Should result in pi/4 ~= .785 camera = Camera(cameraOrigin, cameraLookAt, cameraUp, fov, cameraBackgroundColor) lightDirection = Vector(0, -1, 0) lightDirection2 = Vector(0, 1, 0) lightColor = Vector(red, green, blue) light = DirectionalLight(lightColor, 10, lightDirection) light2 = DirectionalLight(lightColor, 10, lightDirection2)
def get_random_point(x0, x1, y0, y1, z0, z1): # return a Point3D object with random coordinates within the given x,y,z intervals. return Point3D(randint(x0, x1), randint(y0, y1), randint(z0, z1))
def main(): # Шаги сетки по осям Ox, Oy dx, dy = 0.1, 0.1 # Количество узлов сетки по осям Ox, Oy N = 100 M = 30 # Формируем матрицу N на M как массив массивов и инициализируем нулевыми значениями grid = [[0 for x in range(M)] for y in range(N)] # Формируем карту местности с помощью функции, задающей двумерную поверхность for i in range(N): for j in range(M): grid[i][j] = SC(i * dx, j * dy) # Координаты конца неизвестного маршрута, который необходимо продолжить N_ = 98 M_ = 16 # Первая точка маршрута currentOptimalPoint = Point3D(N_, M_, grid[N_][M_], 0) # Временный список и список для хранения искомого оптимального пути tempPnts, optimalPath = [], [] # Добавляем в список с искомым маршрутом первую точку, которая уже известна optimalPath.append(currentOptimalPoint) # Основной цикл поиска оптимального пути for i in reversed(range(N_)): M_ = currentOptimalPoint.M if (M_ == 0): tempPnts.append(Point3D(i, 0, grid[i][0], 0)) tempPnts.append(Point3D(i, 1, grid[i][1], 1)) elif (M_ == M - 1): tempPnts.append(Point3D(i, M - 1, grid[i][M - 1], 0)) tempPnts.append(Point3D(i, M - 2, grid[i][M - 2], 1)) else: tempPnts.append(Point3D(i, M_ - 1, grid[i][M_ - 1], 1)) tempPnts.append(Point3D(i, M_, grid[i][M_], 0)) tempPnts.append(Point3D(i, M_ + 1, grid[i][M_ + 1], 1)) indexOfMin = 0 minDistancePlusTangentSquare = GetSquareOfDistance( currentOptimalPoint, tempPnts[indexOfMin], dy) + GetTangentSquare( currentOptimalPoint, tempPnts[indexOfMin], dx, dy) for k in range(1, len(tempPnts)): temp = GetSquareOfDistance( currentOptimalPoint, tempPnts[k], dy) + GetTangentSquare( currentOptimalPoint, tempPnts[k], dx, dy) if (temp < minDistancePlusTangentSquare): indexOfMin = k minDistancePlusTangentSquare = temp currentOptimalPoint = tempPnts[indexOfMin] optimalPath.append(currentOptimalPoint) tempPnts.clear() # Записываем данные в текстовый файл fileName = "C:\\Users\\Admin\\Documents\\optimalPathPython.txt" with open(fileName, "w") as file: for point in optimalPath: file.write( str(round(point.N * dx, 2)) + " " + str(round(point.M * dy, 2)) + " " + str(point.z) + "\n") file.close()
def __init__(self, p1=Point3D(), p2=Point3D(), color = WHITE, thickness = 1): self.p1 = p1 self.p2 = p2 self.color = color self.thickness = thickness
def __init__(self, angle_X, angle_Y, angle_Z, win_width=1000, win_height=720): pygame.init() self.screen = pygame.display.set_mode((win_width, win_height)) pygame.display.set_caption('Simulation of rotating two prisms') self.screen.set_alpha(None) self.clock = pygame.time.Clock() offset_x = -1 offset_y = -1 self.vertices = [ Point3D(1 + offset_x, 0, 1 + offset_y), Point3D(1 + offset_x, 0, -1 + offset_y), Point3D(1.2 + offset_x, -0.5, 0 + offset_y), Point3D(1.2 + offset_x, 0.5, 0 + offset_y), Point3D(-1 + offset_x, 0, 1 + offset_y), Point3D(-1 + offset_x, 0, -1 + offset_y), Point3D(-1.2 + offset_x, -0.5, 0 + offset_y), Point3D(-1.2 + offset_x, 0.5, 0 + offset_y), ] # Define the vertices that compose each of the 6 faces(sides). # These numbers are indices to the vertices list defined above self.faces = [ (0, 0, 2, 3), (1, 1, 2, 3), (4, 4, 6, 7), (5, 5, 6, 7), (0, 3, 7, 4), (0, 2, 6, 4), (1, 3, 7, 5), (1, 2, 6, 5), ] # Define colors for each face self.colors = [ (250, 0, 0), (210, 0, 0), (170, 0, 0), (130, 0, 0), (0, 250, 0), (0, 180, 0), (0, 110, 0), (0, 70, 0), ] # Starting angles self.angleX = 0 self.angleY = 0 self.angleZ = 0 # Value which will update angle on each iteration self.angle_rotation_X = angle_X self.angle_rotation_Y = angle_Y self.angle_rotation_Z = angle_Z
def __init__(self, factory_size): # class constructor # 1) current elevator position in structure self.cur_pos = Point3D(0, 0, 0) # calling class Point3D self.factory_size = factory_size # 2) the dimension of the structure/factory self.people_in_elevator = [ ] # 3) the list of people currently in the elevator