{"id":26742798,"url":"https://github.com/murapadev/hamc","last_synced_at":"2025-04-14T18:10:26.153Z","repository":{"id":280515201,"uuid":"942145855","full_name":"murapadev/HAMC","owner":"murapadev","description":"HAMC (Hierarchical Adaptive Model Collapse) is an implementation of procedural content generation that combines different texture generations methods.","archived":false,"fork":false,"pushed_at":"2025-03-10T18:49:57.000Z","size":46,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-28T06:33:39.221Z","etag":null,"topics":["connectivity-constraints","content-generation","entropy-based","game-development","generative-algorithms","hierarchical-generation","map-generation","multi-level-generation","pcg","procedural-generation","python","terrain-generation","wave-function-collapse","weighted-generation","wfc"],"latest_commit_sha":null,"homepage":"","language":"Python","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/murapadev.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}},"created_at":"2025-03-03T16:41:24.000Z","updated_at":"2025-03-18T22:39:28.000Z","dependencies_parsed_at":"2025-03-03T21:32:44.735Z","dependency_job_id":"038d6f29-03e7-485d-9a7f-e63544789ed0","html_url":"https://github.com/murapadev/HAMC","commit_stats":null,"previous_names":["murapa96/hamc","murapadev/hamc"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/murapadev%2FHAMC","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/murapadev%2FHAMC/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/murapadev%2FHAMC/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/murapadev%2FHAMC/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/murapadev","download_url":"https://codeload.github.com/murapadev/HAMC/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248933340,"owners_count":21185460,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["connectivity-constraints","content-generation","entropy-based","game-development","generative-algorithms","hierarchical-generation","map-generation","multi-level-generation","pcg","procedural-generation","python","terrain-generation","wave-function-collapse","weighted-generation","wfc"],"created_at":"2025-03-28T06:31:56.816Z","updated_at":"2025-04-14T18:10:26.119Z","avatar_url":"https://github.com/murapadev.png","language":"Python","readme":"# Hierarchical Adaptive Model Collapse (HAMC)\n\n## Overview\n\nThis repository contains a multi-level procedural content generation system that combines:\n\n- **Wave Function Collapse (WFC)** with weighted options to prioritize certain elements\n- **Content hierarchies** (global regions, intermediate blocks, and local tiles)\n- **Connectivity constraints** specifically for rivers, roads, and other special structures\n- **Adaptive backtracking** for better handling of generation failures\n\nThe approach is inspired by a hierarchical generative model where each level (Global, Intermediate, and Local) collapses its cells using a WFC-like method with distinct rules, weights, and constraints.\n\n## Features\n\n- **Hierarchical Generation**: Three distinct layers with their own rules and constraints\n- **Weighted Options**: Probabilistic selection based on configured weights\n- **Shannon Entropy Calculation**: More intelligent cell selection during collapse\n- **Path Validation**: Special validation for rivers and roads to ensure connectivity\n- **Special Block Types**: Customized generation for specific block types (oasis, buildings, etc.)\n- **Transition Zones**: Smooth transitions between different region types\n- **Visualization**: Renders the generated world at all levels of detail\n- **Adaptive Backtracking**: Intelligent backtracking to recover from generation failures\n\n## Technical Approach\n\nThe system is divided into **three hierarchical layers**:\n\n1. **Global Layer:**  \n   Assigns **regions** (e.g., \"bosque\", \"desierto\", \"ciudad\") to cells in a large grid. Defines global-level compatibility rules for region adjacency.\n   - Uses a dictionary `{region: probability}` to handle **weights** of each region.\n\n2. **Intermediate Layer:**  \n   Each global cell is subdivided into a `subgrid` with **blocks** (e.g., \"arboleda\", \"arena\", \"residencial\"). \n   - Includes **transition blocks** (e.g., \"matorral\", \"periurbano\") to smooth boundaries between different regions.\n   - Defines compatibility rules between blocks and includes **weights** (appearance preferences).\n\n3. **Local Layer (Tilemap):**  \n   For each block, generates a small tilemap (e.g., \"Hierba\", \"Agua\", \"Arena\", \"Asfalto\") using a local WFC with its own rules and **weights**.\n   - Incorporates **connectivity constraints**, such as requiring a \"rio\" block to have a vertical \"Agua\" path, or a \"carretera\" block to have a horizontal \"Asfalto/Linea\" path.\n   - Special blocks like \"oasis\" have center-focused water distribution.\n\nAt each level, a \"collapse and propagation\" algorithm is applied with an **entropy function** based on the **weights** of each option (using *Shannon entropy*). When a cell collapses, constraints propagate to neighboring cells, eliminating incompatible options.\n\n## Project Structure\n\n```\n.\n├── main.py                           # Main entry point\n├── hamc/                             # Core package\n│   ├── config/                       # Configuration files\n│   │   ├── block_config.py           # Intermediate blocks config\n│   │   ├── generator_config.py       # Generator parameters\n│   │   ├── region_config.py          # Global regions config\n│   │   └── tile_config.py            # Local tiles config\n│   ├── core/                         # Core functionality\n│   │   ├── backtrack_manager.py      # Advanced backtracking system\n│   │   ├── cell.py                   # Cell class\n│   │   ├── compatibility_cache.py    # Caching for compatibility checks\n│   │   ├── entropy.py                # Entropy calculations\n│   │   ├── generator_state.py        # Generator state management\n│   │   ├── pattern_detector.py       # Pattern recognition utilities\n│   │   └── validator.py              # Path and structure validation\n│   ├── generators/                   # Generator implementations\n│   │   ├── base_generator.py         # Abstract base generator\n│   │   ├── global_generator.py       # Global level generator\n│   │   ├── intermediate_generator.py # Intermediate level generator\n│   │   ├── local_generator.py        # Local level generator\n│   │   └── parallel_generator.py     # Multi-threaded generator\n│   └── visualization/                # Visualization utilities\n│       └── renderer.py               # Rendering to images\n├── tests/                            # Test suite\n│   ├── __init__.py\n│   └── test_generators.py            # Generator tests\n├── run_tests.py                      # Test runner with coverage\n└── setup.py                          # Package installation script\n```\n\n## Key Components\n\n### Cell Class\nEach level uses a `Cell` class that maintains:\n- A dictionary of possible values with weights\n- Methods for calculating entropy and collapsing to a single value\n- Tracking of collapsed state and probability distribution\n\n### Generation Layers\n\n- **BaseGenerator**: Abstract base class with common WFC functionality\n  - Common backtracking mechanism\n  - Snapshot and restore capabilities\n  - Status tracking and logging\n\n- **GlobalGenerator**: Manages the grid of global cells (regions)\n  - Region compatibility enforcement\n  - Ensures all required region types appear\n  - Biome distribution validation\n\n- **IntermediateGenerator**: Manages the intermediate grid of blocks\n  - Subdivides each region into blocks\n  - Handles transition zones between different region types\n  - Special block compatibility rules\n\n- **LocalGenerator**: Manages the generation of local tilemaps\n  - Path validation for rivers and roads\n  - Special initialization for different block types\n  - Connectivity constraints\n  - Optimized constraint propagation\n\n### Special Block Handling\n\n- **River blocks**: Maintain continuous vertical water paths with validation\n- **Road blocks**: Maintain continuous horizontal asphalt paths\n- **Oasis blocks**: Create water concentration in the center with sand transitions\n- **Building blocks**: Generate structured residential, commercial, or industrial layouts\n\n### Backtracking System\n\nThe `BacktrackManager` provides sophisticated backtracking capabilities:\n- Priority-based backtrack point selection\n- Adaptive strategies based on success rates\n- Failed value tracking to avoid repeating errors\n- Level-aware backtracking to optimize performance\n\n## Usage\n\n1. **Install dependencies**\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n2. **Run the generator**\n   ```bash\n   python main.py [--width WIDTH] [--height HEIGHT] [--subgrid SUBGRID] [--local LOCAL] [--seed SEED] [--output OUTPUT] [--debug]\n   ```\n\n   Parameters:\n   - `--width`: Global map width (default: 3)\n   - `--height`: Global map height (default: 3)\n   - `--subgrid`: Intermediate subgrid size (default: 2)\n   - `--local`: Local block size (default: 4)\n   - `--seed`: Random seed for reproducible generation\n   - `--output`: Output directory (default: 'output')\n   - `--debug`: Enable debug logging\n\n3. **Output**\n   The script generates multiple visualization images in the specified output directory:\n   - `global_level.png`: The global regions map\n   - `intermediate_level.png`: The intermediate blocks map  \n   - `complete_map.png`: The final detailed tilemap with grid overlays\n   - `complete_tilemap_clean.png`: The final tilemap without grid overlays\n   - `local_blocks/`: Individual local block tilemaps\n   - Various JSON files with the raw map data\n\n## Running Tests\n\nTests can be run with the included test runner:\n\n```bash\npython run_tests.py\n```\n\nThe test suite validates:\n- Cell initialization and entropy calculation\n- Proper block and region compatibility\n- Path validation for special blocks\n- Collapse and propagation mechanisms\n\n## Customization\n\nYou can customize the generation by modifying:\n\n- **Configurations**: Edit files in the `hamc/config/` directory to change probabilities, compatibility rules, and available elements\n- **Generator parameters**: Adjust map sizes, subgrid divisions, and other parameters in `main.py`\n- **Connectivity constraints**: Modify validation methods in `validator.py` to add specific constraints\n\n## Future Enhancements\n\n- Better performance for large-scale maps\n- Additional special block types and constraints\n- User interface for real-time generation visualization\n- Integration with game engines\n- Cross-level constraint propagation\n\n## References\n\nThis implementation is inspired by the Wave Function Collapse algorithm and hierarchical procedural generation techniques used in modern game development.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmurapadev%2Fhamc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmurapadev%2Fhamc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmurapadev%2Fhamc/lists"}