proof-engine 0.2.3

Real-time graphics from math: glyphs and particles moved by ODEs, strange attractors and force fields, drawn with HDR bloom on OpenGL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901

// ============================================================
// IMPL BLOCKS FOR LOOT EDITOR (no duplicate struct defs)
// ============================================================

impl ItemRarity {
    pub fn base_weight(&self) -> f32 {
        match self {
            ItemRarity::Common => 50.0, ItemRarity::Uncommon => 25.0,
            ItemRarity::Rare => 10.0, ItemRarity::Epic => 4.0,
            ItemRarity::Legendary => 1.0, ItemRarity::Mythic => 0.2,
            ItemRarity::BossExclusive => 0.5,
        }
    }

    pub fn color(&self) -> &'static str {
        match self {
            ItemRarity::Common => "white", ItemRarity::Uncommon => "green",
            ItemRarity::Rare => "blue", ItemRarity::Epic => "purple",
            ItemRarity::Legendary => "orange", ItemRarity::Mythic => "red",
            ItemRarity::BossExclusive => "gold",
        }
    }

    pub fn base_value_mult(&self) -> f32 {
        match self {
            ItemRarity::Common => 1.0, ItemRarity::Uncommon => 3.0,
            ItemRarity::Rare => 10.0, ItemRarity::Epic => 40.0,
            ItemRarity::Legendary => 200.0, ItemRarity::Mythic => 1000.0,
            ItemRarity::BossExclusive => 500.0,
        }
    }

    pub fn drop_rate_pct(&self) -> f32 {
        match self {
            ItemRarity::Common => 0.55, ItemRarity::Uncommon => 0.28,
            ItemRarity::Rare => 0.12, ItemRarity::Epic => 0.04,
            ItemRarity::Legendary => 0.008, ItemRarity::Mythic => 0.002,
            ItemRarity::BossExclusive => 0.005,
        }
    }

    pub fn tier(&self) -> u32 {
        match self {
            ItemRarity::Common => 1, ItemRarity::Uncommon => 2,
            ItemRarity::Rare => 3, ItemRarity::Epic => 4,
            ItemRarity::Legendary => 5, ItemRarity::Mythic => 6,
            ItemRarity::BossExclusive => 5,
        }
    }
}

impl ItemStats {
    pub fn new() -> Self {
        Self { attack: 0.0, defense: 0.0, speed: 0.0, magic: 0.0, hp: 0.0, mp: 0.0, crit_chance: 0.0, crit_damage: 1.5 }
    }
    pub fn weapon(attack: f32) -> Self { let mut s = Self::new(); s.attack = attack; s }
    pub fn armor(defense: f32) -> Self { let mut s = Self::new(); s.defense = defense; s }
    pub fn total_power(&self) -> f32 { self.attack + self.defense + self.magic + self.hp/10.0 + self.mp/10.0 + self.speed*2.0 }
}

impl Item {
    pub fn new(id: u32, name: &str, item_type: ItemType, rarity: ItemRarity, base_value: f32) -> Self {
        Self {
            id, name: name.to_string(), description: String::new(),
            item_type, rarity, base_value, weight: 1.0,
            stats: ItemStats::new(), set_id: None, level_requirement: 1,
            zone: "world".to_string(), stackable: false, max_stack: 1,
            tags: Vec::new(), zone_level: 1, lore: String::new(),
            is_boss_exclusive: false, stack_size: 1,
        }
    }
    pub fn market_value(&self) -> f32 { self.base_value * self.rarity.base_value_mult() }
    pub fn sell_value(&self) -> f32 { self.market_value() * 0.3 }
    pub fn with_stats(mut self, stats: ItemStats) -> Self { self.stats = stats; self }
    pub fn with_level(mut self, lvl: u32) -> Self { self.level_requirement = lvl; self }
    pub fn with_zone(mut self, zone: &str) -> Self { self.zone = zone.to_string(); self }
    pub fn with_set(mut self, set_id: u32) -> Self { self.set_id = Some(set_id); self }
    pub fn with_stackable(mut self, max: u32) -> Self { self.stackable = true; self.max_stack = max; self.stack_size = max; self }
    pub fn with_description(mut self, desc: &str) -> Self { self.description = desc.to_string(); self }
    pub fn with_tag(mut self, tag: &str) -> Self { self.tags.push(tag.to_string()); self }
    pub fn with_lore(mut self, lore: &str) -> Self { self.lore = lore.to_string(); self }
    pub fn is_legendary_or_above(&self) -> bool { self.rarity.tier() >= 5 }
}

impl LootRng {
    pub fn new(seed: u64) -> Self { Self { state: seed.wrapping_add(1) } }
    pub fn next_u64(&mut self) -> u64 {
        self.state ^= self.state << 13;
        self.state ^= self.state >> 7;
        self.state ^= self.state << 17;
        self.state
    }
    pub fn next_u32(&mut self) -> u32 { (self.next_u64() >> 32) as u32 }
    pub fn next_f32(&mut self) -> f32 { (self.next_u64() as f32) / (u64::MAX as f32) }
    pub fn next_f32_range(&mut self, min: f32, max: f32) -> f32 { min + self.next_f32() * (max - min) }
    pub fn next_u32_range(&mut self, min: u32, max: u32) -> u32 {
        if min >= max { return min; }
        min + (self.next_u32() % (max - min))
    }
    pub fn shuffle<T>(&mut self, slice: &mut Vec<T>) {
        for i in (1..slice.len()).rev() {
            let j = self.next_u32() as usize % (i + 1);
            slice.swap(i, j);
        }
    }
}

impl AliasTable {
    pub fn build(weights: &[f32]) -> Self {
        let n = weights.len();
        if n == 0 { return Self { prob: Vec::new(), alias: Vec::new(), n: 0 }; }
        let total: f32 = weights.iter().sum();
        let avg = total / n as f32;
        let mut prob = vec![0.0f32; n];
        let mut alias = vec![0usize; n];
        let mut small = Vec::new();
        let mut large = Vec::new();
        for (i, &w) in weights.iter().enumerate() {
            prob[i] = w / avg;
            if prob[i] < 1.0 { small.push(i); } else { large.push(i); }
        }
        while !small.is_empty() && !large.is_empty() {
            let s = small.pop().unwrap();
            let l = large.pop().unwrap();
            alias[s] = l;
            prob[l] -= 1.0 - prob[s];
            if prob[l] < 1.0 { small.push(l); } else { large.push(l); }
        }
        Self { prob, alias, n }
    }
    pub fn sample(&self, rng: &mut LootRng) -> usize {
        if self.n == 0 { return 0; }
        let i = rng.next_u32() as usize % self.n;
        if rng.next_f32() < self.prob[i] { i } else { self.alias[i] }
    }
}

impl PitySystem {
    pub fn new(base_rate: f32, soft_pity_start: u32, hard_pity: u32) -> Self {
        Self { base_rate, current_rolls: 0, soft_pity_start, hard_pity, soft_pity_increase: 0.05 }
    }
    pub fn roll(&mut self, rng: &mut LootRng) -> bool {
        self.current_rolls += 1;
        let rate = if self.current_rolls >= self.hard_pity { 1.0 }
            else if self.current_rolls >= self.soft_pity_start {
                let extra = (self.current_rolls - self.soft_pity_start) as f32;
                (self.base_rate + extra * self.soft_pity_increase).min(1.0)
            } else { self.base_rate };
        if rng.next_f32() < rate { self.current_rolls = 0; true } else { false }
    }
    pub fn guaranteed_in(&self) -> u32 { self.hard_pity.saturating_sub(self.current_rolls) }
    pub fn current_effective_rate(&self) -> f32 {
        if self.current_rolls >= self.hard_pity { return 1.0; }
        if self.current_rolls >= self.soft_pity_start {
            let extra = (self.current_rolls - self.soft_pity_start) as f32;
            return (self.base_rate + extra * self.soft_pity_increase).min(1.0);
        }
        self.base_rate
    }
}

impl DropContext {
    pub fn new(player_level: u32) -> Self {
        Self { player_level, zone_id: 1, completed_quests: HashSet::new(), kill_count: 0, difficulty: 1, death_count: 0, rng_value: 0.5 }
    }
}

impl LootTable {
    pub fn new(id: u32, name: &str) -> Self {
        Self {
            id, name: name.to_string(), entries: Vec::new(),
            roll_count: RollCountMode::Constant(1),
            guaranteed_entries: Vec::new(),
            boss_exclusive: false, pity_enabled: false,
            pity_threshold: 100, max_drops: None,
            min_rolls: 1, max_rolls: 1,
        }
    }
    pub fn total_weight(&self) -> f32 { self.entries.iter().map(|e| e.weight).sum() }
    pub fn add_entry(&mut self, item_id: u32, weight: f32, min_qty: u32, max_qty: u32) {
        self.entries.push(LootTableEntry {
            kind: LootEntryKind::Item { item_id },
            weight, min_count: min_qty, max_count: max_qty,
            conditions: Vec::new(), guaranteed: false,
            item_id, min_quantity: min_qty, max_quantity: max_qty, condition: None,
        });
    }
    pub fn add_guaranteed(&mut self, item_id: u32) {
        let idx = self.entries.len();
        self.entries.push(LootTableEntry {
            kind: LootEntryKind::Item { item_id },
            weight: 0.0, min_count: 1, max_count: 1,
            conditions: Vec::new(), guaranteed: true,
            item_id, min_quantity: 1, max_quantity: 1, condition: None,
        });
        self.guaranteed_entries.push(idx as u32);
    }
    pub fn roll_simple(&self, rng: &mut LootRng) -> Option<u32> {
        let non_guaranteed: Vec<&LootTableEntry> = self.entries.iter().filter(|e| !e.guaranteed).collect();
        if non_guaranteed.is_empty() { return None; }
        let total: f32 = non_guaranteed.iter().map(|e| e.weight).sum();
        let r = rng.next_f32() * total;
        let mut cum = 0.0f32;
        for e in &non_guaranteed {
            cum += e.weight;
            if r < cum { return Some(e.item_id); }
        }
        non_guaranteed.last().map(|e| e.item_id)
    }
}

impl LootRoller {
    pub fn new(seed: u64) -> Self { Self { rng: LootRng::new(seed), pity_trackers: HashMap::new() } }
    pub fn roll_table(&mut self, table: &LootTable, _catalog: &[Item], ctx: &mut DropContext) -> Vec<DropResult> {
        let mut results = Vec::new();
        for &idx in &table.guaranteed_entries {
            if let Some(e) = table.entries.get(idx as usize) {
                let count = if e.min_count == e.max_count { e.min_count } else { e.min_count + self.rng.next_u32() % (e.max_count - e.min_count + 1) };
                results.push(DropResult { item_id: e.item_id, count, is_guaranteed: true, from_pity: false });
            }
        }
        if let Some(item_id) = table.roll_simple(&mut self.rng) {
            results.push(DropResult { item_id, count: 1, is_guaranteed: false, from_pity: false });
        }
        results
    }
}

impl MonteCarloResult {
    pub fn new() -> Self { Self { runs: 0, item_frequencies: HashMap::new(), total_value_per_run: Vec::new(), drops_per_run: Vec::new() } }
    pub fn drops_mean(&self) -> f32 {
        if self.drops_per_run.is_empty() { 0.0 } else { self.drops_per_run.iter().sum::<u32>() as f32 / self.drops_per_run.len() as f32 }
    }
    pub fn expected_value(&self) -> f32 {
        if self.total_value_per_run.is_empty() { 0.0 } else { self.total_value_per_run.iter().sum::<f32>() / self.total_value_per_run.len() as f32 }
    }
    pub fn item_drop_rate(&self, item_id: u32) -> f32 {
        if self.runs == 0 { 0.0 } else { *self.item_frequencies.get(&item_id).unwrap_or(&0) as f32 / self.runs as f32 }
    }
    pub fn p10(&self) -> f32 { self.percentile(0.10) }
    pub fn p50(&self) -> f32 { self.percentile(0.50) }
    pub fn p90(&self) -> f32 { self.percentile(0.90) }
    pub fn p99(&self) -> f32 { self.percentile(0.99) }
    pub fn std_dev_value(&self) -> f32 {
        if self.total_value_per_run.len() < 2 { return 0.0; }
        let mean = self.expected_value();
        let variance = self.total_value_per_run.iter().map(|&v| (v-mean).powi(2)).sum::<f32>() / (self.total_value_per_run.len()-1) as f32;
        variance.sqrt()
    }
    fn percentile(&self, p: f32) -> f32 {
        if self.total_value_per_run.is_empty() { return 0.0; }
        let mut sorted = self.total_value_per_run.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let idx = ((sorted.len() as f32 * p) as usize).min(sorted.len()-1);
        sorted[idx]
    }
}

impl LootBudget {
    pub fn new(budget: f32) -> Self { Self { total_budget: budget, remaining_budget: budget, allocated: Vec::new() } }
    pub fn allocate(&mut self, item_id: u32, value: f32) -> bool {
        if value <= self.remaining_budget { self.allocated.push((item_id, value)); self.remaining_budget -= value; true } else { false }
    }
    pub fn utilization(&self) -> f32 { 1.0 - self.remaining_budget / self.total_budget }
}

impl DifficultyScaler {
    pub fn new(base: f32, scale: f32) -> Self { Self { base_drop_rate: base, difficulty_scale: scale, player_level: 1, zone_level: 1 } }
    pub fn adjusted_rate(&self) -> f32 { (self.base_drop_rate * (1.0 + self.difficulty_scale * self.zone_level as f32 * 0.1)).min(1.0) }
}

impl LootTableBuilder {
    pub fn new(id: u32, name: &str) -> Self { Self { table: LootTable::new(id, name) } }
    pub fn with_entry(mut self, item_id: u32, weight: f32) -> Self { self.table.add_entry(item_id, weight, 1, 1); self }
    pub fn build(self) -> LootTable { self.table }
}

impl LootEditor {
    pub fn new() -> Self {
        Self { tables: HashMap::new(), catalog: build_item_catalog(), rng: LootRng::new(42), selected_table: None, show_statistics: false }
    }
    pub fn add_table(&mut self, table: LootTable) { self.tables.insert(table.id, table); }
    pub fn roll_table(&mut self, table_id: u32) -> Vec<DropResult> {
        if let Some(table) = self.tables.get(&table_id) {
            let table = table.clone();
            let catalog = self.catalog.clone();
            let mut ctx = DropContext::new(20);
            ctx.rng_value = self.rng.next_f32();
            let mut roller = LootRoller::new(self.rng.next_u64());
            roller.roll_table(&table, &catalog, &mut ctx)
        } else { Vec::new() }
    }
}

impl ItemEffect {
    pub fn new(id: u32, name: &str, trigger: EffectTrigger, description: &str, value: f32) -> Self {
        Self { id, name: name.to_string(), trigger, description: description.to_string(), value, duration: 0.0, cooldown: 0.0, proc_chance: 1.0 }
    }
    pub fn with_duration(mut self, d: f32) -> Self { self.duration = d; self }
    pub fn with_cooldown(mut self, c: f32) -> Self { self.cooldown = c; self }
    pub fn with_proc_chance(mut self, p: f32) -> Self { self.proc_chance = p; self }
    pub fn should_proc(&self, rng: &mut LootRng) -> bool { rng.next_f32() < self.proc_chance }
}

// ============================================================
// SECTION: CRAFTING SYSTEM IMPLS
// ============================================================

impl CraftingSystem {
    pub fn new() -> Self {
        Self { recipes: Vec::new(), unlocked_recipes: HashSet::new(), recipe_by_output: HashMap::new(), recipe_by_station: HashMap::new() }
    }
    pub fn add_recipe(&mut self, recipe: CraftingRecipe) {
        let id = recipe.id;
        let out = recipe.output_item_id;
        let cat = recipe.category.clone();
        self.recipes.push(recipe);
        self.recipe_by_output.entry(out).or_default().push(id);
        self.recipe_by_station.entry(cat).or_default().push(id);
    }
    pub fn craft(&self, recipe_id: u32, skill: u32, rng: &mut LootRng) -> CraftResult {
        if let Some(recipe) = self.recipes.iter().find(|r| r.id == recipe_id) {
            let chance = (recipe.success_chance + skill as f32 * 0.01).min(1.0);
            if rng.next_f32() < chance {
                let quality = if skill > 80 { ItemQuality::Masterwork } else if skill > 50 { ItemQuality::Fine } else { ItemQuality::Normal };
                CraftResult::Success { outputs: vec![(recipe.output_item_id, recipe.output_quantity, quality)], experience: 10 + skill/5 }
            } else { CraftResult::Failed { experience: 5 } }
        } else { CraftResult::Failed { experience: 0 } }
    }
    pub fn build_standard_recipes(&mut self) {
        let recipes = vec![
            CraftingRecipe { id: 1, name: "Iron Sword".into(), inputs: vec![(101,3),(102,1)], output_item_id: 1, output_quantity: 1, skill_required: 10, success_chance: 0.9, byproduct_chance: 0.1, category: "blacksmith".into() },
            CraftingRecipe { id: 2, name: "Leather Vest".into(), inputs: vec![(201,5)], output_item_id: 21, output_quantity: 1, skill_required: 5, success_chance: 0.95, byproduct_chance: 0.0, category: "tailor".into() },
            CraftingRecipe { id: 3, name: "Health Potion".into(), inputs: vec![(301,2),(302,1)], output_item_id: 51, output_quantity: 3, skill_required: 1, success_chance: 0.99, byproduct_chance: 0.0, category: "alchemy".into() },
            CraftingRecipe { id: 4, name: "Steel Sword".into(), inputs: vec![(101,5),(103,2)], output_item_id: 2, output_quantity: 1, skill_required: 30, success_chance: 0.8, byproduct_chance: 0.15, category: "blacksmith".into() },
        ];
        for r in recipes { self.add_recipe(r); }
    }
}

impl EnchantmentLibrary {
    pub fn new() -> Self { Self { enchantments: Vec::new() } }
    pub fn add(&mut self, ench: Enchantment) { self.enchantments.push(ench); }
    pub fn for_target(&self, target: &EnchantmentTarget) -> Vec<&Enchantment> {
        self.enchantments.iter().filter(|e| &e.target == target || e.target == EnchantmentTarget::Any).collect()
    }
    pub fn build_standard_library(&mut self) {
        let enchs = vec![
            Enchantment { id: 1, name: "Sharpness".into(), description: "+damage".into(), target: EnchantmentTarget::Weapon, effects: vec![EnchantmentEffect::DamageBonus(0.1)], rarity: ItemRarity::Common, max_rank: 5, cost: 50 },
            Enchantment { id: 2, name: "Fire Aspect".into(), description: "fire".into(), target: EnchantmentTarget::Weapon, effects: vec![EnchantmentEffect::FireDamage(15.0)], rarity: ItemRarity::Uncommon, max_rank: 3, cost: 100 },
            Enchantment { id: 3, name: "Protection".into(), description: "+defense".into(), target: EnchantmentTarget::Armor, effects: vec![EnchantmentEffect::DefenseBonus(0.1)], rarity: ItemRarity::Common, max_rank: 5, cost: 50 },
            Enchantment { id: 4, name: "Magic Find".into(), description: "more drops".into(), target: EnchantmentTarget::Accessory, effects: vec![EnchantmentEffect::MagicFind(0.05)], rarity: ItemRarity::Rare, max_rank: 3, cost: 200 },
            Enchantment { id: 5, name: "Lifesteal".into(), description: "heal on hit".into(), target: EnchantmentTarget::Weapon, effects: vec![EnchantmentEffect::LifeSteal(0.03)], rarity: ItemRarity::Epic, max_rank: 2, cost: 500 },
        ];
        for e in enchs { self.add(e); }
    }
}

impl ItemGenerator {
    pub fn new(seed: u64) -> Self { Self { rng: LootRng::new(seed) } }
    pub fn generate_item(&mut self, item_id: u32, _name: &str, level: u32, magic_find: f32) -> GeneratedItem {
        let rarity = self.roll_rarity(magic_find);
        let mult = rarity.base_value_mult();
        let base_sell = (level as f32 * 10.0 * mult) as u32;
        let stats = self.generate_stats(level, &rarity);
        GeneratedItem { base_item_id: item_id, rarity, level, stats, sell_value: base_sell, enchantments: Vec::new(), sockets: 0 }
    }
    fn roll_rarity(&mut self, magic_find: f32) -> ItemRarity {
        let r = self.rng.next_f32() / (1.0 + magic_find * 0.01);
        if r < 0.002 { ItemRarity::Mythic } else if r < 0.01 { ItemRarity::Legendary }
        else if r < 0.05 { ItemRarity::Epic } else if r < 0.15 { ItemRarity::Rare }
        else if r < 0.35 { ItemRarity::Uncommon } else { ItemRarity::Common }
    }
    fn generate_stats(&mut self, level: u32, rarity: &ItemRarity) -> ItemStats {
        let base = level as f32 * rarity.base_value_mult().sqrt();
        let vary = || base * (0.9 + self.rng.next_f32() * 0.2);
        ItemStats { attack: vary(), defense: vary(), speed: vary()*0.1, magic: vary(), hp: vary()*5.0, mp: vary()*2.0, crit_chance: self.rng.next_f32()*0.1, crit_damage: 1.5 + self.rng.next_f32()*0.5 }
    }
}

impl EconomySimulator {
    pub fn new(params: EconomySimParams) -> Self {
        let ms = params.num_players as f64 * 1000.0;
        Self { params, money_supply: ms, price_level: 1.0, day: 0, snapshots: Vec::new() }
    }
    pub fn step(&mut self) {
        let new_players = self.params.new_player_spawn_rate_per_day as f64;
        let quit = self.params.quit_rate_per_day as f64;
        let drops = self.params.drops_per_player_per_day as f64 * (self.params.num_players as f64 + new_players - quit);
        let sink = self.params.item_sink_rate as f64 * drops;
        let gold_sink = self.params.gold_sink_rate as f64;
        self.money_supply = self.money_supply * (1.0 - gold_sink) + new_players * 100.0;
        self.price_level *= 1.0 + self.params.inflation_rate_per_day as f64;
        self.snapshots.push(EconomySimSnapshot {
            day: self.day, num_players: self.params.num_players, money_supply: self.money_supply,
            price_level: self.price_level, items_in_circulation: drops as u64, avg_item_value: self.price_level as f32 * 10.0,
        });
        self.day += 1;
    }
    pub fn run(&mut self) {
        for _ in 0..self.params.days_to_simulate { self.step(); }
    }
    pub fn final_inflation(&self) -> f64 { self.price_level - 1.0 }
}

impl PrestigeSystem {
    pub fn new() -> Self {
        Self { current_prestige: 0, total_prestige_points: 0, bonus_magic_find: 0.0, bonus_gold_find: 0.0, bonus_xp: 0.0, prestige_items_unlocked: Vec::new() }
    }
    pub fn prestige(&mut self) -> bool {
        self.current_prestige += 1;
        self.total_prestige_points += 1;
        self.bonus_magic_find = self.current_prestige as f32 * 0.05;
        self.bonus_gold_find = self.current_prestige as f32 * 0.05;
        self.bonus_xp = self.current_prestige as f32 * 0.1;
        true
    }
    pub fn effective_magic_find(&self) -> f32 { self.bonus_magic_find }
    pub fn effective_gold_find(&self) -> f32 { self.bonus_gold_find }
}

// ============================================================
// SECTION: ADDITIONAL HELPER IMPLS
// ============================================================

impl DungeonSimulator {
    pub fn new(seed: u64) -> Self { Self { rng: LootRng::new(seed), catalog: build_item_catalog(), difficulty_mult: 1.0 } }
    pub fn simulate_run(&mut self, dungeon: &DungeonRun) -> DungeonLootResult {
        let mut total_gold = 0u32;
        let mut all_drops: Vec<DropResult> = Vec::new();
        for room in &dungeon.rooms {
            total_gold += self.rng.next_u32_range(room.gold_min, room.gold_max);
            if room.has_chest && self.rng.next_f32() < 0.5 {
                all_drops.push(DropResult { item_id: self.rng.next_u32_range(1, 30), count: 1, is_guaranteed: false, from_pity: false });
            }
        }
        DungeonLootResult { drops: all_drops, gold: total_gold, bonus_items: Vec::new(), experience: dungeon.total_xp, score: dungeon.rooms.len() as u32 * 100 }
    }
}

impl TreasureChestSystem {
    pub fn new(seed: u64) -> Self { Self { rng: LootRng::new(seed), catalog: build_item_catalog() } }
    pub fn open_chest(&mut self, chest_type: &ChestType, player_level: u32, magic_find: f32) -> ChestOpenResult {
        let (gold_min, gold_max, item_count) = match chest_type {
            ChestType::Wooden => (10, 50, 1),
            ChestType::Iron => (50, 200, 2),
            ChestType::Gold => (200, 800, 3),
            ChestType::Crystal => (800, 3000, 5),
            ChestType::Legendary => (3000, 10000, 7),
        };
        let gold = self.rng.next_u32_range(gold_min, gold_max);
        let mut items = Vec::new();
        for _ in 0..item_count {
            let max_id = self.catalog.len() as u32;
            items.push(self.rng.next_u32_range(1, max_id));
        }
        ChestOpenResult { gold, items, bonus_item: None, experience: gold / 10 }
    }
}

impl VendorNpc {
    pub fn new(id: u32, name: &str, vendor_type: VendorType) -> Self {
        Self { id, name: name.to_string(), vendor_type, items: Vec::new(), restock_timer: 0.0, gold_reserve: 10000, reputation_required: 0 }
    }
    pub fn add_item(&mut self, item: VendorItem) { self.items.push(item); }
    pub fn buy_item(&mut self, item_id: u32, player_gold: &mut u32) -> bool {
        if let Some(idx) = self.items.iter().position(|i| i.item_id == item_id && i.stock > 0) {
            let price = self.items[idx].price;
            if *player_gold >= price {
                *player_gold -= price;
                self.items[idx].stock -= 1;
                self.gold_reserve += price;
                return true;
            }
        }
        false
    }
}

impl VendorManager {
    pub fn new() -> Self { Self { vendors: Vec::new() } }
    pub fn add_vendor(&mut self, vendor: VendorNpc) { self.vendors.push(vendor); }
    pub fn vendor_by_id(&self, id: u32) -> Option<&VendorNpc> { self.vendors.iter().find(|v| v.id == id) }
    pub fn vendor_by_id_mut(&mut self, id: u32) -> Option<&mut VendorNpc> { self.vendors.iter_mut().find(|v| v.id == id) }
}

impl Marketplace {
    pub fn new() -> Self { Self { listings: Vec::new(), transactions: Vec::new(), fee_pct: 0.05, next_listing_id: 1 } }
    pub fn list_item(&mut self, seller_id: u32, item_id: u32, price: u32) -> u32 {
        let id = self.next_listing_id;
        self.next_listing_id += 1;
        self.listings.push(MarketListing { id, seller_id, item_id, price, listed_at: 0, expires_at: 7 * 24 });
        id
    }
    pub fn buy_item(&mut self, listing_id: u32, buyer_id: u32) -> Option<u32> {
        if let Some(idx) = self.listings.iter().position(|l| l.id == listing_id) {
            let listing = self.listings.remove(idx);
            let fee = (listing.price as f32 * self.fee_pct) as u32;
            self.transactions.push(MarketTransaction { listing_id, buyer_id, seller_id: listing.seller_id, item_id: listing.item_id, price: listing.price, fee, timestamp: 0 });
            Some(listing.price - fee)
        } else { None }
    }
}

impl DropRateAnalyzer {
    pub fn new() -> Self { Self { entries: Vec::new(), total_weight: 0.0 } }
    pub fn analyze_table(&mut self, table: &LootTable, catalog: &[Item]) -> DropRateAnalysisReport {
        let total = table.total_weight();
        let entries = table.entries.iter().map(|e| {
            let rate = if total > 0.0 { e.weight / total } else { 0.0 };
            let item_name = catalog.iter().find(|i| i.id == e.item_id).map(|i| i.name.clone()).unwrap_or("Unknown".into());
            EntryAnalysis { item_id: e.item_id, item_name, weight: e.weight, drop_rate: rate, expected_per_100: rate * 100.0, expected_kills_for_drop: if rate > 0.0 { 1.0 / rate } else { f32::INFINITY } }
        }).collect();
        DropRateAnalysisReport { table_id: table.id, table_name: table.name.clone(), entries, total_weight: total, average_drop_rate: if table.entries.is_empty() { 0.0 } else { total / table.entries.len() as f32 } }
    }
}

impl LootTableGenerator {
    pub fn new(seed: u64) -> Self { Self { rng: LootRng::new(seed) } }
    pub fn generate_zone_table(&mut self, zone_id: u32, catalog: &[Item]) -> LootTable {
        let mut table = LootTable::new(zone_id, &format!("Zone {} Loot", zone_id));
        for item in catalog.iter().take(20) {
            let weight = item.rarity.base_weight() + self.rng.next_f32() * 5.0;
            table.add_entry(item.id, weight, 1, 1);
        }
        table
    }
    pub fn generate_boss_table(&mut self, boss_id: u32, catalog: &[Item]) -> LootTable {
        let mut table = LootTable::new(boss_id, &format!("Boss {} Loot", boss_id));
        table.boss_exclusive = true;
        for item in catalog.iter().filter(|i| i.rarity.tier() >= 3).take(10) {
            table.add_entry(item.id, item.rarity.base_weight(), 1, 1);
        }
        table
    }
}

impl ComprehensiveLootEditor {
    pub fn new() -> Self {
        Self { loot_editor: LootEditor::new(), item_generator: ItemGenerator::new(42), dungeon_simulator: DungeonSimulator::new(43), vendor_manager: VendorManager::new(), marketplace: Marketplace::new(), economy_simulator: None, prestige_system: PrestigeSystem::new(), session_stats: SessionStats::default() }
    }
    pub fn full_simulation(&mut self, runs: u32) {
        for _ in 0..runs {
            self.session_stats.total_rolls += 1;
        }
    }
}

impl Default for SessionStats {
    fn default() -> Self {
        Self { total_drops: 0, total_gold_earned: 0, items_crafted: 0, dungeons_completed: 0, total_rolls: 0, legendary_drops: 0, session_start: 0 }
    }
}

impl SeasonalLootManager {
    pub fn new(season: Season) -> Self {
        Self { current_season: season, seasonal_tables: HashMap::new(), bonus_multiplier: 1.0, active: true }
    }
    pub fn add_table(&mut self, table_id: u32, table: LootTable) { self.seasonal_tables.insert(table_id, table); }
    pub fn get_multiplier(&self) -> f32 { if self.active { self.bonus_multiplier } else { 1.0 } }
}

impl SetDatabase {
    pub fn new() -> Self { Self { sets: Vec::new() } }
    pub fn add_set(&mut self, set: ItemSetDef) { self.sets.push(set); }
    pub fn find_set(&self, id: u32) -> Option<&ItemSetDef> { self.sets.iter().find(|s| s.id == id) }
    pub fn active_sets(&self, equipped_items: &[u32]) -> Vec<&ItemSetDef> {
        let equipped: HashSet<u32> = equipped_items.iter().copied().collect();
        self.sets.iter().filter(|s| s.item_ids.iter().any(|id| equipped.contains(id))).collect()
    }
}

impl EventManager {
    pub fn new() -> Self { Self { events: Vec::new(), active_event: None, rng: LootRng::new(99) } }
    pub fn add_event(&mut self, event: WorldEvent) { self.events.push(event); }
    pub fn activate_random(&mut self) {
        if self.events.is_empty() { return; }
        let idx = self.rng.next_u32() as usize % self.events.len();
        self.active_event = Some(idx);
    }
    pub fn is_event_active(&self, event_type: &EventType) -> bool {
        self.active_event.and_then(|idx| self.events.get(idx)).map(|e| &e.event_type == event_type).unwrap_or(false)
    }
}

impl ExtendedLootEditor {
    pub fn new() -> Self {
        Self {
            core_editor: LootEditor::new(),
            crafting: CraftingSystem::new(),
            enchantments: EnchantmentLibrary::new(),
            item_generator: ItemGenerator::new(1),
            dungeon_simulator: DungeonSimulator::new(2),
            event_manager: EventManager::new(),
            pity_system: PitySystem::new(0.01, 50, 100),
            streak_counter: 0,
            loot_filter: LootFilterExt::default(),
        }
    }
    pub fn full_roll(&mut self, table_id: u32) -> Vec<DropResult> {
        self.core_editor.roll_table(table_id)
    }
}

impl Default for LootFilterExt {
    fn default() -> Self {
        Self { rules: Vec::new(), enabled: true, log_filtered: false }
    }
}

impl Default for LootContext {
    fn default() -> Self {
        Self { player_level: 1, magic_find: 0.0, gold_find: 0.0, zone_id: 1, kill_streak: 0, is_boss_kill: false, party_size: 1, modifiers: Vec::new() }
    }
}

// ============================================================
// SECTION: LOOT PIPELINE (trait objects)
// ============================================================

pub trait LootModifier {
    fn apply(&self, rolls: &mut Vec<DropResult>, rng: &mut LootRng);
    fn name(&self) -> &str;
    fn priority(&self) -> i32 { 0 }
}

pub struct MagicFindModifier { pub bonus_pct: f32 }
impl LootModifier for MagicFindModifier {
    fn apply(&self, rolls: &mut Vec<DropResult>, _rng: &mut LootRng) {
        let extra = (rolls.len() as f32 * self.bonus_pct) as usize;
        for i in 0..extra.min(rolls.len()) { rolls[i].count += 1; }
    }
    fn name(&self) -> &str { "MagicFind" }
    fn priority(&self) -> i32 { 10 }
}

pub struct BossKillModifier { pub extra_roll_chance: f32 }
impl LootModifier for BossKillModifier {
    fn apply(&self, rolls: &mut Vec<DropResult>, rng: &mut LootRng) {
        if rng.next_f32() < self.extra_roll_chance {
            if let Some(first) = rolls.first().cloned() {
                rolls.push(DropResult { item_id: first.item_id + 1, count: 1, is_guaranteed: false, from_pity: false });
            }
        }
    }
    fn name(&self) -> &str { "BossKill" }
    fn priority(&self) -> i32 { 5 }
}

pub struct LootPipeline {
    pub modifiers: Vec<Box<dyn LootModifier>>,
    pub rng: LootRng,
}

impl LootPipeline {
    pub fn new(seed: u64) -> Self { Self { modifiers: Vec::new(), rng: LootRng::new(seed) } }
    pub fn add_modifier(&mut self, m: Box<dyn LootModifier>) { self.modifiers.push(m); }
    pub fn process(&mut self, mut rolls: Vec<DropResult>) -> Vec<DropResult> {
        for modifier in &self.modifiers {
            modifier.apply(&mut rolls, &mut self.rng);
        }
        rolls
    }
}

// ============================================================
// SECTION: HIERARCHY AND STREAK
// ============================================================

pub struct LootTableHierarchy {
    pub tables: HashMap<u32, LootTable>,
    pub parent_map: HashMap<u32, u32>,
}

impl LootTableHierarchy {
    pub fn new() -> Self { Self { tables: HashMap::new(), parent_map: HashMap::new() } }
    pub fn add_table(&mut self, table: LootTable, parent_id: Option<u32>) {
        let id = table.id;
        self.tables.insert(id, table);
        if let Some(parent) = parent_id { self.parent_map.insert(id, parent); }
    }
    pub fn get_inherited_entries(&self, table_id: u32) -> Vec<LootTableEntry> {
        let mut entries = Vec::new();
        let mut current_id = table_id;
        let mut visited = HashSet::new();
        loop {
            if visited.contains(&current_id) { break; }
            visited.insert(current_id);
            if let Some(table) = self.tables.get(&current_id) { entries.extend(table.entries.clone()); }
            match self.parent_map.get(&current_id) { Some(&parent) => current_id = parent, None => break }
        }
        entries
    }
}

pub struct DropStreakTracker {
    pub dry_streak: u32, pub hot_streak: u32, pub best_streak: u32,
    pub worst_drought: u32, pub total_rolls: u32, pub total_drops: u32, pub last_drop_roll: u32,
}

impl DropStreakTracker {
    pub fn new() -> Self { Self { dry_streak: 0, hot_streak: 0, best_streak: 0, worst_drought: 0, total_rolls: 0, total_drops: 0, last_drop_roll: 0 } }
    pub fn record_roll(&mut self, got_drop: bool) {
        self.total_rolls += 1;
        if got_drop {
            self.total_drops += 1;
            if self.dry_streak > self.worst_drought { self.worst_drought = self.dry_streak; }
            self.dry_streak = 0;
            self.hot_streak += 1;
            if self.hot_streak > self.best_streak { self.best_streak = self.hot_streak; }
            self.last_drop_roll = self.total_rolls;
        } else { self.dry_streak += 1; self.hot_streak = 0; }
    }
    pub fn drop_rate(&self) -> f32 {
        if self.total_rolls == 0 { 0.0 } else { self.total_drops as f32 / self.total_rolls as f32 }
    }
    pub fn rolls_since_last_drop(&self) -> u32 { self.total_rolls - self.last_drop_roll }
}

// ============================================================
// SECTION: SALVAGE AND AFFINITY
// ============================================================

#[derive(Clone, Debug)]
pub struct SalvageResult {
    pub item_id: u32,
    pub materials_gained: Vec<(u32, u32)>,
    pub gold_gained: u32,
}

pub struct SalvageSystem {
    pub rng: LootRng,
    pub base_material_id: u32,
}

impl SalvageSystem {
    pub fn new(seed: u64, base_material_id: u32) -> Self { Self { rng: LootRng::new(seed), base_material_id } }
    pub fn salvage(&mut self, item: &GeneratedItem) -> SalvageResult {
        let bonus = match &item.rarity {
            ItemRarity::Common => 1, ItemRarity::Uncommon => 2, ItemRarity::Rare => 4,
            ItemRarity::Epic => 8, ItemRarity::Legendary => 20, ItemRarity::Mythic => 50, ItemRarity::BossExclusive => 30,
        };
        let qty = (1 + self.rng.next_u32() % 3) * bonus;
        SalvageResult { item_id: item.base_item_id, materials_gained: vec![(self.base_material_id, qty)], gold_gained: item.sell_value / 4 }
    }
    pub fn batch_salvage(&mut self, items: &[GeneratedItem]) -> Vec<SalvageResult> { items.iter().map(|i| self.salvage(i)).collect() }
}

#[derive(Clone, Debug)]
pub struct AffinityBonus { pub stat: &'static str, pub bonus_pct: f32 }

#[derive(Clone, Debug)]
pub struct ItemAffinity { pub affinity_id: u32, pub name: &'static str, pub required_items: Vec<u32>, pub bonuses: Vec<AffinityBonus> }

pub struct AffinityRegistry { pub affinities: Vec<ItemAffinity> }

impl AffinityRegistry {
    pub fn new() -> Self { Self { affinities: Vec::new() } }
    pub fn register(&mut self, a: ItemAffinity) { self.affinities.push(a); }
    pub fn total_bonus(&self, equipped: &[u32], stat: &str) -> f32 {
        let eq: HashSet<u32> = equipped.iter().copied().collect();
        self.affinities.iter()
            .filter(|a| a.required_items.iter().all(|id| eq.contains(id)))
            .flat_map(|a| a.bonuses.iter())
            .filter(|b| b.stat == stat)
            .map(|b| b.bonus_pct)
            .sum()
    }
}

// ============================================================
// SECTION: ACHIEVEMENT TRACKER
// ============================================================

#[derive(Clone, Debug)]
pub struct LootAchievement {
    pub id: u32, pub name: &'static str, pub description: &'static str,
    pub target_count: u32, pub current_count: u32, pub completed: bool, pub reward_item_id: Option<u32>,
}

impl LootAchievement {
    pub fn new(id: u32, name: &'static str, description: &'static str, target: u32, reward: Option<u32>) -> Self {
        Self { id, name, description, target_count: target, current_count: 0, completed: false, reward_item_id: reward }
    }
    pub fn increment(&mut self) -> bool {
        if self.completed { return false; }
        self.current_count += 1;
        if self.current_count >= self.target_count { self.completed = true; return true; }
        false
    }
    pub fn progress_pct(&self) -> f32 { (self.current_count as f32 / self.target_count as f32).min(1.0) }
}

pub struct AchievementTracker { pub achievements: Vec<LootAchievement>, pub completed_ids: Vec<u32> }

impl AchievementTracker {
    pub fn new() -> Self {
        Self {
            achievements: vec![
                LootAchievement::new(1, "First Blood", "First drop", 1, Some(9001)),
                LootAchievement::new(2, "Collector", "100 items", 100, Some(9002)),
                LootAchievement::new(3, "Legendary Hunter", "10 legendaries", 10, Some(9003)),
                LootAchievement::new(4, "Boss Slayer", "100 bosses", 100, Some(9004)),
            ],
            completed_ids: Vec::new(),
        }
    }
    pub fn record(&mut self, amount: u32) -> Vec<u32> {
        let mut done = Vec::new();
        for ach in &mut self.achievements {
            for _ in 0..amount {
                if ach.increment() { done.push(ach.id); }
            }
        }
        self.completed_ids.extend_from_slice(&done);
        done
    }
    pub fn completion_rate(&self) -> f32 {
        let n = self.achievements.len();
        if n == 0 { return 0.0; }
        self.achievements.iter().filter(|a| a.completed).count() as f32 / n as f32
    }
}

// ============================================================
// SECTION: VALIDATION AND VERSION
// ============================================================

pub fn validate_loot_system() -> bool {
    let catalog = build_extended_item_catalog();
    assert!(catalog.len() >= 50, "Catalog too small");
    let mut crafting = CraftingSystem::new();
    crafting.build_standard_recipes();
    assert!(!crafting.recipes.is_empty());
    let mut enchants = EnchantmentLibrary::new();
    enchants.build_standard_library();
    assert!(!enchants.enchantments.is_empty());
    let mut gen = ItemGenerator::new(1);
    let item = gen.generate_item(100, "Test", 50, 100.0);
    assert!(item.sell_value > 0 || item.rarity == ItemRarity::Common);
    true
}

pub fn loot_editor_version() -> &'static str { "LootEditor v2.0 - Full System" }
pub fn loot_editor_full_version() -> &'static str { "LootEditor v2.1 - Complete" }

#[test]
fn test_loot_system_validation() { assert!(validate_loot_system()); }

#[test]
fn test_alias_table_impl() {
    let table = AliasTable::build(&[1.0, 2.0, 3.0, 4.0]);
    let mut rng = LootRng::new(42);
    let s = table.sample(&mut rng);
    assert!(s < 4);
}

#[test]
fn test_pity_system_hard() {
    let mut pity = PitySystem::new(0.01, 50, 100);
    let mut rng = LootRng::new(42);
    pity.current_rolls = 99;
    assert!(pity.roll(&mut rng));
}

#[test]
fn test_item_impl() {
    let item = Item::new(1, "Test", ItemType::Weapon, ItemRarity::Common, 10.0);
    assert!(item.market_value() > 0.0);
}

#[test]
fn test_crafting_impl() {
    let mut cs = CraftingSystem::new();
    cs.build_standard_recipes();
    assert!(!cs.recipes.is_empty());
    let mut rng = LootRng::new(42);
    let result = cs.craft(1, 50, &mut rng);
    match result {
        CraftResult::Success { .. } | CraftResult::Failed { .. } => {}
    }
}

#[test]
fn test_drop_streak() {
    let mut tracker = DropStreakTracker::new();
    for _ in 0..10 { tracker.record_roll(false); }
    tracker.record_roll(true);
    assert_eq!(tracker.worst_drought, 10);
    assert!(tracker.drop_rate() > 0.0);
}

#[test]
fn test_loot_rng() {
    let mut rng = LootRng::new(12345);
    let v = rng.next_f32();
    assert!(v >= 0.0 && v <= 1.0);
    let u = rng.next_u32_range(0, 100);
    assert!(u < 100);
}