Using pygame add 3d ball and realistic lighting, not use any other modules, provide full…
- User
Using pygame add 3d ball and realistic lighting, not use any other modules, provide full code, the lighting can be adjusted by user.
- Assistant
Creating a 3D-rendered sphere with realistic lighting in Pygame alone involves manually handling 3D projections and lighting calculations since Pygame is primarily a 2D library. Below is a complete Python script using Pygame that renders a 3D sphere with adjustable lighting. Users can move the light source using the arrow keys and adjust its elevation with the
WandSkeys.Features:
- 3D Sphere Rendering: The sphere is rendered by calculating the z-coordinate for each pixel that lies on the sphere's surface.
- Realistic Lighting: Uses diffuse shading based on the angle between the light direction and the sphere's surface normals.
- User-Controlled Lighting: Users can adjust the position of the light source using keyboard inputs.
Controls:
- Left/Right Arrow Keys: Move the light source left/right.
- Up/Down Arrow Keys: Move the light source forward/backward.
- W/S Keys: Move the light source up/down.
Complete Code:
import pygame import math import sys # Initialize Pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 SCREEN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("3D Sphere with Realistic Lighting") # Clock for controlling frame rate CLOCK = pygame.time.Clock() FPS = 30 # Sphere properties SPHERE_RADIUS = 200 SPHERE_CENTER = (WIDTH // 2, HEIGHT // 2 + 50) # Slightly lower to center vertically # Light properties # Initial light direction (unit vector) light_dir = [1, 1, -1] # Normalize the light direction length = math.sqrt(light_dir[0]**2 + light_dir[1]**2 + light_dir[2]**2) light_dir = [component / length for component in light_dir] # Light movement step LIGHT_STEP = 0.1 # Colors BACKGROUND_COLOR = (10, 10, 50) SPHERE_COLOR = (255, 165, 0) # Orange def normalize(v): length = math.sqrt(sum([coord ** 2 for coord in v])) if length == 0: return [0, 0, 0] return [coord / length for coord in v] def handle_input(): global light_dir for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() # Adjust light direction based on arrow keys and W/S keys # Using spherical coordinates for light direction adjustments if keys[pygame.K_LEFT]: # Rotate light direction to the left around Y axis angle = LIGHT_STEP new_x = light_dir[0] * math.cos(angle) - light_dir[2] * math.sin(angle) new_z = light_dir[0] * math.sin(angle) + light_dir[2] * math.cos(angle) light_dir[0], light_dir[2] = new_x, new_z if keys[pygame.K_RIGHT]: # Rotate light direction to the right around Y axis angle = -LIGHT_STEP new_x = light_dir[0] * math.cos(angle) - light_dir[2] * math.sin(angle) new_z = light_dir[0] * math.sin(angle) + light_dir[2] * math.cos(angle) light_dir[0], light_dir[2] = new_x, new_z if keys[pygame.K_UP]: # Rotate light direction up around X axis angle = LIGHT_STEP new_y = light_dir[1] * math.cos(angle) - light_dir[2] * math.sin(angle) new_z = light_dir[1] * math.sin(angle) + light_dir[2] * math.cos(angle) light_dir[1], light_dir[2] = new_y, new_z if keys[pygame.K_DOWN]: # Rotate light direction down around X axis angle = -LIGHT_STEP new_y = light_dir[1] * math.cos(angle) - light_dir[2] * math.sin(angle) new_z = light_dir[1] * math.sin(angle) + light_dir[2] * math.cos(angle) light_dir[1], light_dir[2] = new_y, new_z if keys[pygame.K_w]: # Rotate light direction up around Z axis angle = LIGHT_STEP new_x = light_dir[0] * math.cos(angle) - light_dir[1] * math.sin(angle) new_y = light_dir[0] * math.sin(angle) + light_dir[1] * math.cos(angle) light_dir[0], light_dir[1] = new_x, new_y if keys[pygame.K_s]: # Rotate light direction down around Z axis angle = -LIGHT_STEP new_x = light_dir[0] * math.cos(angle) - light_dir[1] * math.sin(angle) new_y = light_dir[0] * math.sin(angle) + light_dir[1] * math.cos(angle) light_dir[0], light_dir[1] = new_x, new_y # Normalize light direction after adjustments light_dir = normalize(light_dir) def draw_sphere(): # Draw the sphere pixel by pixel for y in range(SPHERE_CENTER[1] - SPHERE_RADIUS, SPHERE_CENTER[1] + SPHERE_RADIUS): dy = y - SPHERE_CENTER[1] for x in range(SPHERE_CENTER[0] - SPHERE_RADIUS, SPHERE_CENTER[0] + SPHERE_RADIUS): dx = x - SPHERE_CENTER[0] distance_sq = dx * dx + dy * dy if distance_sq <= SPHERE_RADIUS * SPHERE_RADIUS: # Calculate z coordinate on the sphere dz = math.sqrt(SPHERE_RADIUS * SPHERE_RADIUS - distance_sq) # Surface normal (assuming sphere is centered at origin) normal = [dx, dy, dz] normal = normalize(normal) # Dot product between normal and light direction dot = normal[0] * light_dir[0] + normal[1] * light_dir[1] + normal[2] * light_dir[2] dot = max(dot, 0) # Clamp to [0,1] # Calculate shading shading = dot # Apply shading to sphere color color = ( min(int(SPHERE_COLOR[0] * shading), 255), min(int(SPHERE_COLOR[1] * shading), 255), min(int(SPHERE_COLOR[2] * shading), 255), ) # Draw the pixel SCREEN.set_at((x, y), color) def main(): while True: handle_input() # Clear screen SCREEN.fill(BACKGROUND_COLOR) # Draw sphere with current lighting draw_sphere() # Optional: Draw light direction vector for visualization # You can uncomment the following lines to visualize light direction """ # Scale light direction for visualization light_visual_end = ( int(SPHERE_CENTER[0] + light_dir[0] * 100), int(SPHERE_CENTER[1] + light_dir[1] * 100) ) pygame.draw.line(SCREEN, (255, 255, 255), SPHERE_CENTER, light_visual_end, 2) pygame.draw.circle(SCREEN, (255, 255, 255), light_visual_end, 5) """ # Update the display pygame.display.flip() # Maintain frame rate CLOCK.tick(FPS) if __name__ == "__main__": main()Explanation of the Code:
-
Initialization:
- Pygame Setup: Initializes Pygame and sets up the display window with specified dimensions.
- Sphere Properties: Defines the sphere's radius and its center position on the screen.
- Lighting Properties: Sets the initial light direction as a normalized vector. The light direction can be adjusted using keyboard inputs.
-
Normalization Function:
normalize(v): Ensures that any vector used in calculations has a unit length, which is essential for accurate lighting computations.
-
Input Handling:
handle_input(): Processes user inputs to adjust the light direction. The arrow keys rotate the light around the Y and X axes, while theWandSkeys rotate it around the Z-axis. After each adjustment, the light direction vector is normalized to maintain consistent lighting behavior.
-
Sphere Rendering:
draw_sphere(): Iterates over a square bounding the sphere and determines if each pixel lies on the sphere's surface. For each such pixel:- Calculates the z-coordinate (
dz) using the sphere equation. - Determines the surface normal at that point.
- Computes the dot product between the normal and the light direction to obtain the shading factor.
- Applies the shading to the sphere's base color to achieve realistic lighting.
- Sets the pixel color accordingly.
- Calculates the z-coordinate (
-
Main Loop:
main(): Continuously handles user inputs, clears the screen, renders the sphere with the current lighting, and updates the display. The loop runs at a fixed frame rate to ensure smooth rendering.
-
Optional Visualization:
- The code includes commented-out lines that, when uncommented, visualize the light direction vector as a line and a circle. This can be helpful for debugging or understanding how the light direction affects the shading.
Running the Code:
-
Prerequisites:
- Ensure you have Python installed on your system.
- Install Pygame if you haven't already by running:
pip install pygame
-
Execution:
- Save the provided code to a file, for example,
3d_sphere.py. - Run the script using Python:
python 3d_sphere.py
- Save the provided code to a file, for example,
-
Interacting with the Sphere:
- Use the arrow keys to rotate the light source around the sphere.
- Press
WandSto adjust the light source's elevation. - Observe how the shading on the sphere changes in real-time based on the light's position.
Performance Considerations:
-
Rendering Speed: Since the sphere is rendered pixel-by-pixel, the performance might be limited, especially for larger spheres or higher resolutions. The provided code balances performance with visual quality, but for more complex 3D rendering, using specialized libraries like OpenGL with Pygame would be more efficient.
-
Optimizations: Various optimizations can be applied to improve rendering speed, such as:
- Caching Calculations: Precompute certain values that don't change between frames.
- Limiting the Redraw Area: Only update parts of the screen that change.
- Using Numpy Arrays: Leveraging Numpy for faster numerical computations (note: this would require using additional modules, which the user asked to avoid).
This script offers a fundamental example of 3D rendering and lighting in Pygame without external modules. It serves as a foundation that can be expanded upon for more complex projects involving 3D graphics.