{"id":42296255,"url":"https://github.com/ezeoleaf/mycorust","last_synced_at":"2026-01-27T10:12:46.782Z","repository":{"id":322701135,"uuid":"1086362823","full_name":"ezeoleaf/mycorust","owner":"ezeoleaf","description":"A simple mycelium/hyphae growth simulation written in Rust ","archived":false,"fork":false,"pushed_at":"2025-11-27T20:04:09.000Z","size":464,"stargazers_count":4,"open_issues_count":8,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-28T21:01:30.284Z","etag":null,"topics":["educational","mushroom","mycelium","rust","simulation"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ezeoleaf.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-30T10:12:03.000Z","updated_at":"2025-11-27T20:04:13.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ezeoleaf/mycorust","commit_stats":null,"previous_names":["ezeoleaf/mycorust"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ezeoleaf/mycorust","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ezeoleaf%2Fmycorust","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ezeoleaf%2Fmycorust/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ezeoleaf%2Fmycorust/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ezeoleaf%2Fmycorust/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ezeoleaf","download_url":"https://codeload.github.com/ezeoleaf/mycorust/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ezeoleaf%2Fmycorust/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28811553,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-27T07:41:26.337Z","status":"ssl_error","status_checked_at":"2026-01-27T07:41:08.776Z","response_time":168,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["educational","mushroom","mycelium","rust","simulation"],"created_at":"2026-01-27T10:12:46.712Z","updated_at":"2026-01-27T10:12:46.768Z","avatar_url":"https://github.com/ezeoleaf.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"## MycoRust — Mycelium Growth Simulation\n\nA mycelium/hyphae growth simulation in Rust. Hyphae follow nutrient gradients, branch, form connections (anastomosis), avoid collisions, and leave fading trails. Features advanced network intelligence, weather simulation, adaptive growth, and memory systems.\n\n**Two modes available:**\n- **UI Mode**: Interactive visualization using Macroquad (default)\n- **Headless Mode**: HTTP API server for integration with custom visualization tools\n\n### Prerequisites\n\n- Rust toolchain (stable) — install via `https://rustup.rs`\n\n### Run\n\n#### UI Mode (Default)\n```bash\ncargo run\n# or for better performance\ncargo run --release\n```\n\n#### Headless Mode (HTTP API Server)\nRun the simulation without a UI, exposing an HTTP API to access simulation state:\n\n```bash\n# Headless mode (no UI dependencies)\ncargo run --no-default-features -- --headless --port 8080\n\n# Headless mode with UI features compiled (but not used)\ncargo run --features ui -- --headless --port 8080\n\n# Default port is 8080 if not specified\ncargo run --no-default-features -- --headless\n```\n\nThe simulation runs automatically at ~60 FPS in the background. You can access the current state via HTTP endpoints (see [Headless Mode \u0026 API](#headless-mode--api) section below).\n\n### Run Tests\n\n```bash\n# Run all tests\ncargo test\n\n# Run specific test\ncargo test test_simulation_creation\n\n# Run tests with output\ncargo test -- --nocapture\n```\n\nThe simulation can be tested without requiring a graphics context, making it CI/CD friendly.\n\n### Features\n\n#### Core Simulation\n- Nutrient field rendered as a brown→green heatmap (with diffusion over time). Realistic organic patch-based distribution with multiple nutrient types (sugar and nitrogen).\n- **Directional Nutrient Flow**: Water flow field that drags nutrients in a specific direction, creating anisotropic diffusion. Flow strength and direction are configurable, and rain increases flow strength. This produces beautiful emergent branching behavior as hyphae follow nutrient gradients that are shaped by water flow.\n- **Pressure-Based Nutrient Flow**: Nutrients (carbon and nitrogen) flow from high concentration to low concentration along hyphal connections, creating adaptive routing and reinforcing key pathways. This forms \"highways\" through the mycelium network.\n- **Carbon/Nitrogen Ratio Requirements**: Hyphae require specific C:N ratios (default 10:1) for optimal growth. Growth efficiency decreases when the ratio deviates from optimal, creating realistic nutrient balance constraints.\n- Hyphae growth: gradient following + small random wander.\n- Branching with configurable probability.\n- Edge reflection with axis-correct bounce and a slight jitter.\n- Obstacle avoidance and hyphae-to-hyphae avoidance to reduce overlaps.\n- **Mycelial Density + Self-Inhibition**: Fungi avoid overcrowding their own filaments. A density map tracks hyphae density in each region, and growth is inhibited when density exceeds a threshold. This makes the network look more natural by preventing excessive clustering.\n- **Contaminants/Competitors**: Environmental challenges that affect mycelium growth:\n  - **Toxic Zones**: Harm hyphae by reducing energy and increasing senescence\n  - **Competitor Zones**: Consume nutrients (like Trichoderma), competing with mycelium\n  - **Deadwood Patches**: Nutrient-rich areas that provide food sources\n  - Hyphae detect and avoid toxic/competitor zones, rerouting around dangerous areas\n- Energy model: tips consume nutrients locally and die when energy is depleted.\n- **Hyphal Senescence \u0026 Death**: Biological aging system where hyphae die based on:\n  - Low nutrient flow through connections\n  - Distance from main network (unsupported branches collapse)\n  - Extreme weather conditions (too hot/cold)\n  - Visual decay: brown/grey coloring for dying hyphae\n- Anastomosis: nearby hyphae connect; simple energy balancing along connections.\n- Trails persist and fade over time; old segments are removed to limit memory growth.\n- Live statistics overlay (Hyphae, Spores, Connections, Fruiting Bodies, Avg Energy, Speed, FPS, Weather).\n- Minimap overlay showing nutrients and live hyphae positions.\n- Pulsing, age-faded anastomosis connection visualization (toggle).\n- Adjustable simulation speed (0.1x to 10x) with visual feedback.\n- Performance optimizations: spatial hashing, FPS-based draw decimation, adaptive quality reduction.\n- Scientific tweaks: Sobel chemotaxis and global tropism bias.\n\n#### Network Intelligence \u0026 Computation\n- **Signal Propagation**: Internal signaling (electrical/chemical pulses) travels through the mycelium network, triggering behaviors like growth direction changes and resource redistribution. Signals propagate along connections and decay over time.\n- **Adaptive Growth**: Reinforces efficient paths and prunes redundant hyphae using reinforcement learning. Branches strengthen with high nutrient flow and weaken/decay with low flow. Weak connections are automatically pruned.\n- **Memory \u0026 Learning**: Short-term memory of nutrient locations using decaying weights. Memory influences growth direction, allowing hyphae to remember and return to productive areas. Visualized as a purple overlay.\n\n#### Weather Simulation\n- **Dynamic Weather System**: Realistic weather conditions affect mycelium growth and behavior:\n  - **Temperature**: Affects growth rate and energy consumption\n  - **Humidity**: Influences nutrient diffusion and spore germination\n  - **Rain**: Impacts overall growth conditions\n  - **Seasonal Cycles**: Four distinct seasons (Spring, Summer, Autumn, Winter) with different temperature and humidity curves, affecting growth and fruiting patterns\n  - **Soil Moisture System**: Separate moisture grid that affects tip growth speed, branching factor, survival, and nutrient availability\n  - **Light Exposure System**: Shaded vs sunlit zones affect mycelium growth, with fungi avoiding bright light\n- Weather conditions change over time, creating dynamic environmental challenges.\n- Weather affects growth rate, energy consumption, nutrient diffusion, and spore germination.\n\n#### Growth Management\n- **Growth Limits**: Configurable maximum hyphae count to prevent performance degradation.\n- **Branching Thresholds**: Stop branching when hyphae count exceeds a threshold.\n- **Fusion**: When two hyphae meet very close together, they merge (true biological fusion/anastomosis with merging), combining their energy and taking maximum strength.\n\n#### Visualization \u0026 Interaction\n- **Enhanced Visualization**: \n  - Age-based coloring (young = white, old = dark)\n  - Nutrient flow intensity visualization (green pulses)\n  - Environmental stress visualization (red/orange for low energy, white/blue for high energy)\n  - **Senescence decay visualization**: Brown/grey coloring for dying hyphae (brown for early decay, grey for advanced decay)\n  - Pulsing animations for resource movement and signaling\n- **Heatmap Layers**: Toggleable overlays for visualizing:\n  - **Nutrients**: Nutrient distribution (default: on)\n  - **Moisture**: Soil moisture levels (blue gradient)\n  - **Age**: Hyphal age distribution (green→yellow→red gradient)\n  - **Flow**: Resource flow intensity (cyan→white gradient)\n  - **Growth Probability**: Predicted growth probability based on nutrients, moisture, and light (purple→pink gradient)\n- **Camera System**: Pan and zoom to explore the network at multiple scales (optional, disabled by default).\n- **Screenshot**: Capture high-resolution images of the simulation (P key).\n- **Spatial Culling**: Only visible objects are rendered for better performance.\n\n#### Headless Mode \u0026 API\n- **HTTP API Server**: Run the simulation without a UI, exposing REST endpoints\n- **Automatic Simulation**: Simulation runs continuously at ~60 FPS in the background\n- **JSON State Access**: Get full simulation state as JSON for custom visualization\n- **Control via API**: Step, pause, reset, and query simulation state remotely\n- **No Graphics Dependencies**: Headless mode can run without macroquad/OpenGL\n\n#### Testing\n- Comprehensive test suite with 15+ validation tests\n- Tests run without macroquad (no graphics context required)\n- Validates simulation state after multiple iterations\n- Tests energy levels, bounds checking, connections, memory, weather, and more\n\n### Controls\n\n#### Basic Controls\n- **SPACE**: Pause/Resume (only when not panning)\n- **R**: Reset simulation\n- **Shift+C**: Clear trails\n- **X**: Toggle connections visibility\n- **M**: Toggle minimap visibility\n- **H**: Toggle hyphae visibility\n- **I**: Toggle memory overlay (purple)\n- **S**: Spawn a new hypha at mouse position\n- **N**: Add a sugar patch at mouse position (small radius)\n- **T**: Add a nitrogen patch at mouse position\n- **Left Mouse Button**: Add a single sugar cell at mouse\n- **Right Mouse Button**: Add a single nitrogen cell at mouse\n\n#### Speed Controls\n- **Shift+Left Arrow (←)**: Decrease simulation speed\n- **Shift+Right Arrow (→)**: Increase simulation speed\n- **0**: Reset speed to 1x\n\n#### Camera Controls (when enabled)\n- **Arrow Keys / WASD**: Pan the camera\n- **Mouse Wheel**: Zoom in/out (at mouse position)\n- **Middle Mouse Button / Space+Left Mouse**: Drag to pan\n- **Home**: Reset camera to default position and zoom\n- **C**: Toggle camera enabled/disabled\n- **P**: Take screenshot (saved as PNG with timestamp)\n\n#### Visualization Controls\n- **V**: Toggle enhanced visualization (age/flow/stress coloring)\n- **F**: Toggle flow visualization (green pulses)\n- **1**: Toggle stress visualization (red/orange for low energy)\n\n#### Heatmap Layers\nToggleable heatmap overlays for visualizing different aspects of the simulation:\n- **N**: Toggle nutrients heatmap (default: on) - shows nutrient distribution\n- **U**: Toggle moisture heatmap - shows soil moisture levels (blue gradient)\n- **A**: Toggle age heatmap - shows hyphal age distribution (green→yellow→red)\n- **L**: Toggle flow heatmap - shows resource flow intensity (cyan→white)\n- **G**: Toggle growth probability heatmap - shows predicted growth probability (purple→pink)\n\nControls help is shown at the bottom of the screen. Press **F1** to toggle the help popup.\n\n### Headless Mode \u0026 API\n\nWhen running in headless mode, the simulation exposes an HTTP API server that allows you to:\n- Query the current simulation state\n- Control the simulation (step, pause, reset)\n- Integrate with custom visualization tools\n- Run the simulation on servers without graphics capabilities\n\n#### Starting the Headless Server\n\n```bash\n# Run headless mode (default port: 8080)\ncargo run --no-default-features -- --headless\n\n# Specify custom port\ncargo run --no-default-features -- --headless --port 3000\n```\n\nThe server will start and print available endpoints. The simulation runs automatically in the background at ~60 FPS.\n\n#### API Endpoints\n\nAll endpoints return JSON. CORS is enabled for cross-origin requests.\n\n##### `GET /state`\nGet the complete current simulation state.\n\n**Response**: Full `SimulationStateResponse` JSON containing:\n- `hyphae`: Array of all hyphae with positions, energy, age, strength, etc.\n- `spores`: Array of all spores\n- `connections`: Network connections between hyphae\n- `segments`: Trail segments (for visualization)\n- `fruit_bodies`: Fruiting bodies\n- `nutrients`: Sugar and nitrogen grids (2D arrays)\n- `nutrient_memory`: Memory grid (2D array)\n- `obstacles`: Obstacle grid (2D boolean array)\n- `weather`: Current weather conditions (temperature, humidity, rain, multipliers)\n- `stats`: Statistics (hyphae count, spores count, connections count, fruit count, avg energy, total energy, frame index)\n\n**Example**:\n```bash\ncurl http://localhost:8080/state | jq '.stats'\n```\n\n##### `GET /stats`\nGet simulation statistics only (lighter than `/state`).\n\n**Response**: `StatsData` JSON with counts and energy information.\n\n**Example**:\n```bash\ncurl http://localhost:8080/stats\n```\n\n##### `POST /step?steps=N`\nManually step the simulation forward N times (default: 1).\n\n**Query Parameters**:\n- `steps` (optional): Number of steps to advance (default: 1)\n\n**Response**: Full `SimulationStateResponse` after stepping.\n\n**Example**:\n```bash\n# Step once\ncurl -X POST http://localhost:8080/step\n\n# Step 10 times\ncurl -X POST \"http://localhost:8080/step?steps=10\"\n```\n\n##### `POST /reset`\nReset the simulation to its initial state.\n\n**Response**: Full `SimulationStateResponse` after reset.\n\n**Example**:\n```bash\ncurl -X POST http://localhost:8080/reset\n```\n\n##### `POST /pause`\nToggle the pause state of the simulation.\n\n**Response**: JSON with current pause state: `{\"paused\": true}` or `{\"paused\": false}`\n\n**Example**:\n```bash\ncurl -X POST http://localhost:8080/pause\n```\n\n##### `GET /config`\nGet the current simulation configuration.\n\n**Response**: `SimulationConfig` JSON with all parameters.\n\n**Example**:\n```bash\ncurl http://localhost:8080/config | jq '.grid_size'\n```\n\n#### Example Usage\n\n```bash\n# Start the headless server\ncargo run --no-default-features -- --headless\n\n# In another terminal, query the state\ncurl http://localhost:8080/state | jq '.stats.hyphae_count'\n\n# Get statistics\ncurl http://localhost:8080/stats\n\n# Pause the simulation\ncurl -X POST http://localhost:8080/pause\n\n# Step manually (even when paused, manual steps work)\ncurl -X POST \"http://localhost:8080/step?steps=5\"\n\n# Resume (unpause)\ncurl -X POST http://localhost:8080/pause\n\n# Reset the simulation\ncurl -X POST http://localhost:8080/reset\n```\n\n#### Integration Example (Go)\n\n```go\npackage main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"io\"\n    \"net/http\"\n)\n\ntype Hypha struct {\n    X      float32 `json:\"x\"`\n    Y      float32 `json:\"y\"`\n    Alive  bool    `json:\"alive\"`\n    Energy float32 `json:\"energy\"`\n}\n\ntype Stats struct {\n    HyphaeCount   int   `json:\"hyphae_count\"`\n    FrameIndex    int64 `json:\"frame_index\"`\n}\n\ntype StateResponse struct {\n    Hyphae []Hypha `json:\"hyphae\"`\n    Stats  Stats   `json:\"stats\"`\n}\n\nconst apiBaseURL = \"http://localhost:8080\"\n\nfunc main() {\n    // Get current state\n    resp, err := http.Get(apiBaseURL + \"/state\")\n    if err != nil {\n        panic(err)\n    }\n    defer resp.Body.Close()\n\n    body, err := io.ReadAll(resp.Body)\n    if err != nil {\n        panic(err)\n    }\n\n    var state StateResponse\n    if err := json.Unmarshal(body, \u0026state); err != nil {\n        panic(err)\n    }\n\n    // Access hyphae data\n    for _, hypha := range state.Hyphae {\n        if hypha.Alive {\n            fmt.Printf(\"Hypha at (%.2f, %.2f) with energy %.3f\\n\",\n                hypha.X, hypha.Y, hypha.Energy)\n        }\n    }\n\n    // Get statistics\n    resp, err = http.Get(apiBaseURL + \"/stats\")\n    if err != nil {\n        panic(err)\n    }\n    defer resp.Body.Close()\n\n    body, err = io.ReadAll(resp.Body)\n    if err != nil {\n        panic(err)\n    }\n\n    var stats Stats\n    if err := json.Unmarshal(body, \u0026stats); err != nil {\n        panic(err)\n    }\n\n    fmt.Printf(\"Active hyphae: %d\\n\", stats.HyphaeCount)\n    fmt.Printf(\"Frame: %d\\n\", stats.FrameIndex)\n\n    // Step simulation\n    apiURL := apiBaseURL + \"/step?steps=10\"\n    req, err := http.NewRequest(\"POST\", apiURL, nil)\n    if err != nil {\n        panic(err)\n    }\n\n    client := \u0026http.Client{}\n    resp, err = client.Do(req)\n    if err != nil {\n        panic(err)\n    }\n    defer resp.Body.Close()\n\n    fmt.Println(\"Stepped simulation 10 times\")\n}\n```\n\n#### Integration Example (JavaScript/TypeScript)\n\n```typescript\n// Fetch simulation state\nconst response = await fetch('http://localhost:8080/state');\nconst state = await response.json();\n\n// Access data\nconsole.log(`Hyphae count: ${state.stats.hyphae_count}`);\nconsole.log(`Frame: ${state.stats.frame_index}`);\n\n// Draw hyphae (example with Canvas API)\nconst canvas = document.getElementById('canvas');\nconst ctx = canvas.getContext('2d');\nctx.clearRect(0, 0, canvas.width, canvas.height);\n\nstate.hyphae.forEach(hypha =\u003e {\n  if (hypha.alive) {\n    ctx.fillStyle = `rgba(255, 255, 255, ${hypha.energy})`;\n    ctx.fillRect(hypha.x * 4, hypha.y * 4, 2, 2);\n  }\n});\n\n// Step simulation\nawait fetch('http://localhost:8080/step?steps=1', { method: 'POST' });\n```\n\n### Screenshots\n\n\u003cimg width=\"793\" height=\"797\" alt=\"image\" src=\"https://github.com/user-attachments/assets/7efaf73c-66f8-4376-b319-a34cdd6a5b81\" /\u003e\n\n\u003cimg width=\"636\" height=\"655\" alt=\"image\" src=\"https://github.com/user-attachments/assets/df870878-a154-47b9-a918-fc552936c246\" /\u003e\n\n### Configuration\n\nThe simulation uses a `SimulationConfig` struct for all parameters, located in `src/config.rs`. You can customize the simulation by creating a custom config:\n\n```rust\nuse mycorust::config::SimulationConfig;\n\nlet mut config = SimulationConfig::default();\nconfig.grid_size = 300;  // Larger grid\nconfig.branch_prob = 0.005;  // More branching\nconfig.camera_enabled = true;  // Enable camera\n// ... customize other parameters\n\nlet sim = Simulation::with_config(\u0026mut rng, config);\n```\n\n### Key parameters (in `SimulationConfig`)\n\n#### Grid/Display\n- `grid_size: usize` — logical grid resolution; window size = `grid_size * cell_size` (default: 200)\n- `cell_size: f32` — pixels per grid cell (default: 4.0)\n- `camera_enabled: bool` — enable camera pan/zoom functionality (default: false)\n\n#### Growth \u0026 Branching\n- `branch_prob: f32` — branching probability per step (default: 0.008)\n- `step_size: f32` — movement step length per frame (default: 0.5)\n- `angle_wander_range: f32` — random wander added to direction each frame (default: 0.05)\n- `gradient_steering_strength: f32` — steering toward nutrient gradient (default: 0.1)\n\n#### Nutrients\n- `nutrient_decay: f32` — max nutrient absorbed per step at a tip (default: 0.01)\n- `diffusion_rate: f32` — how quickly nutrients diffuse across neighbors (default: 0.05)\n- `spore_germination_threshold: f32` — nutrient threshold for spores to germinate (default: 0.6)\n- `spore_max_age: f32` — maximum age before spores die (default: 5.0)\n- `tropism_angle: f32`, `tropism_strength: f32` — global tropism bias (default: π/4, 0.01)\n- `nutrient_regen_rate: f32` — rate of nutrient regeneration (default: 0.004)\n- `nutrient_regen_floor: f32` — minimum nutrient level for regeneration (default: 0.12)\n\n#### Directional Flow (Water Drags Nutrients)\n- `flow_enabled: bool` — enable directional nutrient flow (default: true)\n- `flow_strength: f32` — strength of directional flow (0.0-1.0) (default: 0.3)\n- `flow_direction: f32` — flow direction in radians (0 = right, π/2 = down) (default: π/4)\n- `flow_variation: f32` — random variation in flow direction per timestep (default: 0.1)\n\n#### Carbon/Nitrogen Ratio \u0026 Pressure-Based Flow\n- `cn_ratio_required: f32` — required C:N ratio for optimal growth (default: 10.0 = 10:1)\n- `cn_ratio_tolerance: f32` — tolerance around required ratio (default: 0.3 = 30%)\n- `pressure_flow_enabled: bool` — enable pressure-based nutrient flow along connections (default: true)\n- `nutrient_flow_rate: f32` — rate of nutrient flow along connections (default: 0.015)\n\n#### Energy\n- `energy_decay_rate: f32` — passive energy decay per step (default: 0.9985)\n- `min_energy_to_live: f32` — below this, hyphae die (default: 0.005)\n\n#### Hyphal Senescence \u0026 Death\n- `senescence_enabled: bool` — enable hyphal senescence and death system (default: true)\n- `senescence_base_probability: f32` — base death probability per timestep (0.0-1.0) (default: 0.00001)\n- `senescence_nutrient_flow_threshold: f32` — low nutrient flow threshold that increases death probability (default: 0.005)\n- `senescence_distance_threshold: f32` — distance from main network that increases death probability (default: 30.0)\n- `senescence_weather_extreme_threshold: f32` — weather temperature threshold for extreme conditions (default: 0.3)\n- `senescence_unsupported_collapse_distance: f32` — distance beyond which unsupported branches collapse (default: 50.0)\n- `senescence_min_age: f32` — minimum age before senescence applies, giving hyphae time to establish (default: 5.0)\n\n#### Networking\n- `anastomosis_distance: f32` — distance within which hyphae connect (default: 2.0)\n- `connection_flow_rate: f32` — diffusive energy flow along connections (default: 0.02)\n\n#### Avoidance\n- `hyphae_avoidance_distance: f32` — hyphae turn away if the next step is closer than this (default: 2.0)\n\n#### Contaminants/Competitors\n- `zones_enabled: bool` — enable contaminant/competitor zones (default: true)\n- `toxic_zone_count: usize` — number of toxic zones (default: 5)\n- `competitor_zone_count: usize` — number of competitor zones (Trichoderma-like) (default: 3)\n- `deadwood_patch_count: usize` — number of deadwood patches (default: 8)\n- `toxic_zone_radius: f32` — radius of toxic zones (default: 8.0)\n- `competitor_zone_radius: f32` — radius of competitor zones (default: 10.0)\n- `toxic_zone_damage_rate: f32` — energy damage per timestep in toxic zones (default: 0.01)\n- `competitor_nutrient_consumption: f32` — nutrient consumption rate for competitors (default: 0.005)\n- `zone_growth_rate: f32` — rate at which zones grow over time (default: 0.001)\n\n#### Mycelial Density + Self-Inhibition\n- `density_inhibition_enabled: bool` — enable density-based growth inhibition (default: true)\n- `density_map_resolution: usize` — resolution of density map (cells per grid unit) (default: 4)\n- `density_inhibition_threshold: f32` — density threshold above which growth is inhibited (default: 3.0)\n- `density_inhibition_strength: f32` — how strongly density inhibits growth (0.0-1.0) (default: 0.5)\n- `density_decay_rate: f32` — rate at which density map decays over time (default: 0.99)\n\n#### Trails\n- `max_segment_age: f32` — maximum age before segments are removed (default: 10.0)\n- `segment_age_increment: f32` — how fast segments age per frame (default: 0.01)\n\n#### Fruiting\n- `fruiting_min_hyphae: usize` — minimum hyphae count to spawn fruiting bodies (default: 12)\n- `fruiting_threshold_total_energy: f32` — minimum total energy for fruiting (default: 6.0)\n- `fruiting_cooldown: f32` — cooldown between fruiting body spawns (default: 10.0)\n- `fruiting_lifespan_min: f32`, `fruiting_lifespan_max: f32` — fruiting body lifespan range (default: 12.0-20.0)\n- `fruiting_spore_count: usize` — number of spores released by fruiting bodies (default: 6)\n- `fruiting_spore_release_interval: f32` — interval between spore releases (default: 0.15)\n\n#### Network Intelligence: Signal Propagation\n- `signal_propagation_enabled: bool` — enable signal propagation (default: true)\n- `signal_decay_rate: f32` — rate at which signals decay over time (default: 0.95)\n- `signal_strength_threshold: f32` — minimum signal strength to trigger behavior (default: 0.1)\n- `signal_trigger_nutrient_threshold: f32` — nutrient threshold to trigger signals (default: 0.5)\n\n#### Network Intelligence: Adaptive Growth\n- `adaptive_growth_enabled: bool` — enable adaptive growth (default: true)\n- `flow_strengthening_rate: f32` — how fast connections strengthen with flow (default: 0.002)\n- `flow_decay_rate: f32` — how fast connection strength decays (default: 0.998)\n- `min_connection_strength: f32` — minimum connection strength (default: 0.1)\n- `pruning_threshold: f32` — prune branches with strength below this (default: 0.05)\n\n#### Network Intelligence: Memory \u0026 Learning\n- `memory_enabled: bool` — enable memory system (default: true)\n- `memory_decay_rate: f32` — rate at which memory decays over time (default: 0.995)\n- `memory_update_strength: f32` — how strongly nutrient discoveries update memory (default: 0.3)\n- `memory_influence: f32` — how much memory affects growth direction (0.0-1.0) (default: 0.15)\n\n#### Performance: Growth Limits\n- `max_hyphae: usize` — maximum number of hyphae (0 = unlimited) (default: 2000)\n- `max_hyphae_branching_threshold: usize` — stop branching when hyphae count exceeds this (default: 1500)\n\n#### Weather\n- `weather_enabled: bool` — enable weather system (default: true)\n- `weather_affects_growth: bool` — weather affects growth rate (default: true)\n- `weather_affects_energy: bool` — weather affects energy consumption (default: true)\n\n#### Seasonal Cycles\n- `seasonal_cycles_enabled: bool` — enable seasonal temperature/humidity cycles (default: true)\n  - **Spring**: Rapid growth, high humidity, frequent rains\n  - **Summer**: Drought stress, high temperature, low humidity\n  - **Autumn**: Maximum fruiting, moderate conditions\n  - **Winter**: Dormancy, cold temperature, low growth\n\n#### Soil Moisture System\n- `soil_moisture_enabled: bool` — enable soil moisture grid (default: true)\n- `moisture_diffusion_rate: f32` — rate of moisture diffusion (default: 0.02)\n- `moisture_decay_rate: f32` — rate of moisture evaporation (default: 0.999)\n- `moisture_rain_gain: f32` — moisture gain from rain (default: 0.05)\n- `moisture_growth_multiplier: f32` — how much moisture affects growth (default: 0.5)\n- `moisture_branching_multiplier: f32` — how much moisture affects branching (default: 0.3)\n- `moisture_nutrient_multiplier: f32` — how much moisture affects nutrient availability (default: 0.4)\n\n#### Light Exposure System\n- `light_exposure_enabled: bool` — enable light exposure grid (default: true)\n- `light_growth_penalty: f32` — growth penalty in bright areas (default: 0.4)\n- `shaded_zone_count: usize` — number of shaded zones (default: 8)\n- `sunlit_zone_count: usize` — number of sunlit zones (default: 5)\n\n#### Fusion\n- `fusion_enabled: bool` — enable fusion (default: true)\n- `fusion_distance: f32` — distance threshold for fusion (should be \u003c anastomosis_distance) (default: 1.0)\n- `fusion_energy_transfer: f32` — energy transfer rate when fusing (default: 0.5)\n- `fusion_min_age: f32` — minimum age for hyphae to be eligible for fusion (default: 0.1)\n\n#### Initialization\n- `initial_hyphae_count: usize` — number of hyphae at simulation start (default: 5)\n- `obstacle_count: usize` — number of obstacles in the grid (default: 300)\n\nYou can tweak these parameters to change speed, density, network behavior, and look of the simulation. Larger `grid_size` with `--release` gives smoother visuals, but uses more CPU/GPU.\n\n### Testing\n\nThe simulation includes a comprehensive test suite that can run without a graphics context:\n\n```bash\n# Run all tests\ncargo test\n\n# Run specific test\ncargo test test_validation_after_100_iterations\n\n# Run tests with output\ncargo test -- --nocapture\n```\n\n#### Test Coverage\n- **Simulation Creation**: Verifies simulation initializes correctly\n- **Simulation Runs**: Ensures simulation runs without panicking\n- **Hyphae Validation**: Checks energy levels, positions, and bounds\n- **Connections Validation**: Validates connection references and strengths\n- **Nutrients**: Verifies nutrient consumption and regeneration\n- **Memory**: Tests memory system when enabled\n- **Growth Limits**: Ensures max_hyphae limit is respected\n- **Weather**: Validates weather system updates\n- **Statistics**: Checks simulation statistics are accurate\n- **Long Simulation**: Runs 1000 steps to ensure stability\n- **Segments**: Validates segment aging\n- **Branching**: Tests branching behavior\n- **Fusion**: Tests fusion when enabled\n- **Validation**: Comprehensive validation after 100 iterations\n\n### Notes\n\n- Reflection flips direction on the axis of impact and adds jitter to avoid sticking.\n- Nutrients only decay via local consumption by hyphae; a diffusion step spreads nutrients.\n- Obstacles can be enabled in the grid; tips reflect and re-steer when colliding.\n- Weather conditions change dynamically, affecting growth, energy, and nutrient diffusion.\n- Memory system allows hyphae to remember and return to productive nutrient locations.\n- Adaptive growth strengthens efficient paths and prunes weak branches automatically.\n- Fusion merges very close hyphae, combining their energy and characteristics.\n\n### Architecture\n\nThe simulation is organized into several modules:\n\n- **`simulation.rs`** — Core simulation logic with `Simulation`, `SimulationState`, and `SimulationConfig` structs. Includes test suite.\n- **`config.rs`** — Configuration struct with all simulation parameters\n- **`hypha.rs`** — Hypha struct and behavior\n- **`spore.rs`** — Spore struct and behavior\n- **`nutrients.rs`** — Nutrient grid and gradient calculations\n- **`visualization.rs`** — All drawing functions with enhanced visualization options (UI mode only)\n- **`controls.rs`** — Input handling and control text (UI mode only)\n- **`types.rs`** — Shared types (Connection, Segment, FruitBody, Vec2)\n- **`weather.rs`** — Weather system with temperature, humidity, and rain\n- **`camera.rs`** — Camera system for pan/zoom functionality (UI mode only)\n- **`api.rs`** — HTTP API server for headless mode with REST endpoints\n- **`main.rs`** — Main entry point, supports both UI and headless modes\n\nThe `Simulation` struct contains:\n- `state: SimulationState` — All mutable simulation data (nutrients, hyphae, spores, connections, memory, weather, etc.)\n- `config: SimulationConfig` — All configuration parameters\n- Control flags (`paused`, `connections_visible`, `minimap_visible`, `memory_visible`, `enhanced_visualization`, etc.)\n- `camera: Camera` — Camera for pan/zoom (when enabled)\n\n### Troubleshooting\n\n#### UI Mode\n- If the window is too large, lower `grid_size` or `cell_size` in the config.\n- If performance is low, use `cargo run --release` and/or reduce `grid_size`. You can also toggle connections (X), minimap (M), enhanced visualization (V), or lower `max_segment_age`.\n- If trails overwhelm the scene, reduce `max_segment_age` or increase `segment_age_increment` in the config.\n- If hyphae grow too fast, reduce `branch_prob` or enable growth limits (`max_hyphae`).\n- If memory overlay is not visible, ensure `memory_enabled` is true and wait for hyphae to discover nutrients (memory accumulates over time).\n- If camera is not working, ensure `camera_enabled` is true in the config.\n\n#### Headless Mode\n- If the API server doesn't start, check that the port isn't already in use: `lsof -i :8080`\n- If you get connection refused, ensure the server is running and check the port number\n- The simulation runs automatically in the background - you don't need to call `/step` unless you want manual control\n- Use `POST /pause` to pause the automatic simulation loop\n- The simulation respects the pause state, so paused simulations won't advance automatically\n\n#### General\n- If tests fail, check that all dependencies are installed: `cargo test --no-run` to verify compilation.\n- For headless mode without UI dependencies: `cargo run --no-default-features -- --headless`\n- For headless mode with UI features available: `cargo run --features ui -- --headless`\n\n### License\n\nMIT — see `LICENSE` if present, or adapt for personal use.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fezeoleaf%2Fmycorust","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fezeoleaf%2Fmycorust","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fezeoleaf%2Fmycorust/lists"}