Skip to main content

phase4_workflow/
phase4_workflow.rs

1//! Phase 4 Complete Workflow Demo
2//!
3//! Demonstrates combining all Phase 4 features in a comprehensive workflow
4
5use terrain_forge::{
6    algorithms::{
7        Bsp, PrefabConfig, PrefabData, PrefabLibrary, PrefabPlacer, Wfc, WfcConfig,
8        WfcPatternExtractor,
9    },
10    analysis::{DelaunayTriangulation, Graph, GraphAnalysis, Point},
11    Algorithm, Grid, Tile,
12};
13
14fn main() {
15    println!("=== Phase 4 Complete Workflow Demo ===\n");
16
17    // Step 1: Generate base layout with BSP
18    println!("1. Generating Base Layout:");
19    let mut base_grid = Grid::new(35, 25);
20    let bsp = Bsp::default();
21    bsp.generate(&mut base_grid, 12345);
22
23    let base_floors = base_grid.count(|t| t.is_floor());
24    println!(
25        "   Generated {}x{} base layout with {} floors",
26        base_grid.width(),
27        base_grid.height(),
28        base_floors
29    );
30
31    // Step 2: Learn patterns from base layout
32    println!("\n2. Learning Patterns from Base Layout:");
33    let learned_patterns = WfcPatternExtractor::extract_patterns(&base_grid, 3);
34    println!(
35        "   Extracted {} unique 3x3 patterns",
36        learned_patterns.len()
37    );
38
39    // Step 3: Generate enhanced areas with WFC
40    println!("\n3. Generating Enhanced Areas with Learned Patterns:");
41    let mut wfc_grid = Grid::new(20, 15);
42    let wfc = Wfc::new(WfcConfig {
43        floor_weight: 0.45,
44        pattern_size: 3,
45        enable_backtracking: true,
46    });
47    wfc.generate_with_patterns(&mut wfc_grid, learned_patterns.clone(), 54321);
48
49    let wfc_floors = wfc_grid.count(|t| t.is_floor());
50    println!(
51        "   WFC generated {} floors with learned patterns",
52        wfc_floors
53    );
54
55    // Step 4: Find room centers for connectivity analysis
56    println!("\n4. Analyzing Room Connectivity:");
57    let room_centers = find_room_centers(&base_grid);
58    println!("   Identified {} room centers", room_centers.len());
59
60    // Step 5: Create optimal connections with Delaunay + MST
61    println!("\n5. Creating Optimal Room Connections:");
62    if room_centers.len() >= 3 {
63        let triangulation = DelaunayTriangulation::new(room_centers.clone());
64        let mst_edges = triangulation.minimum_spanning_tree();
65
66        println!("   Delaunay triangulation:");
67        println!("     Triangles: {}", triangulation.triangles.len());
68        println!("     All edges: {}", triangulation.edges.len());
69
70        println!("   Minimum spanning tree:");
71        println!("     Optimal edges: {}", mst_edges.len());
72
73        let total_length: f32 = mst_edges
74            .iter()
75            .map(|edge| edge.length(&triangulation.points))
76            .sum();
77        println!("     Total corridor length: {:.1}", total_length);
78
79        // Graph analysis
80        let graph = Graph::new(triangulation.points.clone(), mst_edges);
81        let analysis = GraphAnalysis::analyze(&graph);
82
83        println!("   Connectivity analysis:");
84        println!("     Connected: {}", analysis.is_connected);
85        println!("     Diameter: {:.1}", analysis.diameter);
86        println!("     Clustering: {:.3}", analysis.average_clustering);
87    } else {
88        println!("   Not enough rooms for connectivity analysis");
89    }
90
91    // Step 6: Create specialized prefab library
92    println!("\n6. Creating Specialized Prefab Library:");
93    let library = create_specialized_library();
94
95    println!(
96        "   Created library with {} prefabs:",
97        library.get_prefabs().len()
98    );
99    for prefab in library.get_prefabs() {
100        println!(
101            "     - {} (weight: {:.1}, tags: {:?})",
102            prefab.name, prefab.weight, prefab.tags
103        );
104    }
105
106    // Step 7: Place special features with advanced prefabs
107    println!("\n7. Placing Special Features:");
108    let mut feature_grid = Grid::new(30, 20);
109
110    // Place boss rooms (rare, large)
111    let boss_config = PrefabConfig {
112        max_prefabs: 1,
113        min_spacing: 8,
114        allow_rotation: false,
115        allow_mirroring: false,
116        weighted_selection: true,
117        placement_mode: terrain_forge::algorithms::PrefabPlacementMode::Overwrite,
118        tags: None,
119    };
120
121    let boss_placer = PrefabPlacer::new(boss_config, library.clone());
122    boss_placer.generate(&mut feature_grid, 98765);
123
124    // Place treasure rooms (medium rarity)
125    let treasure_config = PrefabConfig {
126        max_prefabs: 2,
127        min_spacing: 5,
128        allow_rotation: true,
129        allow_mirroring: true,
130        weighted_selection: true,
131        placement_mode: terrain_forge::algorithms::PrefabPlacementMode::Overwrite,
132        tags: None,
133    };
134
135    let treasure_placer = PrefabPlacer::new(treasure_config, library.clone());
136    treasure_placer.generate(&mut feature_grid, 13579);
137
138    let feature_floors = feature_grid.count(|t| t.is_floor());
139    println!("   Placed special features: {} floor tiles", feature_floors);
140
141    // Step 8: Performance and quality metrics
142    println!("\n8. Performance and Quality Metrics:");
143
144    // WFC performance
145    let start = std::time::Instant::now();
146    let mut perf_grid = Grid::new(25, 20);
147    wfc.generate_with_patterns(&mut perf_grid, learned_patterns.clone(), 24680);
148    let wfc_time = start.elapsed();
149
150    // Prefab performance
151    let start = std::time::Instant::now();
152    let placer = PrefabPlacer::new(PrefabConfig::default(), library.clone());
153    let mut prefab_grid = Grid::new(25, 20);
154    placer.generate(&mut prefab_grid, 24680);
155    let prefab_time = start.elapsed();
156
157    // Delaunay performance
158    let start = std::time::Instant::now();
159    let _ = DelaunayTriangulation::new(room_centers.clone());
160    let delaunay_time = start.elapsed();
161
162    println!("   Performance metrics:");
163    println!("     WFC generation: {:?}", wfc_time);
164    println!("     Prefab placement: {:?}", prefab_time);
165    println!("     Delaunay triangulation: {:?}", delaunay_time);
166
167    // Step 9: Quality comparison
168    println!("\n9. Quality Comparison:");
169
170    // Basic generation
171    let mut basic_grid = Grid::new(25, 20);
172    bsp.generate(&mut basic_grid, 11111);
173    let basic_floors = basic_grid.count(|t| t.is_floor());
174
175    // Enhanced generation (WFC + prefabs)
176    let enhanced_floors = perf_grid.count(|t| t.is_floor()) + prefab_grid.count(|t| t.is_floor());
177
178    println!("   Floor tile comparison:");
179    println!(
180        "     Basic BSP: {} floors ({:.1}%)",
181        basic_floors,
182        100.0 * basic_floors as f32 / (25 * 20) as f32
183    );
184    println!(
185        "     Enhanced (WFC + Prefabs): {} floors ({:.1}%)",
186        enhanced_floors,
187        100.0 * enhanced_floors as f32 / (50 * 20) as f32
188    );
189
190    // Step 10: Save configuration for reuse
191    println!("\n10. Saving Configuration:");
192    match library.save_to_json("phase4_library.json") {
193        Ok(()) => println!("   āœ… Saved prefab library to phase4_library.json"),
194        Err(e) => println!("   āŒ Failed to save library: {}", e),
195    }
196
197    println!("\nāœ… Phase 4 complete workflow finished!");
198    println!("   Workflow summary:");
199    println!("   1. Generated base layout with BSP algorithm");
200    println!(
201        "   2. Learned {} patterns for WFC enhancement",
202        learned_patterns.len()
203    );
204    println!(
205        "   3. Analyzed {} room connections with Delaunay triangulation",
206        room_centers.len()
207    );
208    println!("   4. Placed specialized features with weighted prefab selection");
209    println!("   5. Achieved optimal room connectivity with MST");
210    println!("   6. Demonstrated pattern learning and constraint propagation");
211    println!("   \n   Phase 4 features enable:");
212    println!("   - Intelligent pattern-based generation");
213    println!("   - Mathematically optimal room connections");
214    println!("   - Flexible, reusable prefab systems");
215    println!("   - Advanced graph analysis for level design");
216}
217
218fn find_room_centers(grid: &Grid<Tile>) -> Vec<Point> {
219    let mut centers = Vec::new();
220    let mut visited = vec![vec![false; grid.width()]; grid.height()];
221
222    for y in 0..grid.height() {
223        for x in 0..grid.width() {
224            if !visited[y][x] {
225                if let Some(tile) = grid.get(x as i32, y as i32) {
226                    if tile.is_floor() {
227                        let center = find_room_center(grid, &mut visited, x, y);
228                        centers.push(center);
229                    }
230                }
231            }
232        }
233    }
234
235    centers
236}
237
238fn find_room_center(
239    grid: &Grid<Tile>,
240    visited: &mut [Vec<bool>],
241    start_x: usize,
242    start_y: usize,
243) -> Point {
244    let mut room_cells = Vec::new();
245    let mut stack = vec![(start_x, start_y)];
246
247    while let Some((x, y)) = stack.pop() {
248        if visited[y][x] {
249            continue;
250        }
251        visited[y][x] = true;
252        room_cells.push((x, y));
253
254        for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
255            let nx = x as i32 + dx;
256            let ny = y as i32 + dy;
257
258            if nx >= 0 && ny >= 0 && (nx as usize) < grid.width() && (ny as usize) < grid.height() {
259                let nx = nx as usize;
260                let ny = ny as usize;
261
262                if !visited[ny][nx] {
263                    if let Some(tile) = grid.get(nx as i32, ny as i32) {
264                        if tile.is_floor() {
265                            stack.push((nx, ny));
266                        }
267                    }
268                }
269            }
270        }
271    }
272
273    // Calculate centroid
274    let sum_x: usize = room_cells.iter().map(|(x, _)| x).sum();
275    let sum_y: usize = room_cells.iter().map(|(_, y)| y).sum();
276    let count = room_cells.len();
277
278    Point::new(sum_x as f32 / count as f32, sum_y as f32 / count as f32)
279}
280
281fn create_specialized_library() -> PrefabLibrary {
282    let mut library = PrefabLibrary::new();
283
284    // Boss room (very rare, large)
285    let boss_room = PrefabData {
286        name: "boss_chamber".to_string(),
287        width: 9,
288        height: 7,
289        pattern: vec![
290            "#########".to_string(),
291            "#.......#".to_string(),
292            "#..###..#".to_string(),
293            "#..#B#..#".to_string(),
294            "#..###..#".to_string(),
295            "#.......#".to_string(),
296            "#########".to_string(),
297        ],
298        weight: 0.2,
299        tags: vec![
300            "boss".to_string(),
301            "special".to_string(),
302            "large".to_string(),
303        ],
304        legend: None,
305    };
306    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(boss_room));
307
308    // Treasure room (rare)
309    let treasure_room = PrefabData {
310        name: "treasure_vault".to_string(),
311        width: 5,
312        height: 5,
313        pattern: vec![
314            "#####".to_string(),
315            "#...#".to_string(),
316            "#.T.#".to_string(),
317            "#...#".to_string(),
318            "#####".to_string(),
319        ],
320        weight: 0.8,
321        tags: vec![
322            "treasure".to_string(),
323            "special".to_string(),
324            "small".to_string(),
325        ],
326        legend: None,
327    };
328    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(treasure_room));
329
330    // Secret passage (uncommon)
331    let secret_passage = PrefabData {
332        name: "secret_passage".to_string(),
333        width: 3,
334        height: 7,
335        pattern: vec![
336            "###".to_string(),
337            "#.#".to_string(),
338            "#.#".to_string(),
339            "#.#".to_string(),
340            "#.#".to_string(),
341            "#.#".to_string(),
342            "###".to_string(),
343        ],
344        weight: 1.2,
345        tags: vec!["secret".to_string(), "corridor".to_string()],
346        legend: None,
347    };
348    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(secret_passage));
349
350    library
351}