def init3d_view(self): view = gl.GLViewWidget() # view.show() self.mainbox.layout().addWidget( view, 0, 3, 2, 3) # last param = number of buttons + 1 ## create three grids, add each to the view xgrid = gl.GLGridItem() ygrid = gl.GLGridItem() zgrid = gl.GLGridItem() view.addItem(xgrid) view.addItem(ygrid) view.addItem(zgrid) ## rotate x and y grids to face the correct direction xgrid.rotate(90, 0, 1, 0) ygrid.rotate(90, 1, 0, 0) ## scale each grid differently xgrid.scale(0.2, 0.1, 0.1) ygrid.scale(0.2, 0.1, 0.1) zgrid.scale(0.1, 0.2, 0.1) self.gyro_point = gl.GLMeshItem(meshdata=gl.MeshData.sphere( radius=0.25, rows=16, cols=16), color=(0.0, 0.7, 0.0, 1.0)) self.gyro_point.translate(0, 0, 0) view.addItem(self.gyro_point) self.acc_point = gl.GLMeshItem(meshdata=gl.MeshData.sphere(radius=0.25, rows=16, cols=16), color=(0.7, 0.0, 0.0, 1.0)) self.acc_point.translate(0, 0, 0) view.addItem(self.acc_point)
def make_mesh(xyzs, indices, face_colours = [], shader = "shaded", gloptions = "opaque", draw_edges = False, edge_colours = [0,0,0,1]): """ This function returns a Mesh Item that can be viz by pyqtgraph. Parameters ---------- xyzs : ndarray of shape(Nvertices,3) ndarray of shape(Nvertices,3) of the mesh. indices : ndarray of shape(Ntriangles,3) indices of the mesh. face_colours : ndarray of shape(Ntrianges, 4), optional array of colours specifying the colours of each triangles of the mesh. shade : string, optional specify the shader visualisation of the mesh. The options are: shaded, balloon, normalColor, viewNormalColor, edgeHilight, heightColor gloptions : string, optional specify the gloption visualisation of the mesh. The options are: additive, opaque, translucent draw_edges : bool, optional toggle to whether draw the edges of the mesh edge_colours: list, option list with four elements specifying the RGB and Transparency of the edges. Returns ------- mesh : mesh object mesh for visualisation. """ if face_colours == []: mesh = gl.GLMeshItem(vertexes = xyzs, faces = indices, faceColors = None, edgeColor = edge_colours, smooth = False, drawEdges = draw_edges, shader = shader, glOptions = gloptions) else: mesh = gl.GLMeshItem(vertexes = xyzs, faces = indices, faceColors = face_colours, edgeColor = edge_colours, smooth = False, drawEdges = draw_edges, shader = shader, glOptions = gloptions) return mesh
def setup_ui(self): self.gird = OpenGL.GLGridItem() self.addItem(self.gird) self.axis = OpenGL.GLAxisItem() self.addItem(self.axis) self.mesh = OpenGL.GLMeshItem() self.addItem(self.mesh) self.scene = OpenGL.GLMeshItem() self.addItem(self.scene)
def GetShape(shape, gl=None, r=15, spin=0, mode=0, edges=True, bold=.05): face = [] color = [] n = len(shape) - 1 cn = 1 / (n + 3) c = 1 for f in range(n): if c >= n: face.append([0, c, 1]) else: face.append([0, c, c + 1]) if mode is 0: color.append([.5, 0.3, .9, bold]) elif mode is 1: color.append([.8 - c * cn * r, c * cn, .9, bold]) elif mode is 2: color.append( [.8 - c * cn * r, c * cn, .9 - c * cn * 0.1 * r, bold]) elif mode is 3: color.append([ .6 - (c * cn * r) / 10, c * cn, .9 - (c * cn * 0.1) / 2, bold ]) elif mode is 4: color.append([ .1 * (r / 2), c * cn * r * 0.05, .15 * (c * cn * r * 0.1) / 2, bold ]) c += 1 verts = np.array(shape) faces = np.array(face) colors = np.array(color) ## Mesh item will automatically compute face normals. #mx = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colors, smooth=False) if edges: mx = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colors, smooth=False, drawEdges=True, edgeColor=(1, 1, 0, 0.3)) else: mx = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colors, smooth=False) #mx = gl.GLMeshItem(vertexes=verts) mx.translate(0, 0, 0) mx.setGLOptions('additive') return mx, shape
def build_recursive(self, coordinate: Coordinate, side: int, n: int): """ Рекурсивная функция для построения пирамиды Серпинского :param coordinate: кордината центра вписанной окружности в основание пирамиды :param side: длина стороны пирамиды :param n: Параметр рекурсии """ # получаем массивы точек для отрисовки points = self.get_tetrahedron_tops(coordinate, side) # точки A, B, C, D vertex = np.array([ [points[0].x, points[0].y, points[0].z], [points[1].x, points[1].y, points[1].z], [points[2].x, points[2].y, points[2].z], [points[3].x, points[3].y, points[3].z], ]) # создаем грани ABC, ABD, ACD, BCD faces = np.array([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]) # раскрашиваем их в цвета colors = np.array([[1, 0, 0, 1.0], [0, 1, 0, 1.0], [0, 0, 1, 1.0], [1, 1, 0, 1.0]]) # если пирамиды достаточной глубины рекурсии не построены - строим их незакрашенными if n > 0: n -= 1 mesh = gl.GLMeshItem(vertexes=vertex, faces=faces, faceColors=colors, smooth=False, drawEdges=True, drawFaces=False) # добавляем незакрашенную верхнеуровневую пирамиду-каркас к списку пирамиид self.meshes.append(mesh) # строим четыре пирамиды внутри каркаса side /= 2 # находим координаты окружностей, вписанных в непоспостроенные пока еще пирамиды внутри каркаса circle_1, circle_2, circle_3, circle_4 = self.get_circle_center( coordinate, side) # для каждой пары - координаты окружности/деленная пополам длина ребра - вызываем рекурсивно функцию self.build_recursive(circle_1, side, n) self.build_recursive(circle_2, side, n) self.build_recursive(circle_3, side, n) self.build_recursive(circle_4, side, n) n += 1 # дошли до конца в рекурсии - красим пирамиду else: mesh = gl.GLMeshItem(vertexes=vertex, faces=faces, faceColors=colors, smooth=False, drawEdges=True, drawFaces=True) self.meshes.append(mesh)
def createXaxis(self, father): # x-axis x_axis = gl.MeshData.cylinder(rows=10, cols=20, radius=[0.1, 0.1], length=44.) x_axis = gl.GLMeshItem(meshdata=x_axis, smooth=False, color=(0, 1, 0, 0.7), shader='balloon', glOptions='additive') father.addItem(x_axis) x_axis.rotate(-90., 1, 0, 0) x_axis.translate(0, -22, 0) x_axis_arrow = gl.MeshData.cylinder(rows=10, cols=20, radius=[0.5, 0.], length=2.) x_axis_arrow = gl.GLMeshItem(meshdata=x_axis_arrow, smooth=False, color=(0, 1, 0, 0.7), shader='balloon', glOptions='additive') father.addItem(x_axis_arrow) x_axis_arrow.rotate(-90., 1, 0, 0) x_axis_arrow.translate(0, 22, 0) x_axis_word = gl.MeshData.cylinder(rows=10, cols=20, radius=[0.2, 0.2], length=3) x_axis_word = gl.GLMeshItem(meshdata=x_axis_word, smooth=False, color=(0, 1, 0, 0.7), shader='balloon', glOptions='additive') father.addItem(x_axis_word) x_axis_word.rotate(-30, 1, 0, 0) x_axis_word.translate(0, 25, 0) x_axis_word = gl.MeshData.cylinder(rows=10, cols=20, radius=[0.2, 0.2], length=3) x_axis_word = gl.GLMeshItem(meshdata=x_axis_word, smooth=False, color=(0, 1, 0, 0.7), shader='balloon', glOptions='additive') father.addItem(x_axis_word) x_axis_word.rotate(30, 1, 0, 0) x_axis_word.translate(0, 26.5, 0)
def loadPreset(self): preset = ('./lib/presets/systems/'+self.cmb_preset.currentText()) self.reset() with open(preset, 'r') as f: reader = csv.reader(f, delimiter=',') next(reader) for row in reader: if row[0] == "s": self.star = Star(row[1],float(row[2]),float(row[3])) if row[0] == "p": body = Body(row[1],float(row[2]),float(row[3]),float(row[4]),float(row[5]),float(row[6])) if body.color == None: body.color = (random(),random(),random(),1.0) self.body_list.append(body) print(body.color) for body in self.body_list: pix = QPixmap(20,20) pix.fill(QColor(body.color[0]*255, body.color[1]*255, body.color[2]*255)) icon = QIcon(pix) item = QStandardItem(icon, body.name) self.body_list_model.appendRow(item) self.le_starname.setText(str(self.star.name)) self.le_starmass.setText(str(self.star.mass)) self.le_starradius.setText(str(self.star.radius)) for location, body in enumerate(self.body_list): try: texture = imread(planet_textures_path+body.name.lower()+'.jpg') texture = texture / 255 mesh = gl.MeshData.sphere(rows=300, cols=400, radius=1) mesh.setVertexColors(colors=texture) mesh_item = gl.GLMeshItem(meshdata=mesh, smooth=True, computeNormals=False, shader='balloon') mesh_item.scale(1,1,1) mesh_item.translate(location*5,0,0) self.gv_system_view.addItem(mesh_item) except Exception as e: print(e) pass md = gl.MeshData.sphere(rows=600, cols=800, radius=1) try: colors = imread('./lib/assets/textures/stars/G.png') colors = colors / 255 md.setVertexColors(colors=colors) except: pass mi = gl.GLMeshItem(meshdata=md, smooth=True, computeNormals=False, shader='balloon') mi.scale(3, 3, 3) self.gv_system_view.addItem(mi)
def assemble_robot(self): ''' Create meshItems containing the robot's geometry and set mesh attributes, namely shading and parents ''' gl_options = "opaque" shader = "edgeHilight" sf = 3 wheel_color = (.8 / sf, .8 / sf, .8 / sf, 0.2) load_color = wheel_color base_color = wheel_color # Load meshes as GLMeshItems self.item_wheel_l = gl.GLMeshItem(meshdata=self.mesh_wheel_l, smooth=True, color=wheel_color, shader=shader, glOptions=gl_options) self.item_wheel_r = gl.GLMeshItem(meshdata=self.mesh_wheel_r, smooth=True, color=wheel_color, shader=shader, glOptions=gl_options) self.item_load = gl.GLMeshItem(meshdata=self.mesh_load, smooth=False, color=load_color, shader=shader, glOptions=gl_options) self.item_pendulum = gl.GLMeshItem(meshdata=self.mesh_pendulum, smooth=False, color=base_color, shader=shader, glOptions=gl_options) self.item_track = gl.GLMeshItem(meshdata=self.mesh_track, smooth=True, color=base_color, shader=shader, glOptions=gl_options) # Establish Parent Child Relationships self.item_wheel_l.setParent(self.item_track) self.item_wheel_r.setParent(self.item_track) self.item_pendulum.setParent(self.item_track) self.item_load.setParent(self.item_pendulum) self.draw_origin() # Add to scene self.addItem(self.item_wheel_l) self.addItem(self.item_wheel_r) self.addItem(self.item_load) self.addItem(self.item_pendulum) self.addItem(self.item_track)
def drawatoms(self, mol): '''Draw the atoms. :param molecule: The molecule for which to draw the atoms. :type molecule: molecule.Molecule ''' scale = 0.25 rows = 16 cols = 16 shader = 'shaded' smooth = True for atom in mol.atoms: radius = atom.radius() * scale pos = atom.r md = gl.MeshData.sphere(rows=rows, cols=cols, radius=radius) m = gl.GLMeshItem(meshdata=md, smooth=smooth, shader=shader) colors = np.ones((md.faceCount(), 4), dtype=float) rgb = atom.color() colors[:, 0] = rgb[0] # r colors[:, 1] = rgb[1] # g colors[:, 2] = rgb[2] # b colors[:, 3] = 1.0 # a md.setFaceColors(colors) m.translate(pos[0], pos[1], pos[2]) self.viewwidget.addItem(m)
def draw_arrow(self, v1, v2, tip_width, tip_length_scale, color, line_width=2): v2, v1 = np.array(v1), np.array(v2) line = gl.GLLinePlotItem(pos=np.array([v1, v2]), width=line_width, color=color, antialias=False) dist = np.linalg.norm(np.array(v1) - np.array(v2)) c = np.dot([0, 0, 1], v2 - v1) / np.linalg.norm(v2 - v1) ang = np.arccos(np.clip(c, -1, 1)) / np.pi * 180 vec_norm = np.cross([0, 0, 1], v2 - v1) md = gl.MeshData.cylinder(rows=10, cols=20, radius=[0, tip_width], length=dist * tip_length_scale) # if mesh_item == None: mesh_item = gl.GLMeshItem(meshdata=md, smooth=True, color=color, shader='shaded', glOptions='opaque') # else: # mesh_item.setMeshData(meshdata = md) mesh_item.rotate(ang, *vec_norm) mesh_item.translate(*v1) return line, mesh_item
def __init__(self): """ Initialize the graphics window and mesh surface """ # setup the view window self.app = QtGui.QApplication(sys.argv) self.window = gl.GLViewWidget() self.window.setWindowTitle('Terrain') self.window.setGeometry(0, 110, 1920, 1080) self.window.setCameraPosition(distance=30, elevation=12) self.window.show() # constants and arrays self.nsteps = 1 self.ypoints = np.arange(-20, 20 + self.nsteps, self.nsteps) self.xpoints = np.arange(-20, 20 + self.nsteps, self.nsteps) self.nfaces = len(self.ypoints) # create the veritices array verts, faces, colors = self.mesh() self.mesh1 = gl.GLMeshItem( faces=faces, vertexes=verts, faceColors=colors, drawEdges=True, smooth=False, ) self.mesh1.setGLOptions('additive') self.window.addItem(self.mesh1)
def renderVolume(self): import pyqtgraph.opengl as pgl import scipy.ndimage as ndi self.glView = pgl.GLViewWidget() img = np.ascontiguousarray(self.displayAtlas[::8, ::8, ::8]) # render volume #vol = np.empty(img.shape + (4,), dtype='ubyte') #vol[:] = img[..., None] #vol = np.ascontiguousarray(vol.transpose(1, 2, 0, 3)) #vi = pgl.GLVolumeItem(vol) #self.glView.addItem(vi) #vi.translate(-vol.shape[0]/2., -vol.shape[1]/2., -vol.shape[2]/2.) verts, faces = pg.isosurface( ndi.gaussian_filter(img.astype('float32'), (2, 2, 2)), 5.0) md = pgl.MeshData(vertexes=verts, faces=faces) mesh = pgl.GLMeshItem(meshdata=md, smooth=True, color=[0.5, 0.5, 0.5, 0.2], shader='balloon') mesh.setGLOptions('additive') mesh.translate(-img.shape[0] / 2., -img.shape[1] / 2., -img.shape[2] / 2.) self.glView.addItem(mesh) self.glView.show()
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("Multiagent Communication") uic.loadUi('crazyflie_multiagent.ui', self) self.gl_widget = gl.GLViewWidget() self.gl_widget.setWindowTitle('Multi-agent Plotter') self.gl_widget.addItem(gl.GLGridItem()) # Add the grid to the plot self.addAxis() # Initialise mesh item to represent an agent md = gl.MeshData.sphere(rows=5, cols=5, radius=0.25) self.agent_mesh = gl.GLMeshItem(meshdata=md, smooth=False, drawFaces=False, drawEdges=True, edgeColor=(1, 1, 1, 1)) self.gl_widget.addItem(self.agent_mesh) self.btn_exit.clicked.connect(self.btn_exit_clicked) self.action3D_visualiser.triggered.connect(self.open_visualiser)
def makeParallelepiped(self, k, l, w, h): verts = np.array([ [k + l, 0, 0], # 0 [0, 0, 0], # 1 [0, k + w, 0], # 2 [0, 0, k + h], # 3 [k + l, k + w, 0], # 4 [k + l, k + w, k + h], # 5 [0, k + w, k + h], # 6 [k + l, 0, k + h] ]) # 7 faces = np.array([[1, 0, 7], [1, 3, 7], [1, 2, 4], [1, 0, 4], [1, 2, 6], [1, 3, 6], [0, 4, 5], [0, 7, 5], [2, 4, 5], [2, 6, 5], [3, 6, 5], [3, 7, 5]]) r, g, b = rainbowColors() op = .15 colors = np.array([[r, g, b, op] for _ in range(12)]) m1 = gl.GLMeshItem(vertexes=verts, faces=faces, drawFaces=True, drawEdges=True, faceColors=colors, smooth=False, edgeColor=(r, g, b, op), shader='balloon') m1.setGLOptions('additive') self.allDict['parals'].append(m1) self.allParals[m1] = (l + k, w + k, h + k)
def __init__(self): self.traces = dict() self.app = QtGui.QApplication(sys.argv) self.w = gl.GLViewWidget() self.w.opts['distance'] = 60 self.w.setWindowTitle('pyqtgraph example: GLLinePlotItem') self.w.setGeometry(0, 110, 1920, 1080) self.w.show() gx = gl.GLGridItem() gx.rotate(90, 0, 1, 0) gx.translate(-10, 0, 0) self.w.addItem(gx) gy = gl.GLGridItem() gy.rotate(90, 1, 0, 0) gy.translate(0, -10, 0) self.w.addItem(gy) gz = gl.GLGridItem() gz.translate(0, 0, -10) self.w.addItem(gz) m1 = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colors, smooth=False) m1.translate(0, 0.1, 0) m1.setGLOptions('additive') self.w.addItem(m1) self.n = new_particle_source.N for i in range(self.n): pts = np.vstack([x_cords[i], y_cords[i], z_cords[i]]).transpose() self.traces[i] = gl.GLLinePlotItem(pos=pts, antialias=True) self.w.addItem(self.traces[i])
def vis3D_glassBrain(brain_array, pad, ds_factor): # initialize the window view = pgl.GLViewWidget() # downsample the brain image using the ds_factor img = brain_array[::ds_factor, ::ds_factor, ::ds_factor] # do padding of the brain to avoid holes during rendering pad_img = np.zeros( (img.shape[0] + pad, img.shape[1] + pad, img.shape[2] + pad), dtype=img.dtype) pad_img[pad / 2:pad / 2 + img.shape[0], pad / 2:pad / 2 + img.shape[1], pad / 2:pad / 2 + img.shape[2]] = img # build the brain isosurface verts, faces = pg.isosurface( ndi.gaussian_filter(pad_img.astype('float32'), (1, 1, 1)), 5.0) md = pgl.MeshData(vertexes=verts, faces=faces) mesh = pgl.GLMeshItem(meshdata=md, smooth=True, color=[0.5, 0.5, 0.5, 0.1], shader='balloon') mesh.setGLOptions('additive') mesh.translate(-pad_img.shape[0] * (ds_factor / 2.), -pad_img.shape[1] * (ds_factor / 2.), -pad_img.shape[2] * (ds_factor / 2.)) mesh.scale(ds_factor, ds_factor, ds_factor) mesh.rotate(-90, 1, 0, 0) view.addItem(mesh) view.setCameraPosition(distance=200, elevation=20, azimuth=90) view.setWindowTitle('Consciousness is an illusion') view.show() return view
def openStlDialog(self): fname = QFileDialog.getOpenFileName(self, 'Open file', '', "Mesh (*.stl);") if fname[0]: ext_file = path.splitext(fname[0])[1] if ext_file.lower() in fname[1]: self.initParam() self.message("Load " + fname[0]) self.model_path = fname[0] else: return #self.mesh = mesh.Mesh.from_file(fname[0]) #self.mesh_info = modelInfo.ModelInfo(self.mesh) #self.mesh_info.path = fname[0] self.mesh = self.mesh_info.load(fname[0]) self.message(self.mesh_info.get_info()) verts = self.mesh.vectors.reshape(self.mesh.vectors.shape[0]*3,3) n_face = self.mesh.vectors.shape[0] faces = np.arange(n_face*3) faces = faces.reshape(n_face, 3) colors = [1,0,0,0.3] colors = colors * n_face colors = np.array(colors).reshape(n_face, 4) self.update_ui() else: return #verts = np.array([ #[0, 0, 0], #[2, 0, 0], #[1, 2, 0], #[1, 1, 1], #])*50 #faces = np.array([ #[0, 1, 2], #[0, 1, 3], #[0, 2, 3], #[1, 2, 3] #]) #colors = np.array([ #[1, 0, 0, 0.3], #[0, 1, 0, 0.3], #[0, 0, 1, 0.3], #[1, 1, 0, 0.3] #]) # clear and reset view self.view.items = [] self.add_3d_printing_region() # add new model m1 = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colors, smooth=False) m1.translate(5, 5, 0) m1.setGLOptions('additive') self.view.addItem(m1) # reset slider self.sl.setMinimum(0) self.sl.setMaximum(0) self.sl.setValue(0)
def GetApexMesh(gl, xyz, scale=10 / 1.2, color=(.31, .05, .3, 1), drawFaces=False, rows=5, cols=12): # md = gl.MeshData.sphere(rows=5, cols=5) md = gl.MeshData.sphere(rows, cols) x, y, z = xyz # apexMesh = gl.GLMeshItem(meshdata=md, smooth=False, drawFaces=drawFaces, drawEdges=True, edgeColor=color) apexMesh = gl.GLMeshItem(meshdata=md, smooth=False, drawFaces=True, drawEdges=True, color=color) color = 0, 0, 0, 1 # apexMesh.setColor(color) # apexMesh.setGLOptions('additive') apexMesh.translate(x, y, z) apexMesh.scale(scale, scale, scale) # apexMesh.paint() # print(apexMesh.opts.items()) return apexMesh
def __init__(self): QtGui.QWidget.__init__(self) self.view_widget = gl.GLViewWidget(self) # Setting the Viewpoint with Azimuth and Elevation # http://matlab.izmiran.ru/help/techdoc/visualize/chview3.html self.view_widget.setCameraPosition(distance=50, elevation=-70, azimuth=95) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.view_widget) # self.setup_grid() self.setup_xyz_axis(self.view_widget, 3, 5) self.setup_view_box(self.view_widget, 3.0, V_FoV, H_FoV, 15.0) head_mesh_data = gl.MeshData.sphere(rows=10, cols=10) head = gl.GLMeshItem(meshdata=head_mesh_data, smooth=True, shader='shaded', glOptions='opaque') head.translate(0, 0, 0) self.view_widget.addItem(head)
def draw_buildings(self, map): """ Draw the buildings that represent the world :param map: map object that is generated in the CreateWorld class :return: none """ building_meshes = [] building_colors = [] for b in map.buildings: building_meshes.append([b.b1, b.b2, b.t2]) building_meshes.append([b.b1, b.t1, b.t2]) building_meshes.append([b.b1, b.b3, b.t1]) building_meshes.append([b.b3, b.t1, b.t3]) building_meshes.append([b.b2, b.b4, b.t4]) building_meshes.append([b.b2, b.t2, b.t4]) building_meshes.append([b.b3, b.b4, b.t3]) building_meshes.append([b.b4, b.t3, b.t4]) building_meshes.append([b.t1, b.t2, b.t4]) building_meshes.append([b.t1, b.t3, b.t4]) mesh_array = np.asarray(building_meshes) color_array = np.empty((mesh_array.shape[0], 3, 4)) for i in range(mesh_array.shape[0]): color_array[i] = np.array([20/256.0, 20/256.0, 20/256.0, 1]) building_view = gl.GLMeshItem(vertexes=mesh_array, smooth=False, drawEdges=True, vertexColors=color_array) # building_view.setColor([0.9, 0.7, 0.5, 1]) self.w.addItem(building_view)
def cube(): """Easy shape , Cube Returns: gl.GLMeshItem """ vertexes = np.array(list(itertools.product(range(2), repeat=3))) faces = [] for i in range(2): temp = np.where(vertexes == i) for j in range(3): temp2 = temp[0][np.where(temp[1] == j)] for k in range(2): faces.append([temp2[0], temp2[1 + k], temp2[3]]) faces = np.array(faces) pprint = faces colors = np.array([[i * 5, i * 5, i * 5, 0] for i in range(12)]) geom = gl.GLMeshItem( vertexes=vertexes, faces=faces, faceColors=colors, drawEdges=True ) return geom
def __init__(self): self.app = QtGui.QApplication(sys.argv) self.view = gl.GLViewWidget() self.view.show() vertices = [] faces = [] for row in range(32): for col in range(32): vertices.append([col, row, 0]) for i in range(31): # row for k in range(31): # offset faces.append([i * 32 + k, i * 32 + k + 1, (i + 1) * 32 + k]) faces.append([i * 32 + k + 1, (i + 1) * 32 + k + 1, (i + 1) * 32 + k]) vertices = np.array(vertices) faces = np.array(faces) colors = [] for i in range(341): colors.append([1, 0, 0, 0.5]) colors.append([0, 1, 0, 0.5]) colors.append([0, 0, 1, 0.5]) colors.append([1, 0, 0, 0.5]) colors = np.array(colors) self.mesh = gl.GLMeshItem(vertexes=vertices, faces=faces, faceColors=colors) self.mesh.setGLOptions("additive") self.view.addItem(self.mesh) self.view.setWindowTitle('Meshy')
def makeParallelepipedCoords(self, k, l, w, h, x, y, z): window = self.ui.gl verts = np.array([ [k + l, 0, 0], # 0 [0, 0, 0], # 1 [0, k + w, 0], # 2 [0, 0, k + h], # 3 [k + l, k + w, 0], # 4 [k + l, k + w, k + h], # 5 [0, k + w, k + h], # 6 [k + l, 0, k + h] ]) # 7 faces = np.array([[1, 0, 7], [1, 3, 7], [1, 2, 4], [1, 0, 4], [1, 2, 6], [1, 3, 6], [0, 4, 5], [0, 7, 5], [2, 4, 5], [2, 6, 5], [3, 6, 5], [3, 7, 5]]) r, g, b = rainbowColors() op = .2 colors = np.array([[r, g, b, op] for _ in range(12)]) m1 = gl.GLMeshItem(vertexes=verts, faces=faces, drawFaces=True, drawEdges=True, faceColors=colors, smooth=False, edgeColor=(r, g, b, op)) m1.translate(x, y, z) m1.setGLOptions('additive') window.addItem(m1)
def showMultipleOrbits(self): self.finished = False self.orbitPlot.clear() firstPass = True for orbit, params in self.currentOrbits.items(): if firstPass: # Create the celestial body radius = np.linalg.norm([0, params.body.radius, 0]) md = gl.MeshData.sphere(rows=200, cols=300, radius=radius) m1 = gl.GLMeshItem(meshdata=md,smooth=True,color=params.body.qtColor,shader="balloon",glOptions="additive") self.orbitPlot.plot.addItem(m1) firstPass = False rs = params.getRadiusArray() # Plot the initial point initialPoint = gl.GLScatterPlotItem(pos=np.array([rs[0,0], rs[0,1], rs[0,2]]), size=np.array([13]), color=(1,0,0,1.5)) self.orbitPlot.plot.addItem(initialPoint) # Plot the trajectory orbit1 = np.array([rs[:,0], rs[:,1], rs[:,2]]).transpose() orbit = gl.GLLinePlotItem(pos=orbit1, color=params.color, antialias=True) self.orbitPlot.plot.addItem(orbit) # Adjust the plot self.orbitPlot.plot.setCameraPosition(distance=params.body.radius*10) self.orbitPlot.zgrid.scale(np.max(orbit1),np.max(orbit1),np.max(orbit1)) self.orbitPlot.scaleAxis(params.body.radius*2) self.orbitPlot.createAxis()
def GLMeshBox(length, width, height, color): verts = np.array([ [-length / 2, -width / 2, height], [-length / 2, -width / 2, 0], [-length / 2, width / 2, height], [-length / 2, width / 2, 0], [length / 2, width / 2, height], [length / 2, width / 2, 0], [length / 2, -width / 2, height], [length / 2, -width / 2, 0], ]) faces = np.array([ [1, 2, 0], [1, 2, 3], [2, 5, 3], [2, 5, 6], [4, 7, 5], [4, 7, 6], [0, 7, 6], [0, 7, 1], [0, 4, 2], [0, 4, 6], [1, 5, 3], [1, 5, 7], ]) box = gl.GLMeshItem(vertexes=verts, faces=faces, smooth=False) box.setColor(color) return box
def update_quad(self, state): quadrotor_position = np.array([[state.pn], [state.pe], [state.pd]]) # NED coordinates # attitude of quadrotor as a rotation matrix R from body to inertial R = self._Euler2Rotation(state.phi, state.theta, state.psi) # rotate and translate points defining quadrotor rotated_points = self._rotate_points(self.points, R) translated_points = self._translate_points(rotated_points, quadrotor_position) # convert North-East Down to East-North-Up for rendering R = np.array([[0, 1, 0], [1, 0, 0], [0, 0, -1]]) translated_points = R @ translated_points # convert points to triangular mesh defined as array of three 3D points (Nx3x3) mesh = self._quadrotor_points_to_mesh(translated_points) # initialize the drawing the first time update() is called if not self.plot_initialized: # initialize drawing of triangular mesh. self.body = gl.GLMeshItem(vertexes=mesh, # defines the triangular mesh (Nx3x3) vertexColors=self.meshColors, # defines mesh colors (Nx1) drawEdges=True, # draw edges between mesh elements smooth=False, # speeds up rendering computeNormals=False) # speeds up rendering self.window.addItem(self.body) # add body to plot self.plot_initialized = True # else update drawing on all other calls to update() else: # reset mesh using rotated and translated points self.body.setMeshData(vertexes=mesh, vertexColors=self.meshColors) # update the center of the camera view to the quadrotor location view_location = Vector(state.pe, state.pn, -state.pd) # defined in ENU coordinates self.window.opts['center'] = view_location # redraw self.app.processEvents()
def update(self, state): #This will update the animation mav_position = np.array([[state.pn], [state.pe], [-state.h]]) R = self.EulerToRotation(state.phi, state.theta, state.psi) rotated_pts = self.rotatePoints(self.points, R) trans_pts = self.translatePoints(rotated_pts, mav_position) R2 = np.array([[0, 1, 0], [1, 0, 0], [0, 0, -1]]) # Convert to ENU coordinates for rendering trans_pts = R2 @ trans_pts mesh = self.pointsToMesh(trans_pts) if not self.plot_initialize: self.body = gl.GLMeshItem( vertexes=mesh, #defines mesh (Nx3x3) vertexColors=self.mesh_colors, drawEdges=True, smooth=False, #speeds up rendering computeNormals=False) # speeds up rendering self.window.addItem(self.body) self.plot_initialize = True else: self.body.setMeshData(vertexes=mesh, vertexColors=self.mesh_colors) view_location = Vector(state.pe, state.pn, state.h) # in ENU frame self.window.opts['center'] = view_location self.application.processEvents() #redraw
def __init__(self): super(PositionGraph, self).__init__() self.setWindowTitle('Anser Position') self.setBackgroundColor('w') anser_mesh = mesh.Mesh.from_file( utils.resource_path('./app/resources/cad/mesh.stl')) anser_mesh = gl.MeshData(vertexes=anser_mesh.vectors) m = gl.GLMeshItem(meshdata=anser_mesh, shader='shaded', color=(0, 1, 0, 0.1)) m.rotate(135, 0, 0, 1) m.translate(240, 0, -240) m.scale(1, 1, 1) self.addItem(m) gx = gl.GLGridItem() gx.setSize(7, 7, 7) gx.scale(45, 45, 45) gx.rotate(45, 0, 0, 1) #self.addItem(gx) self.pos = np.empty((MAX_NUM_OF_SENSORS, 3)) self.color = np.empty((MAX_NUM_OF_SENSORS, 4)) size = np.empty(MAX_NUM_OF_SENSORS) for i in range(MAX_NUM_OF_SENSORS): self.pos[i] = (0, 0, 0) self.color[i] = (0, 0.0, 0.0, 0.0) size[i] = 6 self.sp1 = gl.GLScatterPlotItem(pos=self.pos, size=size, color=self.color[0], pxMode=True) self.sp1.setGLOptions('translucent') self.addItem(self.sp1) self.setCameraPosition(100, 800, 30) self.sp1.rotate(135, 0, 0, 1)
def mkOctHdr(org=[0,0,0],bxSdLen=1,scl=1,transp=0.5): clr=[0, 1, 1, transp] edge=True smooth=True shader='shaded' glOpt='translucent' trOcth=np.array([list(itTl.permutations([0.25,0.5,0.75,1],4))])[0] norm4du=np.array([np.sqrt(2)/2, -np.sqrt(2)/2, 0, 0]) norm4dv=np.array([np.sqrt(6)/6, np.sqrt(6)/6, -np.sqrt(2/3), 0]) norm4dw=np.array([np.sqrt(12)/12, np.sqrt(12)/12, np.sqrt(12)/12, -np.sqrt(3)/2]) ocThVert=np.array([scl*(np.sum(np.multiply(trOcth,np.tile(norm4du, (trOcth.shape[0],1))),axis=1)+0.5+org[0]), scl*(np.sum(np.multiply(trOcth,np.tile(norm4dv, (trOcth.shape[0],1))),axis=1)+0.5+org[1]), scl*(np.sum(np.multiply(trOcth,np.tile(norm4dw, (trOcth.shape[0],1))),axis=1)+0.5+org[2])]).T ocThHull=spatial.Delaunay(ocThVert) ocThObj=gl.MeshData(vertexes=ocThVert,faces=ocThHull.convex_hull) ocGrObj=gl.GLMeshItem(meshdata=ocThObj, drawEdges=edge, smooth=smooth, color=(clr[0], clr[1], clr[2], clr[3]), shader=shader, glOptions=glOpt) ocGrObj.translate(-((bxSdLen/2)+org[0]), -((bxSdLen/2)+org[1]), -((bxSdLen/2)+org[2])) ocGrObj.rotate(55,1,0,0) ocGrObj.rotate(45,0,0,1) ocGrObj.translate(((bxSdLen/2)+org[0]), ((bxSdLen/2)+org[1]), ((bxSdLen/2)+org[2])) return ocGrObj
def __init__(self): self.t = QtGui.QApplication(sys.argv) self.w = gl.GLViewWidget() self.w.setGeometry(0, 0, 1280, 800) self.w.opts['viewport'] = (0, 0, 2560, 1600) self.w.setCameraPosition(pos=(0, 0, 0), distance=10, elevation=30) self.w.show() # verts = np.array([[x, y] for x in range(20) for y in range(20)]) # faces = [] # for i in range(20): # faces.append([1,1]) # faces = np.array(faces) verts = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) faces = np.array([[0, 1, 2], [1, 2, 3], [0, 2, 4], [2, 4, 6], [4, 5, 6], [5, 6, 7], [1, 5, 3], [3, 5, 7], [2, 6, 3], [6, 3, 7], [0, 4, 1], [1, 4, 5]]) colors = np.array([[1, 0, 0, 0.3], [0, 1, 0, 0.3], [0, 0, 1, 0.3], [1, 1, 0, 0.3], [1, 0, 0, 0.3], [0, 1, 0, 0.3], [0, 0, 1, 0.3], [1, 1, 0, 0.3], [1, 0, 1, 0.3], [0, 1, 1, 0.3], [1, 0, 1, 0.3], [0, 1, 1, 0.3]]) self.mesh = gl.GLMeshItem(vertexes=verts, drawEdges=True, faces=faces, faceColors=colors) self.mesh.translate(0, -1, 0) self.w.addItem(self.mesh)