-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEntityEffectManager.cs
2397 lines (2060 loc) · 99.7 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-2020 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 ([email protected])
// Contributors: Numidium
//
// Notes:
//
using UnityEngine;
using System;
using System.Collections.Generic;
using DaggerfallConnect;
using DaggerfallConnect.FallExe;
using DaggerfallConnect.Save;
using DaggerfallWorkshop.Utility;
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 rerollMinimumHours = 6;
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;
readonly List<LiveEffectBundle> instancedBundles = new List<LiveEffectBundle>();
readonly List<LiveEffectBundle> bundlesToRemove = new List<LiveEffectBundle>();
bool wipeAllBundles = false;
float timeLastCastSoundPlayed;
int[] directStatMods = new int[DaggerfallStats.Count];
int[] directSkillMods = new int[DaggerfallSkills.Count];
int[] combinedStatMods = new int[DaggerfallStats.Count];
int[] combinedStatMaxMods = new int[DaggerfallStats.Count];
int[] combinedSkillMods = new int[DaggerfallSkills.Count];
int[] combinedResistanceMods = new int[DaggerfallResistances.Count];
float refreshModsTimer = 0;
const float refreshModsDelay = 0.2f;
RacialOverrideEffect racialOverrideEffect;
PassiveSpecialsEffect passiveSpecialsEffect;
Dictionary<ulong, DaggerfallUnityItem> activeMagicItemsInRound = new Dictionary<ulong, DaggerfallUnityItem>();
Dictionary<ulong, DaggerfallUnityItem> itemsPendingReroll = new Dictionary<ulong, DaggerfallUnityItem>();
#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;
if (IsPlayerEntity)
{
DaggerfallRestWindow.OnSleepEnd += DaggerfallRestWindow_OnSleepEnd;
EntityEffectBroker.OnEndSyntheticTimeIncrease += EntityEffectBroker_OnEndSyntheticTimeIncrease;
}
}
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;
SaveLoadManager.OnStartLoad -= SaveLoadManager_OnStartLoad;
StartGameBehaviour.OnNewGame -= StartGameBehaviour_OnNewGame;
if (IsPlayerEntity)
{
DaggerfallRestWindow.OnSleepEnd -= DaggerfallRestWindow_OnSleepEnd;
EntityEffectBroker.OnEndSyntheticTimeIncrease -= EntityEffectBroker_OnEndSyntheticTimeIncrease;
}
}
private void Update()
{
// Do nothing if no peer entity, game not in play, or load in progress
if (!entityBehaviour || !GameManager.Instance.IsPlayingGame() || SaveLoadManager.Instance.LoadInProgress)
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;
return;
}
// 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)
{
// Player must always have passive specials effect
PassiveSpecialsCheck();
// Fire no anim spells
if (readySpell != null && readySpell.Settings.NoCastingAnims)
{
CastNoAnimSpell();
return;
}
// 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)
{
if (GameManager.Instance.PlayerEntity.Items.Contains(ItemGroups.MiscItems, (int)MiscItems.Spellbook))
SetReadySpell(lastSpell);
else
DaggerfallUI.AddHUDText(TextManager.Instance.GetText(textDatabase, "noSpellbook"));
return;
}
// Abort spell
if (InputManager.Instance.ActionStarted(InputManager.Actions.AbortSpell) && readySpell != null)
{
AbortReadySpell();
}
}
// Enemies always cast ready spell instantly once queued
else
{
CastReadySpell();
}
}
#endregion
#region Public Methods
/// <summary>
/// Sets ready spell directly from a classic spell index.
/// </summary>
public bool SetReadySpell(int classicSpellIndex, bool noSpellPointCost = false)
{
SpellRecord.SpellRecordData spell;
if (GameManager.Instance.EntityEffectBroker.GetClassicSpellRecord(classicSpellIndex, out spell))
{
// Create effect bundle settings from classic spell
EffectBundleSettings bundleSettings = new EffectBundleSettings();
if (GameManager.Instance.EntityEffectBroker.ClassicSpellRecordDataToEffectBundleSettings(spell, BundleTypes.Spell, out bundleSettings))
{
EntityEffectBundle bundle = new EntityEffectBundle(bundleSettings, GameManager.Instance.PlayerEntityBehaviour);
return SetReadySpell(bundle, noSpellPointCost);
}
}
else
{
Debug.LogFormat("SetReadySpell() failed to GetClassicSpellRecord() for classic spell index {0}", classicSpellIndex);
}
return false;
}
/// <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 or cast already in progress
if ((SilenceCheck() && !noSpellPointCost) || castInProgress)
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, null, spell.Settings.MinimumCastingCost);
// 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
// Classic does not enforce this for enemies, they can cast any spell as long as they still have at least 1 spell point.
// Doing the same here. This also matters for classic AI combat logic, as it uses the existence of any remaining spell points
// to determine whether or not it can still cast spells.
if (IsPlayerEntity && entityBehaviour.Entity.CurrentMagicka < readySpellCastingCost && !godModeCast && !noSpellPointCost)
{
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 CastNoAnimSpell()
{
// Must have a spell loaded
if (readySpell == null)
return;
// Assign bundle directly to self if target is caster
// Otherwise instatiate missile prefab based on element type
if (readySpell.Settings.TargetType == TargetTypes.CasterOnly)
{
AssignBundle(readySpell);
}
else
{
DaggerfallMissile missile = InstantiateSpellMissile(readySpell.Settings.ElementType);
if (missile)
missile.Payload = readySpell;
}
// Deduct spellpoint cost from entity if not free (magic item, innate ability)
if (!readySpellDoesNotCostSpellPoints)
entityBehaviour.Entity.DecreaseMagicka(readySpellCastingCost);
// Clear ready spell and reset casting - do not store last spell for no anim spells (prevent spamming)
RaiseOnCastReadySpell(readySpell);
lastSpell = null;
readySpell = null;
readySpellCastingCost = 0;
instantCast = false;
castInProgress = false;
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;
// Player must be in range to release a touch spell
// Enemies use AI to only cast touch spells within range
if (IsPlayerEntity && readySpell.Settings.TargetType == TargetTypes.ByTouch)
{
Vector3 aimPosition = GameManager.Instance.MainCamera.transform.position;
Vector3 aimDirection = GameManager.Instance.MainCamera.transform.forward;
if (DaggerfallMissile.GetEntityTargetInTouchRange(aimPosition, aimDirection) == null)
{
//Debug.Log("Target entity not in range for touch spell.");
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, AssignBundleFlags flags = AssignBundleFlags.None)
{
// Check flags
bool showNonPlayerFailures = (flags & AssignBundleFlags.ShowNonPlayerFailures) == AssignBundleFlags.ShowNonPlayerFailures;
bool bypassSavingThrows = (flags & AssignBundleFlags.BypassSavingThrows) == AssignBundleFlags.BypassSavingThrows;
bool specialInfection = (flags & AssignBundleFlags.SpecialInfection) == AssignBundleFlags.SpecialInfection;
// 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.runtimeFlags = sourceBundle.Settings.RuntimeFlags;
instancedBundle.name = sourceBundle.Settings.Name;
instancedBundle.iconIndex = sourceBundle.Settings.IconIndex;
instancedBundle.icon = sourceBundle.Settings.Icon;
instancedBundle.fromEquippedItem = sourceBundle.FromEquippedItem;
instancedBundle.castByItem = sourceBundle.CastByItem;
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;
}
// Assign any enchantment params to live effect
effect.EnchantmentParam = sourceBundle.Settings.Effects[i].EnchantmentParam;
// Incoming disease and paralysis effects are blocked if entity is hard immune (e.g. vampires/lycanthropes)
// The exceptions are vampirism/lycanthropy special infections themselves which ignore disease resistance
if (effect is DiseaseEffect && IsEntityImmuneToDisease() && !specialInfection ||
effect is Paralyze && IsEntityImmuneToParalysis())
{
continue;
}
// Set parent bundle
effect.ParentBundle = instancedBundle;
// Spell Absorption, Reflection, Resistance - must have a caster entity set
if (sourceBundle.CasterEntityBehaviour)
{
// Spell Absorption
int absorbSpellPoints;
if (sourceBundle.Settings.BundleType == BundleTypes.Spell && 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;
}
// Spell Reflection
if (!bypassSavingThrows && sourceBundle.Settings.BundleType == BundleTypes.Spell && TryReflection(sourceBundle))
continue;
// Spell Resistance
if (!bypassSavingThrows && sourceBundle.Settings.BundleType == BundleTypes.Spell && TryResistance(sourceBundle))
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;
}
// Saving throw handling
// For effects without magnitude (e.g. paralysis) the entity has a chance to save against entire effect using a saving throw
// For effects with magnitude (e.g. most Destruction magic) this is handled later when the effect rolls for magnitude
// Self-cast spells (e.g. self heals and buffs) should never be saved against
if (!bypassSavingThrows &&
!effect.BypassSavingThrows &&
!effect.Properties.SupportMagnitude &&
sourceBundle.Settings.TargetType != TargetTypes.CasterOnly)
{
// Immune if saving throw made
if (FormulaHelper.SavingThrow(effect, entityBehaviour.Entity) == 0)
{
if (IsPlayerEntity || showNonPlayerFailures)
{
// Output "Save versus spell made." for external contact spells
DaggerfallUI.AddHUDText(TextManager.Instance.GetText(textDatabase, "saveVersusSpellMade"));
}
continue;
}
}
// Player is immune to paralysis in god mode
if (IsPlayerEntity && GameManager.Instance.PlayerEntity.GodMode && effect is Paralyze)
continue;
// Add effect
instancedBundle.liveEffects.Add(effect);
// Cache racial override effect
if (effect is RacialOverrideEffect)
racialOverrideEffect = (RacialOverrideEffect)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}] {1}", instancedBundle.name, instancedBundle.GetHashCode());
}
}
/// <summary>
/// Checks if peered entity is globally immune to disease from career, race, and effect system.
/// </summary>
/// <returns>True if entity immune to disease.</returns>
public bool IsEntityImmuneToDisease()
{
// Entity is hard immune from career or effect
if (entityBehaviour.Entity.Career.Disease == DFCareer.Tolerance.Immune || entityBehaviour.Entity.IsImmuneToDisease)
return true;
// Player entity is hard immune from racial template unless they have an overriding career weakness
if (IsPlayerEntity && (((PlayerEntity)entityBehaviour.Entity).GetLiveRaceTemplate().ImmunityFlags & DFCareer.EffectFlags.Disease) != 0)
{
return entityBehaviour.Entity.Career.Disease != DFCareer.Tolerance.LowTolerance &&
entityBehaviour.Entity.Career.Disease != DFCareer.Tolerance.CriticalWeakness;
}
// Not hard immune - fallback to saving throws where entity may still have enhanced resistance
return false;
}
/// <summary>
/// Checks if peered entity is globally immune to paralysis from career, race, and effect system.
/// </summary>
/// <returns>True if entity immune to paralysis.</returns>
public bool IsEntityImmuneToParalysis()
{
// Entity is hard immune from career or effect
if (entityBehaviour.Entity.Career.Paralysis == DFCareer.Tolerance.Immune || entityBehaviour.Entity.IsImmuneToParalysis)
return true;
// Player entity is hard immune from racial template unless they have an overriding career weakness
if (IsPlayerEntity && (((PlayerEntity)entityBehaviour.Entity).GetLiveRaceTemplate().ImmunityFlags & DFCareer.EffectFlags.Paralysis) != 0)
{
return entityBehaviour.Entity.Career.Paralysis != DFCareer.Tolerance.LowTolerance &&
entityBehaviour.Entity.Career.Paralysis != DFCareer.Tolerance.CriticalWeakness;
}
// Not hard immune - fallback to saving throws where entity may still have enhanced resistance
return false;
}
/// <summary>
/// Searches all effects in all bundles to find incumbent of type T.
/// </summary>
/// <typeparam name="T">Effect class to search for.</typeparam>
/// <returns>Found incumbent effect of type T or null.</returns>
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 find all incumbents of type T.
/// Useful for finding all effects inheriting from a specific parent effect.
/// </summary>
/// <typeparam name="T">Effect class to search for.</typeparam>
/// <returns>All found incumbent effect of type T. Can be null or empty.</returns>
public IEntityEffect[] FindIncumbentEffects<T>()
{
List<IEntityEffect> effects = new List<IEntityEffect>();
foreach (LiveEffectBundle bundle in instancedBundles)
{
foreach (IEntityEffect effect in bundle.liveEffects)
{
if (effect is T)
effects.Add(effect);
}
}
return effects.ToArray();
}
/// <summary>
/// Gets current racial override effect if one is present.
/// Racial override is a special case effect that is cached when started/resumed on entity.
/// While is possible to use <see cref="FindIncumbentEffect{RacialOverrideEffect}()"/>, this method is more efficient.
/// </summary>
/// <returns>RacialOverrideEffect or null.</returns>
public RacialOverrideEffect GetRacialOverrideEffect()
{
return racialOverrideEffect;
}
/// <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, 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();
itemsPendingReroll.Clear();
RaiseOnRemoveBundle(null);
racialOverrideEffect = null;
passiveSpecialsEffect = 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];
}
}
/// <summary>
/// Clears all bundles of BundleTypes.Spell.
/// </summary>
public void ClearSpellBundles()
{
foreach (LiveEffectBundle bundle in instancedBundles)
{
// Expire spell bundles
if (bundle.bundleType == BundleTypes.Spell)
bundlesToRemove.Add(bundle);
}
RemovePendingBundles();
}
/// <summary>
/// Instantiates a spell missile based on prefabs set to player.
/// Mainly used by player casting and action records that throw spells at player.
/// </summary>
/// <param name="elementType">Element of missile.</param>
/// <returns>DaggerfallMissile.</returns>
public DaggerfallMissile InstantiateSpellMissile(ElementTypes elementType)
{
DaggerfallMissile missile = null;
switch (elementType)
{
case ElementTypes.Cold:
missile = Instantiate(ColdMissilePrefab);
break;
case ElementTypes.Fire:
missile = Instantiate(FireMissilePrefab);
break;
case ElementTypes.Poison:
missile = Instantiate(PoisonMissilePrefab);
break;
case ElementTypes.Shock:
missile = Instantiate(ShockMissilePrefab);
break;
case ElementTypes.Magic:
missile = Instantiate(MagicMissilePrefab);
break;
default:
return null;
}
if (missile)
{
missile.transform.parent = GameObjectHelper.GetBestParent();
}
return missile;
}
/// <summary>
/// Allows any effect to update HUD icons when an immediate refresh is required.
/// Example is when an effect ends prematurely due to some condition (e.g. Shield spell busted).
/// </summary>
public void UpdateHUDSpellIcons()
{
if (DaggerfallUI.Instance.enableHUD && DaggerfallUI.Instance.DaggerfallHUD.ActiveSpells != null)
DaggerfallUI.Instance.DaggerfallHUD.ActiveSpells.UpdateIcons();
}
/// <summary>
/// Creates a simple single-effect spell bundle from the specified effect key.
/// </summary>
/// <param name="effectKey">Effect key to create bundle from.</param>
/// <param name="element">Element type for bundle. Defaults to Magic.</param>
/// <param name="effectSettings">Effect settings. Uses full defaults if null.</param>
/// <returns>EntityEffectBundle.</returns>
public EntityEffectBundle CreateSpellBundle(string effectKey, ElementTypes element = ElementTypes.Magic, EffectSettings? effectSettings = null)
{
if (effectSettings == null)
effectSettings = BaseEntityEffect.DefaultEffectSettings();
EffectBundleSettings settings = new EffectBundleSettings()
{
Version = EntityEffectBroker.CurrentSpellVersion,
BundleType = BundleTypes.Spell,
ElementType = element,
Effects = new EffectEntry[] { new EffectEntry(effectKey, effectSettings.Value) },
};
return new EntityEffectBundle(settings, entityBehaviour);
}
#endregion
#region Potions
public void DrinkPotion(DaggerfallUnityItem item)
{
// Item must be a valid potion.
if (item == null || item.PotionRecipeKey == 0)
return;
// Get potion recipe and main effect. (most potions only have one effect)
EntityEffectBroker effectBroker = GameManager.Instance.EntityEffectBroker;
PotionRecipe potionRecipe = effectBroker.GetPotionRecipe(item.PotionRecipeKey);
IEntityEffect potionEffect = effectBroker.GetPotionRecipeEffect(potionRecipe);
// Get any secondary effects and generate the effect entry array. (a single settings struct is shared between the effects)
EffectEntry[] potionEffects;
List<string> secondaryEffects = potionRecipe.SecondaryEffects;
if (secondaryEffects != null)
{
potionEffects = new EffectEntry[secondaryEffects.Count + 1];
potionEffects[0] = new EffectEntry(potionEffect.Key, potionRecipe.Settings);
for (int i = 0; i < secondaryEffects.Count; i++)
{
IEntityEffect effect = effectBroker.GetEffectTemplate(secondaryEffects[i]);
potionEffects[i+1] = new EffectEntry(effect.Key, potionRecipe.Settings);
}
}
else
{
potionEffects = new EffectEntry[] { new EffectEntry(potionEffect.Key, potionRecipe.Settings) };
}
// Create the effect bundle settings.
EffectBundleSettings bundleSettings = new EffectBundleSettings()
{
Version = EntityEffectBroker.CurrentSpellVersion,
BundleType = BundleTypes.Potion,
TargetType = TargetTypes.CasterOnly,
Effects = potionEffects,
};
// Assign effect bundle.
EntityEffectBundle bundle = new EntityEffectBundle(bundleSettings, entityBehaviour);
AssignBundle(bundle, AssignBundleFlags.BypassSavingThrows);
// Play cast sound on drink for player only.
if (IsPlayerEntity)
PlayCastSound(entityBehaviour, GetCastSoundID(ElementTypes.Magic));
}
#endregion
#region Magic Items
/// <summary>
/// Executes payloads on enchanted items.
/// </summary>
/// <param name="flags">Payloads to execute. Required by all payloads.</param>
/// <param name="sourceItem">Item to execute payloads from. Required by all payloads. Item must be enchanted.</param>
/// <param name="sourceCollection">ItemCollection the enchanted item belongs to. Required by Used payload.</param>
/// <param name="targetEntity">Target entity of attack by this entity. Required by Strikes payload.</param>
/// <param name="damageIn">Input damage before effects. Required by Strikes payload.</param>
/// <returns>Output damage after effect. Only changes for Strikes payload.</returns>
public int DoItemEnchantmentPayloads(
EnchantmentPayloadFlags flags,
DaggerfallUnityItem sourceItem,
ItemCollection sourceCollection = null,
DaggerfallEntityBehaviour targetEntity = null,
int damageIn = 0)
{
int damageOut = damageIn;
// Must specify an item
if (sourceItem == null)
return damageOut;
// Get combined enchantments
EnchantmentSettings[] enchantments = sourceItem.GetCombinedEnchantmentSettings();
if (enchantments == null || enchantments.Length == 0)
return damageOut;
// Process all enchantments
foreach (EnchantmentSettings settings in enchantments)
{
// Get effect template
IEntityEffect effectTemplate = GameManager.Instance.EntityEffectBroker.GetEffectTemplate(settings.EffectKey);
if (effectTemplate == null)
{
Debug.LogWarningFormat("DoItemEnchantmentPayloads() effect key {0} not found in broker.", settings.EffectKey);
return damageOut;
}
// Equipped payload
if ((flags & EnchantmentPayloadFlags.Equipped) == EnchantmentPayloadFlags.Equipped && effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.Equipped))
StartEquippedItem(effectTemplate, sourceItem, settings);
// Held payload
// Note: EnchantmentPayloadFlags.Held means the effect wants a long-running bundle assigned, it is unrelated to "cast when held" legacy enchantment
if ((flags & EnchantmentPayloadFlags.Held) == EnchantmentPayloadFlags.Held && effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.Held))
StartHeldItem(effectTemplate, sourceItem, settings);
// Unequip payload
if ((flags & EnchantmentPayloadFlags.Unequipped) == EnchantmentPayloadFlags.Unequipped)
UnequipHeldItem(effectTemplate, sourceItem, settings);
// Used payload
if ((flags & EnchantmentPayloadFlags.Used) == EnchantmentPayloadFlags.Used && effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.Used))
UseItem(effectTemplate, sourceItem, settings, sourceCollection);
// Strikes payload
if ((flags & EnchantmentPayloadFlags.Strikes) == EnchantmentPayloadFlags.Strikes && effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.Strikes))
damageOut += StrikeWithItem(effectTemplate, sourceItem, settings, targetEntity, damageIn);
// Breaks payload
if ((flags & EnchantmentPayloadFlags.Breaks) == EnchantmentPayloadFlags.Breaks && effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.Breaks))
BrokenItem(effectTemplate, sourceItem, settings);
// Do not call following payloads if item has broken
if (sourceItem.currentCondition > 0)
{
// MagicRound payload
if ((flags & EnchantmentPayloadFlags.MagicRound) == EnchantmentPayloadFlags.MagicRound && effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.MagicRound))
MagicRoundCallback(effectTemplate, sourceItem, settings);
// RerollEffect payload
if ((flags & EnchantmentPayloadFlags.RerollEffect) == EnchantmentPayloadFlags.RerollEffect && effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.RerollEffect))
RerollEffectCallback(effectTemplate, sourceItem, settings);