Prefab

Struct Prefab 

Source
pub struct Prefab {
    pub name: String,
    pub width: usize,
    pub height: usize,
    pub data: Vec<bool>,
    pub weight: f32,
    pub tags: Vec<String>,
}

Fields§

§name: String§width: usize§height: usize§data: Vec<bool>§weight: f32§tags: Vec<String>

Implementations§

Source§

impl Prefab

Source

pub fn new(pattern: &[&str]) -> Self

Source

pub fn from_data(data: PrefabData) -> Self

Examples found in repository?
examples/phase4_workflow.rs (line 301)
277fn create_specialized_library() -> PrefabLibrary {
278    let mut library = PrefabLibrary::new();
279
280    // Boss room (very rare, large)
281    let boss_room = PrefabData {
282        name: "boss_chamber".to_string(),
283        width: 9,
284        height: 7,
285        pattern: vec![
286            "#########".to_string(),
287            "#.......#".to_string(),
288            "#..###..#".to_string(),
289            "#..#B#..#".to_string(),
290            "#..###..#".to_string(),
291            "#.......#".to_string(),
292            "#########".to_string(),
293        ],
294        weight: 0.2,
295        tags: vec![
296            "boss".to_string(),
297            "special".to_string(),
298            "large".to_string(),
299        ],
300    };
301    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(boss_room));
302
303    // Treasure room (rare)
304    let treasure_room = PrefabData {
305        name: "treasure_vault".to_string(),
306        width: 5,
307        height: 5,
308        pattern: vec![
309            "#####".to_string(),
310            "#...#".to_string(),
311            "#.T.#".to_string(),
312            "#...#".to_string(),
313            "#####".to_string(),
314        ],
315        weight: 0.8,
316        tags: vec![
317            "treasure".to_string(),
318            "special".to_string(),
319            "small".to_string(),
320        ],
321    };
322    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(treasure_room));
323
324    // Secret passage (uncommon)
325    let secret_passage = PrefabData {
326        name: "secret_passage".to_string(),
327        width: 3,
328        height: 7,
329        pattern: vec![
330            "###".to_string(),
331            "#.#".to_string(),
332            "#.#".to_string(),
333            "#.#".to_string(),
334            "#.#".to_string(),
335            "#.#".to_string(),
336            "###".to_string(),
337        ],
338        weight: 1.2,
339        tags: vec!["secret".to_string(), "corridor".to_string()],
340    };
341    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(secret_passage));
342
343    library
344}
More examples
Hide additional examples
examples/advanced_prefabs.rs (line 205)
187fn create_sample_library() -> PrefabLibrary {
188    let mut library = PrefabLibrary::new();
189
190    // Small room (high weight)
191    let small_room = PrefabData {
192        name: "small_room".to_string(),
193        width: 5,
194        height: 5,
195        pattern: vec![
196            "#####".to_string(),
197            "#...#".to_string(),
198            "#...#".to_string(),
199            "#...#".to_string(),
200            "#####".to_string(),
201        ],
202        weight: 3.0,
203        tags: vec!["room".to_string(), "small".to_string()],
204    };
205    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(small_room));
206
207    // Large room (medium weight)
208    let large_room = PrefabData {
209        name: "large_room".to_string(),
210        width: 7,
211        height: 6,
212        pattern: vec![
213            "#######".to_string(),
214            "#.....#".to_string(),
215            "#.....#".to_string(),
216            "#.....#".to_string(),
217            "#.....#".to_string(),
218            "#######".to_string(),
219        ],
220        weight: 1.5,
221        tags: vec!["room".to_string(), "large".to_string()],
222    };
223    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(large_room));
224
225    // Corridor (low weight)
226    let corridor = PrefabData {
227        name: "corridor".to_string(),
228        width: 7,
229        height: 3,
230        pattern: vec![
231            "#######".to_string(),
232            ".......".to_string(),
233            "#######".to_string(),
234        ],
235        weight: 0.8,
236        tags: vec!["corridor".to_string(), "connection".to_string()],
237    };
238    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(corridor));
239
240    // L-shaped room (rare)
241    let l_room = PrefabData {
242        name: "l_shaped_room".to_string(),
243        width: 6,
244        height: 6,
245        pattern: vec![
246            "######".to_string(),
247            "#....#".to_string(),
248            "#....#".to_string(),
249            "#..###".to_string(),
250            "#..###".to_string(),
251            "######".to_string(),
252        ],
253        weight: 0.5,
254        tags: vec![
255            "room".to_string(),
256            "special".to_string(),
257            "l_shaped".to_string(),
258        ],
259    };
260    library.add_prefab(terrain_forge::algorithms::Prefab::from_data(l_room));
261
262    library
263}
Source

pub fn rect(w: usize, h: usize) -> Self

Source

pub fn rotated(&self) -> Self

Rotate prefab 90 degrees clockwise

Examples found in repository?
examples/advanced_prefabs.rs (line 69)
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}
Source

pub fn mirrored_horizontal(&self) -> Self

Mirror prefab horizontally

Examples found in repository?
examples/advanced_prefabs.rs (line 77)
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}
Source

pub fn mirrored_vertical(&self) -> Self

Mirror prefab vertically

Source

pub fn get(&self, x: usize, y: usize) -> bool

Examples found in repository?
examples/advanced_prefabs.rs (line 269)
265fn print_prefab_pattern(prefab: &terrain_forge::algorithms::Prefab) {
266    for y in 0..prefab.height {
267        print!("     ");
268        for x in 0..prefab.width {
269            print!("{}", if prefab.get(x, y) { "." } else { "#" });
270        }
271        println!();
272    }
273}
Source

pub fn has_tag(&self, tag: &str) -> bool

Trait Implementations§

Source§

impl Clone for Prefab

Source§

fn clone(&self) -> Prefab

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Prefab

§

impl RefUnwindSafe for Prefab

§

impl Send for Prefab

§

impl Sync for Prefab

§

impl Unpin for Prefab

§

impl UnwindSafe for Prefab

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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