Create a land mesh and ocean mesh in python opengl with parallel lighting
- User
Create a land mesh and ocean mesh in python opengl with parallel lighting
- Assistant
Create a land mesh and ocean mesh in python opengl with parallel lighting
Certainly! Below is a comprehensive example of how to create a land mesh and an ocean mesh using Python with OpenGL, incorporating parallel (directional) lighting. This example utilizes PyOpenGL for OpenGL bindings, GLFW for window and context management, and Pyrr for matrix operations.
First, ensure you have the necessary Python packages installed. You can install them using pip:
pip install PyOpenGL PyOpenGL_accelerate glfw numpy pyrr
import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy as np
import sys
from pyrr import Matrix44, Vector3
# Vertex Shader
vertex_shader = """
#version 330 core
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 normal;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
out vec3 FragPos;
out vec3 Normal;
void main()
{
FragPos = vec3(model * vec4(position, 1.0));
Normal = mat3(transpose(inverse(model))) * normal;
gl_Position = projection * view * vec4(FragPos, 1.0);
}
"""
# Fragment Shader
fragment_shader = """
#version 330 core
in vec3 FragPos;
in vec3 Normal;
out vec4 color;
uniform vec3 lightDir; // Directional light direction
uniform vec3 lightColor; // Light color
uniform vec3 objectColor; // Object color
void main()
{
// Normalize vectors
vec3 norm = normalize(Normal);
vec3 lightDirNorm = normalize(-lightDir); // Invert light direction for calculations
// Diffuse shading
float diff = max(dot(norm, lightDirNorm), 0.0);
vec3 diffuse = diff * lightColor;
// Final color
vec3 result = diffuse * objectColor;
color = vec4(result, 1.0);
}
"""
def create_grid(size=10, divisions=100, y_level=0.0, is_ocean=False):
"""
Creates a grid mesh.
Parameters:
size (float): The total size of the grid.
divisions (int): Number of subdivisions.
y_level (float): The Y coordinate for all vertices (height).
is_ocean (bool): Flag to determine if the mesh is ocean.
Returns:
vertices (np.ndarray): Vertex positions.
normals (np.ndarray): Vertex normals.
indices (np.ndarray): Indices for drawing.
"""
vertices = []
normals = []
indices = []
step = size / divisions
half = size / 2
for i in range(divisions + 1):
for j in range(divisions + 1):
x = -half + j * step
z = -half + i * step
y = y_level
vertices.extend([x, y, z])
if is_ocean:
normals.extend([0.0, 1.0, 0.0]) # Ocean normals pointing up
else:
normals.extend([0.0, 1.0, 0.0]) # Flat land normals
for i in range(divisions):
for j in range(divisions):
start = i * (divisions + 1) + j
indices.extend([
start, start + divisions + 1, start + 1,
start + 1, start + divisions + 1, start + divisions + 2
])
return (
np.array(vertices, dtype=np.float32),
np.array(normals, dtype=np.float32),
np.array(indices, dtype=np.uint32)
)
def initialize_window():
"""
Initializes GLFW window.
Returns:
window: The created GLFW window.
"""
if not glfw.init():
print("Failed to initialize GLFW")
sys.exit()
# Configure GLFW
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
# Create window
window = glfw.create_window(800, 600, "Land and Ocean Mesh with Parallel Lighting", None, None)
if not window:
glfw.terminate()
print("Failed to create GLFW window")
sys.exit()
glfw.make_context_current(window)
return window
def compile_shaders():
"""
Compiles the vertex and fragment shaders into a shader program.
Returns:
shader (int): The compiled shader program ID.
"""
shader = OpenGL.GL.shaders.compileProgram(
OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)
)
return shader
def setup_mesh(vertices, normals, indices):
"""
Sets up the VAO, VBOs, and EBO for a mesh.
Parameters:
vertices (np.ndarray): Vertex positions.
normals (np.ndarray): Vertex normals.
indices (np.ndarray): Indices for drawing.
Returns:
VAO (int): Vertex Array Object ID.
VBOs (list): List of Vertex Buffer Object IDs.
EBO (int): Element Buffer Object ID.
"""
VAO = glGenVertexArrays(1)
VBOs = glGenBuffers(2)
EBO = glGenBuffers(1)
glBindVertexArray(VAO)
# Position VBO
glBindBuffer(GL_ARRAY_BUFFER, VBOs[0])
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
glEnableVertexAttribArray(0) # layout(location = 0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
# Normal VBO
glBindBuffer(GL_ARRAY_BUFFER, VBOs[1])
glBufferData(GL_ARRAY_BUFFER, normals.nbytes, normals, GL_STATIC_DRAW)
glEnableVertexAttribArray(1) # layout(location = 1)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None)
# EBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)
glBindVertexArray(0)
return VAO, VBOs, EBO
def main():
# Initialize Window
window = initialize_window()
# Compile Shaders
shader = compile_shaders()
# Create Land Mesh
land_vertices, land_normals, land_indices = create_grid(size=10, divisions=100, y_level=0.0, is_ocean=False)
land_VAO, land_VBOs, land_EBO = setup_mesh(land_vertices, land_normals, land_indices)
# Create Ocean Mesh
ocean_vertices, ocean_normals, ocean_indices = create_grid(size=10, divisions=100, y_level=-0.5, is_ocean=True)
ocean_VAO, ocean_VBOs, ocean_EBO = setup_mesh(ocean_vertices, ocean_normals, ocean_indices)
# Enable Depth Testing
glEnable(GL_DEPTH_TEST)
# Setup Camera
camera_pos = Vector3([0.0, 5.0, 10.0])
camera_target = Vector3([0.0, 0.0, 0.0])
camera_up = Vector3([0.0, 1.0, 0.0])
view = Matrix44.look_at(
eye=camera_pos,
target=camera_target,
up=camera_up
)
projection = Matrix44.perspective_projection(
fovy=45.0,
aspect=800/600,
near=0.1,
far=100.0
)
# Use Shader Program
glUseProgram(shader)
# Get Uniform Locations
model_loc = glGetUniformLocation(shader, "model")
view_loc = glGetUniformLocation(shader, "view")
proj_loc = glGetUniformLocation(shader, "projection")
light_dir_loc = glGetUniformLocation(shader, "lightDir")
light_color_loc = glGetUniformLocation(shader, "lightColor")
object_color_loc = glGetUniformLocation(shader, "objectColor")
# Set View and Projection Matrices
glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)
glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
# Define Light Properties
light_direction = np.array([0.0, -1.0, -1.0], dtype=np.float32)
light_direction /= np.linalg.norm(light_direction) # Normalize
light_color = np.array([1.0, 1.0, 1.0], dtype=np.float32) # White light
glUniform3fv(light_dir_loc, 1, light_direction)
glUniform3fv(light_color_loc, 1, light_color)
# Main Rendering Loop
while not glfw.window_should_close(window):
glfw.poll_events()
# Clear Buffers
glClearColor(0.5, 0.7, 1.0, 1.0) # Sky blue background
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Draw Land
glUniformMatrix4fv(model_loc, 1, GL_FALSE, Matrix44.identity())
object_color_land = np.array([0.3, 0.8, 0.3], dtype=np.float32) # Green
glUniform3fv(object_color_loc, 1, object_color_land)
glBindVertexArray(land_VAO)
glDrawElements(GL_TRIANGLES, len(land_indices), GL_UNSIGNED_INT, None)
# Draw Ocean
model_ocean = Matrix44.identity()
glUniformMatrix4fv(model_loc, 1, GL_FALSE, model_ocean)
object_color_ocean = np.array([0.0, 0.3, 0.8], dtype=np.float32) # Blue
glUniform3fv(object_color_loc, 1, object_color_ocean)
glBindVertexArray(ocean_VAO)
glDrawElements(GL_TRIANGLES, len(ocean_indices), GL_UNSIGNED_INT, None)
glBindVertexArray(0)
# Swap Buffers
glfw.swap_buffers(window)
# Cleanup
glDeleteVertexArrays(1, [land_VAO])
glDeleteBuffers(2, land_VBOs)
glDeleteBuffers(1, [land_EBO])
glDeleteVertexArrays(1, [ocean_VAO])
glDeleteBuffers(2, ocean_VBOs)
glDeleteBuffers(1, [ocean_EBO])
glDeleteProgram(shader)
glfw.terminate()
if __name__ == "__main__":
main()
Shaders:
Mesh Creation:
create_grid function generates a flat grid mesh, which serves as the basis for both land and ocean. The y_level parameter positions the mesh vertically, allowing the ocean to be slightly below the land.OpenGL Setup:
Camera and Projection:
pyrr to create view and projection matrices. The camera is positioned to have a good view of both the land and ocean meshes.Lighting:
Rendering Loop:
Cleanup:
Simply run the Python script in your environment:
python your_script_name.py
A window should appear displaying a flat green grid (land) and a blue grid slightly below it (ocean), both illuminated by a directional light simulating parallel lighting.
This example provides a foundational approach to creating land and ocean meshes with parallel lighting in Python using OpenGL. It sets the stage for more complex and realistic rendering by allowing for further enhancements such as dynamic terrains, advanced lighting, and interactivity.
Not yet included in a published release.