PROJECT OVERVIEW:
Create a single-page React application called "SimulCraft" that acts as a sophisticated traffic simulation engine inspired by the challenges of rendering complex city life on limited hardware, as exemplified by the original Pizza Tycoon. The core value proposition is to provide developers with a powerful yet lightweight tool to build, simulate, and optimize intricate traffic systems, focusing on performance and resource efficiency. This application will enable users to design city layouts, define vehicle behaviors, and visualize traffic flow, all while offering tools to simulate performance constraints, such as CPU clock speed and memory limitations, thereby learning from the ingenious techniques used in vintage games. The goal is to offer a modern development experience for creating retro-inspired or highly optimized simulation elements.
TECH STACK:
- Frontend Framework: React.js
- Styling: Tailwind CSS for rapid UI development and a clean, utility-first approach.
- State Management: Zustand for efficient and simple global state management.
- Routing: React Router DOM for potential future expansion to multi-page views, though MVP is single-page.
- Graphics/Rendering: HTML5 Canvas API for efficient rendering of the simulation grid and vehicles. Libraries like Konva.js or Fabric.js can be considered for easier Canvas manipulation if needed, but direct Canvas API is preferred for performance.
- Animation: Framer Motion for smooth UI transitions and micro-interactions within the control panels.
- Utility Libraries: Lodash for general utility functions.
CORE FEATURES:
1. **City/Road Network Designer:**
* **User Flow:** Users can draw roads, intersections, and define road segments using a simple, intuitive interface powered by the HTML5 Canvas. They select a 'road tool' and click/drag to create paths. Intersection creation is automatic when roads cross or can be manually placed. Users can define segment properties like length, lanes, and speed limits.
* **Details:** A toolbar provides tools for drawing roads (straight, curves), placing intersections, and erasing elements. A properties panel allows editing selected segments (e.g., speed limit, number of lanes).
2. **Vehicle Behavior & AI:**
* **User Flow:** Users can define different types of vehicles (cars, trucks) and configure their basic AI parameters. This includes maximum speed, acceleration, deceleration, turning radius, and minimum following distance.
* **Details:** A dedicated section allows creating vehicle profiles. For each profile, users can adjust sliders and input fields for the aforementioned parameters. Advanced options could include lane-changing behavior rules.
3. **Traffic Simulation Engine:**
* **User Flow:** Once the network and vehicles are defined, users initiate the simulation. The engine calculates vehicle movement based on road network, traffic rules, and vehicle AI. It handles pathfinding, collision avoidance (basic), and queuing at intersections.
* **Details:** This is the core logic running on the Canvas. It iterates through vehicles, updates their positions based on physics and AI, checks for collisions, and manages intersection queues. The simulation speed can be adjusted.
4. **Performance Simulation & Constraints:**
* **User Flow:** Users can set simulated hardware constraints, such as target CPU frequency (MHz) and available RAM (MB). The application will then try to simulate the traffic density and complexity that could realistically run under these constraints.
* **Details:** This involves throttling the simulation loop, potentially simplifying calculations, or limiting the number of active vehicles to match the specified constraints. It provides insights into how the simulation would perform on older hardware.
5. **Visualization & Analytics:**
* **User Flow:** The simulation is visualized in real-time on the Canvas. Users can observe traffic flow, vehicle interactions, and potential bottlenecks. Basic analytics like current vehicle count, average speed, and intersection queue lengths are displayed.
* **Details:** The Canvas displays moving vehicles as simple sprites. UI panels show real-time statistics. Heatmaps or density overlays can be added in later versions.
UI/UX DESIGN:
- **Layout:** A main 3-panel layout. Left sidebar for design tools (Roads, Intersections, Eraser) and vehicle/simulation settings. Central large area for the Canvas simulation view. Right sidebar for real-time analytics, performance controls, and simulation status.
- **Color Palette:** A modern, clean palette with a dark theme for the control panels and a bright, clear canvas. Primary colors: Dark charcoal (#1E1E1E), Deep blue (#2563EB) for accents and interactive elements, Light gray (#E5E7EB) for text and borders, White (#FFFFFF) for key information. Canvas background: A muted green or gray.
- **Typography:** A clean, readable sans-serif font like Inter or Roboto for all UI elements. Headings will be bolder and larger than body text.
- **Responsive Design:** The application will be designed primarily for desktop use due to the complexity of the interface. However, the layout should adapt gracefully to different screen widths, ensuring critical controls remain accessible. The Canvas area should resize fluidly. Tailwind CSS's responsive modifiers (sm:, md:, lg:) will be used.
COMPONENT BREAKDOWN:
- **`App.js`**: Main application component, sets up layout and global state providers.
- **`CanvasView.js`**: Renders the HTML5 Canvas, handles drawing the road network, vehicles, and updates based on simulation state. Manages Canvas interactions (drawing, selection).
* Props: `simulationState`, `onNetworkUpdate`, `isEditing`
- **`Toolbar.js`**: Contains tools for editing the road network (draw road, intersection, eraser). Mounted within `App.js` or a layout component.
* Props: `activeTool`, `onToolSelect`
- **`PropertiesPanel.js`**: Displays and allows editing of properties for selected road segments or vehicles.
* Props: `selectedItem`, `onUpdateItem`
- **`VehicleSettings.js`**: Component for defining and configuring vehicle types and their AI parameters.
* Props: `vehicleTypes`, `onUpdateVehicleTypes`
- **`SimulationControls.js`**: Contains controls for starting, stopping, pausing the simulation, and adjusting simulation speed.
* Props: `isRunning`, `simulationSpeed`, `onControlAction`
- **`PerformancePanel.js`**: Allows users to set CPU/RAM constraints and view performance metrics.
* Props: `constraints`, `performanceData`, `onUpdateConstraints`
- **`AnalyticsPanel.js`**: Displays real-time statistics from the simulation.
* Props: `analyticsData`
- **`Sidebar.js`**: Container component for `Toolbar`, `VehicleSettings`, etc.
- **`RightPanel.js`**: Container for `SimulationControls`, `PerformancePanel`, `AnalyticsPanel`.
DATA MODEL:
- **`simulationState` (Zustand Store):**
* `network`: {
`segments`: [ { id: string, type: 'straight'|'curve'|'intersection', start: {x, y}, end: {x, y}, lanes: number, speedLimit: number, occupied: boolean[] } ],
`intersections`: [ { id: string, x: number, y: number, connectedSegments: string[] } ]
}
* `vehicles`: [ { id: string, type: string, position: {x, y}, velocity: {x, y}, target: {x, y}, route: string[], state: 'moving'|'queuing'|'stopped' } ]
* `vehicleTypes`: [ { name: string, maxSpeed: number, acceleration: number, ... } ]
* `simulationSettings`: { isRunning: boolean, speed: number, cpuMHz: number, ramMB: number }
* `analytics`: { vehicleCount: number, avgSpeed: number, maxQueue: number }
* `editorState`: { activeTool: string, selectedItemId: string | null }
- **Mock Data Format (`vehicleTypes` example):**
```json
[
{
"name": "Sedan",
"maxSpeed": 120,
"acceleration": 3.0,
"deceleration": 5.0,
"length": 4.5,
"turningRadius": 5.0
},
{
"name": "Truck",
"maxSpeed": 90,
"acceleration": 1.5,
"deceleration": 4.0,
"length": 10.0,
"turningRadius": 8.0
}
]
```
ANIMATIONS & INTERACTIONS:
- **UI Transitions:** Smooth slide-in/out effects for side panels using Framer Motion. Subtle fade transitions for modal dialogs (e.g., settings confirmation).
- **Button Hovers:** Slight scale-up or background color change on interactive elements (buttons, tool icons) using Tailwind CSS hover states.
- **Vehicle Movement:** Smooth interpolation of vehicle positions between simulation ticks for a visually appealing flow, even if the simulation logic runs at discrete steps. Use `requestAnimationFrame` for rendering.
- **Loading States:** Skeletons or spinners when loading simulation data or initializing complex computations. Disable controls during critical loading phases.
- **Micro-interactions:** Visual feedback when drawing roads (e.g., a temporary line), selecting an item (e.g., a glowing outline), or when a vehicle successfully navigates an intersection.
EDGE CASES:
- **Empty State:** When no network is defined, the Canvas should display a helpful message guiding the user to start drawing. Analytics and simulation controls should be disabled or show default/empty values.
- **No Vehicles:** If no vehicles are defined or added, the simulation runs but shows no movement. Analytics reflect zero vehicles.
- **Error Handling:** Catch potential errors during Canvas rendering or simulation logic. Display user-friendly error messages (e.g., in a toast notification or status bar) without crashing the application. Specific errors like pathfinding failures or impossible routing scenarios should be logged.
- **Validation:** Input fields for vehicle parameters and road properties should have client-side validation (e.g., speed limits must be positive, lengths cannot be negative). Use Zustand middleware or custom validation logic.
- **Accessibility (a11y):** Ensure all interactive elements have proper ARIA attributes, keyboard navigation is supported for core functionalities, and sufficient color contrast is maintained for UI elements.
- **Performance Throttling:** Implement robust throttling logic for the simulation loop to accurately reflect CPU constraints. This might involve skipping rendering frames or reducing simulation update frequency.
SAMPLE DATA:
```json
{
"network": {
"segments": [
{ "id": "seg1", "type": "straight", "start": {"x": 100, "y": 100}, "end": {"x": 300, "y": 100}, "lanes": 2, "speedLimit": 80, "occupied": [] },
{ "id": "seg2", "type": "straight", "start": {"x": 300, "y": 100}, "end": {"x": 300, "y": 300}, "lanes": 2, "speedLimit": 60, "occupied": [] },
{ "id": "seg3", "type": "intersection", "start": {"x": 300, "y": 100}, "end": {"x": 300, "y": 100}, "lanes": 2, "speedLimit": 60, "occupied": [] }
],
"intersections": [
{ "id": "int1", "x": 300, "y": 100, "connectedSegments": ["seg1", "seg2"] }
]
},
"vehicles": [
{ "id": "car1", "type": "Sedan", "position": {"x": 110, "y": 100}, "velocity": {"x": 5, "y": 0}, "route": ["seg1", "seg2"], "state": "moving" },
{ "id": "car2", "type": "Truck", "position": {"x": 150, "y": 100}, "velocity": {"x": 3, "y": 0}, "route": ["seg1", "seg3"], "state": "moving" }
],
"vehicleTypes": [
{ "name": "Sedan", "maxSpeed": 120, "acceleration": 3.0, "deceleration": 5.0, "length": 4.5, "turningRadius": 5.0 },
{ "name": "Truck", "maxSpeed": 90, "acceleration": 1.5, "deceleration": 4.0, "length": 10.0, "turningRadius": 8.0 }
],
"simulationSettings": {
"isRunning": true,
"speed": 1.0,
"cpuMHz": 25,
"ramMB": 1
},
"analytics": {
"vehicleCount": 2,
"avgSpeed": 4.0,
"maxQueue": 0
}
}
```
DEPLOYMENT NOTES:
- **Build:** Use Create React App (CRA) with modifications for Canvas performance or a Vite setup. Ensure `requestAnimationFrame` is used for rendering loop synchronization.
- **Environment Variables:** Use `.env` files for configuration (e.g., `REACT_APP_API_URL` if external services are added later). For MVP, focus on client-side state.
- **Performance Optimizations:**
* Memoize expensive calculations (e.g., pathfinding). Use `React.memo` or custom hooks.
* Optimize Canvas rendering: Avoid re-drawing the entire scene on every frame if parts haven't changed. Batch drawing operations.
* Debounce or throttle frequent UI updates (e.g., resizing handlers).
* Code Splitting: If the app grows, consider code splitting for different sections (e.g., editor vs. simulation view).
* Web Workers: For computationally intensive tasks like pathfinding or complex physics, offload them to Web Workers to avoid blocking the main UI thread.
- **Production Build:** Run `npm run build` or `yarn build`. Ensure the output is served efficiently (e.g., using a static file server like Nginx or a platform like Netlify/Vercel).