# Web Rope Simulation

A physics-based rope simulation that runs in the browser, with 2D/3D visualization and 3D printing capabilities.

This project simulates a chain of connected beads with realistic physics, allowing users to interact with the rope, visualize it in 2D or 3D, and export models for 3D printing.

## Parameters

The simulation offers configurability through the following parameters:

- **Physics**: gravity, friction, tension, stiffness
- **Rope Structure**: number of beads, bead size, distance between beads
- **Visualization**: 2D/3D modes, rope thickness, color, lighting
- **3D Printing**: tube thickness, segment smoothing, model splitting, LED socket parameters

## 2D

The 2D mode provides a visualization using canvas rendering for optimal performance. It's ideal for physics experimentation and rapid iteration.

## 3D

The 3D mode uses Three.js to render a smooth 3D representation of the rope. It offers:

- Lighting and materials
- Camera controls (orbit, pan, zoom)
- Real-time feedback as rope physics update

## 3D Printing Features

### Smooth Watertight Tube Generation

The simulation generates a smooth, continuous, and watertight 3D tube following the rope's path. This is implemented using CSG (Constructive Solid Geometry) operations via the Manifold.js library, which ensures:

- Proper manifold geometry (no holes, intersections, or non-manifold edges)
- Consistent normals for clean 3D printing results
- Configurable thickness and segment resolution

### Model Splitting

For ropes longer than a printer's build volume, the model can be split into multiple parts:

- User-controllable splitting plane
- Visual feedback showing cut locations
- Automatic registration features at cut points
- Export of individual parts or the full model

### Hinge System

Printed rope sections include optional hinges for articulation:

- Configurable hinge sizing
- Ball-and-socket or cylinder hinges
- Snap-fit design for post-printing assembly

### Registration Features

Cut points include alignment features to ensure proper assembly:

- Keyed interfaces for unambiguous alignment
- Configurable tolerance settings
- Visual preview of connection points

### Internal Mounting Surfaces

The model can include internal platforms for:

- Electronics mounting
- Battery placement
- Weight distribution optimization

Each plate starts after the models is split, as a disc that sits inside eash hemisphere.

### LED Mounting System

Support for embedding LEDs in the printed model:

- Customizable LED spacing and count
- Configurable socket size and depth
- Sockets oriented toward the center for internal mounting
- Channels for wiring
- Diffusion chambers for improved light distribution

### Real-World Units

The system supports real-world measurements:

- Export in millimeters for direct printing
- Scaling tools for size adjustment
- Dimension verification tools

## 3D Printing Implementation Details

### Manifold.js Integration

The system uses Manifold.js for robust CSG operations, ensuring printable models:

- WASM-based processing for high performance
- Reliable boolean operations (union, difference, intersection)
- Proper handling of self-intersections

### Model Splitting

The ball form is split to accomodate printing and construction.

- The user can place and adjust a splitting plane
- Boolean operations create clean cut surfaces
- Complementary interfaces are generated at cut points

### Web Worker Implementation

Computationally intensive 3D operations run in a dedicated Web Worker:

- UI remains responsive during heavy processing
- Progress feedback during lengthy operations
- Message-based communication with main thread
- Separate processing with main thread handling LED position calculation and worker handling tube generation, socket creation, and model splitting
- Proper error handling and recovery

### Hinge Implementation

Hinges are generated using parametric design:

- Custom CSG operations create interlocking components
- Tolerances account for printer specifications
- Self-supporting geometries minimize need for supports

#### Hinge Parameters

Configurable parameters include:

- Socket depth and diameter
- Ball size and tolerance
- Reinforcement thickness
- Rotation limits

### Registration Features

Cut interfaces include keying features:

- Tongue and groove connections
- Alignment pins and sockets
- Labeling system for multi-part assembly

### Internal Mounting Platforms

For electronics integration:

- Flat internal surfaces maintain minimum wall thickness
- Access ports for wiring
- Mounting hole patterns for standard components

### LED Integration

LED mounting is facilitated by:

- Automatically generated LED sockets at evenly spaced intervals along the curve
- Pre-calculated LED positions for optimal placement
- Customizable socket count (default 100)
- Adjustable socket radius and depth
- Sockets pointing toward the center (0,0,0) for internal LED placement
- Diffuser chambers for improved lighting effects
- Avoiding the center plane

LED sockets are too complex to be subtracted with Manifold-3d's CSG, as far as I can tell. To work around this, the sockets will be created as another _positive_ shape group. They are then split with the same split plane, and exported as a separate STL, to be combined and subtracted with another tool. To make this easier, a thin "bounding rectangle" shape will be placed against the print bed, which is the slicing plane. It will serve as registration around the 4 parts:

- top positive
- top negative
- bottom positive
- bottom negative

In the view, they will be colored light blue for positive, and light red for negative.

They will export as four separate STL files.

### Units and Scaling

The system handles real-world dimensions:

- All calculations and exports use millimeters
- Scale validation ensures printability
- Minimum wall thickness enforcement

## Future Development Checklist

### Enhanced 3D Printing Features

- [ ] Wall thickness analysis and correction
- [ ] Printability validation (overhang detection, etc.)
- [ ] Articulation stops and limits

### Optimization and Performance

- [x] Web Worker implementation for computationally intensive tasks
- [x] Progress indicators for long-running operations
- [ ] Adaptive physics timestep
- [ ] Memory usage optimization
- [ ] Mobile device optimization for GUI

### Software Integration

- [ ] Parameters presets/profiles system
- [ ] Programmatic animation capabilities
- [ ] Extended documentation and tutorials

# Web Rope Simulation Architecture Plan

This section outlines the software architecture of the Web Rope Simulation project.

## 1. Project Structure

```
rope-simulation/
├── index.html             # Main HTML entry point
├── lib/                   # Third-party libraries
│   ├── three.module.min.js
│   ├── three.core.min.js
│   ├── three.OrbitControls.js
│   ├── lil-gui.min.js
│   └── manifold-3d@3.0.1/ # For watertight 3D models
├── generated/             # Main application files
│   ├── main.js            # Application entry point
│   ├── Rope.js            # Rope data structure
│   ├── Physics.js         # Physics simulation
│   ├── RopeVisualizer.js  # Rendering logic
│   ├── Print3D.js         # 3D printing preparation
│   └── Print3D-worker.js  # Web Worker for heavy computations
└── readme.md              # Documentation
```

## 2. Component Breakdown

### HTML (index.html)

The main HTML file provides the canvas element and loads the necessary scripts. It includes minimal structure, as most of the UI is generated dynamically by JavaScript.

### Core Components

#### Rope.js

Handles the data structure representing the rope:
- Bead positions, velocities, and connections
- Methods for adding/removing beads
- Constraint management

#### Physics.js

Responsible for simulating rope physics:
- Force application (gravity, tension)
- Collision detection and response
- Constraint solving
- Numerical integration

#### RopeVisualizer.js

Handles rendering in both 2D and 3D modes:
- 2D canvas rendering
- 3D Three.js integration
- Camera controls
- Lighting setup

#### Print3D.js

Handles 3D printing-related functionality:
- Tube mesh generation
- Model splitting
- Hinge generation
- Export to printable formats
- Worker communication

#### Print3D-worker.js

Performs computationally intensive tasks in a separate thread:
- CSG operations for tube generation
- Model splitting computations
- Progress reporting back to main thread
- Error handling and recovery

### Main.js

Orchestrates the entire application:
- Initialization and setup
- GUI creation and management
- Event handling
- Animation loop
- Mode switching

## 3. Implementation Details

### Bead Object Structure

Each bead in the rope contains:
```javascript
{
  position: {x, y, z},  // Current position
  oldPosition: {x, y, z},  // Previous position
  velocity: {x, y, z},  // Current velocity
  mass: number,  // Mass of the bead
  isFixed: boolean,  // Whether the bead is fixed in space
  connections: []  // References to connected beads
}
```

### Simulation Loop

The physics simulation follows a time-stepped approach:
1. Calculate forces on each bead
2. Update velocities
3. Apply constraints
4. Update positions
5. Handle collisions
6. Render updated state

### Mode Handling

The application switches between different modes:
- Edit mode: Allows adding/removing/moving beads
- Simulation mode: Runs the physics simulation
- 3D Print mode: Prepares model for 3D printing

## 4. User Interface

The UI is built using lil-gui for parameter control and provides:
- Simulation controls (play/pause/reset)
- Physics parameter adjustment
- Visualization options
- 3D printing settings
- Export controls

Real-time feedback is provided through:
- Loading indicators for lengthy operations
- Status messages for processing steps
- Visual cues for edit operations

## 5. Implementation Plan Checklist

### Core Functionality

- [x] Basic rope data structure
- [x] Physics simulation
- [x] 2D visualization
- [x] 3D visualization
- [x] User interaction (add/remove/move beads)
- [x] Collision detection
- [x] GUI controls
- [ ] SVG export

### 3D Printing Features

- [x] Smooth tube generation
- [x] 3D model export (GLB format)
- [x] Model splitting UI
- [x] Registration features
- [x] Hinge system
- [x] Web Worker implementation
- [x] Progress indicators for long operations
- [x] LED socket implementation
- [ ] Automatic splitting optimization
- [ ] Multi-material support
- [ ] Printability analysis
- [ ] Support structure generation
- [ ] Infill pattern control
- [ ] Slicing preview
- [ ] Print time estimation
- [ ] Export settings profiles

### Optimization and Testing

- [x] Web Worker offloading
- [x] Progress feedback system
- [ ] Performance profiling
- [ ] Memory optimization
- [ ] Mobile device support
- [ ] Browser compatibility testing
- [ ] Load/stress testing
- [ ] Print result validation
