try:
with open(filename, 'r') as f:
for line in f:
if line.startswith('newmtl'):
parts = line.strip().split(None, 1)
if len(parts) > 1:
current_mtl = parts[1]
materials[current_mtl] = {
'Kd': [1.0, 1.0, 1.0], # Diffuse color default to white
'map_Kd': None # Texture map
}
elif line.startswith('Kd') and current_mtl:
parts = line.strip().split()
materials[current_mtl]['Kd'] = list(map(float, parts[1:4]))
elif line.startswith('map_Kd') and current_mtl:
parts = line.strip().split(None, 1)
if len(parts) > 1:
materials[current_mtl]['map_Kd'] = parts[1]
except IOError:
print(f"Error: Unable to open {filename}")
sys.exit(1)
return materials
try:
with open(filename, 'r') as f:
for line in f:
if line.startswith('mtllib'):
parts = line.strip().split(None, 1)
if len(parts) > 1:
mtl_files.append(parts[1])
elif line.startswith('v '):
parts = line.strip().split()
vertex = list(map(float, parts[1:4]))
vertices.append(vertex)
elif line.startswith('vt '):
parts = line.strip().split()
tex_coord = list(map(float, parts[1:3]))
tex_coords.append(tex_coord)
elif line.startswith('vn '):
parts = line.strip().split()
normal = list(map(float, parts[1:4]))
normals.append(normal)
elif line.startswith('usemtl'):
parts = line.strip().split(None, 1)
if len(parts) > 1:
current_mtl = parts[1]
elif line.startswith('f '):
parts = line.strip().split()
face = []
for part in parts[1:]:
indices = part.split('/')
v_idx = int(indices[0]) - 1
vt_idx = int(indices[1]) - 1 if len(indices) > 1 and indices[1] else None
vn_idx = int(indices[2]) - 1 if len(indices) > 2 and indices[2] else None
face.append({'v': v_idx, 'vt': vt_idx, 'vn': vn_idx})
face.append(current_mtl) # Append material to face
faces.append(face)
if not vertices or not faces:
print(f"Error: {filename} contains no vertices or faces.")
sys.exit(1)
print(f"Loaded {len(vertices)} vertices and {len(faces)} faces from {filename}")
except IOError:
print(f"Error: Unable to open {filename}")
sys.exit(1)
# Load materials from the material files
for mtl_file in mtl_files:
mtl_data = load_mtl(mtl_file)
materials.update(mtl_data)
return {
'vertices': np.array(vertices, dtype='float32'),
'tex_coords': np.array(tex_coords, dtype='float32'),
'normals': np.array(normals, dtype='float32'),
'faces': faces,
'materials': materials
}
Function to load textures from materials
def load_textures(materials):
texture_ids = {}
for mtl_name, mtl_props in materials.items():
texture_file = mtl_props.get('map_Kd')
if texture_file:
texture_id = load_texture(texture_file)
texture_ids[mtl_name] = texture_id
else:
texture_ids[mtl_name] = None
return texture_ids
Function to create a rotation matrix given an axis and angle
def rotation_matrix(axis, angle):
"""
Create a rotation matrix given an axis and angle.
"""
axis = axis / np.linalg.norm(axis)
cos_a = np.cos(angle)
sin_a = np.sin(angle)
one_minus_cos = 1.0 - cos_a
x, y, z = axis
r = np.array([
[cos_a + x * x * one_minus_cos,
x * y * one_minus_cos - z * sin_a,
x * z * one_minus_cos + y * sin_a],
[y * x * one_minus_cos + z * sin_a,
cos_a + y * y * one_minus_cos,
y * z * one_minus_cos - x * sin_a],
[z * x * one_minus_cos - y * sin_a,
z * y * one_minus_cos + x * sin_a,
cos_a + z * z * one_minus_cos]
], dtype='float32')
return r
Camera class for handling position and orientation
class Projectile:
def init(self, position, direction, speed=1.0):
self.position = np.array(position, dtype='float32')
self.direction = np.array(direction, dtype='float32')
self.speed = speed
self.alive = True # Used for removing projectile when out of range or time
code
def update(self, delta_time):
self.position += self.direction * self.speed * delta_time
def draw(self):
glPushMatrix()
glTranslatef(self.position[0], self.position[1], self.position[2])
glColor3f(1.0, 1.0, 0.0) # Yellow color for projectiles
draw_sphere(0.2, 8, 8) # Use the new draw_sphere function
glPopMatrix()
Initialize GLFW and create a window
if not glfw.init():
print("Failed to initialize GLFW")
sys.exit()
window = glfw.create_window(800, 600, "3D Ship Viewer", None, None)
if not window:
print("Failed to create GLFW window")
glfw.terminate()
sys.exit()
while not glfw.window_should_close(window):
# Calculate delta time
current_time = glfw.get_time()
delta_time = current_time - last_time
last_time = current_time
code
# Handle input
# Rotation
if glfw.KEY_UP in keys and keys[glfw.KEY_UP]:
# Pitch up
angle = np.radians(rotate_speed)
rot_axis = ship_rotation_matrix @ np.array([1.0, 0.0, 0.0]) # Ship's local X-axis
rotation = rotation_matrix(axis=rot_axis, angle=angle)
ship_rotation_matrix = ship_rotation_matrix @ rotation
if glfw.KEY_DOWN in keys and keys[glfw.KEY_DOWN]:
# Pitch down
angle = -np.radians(rotate_speed)
rot_axis = ship_rotation_matrix @ np.array([1.0, 0.0, 0.0]) # Ship's local X-axis
rotation = rotation_matrix(axis=rot_axis, angle=angle)
ship_rotation_matrix = ship_rotation_matrix @ rotation
if glfw.KEY_LEFT in keys and keys[glfw.KEY_LEFT]:
# Roll left
angle = -np.radians(rotate_speed)
rot_axis = ship_rotation_matrix @ np.array([0.0, 0.0, 1.0]) # Ship's local Z-axis
rotation = rotation_matrix(axis=rot_axis, angle=angle)
ship_rotation_matrix = ship_rotation_matrix @ rotation
if glfw.KEY_RIGHT in keys and keys[glfw.KEY_RIGHT]:
# Roll right
angle = np.radians(rotate_speed)
rot_axis = ship_rotation_matrix @ np.array([0.0, 0.0, 1.0]) # Ship's local Z-axis
rotation = rotation_matrix(axis=rot_axis, angle=angle)
ship_rotation_matrix = ship_rotation_matrix @ rotation
if glfw.KEY_Q in keys and keys[glfw.KEY_Q]:
# Yaw left
angle = np.radians(rotate_speed)
rot_axis = ship_rotation_matrix @ np.array([0.0, 1.0, 0.0]) # Ship's local Y-axis
rotation = rotation_matrix(axis=rot_axis, angle=angle)
ship_rotation_matrix = ship_rotation_matrix @ rotation
if glfw.KEY_E in keys and keys[glfw.KEY_E]:
# Yaw right
angle = -np.radians(rotate_speed)
rot_axis = ship_rotation_matrix @ np.array([0.0, 1.0, 0.0]) # Ship's local Y-axis
rotation = rotation_matrix(axis=rot_axis, angle=angle)
ship_rotation_matrix = ship_rotation_matrix @ rotation
# Movement
# Compute ship's forward, right, and up directions
forward_direction = ship_rotation_matrix @ np.array([0.0, 0.0, 1.0])
right_direction = ship_rotation_matrix @ np.array([1.0, 0.0, 0.0])
# Apply acceleration
if glfw.KEY_W in keys and keys[glfw.KEY_W]:
ship_vel += acceleration * forward_direction * delta_time
if glfw.KEY_S in keys and keys[glfw.KEY_S]:
ship_vel -= acceleration * forward_direction * delta_time
if glfw.KEY_A in keys and keys[glfw.KEY_A]:
# Strafe left
ship_vel -= acceleration * right_direction * delta_time
if glfw.KEY_D in keys and keys[glfw.KEY_D]:
# Strafe right
ship_vel += acceleration * right_direction * delta_time
# Apply turbulence
turbulence = turbulence_intensity * (np.random.rand(3) - 0.5) * delta_time
ship_vel += turbulence
# Limit speed
speed = np.linalg.norm(ship_vel)
if speed > max_speed:
ship_vel = (ship_vel / speed) * max_speed
# Apply friction
ship_vel -= ship_vel * friction * delta_time
# Update ship position
ship_pos += ship_vel * delta_time
# Shooting
if glfw.KEY_SPACE in keys and keys[glfw.KEY_SPACE]:
# Fire projectile
# Reset the key state to prevent continuous firing
keys[glfw.KEY_SPACE] = False
# Create a new projectile
projectile_speed = 50.0
projectile = Projectile(
position=ship_pos.copy(),
direction=forward_direction.copy(),
speed=projectile_speed
)
projectiles.append(projectile)
# Update projectiles
for projectile in projectiles[:]:
projectile.update(delta_time)
# Remove projectile if it's too far away
if np.linalg.norm(projectile.position - ship_pos) > 500:
projectiles.remove(projectile)
# Update camera based on ship's new position and orientation
camera.update(ship_position=ship_pos, ship_rotation_matrix=ship_rotation_matrix)
# Clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
# Apply camera view
camera.apply_view()
# Draw stars
glDisable(GL_LIGHTING) # Disable lighting for stars
glPointSize(2.0)
glColor3f(1.0, 1.0, 1.0)
glBegin(GL_POINTS)
for star in star_positions:
glVertex3f(star[0], star[1], star[2])
glEnd()
glEnable(GL_LIGHTING) # Re-enable lighting
# Draw projectiles
glDisable(GL_TEXTURE_2D) # Disable texturing for projectiles
for projectile in projectiles:
projectile.draw()
glEnable(GL_TEXTURE_2D)
# Convert 3x3 rotation matrix to 4x4
ship_rotation_matrix_4x4 = np.identity(4, dtype='float32')
ship_rotation_matrix_4x4[:3, :3] = ship_rotation_matrix
# Draw ship
glPushMatrix()
glTranslatef(ship_pos[0], ship_pos[1], ship_pos[2])
# Apply ship rotations using the 4x4 matrix
glMultMatrixf(ship_rotation_matrix_4x4.T)
current_mtl = None
glBegin(GL_TRIANGLES)
for face in ship_faces:
mtl_name = face[-1] # Last element is the material name
if mtl_name != current_mtl:
glEnd()
current_mtl = mtl_name
mtl_props = materials.get(mtl_name, {})
texture_id = texture_ids.get(mtl_name)
if texture_id:
glBindTexture(GL_TEXTURE_2D, texture_id)
glEnable(GL_TEXTURE_2D)
glColor3f(1.0, 1.0, 1.0)
else:
glDisable(GL_TEXTURE_2D)
Kd = mtl_props.get('Kd', [1.0, 1.0, 1.0])
glColor3fv(Kd)
glBegin(GL_TRIANGLES)
for vertex_info in face[:-1]: # Exclude the material name
v_idx = vertex_info['v']
vt_idx = vertex_info['vt']
vn_idx = vertex_info['vn']
if vn_idx is not None and len(normals) > vn_idx:
glNormal3fv(normals[vn_idx])
else:
# If normals are not provided, compute or use a default
glNormal3f(0.0, 0.0, 1.0)
if vt_idx is not None and len(tex_coords) > vt_idx:
glTexCoord2fv(tex_coords[vt_idx])
glVertex3fv(ship_vertices[v_idx])
glEnd()
glPopMatrix()
# Swap buffers and poll events
glfw.swap_buffers(window)
glfw.poll_events()
Terminate GLFW
glfw.terminate()
You're correct in observing that the current rotation implementation leads to interference and unexpected behavior when applying successive pitch and roll rotations. This issue typically arises due to the complexities of managing Euler angles or accumulating rotation matrices, which can result in problems like gimbal lock and non-orthogonal rotation matrices over time.
Understanding the Issue
In your current setup:
Accumulating Rotations: Each key press generates a new rotation matrix based on the current orientation and multiplies it with the existing ship_rotation_matrix. Over time, these compounded rotations can lead to numerical inaccuracies and unexpected orientation changes.
Euler Angle Limitations: Using Euler angles (pitch, yaw, roll) can lead to gimbal lock, where two rotation axes align and cause a loss of one degree of rotational freedom.
Solution: Using Quaternions for Rotation
Quaternions offer a robust way to handle 3D rotations without suffering from gimbal lock. They provide smooth and continuous rotations and maintain the orthogonality of rotation matrices. Here's how you can integrate quaternions into your application:
Implement Quaternion Operations:
Quaternion Representation: A quaternion can be represented as ( q = w + xi + yj + zk ), where ( w ) is the scalar part, and ( (x, y, z) ) is the vector part.
Normalization: Ensure quaternions remain normalized to represent valid rotations.
Multiplication: Combine rotations by quaternion multiplication.
Conversion to Rotation Matrix: Convert the quaternion to a rotation matrix for OpenGL transformations.
Integrate with Your Current Code:
Initialize a Quaternion: Replace the ship_rotation_matrix with a quaternion representing the ship's orientation.
Apply Rotations via Quaternions: Update the ship's orientation by creating incremental rotation quaternions based on user input and multiplying them with the current orientation quaternion.
Update the Rotation Matrix: Convert the updated quaternion to a rotation matrix each frame for rendering.
Step-by-Step Implementation
Let's walk through the necessary changes and additions to your existing code.
1. Define Quaternion Utilities
First, add functions to handle quaternion operations.
# Initialize ship orientation as a quaternion (w, x, y, z)
ship_orientation = np.array([1.0, 0.0, 0.0, 0.0], dtype='float32') # No rotation initially
Update Rotations:
Modify the rotation input handling to use quaternions.
python
# Handle input
if glfw.KEY_UP in keys and keys[glfw.KEY_UP]:
# Pitch up
angle = np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [1.0, 0.0, 0.0]) # Ship's local X-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_DOWN in keys and keys[glfw.KEY_DOWN]:
# Pitch down
angle = -np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [1.0, 0.0, 0.0]) # Ship's local X-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_LEFT in keys and keys[glfw.KEY_LEFT]:
# Roll left
angle = -np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 0.0, 1.0]) # Ship's local Z-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_RIGHT in keys and keys[glfw.KEY_RIGHT]:
# Roll right
angle = np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 0.0, 1.0]) # Ship's local Z-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_Q in keys and keys[glfw.KEY_Q]:
# Yaw left
angle = np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 1.0, 0.0]) # Ship's local Y-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_E in keys and keys[glfw.KEY_E]:
# Yaw right
angle = -np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 1.0, 0.0]) # Ship's local Y-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
Helper Function to Get Rotated Axes:
Add a helper function to obtain the ship's local axes based on its current orientation.
python
def ship_orientation_rotation_axis(quaternion, local_axis):
"""
Rotate a local axis vector by the ship's current orientation quaternion.
"""
# Convert the axis to a pure quaternion
q_axis = np.array([0.0, *local_axis], dtype='float32')
# Compute the rotated axis: q * v * q_conj
q_conj = np.array([quaternion[0], -quaternion[1], -quaternion[2], -quaternion[3]], dtype='float32')
temp = quaternion_multiply(quaternion, q_axis)
rotated = quaternion_multiply(temp, q_conj)
return rotated[1:] # Return the vector part
4. Update the Rotation Matrix for Rendering
Convert the updated quaternion to a rotation matrix each frame.
If projectiles are affected by the ship's rotation (fire direction), ensure their initial direction aligns with the ship's current orientation.
Modify Projectile Creation:
python
if glfw.KEY_SPACE in keys and keys[glfw.KEY_SPACE]:
# Fire projectile
keys[glfw.KEY_SPACE] = False
# Fire direction based on ship's forward direction
forward_direction = quaternion_rotate_vector(ship_orientation, np.array([0.0, 0.0, 1.0]))
# Create a new projectile
projectile_speed = 50.0
projectile = Projectile(
position=ship_pos.copy(),
direction=forward_direction.copy(),
speed=projectile_speed
)
projectiles.append(projectile)
8. (Optional) Implement Smooth Rotation
To enhance the user experience, consider implementing smooth rotation by applying smaller incremental rotations over multiple frames rather than discrete steps per key press.
Final Thoughts and Benefits
By integrating quaternions into your rotation handling:
Avoid Gimbal Lock: Quaternions maintain rotational freedom without the risk of gimbal lock.
Smooth Rotations: Quaternions provide smooth interpolation between orientations.
Numerical Stability: Normalizing quaternions after each operation ensures the rotation remains valid.
This approach should resolve the interference issues you’re experiencing with pitch and roll rotations, leading to more predictable and stable ship orientation behavior.
Complete Updated Code Snippets
For clarity, here are all the updated code snippets integrated into your existing code structure.
# Initialize ship orientation as a quaternion (w, x, y, z)
ship_orientation = np.array([1.0, 0.0, 0.0, 0.0], dtype='float32') # No rotation initially
Update Rotation Handling in the Main Loop:
python
# Handle input
if glfw.KEY_UP in keys and keys[glfw.KEY_UP]:
# Pitch up
angle = np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [1.0, 0.0, 0.0]) # Ship's local X-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_DOWN in keys and keys[glfw.KEY_DOWN]:
# Pitch down
angle = -np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [1.0, 0.0, 0.0]) # Ship's local X-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_LEFT in keys and keys[glfw.KEY_LEFT]:
# Roll left
angle = -np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 0.0, 1.0]) # Ship's local Z-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_RIGHT in keys and keys[glfw.KEY_RIGHT]:
# Roll right
angle = np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 0.0, 1.0]) # Ship's local Z-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_Q in keys and keys[glfw.KEY_Q]:
# Yaw left
angle = np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 1.0, 0.0]) # Ship's local Y-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
if glfw.KEY_E in keys and keys[glfw.KEY_E]:
# Yaw right
angle = -np.radians(rotate_speed)
rot_axis = ship_orientation_rotation_axis(ship_orientation, [0.0, 1.0, 0.0]) # Ship's local Y-axis
delta_quat = quaternion_from_axis_angle(rot_axis, angle)
ship_orientation = quaternion_multiply(ship_orientation, delta_quat)
ship_orientation = quaternion_normalize(ship_orientation)
Convert Quaternion to Rotation Matrix for Rendering:
python
# Convert quaternion to rotation matrix
ship_rotation_matrix_4x4 = quaternion_to_rotation_matrix(ship_orientation)
# Draw ship
glPushMatrix()
glTranslatef(ship_pos[0], ship_pos[1], ship_pos[2])
# Apply ship rotations using the 4x4 matrix
glMultMatrixf(ship_rotation_matrix_4x4.T)
Update Camera's update Method:
python
class Camera:
def __init__(self, distance=15.0, height=5.0):
self.distance = distance
self.height = height
self.position = np.array([0.0, 0.0, 0.0])
self.target = np.array([0.0, 0.0, 0.0])
self.up = np.array([0.0, 1.0, 0.0])
def update(self, ship_position, ship_orientation_quat):
# Camera offset in local space (behind the ship)
camera_offset = np.array([0.0, self.height, -self.distance])
# Rotate the offset by the ship's orientation quaternion
camera_offset_world = quaternion_rotate_vector(ship_orientation_quat, camera_offset)
self.position = ship_position + camera_offset_world
self.target = ship_position
# Up vector transformed by ship's rotation
self.up = quaternion_rotate_vector(ship_orientation_quat, np.array([0.0, 1.0, 0.0]))
def apply_view(self):
gluLookAt(
self.position[0], self.position[1], self.position[2],
self.target[0], self.target[1], self.target[2],
self.up[0], self.up[1], self.up[2]
)
Update Camera Update Call in the Main Loop:
python
# Update camera based on ship's new position and orientation
camera.update(ship_position=ship_pos, ship_orientation_quat=ship_orientation)
Modify Projectile Firing to Use Quaternion Rotations:
python
if glfw.KEY_SPACE in keys and keys[glfw.KEY_SPACE]:
# Fire projectile
keys[glfw.KEY_SPACE] = False
# Fire direction based on ship's forward direction
forward_direction = quaternion_rotate_vector(ship_orientation, np.array([0.0, 0.0, 1.0]))
# Normalize direction
forward_direction = forward_direction / np.linalg.norm(forward_direction)
# Create a new projectile
projectile_speed = 50.0
projectile = Projectile(
position=ship_pos.copy(),
direction=forward_direction.copy(),
speed=projectile_speed
)
projectiles.append(projectile)
Conclusion
By integrating quaternions into your rotation system, you can achieve smooth and interference-free rotations for your 3D ship, enhancing the overall stability and responsiveness of the controls. This approach not only resolves the immediate issues but also sets a solid foundation for more complex rotational behaviors in the future.
If you encounter any further challenges or need additional enhancements, feel free to ask!