我一直在尝试旋转对象,但是旋转时,我意识到它只是平坦的。奇怪的是,我可以清楚地看到z dim的输入在那儿,只是没有考虑到。这是我的代码:

import moderngl
from PyQt5 import QtOpenGL, QtCore, QtGui
from PyQt5.QtCore import Qt, pyqtSignal
import numpy as np
from pyrr import matrix44

cube_verts4 = np.array([
    -1.0, 1.0, -1.0, 1.0,
    -1.0, -1.0, -1.0, 1.0,
    1.0, -1.0, -1.0, 1.0,
    1.0, 1.0, -1.0, 1.0,
    -1.0, 1.0, 1.0, 1.0,
    -1.0, -1.0, 1.0, 1.0,
    1.0, -1.0, 1.0, 1.0,
    1.0, 1.0, 1.0, 1.0,
], dtype=np.float32)

cube_ibo_idxs = np.array([
    0, 1, 2,
    2, 3, 1,
    3, 2, 6,
    6, 5, 3,
    5, 6, 7,
    7, 4, 5,
    4, 7, 1,
    1, 0, 4,
    0, 3, 5,
    5, 4, 0,
    1, 7, 6,
    6, 2, 1

], dtype=np.int32)


class OpenGLWindowWidget(QtOpenGL.QGLWidget):
    vsync = True
    remove_event = pyqtSignal(str)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.gl_version = (4, 3)
        fmt = QtOpenGL.QGLFormat()
        # need compute shader stuff
        fmt.setVersion(self.gl_version[0], self.gl_version[1])
        fmt.setProfile(QtOpenGL.QGLFormat.CoreProfile)
        fmt.setDepthBufferSize(24)
        fmt.setDoubleBuffer(True)
        fmt.setSwapInterval(1 if self.vsync else 0)
        self.ctx = None
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.update)
        self.timer.start(16)
        self.last_mouse_pos = None

        self.rotation_x = 0
        self.rotation_y = 0

    def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
        self.last_mouse_pos = event.pos()

    def mouseMoveEvent(self, event: QtGui.QMouseEvent) -> None:
        dx = event.x() - self.last_mouse_pos.x()
        dy = event.y() - self.last_mouse_pos.y()
        if event.buttons() & Qt.LeftButton:
            self.rotation_x += dx * 0.01
            self.rotation_y += dy * 0.01

        self.last_mouse_pos = event.pos()

    @property
    def gl_version_code(self) -> int:
        return self.gl_version[0] * 100 + self.gl_version[1] * 10

    @property
    def aspect_ratio(self):
        return self.width() / self.height()

    def initializeGL(self) -> None:
        self.ctx = moderngl.create_context(
            require=self.gl_version_code)
        self.prog = self.ctx.program(
            vertex_shader='''
                               #version 330
                               in vec4 vertex;
                               in float power;
                               uniform mat4 mvp_matrix;
                               void main() {
                                   gl_Position = vec4(mvp_matrix * vertex);
                               }
                           ''',
            fragment_shader='''
                                   #version 330
                                   out vec4 color;
                                   void main() {
                                       color = vec4(0.0, 0.0, 0.0, 1.0);
                                   }
                                   ''',
        )

        self.mvp_matrix = self.prog["mvp_matrix"]

        self.vbo = self.ctx.buffer(
            cube_verts4.astype('f4').tobytes())
        self.ibo = self.ctx.buffer(
            cube_ibo_idxs.astype('i4').tobytes())
        vao_content = [
            # 4 floats are assigned to the 'in' variable named 'vertex' in the shader code
            (self.vbo, '4f', 'vertex'),
        ]
        self.vao = self.ctx.vertex_array(self.prog, vao_content,
                                         self.ibo)

    def paintGL(self):
        target_width = 2
        target_height = 2
        r_aspect_ratio = target_width / target_height
        if self.aspect_ratio > r_aspect_ratio:
            v_a = self.aspect_ratio / r_aspect_ratio
            projection = matrix44.create_orthogonal_projection_matrix(
                -v_a * target_width / 2.0,
                v_a * target_width / 2.0, -target_height / 2.0,
                target_height / 2.0, 0, 100, dtype=np.float32)
        else:
            a_v = r_aspect_ratio / self.aspect_ratio
            projection = matrix44.create_orthogonal_projection_matrix(
                -target_width / 2.0, target_width / 2.0,
                -a_v * target_height / 2.0,
                a_v * target_height / 2.0,
                0, 100, dtype=np.float32)

        rotate = matrix44.create_from_y_rotation(
            self.rotation_x) * matrix44.create_from_x_rotation(
            self.rotation_y)

        self.mvp_matrix.write((rotate * projection).astype('f4').tobytes())
        self.ctx.viewport = (0, 0, self.width(), self.height())
        self.ctx.clear(0.0, 1.0, 1.0)
        self.vao.render()
        self.ctx.finish()


这就是我旋转时得到的结果。

python - Z维在Moderngl中消失了吗?-LMLPHP

python - Z维在Moderngl中消失了吗?-LMLPHP

python - Z维在Moderngl中消失了吗?-LMLPHP

我本来期望立方体的轮廓,而不是平面的轮廓。

我什至不知道是什么原因造成了这种影响。最初,我认为这与vec3的对齐方式有关,但是我替换了我的vertex + vbo代码,改为使用vec4s,但仍然无法正常工作。我不知道如何“去除”我的深度。我不熟悉pyrr,所以也许有些矩阵变换是不正确的?

最佳答案

元素索引不构成多维数据集。使用以下索引:

cube_ibo_idxs = np.array([
    0, 1, 2,   0, 2, 3,
    3, 2, 6,   3, 6, 7,
    7, 6, 5,   7, 5, 4,
    7, 4, 0,   7, 0, 3,
    4, 5, 1,   4, 1, 0,
    1, 5, 6,   1, 6, 2
], dtype=np.int32)


pyrr Matrix44操作返回numpy.array
对于数组,*表示逐元素乘法,而@表示矩阵乘法。请参见array。因此,您不想使用@* istead。或者,您可以使用numpy.matmul

在正投影中,近平面设置为0,远平面设置为100。


  
projection = matrix44.create_orthogonal_projection_matrix(
               v_a * -target_width / 2.0, v_a * target_width / 2.0,
               -target_height / 2.0, target_height / 2.0,
               0, 100, dtype=np.float32)



由于几何的中心在(0,0,0),因此立方体网格被长方体视图体积的近平面部分裁剪。更改近平面(例如-100)或在近平面和远平面之间绘制立方体。这意味着您必须沿z轴平移网格。由于(视图空间)z轴指向视口(在Right-handed系统中),因此您必须沿负z方向平移网格(例如-3):

rotate = matrix44.create_from_y_rotation(-self.rotation_x) @ \
         matrix44.create_from_x_rotation(-self.rotation_y) @ \
         matrix44.create_from_translation(np.array([0, 0, -3], dtype=np.float32))


此外,我建议启用Depth Test。参见ModernGL - Context

self.ctx.enable(moderngl.DEPTH_TEST)


使用以下功能绘制几何:

def paintGL(self):
    target_width = 4
    target_height = 4
    r_aspect_ratio = target_width / target_height
    if self.aspect_ratio > r_aspect_ratio:
        v_a = self.aspect_ratio / r_aspect_ratio
        projection = matrix44.create_orthogonal_projection_matrix(
            v_a * -target_width / 2.0, v_a * target_width / 2.0,
            -target_height / 2.0, target_height / 2.0,
            0, 100, dtype=np.float32)
    else:
        a_v = r_aspect_ratio / self.aspect_ratio
        projection = matrix44.create_orthogonal_projection_matrix(
            -target_width / 2.0, target_width / 2.0,
            -a_v * target_height / 2.0, a_v * target_height / 2.0,
            0, 100, dtype=np.float32)

    rotate = matrix44.create_from_y_rotation(-self.rotation_x) @ \
                matrix44.create_from_x_rotation(-self.rotation_y) @ \
                matrix44.create_from_translation(np.array([0, 0, -3], dtype=np.float32))

    self.mvp_matrix.write((rotate @ projection).astype('f4').tobytes())
    self.ctx.viewport = (0, 0, self.width(), self.height())
    self.ctx.clear(0.0, 1.0, 1.0)
    self.ctx.enable(moderngl.DEPTH_TEST)
    self.vao.render()
    self.ctx.finish()


如果使用以下顶点着色器

#version 330
in vec4 vertex;
in float power;
out vec4 v_clip_pos;
uniform mat4 mvp_matrix;
void main() {
    v_clip_pos = mvp_matrix * vertex;
    gl_Position = v_clip_pos;
}


和片段着色器

#version 330
in vec4 v_clip_pos;
out vec4 color;
void main() {

    vec3  ndc_pos = v_clip_pos.xyz / v_clip_pos.w;
    vec3  dx      = dFdx( ndc_pos );
    vec3  dy      = dFdy( ndc_pos );

    vec3 N = normalize(cross(dx, dy));
    N *= sign(N.z);
    vec3 L = vec3(0.0, 0.0, 1.0);
    float NdotL = dot(N, L);

    vec3 diffuse_color = vec3(0.5) * NdotL;
    color              = vec4( diffuse_color.rgb, 1.0 );
}


那么您可以实现轻微的3D效果。

python - Z维在Moderngl中消失了吗?-LMLPHP

10-08 08:23