def initializeGL(self): GL.glClearColor(0.50, 0.50, 0.50, 1.0) self.heightMap = HeightMap('textures/atacama_height2.png') self.projection = QMatrix4x4() self.projection.perspective(self.fov, self.width / self.height, 0.01, 10000) self.cameraPos = QVector3D(0.0, 1.0, 1.0) self.terrainPos = QVector3D(0.0, 0.0, 0.0) self.roverPos = QVector3D(0.0, 0.0, 0.0) print(GL.glGetString(GL.GL_VERSION)) self.camera = Camera(self.cameraPos, self.heightMap) self.terrain = Terrain(self.terrainPos, self.heightMap) self.mask = np.zeros([1001, 1001]) self.terrain.updateRewards(self.mask)
def setup(self): # Set up vertices and indices self.terrainVertices = np.array(self.getVertices(self.vertexCount), dtype='float32') self.terrainIndices = np.array(self.getIndices(self.vertexCount), dtype='uint32') # Setup shaders self.shader = Shader(vertex_source="shaders/terrain.vs", fragment_source="shaders/terrain.fs") self.shader.use() # Set model matrix of terrain # self.model = Matrix44.from_translation(np.array(self.position)) self.model = QMatrix4x4() self.model.scale(500.5, 1.0, 500.5) #self.model.translate(self.position) self.shader.setMat4("model", self.model) # Create Vertex Array Object self.__vao = glGenVertexArrays(1) glBindVertexArray(self.__vao) # Create Buffers and assign data bufs = glGenBuffers(2) glBindBuffer(GL_ARRAY_BUFFER, bufs[0]) glBufferData(GL_ARRAY_BUFFER, sizeof(ctypes.c_float) * len(self.terrainVertices), (ctypes.c_float * len(self.terrainVertices))(*self.terrainVertices), GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufs[1]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(ctypes.c_uint) * len(self.terrainIndices), (ctypes.c_uint * len(self.terrainIndices))(*self.terrainIndices), GL_STATIC_DRAW) # Turn on position attribute and set its size glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(ctypes.c_float), None) # Unbind buffers and VAO glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0); # Setup textures self.colors = ReadTexture("textures/atacama_rgb3.jpg") self.rewardMap = createEmptyTexture() self.heightMap = bindHeightMap(self.heightMap.getHeightMap()) self.shader.stop()
def matrix(self, new_matrix): self._matrix = new_matrix m11 = new_matrix[0][0] # x scale m21 = new_matrix[0][1] # x shear m31 = new_matrix[0][2] # x translate m12 = new_matrix[1][0] # y shear m22 = new_matrix[1][1] # y scale m32 = new_matrix[1][2] # y translate self.transform = QTransform(m11, m12, m21, m22, m31, m32) log.debug( "m11={}, m12={}, m21={}, m22={}, m31={}, m32={}, matrix={}".format( m11, m12, m21, m22, m31, m32, QMatrix4x4(self.transform))) self.matrixChanged.emit()
def paintGL(self): self.qglClearColor(self.clearColor) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) m = QMatrix4x4() m.ortho(-0.5, 0.5, 0.5, -0.5, 4.0, 15.0) m.translate(0.0, 0.0, -10.0) m.rotate(self.xRot / 16.0, 1.0, 0.0, 0.0) m.rotate(self.yRot / 16.0, 0.0, 1.0, 0.0) m.rotate(self.zRot / 16.0, 0.0, 0.0, 1.0) self.program.setUniformValue('matrix', m) for i in range(6): glBindTexture(GL_TEXTURE_2D, self.textures[i]) glDrawArrays(GL_TRIANGLE_FAN, i * 4, 4)
def __init__(self): app = QGuiApplication(sys.argv) qmlAppEngine = QQmlApplicationEngine(QUrl.fromLocalFile("main.qml")) window = qmlAppEngine.rootObjects()[ 0] # this should contain only QQuickWindow that is root item. # ^ for creating multiple window in possible future # try see: http://stackoverflow.com/questions/31298810/multiple-windows-in-a-single-project appViewOGLFormat = window.format() #type: QSurfaceFormat appViewOGLFormat.setProfile(QSurfaceFormat.CoreProfile) appViewOGLFormat.setVersion(3, 3) window.setFormat(appViewOGLFormat) theAdapterInstance = window.findChild( quickfbo.QquickItemFromGlFboViewportAdapter, "glFboViewportAdapter" ) #type: qquickitem_glfbo.QquickItemFromGlFboViewportAdapter theAdapterInstance.SetViewport(self) # Transparent Window: For demo purpose of "per-pixel morphing Window Possibility" # see: http://stackoverflow.com/questions/7613125/how-to-make-a-transparent-window-with-qt-quick # window.setFlags( Qt.FramelessWindowHint ) # see: http://stackoverflow.com/questions/18533641/qquickwindow-transparent # window.setColor( Qt.transparent ) self.app = app self.qmlAppEngine = qmlAppEngine self.window = window self.frameRenderer = None self.loopTimer = None self.frameCounter = 0 self.hgpu = None self.sceneBoxSize = QVector3D(0.5, 0.5, 0.15) self.cellScale = 0.018 self.sceneBoxCam = DirectManeuverTurntableSceneBoxOrthoCam( self.sceneBoxSize) self.haltFlush = False # a flag to primitively interact with fluid. # startup with top-view # from math import radians # self.sceneBoxCam._cam.altitude=radians(90) self.qQuickWorkaround = QMatrix4x4() self.qQuickWorkaround.scale(QVector3D(1, -1, 1)) #- ^ this workaround QQuickFramebufferObject-QtQuick y-flip rendering bug self.last30DeltaTs = []
def __init__(self, obj_path, parent=None): super().__init__(parent) surface_format = QSurfaceFormat() surface_format.setSamples(16) QOpenGLWidget.setFormat(self, surface_format) self.projection = QMatrix4x4() self.vertex_buf_offsets = [3, 3, 2] # position, normal, tex_coord self.vertex_buf_stride = sum(self.vertex_buf_offsets) self.obj_path = obj_path self.initialized = False if not has_libGL: get_main_window().show_status( 'OpenGL library not found. Disabling 3D view.')
def moveCamera(self, az=0, pol=0, x=0, y=0, z=0): move_coef = 0.1 rot_coef = 2 rot_vec = self.getRotVec() if az != 0 or pol != 0: rot_matr = QMatrix4x4() rot_matr.rotate(rot_coef * az, rot_vec) rot_matr.rotate(rot_coef * pol, 0, 1, 0) self.camera_rot = rot_matr * self.camera_rot if z: self.camera_pos += move_coef * self.camera_rot * z if x: self.camera_pos += rot_vec * move_coef * x if y: self.camera_pos.setY(self.camera_pos.y() + y * move_coef)
def follow(self, pose): """ Follow object at pose ---------------------- In: pose -> QMatrix4x4 ---------------------- """ target = pose.inverted()[0] if not self.isFollow: self._modelView = self.deltaT * target self.isFollow = True else: deltaT = self.lastTarget * target self._modelView = self._modelView * deltaT self.lastTarget = QMatrix4x4(pose)
def main(): n = 50 init_boxes(n) random.seed() init_graph(800, 600) set_color("gray") translate(400, 300) set_render_mode(RenderMode.RENDER_MANUAL) degree = 0 fps = 30 m_o = isometric_projection() points = [] while is_run(): if random.choice((-1, 1)) == 1: clock_wise = True else: clock_wise = False for degree in range(0, 180 + (n) * 5, 5): if not is_run(): break clear() for i in range(n): box = boxes[i] dd = max(degree - i * 5, 0) dd = min(dd, 180) if not clock_wise: dd = -dd rad = math.radians(dd) cos_2 = math.cos(rad) sin_2 = math.sin(rad) m = QMatrix4x4(cos_2, sin_2, 0, 0, -sin_2, cos_2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) points.clear() for p in box.points: x, y, z = p v = QVector3D(x, y, z) v2 = m.map(v) v3 = m_o.map(v2) points.append((v3.x(), v3.y())) draw_box(points) delay_fps(fps) delay(1000) close_graph()
def add_triangle_prism(start, start_to_end, perpendicular, width, color, vertex_buf, vertex_buf_stride, index_buf): perpendicular = perpendicular.normalized() * width rotation = QMatrix4x4() rotation.rotate(120, start_to_end) index_offset = (len(vertex_buf) // vertex_buf_stride) vert_pos = start + perpendicular vertex_buf.extend( [vert_pos.x(), vert_pos.y(), vert_pos.z(), *color, 0.0, 0.0]) vert_pos = vert_pos + start_to_end vertex_buf.extend( [vert_pos.x(), vert_pos.y(), vert_pos.z(), *color, 0.0, 0.0]) vert_pos = start + rotation * perpendicular vertex_buf.extend( [vert_pos.x(), vert_pos.y(), vert_pos.z(), *color, 0.0, 0.0]) vert_pos = vert_pos + start_to_end vertex_buf.extend( [vert_pos.x(), vert_pos.y(), vert_pos.z(), *color, 0.0, 0.0]) vert_pos = start + rotation * rotation * perpendicular vertex_buf.extend( [vert_pos.x(), vert_pos.y(), vert_pos.z(), *color, 0.0, 0.0]) vert_pos = vert_pos + start_to_end vertex_buf.extend( [vert_pos.x(), vert_pos.y(), vert_pos.z(), *color, 0.0, 0.0]) tris = [(5, 3, 2), (5, 2, 4), (1, 5, 4), (1, 4, 0), (3, 1, 0), (3, 0, 2), (1, 3, 5), (0, 4, 2)] for tri in tris: index_buf.extend([index_offset + i for i in tri])
def paintGL(self): self.gl.glClearColor(self.clearColor.redF(), self.clearColor.greenF(), self.clearColor.blueF(), self.clearColor.alphaF()) self.gl.glClear( self.gl.GL_COLOR_BUFFER_BIT | self.gl.GL_DEPTH_BUFFER_BIT) m = QMatrix4x4() m.ortho(-0.5, 0.5, 0.5, -0.5, 4.0, 15.0) m.translate(0.0, 0.0, -10.0) m.rotate(self.xRot / 16.0, 1.0, 0.0, 0.0) m.rotate(self.yRot / 16.0, 0.0, 1.0, 0.0) m.rotate(self.zRot / 16.0, 0.0, 0.0, 1.0) self.program.setUniformValue('matrix', m) for i, texture in enumerate(self.textures): texture.bind() self.gl.glDrawArrays(self.gl.GL_TRIANGLE_FAN, i * 4, 4)
def RenderToDrawBuffer_VelocityLine(self, vpMat: QMatrix4x4, tex3DName_velocity: GLuint, cellScale: float, lineScale: float): with uglw.VAOBound(self._vao_blank): with uglw.TextureBound(GL_TEXTURE_3D, tex3DName_velocity): with uglw.ProgBound( self._velocityLineProgramInfo.__progHandle__): cellNx2 = self._fieldSize[0] * self._fieldSize[ 1] * self._fieldSize[2] * 2 glUniform1fv(self._velocityLineProgramInfo.lineScale, 1, lineScale) glUniform1fv(self._velocityLineProgramInfo.cellScale, 1, cellScale) glUniformMatrix4fv(self._velocityLineProgramInfo.vpMat, 1, GL_FALSE, vpMat.data()) glDrawArrays(GL_LINES, 0, cellNx2) glDrawArrays(GL_POINTS, 0, cellNx2)
def drawBackground(self, qp, rect): # The rectangle is in "Scene coordinates". mapFromScene converts to viewport coordinates # Not sure how scene coordinates and self.sceneRect() relate. # The QGraphicsView source code shows the how the rectangle is computed and passed in. viewRect = QRectF(self.mapFromScene(rect).boundingRect()) # Need to scale the rectangle from viewport coordinates to pixmap coordinates # This is matrix algebra. scaleMatrix = QMatrix4x4() scaleMatrix.scale(float(self.pixmap.width())/self.viewport().width(), float(self.pixmap.height())/self.viewport().height()) pixmapRect = scaleMatrix.mapRect(viewRect) # Now we have the target drawing buffer (rect in scene coordinates) # as well as the source drawing buffer (rect in pixmap coordinates). # We are sampling correctly from both. qp.drawPixmap(rect, self.pixmap, pixmapRect)
class UniformBSpline(Spline): """ Implementation of a Uniform B-Spline. """ # M-matrix determines interpolation weights M = QMatrix4x4(-1, 3, -3, 1, 3, -6, 3, 0, -3, 0, 3, 0, 1, 4, 1, 0) / 6 # control points indicies start at 0 i_start = 0 # and go until the fourth-to-last i_end = -3 def _get_ctrl_pts(self, i): """ Overrides Spline._get_ctrl_pts """ # control points for this are just the four points starting at each index return self.ctrl_pts[i:i + 4]
def __init__(self, homography_transform, intensity_mask, parent=None): super().__init__(parent) self._crosshair = False self._crosshair_thickness = 1 self._apply_intensity_mask = False self._invert = False self.setViewport(QOpenGLWidget()) self.gaussian_shader_program = QOpenGLShaderProgram() self.homography_transform = homography_transform self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.horizontalScrollBar().disconnect() self.verticalScrollBar().disconnect() self.intensity_mask = intensity_mask self.intensity_mask_renderer = GaussianIntensityMaskRenderer( parent=self) # background_brush = QBrush() # background_brush.setStyle(Qt.SolidPattern) # background_brush.setColor(Qt.black) # self.setBackgroundBrush(background_brush) self.horizontal_line = QGraphicsLineItem() self.vertical_line = QGraphicsLineItem() self.setTransformationAnchor(QGraphicsView.NoAnchor) self.horizontal_line.setLine(0, 1080 / 2, 1920, 1080 / 2) self.vertical_line.setLine(1920 / 2, 0, 1920 / 2, 1080) self.pen = QPen(Qt.white) self.horizontal_line.setPen(self.pen) self.vertical_line.setPen(self.pen) self.view_matrix = QMatrix4x4() self.dx = 0 self.dy = 0 self.angle = 0 self.scale_value = 1 self.setSceneRect(0, 0, 9000, 9000)
def paintGL(self): if self.wireframe: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) else: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glUseProgram(self.shader) camera_pos = QVector3D( self.camera_pos_sph.x() * math.sin(self.camera_pos_sph.y()) * math.cos(self.camera_pos_sph.z()), self.camera_pos_sph.x() * math.sin(self.camera_pos_sph.y()) * math.sin(self.camera_pos_sph.z()), self.camera_pos_sph.x() * math.cos(self.camera_pos_sph.y())) MVP = QMatrix4x4() MVP.perspective(45, self.w / self.h, 1e-3, 1e4) MVP.lookAt(camera_pos, QVector3D(0, 0, 0), QVector3D(0, 0, 1)) MVP.scale(QVector3D(1, 1, 1) / self.max_dim) gl.glUniformMatrix4fv(self.unif_MVP, 1, gl.GL_FALSE, MVP.data()) gl.glUniform3f(self.unif_lightDir, *self.lightDir) gl.glEnableVertexAttribArray(self.attr_vPosition) gl.glEnableVertexAttribArray(self.attr_vNormal) gl.glEnableVertexAttribArray(self.attr_vColor) gl.glVertexAttribPointer(self.attr_vPosition, 3, gl.GL_FLOAT, False, 0, self.vertexArray) gl.glVertexAttribPointer(self.attr_vNormal, 3, gl.GL_FLOAT, False, 0, self.normalArray) gl.glVertexAttribPointer(self.attr_vColor, 3, gl.GL_FLOAT, False, 0, self.colorArray) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3 * self.num_triangles) gl.glDisableVertexAttribArray(self.attr_vPosition) gl.glDisableVertexAttribArray(self.attr_vNormal) gl.glDisableVertexAttribArray(self.attr_vColor)
def __init__(self, parent): super().__init__(parent) self.loc = 1.0 corner = 10.0 horizontal_vertices = np.array([ -corner, self.loc, 0.1, corner, self.loc, 0.1, corner, -self.loc, 0.1, corner, -self.loc, 0.1, -corner, -self.loc, 0.1, -corner, self.loc, 0.1 ], dtype=np.float32) vertical_vertices = np.array([ -self.loc, corner, 0.1, self.loc, corner, 0.1, self.loc, -corner, 0.1, self.loc, -corner, 0.1, -self.loc, -corner, 0.1, -self.loc, corner, 0.1 ], dtype=np.float32) self.vertical_line = CrosshairLine(parent=self, vertex_data=vertical_vertices) self.horizontal_line = CrosshairLine(parent=self, vertex_data=horizontal_vertices) self.view_matrix = QMatrix4x4()
def ortho_look_at(eye_x: float, eye_y: float, eye_z: float, center_x: float, center_y: float, center_z: float, up_x: float, up_y: float, up_z: float) -> QMatrix4x4: """ Return the ortho projection matrix :param eye_x: :param eye_y: :param eye_z: :param center_x: :param center_y: :param center_z: :param up_x: :param up_y: :param up_z: :return: the matrix """ matrix = QMatrix4x4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1) matrix.lookAt(QVector3D(eye_x, eye_y, eye_z), QVector3D(center_x, center_y, center_z), QVector3D(up_x, up_y, up_z)) return matrix
def render(self, gl): gl.glViewport(0, 0, self.width(), self.height()) gl.glClear(gl.GL_COLOR_BUFFER_BIT) self.m_program.bind() matrix = QMatrix4x4() matrix.perspective(60, 4.0/3.0, 0.1, 100.0) matrix.translate(0, 0, -2) matrix.rotate(100.0 * self.m_frame / self.screen().refreshRate(), 0, 1, 0) self.m_program.setUniformValue(self.m_matrixUniform, matrix) vertices = array.array('f', [ 0.0, 0.707, -0.5, -0.5, 0.5, -0.5]) gl.glVertexAttribPointer(self.m_posAttr, 2, gl.GL_FLOAT, False, 0, vertices) gl.glEnableVertexAttribArray(self.m_posAttr) colors = array.array('f', [ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]) gl.glVertexAttribPointer(self.m_colAttr, 3, gl.GL_FLOAT, False, 0, colors) gl.glEnableVertexAttribArray(self.m_colAttr) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) self.m_program.release() self.m_frame += 1
def GetSceneBoxCursorIntersection(self, vpMat: QMatrix4x4, boxSize: QVector3D, winspaceCursorPos: QPoint, winspaceDimension: QPoint) -> QVector3D: """ :param winspaceCursorPos: lower-left corner as origin :return: 3D world position of cursor interaction """ # render depthImage and get depthValue ------------------------------------------------------------------------- self._depthInteractionBuffer.RequestBindFBO(winspaceDimension) glViewport(0, 0, winspaceDimension.x(), winspaceDimension.y()) with uglw.VAOBound(self._vao_blank): with uglw.ProgBound(self._sceneBoxSurfProgramInfo.__progHandle__): with uglw.EnableScope(GL_DEPTH_TEST): glClearBufferfv(GL_DEPTH, 0, (1., )) glUniform3fv(self._sceneBoxSurfProgramInfo.boxSize, 1, utyp.GetTuple(boxSize)) glUniformMatrix4fv(self._sceneBoxSurfProgramInfo.vpMat, 1, GL_FALSE, vpMat.data()) glDrawArrays(GL_TRIANGLES, 0, 3 * 2 * 6) winspaceCursorDepthValue = glReadPixels(winspaceCursorPos.x(), winspaceCursorPos.y(), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT)[0][0] # print( winspaceCursorDepthValue ) glBindFramebuffer(GL_FRAMEBUFFER, 0) # unproject cursor into worldCoord ----------------------------------------------------------------------------- if winspaceCursorDepthValue == 1.0: raise ValueError # cursor ray hit background, no object to manipulate return self.GetUnprojection(winspaceCursorPos, winspaceCursorDepthValue, winspaceDimension, vpMat)
def __init__(self, parent=None, shape=(512, 512)): super(CGH, self).__init__(parent) self.traps = [] # SLM geometry self._shape = shape # self.phi = np.zeros(self.shape).astype(np.uint8) # Instrument properties # vacuum wavelength of trapping laser [um] self._wavelength = 1.064 # refractive index of medium self._refractiveIndex = 1.340 # magnification of objective lens self._magnification = 100. # focal length of objective lens [um] self._focalLength = 200. # camera pitch [um/pixel] self._cameraPitch = 4.8 # SLM pitch [um/pixel] self._slmPitch = 8. # SLM scale factor self._scaleFactor = 3. # Coordinate transformation matrix for trap locations self.m = QMatrix4x4() # Location of optical axis in camera coordinates self._rc = QVector3D(320., 240., 0.) # Orientation of camera relative to SLM [degrees] self._thetac = 0. # Location of optical axis in SLM coordinates self._rs = QPointF(self.width / 2., self.height / 2.) # Tilt of SLM relative to optical axis [degrees] self._phis = 8. # Splay wavenumber self._splayFactor = 0.01
class CatmullRomSpline(Spline): """ Implementation of a Catmull-Rom Spline. """ # M-matrix determines interpolation weights M = QMatrix4x4(-1, 3, -3, 1, 2, -5, 4, -1, -1, 0, 1, 0, 0, 2, 0, 0) / 2 # control points indicies start at 0 i_start = 0 # and go until the second-to-last i_end = -1 def _get_ctrl_pts(self, i): """ Overrides Spline._get_ctrl_pts """ # middle two control points are always the same p2 = self.ctrl_pts[i] p3 = self.ctrl_pts[i + 1] if i == 0: # if at the first set of control points, # need to calculate starting auto tangents p4 = self.ctrl_pts[i + 2] tangent = (2 * p3 - p4 - p2) / 2 p1 = p2 - tangent elif i == len(self.ctrl_pts) - 2: # if at the last set of control points, # need to calculate ending auto tangents p1 = self.ctrl_pts[i - 1] tangent = (2 * p2 - p1 - p3) / 2 p4 = p3 + tangent else: # otherwise, just use the normal control points p1 = self.ctrl_pts[i - 1] p4 = self.ctrl_pts[i + 2] return p1, p2, p3, p4
def create_matrix(model, links, frames, bf): # ローカル位置 trans_vs = [QVector3D() for i in range(len(links))] # 加算用クォータニオン add_qs = [QQuaternion() for i in range(len(links))] for lidx, lbone in enumerate(reversed(links)): # 位置 if lidx == 0: # 一番親は、グローバル座標を考慮 trans_vs[lidx] = lbone.position + calc_bone_by_complement( frames, lbone.name, bf.frame).position else: # 位置:自身から親の位置を引いた値 trans_vs[lidx] = lbone.position + calc_bone_by_complement( frames, lbone.name, bf.frame).position - links[len(links) - lidx].position # 回転 rot = calc_bone_by_complement(frames, lbone.name, bf.frame).rotation if lbone.fixed_axis != QVector3D(): # 軸固定の場合、回転を制限する rot = QQuaternion.fromAxisAndAngle(lbone.fixed_axis, rot.lengthSquared()) add_qs[lidx] = rot # if "ひじ" in lbone.name: # # 右手系→左手系への変換 # # trans_vs[lidx].setX(trans_vs[lidx].x() * -1) # add_qs[lidx].setX(add_qs[lidx].x() * -1) # add_qs[lidx].setY(add_qs[lidx].y() * -1) # # add_qs[lidx].setScalar(add_qs[lidx].scalar() * -1) # # logger.info("%s: fix: %s, vs: %s, qs: %s", lbone.name, lbone.fixed_axis, trans_vs[lidx], add_qs[lidx].toEulerAngles()) # logger.info("trans_vs[%s]: %s", lidx, trans_vs[lidx]) # logger.info("add_qs[%s]: %s", lidx, add_qs[lidx]) # 行列 matrixs = [QMatrix4x4() for i in range(len(links))] for n in range(len(matrixs)): # 行列を生成 matrixs[n] = QMatrix4x4() # 移動 matrixs[n].translate(trans_vs[n]) # 回転 matrixs[n].rotate(add_qs[n]) # logger.info("matrixs n: %s, %s", n, matrixs[n]) # 各関節の位置 global_4ds = [QVector4D() for i in range(len(links))] for n in range(len(global_4ds)): for m in range(n): if m == 0: # 0番目の位置を初期値とする global_4ds[n] = copy.deepcopy(matrixs[0]) else: # 自分より前の行列結果を掛け算する global_4ds[n] *= copy.deepcopy(matrixs[m]) # 自分は、位置だけ掛ける global_4ds[n] *= QVector4D(trans_vs[n], 1) # if bf.frame == 0: # logger.info("global_4ds %s, %s, %s", n, links[len(links) - n - 1].name, global_4ds[n].toVector3D()) return trans_vs, add_qs, matrixs, global_4ds
def calc_upper_vertex(upper_vertices, model, head_links, frames, bf): # キー:頂点Y位置小数点第一位まるめ upper_vertex_pos = {} # グローバル行列算出 _, _, matrixs, _ = create_matrix(model, head_links, frames, bf) # 該当ボーンのグローバル行列まで求める upper_matrixes = [QMatrix4x4() for i in range(len(head_links))] for n in range(len(matrixs)): for m in range(n + 1): if n == 0: # 最初は行列そのもの upper_matrixes[n] = copy.deepcopy(matrixs[0]) else: # 2番目以降は行列をかける upper_matrixes[n] *= copy.deepcopy(matrixs[m]) # logger.debug("**u_matrixes[%s]: %s %s -> %s", n, m, matrixs[m], upper_matrixes[n]) # logger.debug("upper_matrixes[%s]: %s", n, upper_matrixes[n]) # 該当リンクボーンのリンクINDEX取得 head_links_indexes = {} for lidx, l in enumerate(reversed(head_links)): head_links_indexes[l.index] = lidx # 上半身の頂点位置 for uv in upper_vertices: # 頂点が乗っているウェイトボーン情報取得 deform_bone = model.bones[model.bone_indexes[uv.deform.index0]] # 頂点初期位置 uv_diff = uv.position - deform_bone.position # 上半身の頂点の位置を算出する upper_pos = upper_matrixes[head_links_indexes[ deform_bone.index]] * QVector4D(uv_diff, 1) # logger.debug("upper_matrixes0 : %s, upper_pos: %s", upper_matrixes[0], upper_pos) # logger.debug("upper_matrixes1 : %s, upper_pos: %s", upper_matrixes[1], upper_pos) # 3Dに変換 uv_pos = upper_pos.toVector3D() uv_round = round(uv_pos.y(), 1) # logger.debug("uv_pos.y: %s -> %s: 0:%s, -1:%s, 1:%s", uv_pos.y(), uv_round, round(uv_pos.y(), 0), round(uv_pos.y(), -1), round(uv_pos.y(), 1)) if uv_round not in upper_vertex_pos.keys(): upper_vertex_pos[uv_round] = {} # 最小値 upper_vertex_pos[uv_round]["min"] = QVector3D(99999, 99999, 99999) # 最大値 upper_vertex_pos[uv_round]["max"] = QVector3D( -99999, -99999, -99999) # 実値 upper_vertex_pos[uv_round]["values"] = [] # if round(uv.position.y(),2) == 8.01: # logger.info("v: %s %s, uv_pos: %s", uv.index, uv.position, uv_pos) if upper_vertex_pos[uv_round]["min"].z() > uv_pos.z(): # 最小値より小さい場合、上書き upper_vertex_pos[uv_round]["min"] = uv_pos if upper_vertex_pos[uv_round]["max"].z() < uv_pos.z(): # 最大値より小さい場合、上書き upper_vertex_pos[uv_round]["max"] = uv_pos # 実値追加 upper_vertex_pos[uv_round]["values"].append(uv_pos) # if bf.frame == 0: # for uvkey in upper_vertex_pos.keys(): # logger.info("upper_vertex_pos key: %s, min: %s, max: %s, len: %s", uvkey, upper_vertex_pos[uv_round]["min"], upper_vertex_pos[uv_round]["max"], len(upper_vertex_pos[uvkey]["values"])) return upper_vertex_pos
def _matrixToQMatrix4x4(self, m): return QMatrix4x4(m.at(0, 0), m.at(0, 1), m.at(0, 2), m.at(0, 3), m.at(1, 0), m.at(1, 1), m.at(1, 2), m.at(1, 3), m.at(2, 0), m.at(2, 1), m.at(2, 2), m.at(2, 3), m.at(3, 0), m.at(3, 1), m.at(3, 2), m.at(3, 3))
def translate(self, x, y, z): T = QMatrix4x4() T.translate(QVector3D(x, y, z)) self.position = T * self.position del T
def view_matrix(self): mat_v = QMatrix4x4() mat_v.lookAt(self._eye, self._center, self._up) return mat_v
def __init__(self, scene, **kwargs): """Initialize actor.""" super(Actor, self).__init__() self._state = 0 #1=scale, 2=rotation, 3=scale self._lines = None self._axis = 0 # 1=x, 2=y, 3=z self._scene = scene self._transform = kwargs.get("transform", QMatrix4x4()) self._render_mode = kwargs.get("mode", Actor.RenderMode.Triangles) self._render_type = kwargs.get("type", Actor.RenderType.Solid) self._material = kwargs.get("material", Material()) self._wireframe = kwargs.get( "wireframe", Material(diffuse=QVector3D(0.25, 0.25, 0.25))) self._viewport = kwargs.get("viewport", (0.0, 0.0, 1.0, 1.0)) self._name = kwargs.get("name", "Actor" + str(id(self))) self._shader_collection = Shaders() #self._texture_collection = Textures() self._solid_shader = self._shader_collection.uniformMaterialPhongShader( ) self._solid_flat_shader = self._shader_collection.uniformMaterialPhongFlatShader( ) self._nolight_solid_shader = self._shader_collection.uniformMaterialShader( ) self._wireframe_shader = self._shader_collection.uniformMaterialShader( ) self._nolight_wireframe_shader = self._shader_collection.uniformMaterialShader( ) self._normal_visualizing_shader = self._shader_collection.normalVisShader( ) self._active_shader = self._solid_shader self._active_material = self._material self._vao = QOpenGLVertexArrayObject() self._vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) self._ibo = QOpenGLBuffer(QOpenGLBuffer.IndexBuffer) self._num_vertices = 0 self._num_indices = 0 self._hasNormals = False self._hasColors = False self._hasTextureCoords = False self._hasIndices = False self._hasFaces = False self._texture = None #self._bbox = None self._visible = True self._enabled = False self._pickable = True self._selectable = False self._selected = False self._highlighted = False self._errorMaterial = Material.ruby() self._errorHighlight = False self._warningMaterial = Material.gold() self._warningHighlight = False self._pickFactor = 1.0
def setPosition(self, pos): #print("pos==",pos) self._transform = QMatrix4x4() self._transform.translate(pos.x(), pos.y(), pos.z())
def GetProjectionMatrixOfTurntable(self, radius: float, height: float) -> QMatrix4x4: fb = self.GetOriginFrameBoundary(radius, height) ret = QMatrix4x4() ret.ortho(fb.left, fb.right, fb.bottom, fb.top, fb.near, fb.far) return ret