import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
# Rotation state
rotate_x = 0
rotate_y = 0
last_x, last_y = 0, 0
dragging = False
def draw_axes():
"""Draw the X, Y, Z axes in 3D space."""
glBegin(GL_LINES)
# X axis (red)
glColor3f(1.0, 0.0, 0.0) # Red for X
glVertex3f(0.0, 0.0, 0.0)
glVertex3f(1.0, 0.0, 0.0)
# Y axis (green)
glColor3f(0.0, 1.0, 0.0) # Green for Y
glVertex3f(0.0, 0.0, 0.0)
glVertex3f(0.0, 1.0, 0.0)
# Z axis (blue)
glColor3f(0.0, 0.0, 1.0) # Blue for Z
glVertex3f(0.0, 0.0, 0.0)
glVertex3f(0.0, 0.0, 1.0)
glEnd()
def setup_openGL(width, height):
"""Set up the OpenGL context, perspective, and viewport."""
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
# Set perspective view
gluPerspective(45, float(width) / float(height), 0.1, 50.0)
glTranslatef(0.0, 0.0, -10) # Move camera back to view the axes
# Enable depth testing for proper 3D rendering
glEnable(GL_DEPTH_TEST)
# Clear the screen to black background
glClearColor(0.0, 0.0, 0.0, 1.0) # Black background
print("OpenGL setup completed.")
def rotate_view(dx, dy):
"""Update the rotation angles based on mouse movement."""
global rotate_x, rotate_y
rotate_x += dy * 0.5 # Scale the rotation speed
rotate_y += dx * 0.5
print(f"Rotate X: {rotate_x}, Rotate Y: {rotate_y}")
def main():
global last_x, last_y, rotate_x, rotate_y, dragging
# Initialize Pygame
pygame.init()
# Set up the display window with OpenGL
width, height = 800, 600
pygame.display.set_mode((width, height), DOUBLEBUF | OPENGL)
# Set up OpenGL settings
setup_openGL(width, height)
# Main render loop
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == MOUSEBUTTONDOWN:
# Start dragging when mouse button is pressed
if event.button == 1: # Left mouse button
dragging = True
last_x, last_y = event.pos
elif event.type == MOUSEBUTTONUP:
# Stop dragging when mouse button is released
if event.button == 1: # Left mouse button
dragging = False
elif event.type == MOUSEMOTION:
if dragging:
dx, dy = event.pos[0] - last_x, event.pos[1] - last_y
rotate_view(dx, dy) # Update rotation angles
last_x, last_y = event.pos
# Clear the screen and prepare for drawing
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Reset the transformation matrix and apply the rotation
glLoadIdentity() # Reset the matrix
glTranslatef(0.0, 0.0, -10) # Move the camera back further
glRotatef(rotate_x, 1, 0, 0) # Rotate around X axis
glRotatef(rotate_y, 0, 1, 0) # Rotate around Y axis
# Draw the axes
draw_axes()
# Swap buffers to display the scene
pygame.display.flip()
# Control the frame rate (optional)
pygame.time.wait(10)
# Quit Pygame
pygame.quit()
if __name__ == "__main__":
main()