0

在无头模式下运行时,我遇到了 Moderngl 最新版本的一个非常奇怪的问题。下面的代码应该给我一个三角形,它在右侧和顶部接触视口的边缘,但右侧和顶部的顶点在视口之外延伸了 1.98 左右的一些奇数因子。将 x 和 y 值更改为 0.5 不会改变输出。这在 OSX 和 Linux 上是一样的。有谁知道这里发生了什么?

import moderngl
from pyrr import Matrix44
import numpy as np
import cv2

vertex_shader_source = """
    #version 330
    in vec3 local_vertex;
    uniform mat4 modelview_matrix;
    uniform mat4 projection_matrix;
    void main(){
        gl_Position = projection_matrix * modelview_matrix * vec4( local_vertex, 1.0 );
    }
"""

fragment_shader_source = """
    #version 330
    out vec4 out_color;
    void main() {
        out_color = vec4(1.0, 1.0, 1.0, 1.0);
    }
"""

context = moderngl.create_standalone_context()
prog = context.program(vertex_shader=vertex_shader_source, fragment_shader=fragment_shader_source)

vertices = np.array([[ 0.0,  0.0, 0.0],
                        [ 1.0,  0.0, 0.0],
                        [ 1.0,  1.0, 0.0]])

vbo = context.buffer(vertices.tobytes())
vao = context.simple_vertex_array(prog, vbo, "local_vertex")
color_renderbuffer = context.renderbuffer((128, 128))
fbo_regular = context.framebuffer(color_attachments=(color_renderbuffer))

modelview_matrix = Matrix44.look_at(np.array([0.0, 0.0, 10.0]), np.array([0.0, 0.0, 0.0]), np.array([0.0, 1.0, 0.0]))
projection_matrix = Matrix44.orthogonal_projection(-1.0, 1.0, -1.0, 1.0, 1.0, 100.0)
prog["projection_matrix"].write(projection_matrix.astype("f4").tobytes())
prog["modelview_matrix"].write(modelview_matrix.astype("f4").tobytes())

fbo_regular.use()
context.clear(1.0, 0.0, 0.0)
vao.render()

data = fbo_regular.read(components=3, alignment=1, dtype='f4')
data_array = np.frombuffer(data, dtype=np.float32).reshape(128,128,3)
cv2.imwrite("output0.png",(data_array[::-1]) * 255.0)

输出是: 文本

更新:显然,当我使用“结构”模块时,问题就消失了。

self.vbo = self.ctx.buffer(struct.pack('9f', 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0))

是什么赋予了??

4

2 回答 2

1

Numpy 默认使用 64 位浮点数,因此in vec3 local_vertex在您的顶点着色器中会有些混乱。见:https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)

# The most efficient way is to construct the array using the right dtype
self.vertices = np.array([[ 0.0,  0.0, 0.0],
                          [ 1.0,  0.0, 0.0],
                          [ 1.0,  1.0, 0.0]], dtype='f4')

# Because both numpy and moderngl supports the buffer protocol
# we can pass them directly instead of converting to `bytes`
self.vbo = self.ctx.buffer(self.vertices)

如果您对moderngl 有疑问,您也可以联系moderngl 社区:https ://github.com/moderngl/moderngl

于 2020-03-30T21:49:46.297 回答
0

通过将 numpy 缓冲区转换为 f4 类型来解决它:

self.vertices = np.array([[ 0.0,  0.0, 0.0],
                          [ 1.0,  0.0, 0.0],
                          [ 1.0,  1.0, 0.0]])

self.vbo = self.ctx.buffer(self.vertices.astype('f4'))

给出预期的结果。一个 numpy 浮点数组的默认数据类型是 f8(64 位双精度),顶点缓冲区需要 32 位。这恰好给出了类似的结果,这让我失望了。

于 2020-03-15T14:03:16.553 回答