def drawIsoSphere(self, r=1.): """ draw an Iso-sphere (I'm not sure that the texture coordinates are quite right) """ if (len(self.verts) == 0): self.getIsoSphere() #need to populate the isosphere first #from here : https://www.gamedev.net/topic/116339-request-for-help-texture-mapping-an-icosahedron/ def GetTextureCoord(normal): x = normal[0] y = normal[1] v = np.arcsin(y) / (np.pi / 2.) if (abs(y) < 1.0): u = 0.5 + 0.5 * np.arctan2(x, y) / np.pi else: u = 0 # Actually undefined. return u, v vertex_arr = np.array(np.multiply(self.verts, r / 2.), 'f') fvert = [] fnorm = [] ftex = [] for f in self.faces: fvert.append( [vertex_arr[f[0]], vertex_arr[f[1]], vertex_arr[f[2]]]) normal = np.cross(vertex_arr[f[0]], vertex_arr[f[1]]) fnorm.append(normal) u, v = GetTextureCoord(normal) ftex.append([u, v, 0.]) fnorm = np.array(fnorm) fvert = np.array(fvert) ftex = np.array(ftex) vertex_vbo = vbo.VBO(fvert) normal_vbo = vbo.VBO(fnorm) tex_vbo = vbo.VBO(ftex) vertex_vbo.bind() glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glVertexPointerf(vertex_vbo) glNormalPointerf(normal_vbo) glTexCoordPointerf(tex_vbo) glDrawArrays(GL_TRIANGLES, 0, fvert.size) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY)
def VBO_cylindre(iMax=8): """ Create the "sphere" VBO & EBO """ global vertexPositions global indexPositions global nbIndex global styleIndex vertices = [] edgeIndices = [] surfIndices = [] i = 0 while i <= iMax: phi = 2 * math.pi * i / float(iMax) vertices = vertices + [-0.5, 0.5 * math.cos(phi), 0.5 * math.sin(phi)] vertices = vertices + [0.5, 0.5 * math.cos(phi), 0.5 * math.sin(phi)] if i != iMax: edgeIndices = edgeIndices + [2 * i, 2 * i + 1] edgeIndices = edgeIndices + [2 * i, 2 * (i + 1)] edgeIndices = edgeIndices + [2 * i + 1, 2 * (i + 1) + 1] surfIndices = surfIndices + [2 * i, 2 * (i + 1), 2 * (i + 1) + 1] surfIndices = surfIndices + [2 * (i + 1) + 1, 2 * i + 1, 2 * i] surfIndices = surfIndices + [2 * i, 2 * (i + 1), 2 * (iMax + 1)] surfIndices = surfIndices + [ 2 * i + 1, 2 * (i + 1) + 1, 2 * (iMax + 1) + 1 ] i += 1 vertices = vertices + [-0.5, 0., 0.] vertices = vertices + [0.5, 0., 0.] vertices = np.array([vertices], dtype='f') edgeIndices = np.array([edgeIndices], dtype=np.int32) surfIndices = np.array([surfIndices], dtype=np.int32) vertexPositions = vertexPositions + [ vbo.VBO(vertices), ] indexPositions = indexPositions + [ [ vbo.VBO(edgeIndices, target=GL_ELEMENT_ARRAY_BUFFER), vbo.VBO(surfIndices, target=GL_ELEMENT_ARRAY_BUFFER) ], ] nbIndex = nbIndex + [ [edgeIndices.size, surfIndices.size], ] styleIndex = styleIndex + [ [GL_LINES, GL_TRIANGLES], ]
def __init__(self, cam_model_files: Tuple[str, str], tracked_cam_parameters: data3d.CameraParameters, tracked_cam_track: List[data3d.Pose], point_cloud: data3d.PointCloud): """ Initialize CameraTrackRenderer. Load camera model, create buffer objects, load textures, compile shaders, e.t.c. :param cam_model_files: path to camera model obj file and texture. The model consists of triangles with per-point uv and normal attributes :param tracked_cam_parameters: tracked camera field of view and aspect ratio. To be used for building tracked camera frustrum :param point_cloud: colored point cloud """ tracked_cam_track = np.array( [_to_transformation_mat(pose) for pose in tracked_cam_track]) _transform_track(tracked_cam_track, point_cloud) camera_vertex_vbo, camera_index_vbo = _load_model(cam_model_files[0]) self._texture_objects = namedtuple( 'TextureObjects', 'camera camera_screen')(_load_texture(cam_model_files[1]), _allocate_empty_texture()) self._camera_screen_frame_buffer = \ _configure_screen_frame_buffer(self._texture_objects.camera_screen) self._tracked_cam_projection = _projection_matrix( tracked_cam_parameters.fov_y, tracked_cam_parameters.aspect_ratio, 0.1, 30) self._tracked_cam_track = tracked_cam_track BufferObjects = namedtuple( 'BufferObjects', 'camera_vertices camera_indices frustrum point_cloud track') self._buffer_objects = BufferObjects( camera_vertex_vbo, camera_index_vbo, vbo.VBO( np.array(_generate_frustrum(self._tracked_cam_projection), dtype=np.float32)), vbo.VBO( np.array(np.stack((point_cloud.points, point_cloud.colors)), dtype=np.float32)), vbo.VBO( np.array([cam_pos[0:3, 3] for cam_pos in tracked_cam_track], dtype=np.float32))) self._shaders = _build_shaders() GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | GLUT.GLUT_DEPTH) GL.glEnable(GL.GL_DEPTH_TEST)
def setData(self, vertexArray, normalArray, colorArray): if len(vertexArray) != len(colorArray) or len(vertexArray) != len( normalArray): raise RuntimeError( "vertexArray, normalArray and colorArray must be same length") self.vertexArray = vertexArray self.colorArray = colorArray self.normalArray = normalArray self.vertexVBO = vbo.VBO(vertexArray) self.colorVBO = vbo.VBO(colorArray) self.normalVBO = vbo.VBO(normalArray)
def compile(self, mode=None): """Compile this sphere for use on mode returns coordvbo,indexvbo,count """ coords, indices = self.compileArrays() vbos = vbo.VBO(coords), vbo.VBO( indices, target='GL_ELEMENT_ARRAY_BUFFER'), len(indices) if hasattr(mode, 'cache'): holder = mode.cache.holder(self, vbos) holder.depend(self, 'radius') return vbos
def __init__(self): #set up initial conditions pos = numpy.ndarray((640 * 480 * 4, 1), dtype=numpy.float32) self.pos_vbo = vbo.VBO(data=pos, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) self.pos_vbo.bind() #same shit, different toilet self.col_vbo = vbo.VBO(data=pos, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) self.col_vbo.bind()
def create_tetrahedron_vbo(edge=1.0): """ Creates a VBO tetrahedron for shaders. :param edge: Edge length :type edge: float, int :return: VBO object :rtype: VBObject """ def ex(element): """ Export element to list. :param element: Element :return: List :rtype: list """ return element.export_to_list() # Create points a = Point3(-0.5, -0.288675, -0.288675) * edge b = Point3(0.5, -0.288675, -0.288675) * edge # noinspection PyArgumentEqualDefault c = Point3(0.0, 0.577350, -0.288675) * edge # noinspection PyArgumentEqualDefault d = Point3(0.0, 0.0, 0.57735) * edge # Create normals n1 = ex(_normal_3_points(a, b, d)) n2 = ex(_normal_3_points(b, c, d)) n3 = ex(_normal_3_points(c, a, d)) n4 = ex(_normal_3_points(c, b, a)) # Create triangles vertex_array = [ ex(a), ex(b), ex(d), ex(b), ex(c), ex(d), ex(c), ex(a), ex(d), ex(a), ex(b), ex(c) ] normal_array = [n1, n1, n1, n2, n2, n2, n3, n3, n3, n4, n4, n4] # Return VBO return VBObject(_vbo.VBO(_array(vertex_array, 'f')), _vbo.VBO(_array(normal_array, 'f')), len(vertex_array))
def draw(this): if this.bCreate == False: this.vbo = vbo.VBO(ny.array(this.data, 'f')) this.ebo = vbo.VBO(ny.array(this.idata, 'H'), target=GL_ELEMENT_ARRAY_BUFFER) this.eboLength = len(this.idata) this.bCreate = True #this.createVAO() this.vbo.bind() glInterleavedArrays(GL_T2F_V3F, 0, None) this.ebo.bind() glDrawElements(GL_TRIANGLES, this.eboLength, GL_UNSIGNED_SHORT, None)
def init(): global program, vertexPositions, indexPositions glClearColor(0, 1, 0, 0) program = compileProgram(compileShader(vert, GL_VERTEX_SHADER), compileShader(frag, GL_FRAGMENT_SHADER)) vertices = numpy.array([[-1, -1, 0], [1, -1, 0], [1, 1, 0], [1, 1, 0], [-1, 1, 0], [-1, -1, 0]], dtype='f') vertexPositions = vbo.VBO(vertices) indices = numpy.array([[0, 1, 2], [3, 4, 5]], dtype=numpy.int32) indexPositions = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER) glEnableVertexAttribArray(glGetAttribLocation(program, 'p'))
def createvbo(self): self.indvbo = vbo.VBO(self.indbytes, usage='GL_STATIC_DRAW', target='GL_ELEMENT_ARRAY_BUFFER') vbobytes = self.verbytes if self.uvsbytes: self.uvsoff = len(vbobytes) vbobytes += self.uvsbytes if self.colbytes: self.coloff = len(vbobytes) vbobytes += self.colbytes self.vervbo = vbo.VBO(vbobytes, usage='GL_STATIC_DRAW') self.vbomade = True
def prepare_floor(self): size = 6 mesh = trimesh.Trimesh( [[-size, 0, -size], [-size, 0, +size], [+size, 0, +size], [-size, 0, -size], [+size, 0, +size], [+size, 0, -size]], faces=[[0, 1, 2], [3, 4, 5]]) vertices = np.array(mesh.triangles, dtype=np.float32).reshape(-1, 3) vertices = vertices.reshape((-1)) normals = np.repeat(mesh.face_normals, 3, axis=0).astype(np.float32) self.floor_vertices = vbo.VBO(vertices) self.floor_normals = vbo.VBO(normals)
def loadVBO(self): from OpenGL.arrays import vbo X = np.zeros((1,4), dtype = np.float32) C = np.zeros((1,4), dtype = np.float32) self.pos_vbo = vbo.VBO(data=X, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) self.pos_vbo.bind() self.col_vbo = vbo.VBO(data=C, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) self.col_vbo.bind() return self
def __init__( self, texid: int, grid_x: int = 5, grid_y: int = 5, shader: int = 0, ): """ Setup default position for sprite. Initialize mesh of selected size. :param texid: ID of texture :param grid_x: Mesh elements along axis X :param grid_y: Mesh elements along axis Y :param shader: ID of shader. Select 0 if you need no shader """ # Setup default positions of sprite self.position = np.array([0, 0., 0.]) self.rotate = np.array([0., 0., 0.]) self.scale = np.array([1.0, 1.0, 1.0]) self.color = np.array([1.0, 1.0, 1.0]) # Setup default animation settings self.max_animation_timer = 1 self.step_animation_timer = 0.001 # Setup default vectors for image transformation self.vector = np.array([0.0, 0.0, 0.0]) self.rotation_vector = np.array([0.0, 0.0, 0.0]) self._texid = texid self._shader = shader self._time_counter = 0.0 # Create vertices array for the sprite vertices = self._mesh_create(grid_size_x=grid_x, grid_size_y=grid_y) self._vertices_count = len(vertices) self._vbo_vertices = glvbo.VBO(np.array(vertices, 'f')) self._vbo_texcoords = glvbo.VBO(np.array(vertices, 'f') + 0.5) self._vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(self._vao) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY) self._vbo_vertices.bind() gl.glVertexPointer(3, gl.GL_FLOAT, 0, None) self._vbo_texcoords.bind() gl.glTexCoordPointer(3, gl.GL_FLOAT, 0, None) gl.glBindVertexArray(0)
def swapInFrame(self, i, playOrigVideo=True, updateNormals=True): if not self.mesh: self.makeMesh() if i > self.Xs.shape[2]: print "Warning: Trying to load in frame %i that is beyond range of %i frames" % ( i, self.Xs.shape[2]) return m = self.mesh VPos = np.zeros(m.VPos.shape) Mask = self.Mask [X, Y, Z] = [self.Xs[:, :, i], self.Ys[:, :, i], self.Zs[:, :, i]] VPos[:, 0] = X[Mask > 0] VPos[:, 1] = Y[Mask > 0] VPos[:, 2] = -Z[Mask > 0] if playOrigVideo: m.VPos = VPos elif self.rawAmplification: m.VPos = np.reshape(self.newPos[:, i], VPos.shape) else: deltaCoordsAmp = np.reshape(self.ampDeltaCoords[:, i], [VPos.shape[0] * 2, 3]) #Run the solver on the amplified delta coordinates and determine the frame vertices (L, M_inv, solver, deltaCoords) = makeLaplacianMatrixSolverIGLSoft( VPos, m.ITris, np.arange(VPos.shape[0]), self.gamma, makeSolver=True) deltaCoords = deltaCoordsAmp[0:VPos.shape[0], :] posAmp = deltaCoordsAmp[VPos.shape[0]:, :] m.VPos = solveLaplacianMatrixIGLSoft(solver, L, M_inv, deltaCoordsAmp, np.arange(VPos.shape[0]), VPos, self.gamma) if m.VPosVBO: m.VPosVBO.delete() if updateNormals: m.updateNormalBuffer() if m.VNormalsVBO: m.VNormalsVBO.delete() m.VPosVBO = vbo.VBO(np.array(m.VPos, dtype=np.float32)) m.VNormalsVBO = vbo.VBO(np.array(m.VNormals, dtype=np.float32)) if self.loadedColor: if m.VColorsVBO: m.VColorsVBO.delete() c = getColorsFromMap(self.us[:, :, i], self.vs[:, :, i], self.Cs[:, :, :, i], self.Mask) m.VColors = c print "Getting colors" m.VColorsVBO = vbo.VBO(np.array(c, dtype=np.float32))
def _try_load_model(self): error, model = openvr.VRRenderModels().loadRenderModel_Async( self.model_name) if error == openvr.VRRenderModelError_Loading: return vertices0 = list() indices0 = list() if model is not None: for v in range(model.unVertexCount): vd = model.rVertexData[v] vertices0.append(float(vd.vPosition.v[0])) # position X vertices0.append(float(vd.vPosition.v[1])) # position Y vertices0.append(float(vd.vPosition.v[2])) # position Z vertices0.append(float(vd.vNormal.v[0])) # normal X vertices0.append(float(vd.vNormal.v[1])) # normal Y vertices0.append(float(vd.vNormal.v[2])) # normal Z vertices0.append(float( vd.rfTextureCoord[0])) # texture coordinate U vertices0.append(float( vd.rfTextureCoord[1])) # texture coordinate V for i in range(model.unTriangleCount * 3): index = model.rIndexData[i] indices0.append(int(index)) vertices0 = numpy.array(vertices0, dtype=numpy.float32) indices0 = numpy.array(indices0, dtype=numpy.uint32) # self.vertexPositions = vbo.VBO(vertices0) self.indexPositions = vbo.VBO(indices0, target=GL.GL_ELEMENT_ARRAY_BUFFER) # http://stackoverflow.com/questions/14365484/how-to-draw-with-vertex-array-objects-and-gldrawelements-in-pyopengl self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) self.vertexPositions.bind() self.indexPositions.bind() # Vertices GL.glEnableVertexAttribArray(0) fsize = sizeof(c_float) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 8 * fsize, cast(0 * fsize, c_void_p)) # Normals GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, False, 8 * fsize, cast(3 * fsize, c_void_p)) # Texture coordinates GL.glEnableVertexAttribArray(2) GL.glVertexAttribPointer(2, 2, GL.GL_FLOAT, False, 8 * fsize, cast(6 * fsize, c_void_p)) GL.glBindVertexArray(0) self.model = model self.model_is_loaded = True self._try_load_texture()
def generate_vbos(self): """Generates the vbo for this MeshPart Creates the arrays that are necessary for smooth rendering """ from OpenGL.arrays import vbo from numpy import array # Build VBO v = [] n = [] t = [] c = [] for face in self.faces: v1 = self.parent.vertices[face.a.vertex] v2 = self.parent.vertices[face.b.vertex] v3 = self.parent.vertices[face.c.vertex] v += [[v1.x, v1.y, v1.z], [v2.x, v2.y, v2.z], [v3.x, v3.y, v3.z]] if face.a.normal is not None: n1 = self.parent.normals[face.a.normal] n2 = self.parent.normals[face.b.normal] n3 = self.parent.normals[face.c.normal] n += [[n1.x, n1.y, n1.z], [n2.x, n2.y, n2.z], [n3.x, n3.y, n3.z]] if face.a.tex_coord is not None: t1 = self.parent.tex_coords[face.a.tex_coord] t2 = self.parent.tex_coords[face.b.tex_coord] t3 = self.parent.tex_coords[face.c.tex_coord] t += [[t1.x, t1.y], [t2.x, t2.y], [t3.x, t3.y]] if len(self.parent.colors) > 0: # face.a.color is not None: c1 = self.parent.colors[face.a.vertex] c2 = self.parent.colors[face.b.vertex] c3 = self.parent.colors[face.c.vertex] c += [[c1.x, c1.y, c1.z], [c2.x, c2.y, c2.z], [c3.x, c3.y, c3.z]] self.vertex_vbo = vbo.VBO(array(v, 'f')) if len(n) > 0: self.normal_vbo = vbo.VBO(array(n, 'f')) if len(t) > 0: self.tex_coord_vbo = vbo.VBO(array(t, 'f')) if len(c) > 0: self.color_vbo = vbo.VBO(array(c, 'f'))
def fountain(num, method=fountain_urqmd): """Initialize position, color and velocity arrays we also make Vertex Buffer Objects for the position and color arrays""" pos, col, vel = method(num) #create the Vertex Buffer Objects from OpenGL.arrays import vbo pos_vbo = vbo.VBO(data=pos, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) pos_vbo.bind() col_vbo = vbo.VBO(data=col, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) col_vbo.bind() return (pos_vbo, col_vbo, vel)
def update(self, xyz=None, rgb=None, pose=None): ''' Update the point clouds points (XYZ or RGB) and/or pose. `xyz` and `rgb` are (N, 3) arrays of positions and colors. The normalization of colors is assumed from their datatype. `pose` is a 4x4 transformation matrix. Alternatively, `xyz` is an (N, 6) array of packed positions and colors. The first 3 elements of each vector are interpreted as position whereas hte second 3 elements of each vector are interpreted as non-normalized color (0-255). ''' if pose is not None: self._pose = numpy.array(pose, dtype=numpy.float32) if xyz is not None: if not isinstance(xyz, numpy.ndarray): xyz = numpy.array(xyz) xyz = xyz.reshape((-1, xyz.shape[-1])) if xyz.shape[-1] == 6: # split up the position and color components rgb = xyz[:, 3:6] xyz = xyz[:, 0:3] if xyz.shape[-1] != 3: raise RuntimeError( 'invalid point cloud XYZ dimension: {}'.format(xyz.shape)) # ref: http://pyopengl.sourceforge.net/context/tutorials/shader_1.html self._xyz_vbo = vbo.VBO(xyz.astype(numpy.float32)) logger.debug('loaded point cloud with {} XYZ points'.format( xyz.shape)) if rgb is not None: if not isinstance(xyz, numpy.ndarray): rgb = numpy.array(rgb) rgb = rgb.reshape((-1, rgb.shape[-1])) if rgb.shape[-1] != 3: raise RuntimeError( 'invalid point cloud RGB dimension: {}'.format(rgb.shape)) # infer normalization from datatype if numpy.issubdtype(rgb.dtype, numpy.integer): normalization = 255 else: normalization = 1 self._rgb_vbo = vbo.VBO(rgb.astype(numpy.float32) / normalization) logger.debug('loaded point cloud with {} RGB points'.format( rgb.shape))
def load_vbo(pc_data, clr_data): """获取顶点和颜色信息""" if pc_data.size == 0: return try: vtx_Point = glvbo.VBO(pc_data[:, :3].astype( np.float32)) # 使用 顶点_强度_颜色 数组的前三列,创建顶点数据VBO except: global_log.error("shape:{}\nexcept:\n{}".format( pc_data.shape, traceback.format_exc())) vtx_Color = glvbo.VBO(clr_data.astype(np.float32) / 255.0) # 使用 顶点_强度_颜色 数组的后三列,创建颜色数据VBO vtx_count = len(pc_data) # 记录一帧数据的顶点个数 return vtx_Point, vtx_Color, vtx_count
def make(self): """ This function creates vertices and indices :return: """ if self.shape is "sphere": v, t, n, tex = objects.sphere(self.size) self.vertices = vbo.VBO(v, target=GL_ARRAY_BUFFER, usage=GL_STATIC_DRAW) self.indices = vbo.VBO(t, target=GL_ELEMENT_ARRAY_BUFFER) elif self.shape is "parallelepiped": v, t, = objects.parallelepiped(self.size) self.vertices = vbo.VBO(v, target=GL_ARRAY_BUFFER, usage=GL_STATIC_DRAW) self.indices = vbo.VBO(t, target=GL_ELEMENT_ARRAY_BUFFER) elif self.shape is "cross": # Fixation cross v, t = objects.cross() self.vertices = vbo.VBO(v, target=GL_ARRAY_BUFFER, usage=GL_STATIC_DRAW) self.indices = vbo.VBO(t, target=GL_ELEMENT_ARRAY_BUFFER) elif self.shape is 'line': v = np.array([ [-1.0, 0.0, 0.0], [1.0, 0.0, 0.0] ], dtype='float32') t = np.array([0, 1], np.int32) self.vertices = vbo.VBO(v*self.size, target=GL_ARRAY_BUFFER, usage=GL_STATIC_DRAW) self.indices = vbo.VBO(t, target=GL_ELEMENT_ARRAY_BUFFER) else: raise Exception('{} is not a valid object shape'.format(self.shape))
def draw(this): if this.bCreate == False: this.vbo = vbo.VBO(np.array(this.data, 'f')) this.ebo = vbo.VBO(np.array(this.idata, 'H'), target=GL_ELEMENT_ARRAY_BUFFER) this.eboLength = len(this.idata) this.bCreate = True #this.createVAO() this.vbo.bind() # 函数将会将会根据参数,激活各种顶点数组,并存储顶点 glInterleavedArrays(GL_T2F_V3F, 0, None) this.ebo.bind() # 会按照我们传入的顶点顺序和指定的绘制方式进行绘制 GL_TRIANGLES三角形 glDrawElements(GL_TRIANGLES, this.eboLength, GL_UNSIGNED_SHORT, None)
def reorganize(self, faces, vs, ns, ts): """ We have to reorganize the data such that we can index everything with one index array. For this we create vertices that contain texture and noral information (possibly duplicating data) and an index array that indexes the vertices for each face """ last_ind = 0 vertices = [] vertex_indices = [] for f in faces: v1 = vs[f.vertexIndices[0]] v2 = vs[f.vertexIndices[1]] v3 = vs[f.vertexIndices[2]] t1 = ts[f.texIndices[0]] t2 = ts[f.texIndices[1]] t3 = ts[f.texIndices[2]] n1 = ns[f.normals[0]] n2 = ns[f.normals[1]] n3 = ns[f.normals[2]] vertex1 = [v1 + n1 + t1] vertex2 = [v2 + n2 + t2] vertex3 = [v3 + n3 + t3] if vertex1 in vertices: ind1 = vertices.index(vertex1) else: vertices.append(vertex1) ind1 = last_ind last_ind += 1 if vertex2 in vertices: ind2 = vertices.index(vertex2) else: vertices.append(vertex2) ind2 = last_ind last_ind += 1 if vertex3 in vertices: ind3 = vertices.index(vertex3) else: vertices.append(vertex3) ind3 = last_ind last_ind += 1 vertex_indices += [[ind1, ind2, ind3]] self.vbo = vbo.VBO(np.array(vertices, dtype=np.float32)) self.ebo = vbo.VBO(np.array(vertex_indices, dtype=np.int32), target=gl.GL_ELEMENT_ARRAY_BUFFER)
def loadMesh(stl): # Get information about our mesh our_mesh = mesh.Mesh.from_file(stl) params.num_of_verts = our_mesh.vectors.shape[0] * 3 params.bounds = { 'xmin': np.min(our_mesh.vectors[:, :, 0]), 'xmax': np.max(our_mesh.vectors[:, :, 0]), 'ymin': np.min(our_mesh.vectors[:, :, 1]), 'ymax': np.max(our_mesh.vectors[:, :, 1]), 'zmin': np.min(our_mesh.vectors[:, :, 2]), 'zmax': np.max(our_mesh.vectors[:, :, 2]) } params.total_thickness = params.bounds['zmax'] - params.bounds['zmin'] # make VAO for drawing our mesh params.VAO = glGenVertexArrays(1) glBindVertexArray(params.VAO) vertVBO = vbo.VBO(data=our_mesh.vectors.astype(GLfloat).tostring(), usage='GL_STATIC_DRAW', target='GL_ARRAY_BUFFER') vertVBO.bind() vertVBO.copy_data() glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), vertVBO) glEnableVertexAttribArray(0) glBindVertexArray(0) # a mask vertex array for stencil buffer to subtract maskVert = np.array( [[0, 0, 0], [printer.width * printer.pixel, 0, 0], [printer.width * printer.pixel, printer.height * printer.pixel, 0], [0, 0, 0], [printer.width * printer.pixel, printer.height * printer.pixel, 0], [0, printer.height * printer.pixel, 0]], dtype=GLfloat) # make VAO for drawing mask params.maskVAO = glGenVertexArrays(1) glBindVertexArray(params.maskVAO) maskVBO = vbo.VBO(data=maskVert.tostring(), usage='GL_STATIC_DRAW', target='GL_ARRAY_BUFFER') maskVBO.bind() maskVBO.copy_data() glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), maskVBO) glEnableVertexAttribArray(0) maskVBO.unbind() glBindVertexArray(0)
def _load_camera_model(self, cam_model_files: Tuple[str, str]): vertices = [] texcoords = [] faces = [] for line in open(cam_model_files[0]): t, *coords = line.split() if t == 'v': vertices.append(list(map(float, coords))) elif t == 'vt': texcoords.append(list(map(float, coords))) elif t == 'f': faces.append(list(map(int, coords))) self._camera_model_vertices_buffer = vbo.VBO( np.array(sum((vertices[i - 1] for i in sum(faces, [])), []), dtype=np.float32)) self._camera_model_texcoords_buffer = vbo.VBO( np.array(sum((texcoords[i - 1] for i in sum(faces, [])), []), dtype=np.float32)) self._camera_model_tex = GL.glGenTextures(1) image_data = cv2.imread(cam_model_files[1]) image_data = cv2.resize(image_data, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) height, width, _ = image_data.shape self._camera_model_texture_size = (width, height) self._camera_screen_coords = np.array( [(0.113281 * width, 0.0313 * height), (0.28125 * width, 0.1485 * height)], dtype=np.int) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glBindTexture(GL.GL_TEXTURE_2D, self._camera_model_tex) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB, width, height, 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, np.flipud(image_data)) GL.glGenerateMipmap(GL.GL_TEXTURE_2D)
def __init__(self, parent=None, **kwargs): super(TestWidget, self).__init__(parent, **kwargs) self.data = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]], dtype=np.float32) self.cols = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]], dtype=np.float32) self.index = np.array([0, 1, 2, 0, 3, 2], dtype=np.uint32) print(self.cols) self.vbo = glvbo.VBO(self.data) self.vbo_cols = glvbo.VBO(self.cols) self.vbo_index = glvbo.VBO(self.index, target=gl.GL_ELEMENT_ARRAY_BUFFER)
def _update_buffers(self, vertices, normals): self.render_lock.acquire() if self.vertex_buffer is None: self.vertex_buffer = vbo.VBO(vertices) else: self.vertex_buffer.set_array(vertices) if self.normal_buffer is None: self.normal_buffer = vbo.VBO(normals) else: self.normal_buffer.set_array(normals) self.vertex_buffer_size = vertices.shape[0] self.request_render = True self.render_lock.release()
def constructCylinderMesh(self, slices, radius, length, direction): self.slices = slices self.radius = radius self.vertex_array_type = GL_TRIANGLES vertex_list, tris = construct_triangle_cylinder(slices, radius, length) self.numVertices = len(vertex_list) self.numIndices = len(tris) * 3 # Create the Vertex Array Object self.vertexArrayObject = GLuint(0) glGenVertexArrays(1, self.vertexArrayObject) glBindVertexArray(self.vertexArrayObject) indices = np.array( tris, dtype='uint32') # np.array(tris).reshape(1,numIndices)[0] self.indices = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER) self.vertices = vbo.VBO(np.array(vertex_list, 'f'))
def initVBO(self): if self.mTextureID != 0 and self.mVBO is None: vData = [] for i in range(4): vData.append(HVertexData2D()) iData = np.arange(4, dtype=GLuint) vDataBytes = vData[0].tobytes() + vData[1].tobytes( ) + vData[2].tobytes() + vData[3].tobytes() self.mVBO = vbo.VBO(data=vDataBytes, usage='GL_DYNAMIC_DRAW', target='GL_ARRAY_BUFFER') self.mIBO = vbo.VBO(data=iData.tobytes(), usage='GL_DYNAMIC_DRAW', target='GL_ELEMENT_ARRAY_BUFFER')
def __init__(self,output_size,in_tex_array_id): self.texsize = output_size self.tex_array_id = in_tex_array_id self.fbo = FBO_RTT(output_size,output_size) self.data = np.zeros([output_size,output_size],dtype='float32') self.shader = MaterialManager.Materials['surfacemeasure'] self.posattr = glGetAttribLocation(self.shader,'positions') self.texattr = glGetAttribLocation(self.shader,'texcoords') self.vertexbuffer = np.array([-1.0,-1.0,0.0,0.0,1.0, -1.0,1.0,0.0,1.0,1.0, 1.0,1.0,1.0,1.0,1.0, 1.0,-1.0,1.0,0.0,1.0],dtype='float32') self.vbo = vbo.VBO(data=self.vertexbuffer,usage=GL_DYNAMIC_DRAW,target=GL_ARRAY_BUFFER) self.ibo = vbo.VBO(data=np.array([0,2,3,0,1,2],dtype='uint32'),usage=GL_DYNAMIC_DRAW,target=GL_ELEMENT_ARRAY_BUFFER) self.out_data = np.zeros([output_size,output_size], dtype = 'float32')
def create_piramid_vbo(arista=1.0): """Crea una piramide de base cuadrada usando vbos para el manejo de shaders, retorna un objeto vboObject""" def ex(element): """Exporta el elemento a una lista""" return element.export_to_list() # Se crean los puntos a = Point3(-0.5, -0.5, -0.333) * arista b = Point3(0.5, -0.5, -0.333) * arista c = Point3(0.5, 0.5, -0.333) * arista d = Point3(-0.5, 0.5, -0.333) * arista e = Point3(0.0, 0.0, 0.666) * arista # Se crean las normales n1 = ex(normal3points(a, b, e)) n2 = ex(normal3points(b, c, e)) n3 = ex(normal3points(c, d, e)) n4 = ex(normal3points(d, a, e)) n5 = ex(normal3points(c, b, a)) # Se crean las listas de puntos y normales en orden por triangulos, cada 3 puntos se forma una cara vertex_array = [ ex(b), ex(e), ex(a), ex(b), ex(c), ex(e), ex(c), ex(d), ex(e), ex(d), ex(a), ex(e), ex(a), ex(b), ex(c), ex(c), ex(d), ex(a) ] normal_array = [ n1, n1, n1, n2, n2, n2, n3, n3, n3, n4, n4, n4, n5, n5, n5, n5, n5, n5 ] # Se retornan los vertex buffer object return VboObject(vbo.VBO(array(vertex_array, 'f')), vbo.VBO(array(normal_array, 'f')), len(vertex_array))