#!/usr/bin/env python3
"""Render orthogonal views of the STL as PPM images using trimesh."""
import trimesh
import numpy as np
import os

path = "/app/projects/esp32-box/original/Window 20x60mm.stl"
m = trimesh.load(path)

OUT = "/app/projects/esp32-box/exports"

def render_view(mesh, direction, up, filename, size=400):
    """Render mesh from a given view direction."""
    scene = trimesh.scene.Scene(mesh)
    # Set camera
    scene.camera_transform = trimesh.scene.utils.orbit_camera(
        np.degrees(np.arctan2(direction[0], direction[2])),
        np.degrees(np.arcsin(direction[1])),
        80,  # distance
        mesh.centroid
    )
    # Render
    data = scene.save_image(resolution=[size, size], visible=True)
    with open(os.path.join(OUT, filename), "wb") as f:
        f.write(data)
    print(f"Saved {filename}")

# Front view (looking from +Y): X horizontal, Z vertical
# This shows the main face of the panel
print("Rendering views...")

# Save as PNG via trimesh rendering (needs pyglet)
try:
    from PIL import Image
    # Try raster rendering approach
    for angle_name, direction, up in [
        ("front", [0, 1, 0], [0, 0, 1]),
        ("top", [0, 0, -1], [0, -1, 0]),
        ("side", [1, 0, 0], [0, 0, 1]),
        ("perspective", [-0.7, 0.5, 0.5], [0, 0, 1]),
    ]:
        scene = trimesh.scene.Scene(m)
        transform = trimesh.scene.utils.orbit_camera(
            np.degrees(np.arctan2(direction[0], direction[2])),
            np.degrees(np.arcsin(direction[1])),
            100,
            mesh.centroid
        )
        scene.camera_transform = transform
        png_bytes = scene.save_image(resolution=[500, 500], visible=True)
        fname = f"window_{angle_name}.png"
        with open(os.path.join(OUT, fname), "wb") as f:
            f.write(png_bytes)
        print(f"  {fname}: {len(png_bytes)} bytes")
except Exception as e:
    print(f"Render error: {e}")
    
print("DONE")
