Exemple #1
0
    def __init__(self, scene, **kwargs):
        """Initialize actor."""
        super(Actor, self).__init__()

        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._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
Exemple #2
0
 def mousePressEvent(self, event):
     for vertex in self.parent().graph.vertices:
         if vertex.circle.contains(event.pos() +
                                   self.pos()) and vertex.label != None:
             self.parent().labelLine.setText(vertex.label)
             break
     widget = self.parent()
     if widget.timerID != 0:
         widget.killTimer(widget.timerID)
         widget.timerID = 0
     self.verticesPosWhenClicked = []
     self.mousePosWhenClicked = event.pos()
     for vertex in self.parent().graph.vertices:
         self.verticesPosWhenClicked.append(QVector3D(vertex))
Exemple #3
0
 def ray(self, point):
     ray_start = QVector4D(point)
     ray_start.setZ(-1.0)
     ray_start.setW(1.0)
     ray_end = QVector4D(point)
     ray_end.setZ(0.0)
     ray_end.setW(1.0)
     inverseProjectionMatrix = self._camera.projectionMatrix.inverted()[0]
     inverseViewMatrix = self._camera.viewMatrix.inverted()[0]
     ray_start_camera = inverseProjectionMatrix * ray_start
     ray_start_camera /= ray_start_camera.w()
     ray_end_camera = inverseProjectionMatrix * ray_end
     ray_end_camera /= ray_end_camera.w()
     ray_start_world = inverseViewMatrix * ray_start_camera
     ray_start_world /= ray_start_world.w()
     ray_end_world = inverseViewMatrix * ray_end_camera
     ray_end_world /= ray_end_world.w()
     ray = ray_end_world - ray_start_world
     ray_direction = QVector3D(ray[0], ray[1], ray[2]).normalized()
     return Ray(self,
                origin=QVector3D(ray_start_world[0], ray_start_world[1],
                                 ray_start_world[2]),
                direction=QVector3D(ray_direction[0], ray_direction[1],
                                    ray_direction[2]))
Exemple #4
0
    def __init__(self, **kwargs):
        """Initialize trackball"""
        super(Trackball, self).__init__()

        self._rotation = kwargs.get("rotation", QQuaternion())
        self._angularVelocity = kwargs.get("velocity", 0.0)
        self._axis = kwargs.get("axis", QVector3D(0.0, 1.0, 0.0))
        self._mode = kwargs.get("mode", self.TrackballMode.Spherical)

        self._lastPos = QPointF()
        self._lastTime = QTime.currentTime()
        self._paused = kwargs.get("paused", False)
        self._pressed = False

        self._first_person = False
Exemple #5
0
def position_to_frame_lower_calc(frame, pos, slope_motion):
    direction = pos[0] - pos[7]
    up = QVector3D.crossProduct(direction, (pos[4] - pos[1]))
    lower_body_orientation = QQuaternion.fromDirection(direction, up)
    initial = QQuaternion.fromDirection(QVector3D(0, -1, 0),
                                        QVector3D(0, 0, 1))
    lower_body_rotation = lower_body_orientation * initial.inverted()

    # 傾き補正
    lower_correctqq = QQuaternion()

    # 傾きデータがある場合、補正をかける
    if slope_motion is not None:
        # Y軸の回転具合を求める
        y_degree = (180 - abs(lower_body_rotation.toEulerAngles().y())) / 180

        # 一旦オイラー角に変換して、角度のかかり具合を補正し、再度クォータニオンに変換する
        lower_correctqq = QQuaternion.fromEulerAngles(
            slope_motion.frames["下半身"][0].rotation.toEulerAngles() *
            y_degree).inverted()

    lower_body_rotation = lower_correctqq * lower_body_rotation

    return lower_body_rotation, lower_correctqq
Exemple #6
0
 def prepareLine(self, line, colors, start_index=None):
     assert len(line) == len(colors)
     if start_index is None:
         start = len(self.coords_array)
         self.coords_array += line
         self.colors += colors
         self.normals += [QVector3D(0, 1, 0)] * len(line)
         end = len(self.coords_array)
     else:
         start = start_index
         for i, j in enumerate(range(start_index, start_index + len(line))):
             self.coords_array[j] = line[i]
             self.colors[j] = colors[i]
         end = start_index + len(line)
     return start, end
Exemple #7
0
 def get_coordinates(self):
     sz = self.font.getsize(self.text)
     img = Image.new('L', sz, 0)
     draw = ImageDraw.Draw(img)
     draw.text((0, 0), self.text, font=self.font, fill=255)
     bmp = np.array(img) > 128
     bmp = bmp[::-1]
     sz = self.parent.screen.camera.size()
     y, x = np.nonzero(bmp)
     x = x + normal(scale=self.fuzz, size=len(x)) - np.mean(x)
     y = y + normal(scale=self.fuzz, size=len(y)) - np.mean(y)
     x = x * self.spacing + sz.width() / 2
     y = y * self.spacing + sz.height() / 2
     p = list(map(lambda x, y: QVector3D(x, y, 0), x, y))
     return p
Exemple #8
0
 def general_segment_animation(self,
                               obj,
                               ix,
                               iy,
                               ia,
                               x,
                               y,
                               a,
                               clockwise,
                               duration=2000):
     if (ia > 2 * math.pi or ia < 0 or a > 2 * math.pi or a < 0):
         print("invalid angle values - must be >=0 and < 2*pi")
         a, ia = 0, 0
     anim = QPropertyAnimation(obj, b'pos')
     anim.setDuration(duration)
     r = 0
     if (not clockwise and a < ia): ia -= 2 * math.pi
     if (clockwise and a > ia): ia += 2 * math.pi
     start = QVector3D(float(ix), float(iy), float(ia))
     anim.setStartValue(start)
     end = QVector3D(float(x), float(y), float(a))
     anim.setEndValue(end)
     #anim.setKeyValueAt(0.999, QVector3D(float(x), float(y), float(a + r)))
     return anim
    def SetGrid(self, size: T.Tuple[int, int, int], cellScale):
        ONE_3D = QVector3D(1, 1, 1)
        rDx = 1 / cellScale

        with uglw.ProgBound(self._iprog_advection.__progHandle__):
            glUniform3fv(self._iprog_advection.rGridsize, 1,
                         utyp.GetTuple(ONE_3D / QVector3D(*size)))

        with uglw.ProgBound(self._iprog_divergence.__progHandle__):
            glUniform1fv(self._iprog_divergence.halfRdx, 1, 0.5 * rDx)

        with uglw.ProgBound(self._iprog_gradsub.__progHandle__):
            glUniform1fv(self._iprog_gradsub.halfRdx, 1, 0.5 * rDx)
            glUniform1iv(self._iprog_gradsub.u3_1, 1, 0)
            glUniform1iv(self._iprog_gradsub._3p1, 1, 1)

        with uglw.ProgBound(self._iprog_jacobi.__progHandle__):
            glUniform1iv(self._iprog_jacobi.fieldX, 1, 0)
            glUniform1iv(self._iprog_jacobi.fieldB, 1, 1)
            glUniform2fv(self._iprog_jacobi.alphaRbeta, 1,
                         (-cellScale * cellScale, 1 / 6))

        self._rDx = rDx
        self._gridSize = size
Exemple #10
0
    def __iniGraph3D(self):  ##创建3D图表
        self.graph3D = Q3DScatter()
        self.__container = QWidget.createWindowContainer(
            self.graph3D)  #继承自QWindow,必须如此创建

        self.dataProxy = QScatterDataProxy()  #数据代理  QScatterDataProxy
        self.series = QScatter3DSeries(self.dataProxy)  #创建序列 QScatter3DSeries
        self.series.setItemLabelFormat("(x,z,y)=(@xLabel,@zLabel,@yLabel)")
        self.series.setMeshSmooth(True)
        self.graph3D.addSeries(self.series)

        ##  设置坐标轴,使用内建的坐标轴
        self.graph3D.axisX().setTitle("axis X")
        self.graph3D.axisX().setTitleVisible(True)

        self.graph3D.axisY().setTitle("axis Y")
        self.graph3D.axisY().setTitleVisible(True)

        self.graph3D.axisZ().setTitle("axis Z")
        self.graph3D.axisZ().setTitleVisible(True)

        self.graph3D.activeTheme().setLabelBackgroundEnabled(False)

        self.series.setMesh(QAbstract3DSeries.MeshSphere)  #散点形状
        self.series.setItemSize(0.15)  # 散点大小 default 0. value 0~1

        ## 墨西哥草帽,-10:0.5:10, N=41
        N = 41
        itemCount = N * N
        itemArray = []  #QScatterDataItem 的列表

        x = -10.0
        for i in range(1, N + 1):
            y = -10.0
            for j in range(1, N + 1):
                z = math.sqrt(x * x + y * y)
                if z != 0:
                    z = 10 * math.sin(z) / z
                else:
                    z = 10
                vect3D = QVector3D(x, z, y)  #三维坐标点
                item = QScatterDataItem(vect3D)  #空间一个散点对象 QScatterDataItem
                itemArray.append(item)
                y = y + 0.5
            x = x + 0.5

        self.dataProxy.resetArray(itemArray)  #重置数组
        self.series.selectedItemChanged.connect(self.do_itemSelected)
Exemple #11
0
    def __init__(
            self,
            parent=None,
            r=QVector3D(),
            alpha=1.,  # relative amplitude
            phi=None,  # relative phase
            cgh=None,  # computational pipeline
            structure=None,  # structuring field
            state=states.normal):
        super(QTrap, self).__init__(parent)

        self.blockRefresh(True)

        # operational state
        self._state = state

        # appearance
        self.brush = {
            states.normal: pg.mkBrush(100, 255, 100, 120),
            states.selected: pg.mkBrush(255, 105, 180, 120),
            states.grouping: pg.mkBrush(255, 255, 100, 120)
        }
        self.baseSize = 15.
        self.spot = {
            'pos': QPointF(),
            'size': self.baseSize,
            'pen': pg.mkPen('w', width=0.2),
            'brush': self.brush[state],
            'symbol': self.plotSymbol()
        }

        # physical properties
        self.r = r
        self._alpha = alpha
        if phi is None:
            self.phi = np.random.uniform(low=0., high=2. * np.pi)
        else:
            self.phi = phi
        self.registerProperties()
        self.updateAppearance()

        # hologram calculation
        self._structure = structure
        self.psi = None
        self.cgh = cgh

        self.needsRefresh = True
        self.blockRefresh(False)
Exemple #12
0
 def mouseMoveEvent(self, event):
     vertices = self.parent().graph.vertices
     verticesPos = [QVector3D(i) for i in self.verticesPosWhenClicked]
     for (pos, afterPos) in zip(self.verticesPosWhenClicked, verticesPos):
         afterPos.setX(pos.x() - self.center().x())
         afterPos.setY(pos.y() - self.center().y())
         afterPos.setZ(pos.z() - self.center().z())
     disp = event.pos() - self.mousePosWhenClicked
     xAngle = QVector2D(disp).length() * 2 * math.pi / 360
     if QVector2D(disp).length() != 0:
         if (-numpy.sign(disp.x())) != 0:
             zAngle = math.acos(
                 (-disp.y()) /
                 QVector2D(disp).length()) * (-numpy.sign(disp.x()))
         else:
             zAngle = math.acos((-disp.y()) / QVector2D(disp).length())
     else:
         zAngle = 0
     xTurnList = [
         1, 0, 0, 0,
         math.cos(xAngle), -math.sin(xAngle), 0,
         math.sin(xAngle),
         math.cos(xAngle)
     ]
     zTurnList = [
         math.cos(zAngle), -math.sin(zAngle), 0,
         math.sin(zAngle),
         math.cos(zAngle), 0, 0, 0, 1
     ]
     minusZTurnList = [
         math.cos(-zAngle), -math.sin(-zAngle), 0,
         math.sin(-zAngle),
         math.cos(-zAngle), 0, 0, 0, 1
     ]
     zTurnMatrix = MyM3R(zTurnList)
     xTurnMatrix = MyM3R(xTurnList)
     minusZTurnMatrix = MyM3R(minusZTurnList)
     for (pos, vertex) in zip(verticesPos, vertices):
         zTurnMatrix.transform(pos)
         xTurnMatrix.transform(pos)
         minusZTurnMatrix.transform(pos)
         vertex.setX(pos.x() + self.center().x())
         vertex.setY(pos.y() + self.center().y())
         vertex.setZ(pos.z() + self.center().z())
     for vertex in vertices:
         vertex.circle.move()
     for edge in self.parent().graph.edges:
         edge.move()
Exemple #13
0
 def dotask(self):
     traps = self.group.flatten()
     if len(traps) == 1:
         trap = traps[0]
         fn, fn_ext = os.path.splitext(self.parent.dvr.filename)
         zmax = -100
         z = trap.r.z()
         dz = -3
         dr = QVector3D(0, 0, dz)
         while z >= zmax:
             prefix = fn+'_'+str(z)
             self.register('MaxTask', prefix=prefix)
             self.register('Translate', traps=trap, dr=dr)
             z += dz
     else:
         logger.warning("Please create a QTrapGroup with one trap.")
Exemple #14
0
def read_positions(position_file):
    """Read joint position data"""
    f = open(position_file, "r")

    positions = []
    while True:
        line = f.readline()
        if not line:
            break
        line = line.rstrip('\r\n')
        a = re.split(' ', line)
        # 元データはz軸が垂直上向き。MMDに合わせるためにyとzを入れ替える。
        q = QVector3D(float(a[1]), float(a[3]), float(a[2])) # a[0]: index
        positions.append(q) # a[0]: index
    f.close()
    return positions
Exemple #15
0
 def compute(self, point, object, light, camera):
     """ Compute light for matte shader
                   :param point:  QVector3D point at point t
                   :param object:  Primitive object that got hit
                   :param light:  Light
                   :param camera: Camera
                   :return:
                       QVector3D with calculated value for lambert
            """
     diffuse_Color = QVector3D(0.5, 0.5, 0.5)
     diffuse_coefficient = 0.9
     light_dir = light.direction(point)  # L
     normal = object.normal_at(point)  # N
     NdotL = QVector3D.dotProduct(light_dir, normal)
     lambert = diffuse_coefficient * diffuse_Color * light.color * max(NdotL, 0.0)
     return lambert
Exemple #16
0
    def __init__(self, processor, df, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.processor = processor
        # Data
        self.df = df

        # UI
        self.setupUi(self)
        self.setupControls()
        self.keyPressEvent = self.keyPressed
        self.mouseMoveEvent = self.mouseMoved

        # Control & Display
        self.mouse_grabbed = False

        self.camera_pos = QVector3D(0.5, 0.5, -2)  # Start camera position
        self.center = QVector3D(0.5, 0, 0.5)  # Center of object
        self.rot_center = QVector3D(0.5, 0.5, 0.5)  # Center of rotation
        self.camera_rot = QVector3D(0, 0, 1)  # Camera rotation
        self.scale_vec = QVector3D(1, 1, 1)  # Object scale
        self.real_prop = processor.get_real_scaling()  # val to lat

        self.light_pos = QVector3D(self.xLightSpinBox.value(),
                                   self.yLightSpinBox.value(),
                                   self.zLightSpinBox.value())
        self.ambient = self.ambientSlider.value() / 100
        self.diffuse = self.diffuseSlider.value() / 100
        self.alpha = self.alphaSlider.value() / 100  # Transparency

        # Drawing
        self.normals = []
        self.colors = []
        self.coords_array = []
        # !> len(self.normals) == len(self.colors) == len(self.coords_array)

        self.update_light = False  # Update for light is needed
        self.update_buffer = False  # Update for whole buffer is needed

        self.show_grid = self.gridCheckBox.isChecked()
        self.show_contour = self.contourCheckBox.isChecked()
        self.contour_levels = self.contourLevelSpinBox.value()
        self.show_light_lines = True
        self.grid_freq = 10

        self.grid_color = QVector4D(1, 1, 1, 1)
        self.contour_color = QVector4D(1, 1, 1, 1)
        self.light_line_color = QVector4D(1, 0.6, 0, 1)

        self.prepareScene()
        self.updateUi()

        self.shaders = QOpenGLShaderProgram()
        self.openGLWidget.initializeGL = self.initializeGL
        self.openGLWidget.paintGL = self.paintGL
Exemple #17
0
    def ray_pick_test(self, origin, direction):
        """Check whether the given ray intersects this object.

        :param QVector3D origin: the camera position
        :param QVector3D direction: the direction vector. This MUST be normalized.
        :returns: the distance to the closest point of this object along the ray. Negative values if no intersection
        """
        L = origin - QVector3D(*self.offset)
        t0, t1 = solve_quadratic(1, 2 * QVector3D.dotProduct(direction, L),
                                 QVector3D.dotProduct(L, L) - self.scale**2)
        if t0 is None or (t0 <= 0 and t1 <= 0):
            return -1
        elif t0 > 0 and t0 < t1:
            return t0
        else:
            return t1
    def paintGL(self):
        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT
                        | self.gl.GL_DEPTH_BUFFER_BIT)

        # Set rotation so that the quad is rotated 45 degrees clockwise
        self.currentRotation = QVector3D(0.0, 0.0, 45.0)
        self.program.setUniformValue(self.objectRotation, self.currentRotation)

        # Before painting we set the scaling "uniform" parameter in the vertex shader.
        # This will be used to scale the vertex positions.
        self.program.setUniformValue(self.viewportScaling, self.currentScaling)

        # Draw a quad starting at vertex number. Since we enabled attribarrays, it will fetch data from the array buffer
        self.gl.glDrawArrays(self.gl.GL_QUADS, 0, self.numberOfVertices)

        self.dumpGLLogMessages("paintGL()")
Exemple #19
0
    def get_coordinates(self):
        '''Returns coordinates of lit pixels in text'''
        if len(self.text) == 0:
            return []
        # Buffer for drawing text
        w, h = 100, 20
        pixmap = QPixmap(w, h)
        pixmap.fill(QColor('black'))

        # Painter for rendering text
        painter = QPainter(pixmap)

        # White text on black background
        pen = QPen()
        pen.setWidth(1)
        pen.setColor(QColor('white'))
        painter.setPen(pen)

        # Small sans serif font, no antialiasing
        font = QFont()
        font.setFamily('Arial')
        font.setPointSize(9)
        font.setStyleStrategy(QFont.NoAntialias)
        painter.setFont(font)

        # Draw text into buffer
        painter.drawText(0, h, self.text)
        painter.end()

        # Extract bitmap data from buffer
        image = pixmap.toImage()
        data = image.bits()
        data.setsize(h * w * 4)
        bmp = np.frombuffer(data, np.uint8).reshape((h, w, 4))
        bmp = bmp[:, :, 0]

        # Coordinates of lit pixels
        y, x = np.nonzero(bmp)
        y *= -1
        x = x + normal(scale=self.fuzz, size=len(x)) - np.mean(x)
        y = y + normal(scale=self.fuzz, size=len(y)) - np.mean(y)
        x *= self.spacing
        y *= self.spacing
        x += self.parent().camera.device.width / 2
        y += self.parent().camera.device.height / 2
        p = list(map(lambda x, y: QVector3D(x, y, 0), x, y))
        return p
Exemple #20
0
 def prepareNormalLines(self, polygons, normals, colors):
     """Normal lines for each polygon.
     Debug only
     """
     norm_i = 0
     start = len(self.coords_array)
     for polygon in polygons:
         point = polygon[0]
         normal = normals[norm_i]
         # color = colors[norm_i]
         color = QVector4D(1, 1, 1, 1)
         point_2 = QVector3D(*point) + normal * 0.04
         point_2 = (point_2.x(), point_2.y(), point_2.z())
         self.prepareLine((point, point_2), [color] * 2)
         norm_i += len(polygon)
     end = len(self.coords_array)
     return start, end
def read_files(PATH, files):
    with open(PATH + files, 'r') as f:
        positions = []
        while True:
            line = f.readline()
            if not line:
                break
            line = line.rstrip('\n')

            inposition = []
            for inline in re.split(",\s*", line):
                if inline:
                    a = re.split(' ', inline)
                    q = QVector3D(float(a[1]), float(a[3]), float(a[2]))
                    inposition.append(q)
            positions.append(inposition)
    return positions
Exemple #22
0
 def compute(self, point, object, light, camera):
     """ Compute light for matte shader
                   :param point:  QVector3D point at point t
                   :param object:  Primitive object that got hit
                   :param light:  Light
                   :param camera: Camera
                   :return:
                       QVector3D with calculated value for lambert
            """
     specular_color = QVector3D(1.0, 1.0, 1.0)
     light_dir = light.direction(point)  # L
     normal = object.normal_at(point)  # N
     eye_dir = (camera.position - point).normalized()  # V
     half_vector = (eye_dir + light_dir).normalized()
     NdotH = QVector3D.dotProduct(normal, half_vector)
     specular = light.color * specular_color * pow(max(NdotH, 0.0), light.shininess)
     return specular
Exemple #23
0
 def plot3D(self,func,csize:CubeSize,nbsamples:list=[50,50]):
     ''' E/ func: funtion to be diplayed on screen ; takes 3 parameters (x,y,t) with t optional (static animation)
         E/ csize: list containing 3 integers (sizeX,sizeY,sizeZ) to know the boundaries 
         E/ nbsamples (OPTIONAL) : list containing 2 integers (sampleX,sampleZ) to define the resolution of the graph
         S/ No output, sets the right data in the functionProxy to display the graph '''
     valuesArray = []
     stepX=csize.getSize(Axis.X)/(nbsamples[0]-2)
     stepZ=csize.getSize(Axis.Z)/(nbsamples[1]-2)
     for i in range(nbsamples[1]):
         currentRow=[]
         z=min(csize.getSize(Axis.Z)-1,i*stepZ)
         for j in range(nbsamples[0]):
             x=min(csize.getSize(Axis.X)-1,j*stepX)
             y=func(x,z)
             currentRow.append(QSurfaceDataItem(QVector3D(x,y,z)))
         valuesArray.append(currentRow)
     self.functionProxy.resetArray(valuesArray)      
    def __init__(self, scene, **kwargs):
        """Initialize actor."""
        super(OrientationMarker, self).__init__(scene, **kwargs)

        self._resolution = kwargs.get("resolution", 12)
        self._colorx = kwargs.get("xcolor", QVector3D(1.0, 0.0, 0.0))
        self._colory = kwargs.get("ycolor", QVector3D(0.0, 1.0, 0.0))
        self._colorz = kwargs.get("zcolor", QVector3D(0.0, 0.47, 0.78))
       
        ## create sphere
        matrix = QMatrix4x4()
        matrix.scale(0.4, 0.4, 0.4)
        self.addPart(Icosahedron(self.scene, name="sphere",
            level=2, colors=False, material=Material(ambient=QVector3D(0.25, 0.25, 0.25), 
            diffuse=QVector3D(0.4, 0.4, 0.4), 
            specular=QVector3D(.2, .2, .2), 
            shininess=128.8), transform=matrix))

        ## x axis cone
        matrix = QMatrix4x4()
        matrix.rotate(-90.0, QVector3D(0.0, 0.0, 1.0))
        matrix.scale(0.19, 0.2, 0.19)
        matrix.translate(0.0, 2.8, 0.0)
        self.addPart(Cone(self.scene, name="xaxis",
            resolution=self._resolution, material=Material(diffuse=self._colorx, specular=QVector3D(0.5, 0.5, 0.5), 
            shininess=76.8), transform=matrix))

        ## y axis cone
        matrix = QMatrix4x4()
        matrix.scale(0.19, 0.2, 0.19)
        matrix.translate(0.0, 2.7, 0.0) ##6.0
        self.addPart(Cone(self.scene, name="yaxis",
            resolution=self._resolution, material=Material(diffuse=self._colory, specular=QVector3D(0.5, 0.5, 0.5), 
            shininess=76.8), transform=matrix))

        ## z axis cone
        matrix = QMatrix4x4()
        matrix.rotate(90.0, QVector3D(1.0, 0.0, 0.0))
        matrix.scale(0.19, 0.2, 0.19)
        matrix.translate(0.0, 2.7, 0.0)
        self.addPart(Cone(self.scene, name="zaxis",
            resolution=self._resolution, material=Material(diffuse=self._colorz, specular=QVector3D(0.5, 0.5, 0.5), 
            shininess=76.8), transform=matrix))
Exemple #25
0
    def createScene(self):
        # Root entity
        rootEntity = QEntity()

        light_entity = QEntity(rootEntity)
        light = QPointLight(light_entity)
        light.setColor(QColor(255, 255, 255))
        light.setIntensity(0.6)
        trans = QTransform()
        trans.setTranslation(QVector3D(0, 0, 2))

        light_entity.addComponent(trans)
        light_entity.addComponent(light)

        # Material
        material = QPhongMaterial(rootEntity)
        material.setAmbient(QColor(100, 100, 100))
        # material.setShininess(0)

        self.robot_entity = QEntity(rootEntity)
        f1_mesh = QMesh()
        f1_mesh.setSource(QUrl('qrc:/assets/' + self.robot_type + '.obj'))

        self.robot_entity.addComponent(f1_mesh)

        self.robot_entity.addComponent(material)

        sphereTransform = QTransform()

        controller = OrbitTransformController(sphereTransform)
        controller.setTarget(sphereTransform)
        controller.setRadius(0.0)

        self.sphereRotateTransformAnimation = QPropertyAnimation(
            sphereTransform)
        self.sphereRotateTransformAnimation.setTargetObject(controller)
        self.sphereRotateTransformAnimation.setPropertyName(b"angle")
        self.sphereRotateTransformAnimation.setStartValue(0)
        self.sphereRotateTransformAnimation.setEndValue(360)
        self.sphereRotateTransformAnimation.setDuration(10000)
        self.sphereRotateTransformAnimation.setLoopCount(-1)
        self.robot_entity.addComponent(sphereTransform)
        self.start_animation()

        return rootEntity
    def fillSqrtSinProxy(self):
        stepX = (self.sampleMax - self.sampleMin) / (self.sampleCountX - 1)
        stepZ = (self.sampleMax - self.sampleMin) / (self.sampleCountZ - 1)

        dataArray = []
        μ = np.array([0., 0.])
        ρ = self.rho  # -0.4082482904638631
        σ1 = 1.0
        σ2 = 1.224744871391589
        N = 200
        X = np.linspace(-3, 3, N)
        Y = np.linspace(-3, 3, N)
        X, Y = np.meshgrid(X, Y)
        pos = np.empty(X.shape + (2, ))
        pos[:, :, 0] = X
        pos[:, :, 1] = Y
        n = μ.shape[0]
        Sigma = np.array([[σ1**2, ρ * σ1 * σ2], [ρ * σ1 * σ2, σ2**2]])
        F = multivariate_normal(μ, Sigma)
        Z = F.pdf(pos)
        for i in range(N):
            newRow = []
            for j in range(N):
                x = X[i, j]
                y = Y[i, j]
                z = Z[i, j]
                newRow.append(QSurfaceDataItem(QVector3D(x, z, y)))
            dataArray.append(newRow)
        '''
        for i in range(self.sampleCountZ):

            # Keep values within range bounds, since just adding step can cause
            # minor drift due to the rounding errors.
            z = min(self.sampleMax, (i * stepZ + self.sampleMin))
            newRow = []
            for j in range(self.sampleCountX):
                x = min(self.sampleMax, (j * stepX + self.sampleMin))
                R = math.sqrt(z * z + x * x) + 0.01
                y = (math.sin(R) / R + 0.24) * 1.61

                newRow.append(QSurfaceDataItem(QVector3D(x, y, z)))

            dataArray.append(newRow)
        '''
        self.m_sqrtSinProxy.resetArray(dataArray)
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 generateData(self):
        # 生成模拟数据
        magneticFieldArray = []

        for i in range(self.m_fieldLines):
            horizontalAngle = (self.doublePi * i) / self.m_fieldLines
            xCenter = self.ellipse_a * math.cos(horizontalAngle)
            zCenter = self.ellipse_a * math.sin(horizontalAngle)

            # Rotate - arrow is always tangential to the origin.
            # 旋转-箭头始终与原点相切。
            yRotation = QQuaternion.fromAxisAndAngle(
                0.0, 1.0, 0.0, horizontalAngle * self.radiansToDegrees)

            for j in range(self.m_arrowsPerLine):
                # Calculate the point on the ellipse centered on the origin and
                # 计算椭圆上以原点为中心的点
                # parallel to the x-axis.
                # 平行于X轴。
                verticalAngle = ((self.doublePi * j) /
                                 self.m_arrowsPerLine) + self.m_angleOffset
                xUnrotated = self.ellipse_a * math.cos(verticalAngle)
                y = self.ellipse_b * math.sin(verticalAngle)

                # Rotate the ellipse around the y-axis.
                # 围绕Y轴旋转椭圆。
                xRotated = xUnrotated * math.cos(horizontalAngle)
                zRotated = xUnrotated * math.sin(horizontalAngle)

                # Add the offset.
                # 添加偏移量。
                x = xCenter + xRotated
                z = zCenter + zRotated

                zRotation = QQuaternion.fromAxisAndAngle(
                    0.0, 0.0, 1.0, verticalAngle * self.radiansToDegrees)
                totalRotation = yRotation * zRotation

                itm = QScatterDataItem(QVector3D(x, y, z), totalRotation)
                magneticFieldArray.append(itm)

        if self.m_graph.selectedSeries() is self.m_magneticField:
            self.m_graph.clearSelection()

        self.m_magneticField.dataProxy().resetArray(magneticFieldArray)
Exemple #29
0
    def create_atom(self, atom: Atom, root_entity, color: QColor):
        if atom.element in self._materials_dict:
            material = self._materials_dict[atom.element]
        else:
            material = QDiffuseSpecularMaterial(root_entity)
            material.setDiffuse(color)
            material.setAmbient(color.darker(200))
            self._materials_dict[atom.element] = material

        sphere_entity = QEntity(root_entity)
        sphere_mesh = QSphereMesh()
        sphere_mesh.setRadius(0.5)
        sphere_transform = QTransform()
        sphere_transform.setTranslation(QVector3D(*atom.coords_cartesian))

        sphere_entity.addComponent(sphere_mesh)
        sphere_entity.addComponent(sphere_transform)
        sphere_entity.addComponent(material)
Exemple #30
0
    def mousePressEvent(self, event):
        viewport = np.array(GL.glGetIntegerv(GL.GL_VIEWPORT))

        if(self.sketching):
            self.sketchPoints.append([event.x(), viewport[3] - event.y()])
        else:
            self.lastMousePos = event.pos()
            print("clicked")
            cursorX = event.x()
            cursorY = event.y()
            winX = float(cursorX)
            winY = float(viewport[3] - cursorY)

            # obtain Z position
            winZ = GL.glReadPixels(winX, winY, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT);

            winVector = QVector3D(winX, winY, winZ)
            print(winVector)