示例#1
0
 def test_filtering_list_intersections(self):
     s1 = Sphere()
     s2 = Cube()
     Operation = namedtuple("Operation", ["operation", "x0", "x1"])
     operatios = [
         Operation("union", 0, 3),
         Operation("intersection", 1, 2),
         Operation("difference", 0, 1)
     ]
     for operation in operatios:
         c = CSG(operation.operation, s1, s2)
         xs = Intersection.intersections(Intersection(1, s1), Intersection(2, s2), Intersection(3, s1), Intersection(4, s2))
         result = c.filter_intersections(xs)
         self.assertEqual(len(result), 2)
         self.assertEqual(result[0], xs[operation.x0])
         self.assertEqual(result[1], xs[operation.x1])
def test_logarithmic_map():
    p0 = np.array([[np.cos(0.), np.sin(0.)], [np.cos(0.),
                                              np.sin(0.)],
                   [np.cos(0.5 * np.pi),
                    np.sin(0.5 * np.pi)], [np.cos(np.pi),
                                           np.sin(np.pi)]])
    p1 = np.array([[1., 0.], [0.707106781186548, 0.707106781186548],
                   [0.707106781186548, 0.707106781186548],
                   [-0.707106781186548, 0.707106781186548]])
    expected = np.array([[0., 0.], [0., 0.25 * np.pi], [0.25 * np.pi, 0.],
                         [0., 0.25 * np.pi]])

    circle = Sphere(1)
    print("")
    print(circle.logarithmic_map(p0, p1))
    print(expected)
    assert_array_almost_equal(circle.logarithmic_map(p0, p1), expected)
示例#3
0
    def initUI(self):

        self.master.title("ray tracing test")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_rectangle((5, 5)*2,
            outline="", fill="#8c8c8c")
        
        #  def __init__(self, origin: Vec3, focal_length: float, view_dir: Vec3, l: int, r: int, b: int, t: int):
        cam_pos = Vec3(0,10,-20)
        cam_dir = Vec3(0,1,0.1)
        cam = Camera(cam_pos, 100, cam_dir, -WIDTH//2, WIDTH//2, -HEIGHT//2, HEIGHT//2)
        objects = []

        # sphere = Sphere(Vec3(0, 100, 0), 50)
        objects.append(Sphere(Vec3(0, 100, 0), 50))
        objects.append(Sphere(Vec3(-12, 60, -20), 10))
        objects.append(Sphere(Vec3(-12, 60, 20), 10))
        objects.append(Sphere(Vec3(12, 60, 20), 10))
        objects.append(Sphere(Vec3(-12, 80, 40), 10))
        objects.append(Triangle(Vec3(0, 60, -30), Vec3(40, 60, -20), Vec3(10, 60, 10)))
        objects.append(Triangle(Vec3(0, 60, -30), Vec3(10, 40, -50), Vec3(40, 60, -20)))

        objects.append(Sphere(Vec3(-35, 34, 34), 5))

        objects.append(Triangle(Vec3(-50, 20, -80), Vec3(50, 20, -80), Vec3(-50, 200, -80)))
        objects.append(Triangle(Vec3(50, 20, -80), Vec3(50, 200, -80), Vec3(-50, 200, -80)))

        objects.append(Triangle(Vec3(-50, 20, 100), Vec3(-50, 200, 100), Vec3(50, 20, 100)))
        objects.append(Triangle(Vec3(50, 20, 100), Vec3(-50, 200, 100), Vec3(50, 200, 100)))

        for i in range(0, WIDTH):
            for j in range(0, HEIGHT):
                ray = cam.compute_ray(i, j, WIDTH, HEIGHT)

                Lr, Lg, Lb = rayColor(ray, objects, 0, None)

                Lr = hex(Lr)[2:]
                Lg = hex(Lg)[2:]
                Lb = hex(Lb)[2:]
                
                if len(Lr) == 1:
                    Lr = '0'+ Lr
                if len(Lg) == 1:
                    Lg = '0'+ Lg
                if len(Lb) == 1:
                    Lb = '0'+ Lb
                
                hex_fill = '#' + Lr + Lg + Lb
                canvas.create_rectangle((i, j)*2, outline="", fill=hex_fill)

        canvas.pack(fill=BOTH, expand=1)
示例#4
0
def random_scene():
    lista = list()
    lista.append(
        Sphere(
            np.array((0, -1000, 0)), 1000,
            material.lambertian(
                checker_texture(constant_texture(np.array((0.2, 0.3, 1))),
                                constant_texture(np.array((0.9, 0.9, 0.9)))))))

    for a in range(-11, 11):
        for b in range(-11, 11):
            choose_mat = random()
            center: np.ndarray = np.array(
                (a + 0.9 * random(), 0.2, b + 0.9 * random()))
            if np.linalg.norm(center - np.array((4.0, 0.2, 0.0))) > 0.9:
                if choose_mat < 0.8:  # diffuse
                    lista.append(
                        Sphere(
                            center, 0.2,
                            material.lambertian(
                                constant_texture(
                                    np.array((random() * random(),
                                              random() * random(),
                                              random() * random()))))))
                elif choose_mat < 0.95:  # metal
                    lista.append(
                        Sphere(
                            center, 0.2,
                            material.metal(
                                np.array((0.5 * (1 + random()),
                                          0.5 * (1 + random()),
                                          0.5 * (1 + random()))),
                                0.5 * random())))

                else:
                    lista.append(Sphere(center, 0.2, material.dielectric(1.5)))

    lista.append(Sphere(np.array((0, 1, 0)), 1, material.dielectric(1.5)))
    lista.append(
        Sphere(
            np.array((-4, 1, 0)), 1,
            material.lambertian(constant_texture(np.array((0.4, 0.2, 0.1))))))
    lista.append(
        Sphere(np.array((4, 1, 0)), 1,
               material.metal(np.array((0.7, 0.6, 0.5)), 0.0)))

    return hitable_list(lista)
示例#5
0
 def test_shade_hit_with_transparent_material(self):
     w = World.default_world()
     floor = Plane()
     floor.transform = Transformations.translation(0, -1, 0)
     floor.material.transparency = 0.5
     floor.material.refractive_index = 1.5
     w.objects.append(floor)
     ball = Sphere()
     ball.material.color = Color(1, 0, 0)
     ball.material.ambient = 0.5
     ball.transform = Transformations.translation(0, -3.5, -0.5)
     w.objects.append(ball)
     r = Ray(Point(0, 0, -3), Vector(0, -math.sqrt(2) / 2,
                                     math.sqrt(2) / 2))
     xs = Intersection.intersections(Intersection(math.sqrt(2), floor))
     comps = Computations.prepare_computations(xs[0], r, xs)
     color = World.shade_hit(w, comps, 5)
     self.assertEqual(color, Color(0.93642, 0.68642, 0.68642))
示例#6
0
    def run(self, method=None):
        if method == constants.HM_MDA:
            from midpointDisplacement import MDA
            heightObject = MDA(self.size, self.roughness)
        elif method == constants.HM_DSA:
            from diamondSquare import DSA
            heightObject = DSA(self.size)
        elif method == constants.HM_SPH:
            from sphere import Sphere
            heightObject = Sphere(self.size, self.roughness)
        elif method == constants.HM_PERLIN:
            from perlinNoise import Perlin
            heightObject = Perlin(self.size)
        else:
            print "No method for generating heightmap found!"

        heightObject.run()
        self.heightmap = heightObject.heightmap
        del heightObject
示例#7
0
def main():
    global window
    global sphere
    global camera

    camera = Camera()
    sphere = Sphere()

    glutInit(sys.argv)

    # Select type of Display mode:
    #  Double buffer
    #  RGBA color
    # Alpha components supported
    # Depth buffer
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)

    # get a 640 x 480 window
    glutInitWindowSize(640, 480)

    # the window starts at the upper left corner of the screen
    glutInitWindowPosition(0, 0)
    window = glutCreateWindow("CENG487 Template")

    # Display Func
    glutDisplayFunc(DrawGLScene)

    # When we are doing nothing, redraw the scene.
    glutIdleFunc(DrawGLScene)

    # Register the function called when our window is resized.
    glutReshapeFunc(ReSizeGLScene)

    # Register the function called when the keyboard is pressed.
    glutKeyboardFunc(keyPressed)

    glutMouseFunc(mousePressed)

    # Initialize our window.
    InitGL(640, 480)

    # Start Event Processing Engine
    glutMainLoop()
示例#8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("imageout", help="Path to the rendered image")
    args = parser.parse_args()
    WIDTH = 320
    HEIGHT = 200
    camera = Vector(0, 0, -1)

    objects = [
        Sphere(Point(0, 0, 0), 0.5, Material(Color.from_hex("#FF0000"))),
    ]
    lights = [Light(Point(1.5, -0.5, -10.0), Color.from_hex("#FFFFFF"))]
    scene = Scene(camera, objects, lights, WIDTH, HEIGHT)
    engine = RenderEngine()

    image = engine.render(scene)

    with open(args.imageout, "w+") as f:
        image.write_ppm(f)
class ThreeDimensionalObjectFactory:

    obj_list = [Sphere(), RegularOctahedron()]

    @classmethod
    def get_menu(cls):
        menu = ''
        for idx in range(len(cls.obj_list)):
            menu += '{0}.\t {1}\n'.format(idx + 1, cls.obj_list[idx].name)
        return menu

    @classmethod
    def create(cls, name):
        if name == '1' or name == Sphere().name:
            return Sphere()
        elif name == '2' or name == RegularOctahedron().name:
            return RegularOctahedron()
        else:
            raise VolumeCalculatorException(name + ' は無効です.')
示例#10
0
 def showNormals(s,figm=None,algo='sobel',color=(1,0,0),as2D=False):
   s.getNormals(algo)
   if as2D:
     if figm is None:
       figm = plt.figure()
     I = (s.n.copy()+1.0)*0.5 # make non negative
     I[np.logical_not(s.mask),0] = 0.;
     I[np.logical_not(s.mask),1] = 0.;
     I[np.logical_not(s.mask),2] = 0.;
     plt.imshow(I)
   else:
     if figm is None:
       figm = mlab.figure(bgcolor=(1,1,1)) 
     M = Sphere(2)
     M.plotFanzy(figm,1.0,linewidth=1)
     mlab.points3d(s.n[s.mask,0],s.n[s.mask,1],s.n[s.mask,2],
         scale_factor=0.01, color=color, figure=figm, 
         mode='point',mask_points=1)
   return figm
def test_parallel_transport():
    p0 = np.array([[np.cos(0.), np.sin(0.)], [np.cos(0.),
                                              np.sin(0.)],
                   [np.cos(0.5 * np.pi),
                    np.sin(0.5 * np.pi)], [np.cos(np.pi),
                                           np.sin(np.pi)]])
    p1 = np.array([[1., 0.], [1., 0.], [0.707106781186548, 0.707106781186548],
                   [np.cos(0.), np.sin(0.)]])
    v = np.array([[0., 0.], [0., 0.25 * np.pi], [1, 0.], [0., 0.25 * np.pi]])
    expected = np.array([[0., 0.], [0., 0.25 * np.pi],
                         [0.707106781186548, -0.707106781186548],
                         [0., 0.25 * np.pi]])
    # Care should be taken when transporting to antipodes.
    # In this case, the sign of v_y is incorrect.

    circle = Sphere(1)
    print("")
    result = circle.parallel_transport(v, p0, p1)
    print(result)
    assert_array_almost_equal(result, expected)  #, decimal=
    def __init__(self, width, height, fft_mode=False):
        super(Visual_Music_Player, self).__init__(width,
                                                  height,
                                                  fullscreen=False)

        self.width = width
        self.height = height
        self.fft_mode = fft_mode
        self.window_batch = pyglet.graphics.Batch()
        self.grid = None
        self.audio_parser = None
        self.feature_buffer = None
        self.feature_buffer_size = 16

        #currently we're sticking to using a sphere
        self.surface_geometry = Sphere(16)

        #move this to an RBM class
        self.r = RBM(num_visible=128, num_hidden=32)
        self.r2 = RBM(num_visible=32, num_hidden=4)
def test__pole_ladder_transport():
    p0 = np.array([[np.cos(0.), np.sin(0.)], [np.cos(0.),
                                              np.sin(0.)],
                   [np.cos(0.5 * np.pi),
                    np.sin(0.5 * np.pi)], [np.cos(np.pi),
                                           np.sin(np.pi)]])
    p1 = np.array([[1., 0.], [1., 0.], [0.707106781186548, 0.707106781186548],
                   [np.cos(0.), np.sin(0.)]])
    v = np.array([[0., 0.], [0., 0.25 * np.pi], [1, 0.], [0., 0.25 * np.pi]])
    expected = np.array([[0., 0.], [0., 0.25 * np.pi],
                         [0.707106781186548, -0.707106781186548],
                         [0., 0.75 * np.pi]])
    # Care should be taken when pole transporting between antipodes in one step!
    # v seems to lengthen!

    circle = Sphere(1)
    print("")
    print(circle._pole_ladder_transport(v, p0, p1))
    assert_array_almost_equal(circle._pole_ladder_transport(v, p0, p1),
                              expected)
示例#14
0
def run():
    window_surface = pygame.display.set_mode((400, 400))
    sphere = Sphere(Point(0, 0, 0), radius=1.)
    view_point = ViewPoint(Point(0, 0, -5.1))
    pixels = pygame.PixelArray(window_surface)
    image = Image(Rectangle(Point(-1, -1, -4.1), Vector(0.005, 0., 0.), Vector(0, 0.005, 0.)), pixels)
    ray_generator = RayGenerator(view_point, image)
    rays = ray_generator.generate()

    theta, phi = 0. , 0.
    light_source = LightSource(Vector(math.sin(theta)*math.cos(phi), math.sin(theta)*math.sin(phi), math.cos(theta)), 0.5)

    ray_intersector = RaySphereIntersector(sphere, view_point.point().as_vector())
    ray_shader = RayShader()

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    theta += 0.1
                if event.key == pygame.K_UP:
                    theta -= 0.1
                if event.key == pygame.K_LEFT:
                    phi -= 0.1
                if event.key == pygame.K_RIGHT:
                    phi += 0.1


        window_surface.fill((0, 0, 0,))

        draw(rays, ray_intersector, ray_shader, light_source, sphere, image)
        light_source = LightSource(
            Vector(math.sin(theta) * math.cos(phi), math.sin(theta) * math.sin(phi), math.cos(theta)), 0.5)
        pygame.display.flip()

        print("theta " + str(theta))
        print("phi " + str(phi))
        print(" ")
def test_is_in_tangent_space():
    p = np.array([
        [np.cos(0.), np.sin(0.)],
        [np.cos(0.), np.sin(0.)],
        [np.cos(0.), np.sin(0.)],
        [np.cos(0.), np.sin(0.)],
        [np.cos(0.25 * np.pi), np.sin(0.25 * np.pi)],
        [np.cos(0.25 * np.pi), np.sin(0.25 * np.pi)],
    ])
    v = np.array([[0., 0.], [1., 0.], [0., 1.], [0., -1.], [1., 1.],
                  [0.707106781186548, -0.707106781186548]])
    expected = np.array([
        [True],
        [False],
        [True],
        [True],
        [False],
        [True],
    ])
    circle = Sphere(1)
    assert_array_almost_equal(circle.is_in_tangent_space(p, v), expected)
示例#16
0
def main() -> None:
    pg.init()
    pg.display.set_caption("Sphere")
    screen = pg.display.set_mode((const.WIDTH, const.HEIGHT))
    screen.fill(const.WHITE)
    clock = pg.time.Clock()

    sphere = Sphere(size=(const.WIDTH, const.HEIGHT))

    running = True
    while running:
        screen.fill(const.WHITE)
        clock.tick(const.FPS)

        screen.blit(sphere, (0, 0))

        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False

        sphere.update()
        pg.display.flip()
def get_hit_point_draw(combined_ray, linecolor):
    start = np.array([0.0, 0.0, 0.0])

    rot = np.array([0.0, 1.0, 0, 0.0])
    # rotate a vector by quaternion rotation
    dir = rotate_vec_by_quaternion(rot, combined_ray)
    end = start + dir

    #get hitting point
    sphere = Sphere(Point3(0, 0, 0), 1)
    ray = Ray3(Point3(start[0], start[1], start[2]),
               Vector3(dir[0], dir[1], dir[2]))
    hitpoint = sphere.intersect(ray)

    #check if hitting point is on sphere surface
    # check_point_on_sphere(0, 0, 0, hitpoint, 1)

    # convert unity coordinate to python coordinate
    unity_to_python_point(start)
    unity_to_python_point(end)
    unity_to_python_point(hitpoint)

    return hitpoint
    def test_shade_hit_with_reflective_transparent_material(self):
        w = World()
        r = Ray(Point(0, 0, -3), Vector(0, -sqrt(2)/2, sqrt(2)/2))

        floor = Plane()
        floor.set_transform(translate(0, -1, 0))
        floor.material.reflective = 0.5
        floor.material.transparency = 0.5
        floor.material.refractive_index = 1.5
        w.objs.append(floor)

        ball = Sphere()
        ball.material.color = Color(1, 0, 0)
        ball.material.ambient = 0.5
        ball.set_transform(translate(0, -3.5, -0.5))
        w.objs.append(ball)

        ls = [Intersection(sqrt(2), floor)]
        xs = Intersections(ls)
        comps = xs[0].prepare_computations(r, xs)
        color = w.shade_hit(comps, 5)
        # print(color)
        self.assertTrue(Color(0.93391, 0.69643, 0.69243) == color)
    def test_shade_hit_with_transparent_material(self):
        
        w = World()
        floor = Plane()
        floor.set_transform(translate(0, -1, 0))
        floor.material.transparency = 0.5
        floor.material.refractive_index = 1.5

        ball = Sphere()
        ball.material.color = Color(1., 0., 0.)
        ball.material.ambient = 0.5
        ball.set_transform(translate(0, -3.5, -0.5))

        w.objs = [floor, ball]

        r = Ray(Point(0, 0, -3), Vector(0, -sqrt(2)/2, sqrt(2)/2))

        ls = [Intersection(sqrt(2), floor)]
        xs = Intersections(ls)

        comps = xs[0].prepare_computations(r, xs)
        color = w.shade_hit(comps, 5)
        self.assertTrue(Color(0.93642, 0.68642, 0.68642) == color)
示例#20
0
def randomScene(no_of_spheres,
                world_space=3.0,
                min_radius=0.35,
                max_radius=0.5):
    materials = []
    spheres = []
    for i in range(0, no_of_spheres):
        temp = int(random() * 2)
        if temp == 0:
            materials.append(Lambert(Vec3(random(), random(), random())))
        elif temp == 1:
            materials.append(
                Metal(Vec3(random(), random(), random()),
                      random() * 0.7))
    for i in range(0, no_of_spheres):
        x = (random() * 2 - 1) * world_space
        y = (random() * 2 - 1) * world_space * 0.4
        z = (random() * 2 - 1) * world_space
        r = uniform(min_radius, max_radius)
        print(x, y, z, r)
        spheres.append(Sphere(Vec3(x, y, z), r, materials[i]))
    print(len(spheres))
    return spheres
    def test_circle_initialization_str_repr_and_properties(self):
        s1 = Sphere(10)
        s2 = Sphere.from_diameter(40)
        assert type(s2) == Sphere
        self.assertEqual(s1.radius, 10.0)
        self.assertEqual(s1.diameter, 20.0)
        self.assertEqual(s2.radius, 20.0)
        self.assertEqual(s2.diameter, 40.0)
        s1.radius = 30
        self.assertEqual(s1.diameter, 60.0)
        s2.diameter = 30
        self.assertEqual(s2.radius, 15.0)

        self.assertEqual(str(s1), "Sphere with radius: 30.000")
        self.assertEqual(repr(s1), "Sphere(30.0)")
        self.assertEqual(round(s1.area), 11310)
        with pytest.raises(AttributeError) as error:
            s1.area = 50
            assert "AttributeError: can't set attribute" in error

        self.assertEqual(round(s1.volume), 113097)
        with pytest.raises(AttributeError) as error:
            s1.volume = 50
            assert "AttributeError: can't set attribute" in error
示例#22
0
def random_scene():
    """Generate a random scene."""

    result = []
    sphere = Sphere(Vec3(0, -1000, 0), 1000, Lambertian(Vec3(0.5, 0.5, 0.5)))
    result.append(sphere)

    for a in range(-11, 11):
        for b in range(-11, 11):
            choose_mat = random()
            center = Vec3(a + 0.9 * random(), 0.2, b + 0.9 * random())
            if (center - Vec3(4, 0.2, 0)).length > 0.9:
                if choose_mat < 0.8:
                    # make diffuse
                    sphere = Sphere(
                        center, 0.2,
                        Lambertian(
                            Vec3(random() * random(),
                                 random() * random(),
                                 random() * random())))
                elif choose_mat < 0.95:
                    # make metallic
                    sphere = Sphere(
                        center, 0.2,
                        Metal(
                            Vec3(0.5 * (1 + random()), 0.5 * (1 + random()),
                                 0.5 * (1 + random())), 0.5 * random()))
                else:
                    # make glassy
                    sphere = Sphere(center, 0.2, Dielectric(1.5))
                result.append(sphere)

    result.append(Sphere(Vec3(0, 1, 0), 1.0, Dielectric(1.5)))
    result.append(Sphere(Vec3(-4, 1, 0), 1.0, Lambertian(Vec3(0.4, 0.2, 0.1))))
    result.append(Sphere(Vec3(4, 1, 0), 1.0, Metal(Vec3(0.7, 0.6, 0.5), 0.0)))

    return Hitable_List(result)
示例#23
0
def random_scene():
    '''Generate a scene with three main spheres and several randomly placed spheres with random textures'''
    world = HittableList()

    checker = CheckerTexture(Color(0.2, 0.3, 0.1), Color(0.9, 0.9, 0.9))
    ground_material = Lambertian(checker)
    world.add(Sphere(Point3(0, -1000, 0), 1000, ground_material))

    for a in range(-11, 11):
        for b in range(-11, 11):
            choose_mat = random()
            center = Point3(a + 0.9 * random(), 0.2, b + 0.9 * random())

            if (center - Point3(4, 0.2, 0)).length() > 0.9:

                if choose_mat < 0.8:
                    albedo = Color.random() * Color.random()
                    sphere_material = Lambertian(albedo)
                    center2 = center + Vec3(0, uniform(0, 0.5), 0)
                    world.add(
                        MovingSphere(center, center2, 0.0, 1.0, 0.2,
                                     sphere_material))
                elif choose_mat < 0.95:
                    albedo = Color.random(0.5, 1)
                    fuzz = uniform(0, 0.5)
                    sphere_material = Metal(albedo, fuzz)
                    world.add(Sphere(center, 0.2, sphere_material))
                else:
                    sphere_material = Dielectric(1.5)
                    world.add(Sphere(center, 0.2, sphere_material))

    material1 = Dielectric(1.5)
    world.add(Sphere(Point3(0, 1, 0), 1.0, material1))

    material2 = Lambertian(Color(0.4, 0.2, 0.1))
    world.add(Sphere(Point3(-4, 1, 0), 1.0, material2))

    material3 = Metal(Color(0.7, 0.6, 0.5), 0.0)
    world.add(Sphere(Point3(4, 1, 0), 1.0, material3))

    return world
示例#24
0
def random_scene():
    scene = []
    scene.append(
        Sphere(Vec3(0, -1000, 0), 1000, Lambertian(Vec3(0.5, 0.5, 0.5))))
    i = 1
    for a in range(-11, 11):
        for b in range(-11, 11):
            choose_mat = random.random()
            center = Vec3(a + 0.9 * random.random(), 0.2,
                          b + 0.9 * random.random())
            if ((center - Vec3(4, 0.2, 0)).length > 0.9):
                if (choose_mat < 0.8):
                    scene.append(
                        Sphere(
                            center, 0.2,
                            Lambertian(
                                Vec3(random.random() * random.random(),
                                     random.random() * random.random(),
                                     random.random() * random.random()))))
                elif (choose_mat < 0.95):
                    scene.append(
                        Sphere(
                            center, 0.2,
                            Metal(
                                Vec3(0.5 * (1 + random.random()),
                                     0.5 * (1 + random.random()),
                                     0.5 * (1 + random.random())),
                                0.5 * random.random())))
                else:
                    scene.append(Sphere(center, 0.2, Dielectric(1.5)))

    scene.append(Sphere(Vec3(0, 1, 0), 1.0, Dielectric(1.5)))
    scene.append(Sphere(Vec3(-4, 1, 0), 1.0, Lambertian(Vec3(0.4, 0.2, 0.1))))
    scene.append(Sphere(Vec3(4, 1, 0), 1.0, Metal(Vec3(0.7, 0.6, 0.5), 0.0)))

    return scene
示例#25
0
from color import Color
from point import Point
from sphere import Sphere
from ray import Ray
from light import Light
from material import Material, CheckeredMaterial

WIDTH = 960
HEIGHT = 540
RENDERED_IMG = "blueBalls.ppm"
CAMERA = Vector(0, -0.35, -1)
OBJECTS = [
    # Ground Plane
    Sphere(
        Point(0, 10000.5, 1), 10000,
        CheckeredMaterial(color1=Color.from_hex("#440800"),
                          color2=Color.from_hex("#E5B87C"),
                          ambient=0.3,
                          reflection=0.2)),

    # Blue Ball 1
    Sphere(Point(0.6, -0.1, 1), 0.5, Material(Color.from_hex("#FFFF00"))),
    # Ball 2
    Sphere(Point(-0.6, -0.1, 2.5), 0.5, Material(Color.from_hex("#0000FF"))),
    # Mirror
    Sphere(Point(0, -0.1, 1.5), 0.5,
           Material(Color.from_hex("#FFFFFF"), reflection=0.9))
]
LIGHTS = [
    Light(Point(1.5, 0.5, 1), Color.from_hex("#FFFFFF")),
    Light(Point(-0.5, -10.5, 0), Color.from_hex("#E6E6E6"))
]
示例#26
0
        for y in range(self.height):
            for x in range(self.width):
                i = (2 * (x + 0.5) / self.width - 1) * self.width / self.height * tan(fov / 2)
                j = (2 * (y + 0.5) / self.height - 1) * tan(fov / 2)
                direction = norm(V3(i, j, -1))
                self.pixels[y][x] = self.castRay(V3(0, 0, 0), direction)


r = Raytracer(1000, 1000)
r.light = Light(
    position = V3(0, 0, 20),
    intensity = 1.5
)
r.scene = [
    #Oso1 
    Sphere(V3(-3, 2, -11), 1.4, white1), #cabeza blanca  
    Sphere(V3(-2.8, -1.65, -11), 2.3, white2), #cuerpo blanca
    Sphere(V3(-4.3, 3.2, -10.5), 0.5, white1), #oreja blanca
    Sphere(V3(-1.7, 3.2, -10.5), 0.5, white1), #oreja blanca
    Sphere(V3(-2.5, 1.5, -9), 0.25, white2), #nariz blanca
    Sphere(V3(-4.7, 0.22, -10.5), 0.45, white1), #brazo blanco
    Sphere(V3(-0.8, 0.23, -10.5), 0.45, white1), #brazo blanco
    Sphere(V3(-4.7, -3.6, -10.5), 0.45, white1), #pierna blanco
    Sphere(V3(-0.9, -3.5, -10.5), 0.45, white1), #pierna blanco
    Sphere(V3(-2.5, 1.8, -8), 0.1, black), #ojo
    Sphere(V3(-2, 1.8, -8), 0.1, black), #ojo
    Sphere(V3(-2.25, 1.35, -8), 0.1, black), #ojo
    Sphere(V3(-2.5, 0, -9), 0.23, red), #adorno rojo
    Sphere(V3(-2.8, -0.2, -9), 0.23, red), #adorno rojo
    Sphere(V3(-2.0, 0, -9), 0.23, red), #adorno rojo
    Sphere(V3(-2.3, -0.2, -9), 0.23, red), #adorno rojo
示例#27
0
            return color(255, 0, 0)
        else:
            return color(0, 0, 255)

    def render(self, sphere):
        fov = int(pi / 2)
        for y in range(self.height):
            for x in range(self.width):
                i = (2 * (x + 0.5) / self.width - 1) * tan(
                    fov / 2) * self.width / self.height
                j = -(2 * (y + 0.5) / self.height - 1) * tan(fov / 2)
                # x = int(x)
                # y = int(y)
                # print(x, y)
                direction = norm(V3(i, j, -1))
                self.pixels[y][x] = self.cast_ray(V3(0, 0, 0), direction,
                                                  sphere)

    def silly_render(self):
        for x in range(self.width):
            for y in range(self.height):
                r = int((x / self.width) * 255) if x / self.width < 1 else 1
                g = int((y / self.height) * 255) if y / self.height < 1 else 1
                b = 0
                self.pixels[y][x] = color(r, g, b)


r = Raytracer(1000, 1000)
s = Sphere(V3(-3, 0, -16), 2)
r.render(s)
r.display()
示例#28
0
def keyPressed(*args):
    global camera
    global lineVision
    global objVision
    
    key=glutGetModifiers()
    
    #print(args[0])
    
    # If escape is pressed, kill everything.
    if args[0]==ESCAPE:
        sys.exit()
    elif args[0] == b'z':
        scene.objects[0].rotate_point_z(10,scene.objects[0].center)
    elif args[0] == b"x":
        scene.objects[0].rotate_point_x(10,scene.objects[0].center)
    elif args[0] == b"c":
        scene.objects[0].rotate_point_y(10,scene.objects[0].center)
        
    elif args[0] == b"b":
        scene.objects[0].increase_subdivisions()
    elif args[0] == b"n":
        scene.objects[0].decrease_subdivisions()

 
        
    elif args[0] == b"w":
        camera.move_forward(.1)
    elif args[0] == b"s":
        camera.move_backward(.1)
        
    elif args[0] == b"1":
        scene.cleanScene()
        scene.addObject(Sphere(18,12,1))
        scene.addObject(grid)
    elif args[0] == b"2":
        scene.cleanScene()
        scene.addObject(Torus(11,11,.3,1))
        scene.addObject(grid)
    elif args[0] == b"3":
        scene.cleanScene()
        scene.addObject(Cylinder(2,11,0.08))
        scene.addObject(grid)
    elif args[0] == b"4":
        scene.cleanScene()
        scene.addObject(Box(1,1,1))
        scene.addObject(grid)
    elif args[0] == b"5":
        scene.cleanScene()
        scene.addObject(Pyramid(.4))
        scene.addObject(grid)
    elif args[0] == b"6":
        scene.cleanScene()
        scene.addObject(Icosahedron())
        scene.addObject(grid)
    elif args[0] == b"7":
        scene.cleanScene()
        scene.addObject(Octahedron(1,3))
        scene.addObject(grid)
        
    elif args[0] == b"l":
        lineVision=True
        objVision=False
    elif args[0] == b"o":
        lineVision=False
        objVision=True
    elif args[0] == b"p":
        lineVision=True
        objVision=True
        
    elif args[0] == b"f":
        camera=Camera(Vec3d(0,0,5),Vec3d(0,0,-1))
示例#29
0
def test_repr():
    s = Sphere(4)
    assert repr(s) == "Sphere(4)"

    s2 = eval(repr(s))
    assert s2.radius == 4
示例#30
0
def test_str():
    s = Sphere(4)
    assert str(s) == "Sphere with radius: 4"