Skip to main content

yang_pcg/
config.rs

1// 配置管理模块
2// 负责定义和归一化生成配置
3
4use crate::error::{PcgError, PcgResult};
5use serde::{Deserialize, Serialize};
6
7/// 地图生成配置
8///
9/// 包含所有可配置的生成参数,支持序列化、反序列化和默认值填充。
10/// 配置采用层级合并策略:默认配置 -> 预设配置 -> 实例覆盖 -> 运行时覆盖。
11#[derive(Debug, Clone, Serialize, Deserialize)]
12#[non_exhaustive]
13pub struct GenerationConfig {
14    /// 房间数量范围
15    pub room_count: RangeU16,
16    /// 关键路径长度范围
17    pub critical_path_length: RangeU16,
18    /// 分支数量范围
19    pub branch_count: RangeU16,
20    /// 死路数量范围。
21    ///
22    /// **RESERVED(未接线)**:当前生成管线不读取该字段;修改它只会经
23    /// `ConfigDigest` 改变派生种子,不会按语义影响死路数量。
24    pub dead_end_count: RangeU16,
25    /// 房间尺寸配置
26    pub room_size: RoomSizeConfig,
27    /// 走廊配置
28    pub corridor: CorridorConfig,
29    /// 地形配置
30    pub terrain: TerrainConfig,
31    /// 交互物生成配置
32    pub item_spawns: ItemSpawnConfig,
33    /// 敌人生成配置
34    pub enemy_spawns: EnemySpawnConfig,
35    /// 分块配置
36    pub chunking: ChunkingConfig,
37    /// 主题标签列表
38    pub theme_tags: Vec<String>,
39    /// 生成模式
40    pub generation_mode: GenerationMode,
41    /// 能力开关
42    pub capability_flags: CapabilityFlags,
43}
44
45impl Default for GenerationConfig {
46    fn default() -> Self {
47        Self {
48            room_count: RangeU16 { min: 10, max: 20 },
49            critical_path_length: RangeU16 { min: 5, max: 10 },
50            branch_count: RangeU16 { min: 1, max: 3 },
51            dead_end_count: RangeU16 { min: 0, max: 2 },
52            room_size: RoomSizeConfig::default(),
53            corridor: CorridorConfig::default(),
54            terrain: TerrainConfig::default(),
55            item_spawns: ItemSpawnConfig::default(),
56            enemy_spawns: EnemySpawnConfig::default(),
57            chunking: ChunkingConfig::default(),
58            theme_tags: vec!["default".to_string()],
59            generation_mode: GenerationMode::OfflineFullFloor,
60            capability_flags: CapabilityFlags::default(),
61        }
62    }
63}
64
65impl GenerationConfig {
66    /// 归一化配置
67    ///
68    /// 验证配置的有效性,填充缺失的默认值,并返回归一化后的配置。
69    ///
70    /// # 错误
71    ///
72    /// - 当数值范围非法时返回 `PcgError::Config`
73    /// - 当存在互斥约束时返回 `PcgError::Config`
74    pub fn normalize(&self) -> PcgResult<NormalizedConfig> {
75        // 验证房间数量范围
76        if self.room_count.min > self.room_count.max {
77            return Err(PcgError::config_with_field(
78                format!(
79                    "房间数量范围非法: min({}) > max({})",
80                    self.room_count.min, self.room_count.max
81                ),
82                "room_count",
83            ));
84        }
85
86        if self.room_count.min < 2 {
87            return Err(PcgError::config_with_field(
88                "房间数量最小值不能小于 2(至少需要起点和终点)",
89                "room_count.min",
90            ));
91        }
92
93        // OPT-R-02: 房间数量上界保护,防止 OOM
94        if self.room_count.max > 4096 {
95            return Err(PcgError::config_with_field(
96                format!("房间数量最大值({})超过上限 4096", self.room_count.max),
97                "room_count.max",
98            ));
99        }
100
101        // OPT-R-02: 组合 OOM 防护 — room_count.max × max_width × max_height 乘积约束
102        let total_cells = (self.room_count.max as u64)
103            * (self.room_size.max_width as u64)
104            * (self.room_size.max_height as u64);
105        const MAX_TOTAL_CELLS: u64 = 64_000_000; // ~64 MB 原始瓦片数据
106        if total_cells > MAX_TOTAL_CELLS {
107            return Err(PcgError::config_with_field(
108                format!(
109                    "总瓦片数({} = room_count.max({})×max_width({})×max_height({}))超过上限({})",
110                    total_cells,
111                    self.room_count.max,
112                    self.room_size.max_width,
113                    self.room_size.max_height,
114                    MAX_TOTAL_CELLS,
115                ),
116                "room_count / room_size 组合",
117            ));
118        }
119
120        // 验证关键路径长度范围
121        if self.critical_path_length.min > self.critical_path_length.max {
122            return Err(PcgError::config_with_field(
123                format!(
124                    "关键路径长度范围非法: min({}) > max({})",
125                    self.critical_path_length.min, self.critical_path_length.max
126                ),
127                "critical_path_length",
128            ));
129        }
130
131        if self.critical_path_length.min < 2 {
132            return Err(PcgError::config_with_field(
133                "关键路径长度最小值不能小于 2",
134                "critical_path_length.min",
135            ));
136        }
137
138        // 验证关键路径长度不超过房间总数
139        if self.critical_path_length.min > self.room_count.max {
140            return Err(PcgError::config_with_field(
141                format!(
142                    "关键路径长度最小值({})不能超过房间总数最大值({})",
143                    self.critical_path_length.min, self.room_count.max
144                ),
145                "critical_path_length.min",
146            ));
147        }
148
149        // 验证分支数量范围
150        if self.branch_count.min > self.branch_count.max {
151            return Err(PcgError::config_with_field(
152                format!(
153                    "分支数量范围非法: min({}) > max({})",
154                    self.branch_count.min, self.branch_count.max
155                ),
156                "branch_count",
157            ));
158        }
159
160        // 验证死路数量范围
161        if self.dead_end_count.min > self.dead_end_count.max {
162            return Err(PcgError::config_with_field(
163                format!(
164                    "死路数量范围非法: min({}) > max({})",
165                    self.dead_end_count.min, self.dead_end_count.max
166                ),
167                "dead_end_count",
168            ));
169        }
170
171        // 验证房间尺寸配置
172        self.room_size.validate()?;
173
174        // 验证走廊配置
175        self.corridor.validate()?;
176
177        // 验证地形配置
178        self.terrain.validate()?;
179
180        // 验证交互物配置
181        self.item_spawns.validate()?;
182
183        // 验证敌人配置
184        self.enemy_spawns.validate()?;
185
186        // 验证分块配置
187        self.chunking.validate()?;
188
189        // 验证能力开关与生成模式的兼容性
190        if self.generation_mode == GenerationMode::RuntimeChunked
191            && !self.capability_flags.runtime_chunked
192        {
193            return Err(PcgError::config(
194                "运行时分块模式需要启用 runtime_chunked 能力开关",
195            ));
196        }
197
198        if self.generation_mode == GenerationMode::HybridPrecompute
199            && !self.capability_flags.hybrid_precompute
200        {
201            return Err(PcgError::config(
202                "混合预计算模式需要启用 hybrid_precompute 能力开关",
203            ));
204        }
205
206        // 构建归一化配置
207        Ok(NormalizedConfig {
208            config: self.clone(),
209            time_budget_ms: None,
210            iteration_budget: None,
211        })
212    }
213
214    /// 全量覆盖配置(推荐)
215    ///
216    /// 用 `other` 的所有字段**全量覆盖**当前配置,返回覆盖后的新实例。
217    /// 用于实现配置层级:默认配置 -> 预设配置 -> 实例覆盖 -> 运行时覆盖。
218    ///
219    /// 注意:此方法并非增量合并——`other` 中的所有字段(包括默认值)都会覆盖对应字段。
220    pub fn override_with(self, other: GenerationConfig) -> Self {
221        Self {
222            room_count: other.room_count,
223            critical_path_length: other.critical_path_length,
224            branch_count: other.branch_count,
225            dead_end_count: other.dead_end_count,
226            room_size: other.room_size,
227            corridor: other.corridor,
228            terrain: other.terrain,
229            item_spawns: other.item_spawns,
230            enemy_spawns: other.enemy_spawns,
231            chunking: other.chunking,
232            // theme_tags 仅在 other 非空时覆盖
233            theme_tags: if other.theme_tags.is_empty() {
234                self.theme_tags
235            } else {
236                other.theme_tags
237            },
238            generation_mode: other.generation_mode,
239            capability_flags: other.capability_flags,
240        }
241    }
242
243    /// 合并配置(全量覆盖)
244    ///
245    /// 将当前配置与另一个配置"合并"。**实际为无条件全量覆盖**——other 中的所有字段
246    /// 直接覆盖 self 对应字段(非逐字段区分默认值/非默认值的语义合并)。
247    /// 用于实现配置层级:默认配置 -> 预设配置 -> 实例覆盖 -> 运行时覆盖。
248    #[deprecated(note = "请用 override_with,此方法实为全量覆盖而非增量合并")]
249    #[allow(deprecated)]
250    pub fn merge(&self, other: &GenerationConfig) -> Self {
251        // 简化实现:直接使用 other 的值全量覆盖
252        // 未来可改为更细粒度的合并逻辑(仅覆盖非默认值)
253        let mut merged = self.clone();
254
255        // 合并房间数量范围
256        merged.room_count = other.room_count;
257        merged.critical_path_length = other.critical_path_length;
258        merged.branch_count = other.branch_count;
259        merged.dead_end_count = other.dead_end_count;
260
261        // 合并子配置
262        merged.room_size = other.room_size.clone();
263        merged.corridor = other.corridor.clone();
264        merged.terrain = other.terrain.clone();
265        merged.item_spawns = other.item_spawns.clone();
266        merged.enemy_spawns = other.enemy_spawns.clone();
267        merged.chunking = other.chunking.clone();
268
269        // 合并主题标签(直接覆盖)
270        if !other.theme_tags.is_empty() {
271            merged.theme_tags = other.theme_tags.clone();
272        }
273
274        // 合并生成模式和能力开关
275        merged.generation_mode = other.generation_mode;
276        merged.capability_flags = other.capability_flags.clone();
277
278        merged
279    }
280}
281
282/// 归一化后的配置
283///
284/// 经过验证和归一化处理的配置,保证所有字段都是有效的。
285#[derive(Debug, Clone)]
286#[non_exhaustive]
287pub struct NormalizedConfig {
288    /// 原始配置
289    pub config: GenerationConfig,
290    /// 时间预算(毫秒),超过后提前返回部分结果
291    pub time_budget_ms: Option<u64>,
292    /// 迭代预算,超过后提前返回部分结果
293    pub iteration_budget: Option<u32>,
294}
295
296impl NormalizedConfig {
297    /// 获取配置引用
298    pub fn config(&self) -> &GenerationConfig {
299        &self.config
300    }
301
302    /// 设置时间预算(毫秒)
303    pub fn with_time_budget(mut self, ms: u64) -> Self {
304        self.time_budget_ms = Some(ms);
305        self
306    }
307
308    /// 设置迭代预算
309    pub fn with_iteration_budget(mut self, iterations: u32) -> Self {
310        self.iteration_budget = Some(iterations);
311        self
312    }
313}
314
315/// 无符号 16 位整数范围
316#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
317#[non_exhaustive]
318pub struct RangeU16 {
319    pub min: u16,
320    pub max: u16,
321}
322
323impl RangeU16 {
324    /// 创建新的范围
325    pub const fn new(min: u16, max: u16) -> Self {
326        Self { min, max }
327    }
328
329    /// 判断范围是否有效(`min <= max`)。
330    ///
331    /// 外部调用方只需检查有效性时用此方法;需要携带字段路径的错误信息请用 [`validate`](Self::validate)。
332    pub const fn is_valid(&self) -> bool {
333        self.min <= self.max
334    }
335
336    /// 验证范围是否有效,无效时返回带字段路径的配置错误。
337    pub(crate) fn validate(&self, field_name: &str) -> PcgResult<()> {
338        if self.min > self.max {
339            return Err(PcgError::config_with_field(
340                format!("范围非法: min({}) > max({})", self.min, self.max),
341                field_name,
342            ));
343        }
344        Ok(())
345    }
346}
347
348/// 房间尺寸配置
349#[derive(Debug, Clone, Serialize, Deserialize)]
350#[non_exhaustive]
351pub struct RoomSizeConfig {
352    /// 最小宽度(网格单位)
353    pub min_width: u16,
354    /// 最大宽度(网格单位)
355    pub max_width: u16,
356    /// 最小高度(网格单位)
357    pub min_height: u16,
358    /// 最大高度(网格单位)
359    pub max_height: u16,
360}
361
362impl Default for RoomSizeConfig {
363    fn default() -> Self {
364        Self {
365            min_width: 8,
366            max_width: 16,
367            min_height: 8,
368            max_height: 16,
369        }
370    }
371}
372
373impl RoomSizeConfig {
374    fn validate(&self) -> PcgResult<()> {
375        if self.min_width > self.max_width {
376            return Err(PcgError::config_with_field(
377                format!(
378                    "房间宽度范围非法: min({}) > max({})",
379                    self.min_width, self.max_width
380                ),
381                "room_size.width",
382            ));
383        }
384
385        if self.min_height > self.max_height {
386            return Err(PcgError::config_with_field(
387                format!(
388                    "房间高度范围非法: min({}) > max({})",
389                    self.min_height, self.max_height
390                ),
391                "room_size.height",
392            ));
393        }
394
395        if self.min_width < 4 || self.min_height < 4 {
396            return Err(PcgError::config_with_field(
397                "房间最小尺寸不能小于 4x4",
398                "room_size",
399            ));
400        }
401
402        // OPT-R-02: 房间尺寸上界保护,防止 OOM
403        if self.max_width > 512 || self.max_height > 512 {
404            return Err(PcgError::config_with_field(
405                format!(
406                    "房间最大尺寸({}x{})超过上限 512x512",
407                    self.max_width, self.max_height
408                ),
409                "room_size",
410            ));
411        }
412
413        Ok(())
414    }
415}
416
417/// 走廊配置
418#[derive(Debug, Clone, Serialize, Deserialize)]
419#[non_exhaustive]
420pub struct CorridorConfig {
421    /// 走廊宽度(网格单位)
422    pub width: u16,
423    /// 最大转折次数。
424    ///
425    /// **RESERVED(未接线)**:当前生成管线不读取该字段。
426    pub max_turns: u16,
427    /// 连接策略
428    pub connection_strategy: ConnectionStrategy,
429}
430
431impl Default for CorridorConfig {
432    fn default() -> Self {
433        Self {
434            width: 2,
435            max_turns: 3,
436            connection_strategy: ConnectionStrategy::Orthogonal,
437        }
438    }
439}
440
441impl CorridorConfig {
442    fn validate(&self) -> PcgResult<()> {
443        if self.width < 1 {
444            return Err(PcgError::config_with_field(
445                "走廊宽度不能小于 1",
446                "corridor.width",
447            ));
448        }
449
450        if self.width > 10 {
451            return Err(PcgError::config_with_field(
452                "走廊宽度不能大于 10",
453                "corridor.width",
454            ));
455        }
456
457        if self.max_turns == 0 || self.max_turns > 20 {
458            return Err(PcgError::config("max_turns 必须在 1..=20 范围内"));
459        }
460
461        Ok(())
462    }
463}
464
465/// 连接策略
466#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
467#[non_exhaustive]
468pub enum ConnectionStrategy {
469    /// 正交连接(仅水平和垂直)
470    Orthogonal,
471    /// 直线连接
472    Straight,
473    /// 共享边开口
474    SharedEdge,
475}
476
477/// 地形配置
478#[derive(Debug, Clone, Serialize, Deserialize)]
479#[non_exhaustive]
480pub struct TerrainConfig {
481    /// 障碍物密度(0.0 - 1.0)
482    pub obstacle_density: f32,
483    /// 最小可通行面积比例(0.0 - 1.0)。
484    ///
485    /// **RESERVED(未接线)**:当前生成管线不读取该字段。
486    pub min_walkable_ratio: f32,
487}
488
489impl Default for TerrainConfig {
490    fn default() -> Self {
491        Self {
492            obstacle_density: 0.2,
493            min_walkable_ratio: 0.6,
494        }
495    }
496}
497
498impl TerrainConfig {
499    fn validate(&self) -> PcgResult<()> {
500        if !(0.0..=1.0).contains(&self.obstacle_density) {
501            return Err(PcgError::config_with_field(
502                format!(
503                    "障碍物密度必须在 0.0-1.0 范围内,当前值: {}",
504                    self.obstacle_density
505                ),
506                "terrain.obstacle_density",
507            ));
508        }
509
510        if !(0.0..=1.0).contains(&self.min_walkable_ratio) {
511            return Err(PcgError::config_with_field(
512                format!(
513                    "最小可通行面积比例必须在 0.0-1.0 范围内,当前值: {}",
514                    self.min_walkable_ratio
515                ),
516                "terrain.min_walkable_ratio",
517            ));
518        }
519
520        if self.obstacle_density + self.min_walkable_ratio > 1.0 {
521            return Err(PcgError::config_with_field(
522                "障碍物密度与最小可通行面积比例之和不能超过 1.0",
523                "terrain",
524            ));
525        }
526
527        Ok(())
528    }
529}
530
531/// 交互物生成配置
532#[derive(Debug, Clone, Serialize, Deserialize)]
533#[non_exhaustive]
534pub struct ItemSpawnConfig {
535    /// 每个房间的交互物数量范围
536    pub count_per_room: RangeU16,
537    /// 最小间距(网格单位)
538    pub min_spacing: u16,
539    /// 稀有度权重
540    pub rarity_weights: Vec<f32>,
541}
542
543impl Default for ItemSpawnConfig {
544    fn default() -> Self {
545        Self {
546            count_per_room: RangeU16 { min: 1, max: 3 },
547            min_spacing: 2,
548            rarity_weights: vec![0.6, 0.3, 0.1], // 普通、稀有、史诗
549        }
550    }
551}
552
553impl ItemSpawnConfig {
554    fn validate(&self) -> PcgResult<()> {
555        self.count_per_room.validate("item_spawns.count_per_room")?;
556
557        if self.min_spacing < 1 {
558            return Err(PcgError::config_with_field(
559                "交互物最小间距不能小于 1",
560                "item_spawns.min_spacing",
561            ));
562        }
563        if self.min_spacing > 128 {
564            return Err(PcgError::config_with_field(
565                "交互物最小间距不能超过 128",
566                "item_spawns.min_spacing",
567            ));
568        }
569
570        // OPT-L-04: 长度必须为 3(普通、稀有、史诗),与 sample_rarity_tier 硬编码一致
571        if self.rarity_weights.len() != 3 {
572            return Err(PcgError::config_with_field(
573                "稀有度权重必须恰好有 3 个值(普通、稀有、史诗)",
574                "item_spawns.rarity_weights",
575            ));
576        }
577
578        // 拒绝 NaN 权重
579        if self.rarity_weights.iter().any(|w| w.is_nan()) {
580            return Err(PcgError::config("权重不能为 NaN"));
581        }
582
583        // OPT-L-02: 拒绝负权重
584        if self.rarity_weights.iter().any(|&w| w < 0.0) {
585            return Err(PcgError::config_with_field(
586                "稀有度权重不能为负数",
587                "item_spawns.rarity_weights",
588            ));
589        }
590
591        // 验证稀有度权重总和
592        let total_weight: f32 = self.rarity_weights.iter().sum();
593        if (total_weight - 1.0).abs() > 0.01 {
594            return Err(PcgError::config_with_field(
595                format!("稀有度权重总和必须为 1.0,当前值: {}", total_weight),
596                "item_spawns.rarity_weights",
597            ));
598        }
599
600        Ok(())
601    }
602}
603
604/// 敌人生成配置
605#[derive(Debug, Clone, Serialize, Deserialize)]
606#[non_exhaustive]
607pub struct EnemySpawnConfig {
608    /// 每个房间的敌人数量范围
609    pub count_per_room: RangeU16,
610    /// 最小间距(网格单位)
611    pub min_spacing: u16,
612    /// 与入口的最小安全距离(网格单位)
613    pub min_distance_from_entrance: u16,
614    /// 基础难度预算
615    pub base_difficulty_budget: u16,
616}
617
618impl Default for EnemySpawnConfig {
619    fn default() -> Self {
620        Self {
621            count_per_room: RangeU16 { min: 2, max: 5 },
622            min_spacing: 3,
623            min_distance_from_entrance: 4,
624            base_difficulty_budget: 100,
625        }
626    }
627}
628
629impl EnemySpawnConfig {
630    fn validate(&self) -> PcgResult<()> {
631        self.count_per_room
632            .validate("enemy_spawns.count_per_room")?;
633
634        if self.min_spacing < 1 {
635            return Err(PcgError::config_with_field(
636                "敌人最小间距不能小于 1",
637                "enemy_spawns.min_spacing",
638            ));
639        }
640
641        if self.min_distance_from_entrance < 2 {
642            return Err(PcgError::config_with_field(
643                "敌人与入口的最小安全距离不能小于 2",
644                "enemy_spawns.min_distance_from_entrance",
645            ));
646        }
647
648        Ok(())
649    }
650}
651
652/// 分块配置
653#[derive(Debug, Clone, Serialize, Deserialize)]
654#[non_exhaustive]
655pub struct ChunkingConfig {
656    /// 分块大小(网格单位)
657    pub chunk_size: u16,
658    /// 是否启用分块
659    pub enabled: bool,
660}
661
662impl Default for ChunkingConfig {
663    fn default() -> Self {
664        Self {
665            chunk_size: 32,
666            enabled: false,
667        }
668    }
669}
670
671impl ChunkingConfig {
672    fn validate(&self) -> PcgResult<()> {
673        if self.enabled && self.chunk_size < 8 {
674            return Err(PcgError::config_with_field(
675                "分块大小不能小于 8",
676                "chunking.chunk_size",
677            ));
678        }
679
680        Ok(())
681    }
682}
683
684/// 生成模式
685#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
686#[non_exhaustive]
687pub enum GenerationMode {
688    /// 离线整层生成
689    OfflineFullFloor,
690    /// 运行时分块生成
691    RuntimeChunked,
692    /// 混合预计算模式
693    HybridPrecompute,
694}
695
696/// 能力开关
697///
698/// 用于控制特定功能的启用状态,支持版本兼容和功能降级。
699#[derive(Debug, Clone, Default, Serialize, Deserialize)]
700#[non_exhaustive]
701pub struct CapabilityFlags {
702    /// 是否启用运行时分块
703    #[serde(default)]
704    pub runtime_chunked: bool,
705    /// 是否启用混合预计算
706    #[serde(default)]
707    pub hybrid_precompute: bool,
708    /// 是否启用 Grammar 兼容输出。
709    ///
710    /// **RESERVED(未接线)**:当前生成管线不读取该字段。
711    #[serde(default)]
712    pub grammar_support: bool,
713    /// 是否启用调试输出。
714    ///
715    /// **RESERVED(未接线)**:当前生成管线不读取该字段。
716    #[serde(default)]
717    pub debug_output: bool,
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723
724    #[test]
725    fn test_default_config_is_valid() {
726        let config = GenerationConfig::default();
727        let result = config.normalize();
728        assert!(result.is_ok());
729    }
730
731    #[test]
732    fn test_invalid_room_count_range() {
733        let config = GenerationConfig {
734            room_count: RangeU16 { min: 20, max: 10 },
735            ..Default::default()
736        };
737
738        let result = config.normalize();
739        assert!(result.is_err());
740
741        if let Err(err) = result {
742            assert_eq!(err.error_code(), "PCG-CONFIG-001");
743        }
744    }
745
746    #[test]
747    fn test_room_count_too_small() {
748        let config = GenerationConfig {
749            room_count: RangeU16 { min: 1, max: 10 },
750            ..Default::default()
751        };
752
753        let result = config.normalize();
754        assert!(result.is_err());
755    }
756
757    #[test]
758    fn test_critical_path_exceeds_room_count() {
759        let config = GenerationConfig {
760            room_count: RangeU16 { min: 5, max: 10 },
761            critical_path_length: RangeU16 { min: 15, max: 20 },
762            ..Default::default()
763        };
764
765        let result = config.normalize();
766        assert!(result.is_err());
767    }
768
769    #[test]
770    fn test_invalid_room_size() {
771        let mut config = GenerationConfig::default();
772        config.room_size.min_width = 20;
773        config.room_size.max_width = 10;
774
775        let result = config.normalize();
776        assert!(result.is_err());
777    }
778
779    #[test]
780    fn test_room_size_too_small() {
781        let mut config = GenerationConfig::default();
782        config.room_size.min_width = 2;
783        config.room_size.min_height = 2;
784
785        let result = config.normalize();
786        assert!(result.is_err());
787    }
788
789    #[test]
790    fn test_invalid_corridor_width() {
791        let mut config = GenerationConfig::default();
792        config.corridor.width = 0;
793
794        let result = config.normalize();
795        assert!(result.is_err());
796    }
797
798    #[test]
799    fn test_invalid_obstacle_density() {
800        let mut config = GenerationConfig::default();
801        config.terrain.obstacle_density = 1.5;
802
803        let result = config.normalize();
804        assert!(result.is_err());
805    }
806
807    #[test]
808    fn test_obstacle_density_and_walkable_ratio_conflict() {
809        let mut config = GenerationConfig::default();
810        config.terrain.obstacle_density = 0.6;
811        config.terrain.min_walkable_ratio = 0.6;
812
813        let result = config.normalize();
814        assert!(result.is_err());
815    }
816
817    #[test]
818    fn test_invalid_rarity_weights_sum() {
819        let mut config = GenerationConfig::default();
820        config.item_spawns.rarity_weights = vec![0.5, 0.3, 0.1]; // 总和不为 1.0
821
822        let result = config.normalize();
823        assert!(result.is_err());
824    }
825
826    #[test]
827    fn test_invalid_rarity_weights_len() {
828        let mut config = GenerationConfig::default();
829        config.item_spawns.rarity_weights = vec![0.6, 0.3, 0.05, 0.05]; // 4 个值
830
831        let result = config.normalize();
832        assert!(result.is_err());
833    }
834
835    #[test]
836    fn test_capability_flags_validation() {
837        let mut config = GenerationConfig {
838            generation_mode: GenerationMode::RuntimeChunked,
839            ..Default::default()
840        };
841        config.capability_flags.runtime_chunked = false;
842
843        let result = config.normalize();
844        assert!(result.is_err());
845    }
846
847    #[test]
848    fn test_config_override_with() {
849        let base = GenerationConfig::default();
850        let override_config = GenerationConfig {
851            room_count: RangeU16 { min: 15, max: 25 },
852            theme_tags: vec!["dungeon".to_string()],
853            ..Default::default()
854        };
855
856        let overridden = base.override_with(override_config);
857
858        assert_eq!(overridden.room_count.min, 15);
859        assert_eq!(overridden.room_count.max, 25);
860        assert_eq!(overridden.theme_tags, vec!["dungeon".to_string()]);
861    }
862
863    #[test]
864    #[allow(deprecated)]
865    fn test_config_merge() {
866        let base = GenerationConfig::default();
867        let override_config = GenerationConfig {
868            room_count: RangeU16 { min: 15, max: 25 },
869            theme_tags: vec!["dungeon".to_string()],
870            ..Default::default()
871        };
872
873        let merged = base.override_with(override_config);
874
875        assert_eq!(merged.room_count.min, 15);
876        assert_eq!(merged.room_count.max, 25);
877        assert_eq!(merged.theme_tags, vec!["dungeon".to_string()]);
878    }
879
880    #[test]
881    fn test_range_u16_validation() {
882        let valid_range = RangeU16 { min: 5, max: 10 };
883        assert!(valid_range.validate("test").is_ok());
884
885        let invalid_range = RangeU16 { min: 10, max: 5 };
886        assert!(invalid_range.validate("test").is_err());
887    }
888
889    // OPT-T-07: 边界/非法 config 拒绝测试
890
891    #[test]
892    fn test_nan_obstacle_density_rejected() {
893        let mut config = GenerationConfig::default();
894        config.terrain.obstacle_density = f32::NAN;
895        let result = config.normalize();
896        assert!(result.is_err(), "NaN obstacle_density 应被拒绝");
897    }
898
899    #[test]
900    fn test_inf_obstacle_density_rejected() {
901        let mut config = GenerationConfig::default();
902        config.terrain.obstacle_density = f32::INFINITY;
903        let result = config.normalize();
904        assert!(result.is_err(), "Inf obstacle_density 应被拒绝");
905
906        let mut config2 = GenerationConfig::default();
907        config2.terrain.obstacle_density = f32::NEG_INFINITY;
908        let result2 = config2.normalize();
909        assert!(result2.is_err(), "-Inf obstacle_density 应被拒绝");
910    }
911
912    #[test]
913    fn test_negative_rarity_weights_rejected() {
914        let mut config = GenerationConfig::default();
915        config.item_spawns.rarity_weights = vec![-0.1, 0.5, 0.6];
916        let result = config.normalize();
917        assert!(result.is_err(), "负权重应被拒绝");
918    }
919
920    #[test]
921    fn test_empty_rarity_weights_rejected() {
922        let mut config = GenerationConfig::default();
923        config.item_spawns.rarity_weights = vec![];
924        let result = config.normalize();
925        assert!(result.is_err(), "空 rarity_weights 应被拒绝");
926    }
927
928    #[test]
929    fn test_rarity_weights_wrong_length_rejected() {
930        // len = 1
931        let mut config = GenerationConfig::default();
932        config.item_spawns.rarity_weights = vec![1.0];
933        assert!(config.normalize().is_err(), "len=1 应被拒绝");
934
935        // len = 2
936        let mut config = GenerationConfig::default();
937        config.item_spawns.rarity_weights = vec![0.5, 0.5];
938        assert!(config.normalize().is_err(), "len=2 应被拒绝");
939
940        // len = 4
941        let mut config = GenerationConfig::default();
942        config.item_spawns.rarity_weights = vec![0.25, 0.25, 0.25, 0.25];
943        assert!(config.normalize().is_err(), "len=4 应被拒绝");
944    }
945
946    #[test]
947    fn test_room_count_min_exceeds_max_rejected() {
948        let config = GenerationConfig {
949            room_count: RangeU16 { min: 50, max: 30 },
950            ..Default::default()
951        };
952        let result = config.normalize();
953        assert!(result.is_err(), "room_count min>max 应被拒绝");
954    }
955
956    #[test]
957    fn test_room_size_max_exceeds_boundary() {
958        // max_width > 512
959        let mut config = GenerationConfig::default();
960        config.room_size.max_width = 513;
961        assert!(config.normalize().is_err(), "max_width>512 应被拒绝");
962
963        // max_height > 512
964        let mut config = GenerationConfig::default();
965        config.room_size.max_height = 600;
966        assert!(config.normalize().is_err(), "max_height>512 应被拒绝");
967    }
968
969    #[test]
970    fn test_room_count_max_exceeds_boundary() {
971        let config = GenerationConfig {
972            room_count: RangeU16 { min: 10, max: 4097 },
973            ..Default::default()
974        };
975        let result = config.normalize();
976        assert!(result.is_err(), "room_count.max>4096 应被拒绝");
977    }
978
979    #[test]
980    fn test_min_walkable_ratio_out_of_range() {
981        // > 1.0
982        let mut config = GenerationConfig::default();
983        config.terrain.min_walkable_ratio = 1.5;
984        assert!(config.normalize().is_err(), "ratio>1.0 应被拒绝");
985
986        // < 0.0
987        let mut config = GenerationConfig::default();
988        config.terrain.min_walkable_ratio = -0.1;
989        assert!(config.normalize().is_err(), "ratio<0.0 应被拒绝");
990
991        // NaN
992        let mut config = GenerationConfig::default();
993        config.terrain.min_walkable_ratio = f32::NAN;
994        assert!(config.normalize().is_err(), "NaN ratio 应被拒绝");
995    }
996}