Make a python script using moderngl that renders a simple cube with depth shadering,…
- User
Make a python script using moderngl that renders a simple cube with depth shadering, allow me to orbit cube to view it by dragging mouse.
- Assistant
Make a python script using moderngl that renders a simple cube with depth shadering, allow me to orbit cube to view it by dragging mouse.
Here's a Python script using moderngl and moderngl_window that renders a simple cube with depth shading. The script allows you to orbit around the cube by dragging the mouse. The cube is shaded based on depth, and you can rotate the view interactively.
import moderngl
import moderngl_window
from moderngl_window import geometry
from pyrr import Matrix44, Vector3
class CubeApp(moderngl_window.WindowConfig):
title = "Cube with Depth Shading"
window_size = (800, 600)
aspect_ratio = 800 / 600
resource_dir = '.'
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Create cube geometry
self.cube = geometry.cube()
# Load shaders
self.prog = self.ctx.program(
vertex_shader='''
#version 330 core
in vec3 in_position;
in vec3 in_normal;
uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
out vec3 frag_normal;
out vec3 frag_position;
void main() {
gl_Position = proj * view * model * vec4(in_position, 1.0);
frag_normal = mat3(transpose(inverse(model))) * in_normal;
frag_position = vec3(model * vec4(in_position, 1.0));
}
''',
fragment_shader='''
#version 330 core
in vec3 frag_normal;
in vec3 frag_position;
out vec4 color;
void main() {
// Simple depth-based shading
float depth = gl_FragCoord.z / gl_FragCoord.w;
color = vec4(vec3(depth), 1.0);
}
'''
)
# Set up transformations
self.model = Matrix44.identity(dtype='f4')
self.view = Matrix44.look_at(
eye=Vector3([0.0, 0.0, 5.0]),
target=Vector3([0.0, 0.0, 0.0]),
up=Vector3([0.0, 1.0, 0.0]),
dtype='f4'
)
self.projection = Matrix44.perspective_projection(
fovy=60.0,
aspect=self.window_size[0] / self.window_size[1],
near=0.1,
far=100.0,
dtype='f4'
)
# Set uniform variables
self.prog['model'].write(self.model)
self.prog['view'].write(self.view)
self.prog['proj'].write(self.projection)
# Enable depth test
self.ctx.enable(moderngl.DEPTH_TEST)
# Mouse variables
self.mouse_button_down = False
self.rotation = Matrix44.identity(dtype='f4')
def render(self, time, frame_time):
self.ctx.clear(0.1, 0.1, 0.1, 1.0)
self.ctx.enable_only(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
# Apply rotation
model = self.rotation * self.model
self.prog['model'].write(model)
# Render cube
self.cube.render(self.prog)
def mouse_drag_event(self, x, y, dx, dy):
# Update rotation based on mouse movement
if self.mouse_button_down:
# Calculate rotation angles
delta_x = dx * 0.01
delta_y = dy * 0.01
rot_x = Matrix44.from_x_rotation(delta_y)
rot_y = Matrix44.from_y_rotation(delta_x)
self.rotation = rot_x * rot_y * self.rotation
def mouse_press_event(self, x, y, button):
# Mouse button pressed
self.mouse_button_down = True
def mouse_release_event(self, x, y, button):
# Mouse button released
self.mouse_button_down = False
def resize(self, width, height):
self.projection = Matrix44.perspective_projection(
fovy=60.0,
aspect=width / height,
near=0.1,
far=100.0,
dtype='f4'
)
self.prog['proj'].write(self.projection)
if __name__ == '__main__':
moderngl_window.run_window_config(CubeApp)
Explanation:
Imports:
moderngl: Provides Modern OpenGL functionality.moderngl_window: Handles window creation and event management.geometry: Used to create basic geometric shapes like the cube.pyrr: A library for matrix and vector operations, similar to GLM.CubeApp Class:
moderngl_window.WindowConfig to create a windowed application.Initialization (__init__):
geometry.cube().gl_FragCoord.z.Rendering (render):
Mouse Interaction:
mouse_drag_event: Called when the mouse is dragged.
dx, dy).mouse_press_event and mouse_release_event: Track the mouse button state.Resize Handling (resize):
Instructions to Run the Script:
Install Dependencies:
Make sure you have moderngl, moderngl_window, and pyrr installed.
You can install them using pip:
pip install moderngl moderngl_window pyrr
Run the Script:
Save the script to a file, e.g., cube_app.py.
Run the script using Python:
python cube_app.py
Interact with the Cube:
Note:
cube() function from moderngl_window.geometry to create the cube geometry.gl_FragCoord.z).ctx.enable_only function ensures that only depth testing and face culling are enabled during rendering.Feel free to modify the shaders or add more features to the script to suit your needs!
Not yet included in a published release.