import streamlit as st import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection from scipy import spatial import pymesh from solid import * from solid.utils import * import os import trimesh def plot_vertices_and_mesh(vertices, faces): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(vertices[:, 0], vertices[:, 1], vertices[:, 2]) for face in faces: vertices_of_face = vertices[face] poly = Poly3DCollection([vertices_of_face]) ax.add_collection3d(poly) st.pyplot(fig) def plot_convex_hull(points): hull = spatial.ConvexHull(points) plt.figure() plt.plot(points[:, 0], points[:, 1], 'o') for simplex in hull.simplices: plt.plot(points[simplex, 0], points[simplex, 1], 'k-') st.pyplot(plt) def create_3d_meshes(): # Create a box mesh box_a = trimesh.creation.box(extents=[1, 1, 1]) box_a.export('pymesh_example_01.stl') # Create another box mesh and perform a boolean operation box_b = trimesh.creation.box(extents=[0.2, 0.2, 1], translate=[0.4, 0.4, 0]) box_c = box_a.difference(box_b) box_c.export('pymesh_example_02.stl') st.write("3D meshes saved to files.") def create_solid_models(): d = difference()(cube(size=10, center=True), sphere(r=6.5, segments=300)) scad_render_to_file(d, '/tmp/solidpython_example_01.scad') c = circle(r=1) t = translate([2, 0, 0])(c) e = linear_extrude(height=10, center=True, convexity=10, twist=-500, slices=500)(t) col = color('lightgreen')(e) scad_render_to_file(col, '/tmp/solidpython_example_02.scad') st.write("Solid models saved to files.") st.title("Exploring 3D Graphics and Geometry with Python") st.markdown(""" This application demonstrates basic concepts of 3D graphics in Python. You can visualize 3D objects, create convex hulls, generate and save 3D meshes, and explore solid modeling. Each section below offers a different aspect of 3D graphics. """) st.subheader("1. Plot Vertices and Meshes") if st.button('Show 3D Vertices and Meshes'): vertices = np.array([[-3, -3, 0], [+3, -3, 0], [+3, +3, 0], [-3, +3, 0], [+0, +0, +3]]) faces = np.array([[4, 1, 0], [4, 2, 1], [3, 4, 0], [3, 4, 2], [3, 2, 1], [3, 1, 0]], dtype=np.int32) plot_vertices_and_mesh(vertices, faces) st.subheader("2. Plot Convex Hull") if st.button('Show Convex Hull'): points = np.array([[0, 0], [-2, 0], [-2, 2], [0, 1.5], [2, 2], [2, 0]]) plot_convex_hull(points) st.subheader("3. Create and Save 3D Meshes") if st.button('Generate 3D Meshes'): create_3d_meshes() st.subheader("4. Create and Save Solid Models") if st.button('Generate Solid Models'): create_solid_models() st.markdown(""" Developed using Python libraries like matplotlib, scipy, pymesh, and solid, this application serves as an introductory tool for understanding and visualizing 3D concepts in Python. """)