См. пример кода ниже:
Код: Выделить всё
import glfw
import moderngl
import numpy as np
# Initialize glfw
if not glfw.init():
raise Exception("glfw can not be initialized!")
# Create the first windowed mode window and its OpenGL context. We call it window 1.
window1 = glfw.create_window(400, 400, "OpenGL Window 1", None, None)
if not window1:
glfw.terminate()
raise Exception("glfw window can not be created!")
# Make the window's context current
glfw.make_context_current(window1)
# Create ModernGL context
ctx1 = moderngl.create_context()
# Create the second windowed mode window and its OpenGL context. We call it window 2.
window2 = glfw.create_window(400, 400, "OpenGL Window 2", None, None)
if not window2:
glfw.terminate()
raise Exception("glfw window can not be created!")
# Make the window's context current
glfw.make_context_current(window2)
# Create ModernGL context
ctx2 = moderngl.create_context()
print(ctx1)
print(ctx2)
print(window1)
print(window2)
# Create a simple shader program for ctx1
prog1 = ctx1.program(
vertex_shader="""
#version 330 core
in vec3 in_position;
void main() {
gl_Position = vec4(in_position, 1.0);
}
""",
fragment_shader="""
#version 330 core
layout (location = 0) out vec4 fragColor;
void main() {
vec3 color = vec3(1, 0, 0);
fragColor = vec4(color, 1.0);
}
"""
)
# Create a simple shader program for ctx2
prog2 = ctx2.program(
vertex_shader="""
#version 330 core
in vec3 in_position;
void main() {
gl_Position = vec4(in_position, 1.0);
}
""",
fragment_shader="""
#version 330 core
layout (location = 0) out vec4 fragColor;
void main() {
vec3 color = vec3(1, 0, 0);
fragColor = vec4(color, 1.0);
}
"""
)
print(prog1)
print(prog2)
vertices = np.array([
0.5, 0.0, 0.0,
0.25, 0.5, 0.0,
0.0, 0.0, 0.0,
], dtype='f4')
vbo1 = ctx1.buffer(vertices.tobytes())
vao1 = ctx1.vertex_array(prog1, [(vbo1, '3f', 'in_position')])
vbo2 = ctx2.buffer(vertices.tobytes())
vao2 = ctx2.vertex_array(prog2, [(vbo2, '3f', 'in_position')])
# Render to window1
glfw.make_context_current(window1)
print("Current context: ", ctx1, "Current window (Should be window 1): ", window1)
FrameBuffer1 = ctx1.detect_framebuffer()
print(f"Framebuffer ID for ctx1: {FrameBuffer1.glo}")
ctx1.clear(0.0, 1.0, 1.0, 1.0)
vao1.render(moderngl.TRIANGLES)
glfw.swap_buffers(window1)
glfw.make_context_current(None)
# Render to window2
glfw.make_context_current(window2)
print("Current context: ", ctx2, "Current window: (Should be window 2)", window2)
FrameBuffer2 = ctx2.detect_framebuffer()
print(f"Framebuffer ID for ctx2: {FrameBuffer2.glo}")
ctx2.clear(1.0, 1.0, 0.0, 1.0)
vao2.render(moderngl.TRIANGLES)
glfw.swap_buffers(window2)
glfw.make_context_current(None)
# Hold the windows open until they are closed
while not glfw.window_should_close(window1) and not glfw.window_should_close(window2):
# Poll for and process events
glfw.poll_events()
# Terminate glfw
glfw.terminate()
Красный треугольник отображается только во втором окне.
Я дважды проверил RGB Значения /Alpha внутри фрагментного шейдера. Я считаю, что правильно обновляю соответствующие контексты, а затем публикую их по мере необходимости. Я добавил отладочные распечатки для проверки уникальности следующих объектов:
Код: Выделить всё
ModernGL Context 1
ModernGL Context 2
glfw Window 1
glfw Window 2
ModernGL Context 1 Shader Program
ModernGL Context 2 Shader Program
Current context/window prior to attempting to render to window 1
Framebuffer ID with respect to context 1
Current context/window prior to attempting to render to window 2
Framebuffer ID with respect to context 2
Код: Выделить всё
Current context: Current window (Should be window 1):
Framebuffer ID for ctx1: 0
Current context: Current window: (Should be window 2)
Framebuffer ID for ctx2: 0
Я застрял. о том, почему у меня нет двух треугольников, а только один, и я задаю этот вопрос, пытаясь просмотреть документацию ModernGL и OpenGL.
Любые идеи относительно того, почему происходит такое поведение и какой подход я могу предпринять, чтобы решить эту проблему? Это связано с тем, что мне приходится делать контексты общими при вызове «moderngl.create_context()» (т. е. «ctx2 = Moderngl.create_context(shared=ctx1)»)? В некотором коде, пытающемся решить эту проблему, мне удалось создать несколько окон glfw с общим контекстом ModernGL и общей программой шейдера, но я могу визуализировать только белый треугольник, а треугольники не красные; что заставляет меня думать, что, возможно, такое направление неправильное.
Подробнее здесь: https://stackoverflow.com/questions/792 ... fw-windows