Skip to content

Nihara-D/physics-sandbox

Repository files navigation

Physics Sandbox - 3D Interactive Simulation Engine

Creator: Nihara Dayarathne
Email: shniharard@gmail.com

Overview

A sophisticated, web-based 3D physics sandbox simulator featuring interactive object manipulation, creature design, and genetic algorithm evolution. Built with cutting-edge web technologies for real-time simulation and visualization.

Features

1. Sandbox Builder Mode

  • Create and manipulate 3D physics objects (boxes, spheres, cylinders, cones, planes)
  • Real-time physics simulation with gravity, friction, and restitution
  • Interactive object properties editor
  • Save and load sandbox configurations
  • Visual feedback with highlighted selection

2. Creature Designer Mode

  • Design soft-body creatures (organic, spring-based physics)
  • Design rigid-body creatures (mechanical, joint-based systems)
  • Visual creature editor with segment and joint visualization
  • Mutation system for evolutionary exploration
  • Save and organize creature designs

3. Evolution Simulator Mode

  • Genetic algorithm framework with population-based evolution
  • Neural network controllers for creature behavior
  • Multiple fitness metrics:
    • Speed: Maximize horizontal movement distance
    • Height: Maximize vertical displacement
    • Stability: Minimize oscillation and instability
    • Hybrid: Balanced fitness evaluation
  • Environmental challenges:
    • Flat ground
    • Slopes and ramps
    • Water/fluid environments
    • Obstacle courses
  • Real-time fitness visualization and generational tracking

Technical Stack

Frontend

  • React 19.2 - UI framework
  • Next.js 16.2 - Full-stack web framework with Turbopack
  • Three.js - 3D graphics and rendering
  • React Three Fiber - React renderer for Three.js
  • @react-three/rapier - Rapier physics engine integration
  • Zustand - State management
  • Tailwind CSS - Styling and design system
  • Lucide React - Icon library

Physics Engine

  • Rapier3D - High-performance 3D physics simulation
    • Rigid body dynamics
    • Soft body simulation (spring constraints)
    • Collision detection and response
    • Joint constraints
    • Gravity and damping

AI & Genetics

  • Neural Networks: 2-layer MLPs with backpropagation-free evolution
  • Genetic Algorithms: Tournament selection, crossover, and mutation
  • Evolution Strategies: Population-based optimization

Architecture

File Structure

├── app/
│   ├── layout.tsx          # Root layout with branding
│   ├── page.tsx            # Main app entry point
│   └── globals.css         # Design tokens and theming
├── components/
│   ├── Header.tsx          # App header with controls
│   ├── ModeSelector.tsx    # Mode selection sidebar
│   ├── PhysicsScene.tsx    # Three.js canvas component
│   ├── modes/
│   │   ├── SandboxMode.tsx
│   │   ├── CreatureDesignerMode.tsx
│   │   └── EvolutionMode.tsx
│   └── sandbox/
│       ├── SandboxToolbar.tsx
│       └── SandboxProperties.tsx
├── lib/
│   ├── types.ts            # TypeScript type definitions
│   ├── store.ts            # Zustand state management
│   ├── physics-utils.ts    # Physics helper functions
│   └── genetics.ts         # Genetics and neural network logic
└── scripts/                # Utility scripts

Core Systems

Physics System (lib/physics-utils.ts)

  • Vector3 and Quaternion utilities
  • Object creation and collision detection
  • Physics constants and defaults
  • Serialization for save/load functionality

Genetics Engine (lib/genetics.ts)

  • Creature genome definition and generation
  • Neural network creation and evaluation
  • Genetic operators (mutation, crossover)
  • Fitness calculation framework
  • Population management

State Management (lib/store.ts)

  • Global app state with Zustand
  • Mode switching and UI state
  • Object and creature management
  • Evolution simulation state
  • Save/load functionality with localStorage

Usage

Sandbox Builder

  1. Select object type from toolbar (Box, Sphere, Cylinder, Cone, Plane)
  2. Click "Add" button to spawn objects
  3. Click objects in canvas to select them
  4. Adjust properties (mass, friction, bounciness, color) in right panel
  5. Use Play/Pause button to control simulation

Creature Designer

  1. Click "Create Creature" button
  2. Choose creature type (Soft-body or Rigid-body)
  3. Click "Mutate" to generate variants
  4. View creature segments and joint structure
  5. Delete creatures to clean up

Evolution Simulator

  1. Set population size (5-50 creatures)
  2. Choose fitness metric (Speed, Height, Stability, Hybrid)
  3. Select environment challenge
  4. Click "Start Evolution" to run genetic algorithm
  5. Monitor fitness trends and generational progress

Physics Simulation Details

Rapier3D Engine

  • Time Step: 1/60 second (60 FPS target)
  • Gravity: -9.81 m/s² (Earth-like)
  • Linear Damping: 0.01 (slight air resistance)
  • Angular Damping: 0.01 (rotational resistance)
  • Collision Groups: Static (ground), Dynamic (objects), Creature bodies

Soft-Body Physics

  • Spring constraints between body segments
  • Fixed joints for structure
  • Oscillatory motion and wave propagation

Rigid-Body Physics

  • Revolute and prismatic joints
  • Motor-driven actuators
  • Joint angle limits and spring stiffness

Genetic Algorithm Framework

Creature Genome

{
  segments: [
    { dimensions, mass, color, offset, type }
  ],
  joints: [
    { type, bodies, limits, motor parameters }
  ],
  neuralWeights: number[]
}

Neural Network Architecture

  • Input Layer: Sensory inputs (position, velocity, acceleration)
  • Hidden Layer: 16 neurons with ReLU activation
  • Output Layer: Motor controls per joint (tanh activation, [-1, 1] range)

Genetic Operations

  • Selection: Tournament selection with fitness bias
  • Crossover: Segment and joint inheritance
  • Mutation: Parameter variance with controlled rates
  • Elite Preservation: Top performers carry forward

Design System

Color Palette

  • Primary: Cyan (#00d9ff) - Interactive elements
  • Secondary: Indigo (#6366f1) - Secondary accent
  • Accent: Cyan (#00d9ff) - Highlights
  • Background: Dark gray (#0f0f1e) - Main canvas
  • Foreground: Light gray (#e8e8f0) - Text
  • Sidebar: Darker gray (#16162a) - Navigation

Typography

  • Font: Geist and Geist Mono (from Google Fonts)
  • Headings: Bold, 1.5-2rem
  • Body: Regular, 0.875-1rem
  • Mono: Code and values, Geist Mono

Performance Optimization

Rendering

  • Hardware-accelerated WebGL via Three.js
  • Frustum culling for off-screen objects
  • LOD (Level of Detail) for complex scenes
  • Efficient particle systems for visual feedback

Physics

  • Spatial partitioning via Rapier
  • Sleeping rigid bodies to reduce computation
  • Constraint relaxation and adaptive time stepping
  • Web Worker support for evolution simulations (future)

Browser Compatibility

  • Chrome/Chromium 90+
  • Firefox 88+
  • Safari 14+
  • Edge 90+

Requirements: WebGL 2.0, ES2020 JavaScript

Future Enhancements

  1. Advanced Features

    • Water/fluid dynamics simulation
    • Particle systems and effects
    • Procedural terrain generation
    • Multi-threaded evolution on Web Workers
  2. Genetic Algorithm Improvements

    • Speciation and niching
    • Memetic algorithms with local search
    • Coevolution (predator-prey)
    • Novelty search
  3. Creator Tools

    • Custom environment editor
    • Creature body part library
    • Joint constraint presets
    • Animation timeline and playback
  4. Sharing & Community

    • Cloud save synchronization
    • Creature sharing marketplace
    • Evolution leaderboards
    • Collaborative sandbox sessions

Controls

  • Mouse Orbit: Click and drag to rotate camera
  • Scroll: Zoom in/out
  • Click Object: Select for editing
  • Button Controls: Add/remove objects, pause/resume

Performance Metrics

  • Target FPS: 60
  • Max Objects: 100+ (depends on system)
  • Physics Updates: 60 Hz
  • Rendering: GPU-accelerated

Credits

Creator: Nihara Dayarathne (shniharard@gmail.com)

Built with:

  • Three.js + React Three Fiber
  • Rapier3D Physics
  • React + Next.js
  • Zustand State Management

License

This project is created by Nihara Dayarathne. All code, designs, and branding are proprietary and the creator's intellectual property.


Last Updated: 2026
Version: 1.0.0

About

Interactive 3D physics sandbox with creature evolution and genetic algorithms. Build structures, design creatures with neural networks, and watch them learn through genetic evolution - all running in your browser with real-time physics simulation using Three.js and Rapier3D.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages