Exemple #1
0
    def __init__(self, *args, **kwargs):
        """
        Initialize the transform.
        """

        code = library.get("transforms/trackball-pan.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._aspect = Transform._get_kwarg("aspect", kwargs) or 1
        self._znear = Transform._get_kwarg("znear", kwargs) or 2.0
        self._zfar = Transform._get_kwarg("zfar", kwargs) or 1000.0
        theta = Transform._get_kwarg("theta", kwargs) or 45
        phi = Transform._get_kwarg("phi", kwargs) or 45
        self._distance = Transform._get_kwarg("distance", kwargs) or 8
        self._zoom = Transform._get_kwarg("zoom", kwargs) or 35
        self._width = 1
        self._height = 1
        self._window_aspect = 1
        self._view_x = 0
        self._view_y = 0
        self._shift = False

        self._trackball = _trackball.Trackball(45,45)
        self._projection = np.eye(4, dtype=np.float32)
        self._view = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -abs(self._distance))
Exemple #2
0
    def distance(self, distance):
        """ Distance from the trackball to the object """

        self._distance = abs(distance)
        self._view = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -abs(self._distance))
        self["view"] = self._view
Exemple #3
0
 def matrix_model(model):
     glm.scale(model, self.size, self.size, self.size)
     glm.rotate(model, self.deg_y, 1, 0, 0)
     glm.rotate(model, self.deg_x, 0, 0, 1)
     glm.translate(model, self.mov_x, -self.mov_y, 0)
     # model[3,3] = 1
     return model
Exemple #4
0
    def __init__(self, *args, **kwargs):
        """
        Initialize the transform.
        """

        code = library.get("transforms/trackball-pan.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._aspect = Transform._get_kwarg("aspect", kwargs) or 1
        self._znear = Transform._get_kwarg("znear", kwargs) or 2.0
        self._zfar = Transform._get_kwarg("zfar", kwargs) or 1000.0
        theta = Transform._get_kwarg("theta", kwargs) or 45
        phi = Transform._get_kwarg("phi", kwargs) or 45
        self._distance = Transform._get_kwarg("distance", kwargs) or 8
        self._zoom = Transform._get_kwarg("zoom", kwargs) or 35
        self._width = 1
        self._height = 1
        self._window_aspect = 1
        self._view_x = 0
        self._view_y = 0
        self._shift = False

        self._trackball = _trackball.Trackball(45, 45)
        self._projection = np.eye(4, dtype=np.float32)
        self._view = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -abs(self._distance))
 def matrix_model(model):
     glm.scale(model, self.size, self.size, self.size)
     glm.rotate(model, self.deg_y, 1, 0, 0)
     glm.rotate(model, self.deg_x, 0, 0, 1)
     glm.translate(model, self.mov_x, -self.mov_y, 0)
     # model[3,3] = 1
     return model
Exemple #6
0
    def render(self, dt):
        if not self.draw:
            return False
        # View
        view = np.eye(4, dtype=np.float32)
        glm.translate(view, self.params["posx"], self.params["posy"],
                      self.params["posz"])
        self.program['view'] = view

        # Model
        model = np.eye(4, dtype=np.float32)
        glm.rotate(model, self.params["theta"], 0, 0, 1)
        glm.rotate(model, self.params["phi"], 0, 1, 0)
        self.program['model'] = model

        # Modulations
        self.program['radius'] = self.params["size"]
        self.program['cutoff'] = self.params['cutoff']

        position = self.program['position']
        angles = np.linspace(0, np.pi * self.params["ratio"] * n, n)
        thet = np.linspace(0, np.pi * self.params["ratio"] * 2, n)
        distances = np.linspace(0, (0.00005 + self.params["distance"]) * n, n)

        position[:, 0] = distances * np.sin(angles) * np.cos(thet)
        position[:, 1] = distances * np.sin(angles) * np.sin(thet)
        position[:, 2] = distances * np.cos(angles)

        # Drawing
        self.window.clear()
        self.program.draw(gl.GL_POINTS)
        self.draw = False
        return True
Exemple #7
0
    def distance(self, distance):
        """ Distance from the trackball to the object """

        self._distance = abs(distance)
        self._view = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -abs(self._distance))
        self["view"] = self._view
Exemple #8
0
    def distance(self, value):
        """ Distance of the camera to the origin """

        if value > 1:
            self._distance = value
            self._view = np.eye(4, dtype=np.float32)
            glm.translate(self._view, 0, 0, -self._distance)
            self["view"] = self._view
Exemple #9
0
    def distance(self, value):
        """ Distance of the camera to the origin """

        if value > 1:
            self._distance = value
            self._view = np.eye(4, dtype=np.float32)
            glm.translate(self._view, 0, 0, -self._distance)
            self["view"] = self._view
Exemple #10
0
 def update(self):
     model = correctly_rotated_model_matrix()
     glm.rotate(model, self.rotation[0], 1, 0, 0)
     glm.rotate(model, self.rotation[1], 0, 1, 0)
     glm.rotate(model, self.rotation[2], 0, 0, 1)
     glm.translate(model, self.position[0], self.position[1], self.position[2])
     glm.scale(model, self.scale[0], self.scale[1], self.scale[2])
     self.model_matrix = model
Exemple #11
0
def on_draw(dt):
    window.clear()

    global ALL_DATA, ALL_N, n, n_particles
    global rng
    global omega, phi_g, phi_p
    global positions, velocities, fitness_scores, best_positions, best_fitness_scores
    global global_best_position, global_best_fitness

    Rp = rng.rand()
    Rg = rng.rand()
    velocities *= omega
    velocities += (best_positions - positions) * (phi_p * Rp)
    velocities += (global_best_position - positions) * (phi_g * Rg)
    positions += velocities
    results = Parallel(n_jobs=1)(delayed(evaluate_particle)(particle, pos)
                                 for particle, pos in enumerate(positions))
    fitness_scores = np.array([f[2] for f in results], dtype=np.float32)
    diff_indices = np.where(fitness_scores < best_fitness_scores)[0]

    if len(diff_indices) > 0:
        best_positions[diff_indices, :] = positions[diff_indices, :]
        best_fitness_scores[diff_indices] = fitness_scores[diff_indices]

    new_best_fitness_indices = np.where(
        fitness_scores < global_best_fitness)[0]
    if len(new_best_fitness_indices) > 0:
        new_best_fitness_value = np.min(
            fitness_scores[new_best_fitness_indices])
        new_best_fitness_arg = np.argmin(
            fitness_scores[new_best_fitness_indices])

        global_best_fitness = new_best_fitness_value
        global_best_position = positions[new_best_fitness_arg]

    #
    #
    #

    global program
    ALL_DATA = np.vstack((VIEW_DATA, positions))
    program["position"] = 0.75 * ALL_DATA
    #
    #
    #

    global theta, phi, translate
    global sx, sy, sz
    window.clear()
    program.draw(gl.GL_POINTS)
    model = np.eye(4, dtype=np.float32)

    glm.scale(model, sx, sy, sz)
    glm.rotate(model, theta, 1, 0, 0)
    glm.rotate(model, phi, 0, 1, 0)
    glm.translate(model, tx, ty, tz)
    program["model"] = model
Exemple #12
0
 def matrix_model():
     model = np.eye(4, dtype=np.float32)
     #model *= size
     glm.rotate(model, theta, 1, 0, 0)
     glm.rotate(model, -phi, 0, 1, 0)
     glm.translate(model, tx, ty, 0)
     glm.scale(model, size)
     #model[3,3] = 1
     return model
 def matrix_model():
     model = np.eye(4, dtype=np.float32)
     #model *= size
     glm.rotate(model, theta, 1, 0, 0)
     glm.rotate(model, -phi, 0, 1, 0)
     glm.translate(model, tx, ty, 0)
     glm.scale(model, size)
     #model[3,3] = 1
     return model      
Exemple #14
0
    def do_update( self ):
        M = np.eye( 4 )
        M = glm.rotate( M, -90, 1, 0, 0 ) # rotates CCW
        glm.translate( M, -self.view_xyz[0], -self.view_xyz[1], -self.view_xyz[2] )
        glm.rotate( M, self.view_hpr[0], 0, 1, 0 )
        glm.rotate( M, self.view_hpr[1], 1, 0, 0 )

        self._model = M
        self["model"] = self._model
Exemple #15
0
    def on_draw(dt):
        nonlocal frame, x, y, z, theta, phi, gamma

        # Export screenshot
        gl.glReadPixels(0, 0, window.width, window.height, gl.GL_RGB,
                        gl.GL_UNSIGNED_BYTE, framebuffer)
        if frame > 2:  # Skip empty zero frame
            if (frame) % 3 == 0:
                pbar.update()
                gt.append(
                    [f'{(frame-3)//3:05d}.png', x, y, z, theta, phi, gamma])
                png.from_array(framebuffer, 'RGB').save(
                    root / 'images' / f'{(frame-3)//3:05d}.png')
            elif (frame) % 3 == 1:
                png.from_array(framebuffer, 'RGB').save(
                    root / 'no_rotation' / f'{(frame-4)//3:05d}.png')
            elif (frame) % 3 == 2:
                png.from_array(framebuffer, 'RGB').save(
                    root / 'no_translation' / f'{(frame-5)//3:05d}.png')

        if (frame - 1) % 3 == 0:
            theta = np.random.random_sample() * 360
            x, y = np.random.random_sample(2) * (max_xy - min_xy) + min_xy
            if not fixed_z:
                z = np.random.random_sample() * (max_z - min_z) + min_z
            if shape == 'cube':
                phi = np.random.random_sample() * 180
            if shape in shapes:
                phi = np.random.random_sample() * 180
                gamma = np.random.random_sample() * 360

        window.clear()

        # Fill cube
        gl.glDisable(gl.GL_BLEND)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_POLYGON_OFFSET_FILL)
        cube['u_color'] = 1, 1, 1, 1
        cube.draw(gl.GL_TRIANGLES, I)

        # Rotate cube
        view = cube['u_view'].reshape(4, 4)
        model = np.eye(4, dtype=np.float32)
        if (frame - 1) % 3 != 1:
            glm.rotate(model, theta, 0, 0, 1)
            glm.rotate(model, phi, 0, 1, 0)
            glm.rotate(model, gamma, 1, 0, 0)

        # Translate cube
        if (frame - 1) % 3 != 2:
            glm.translate(model, x, y, z)

        cube['u_model'] = model
        cube['u_normal'] = np.array(np.matrix(np.dot(view, model)).I.T)

        frame += 1
Exemple #16
0
    def __init__(self, *args, **kwargs):
        code = library.get("transforms/pvm.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._fovy = 40
        self._znear, self._zfar = 2.0, 100.0
        self._view = np.eye(4, dtype=np.float32)
        self._model = np.eye(4, dtype=np.float32)
        self._projection = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -5)
Exemple #17
0
    def __init__(self, *args, **kwargs):
        code = get_code("pvm.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._fovy = 40
        self._znear, self._zfar = 2.0, 100.0
        self._view = np.eye(4, dtype=np.float32)
        self._model = np.eye(4, dtype=np.float32)
        self._projection = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -5)
Exemple #18
0
 def get_view(self):
     view = np.eye(4, dtype=np.float)
     glm.translate(
         view, *(-self._position
                 ))  # shift the world so that the camera is at the origin
     glm.yrotate(view,
                 self._yaw)  # rotate the world so that it faces the camera
     glm.xrotate(view, self._pitch)
     glm.zrotate(view, self._roll)
     glm.scale(view, 1, -1, -1)
     return view
Exemple #19
0
    def __init__(self, *args, **kwargs):
        code = library.get("transforms/pvm.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._width = None
        self._height = None
        self._distance = Transform._get_kwarg("distance", kwargs) or 5
        self._fovy = Transform._get_kwarg("fovy", kwargs) or 40
        self._znear = Transform._get_kwarg("znear", kwargs) or 2.0
        self._zfar = Transform._get_kwarg("zfar", kwargs) or 100.0
        self._view = np.eye(4, dtype=np.float32)
        self._model = np.eye(4, dtype=np.float32)
        self._projection = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -self._distance)
Exemple #20
0
    def __init__(self, *args, **kwargs):
        #if "code" not in kwargs.keys():
        code = get_code("pvm.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._fovy = 25
        self._znear, self._zfar = 2.0, 100.0
        self._trackball = _trackball.Trackball(45,45)
        self._viewport = None
        self._model = self._trackball.model
        self._projection = np.eye(4, dtype=np.float32)
        self._view = np.eye(4, dtype=np.float32)
        self._aspect = 1.0
        glm.translate(self._view, 0, 0, -8)
Exemple #21
0
    def __init__(self, *args, **kwargs):
        code = library.get("transforms/pvm.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._width     = None
        self._height    = None
        self._distance = Transform._get_kwarg("distance", kwargs) or 5
        self._fovy     = Transform._get_kwarg("fovy", kwargs) or 40
        self._znear    = Transform._get_kwarg("znear", kwargs) or 2.0
        self._zfar     = Transform._get_kwarg("zfar", kwargs) or 100.0
        self._view = np.eye(4, dtype=np.float32)
        self._model = np.eye(4, dtype=np.float32)
        self._projection = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -self._distance)
Exemple #22
0
    def __init__(self, *args, **kwargs):
        """
        Initialize the transform.
        Note that parameters must be passed by name (param=value).

        Kwargs parameters
        -----------------

        aspect : float (default is None)
           Indicate what is the aspect ratio of the object displayed. This is
           necessary to convert pixel drag move in oject space coordinates.

        znear : float, float (default is 2)
           Near clip plane

        zfar : float, float (default is 1000)
           Distance clip plane

        theta : float (default is 45)
           Angle (in degrees) around the z axis

        phi:  float (default is 45)
           Angle (in degrees) around the x axis

        distance: float (default is 8)
           Distance from the trackball to the object

        zoom : float (default is 35)
           Zoom level
        """

        code = library.get("transforms/trackball.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._aspect = Transform._get_kwarg("aspect", kwargs) or 1
        self._znear = Transform._get_kwarg("znear", kwargs) or 2.0
        self._zfar = Transform._get_kwarg("zfar", kwargs) or 1000.0
        theta = Transform._get_kwarg("theta", kwargs) or 45
        phi = Transform._get_kwarg("phi", kwargs) or 45
        self._distance = Transform._get_kwarg("distance", kwargs) or 8
        self._zoom = Transform._get_kwarg("zoom", kwargs) or 35
        self._width = 1
        self._height = 1
        self._window_aspect = 1

        self._trackball = _trackball.Trackball(45,45)
        self._projection = np.eye(4, dtype=np.float32)
        self._view = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -abs(self._distance))
Exemple #23
0
    def on_draw(dt):
        nonlocal depth
        color_buf = np.zeros((imgsize, imgsize, 4),
                             np.float32).view(gloo.TextureFloat2D)
        depth_buf = np.zeros((imgsize, imgsize),
                             np.float32).view(gloo.DepthTexture)
        fbo = gloo.FrameBuffer(color=color_buf, depth=depth_buf)
        fbo.activate()

        window.clear()

        # Fill cube
        gl.glDisable(gl.GL_BLEND)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_POLYGON_OFFSET_FILL)
        gl.glClearColor(0.0, 0.0, 0.0, 0.0)

        # Rotate cube
        model = np.eye(4, dtype=np.float32)

        # model = R_ @ model
        glm.rotate(model, R[0], 0, 0, 1)
        glm.rotate(model, R[1], 0, 1, 0)
        glm.rotate(model, R[2], 1, 0, 0)

        # Translate cube
        glm.translate(model, *t)

        cube['u_model'] = model
        # cube['u_normal'] = np.array(np.matrix(np.dot(view, model)).I.T)

        cube.draw(gl.GL_TRIANGLES, I)
        # depth = np.zeros((shape[0], shape[1], 4), dtype=np.float32)
        # gl.glReadPixels(0, 0, shape[1], shape[0], gl.GL_RGBA, gl.GL_FLOAT, depth)
        # depth.shape = shape[0], shape[1], 4
        # depth = depth[::-1, :]
        # depth = depth[:, :, 0] # Depth is saved in the first channel

        # Export screenshot
        gl.glReadPixels(0, 0, window.width, window.height, gl.GL_RGB,
                        gl.GL_FLOAT, depthbuffer)

        # png.from_array(np.floor((depthbuffer - 0) / depthbuffer.max() * 255).astype(np.uint8),
        #                'RGB').save('./images' +
        #                            f'depth{time.time()}.png')

        fbo.deactivate()
        fbo.delete()
        depth = depthbuffer.reshape((128, 128, 3))[::-1, :, 0]
Exemple #24
0
    def __init__(self, *args, **kwargs):
        """
        Initialize the transform.
        Note that parameters must be passed by name (param=value).

        Kwargs parameters
        -----------------

        aspect : float (default is None)
           Indicate what is the aspect ratio of the object displayed. This is
           necessary to convert pixel drag move in oject space coordinates.

        znear : float, float (default is 2)
           Near clip plane

        zfar : float, float (default is 1000)
           Distance clip plane

        theta : float (default is 45)
           Angle (in degrees) around the z axis

        phi:  float (default is 45)
           Angle (in degrees) around the x axis

        distance: float (default is 8)
           Distance from the trackball to the object

        zoom : float (default is 35)
           Zoom level
        """

        code = library.get("transforms/trackball.glsl")
        Transform.__init__(self, code, *args, **kwargs)

        self._aspect = Transform._get_kwarg("aspect", kwargs) or 1
        self._znear = Transform._get_kwarg("znear", kwargs) or 2.0
        self._zfar = Transform._get_kwarg("zfar", kwargs) or 1000.0
        theta = Transform._get_kwarg("theta", kwargs) or 45
        phi = Transform._get_kwarg("phi", kwargs) or 45
        self._distance = Transform._get_kwarg("distance", kwargs) or 8
        self._zoom = Transform._get_kwarg("zoom", kwargs) or 35
        self._width = 1
        self._height = 1
        self._window_aspect = 1

        self._trackball = _trackball.Trackball(45, 45)
        self._projection = np.eye(4, dtype=np.float32)
        self._view = np.eye(4, dtype=np.float32)
        glm.translate(self._view, 0, 0, -abs(self._distance))
Exemple #25
0
    def wheelEvent(self, wheel_event):
        if self._render_mode == self.TEXTURE_RENDER_MODE:
            return

        scroll_steps = wheel_event.angleDelta().y(
        ) / 8 / 15  # Get actual number of steps (default is 15 deg/step)

        view_y = self._world_to_view[-1, 2]
        if (view_y >= 0 and scroll_steps > 0) or (view_y <= -self._far_clip_z
                                                  and scroll_steps < 0):
            return

        distance_speedup = np.clip(abs(view_y) / 4.0, 1.0, 10.0)
        glm.translate(self._world_to_view, 0, 0,
                      scroll_steps * self._scroll_speed * distance_speedup)
Exemple #26
0
    def on_draw(dt):
        nonlocal phi, theta, omega, dx, dy, dz, scale, d

        model = np.eye(4, 4, dtype=np.float32)
        glm.xrotate(model, omega)
        glm.yrotate(model, phi)
        glm.zrotate(model, theta)
        glm.scale(model, scale, scale, scale)
        glm.translate(model, dx, dy, dz)
        cube['model'] = model

        cube['color'] = color

        window.clear()
        cube.draw(gl.GL_TRIANGLES, I)
Exemple #27
0
 def on_mouse_scroll(x, y, dx, dy):
     if self.size + dy * 0.1 < 0.1:
         self.size = 0.1
     else:
         # self.size += dy * 0.1
         # self.zoom += dy*1
         self.u_view = glm.translate(self.u_view, 0, 0, dy)
 def on_mouse_scroll(x, y, dx, dy):
     if self.size + dy * 0.1 < 0.1:
         self.size = 0.1
     else:
         # self.size += dy * 0.1
         # self.zoom += dy*1
         self.u_view = glm.translate(self.u_view , 0, 0, dy)
Exemple #29
0
    def on_draw(dt):
        nonlocal phi, theta, omega, dx, dy, dz, scale, d

        matrix = np.eye(4, 4, dtype=np.float32)
        glm.xrotate(matrix, omega)
        glm.yrotate(matrix, phi)
        glm.zrotate(matrix, theta)
        glm.scale(matrix, scale, scale, scale)
        glm.translate(matrix, dx, dy, dz)

        result = [np.matmul([*p, 1], matrix)[0:3] for p in V]

        cube['position'] = [project(*p, d) for p in result]

        window.clear()
        cube.draw(gl.GL_LINE_LOOP, I)
Exemple #30
0
 def init(self):
     view = np.eye(4, dtype=np.float32)
     glm.translate(view, 0, 0, -20)
     model = np.eye(4, dtype=np.float32)
     projection = np.eye(4, dtype=np.float32)
     p = gloo.Program(ge.vertex_shaders['v1'], ge.fragment_shaders['f1'])
     self['program_shader'] = p
     if self['vertex_buffer'] is None:
         self.set_vertex(self['vertex'])
     if self['index_buffer'] is None:
         self.set_index(self['index'])
     if game.window is not None:
         self.set_projection(game.window.width, game.window.height)
     self.set_color(self['color'])
     p['u_view'] = view
     p['u_projection'] = projection
     p['u_model'] = model
     p.bind(self['vertex_buffer'])
    def render(self, dt):
        self.window.activate()
        self.window.clear()
        if self.iMat is not None:
            self.iMat = np.eye(4, dtype=np.float32)
            if not self.gimbal:
                glm.xrotate(self.iMat, self.horizontal_angle)
                glm.yrotate(self.iMat, self.vertical_angle)
            else:
                self.position = [0., 0., self.params["distance"]]
            glm.translate(self.iMat, *self.position)
            if self.gimbal:
                glm.xrotate(self.iMat, self.params["horizontal_angle"])
                glm.yrotate(self.iMat, self.params["vertical_angle"])
            self.params["iMat"] = self.iMat
        for p in self.program_params:
            self.program[p] = self.params[p]
        dt = dt / self.fps

        if self.iTime:
            self.program["iTime"] = dt
        try:
            self.program.draw(gl.GL_TRIANGLE_STRIP)
            if self.old_program:
                self.old_program.delete()
                del self.old_program
                self.old_program = None
                print("Loaded new program!")
        except RuntimeError:
            if not self.old_program:
                raise
            self.old_program.draw(gl.GL_TRIANGLE_STRIP)
            self.program.delete()
            del self.program
            self.program = self.old_program
            self.old_program = None
            self.paused = True

        if self.title == "Map":
            gl.glEnable(gl.GL_BLEND)
            gl.glBlendFunc(gl.GL_ONE_MINUS_DST_COLOR, gl.GL_ZERO)
            self.point_program.draw(gl.GL_POINTS)
        self.prev_params = copy.deepcopy(self.params)
Exemple #32
0
    def _draw_circles(self, centers):
        gl.glEnable(gl.GL_BLEND)
        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glDisable(gl.GL_DEPTH_TEST)

        gl.glLineWidth(3)

        for i in range(len(centers)):
            center = centers[i]
            radius = self.__harmonics[i].radius
            model = np.eye(4, dtype=np.float32)
            glm.scale(model, radius / 2, radius / 2, 1)
            glm.translate(model, center[0] / 2, center[1] / 2, 0)

            self.__circles_program[self.u_model] = model
            self.__circles_program[self.u_color] = self.__circle_color
            self.__circles_program.draw(gl.GL_TRIANGLE_FAN, self.__circle_i)

            self.__circles_program[self.u_color] = self.__ocircle_color
            self.__circles_program.draw(gl.GL_LINE_LOOP, self.__ocircle_i)
Exemple #33
0
def draw(fx):

    window = app.Window(width=800, height=800, color=(1,1,1,1))

    pos, rad, col = next(fx)
    n = len(rad)

    program = gloo.Program(vertex, fragment, count=n)
    view = np.eye(4, dtype=np.float32)
    glm.translate(view, 0, 0, -5)

    program['position'] = pos
    program['radius']   = rad
    program['fg_color'] = 0,0,0,1
    program['bg_color'] = col
    program['linewidth'] = 1.0
    program['antialias'] = 1.0
    program['model'] = np.eye(4, dtype=np.float32)
    program['projection'] = np.eye(4, dtype=np.float32)
    program['view'] = view

    @window.event
    def on_draw(dt):
        global theta, phi
        program['position'], program['radius'], program['bg_color'] = next(fx)

        window.clear()
        program.draw(gl.GL_POINTS)
        theta += .5
        phi += .5
        model = np.eye(4, dtype=np.float32)
        glm.rotate(model, theta, 0, 0, 1)
        glm.rotate(model, phi, 0, 1, 0)
        program['model'] = model

    @window.event
    def on_resize(width,height):
        program['projection'] = glm.perspective(45.0, width / float(height), 1.0, 1000.0)

    gl.glEnable(gl.GL_DEPTH_TEST)
    app.run()   
def display_cloud(cloud):
    window = app.Window(width=800, height=800, color=(1, 1, 1, 1))

    @window.event
    def on_draw(dt):
        global theta, phi, translate
        window.clear()
        program.draw(gl.GL_POINTS)
        theta += .5
        phi += .5
        model = np.eye(4, dtype=np.float32)
        glm.rotate(model, theta, 0, 0, 1)
        glm.rotate(model, phi, 0, 1, 0)
        program['model'] = model

    @window.event
    def on_resize(width, height):
        program['projection'] = glm.perspective(45.0, width / float(height),
                                                1.0, 1000.0)

    n = len(cloud)
    program = gloo.Program(vertex, fragment, count=n)
    view = np.eye(4, dtype=np.float32)
    glm.translate(view, 0, 0, -5)

    program['position'] = cloud
    program['radius'] = [5] * n
    program['fg_color'] = 0, 0, 0, 1
    colors = np.random.uniform(0.75, 1.00, (n, 4))
    colors[:, 3] = 1
    program['bg_color'] = colors
    program['linewidth'] = 1.0
    program['antialias'] = 1.0
    program['model'] = np.eye(4, dtype=np.float32)
    program['projection'] = np.eye(4, dtype=np.float32)
    program['view'] = view

    gl.glEnable(gl.GL_DEPTH_TEST)
    app.run()
Exemple #35
0
def on_key_press(symbol, modifiers):
    global alpha
    dx=dy=dz=0
    shift = True if modifiers == 1 else False
    
    mat = np.eye(4, dtype=np.float32)
    letra = ''
    if symbol==-1:
        return
    letra = chr(symbol)
    if letra =='W':
        dz=-0.1
    elif letra == 'S':
        dz=0.1
    elif letra=='D':
        dx=0.1
    elif letra =='A':
        dx=-0.1
    elif letra ==' ':
        dy=0.1
    elif letra =='Z':
        dy=-0.1
    elif letra =='R':
        alpha+=1
        glm.rotate(mat,alpha,0,1,0)
        cube['u_model'] = mat
    elif letra =='Q':
        alpha-=1
        glm.rotate(mat,alpha,0,1,0)
        cube['u_model'] = mat
        
    glm.translate(mat, dx,dy,dz)
    view = cube['u_view'].reshape(4, 4)
    x,y,z = cube["u_light_position"] 
    print('[',x,'],[',y,'],[',z,']')
    cube["u_light_position"] = x+dx,y+dy,z+dz
    cube['u_normal'] = np.array(np.matrix(np.dot(view, mat)).I.T)
    sleep(0.01)
Exemple #36
0
 def on_mouse_drag(self, x, y, dx, dy, button):
     width = self._width
     height = self._height
     x  = (x*2.0 - width)/width
     dx = (2.*dx)/width
     y  = (height - y*2.0)/height
     dy = -(2.*dy)/height
     if button == 2:
         # Left click
         self["view"] = glm.translate(self._view, dx, dy, 0)
     elif button == 8:
         # Right click
         self._trackball.drag_to(x,y,dx,dy)
         self["model"] = self._trackball.model
Exemple #37
0
    def get_key_point_transform(self, position, caller):
        """
        From position to transformation matrix
        Apply corresponding scale first

        :param position: len 3 np.array of the new positions to be updated
        :param caller: caller name, defined in self.component_names
        """
        if caller == "arm":
            return glm.translation(*position)
        else:
            return glm.translate(
                glm.scale(np.eye(4, dtype=np.float32), self.finger_scale,
                          self.finger_scale, self.finger_scale), *position)
Exemple #38
0
def on_key_press(key, modifiers):
    global phi, theta
    if key == app.window.key.UP:
        glm.translate(view, 0, 0, 0.1)
        program['u_view'] = view

    elif key == app.window.key.DOWN:
        glm.translate(view, 0, 0, -0.1)
        program['u_view'] = view

    elif key == app.window.key.RIGHT:
        glm.translate(view, -0.1, 0, 0)
        program['u_view'] = view
    elif key == app.window.key.LEFT:
        glm.translate(view, 0.1, 0, 0)
        program['u_view'] = view
Exemple #39
0
    def __init__(self, *args, **kwargs):
        """
        Initialize the transform.
        """

        code = library.get("transforms/trackball.glsl")
        Transform.__init__( self, code, *args, **kwargs )

        self._width = 1
        self._height = 1

#        self.view_xyz = np.asarray( [ 2, 2, 0.5 ] )  # camera xyz
#        self.view_hpr = np.asarray( [ 187, 0, 0 ] )  # camera heading, pitch, roll (degrees)
#        self.view_xyz = np.asarray( [ 0.5, 0.25, 6.0 ] )  # camera xyz
#        self.view_hpr = np.asarray( [ 270, -22.5, 0 ] )  # camera heading, pitch, roll (degrees)

        self.view_xyz = np.asarray( [ 0.0, 0.0, 1.0 ] )  # camera xyz
        self.view_hpr = np.asarray( [ 0.0, 0.0, 0.0 ] )  # camera heading, pitch, roll (degrees)

        self._model = np.eye( 4, dtype=np.float32 )
        self._projection = np.eye( 4, dtype=np.float32 )
        self._view = np.eye( 4, dtype=np.float32 )

        glm.translate( self._model, 0, 0, -1 )
Exemple #40
0
    def init(self):
        gl.glEnable(gl.GL_DEPTH_TEST)
        for e in self.entities:
            draw = e.draw
            view = np.eye(4, dtype=np.float32)
            glm.translate(view, 0, 0, -20)
            model = np.eye(4, dtype=np.float32)
            projection = np.eye(4, dtype=np.float32)

            p = gloo.Program(ge.vertex_shaders['v1'],
                             ge.fragment_shaders['f1'])
            p['u_view'] = view
            p['u_projection'] = projection
            p['u_model'] = model
            p.bind(draw.vertex_buffer)

            draw.program_shader = p
            if draw.vertex_buffer is None:
                draw.set_vertex(draw.vertex)
            if draw.index_buffer is None:
                draw.set_index(draw['index'])
            if self.window is not None:
                draw.set_projection(self.window.width, self.window.height)
            draw.set_color(draw.color)
    def __init__(self, window_width=1024, window_height=1024, degree=0):
        self.programs = []

        window = app.Window(window_width, window_height, color=(0, 0, 0, 1))
        framebuffer = np.zeros((window.height, window.width * 3), dtype=np.uint8)

        self.deg_x, self.deg_y, self.mov_x, self.mov_y, self.size, self.zoom, self.radius = 0, 0, 0, 0, 1, -200, 200
        self.u_model, self.u_view, self.u_projection = np.eye(4, dtype=np.float32), np.eye(4, dtype=np.float32), np.eye(
            4, dtype=np.float32)

        u_view = np.eye(4, dtype=np.float32)
        glm.rotate(u_view, -90, 1, 0, 0)
        #glm.rotate(u_view, -70, 1, 0, 0)
        glm.rotate(u_view, degree + 270, 0, 1, 0)
        glm.translate(u_view, 0, 0, 0) #(0, 0, -125)

        self.u_view = u_view

        self.demo_dt = 0
        self.scIdx = 0
        @window.event
        def on_draw(dt):
            window.clear()
            demo_idx = 0
            for program_object in self.programs:
                program = program_object.program

                model = matrix_model(np.copy(program_object.u_model))
                #self.deg_x += dt*20
                #self.deg_y += dt*40
                self.demo_dt += dt/5

                demo_idx += 1
                '''
                if self.demo_dt > 2:
                    if demo_idx == 1:
                        if self.demo_dt > 2.4:
                            if program['alpha'] <= 0.1:
                                continue
                            else:
                                program['alpha'] -= 0.01
                    elif demo_idx == 2:
                        if self.demo_dt > 2.8:
                            program['alpha'] += 0.01
                '''



                program['u_model'] = np.dot(model, self.u_model)

                program['u_view'] = self.u_view
                program['u_projection'] = self.u_projection
                if program_object.draw_mode == gl.GL_TRIANGLES:
                    program.draw(program_object.draw_mode, program_object.face)
                elif program_object.draw_mode == gl.GL_LINES and program_object.name == 'ProgramSFM3DRegion':
                    gl.glDisable(gl.GL_POLYGON_OFFSET_FILL)
                    gl.glEnable(gl.GL_BLEND)
                    gl.glDepthMask(gl.GL_FALSE)
                    program.draw(program_object.draw_mode, program_object.O)
                    gl.glDepthMask(gl.GL_TRUE)
                else:
                    program.draw(program_object.draw_mode)


        @window.event
        def on_resize(width, height):
            ratio = width / float(height)
            self.u_projection = glm.perspective(64.0, ratio, 1, 10000.0)

        @window.event
        def on_init():
            gl.glEnable(gl.GL_DEPTH_TEST)

        @window.event
        def on_mouse_scroll(x, y, dx, dy):
            if self.size + dy * 0.1 < 0.1:
                self.size = 0.1
            else:
                # self.size += dy * 0.1
                # self.zoom += dy*1
                self.u_view = glm.translate(self.u_view , 0, 0, dy)

        @window.event
        def on_mouse_drag(x, y, dx, dy, button):
            if button == 2:
                self.deg_y += dy  # degrees
                self.deg_x += dx  # degrees
            elif button == 8:
                self.mov_y += dy/10  # degrees
                self.mov_x += dx/10  # degrees

        @window.event
        def on_key_press(symbol, modifiers):
            """

            :param symbol:
            :param modifiers:
            :return:
            """
            '''
            if symbol == 88:  # x
                self.view_orth_vector = np.array([self.radius, 0, 0])
                self.program['u_view'] = glm.translation(self.view_orth_vector[0], self.view_orth_vector[1],
                                                         self.view_orth_vector[2])
            elif symbol == 89:  # y
                self.view_orth_vector = np.array([0, self.radius, 0])
                self.program['u_view'] = glm.translation(self.view_orth_vector[0], self.view_orth_vector[1],
                                                         self.view_orth_vector[2])
            elif symbol == 90:  # z
                self.view_orth_vector = np.array([0, 0, self.radius])
                self.program['u_view'] = glm.translation(self.view_orth_vector[0], self.view_orth_vector[1],
                                                         self.view_orth_vector[2])
            elif symbol == 70:  # f
                self.view_orth_vector = -self.view_orth_vector
                self.program['u_view'] = glm.translation(self.view_orth_vector[0], self.view_orth_vector[1],
                                                         self.view_orth_vector[2])
            elif symbol == 80:  # p
                gl.glReadPixels(0, 0, window.width, window.height,
                                gl.GL_RGB, gl.GL_UNSIGNED_BYTE, framebuffer)
                png.from_array(framebuffer, 'RGB').save('screenshot.png')

            print('Key pressed (symbol=%s, modifiers=%s)' % (symbol, modifiers))
            # self.program['color_sel'] = 1 - self.program['color_sel']
            '''
            #print(symbol)
            if symbol == 67:  # c --> change color
                for program_object in self.programs:
                    if program_object.name == 'ProgramSFM3DRegion':
                        program_object.program['color_sel'] = 1 - program_object.program['color_sel']
            elif symbol == 65:  # a --> align sfm to google
                for program_object in self.programs:
                    if program_object.name == 'ProgramSFM3DRegion' or program_object.name == 'programTrajectory':
                        program_object.align_flip()
            elif symbol == 73:  # i --> inverse google according anchor
                for program_object in self.programs:
                    if program_object.name == 'ProgramSV3DRegion':
                        program_object.apply_anchor_flip()
            elif symbol == 89:  # y --> rotate google according anchor yaw
                for program_object in self.programs:
                    if program_object.name == 'ProgramSV3DRegion':
                        program_object.apply_yaw_flip()
            elif symbol == 80:  # p --> print scrren
                gl.glReadPixels(0, 0, window.width, window.height,
                                gl.GL_RGB, gl.GL_UNSIGNED_BYTE, framebuffer)
                #png.from_array(framebuffer, 'RGB').save('screenshot{}.png'.format(self.scIdx))
                my_texture = np.reshape(framebuffer, (window.height, window.width, 3))
                # Some unknown reason
                # The buffer didn't match what I see in the window
                my_texture = np.flipud(my_texture)
                scipy.misc.imsave('yolo.png', my_texture)

                self.scIdx += 1

        def matrix_model(model):
            glm.scale(model, self.size, self.size, self.size)
            glm.rotate(model, self.deg_y, 1, 0, 0)
            glm.rotate(model, self.deg_x, 0, 0, 1)
            glm.translate(model, self.mov_x, -self.mov_y, 0)
            # model[3,3] = 1
            return model
Exemple #42
0
    fovy = np.minimum(np.maximum(fovy*(1+dy/100), 10.0), 179.0)
    program['projection'] = glm.perspective(fovy,
                                            window.width/float(window.height),
                                            1.0, 100.0)

@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glDisable(gl.GL_BLEND)


program = gloo.Program(vertex, fragment)
program.bind(V)
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -3)
program['texture'] = data.get("checkerboard")
program['model'] = model
program['view'] = view
program['grid'] = Grid("pos", "index")
program['grid']["rows"] = rows
program['grid']["cols"] = cols
program['clip'] = Clip("v_index")
program['clip']["rows"] = rows
program['clip']["cols"] = cols

fovy = 30
phi, theta = 30, 20
app.run()
 def offset_position(self, ecef):
     glm.translate(self.u_model, ecef[1], ecef[2], ecef[0])
Exemple #44
0
shapes = [ primitives.plane(1.5),
           primitives.cube(1.5),
           primitives.sphere(),
           primitives.cubesphere(),
           primitives.cylinder(),
           primitives.torus(),
           primitives.cone(),
           primitives.pyramid(),
           primitives.teapot() ]
vertices, indices = shapes[index]

program = gloo.Program(vertex, fragment)
program.bind(vertices)
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -5)
program['model'] = model
program['view'] = view
program['normal'] = np.array(np.matrix(np.dot(view, model)).I.T)
program['texture'] = data.checkerboard()
program["light1_position"] = 3, 0, 0+5
program["light2_position"] = 0, 3, 0+5
program["light3_position"] = -3, -3, +5
program["light1_color"]    = 1, 0, 0
program["light2_color"]    = 0, 1, 0
program["light3_color"]    = 0, 0, 1
phi, theta = 0, 0

app.run()