/
EntityEffectManager.cs
1632 lines (1394 loc) · 63.9 KB
/
EntityEffectManager.cs
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Project: Daggerfall Tools For Unity
// Copyright: Copyright (C) 2009-2018 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using UnityEngine;
using System;
using System.Collections.Generic;
using DaggerfallConnect;
using DaggerfallConnect.FallExe;
using DaggerfallConnect.Save;
using DaggerfallWorkshop.Game.Entity;
using DaggerfallWorkshop.Game.UserInterfaceWindows;
using DaggerfallWorkshop.Game.Serialization;
using DaggerfallWorkshop.Game.Utility;
using DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects;
using DaggerfallWorkshop.Game.Formulas;
using DaggerfallWorkshop.Game.Items;
using FullSerializer;
namespace DaggerfallWorkshop.Game.MagicAndEffects
{
/// <summary>
/// Peered with a DaggerfallEntityBehaviour for magic and effect handling related to that entity.
/// Manages list of active effects currently operating on peered entity.
/// Used by player and enemies to send and receive magic effects from various sources.
/// NOTE: Under active development and subject to frequent change.
/// </summary>
public class EntityEffectManager : MonoBehaviour
{
#region Fields
const string textDatabase = "ClassicEffects";
const string youDontHaveTheSpellPointsMessageKey = "youDontHaveTheSpellPoints";
const int minAcceptedSpellVersion = 1;
const int magicCastSoundID = 349;
const int poisonCastSoundID = 350;
const int shockCastSoundID = 351;
const int fireCastSoundID = 352;
const int coldCastSoundID = 353;
public DaggerfallMissile FireMissilePrefab;
public DaggerfallMissile ColdMissilePrefab;
public DaggerfallMissile PoisonMissilePrefab;
public DaggerfallMissile ShockMissilePrefab;
public DaggerfallMissile MagicMissilePrefab;
EntityEffectBundle readySpell = null;
EntityEffectBundle lastSpell = null;
bool instantCast = false;
bool castInProgress = false;
bool readySpellDoesNotCostSpellPoints = false;
int readySpellCastingCost;
DaggerfallEntityBehaviour entityBehaviour = null;
EntityTypes entityType;
List<LiveEffectBundle> instancedBundles = new List<LiveEffectBundle>();
List<LiveEffectBundle> bundlesToRemove = new List<LiveEffectBundle>();
bool wipeAllBundles = false;
int[] directStatMods = new int[DaggerfallStats.Count];
int[] directSkillMods = new int[DaggerfallSkills.Count];
int[] combinedStatMods = new int[DaggerfallStats.Count];
int[] combinedSkillMods = new int[DaggerfallSkills.Count];
int[] combinedResistanceMods = new int[DaggerfallResistances.Count];
float refreshModsTimer = 0;
const float refreshModsDelay = 0.2f;
#endregion
#region Properties
public bool HasReadySpell
{
get { return (readySpell != null); }
}
public EntityEffectBundle ReadySpell
{
get { return readySpell; }
set { readySpell = value; }
}
public EntityEffectBundle LastSpell
{
get { return lastSpell; }
}
public DaggerfallEntityBehaviour EntityBehaviour
{
get { return entityBehaviour; }
}
public bool IsPlayerEntity
{
get { return (entityType == EntityTypes.Player); }
}
public LiveEffectBundle[] EffectBundles
{
get { return instancedBundles.ToArray(); }
}
public int EffectCount
{
get { return instancedBundles.Count; }
}
public int DiseaseCount
{
get { return GetDiseaseCount(); }
}
public LiveEffectBundle[] DiseaseBundles
{
get { return GetDiseaseBundles(); }
}
public int PoisonCount
{
get { return GetPoisonCount(); }
}
public LiveEffectBundle[] PoisonBundles
{
get { return GetPoisonBundles(); }
}
#endregion
#region Unity
private void Awake()
{
// Check if this is player's effect manager
// We do some extra coordination for player
entityBehaviour = GetComponent<DaggerfallEntityBehaviour>();
if (entityBehaviour)
{
entityType = entityBehaviour.EntityType;
}
// Only player listens for release frame
if (IsPlayerEntity)
GameManager.Instance.PlayerSpellCasting.OnReleaseFrame += PlayerSpellCasting_OnReleaseFrame;
// Wire up events
EntityEffectBroker.OnNewMagicRound += EntityEffectBroker_OnNewMagicRound;
SaveLoadManager.OnStartLoad += SaveLoadManager_OnStartLoad;
StartGameBehaviour.OnNewGame += StartGameBehaviour_OnNewGame;
}
private void Start()
{
// Listen for entity death to remove effect bundles
if (entityBehaviour && entityBehaviour.Entity != null)
{
entityBehaviour.Entity.OnDeath += Entity_OnDeath;
}
}
private void OnDestroy()
{
EntityEffectBroker.OnNewMagicRound -= EntityEffectBroker_OnNewMagicRound;
}
private void Update()
{
// Do nothing if no peer entity
if (!entityBehaviour)
return;
// Remove any bundles pending deletion
RemovePendingBundles();
// Run any per-frame constant effects
DoConstantEffects();
// Refresh mods more frequently than magic rounds, but not too frequently
refreshModsTimer += Time.deltaTime;
if (refreshModsTimer > refreshModsDelay)
{
UpdateEntityMods();
refreshModsTimer = 0;
}
// Wipe all bundles if scheduled - doing here ensures not currently iterating bundles during a magic round
if (wipeAllBundles)
{
WipeAllBundles();
wipeAllBundles = false;
}
// Player can cast a spell, recast last spell, or abort current spell
// Handling input here is similar to handling weapon input in WeaponManager
if (IsPlayerEntity)
{
// Fire instant cast spells
if (readySpell != null && instantCast)
{
CastReadySpell();
return;
}
// Cast spell
if (InputManager.Instance.ActionStarted(InputManager.Actions.ActivateCenterObject) && readySpell != null)
{
CastReadySpell();
return;
}
// Recast spell - not available while playing another spell animation
if (InputManager.Instance.ActionStarted(InputManager.Actions.RecastSpell) && lastSpell != null &&
!GameManager.Instance.PlayerSpellCasting.IsPlayingAnim)
{
SetReadySpell(lastSpell);
return;
}
// Abort spell
if (InputManager.Instance.ActionStarted(InputManager.Actions.AbortSpell) && readySpell != null)
{
AbortReadySpell();
return;
}
}
// Enemies always cast ready spell instantly once queued
else
{
CastReadySpell();
}
}
#endregion
#region Public Methods
/// <summary>
/// Assigns a new spell to be cast.
/// For player entity, this will display "press button to fire spell" message.
/// </summary>
public bool SetReadySpell(EntityEffectBundle spell, bool noSpellPointCost = false)
{
// Do nothing if silenced
if (SilenceCheck() && !noSpellPointCost)
return false;
// Spell must appear valid
if (spell == null || spell.Settings.Version < minAcceptedSpellVersion)
return false;
// Get spellpoint costs of this spell
int totalGoldCostUnused;
FormulaHelper.CalculateTotalEffectCosts(spell.Settings.Effects, spell.Settings.TargetType, out totalGoldCostUnused, out readySpellCastingCost);
// Allow casting spells of any cost if entity is player and godmode enabled
bool godModeCast = (IsPlayerEntity && GameManager.Instance.PlayerEntity.GodMode);
// Enforce spell point costs - Daggerfall does this when setting ready spell
if (entityBehaviour.Entity.CurrentMagicka < readySpellCastingCost && !godModeCast && !noSpellPointCost)
{
// Output message only for player
if (IsPlayerEntity)
DaggerfallUI.AddHUDText(TextManager.Instance.GetText(textDatabase, youDontHaveTheSpellPointsMessageKey));
readySpell = null;
readySpellCastingCost = 0;
return false;
}
// Assign spell - caster only spells are cast instantly
readySpell = spell;
RaiseOnNewReadySpell(spell);
readySpellDoesNotCostSpellPoints = noSpellPointCost;
if (readySpell.Settings.TargetType == TargetTypes.CasterOnly)
instantCast = true;
if (IsPlayerEntity && !instantCast)
{
DaggerfallUI.AddHUDText(HardStrings.pressButtonToFireSpell, 0.4f);
}
return true;
}
public void AbortReadySpell()
{
readySpell = null;
readySpellDoesNotCostSpellPoints = false;
}
public void CastReadySpell()
{
// Do nothing if silenced
if (SilenceCheck())
return;
// Must have a ready spell and a previous cast must not be in progress
if (readySpell == null || castInProgress)
return;
// Deduct spellpoint cost from entity if not free (magic item, innate ability)
if (!readySpellDoesNotCostSpellPoints)
entityBehaviour.Entity.DecreaseMagicka(readySpellCastingCost);
// Play casting animation based on element type
// Spell is released by event handler PlayerSpellCasting_OnReleaseFrame
// TODO: Do not need to show spellcasting animations for certain spell effects
if (IsPlayerEntity)
{
// Play casting animation and block further casting attempts until previous cast is complete
GameManager.Instance.PlayerSpellCasting.PlayOneShot(readySpell.Settings.ElementType);
castInProgress = true;
}
else
{
EnemyCastReadySpell();
}
}
public void AssignBundle(EntityEffectBundle sourceBundle, bool showNonPlayerFailures = false)
{
// Source bundle must have one or more effects
if (sourceBundle.Settings.Effects == null || sourceBundle.Settings.Effects.Length == 0)
{
Debug.LogWarning("AssignBundle() could not assign bundle as source has no effects");
return;
}
// Create new instanced bundle and copy settings from source bundle
LiveEffectBundle instancedBundle = new LiveEffectBundle();
instancedBundle.version = sourceBundle.Settings.Version;
instancedBundle.bundleType = sourceBundle.Settings.BundleType;
instancedBundle.targetType = sourceBundle.Settings.TargetType;
instancedBundle.elementType = sourceBundle.Settings.ElementType;
instancedBundle.name = sourceBundle.Settings.Name;
instancedBundle.iconIndex = sourceBundle.Settings.IconIndex;
instancedBundle.fromEquippedItem = sourceBundle.FromEquippedItem;
instancedBundle.liveEffects = new List<IEntityEffect>();
if (sourceBundle.CasterEntityBehaviour)
{
instancedBundle.caster = sourceBundle.CasterEntityBehaviour;
instancedBundle.casterEntityType = sourceBundle.CasterEntityBehaviour.EntityType;
instancedBundle.casterLoadID = GetCasterLoadID(sourceBundle.CasterEntityBehaviour);
}
// Instantiate all effects in this bundle
for (int i = 0; i < sourceBundle.Settings.Effects.Length; i++)
{
// Instantiate effect
IEntityEffect effect = GameManager.Instance.EntityEffectBroker.InstantiateEffect(sourceBundle.Settings.Effects[i]);
if (effect == null)
{
Debug.LogWarningFormat("AssignBundle() could not add effect as key '{0}' was not found by broker.", sourceBundle.Settings.Effects[i].Key);
continue;
}
// Set parent bundle
effect.ParentBundle = instancedBundle;
// Spell absorption - must have a caster entity set
if (sourceBundle.CasterEntityBehaviour)
{
int absorbSpellPoints;
if (TryAbsorption(effect, sourceBundle.Settings.TargetType, sourceBundle.CasterEntityBehaviour.Entity, out absorbSpellPoints))
{
// Spell passed all checks and was absorbed - return cost output to target
entityBehaviour.Entity.IncreaseMagicka(absorbSpellPoints);
// Output "Spell was absorbed."
DaggerfallUI.AddHUDText(TextManager.Instance.GetText(textDatabase, "spellAbsorbed"));
continue;
}
}
// Start effect
effect.Start(this, sourceBundle.CasterEntityBehaviour);
// Do not proceed if chance failed
if (effect.Properties.SupportChance &&
effect.Properties.ChanceFunction == ChanceFunction.OnCast &&
!effect.ChanceSuccess)
{
// Output failure messages
if (IsPlayerEntity && sourceBundle.Settings.TargetType == TargetTypes.CasterOnly)
{
// Output "Spell effect failed." for caster only spells
DaggerfallUI.AddHUDText(TextManager.Instance.GetText(textDatabase, "spellEffectFailed"));
}
else if (IsPlayerEntity || showNonPlayerFailures)
{
// Output "Save versus spell made." for external contact spells
DaggerfallUI.AddHUDText(TextManager.Instance.GetText(textDatabase, "saveVersusSpellMade"));
}
continue;
}
// Do not add unflagged incumbent effects
// But allow for an icon refresh as duration might have changed and we want to update this sooner than next magic round
if (effect is IncumbentEffect && !(effect as IncumbentEffect).IsIncumbent)
{
RaiseOnAssignBundle(instancedBundle);
continue;
}
// Add effect
instancedBundle.liveEffects.Add(effect);
// At this point effect is ready and gets initial magic round
effect.MagicRound();
}
// Add bundles with at least one effect
if (instancedBundle.liveEffects.Count > 0)
{
instancedBundles.Add(instancedBundle);
RaiseOnAssignBundle(instancedBundle);
Debug.LogFormat("Adding bundle {0}", instancedBundle.GetHashCode());
}
}
/// <summary>
/// Searches all effects in all bundles to find incumbent of type T.
/// </summary>
/// <typeparam name="T">Found incumbent effect of type T or null.</typeparam>
public IEntityEffect FindIncumbentEffect<T>()
{
foreach (LiveEffectBundle bundle in instancedBundles)
{
foreach (IEntityEffect effect in bundle.liveEffects)
{
if (effect is T)
return effect;
}
}
return null;
}
/// <summary>
/// Searches all effects in all bundles to heal an amount of attribute loss.
/// Will spread healing amount across multiple effects if required.
/// </summary>
/// <param name="stat">Attribute to heal.</param>
/// <param name="amount">Amount to heal. Must be a positive value.</param>
public void HealAttribute(DFCareer.Stats stat, int amount)
{
if (amount < 0)
{
Debug.LogWarning("EntityEffectManager.HealDamagedAttribute() received a negative value for amount - ignoring.");
return;
}
int remaining = amount;
foreach (LiveEffectBundle bundle in instancedBundles)
{
foreach (BaseEntityEffect effect in bundle.liveEffects)
{
// Get attribute modifier of this effect and ignore if attribute not damaged
int mod = effect.GetAttributeMod(stat);
if (mod >= 0)
continue;
// Heal all or part of damage depending on how much healing remains
int damage = Mathf.Abs(mod);
if (remaining > damage)
{
effect.HealAttributeDamage(stat, remaining - damage);
remaining -= damage;
}
else
{
effect.HealAttributeDamage(stat, remaining);
return;
}
}
}
}
/// <summary>
/// Cancels all remaining rounds of any active incumbent effect of type T and calls End() on that effect.
/// If incumbent effect T is only live effect in bundle then whole bundle will be removed.
/// If other effects remain in bundle then incumbent effect will stop operation and bundle will expire when other effects allow it.
/// Does nothing if no incumbent effect of type T found.
/// </summary>
/// <typeparam name="T">IncumbentEffect type T to end.</typeparam>
public void EndIncumbentEffect<T>()
{
IEntityEffect effect = FindIncumbentEffect<T>();
if (effect != null)
{
effect.RoundsRemaining = 0;
effect.End();
}
}
/// <summary>
/// Wipe all effect bundles from this entity.
/// </summary>
private void WipeAllBundles()
{
instancedBundles.Clear();
RaiseOnRemoveBundle(null);
}
/// <summary>
/// Merge custom stat mods directly into this entity.
/// Changes reset at the start of each magic round.
/// </summary>
/// <param name="statMods">Stat mods array, must be DaggerfallStats.Count length.</param>
public void MergeDirectStatMods(int[] statMods)
{
if (statMods == null || statMods.Length != DaggerfallStats.Count)
return;
for (int i = 0; i < statMods.Length; i++)
{
directStatMods[i] += statMods[i];
}
}
/// <summary>
/// Merge custom skill mods directly into this entity.
/// Changes reset at the start of each magic round.
/// </summary>
/// <param name="skillMods">Skill mods array, must be DaggerfallSkills.Count length.</param>
public void MergeDirectSkillMods(int[] skillMods)
{
if (skillMods == null || skillMods.Length != DaggerfallSkills.Count)
return;
for (int i = 0; i < skillMods.Length; i++)
{
directSkillMods[i] += skillMods[i];
}
}
public void ClearSpellBundles()
{
foreach (LiveEffectBundle bundle in instancedBundles)
{
// Expire spell bundles
if (bundle.bundleType == BundleTypes.Spell)
bundlesToRemove.Add(bundle);
}
RemovePendingBundles();
}
#endregion
#region Magic Items
/// <summary>
/// Handles any magic-related work of equipping an item to this entity.
/// Does nothing if item contains no "cast when held" enchantments.
/// </summary>
/// <param name="item">Item just equipped.</param>
public void StartEquippedItem(DaggerfallUnityItem item)
{
// Item must have enchancements
if (item == null || !item.IsEnchanted)
return;
// Equipped items must have "cast when held" enchantments
DaggerfallEnchantment[] enchantments = item.Enchantments;
foreach (DaggerfallEnchantment enchantment in enchantments)
{
if (enchantment.type == EnchantmentTypes.CastWhenHeld)
{
SpellRecord.SpellRecordData spell;
if (GameManager.Instance.EntityEffectBroker.GetClassicSpellRecord(enchantment.param, out spell))
{
//Debug.LogFormat("EntityEffectManager.StartEquippedItem: Found CastWhenHeld enchantment '{0}'", spell.spellName);
// Create effect bundle settings from classic spell
EffectBundleSettings bundleSettings = new EffectBundleSettings();
if (!GameManager.Instance.EntityEffectBroker.ClassicSpellRecordDataToEffectBundleSettings(spell, BundleTypes.HeldMagicItem, out bundleSettings))
continue;
// Assign bundle
EntityEffectBundle bundle = new EntityEffectBundle(bundleSettings, entityBehaviour);
bundle.FromEquippedItem = item;
AssignBundle(bundle);
// Play cast sound on equip for player only
if (IsPlayerEntity)
PlayCastSound(entityBehaviour, GetCastSoundID(bundle.Settings.ElementType));
// TODO: Use correct icon - the index in spell record data is the not the icon displayed by classic
// Not sure how this is determined by classic for equipped items, but it is consistent
// TODO: Apply durability loss to equipped item on equip and over time
// http://en.uesp.net/wiki/Daggerfall:Magical_Items#Durability_of_Magical_Items
}
}
}
}
/// <summary>
/// Handles any magic-related work of unequipping an item from this entity
/// </summary>
/// <param name="item">Item just unequipped.</param>
public void StopEquippedItem(DaggerfallUnityItem item)
{
// Item must have enchancements
if (item == null || !item.IsEnchanted)
return;
// Check all running bundles for any linked to this item and schedule instant removal
foreach (LiveEffectBundle bundle in instancedBundles)
{
if (bundle.fromEquippedItem != null && bundle.fromEquippedItem.UID == item.UID)
bundlesToRemove.Add(bundle);
}
}
/// <summary>
/// Offers item to effect manager when used by player in inventory.
/// </summary>
/// <param name="item">Item just used.</param>
public void UseItem(DaggerfallUnityItem item)
{
// Item must have enchancements
if (item == null || !item.IsEnchanted)
return;
// Cast first "cast when used" enchantment
// This works by sending effect to readySpell which currently cannot queue more than one spell
// Not sure how classic handles multiple "cast when used" effects, especially for "press to release" styled spells
DaggerfallEnchantment[] enchantments = item.Enchantments;
foreach (DaggerfallEnchantment enchantment in enchantments)
{
if (enchantment.type == EnchantmentTypes.CastWhenUsed)
{
SpellRecord.SpellRecordData spell;
if (GameManager.Instance.EntityEffectBroker.GetClassicSpellRecord(enchantment.param, out spell))
{
//Debug.LogFormat("EntityEffectManager.UseItem: Found CastWhenUsed enchantment '{0}'", spell.spellName);
// Create effect bundle settings from classic spell
EffectBundleSettings bundleSettings = new EffectBundleSettings();
if (!GameManager.Instance.EntityEffectBroker.ClassicSpellRecordDataToEffectBundleSettings(spell, BundleTypes.Spell, out bundleSettings))
continue;
// Assign bundle to ready spell
EntityEffectBundle bundle = new EntityEffectBundle(bundleSettings, entityBehaviour);
SetReadySpell(bundle, true);
// TODO: Apply durability loss to used item on use
// http://en.uesp.net/wiki/Daggerfall:Magical_Items#Durability_of_Magical_Items
}
break;
}
}
}
/// <summary>
/// Assigns "cast when strikes" effects to this manager.
/// </summary>
/// <param name="item">Item striking this entity.</param>
/// <param name="caster">Entity attacking with item.</param>
public void StrikeWithItem(DaggerfallUnityItem item, DaggerfallEntityBehaviour caster)
{
// Item must have enchancements
if (item == null || !item.IsEnchanted)
return;
// Create bundle for every "cast when strikes" enchantment
List<EntityEffectBundle> bundles = new List<EntityEffectBundle>();
DaggerfallEnchantment[] enchantments = item.Enchantments;
foreach (DaggerfallEnchantment enchantment in enchantments)
{
if (enchantment.type == EnchantmentTypes.CastWhenStrikes)
{
SpellRecord.SpellRecordData spell;
if (GameManager.Instance.EntityEffectBroker.GetClassicSpellRecord(enchantment.param, out spell))
{
//Debug.LogFormat("EntityEffectManager.StrikeWithItem: Found CastWhenStrikes enchantment '{0}'", spell.spellName);
// Create effect bundle settings from classic spell
EffectBundleSettings bundleSettings = new EffectBundleSettings();
if (!GameManager.Instance.EntityEffectBroker.ClassicSpellRecordDataToEffectBundleSettings(spell, BundleTypes.Spell, out bundleSettings))
continue;
// Assign bundle to list
EntityEffectBundle bundle = new EntityEffectBundle(bundleSettings, entityBehaviour);
bundle.CasterEntityBehaviour = caster;
bundles.Add(bundle);
// TODO: Apply durability loss to used item on strike
// http://en.uesp.net/wiki/Daggerfall:Magical_Items#Durability_of_Magical_Items
}
}
}
// Assign bundles to this entity
foreach (EntityEffectBundle bundle in bundles)
{
AssignBundle(bundle, true);
}
}
#endregion
#region Spell Absorption
/// <summary>
/// Tests incoming effect for spell absorption. If absorption succeeds the entity will
/// block effect and recover spell points equal to the casting cost of blocked effect.
/// If target does not have enough spell points free to absorb effect cost then effect will NOT be absorbed.
/// For example if player has 0 of 50 spell points available, they can absorb an incoming effect costing up to 50 spell points.
/// An effect costing 51 spell points cannot be absorbed. It's "all or nothing".
/// Notes:
/// - There are two variants of spell absorption in Daggerfall.
/// - Career-based: This is the "none / in light / in darkness / always" assigned to entity career kit.
/// - Effect-based: Generated by having an active Spell Absorption effect from a spell or item.
/// - In classic effect-based absorption from spells/items will override career-based absorption. Not sure if bug.
/// - Career-based absorption will always succeed chance check.
/// - Spell-based will roll for check on each absorb attempt.
/// </summary>
/// <param name="effect">Incoming effect.</param>
/// <param name="targetType">Source bundle target type for spell cost calculation.</param>
/// <param name="casterEntity">Source caster entity behaviour for spell cost calculation.</param>
/// <param name="absorbSpellPointsOut">Number of spell points absorbed. Only valid when returning true.</param>
/// <returns>True if absorbed.</returns>
bool TryAbsorption(IEntityEffect effect, TargetTypes targetType, DaggerfallEntity casterEntity, out int absorbSpellPointsOut)
{
absorbSpellPointsOut = 0;
// Effect cannot be null
if (effect == null)
return false;
// Currently only absorbing Destruction magic - not sure on status of absorbing other magic schools
// This is to prevent something as benign as a self-heal from player being blocked and absorbed
// With current design, absorption is checked for ALL incoming effects to entity so require some sanity checks
if (effect.Properties.MagicSkill != DFCareer.MagicSkills.Destruction)
return false;
// Get casting cost for this effect
// Costs are calculated as if target cast the spell, not the actual caster
// Note that if player self-absorbs a spell this will be equal anyway
int effectCastingCost = GetEffectCastingCost(effect, targetType, entityBehaviour.Entity);
// The entity must have enough spell points free to absorb incoming effect
int availableSpellPoints = entityBehaviour.Entity.MaxMagicka - entityBehaviour.Entity.CurrentMagicka;
if (effectCastingCost > availableSpellPoints)
return false;
else
absorbSpellPointsOut = effectCastingCost;
// Check if entity has an absorb incumbent running
SpellAbsorption absorbEffect = FindIncumbentEffect<SpellAbsorption>() as SpellAbsorption;
if (absorbEffect != null)
return TryEffectBasedAbsorption(effect, absorbEffect, casterEntity);
// Handle career-based absorption
if (entityBehaviour.Entity.Career.SpellAbsorption != DFCareer.SpellAbsorptionFlags.None)
return TryCareerBasedAbsorption(effect, casterEntity);
return false;
}
int GetEffectCastingCost(IEntityEffect effect, TargetTypes targetType, DaggerfallEntity casterEntity)
{
int goldCost, spellPointCost;
FormulaHelper.CalculateEffectCosts(effect, effect.Settings, out goldCost, out spellPointCost, casterEntity);
spellPointCost = FormulaHelper.ApplyTargetCostMultiplier(spellPointCost, targetType);
//Debug.LogFormat("Calculated {0} spell point cost for effect {1}", spellPointCost, effect.Key);
return spellPointCost;
}
bool TryEffectBasedAbsorption(IEntityEffect effect, SpellAbsorption absorbEffect, DaggerfallEntity casterEntity)
{
return RollAbsorptionChance(absorbEffect, casterEntity);
}
bool TryCareerBasedAbsorption(IEntityEffect effect, DaggerfallEntity casterEntity)
{
// Always resists
DFCareer.SpellAbsorptionFlags spellAbsorption = casterEntity.Career.SpellAbsorption;
if (spellAbsorption == DFCareer.SpellAbsorptionFlags.Always)
return true;
// Resist in darkness (inside building or dungeon or outside at night)
// Use player for inside/outside context - everything is where the player is
if (spellAbsorption == DFCareer.SpellAbsorptionFlags.InDarkness)
{
if (GameManager.Instance.PlayerEnterExit.IsPlayerInside)
return true;
else if (DaggerfallUnity.Instance.WorldTime.Now.IsNight)
return true;
}
// Resist in light (outside during the day)
if (spellAbsorption == DFCareer.SpellAbsorptionFlags.InLight)
{
if (!GameManager.Instance.PlayerEnterExit.IsPlayerInside && DaggerfallUnity.Instance.WorldTime.Now.IsDay)
return true;
}
return false;
}
bool RollAbsorptionChance(SpellAbsorption absorbEffect, DaggerfallEntity casterEntity)
{
int chance = absorbEffect.Settings.ChanceBase + absorbEffect.Settings.ChancePlus * (int)Mathf.Floor(casterEntity.Level / absorbEffect.Settings.ChancePerLevel);
int roll = UnityEngine.Random.Range(1, 100);
return (roll <= chance);
}
#endregion
#region Poisons
/// <summary>
/// Helper to create a classic poison effect bundle.
/// </summary>
/// <param name="poisonType">Classic poison type.</param>
/// <returns>EntityEffectBundle.</returns>
public EntityEffectBundle CreatePoison(Poisons poisonType)
{
EffectBundleSettings settings = new EffectBundleSettings()
{
Version = EntityEffectBroker.CurrentSpellVersion,
BundleType = BundleTypes.Poison,
Effects = new EffectEntry[] { new EffectEntry(PoisonEffect.GetClassicPoisonEffectKey(poisonType)) },
};
return new EntityEffectBundle(settings, entityBehaviour);
}
#endregion
#region Diseases
/// <summary>
/// Helper to create a classic disease effect bundle.
/// </summary>
/// <param name="diseaseType">Classic disease type.</param>
/// <returns>EntityEffectBundle.</returns>
public EntityEffectBundle CreateDisease(Diseases diseaseType)
{
EffectBundleSettings settings = new EffectBundleSettings()
{
Version = EntityEffectBroker.CurrentSpellVersion,
BundleType = BundleTypes.Disease,
Effects = new EffectEntry[] { new EffectEntry(DiseaseEffect.GetClassicDiseaseEffectKey(diseaseType)) },
};
return new EntityEffectBundle(settings, entityBehaviour);
}
/// <summary>
/// Helper to create a disease effect bundle from any effect key.
/// This is just here for testing right now as no custom diseases exist.
/// </summary>
/// <param name="key">Effect key to use as infection.</param>
/// <returns>EntityEffectBundle.</returns>
public EntityEffectBundle CreateDisease(string key)
{
EffectBundleSettings settings = new EffectBundleSettings()
{
Version = EntityEffectBroker.CurrentSpellVersion,
BundleType = BundleTypes.Disease,
Effects = new EffectEntry[] { new EffectEntry(key) },
};
return new EntityEffectBundle(settings, entityBehaviour);
}
public void CureDisease(Diseases disease)
{
// Find specific disease incumbent
LiveEffectBundle[] bundles = GetDiseaseBundles();
foreach (LiveEffectBundle bundle in bundles)
{
// Must have a live effect
if (bundle.liveEffects == null || bundle.liveEffects.Count == 0)
continue;
// Must be a disease effect
if (!(bundle.liveEffects[0] is DiseaseEffect))
continue;
// Must be correct type of disease effect
DiseaseEffect effect = bundle.liveEffects[0] as DiseaseEffect;
if (effect.ClassicDiseaseType == disease)
{
effect.CureDisease();
Debug.LogFormat("Cured disease {0}", disease);
}
}
}
public void CureAllDiseases()
{
// Cure all disease bundles
LiveEffectBundle[] bundles = GetDiseaseBundles();
foreach (LiveEffectBundle bundle in bundles)
{
RemoveBundle(bundle);
Debug.LogFormat("Removing disease bundle {0}", bundle.GetHashCode());
}
}
int GetDiseaseCount()
{
int count = 0;
foreach (LiveEffectBundle bundle in instancedBundles)
{
if (bundle.bundleType == BundleTypes.Disease)
count++;
}
return count;
}
LiveEffectBundle[] GetDiseaseBundles()
{
List<LiveEffectBundle> diseaseBundles = new List<LiveEffectBundle>();
foreach (LiveEffectBundle bundle in instancedBundles)
{
if (bundle.bundleType == BundleTypes.Disease)
diseaseBundles.Add(bundle);
}
return diseaseBundles.ToArray();
}
int GetPoisonCount()
{
int count = 0;
foreach (LiveEffectBundle bundle in instancedBundles)
{
if (bundle.bundleType == BundleTypes.Poison)
count++;
}
return count;
}
LiveEffectBundle[] GetPoisonBundles()
{
List<LiveEffectBundle> poisonBundles = new List<LiveEffectBundle>();
foreach (LiveEffectBundle bundle in instancedBundles)
{
if (bundle.bundleType == BundleTypes.Poison)
poisonBundles.Add(bundle);
}
return poisonBundles.ToArray();
}
public void CureAllPoisons()
{
// Cure all poison bundles
LiveEffectBundle[] bundles = GetPoisonBundles();
foreach (LiveEffectBundle bundle in bundles)
{
RemoveBundle(bundle);
Debug.LogFormat("Removing poison bundle {0}", bundle.GetHashCode());
}
}
#endregion
#region Static Helpers
public static void BreakNormalPowerConcealmentEffects(DaggerfallEntityBehaviour entityBehaviour)
{
// Get entity effect manager
EntityEffectManager manager = entityBehaviour.GetComponent<EntityEffectManager>();
if (!manager)
return;
// End Chameleon-Normal
if (entityBehaviour.Entity.HasConcealment(MagicalConcealmentFlags.BlendingNormal))
manager.EndIncumbentEffect<ChameleonNormal>();
// End Invisibility-Normal
if (entityBehaviour.Entity.HasConcealment(MagicalConcealmentFlags.InvisibleNormal))
manager.EndIncumbentEffect<InvisibilityNormal>();
// End Shadow-Normal