Untitled

to run-> open terminal->python filename.py
 avatar
unknown
python
21 days ago
3.5 kB
9
Indexable
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from matplotlib.animation import FuncAnimation
import numpy as np

def rotate_x(points, angle):
    """Rotates points around the x-axis."""
    rad = np.radians(angle)
    rotation_matrix = np.array([[1, 0, 0],
                                [0, np.cos(rad), -np.sin(rad)],
                                [0, np.sin(rad), np.cos(rad)]])
    return np.dot(points, rotation_matrix.T)

def rotate_y(points, angle):
    """Rotates points around the y-axis."""
    rad = np.radians(angle)
    rotation_matrix = np.array([[np.cos(rad), 0, np.sin(rad)],
                                [0, 1, 0],
                                [-np.sin(rad), 0, np.cos(rad)]])
    return np.dot(points, rotation_matrix.T)

def compute_normal(polygon, vertices):
    """Computes the normal of a polygon using the cross product."""
    v1 = vertices[polygon[1]] - vertices[polygon[0]]
    v2 = vertices[polygon[2]] - vertices[polygon[0]]
    normal = np.cross(v1, v2)
    return normal

def plot_colored_wireframe(vertices, polygons, ax, rotation_x=0, rotation_y=0):
    """Plots the 3D wireframe model with fixed colors for hidden surface removal."""
    
    # Rotate the vertices
    vertices = rotate_x(vertices, rotation_x)
    vertices = rotate_y(vertices, rotation_y)

    # Define the view vector (camera looking along the -z axis)
    view_vector = np.array([0, 0, -1])
    
    # Compute normals and their dot product with the view vector
    polygon_data = []
    for i, polygon in enumerate(polygons):
        normal = compute_normal(polygon, vertices)
        dot_product = np.dot(normal, view_vector)
        polygon_data.append((i, polygon, dot_product))

    # Sort polygons by dot product (to render back-to-front)
    sorted_polygons = sorted(polygon_data, key=lambda x: x[2], reverse=True)

    # Clear the axes before re-rendering
    ax.cla()

    # Define fixed colors for each polygon
    fixed_colors = plt.cm.Set3(np.linspace(0, 1, len(polygons)))  # Brighter color palette

    # Plot each polygon with its fixed color
    for i, polygon, _ in sorted_polygons:
        polygon_vertices = vertices[polygon]
        x, y, z = zip(*polygon_vertices)
        ax.plot(x + (x[0],), y + (y[0],), z + (z[0],), color='black')  # Plot edges (wireframe)
        ax.add_collection3d(Poly3DCollection([polygon_vertices], color=fixed_colors[i], alpha=1.0))  # Fully opaque

    # Set aspect ratio and labels
    ax.set_box_aspect([1, 1, 1])  # Equal scaling for x, y, z axes
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_title('3D Wireframe Model with animation')

# Define vertices and polygons (example: cube)
vertices = np.array([
    [0, 0, 0],  # 0
    [1, 0, 0],  # 1
    [1, 1, 0],  # 2
    [0, 1, 0],  # 3
    [0, 0, 1],  # 4
    [1, 0, 1],  # 5
    [1, 1, 1],  # 6
    [0, 1, 1]   # 7
])

polygons = np.array([
    [0, 1, 2, 3],  # Front
    [4, 5, 6, 7],  # Back
    [0, 4, 5, 1],  # Right
    [2, 6, 7, 3],  # Left
    [0, 3, 7, 4],  # Top
    [1, 5, 6, 2]   # Bottom
])

# Create the 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Animation function
def update(frame):
    plot_colored_wireframe(vertices, polygons, ax, rotation_x=frame, rotation_y=frame)

# Create continuous animation
ani = FuncAnimation(fig, update, frames=np.arange(0, 360, 5), interval=50)

plt.show()
Leave a Comment