PrefabPlacer

Struct PrefabPlacer 

Source
pub struct PrefabPlacer { /* private fields */ }

Implementations§

Source§

impl PrefabPlacer

Source

pub fn new(config: PrefabConfig, library: PrefabLibrary) -> Self

Examples found in repository?
examples/advanced_prefabs.rs (line 108)
10fn main() {
11    println!("=== Advanced Prefab System Demo ===\n");
12
13    // Step 1: Create prefab library programmatically
14    println!("1. Creating Prefab Library:");
15    let library = create_sample_library();
16
17    println!(
18        "   Created library with {} prefabs:",
19        library.get_prefabs().len()
20    );
21    for prefab in library.get_prefabs() {
22        println!(
23            "     - {} ({}x{}, weight: {:.1}, tags: {:?})",
24            prefab.name, prefab.width, prefab.height, prefab.weight, prefab.tags
25        );
26    }
27
28    // Step 2: Demonstrate weighted selection
29    println!("\n2. Weighted Selection Test:");
30    let mut rng = Rng::new(12345);
31    let mut selection_counts = std::collections::HashMap::new();
32
33    for _ in 0..100 {
34        if let Some(prefab) = library.select_weighted(&mut rng, None) {
35            *selection_counts.entry(prefab.name.clone()).or_insert(0) += 1;
36        }
37    }
38
39    println!("   Selection frequency (100 trials):");
40    for (name, count) in &selection_counts {
41        println!("     {}: {} times", name, count);
42    }
43
44    // Step 3: Tag-based selection
45    println!("\n3. Tag-based Selection:");
46    let room_prefabs = library.get_by_tag("room");
47    let corridor_prefabs = library.get_by_tag("corridor");
48
49    println!("   Room prefabs: {}", room_prefabs.len());
50    for prefab in &room_prefabs {
51        println!("     - {}", prefab.name);
52    }
53
54    println!("   Corridor prefabs: {}", corridor_prefabs.len());
55    for prefab in &corridor_prefabs {
56        println!("     - {}", prefab.name);
57    }
58
59    // Step 4: Transformation examples
60    println!("\n4. Prefab Transformations:");
61    if let Some(base_prefab) = library.get_prefabs().first() {
62        println!(
63            "   Base prefab '{}' ({}x{}):",
64            base_prefab.name, base_prefab.width, base_prefab.height
65        );
66        print_prefab_pattern(base_prefab);
67
68        // Rotation
69        let rotated = base_prefab.rotated();
70        println!(
71            "   After 90° rotation ({}x{}):",
72            rotated.width, rotated.height
73        );
74        print_prefab_pattern(&rotated);
75
76        // Horizontal mirror
77        let mirrored = base_prefab.mirrored_horizontal();
78        println!(
79            "   After horizontal mirror ({}x{}):",
80            mirrored.width, mirrored.height
81        );
82        print_prefab_pattern(&mirrored);
83
84        // Combined transformation
85        let transform = PrefabTransform {
86            rotation: 1,
87            mirror_h: true,
88            mirror_v: false,
89        };
90        let transformed = transform.apply(base_prefab);
91        println!(
92            "   After rotation + mirror ({}x{}):",
93            transformed.width, transformed.height
94        );
95        print_prefab_pattern(&transformed);
96    }
97
98    // Step 5: Generation with advanced prefabs
99    println!("\n5. Generation with Advanced Prefabs:");
100    let config = PrefabConfig {
101        max_prefabs: 5,
102        min_spacing: 3,
103        allow_rotation: true,
104        allow_mirroring: true,
105        weighted_selection: true,
106    };
107
108    let placer = PrefabPlacer::new(config, library.clone());
109    let mut grid = Grid::new(30, 25);
110    placer.generate(&mut grid, 54321);
111
112    let floor_count = grid.count(|t| t.is_floor());
113    println!(
114        "   Generated {}x{} grid with {} floor tiles",
115        grid.width(),
116        grid.height(),
117        floor_count
118    );
119
120    print_grid(&grid);
121
122    // Step 6: JSON serialization example
123    println!("\n6. JSON Serialization:");
124    match library.save_to_json("prefab_library.json") {
125        Ok(()) => {
126            println!("   ✅ Saved library to prefab_library.json");
127
128            // Try to load it back
129            match PrefabLibrary::load_from_json("prefab_library.json") {
130                Ok(loaded_library) => {
131                    println!("   ✅ Successfully loaded library back");
132                    println!("   Loaded {} prefabs", loaded_library.get_prefabs().len());
133                }
134                Err(e) => println!("   ❌ Failed to load: {}", e),
135            }
136        }
137        Err(e) => println!("   ❌ Failed to save: {}", e),
138    }
139
140    // Step 7: Performance comparison
141    println!("\n7. Performance Comparison:");
142
143    // Simple generation
144    let simple_config = PrefabConfig {
145        max_prefabs: 10,
146        min_spacing: 2,
147        allow_rotation: false,
148        allow_mirroring: false,
149        weighted_selection: false,
150    };
151
152    let start = std::time::Instant::now();
153    let simple_placer = PrefabPlacer::new(simple_config, library.clone());
154    let mut simple_grid = Grid::new(40, 30);
155    simple_placer.generate(&mut simple_grid, 98765);
156    let simple_time = start.elapsed();
157
158    // Advanced generation
159    let advanced_config = PrefabConfig {
160        max_prefabs: 10,
161        min_spacing: 2,
162        allow_rotation: true,
163        allow_mirroring: true,
164        weighted_selection: true,
165    };
166
167    let start = std::time::Instant::now();
168    let advanced_placer = PrefabPlacer::new(advanced_config, library);
169    let mut advanced_grid = Grid::new(40, 30);
170    advanced_placer.generate(&mut advanced_grid, 98765);
171    let advanced_time = start.elapsed();
172
173    println!("   Simple generation: {:?}", simple_time);
174    println!("   Advanced generation: {:?}", advanced_time);
175    println!(
176        "   Overhead: {:.1}x",
177        advanced_time.as_nanos() as f32 / simple_time.as_nanos() as f32
178    );
179
180    println!("\n✅ Advanced prefab system demo complete!");
181    println!("   - JSON serialization for persistent libraries");
182    println!("   - Weighted selection for balanced generation");
183    println!("   - Transformations for variety and reuse");
184    println!("   - Tag-based organization for targeted selection");
185}
More examples
Hide additional examples
examples/phase4_workflow.rs (line 119)
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    };
118
119    let boss_placer = PrefabPlacer::new(boss_config, library.clone());
120    boss_placer.generate(&mut feature_grid, 98765);
121
122    // Place treasure rooms (medium rarity)
123    let treasure_config = PrefabConfig {
124        max_prefabs: 2,
125        min_spacing: 5,
126        allow_rotation: true,
127        allow_mirroring: true,
128        weighted_selection: true,
129    };
130
131    let treasure_placer = PrefabPlacer::new(treasure_config, library.clone());
132    treasure_placer.generate(&mut feature_grid, 13579);
133
134    let feature_floors = feature_grid.count(|t| t.is_floor());
135    println!("   Placed special features: {} floor tiles", feature_floors);
136
137    // Step 8: Performance and quality metrics
138    println!("\n8. Performance and Quality Metrics:");
139
140    // WFC performance
141    let start = std::time::Instant::now();
142    let mut perf_grid = Grid::new(25, 20);
143    wfc.generate_with_patterns(&mut perf_grid, learned_patterns.clone(), 24680);
144    let wfc_time = start.elapsed();
145
146    // Prefab performance
147    let start = std::time::Instant::now();
148    let placer = PrefabPlacer::new(PrefabConfig::default(), library.clone());
149    let mut prefab_grid = Grid::new(25, 20);
150    placer.generate(&mut prefab_grid, 24680);
151    let prefab_time = start.elapsed();
152
153    // Delaunay performance
154    let start = std::time::Instant::now();
155    let _ = DelaunayTriangulation::new(room_centers.clone());
156    let delaunay_time = start.elapsed();
157
158    println!("   Performance metrics:");
159    println!("     WFC generation: {:?}", wfc_time);
160    println!("     Prefab placement: {:?}", prefab_time);
161    println!("     Delaunay triangulation: {:?}", delaunay_time);
162
163    // Step 9: Quality comparison
164    println!("\n9. Quality Comparison:");
165
166    // Basic generation
167    let mut basic_grid = Grid::new(25, 20);
168    bsp.generate(&mut basic_grid, 11111);
169    let basic_floors = basic_grid.count(|t| t.is_floor());
170
171    // Enhanced generation (WFC + prefabs)
172    let enhanced_floors = perf_grid.count(|t| t.is_floor()) + prefab_grid.count(|t| t.is_floor());
173
174    println!("   Floor tile comparison:");
175    println!(
176        "     Basic BSP: {} floors ({:.1}%)",
177        basic_floors,
178        100.0 * basic_floors as f32 / (25 * 20) as f32
179    );
180    println!(
181        "     Enhanced (WFC + Prefabs): {} floors ({:.1}%)",
182        enhanced_floors,
183        100.0 * enhanced_floors as f32 / (50 * 20) as f32
184    );
185
186    // Step 10: Save configuration for reuse
187    println!("\n10. Saving Configuration:");
188    match library.save_to_json("phase4_library.json") {
189        Ok(()) => println!("   ✅ Saved prefab library to phase4_library.json"),
190        Err(e) => println!("   ❌ Failed to save library: {}", e),
191    }
192
193    println!("\n✅ Phase 4 complete workflow finished!");
194    println!("   Workflow summary:");
195    println!("   1. Generated base layout with BSP algorithm");
196    println!(
197        "   2. Learned {} patterns for WFC enhancement",
198        learned_patterns.len()
199    );
200    println!(
201        "   3. Analyzed {} room connections with Delaunay triangulation",
202        room_centers.len()
203    );
204    println!("   4. Placed specialized features with weighted prefab selection");
205    println!("   5. Achieved optimal room connectivity with MST");
206    println!("   6. Demonstrated pattern learning and constraint propagation");
207    println!("   \n   Phase 4 features enable:");
208    println!("   - Intelligent pattern-based generation");
209    println!("   - Mathematically optimal room connections");
210    println!("   - Flexible, reusable prefab systems");
211    println!("   - Advanced graph analysis for level design");
212}
Source

pub fn with_library(library: PrefabLibrary) -> Self

Trait Implementations§

Source§

impl Algorithm for PrefabPlacer

Source§

fn generate(&self, grid: &mut Grid<Tile>, seed: u64)

Generate content into the grid using the given seed
Source§

fn name(&self) -> &'static str

Algorithm name for identification
Source§

impl Default for PrefabPlacer

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V