-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCalRemixHelper.cs
More file actions
2556 lines (2395 loc) · 125 KB
/
CalRemixHelper.cs
File metadata and controls
2556 lines (2395 loc) · 125 KB
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
using CalamityMod;
using CalamityMod.CalPlayer;
using CalamityMod.DataStructures;
using CalamityMod.Projectiles.Summon;
using CalamityMod.World;
using CalRemix.Content.Items.Ammo;
using CalRemix.UI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ReLogic.Content;
using SubworldLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Terraria;
using Terraria.Audio;
using Terraria.Chat;
using Terraria.DataStructures;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;
namespace CalRemix
{
public static class CalRemixHelper
{
public static CalRemixItem Remix(this Item item) => item.GetGlobalItem<CalRemixItem>();
public static CalRemixNPC Remix(this NPC npc) => npc.GetGlobalNPC<CalRemixNPC>();
public static CalRemixPlayer Remix(this Player player) => player.GetModPlayer<CalRemixPlayer>();
public static CalRemixProjectile Remix(this Projectile projectile) => projectile.GetGlobalProjectile<CalRemixProjectile>();
public static Player Target(this NPC n)
{
if (n.target == -1)
{
n.TargetClosest(false);
}
return Main.player[n.target];
}
/// <summary>
/// Checks if the player has a stack of an item.
/// </summary>
public static bool HasStack(this Player player, int itemType, int stackNum)
{
for (int i = 0; i < 58; i++)
{
Item item = player.inventory[i];
if (item.type == itemType) { if (item.stack >= stackNum) return true; }
}
return false;
}
/// Checks if the player has a light pet active.
/// </summary>
public static bool HasLightPet(this Player player)
{
for (int i = 0; i < player.buffType.Length; i++)
{
if (Main.lightPet[player.buffType[i]])
return true;
}
return false;
}
/// <summary>
/// Consumes an item stack from the player.
/// </summary>
public static void ConsumeStack(this Player player, int itemType, int stackNum)
{
for (int i = 0; i < 58; i++)
{
ref Item item = ref player.inventory[i];
if (player.HasStack(itemType, stackNum)) item.stack -= stackNum;
}
}
/// <summary>
/// Checks if the player has every item of a given list.
/// </summary>
public static bool HasItems(this Player player, List<int> items)
{
for (int i = 0; i < items.Count; i++)
{
if (!player.HasItem(items[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Checks if the player has an item from a mod.
/// </summary>
public static bool HasCrossModItem(Player player, Mod Mod, string ItemName)
{
if (Mod != null)
{
if (player.HasItem(Mod.Find<ModItem>(ItemName).Type))
return true;
}
return false;
}
public static bool HasCrossModItem(Player player, string ModName, string ItemName)
{
if (ModLoader.HasMod(ModName))
{
if (player.HasItem(ModLoader.GetMod(ModName).Find<ModItem>(ItemName).Type))
return true;
}
return false;
}
/// <summary>
/// Changes item to the specified type. If stack is non-zero, change to the stack parameter.
/// </summary>
public static Item ChangeItemWithStack(this Item item, int to, int stack = 0)
{
bool flag = item.favorited;
stack = (stack <= 0) ? item.stack : stack;
item.SetDefaults(to);
item.favorited = flag;
item.stack = stack;
return item;
}
/// <summary>
/// Updates buff and checks if the player is dead. If dead, sets minion bool to false. If not, update timeLeft.
/// </summary>
public static void CheckMinionCondition(this Projectile projectile, int buff, bool minionBool)
{
Player player = Main.player[projectile.owner];
player.AddBuff(buff, 3600);
if (player.dead)
minionBool = false;
if (minionBool)
projectile.timeLeft = 2;
}
/// <summary>
/// Get the localized text using the provided key
/// </summary>
public static LocalizedText LocalText(string key) => Language.GetOrRegister("Mods.CalRemix." + key);
/// <summary>
/// Get the localized dialog using the provided key and send to all players in chat
/// </summary>
public static void GetNPCDialog(string key, Color? textColor = null)
{
if (!textColor.HasValue)
textColor = Color.White;
if (Main.netMode == NetmodeID.SinglePlayer)
Main.NewText(LocalText($"Dialog.{key}").Value, textColor.Value);
else
ChatHelper.BroadcastChatMessage(NetworkText.FromKey($"Mods.CalRemix.Dialog.{key}"), textColor.Value);
}
private static readonly FieldInfo shaderTextureField = typeof(MiscShaderData).GetField("_uImage1", BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly FieldInfo shaderTextureField2 = typeof(MiscShaderData).GetField("_uImage2", BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly FieldInfo shaderTextureField3 = typeof(MiscShaderData).GetField("_uImage3", BindingFlags.NonPublic | BindingFlags.Instance);
/// <summary>
/// Uses reflection to set the _uImage1. Its underlying data is private and the only way to change it publicly is via a method that only accepts paths to vanilla textures.
/// </summary>
/// <param name="shader">The shader</param>
/// <param name="texture">The texture to use</param>
public static void SetShaderTexture(this MiscShaderData shader, Asset<Texture2D> texture) => shaderTextureField.SetValue(shader, texture);
/// <summary>
/// Uses reflection to set the _uImage2. Its underlying data is private and the only way to change it publicly is via a method that only accepts paths to vanilla textures.
/// </summary>
/// <param name="shader">The shader</param>
/// <param name="texture">The texture to use</param>
public static void SetShaderTexture2(this MiscShaderData shader, Asset<Texture2D> texture) => shaderTextureField2.SetValue(shader, texture);
/// <summary>
/// Uses reflection to set the _uImage3. Its underlying data is private and the only way to change it publicly is via a method that only accepts paths to vanilla textures.
/// </summary>
/// <param name="shader">The shader</param>
/// <param name="texture">The texture to use</param>
public static void SetShaderTexture3(this MiscShaderData shader, Asset<Texture2D> texture) => shaderTextureField3.SetValue(shader, texture);
/// <summary>
/// Sets a <see cref="SpriteBatch"/>'s <see cref="BlendState"/> arbitrarily.
/// </summary>
/// <param name="spriteBatch">The sprite batch.</param>
/// <param name="blendState">The blend state to use.</param>
public static void SetBlendState(this SpriteBatch spriteBatch, BlendState blendState)
{
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, blendState, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix);
}
/// <summary>
/// Reset's a <see cref="SpriteBatch"/>'s <see cref="BlendState"/> based to a typical <see cref="BlendState.AlphaBlend"/>.
/// </summary>
/// <param name="spriteBatch">The sprite batch.</param>
/// <param name="blendState">The blend state to use.</param>
public static void ResetBlendState(this SpriteBatch spriteBatch) => spriteBatch.SetBlendState(BlendState.AlphaBlend);
public static void DrawBloomLine(this SpriteBatch spriteBatch, Vector2 start, Vector2 end, Color color, float width)
{
// Draw nothing if the start and end are equal, to prevent division by 0 problems.
if (start == end)
return;
start -= Main.screenPosition;
end -= Main.screenPosition;
Texture2D line = ModContent.Request<Texture2D>("CalRemix/Assets/ExtraTextures/Lines/BloomLine").Value;
float rotation = (end - start).ToRotation() + MathHelper.PiOver2;
Vector2 scale = new Vector2(width, Vector2.Distance(start, end)) / line.Size();
Vector2 origin = new(line.Width / 2f, line.Height);
spriteBatch.Draw(line, start, null, color, rotation, origin, scale, SpriteEffects.None, 0f);
}
public static void SwapToRenderTarget(this RenderTarget2D renderTarget, Color? flushColor = null)
{
// Local variables for convinience.
GraphicsDevice graphicsDevice = Main.graphics.GraphicsDevice;
SpriteBatch spriteBatch = Main.spriteBatch;
// If we are in the menu, a server, or any of these are null, return.
if (Main.gameMenu || Main.dedServ || renderTarget is null || graphicsDevice is null || spriteBatch is null)
return;
// Otherwise set the render target.
graphicsDevice.SetRenderTarget(renderTarget);
// "Flush" the screen, removing any previous things drawn to it.
flushColor ??= Color.Transparent;
graphicsDevice.Clear(flushColor.Value);
}
public static void ChatMessage(string text, Color color, NetworkText netText = null)
{
if (Main.netMode == NetmodeID.SinglePlayer)
Main.NewText(text, color);
else if (Main.netMode == NetmodeID.Server)
ChatHelper.BroadcastChatMessage(netText ?? NetworkText.FromLiteral(text), color);
}
public static void SpawnNPCOnPlayer(int playerWhoAmI, int type)
{
if (Main.netMode != NetmodeID.MultiplayerClient)
NPC.SpawnOnPlayer(playerWhoAmI, type);
else
NetMessage.SendData(MessageID.SpawnBossUseLicenseStartEvent, number: playerWhoAmI, number2: type);
}
public static void SpawnClientBossRandomPos(int id, Vector2 position, bool msg = true)
{
CalamityNetcode.NewNPC_ClientSide(position + Main.rand.NextVector2CircularEdge(1000, 600), id, Main.LocalPlayer);
if (msg)
ChatMessage(Language.GetTextValue("Announcement.HasAwoken", ContentSamples.NpcsByNetId[id].TypeName), new Color(175, 75, 255), NetworkText.FromKey("Announcement.HasAwoken", ContentSamples.NpcsByNetId[id].GetTypeNetName()));
}
public static void SpawnClientBoss(int id, Vector2 position, bool msg = true)
{
CalamityNetcode.NewNPC_ClientSide(position, id, Main.LocalPlayer);
if (msg)
ChatMessage(Language.GetTextValue("Announcement.HasAwoken", ContentSamples.NpcsByNetId[id].TypeName), new Color(175, 75, 255), NetworkText.FromKey("Announcement.HasAwoken", ContentSamples.NpcsByNetId[id].GetTypeNetName()));
}
/// <summary>
/// Spawns a new npc with multiplayer and action invocation support.
/// </summary>
/// <param name="source">The source of the npc.</param>
/// <param name="x">The x spawn position of the npc.</param>
/// <param name="y">The y spawn position of the npc.</param>
/// <param name="type">The id of the npc type that should be spawned.</param>
/// <param name="minSlot">The lowest slot in <see cref="Main.npc"/> the npc can use.</param>
/// <param name="ai0">The <see cref="NPC.ai"/>[0] value.</param>
/// <param name="ai1">The <see cref="NPC.ai"/>[1] value.</param>
/// <param name="ai2">The <see cref="NPC.ai"/>[0] value.</param>
/// <param name="ai3">The <see cref="NPC.ai"/>[1] value.</param>
/// <param name="target">The player index to use for the <see cref="NPC.target"/> value.</param>
/// <param name="npcTasks">The actions the <see cref="NPC"/> executes.</param>
/// <param name="awakenMessage">Sends a boss awaken message in chat</param>
public static NPC SpawnNewNPC(IEntitySource source, int x, int y, int type, int minSlot = 0, float ai0 = 0f, float ai1 = 0f, float ai2 = 0f, float ai3 = 0f, int target = 255, Action<NPC> npcTasks = null, bool awakenMessage = false)
{
NPC npc = Main.npc[0];
if (Main.netMode != NetmodeID.MultiplayerClient)
{
npc = NPC.NewNPCDirect(source, x, y, type, minSlot, ai0, ai1, ai2, ai3, target);
if (Main.npc.IndexInRange(npc.whoAmI))
{
npcTasks?.Invoke(npc);
if (Main.dedServ)
npc.netUpdate = true;
}
}
if (awakenMessage)
ChatMessage(Language.GetTextValue("Announcement.HasAwoken", npc.TypeName), new Color(175, 75, 255), NetworkText.FromKey("Announcement.HasAwoken", npc.GetTypeNetName()));
return npc;
}
/// <summary>
/// Spawns a new npc with multiplayer and action invocation support.
/// </summary>
/// <param name="source">The source of the npc.</param>
/// <param name="position">The spawn position of the npc.</param>
/// <param name="type">The id of the npc type that should be spawned.</param>
/// <param name="minSlot">The lowest slot in <see cref="Main.npc"/> the npc can use.</param>
/// <param name="ai0">The <see cref="NPC.ai"/>[0] value.</param>
/// <param name="ai1">The <see cref="NPC.ai"/>[1] value.</param>
/// <param name="ai2">The <see cref="NPC.ai"/>[0] value.</param>
/// <param name="ai3">The <see cref="NPC.ai"/>[1] value.</param>
/// <param name="target">The player index to use for the <see cref="NPC.target"/> value.</param>
/// <param name="npcTasks">The actions the <see cref="NPC"/> executes.</param>
/// <param name="awakenMessage">Sends a boss awaken message in chat</param>
public static NPC SpawnNewNPC(IEntitySource source, Vector2 position, int type, int minSlot = 0, float ai0 = 0f, float ai1 = 0f, float ai2 = 0f, float ai3 = 0f, int target = 255, Action<NPC> npcTasks = null, bool awakenMessage = false)
{
return SpawnNewNPC(source, (int)position.X, (int)position.Y, type, minSlot, ai0, ai1, ai2, ai3, target, npcTasks, awakenMessage);
}
/// <summary>
/// Spawns a NPC at this entity's center
/// </summary>
/// <param name="entity"></param>
/// <param name="id"></param>
/// <param name="ai0"></param>
/// <param name="ai1"></param>
/// <param name="ai2"></param>
/// <param name="ai3"></param>
/// <returns></returns>
public static NPC QuickSpawnNPC(this Entity entity, int id, float ai0 = 0f, float ai1 = 0f, float ai2 = 0f, float ai3 = 0f)
{
return SpawnNewNPC(entity.GetSource_FromThis(), (int)entity.Center.X, (int)entity.Center.Y, id, ai0: ai0, ai1: ai1, ai2: ai2, ai3: ai3);
}
public static void DestroyTile(int i, int j, bool fail = false, bool effectOnly = false, bool noItem = false)
{
WorldGen.KillTile(i, j, fail, effectOnly, noItem);
if (!Main.tile[i, j].HasTile && Main.netMode != NetmodeID.SinglePlayer)
NetMessage.SendData(MessageID.TileManipulation, -1, -1, null, 0, i, j, 0f, 0, 0, 0);
}
/// <summary>
/// Summons a projectile of a specific type while also adjusting damage for vanilla spaghetti regarding hostile projectiles.
/// </summary>
/// <param name="spawnX">The x spawn position of the projectile.</param>
/// <param name="spawnY">The y spawn position of the projectile.</param>
/// <param name="velocityX">The x velocity of the projectile.</param>
/// <param name="velocityY">The y velocity of the projectile</param>
/// <param name="type">The id of the projectile type that should be spawned.</param>
/// <param name="damage">The damage of the projectile.</param>
/// <param name="knockback">The knockback of the projectile.</param>
/// <param name="owner">The owner index of the projectile.</param>
/// <param name="ai0">An optional <see cref="NPC.ai"/>[0] fill value. Defaults to 0.</param>
/// <param name="ai1">An optional <see cref="NPC.ai"/>[1] fill value. Defaults to 0.</param>
public static int NewProjectileBetter(float spawnX, float spawnY, float velocityX, float velocityY, int type, int damage, float knockback, int owner = -1, float ai0 = 0f, float ai1 = 0f)
{
if (owner == -1)
owner = Main.myPlayer;
damage = (int)(damage * 0.5);
if (Main.expertMode)
damage = (int)(damage * 0.5);
int index = Projectile.NewProjectile(new EntitySource_WorldEvent(), spawnX, spawnY, velocityX, velocityY, type, damage, knockback, owner, ai0, ai1);
if (index >= 0 && index < Main.maxProjectiles)
Main.projectile[index].netUpdate = true;
return index;
}
/// <summary>
/// Summons a projectile of a specific type while also adjusting damage for vanilla spaghetti regarding hostile projectiles.
/// </summary>
/// <param name="center">The spawn position of the projectile.</param>
/// <param name="velocity">The velocity of the projectile</param>
/// <param name="type">The id of the projectile type that should be spawned.</param>
/// <param name="damage">The damage of the projectile.</param>
/// <param name="knockback">The knockback of the projectile.</param>
/// <param name="owner">The owner index of the projectile.</param>
/// <param name="ai0">An optional <see cref="NPC.ai"/>[0] fill value. Defaults to 0.</param>
/// <param name="ai1">An optional <see cref="NPC.ai"/>[1] fill value. Defaults to 0.</param>
public static int NewProjectileBetter(Vector2 center, Vector2 velocity, int type, int damage, float knockback, int owner = -1, float ai0 = 0f, float ai1 = 0f)
{
return NewProjectileBetter(center.X, center.Y, velocity.X, velocity.Y, type, damage, knockback, owner, ai0, ai1);
}
/// <summary>
/// Returns all projectiles present of a specific type.
/// </summary>
/// <param name="desiredTypes">The projectile type to check for.</param>
public static IEnumerable<Projectile> AllProjectilesByID(params int[] desiredTypes)
{
for (int i = 0; i < Main.maxProjectiles; i++)
{
if (Main.projectile[i].active && desiredTypes.Contains(Main.projectile[i].type))
yield return Main.projectile[i];
}
}
/// <summary>
/// Returns a readable projectile damage number
/// </summary>
/// <param name="normal">The damage in normal mode</param>
/// <param name="expert">The damage in expert mode. If left 0, defaults to normal damage</param>
/// <param name="master">The damage in master mode. If left 0, defaults to expert damage, then normal damage</param>
/// <returns></returns>
public static int ProjectileDamage(int normal, int expert = 0, int master = 0)
{
if (Main.masterMode && master != 0)
return (int)(master / 6f);
else if (Main.masterMode && master == 0 && expert != 0)
return (int)(expert / 6f);
else if (Main.masterMode && master == 0 && expert == 0)
return (int)(normal / 6f);
else if (Main.expertMode && expert != 0)
return (int)(expert / 4f);
else if (Main.masterMode && expert == 0)
return (int)(normal / 4f);
else
return (int)(normal / 2f);
}
/// <summary>
/// Checks if a point is inside of a given elipse area and position
/// </summary>
/// <param name="x">X to checkt</param>
/// <param name="y">Y to check</param>
/// <param name="h">Elipse center x</param>
/// <param name="k">Elipse center y</param>
/// <param name="a">X size</param>
/// <param name="b">Y size</param>
/// <returns>true if the point is inside</returns>
public static bool WithinElipse(float x, float y, float h, float k, float a, float b)
{
double p = (MathF.Pow((x - h), 2) / MathF.Pow(a, 2))
+ (MathF.Pow((y - k), 2) / MathF.Pow(b, 2));
return p < 1;
}
/// <summary>
/// Checks if a point is inside of a given heart area and position
/// </summary>
/// <param name="origin">The center of the heart</param>
/// <param name="roughDimensions">The width and height of the heart</param>
/// <param name="point">The point to check</param>
/// <returns>true if the point is inside</returns>
public static bool WithinHeart(Point origin, Point roughDimensions, Point point)
{
float x = (point.X - origin.X) / (roughDimensions.X / 2f);
float y = -(point.Y - origin.Y) / (roughDimensions.Y / 2f);
return (MathF.Pow(MathF.Pow(x, 2) + MathF.Pow(y, 2) - 1f, 3f) - (MathF.Pow(x, 2) * MathF.Pow(y, 3))) <= 0f;
}
/// <summary>
/// Checks if a point is inside of a given rhombus area and position
/// </summary>
/// <param name="origin">The center of the rhombus</param>
/// <param name="dimensions">The width and height of the rhombus</param>
/// <param name="point">The point to check</param>
/// <returns>true if the point is inside</returns>
public static bool WithinRhombus(Point origin, Point dimensions, Point point)
{
float val = ((Math.Abs(point.X - origin.X)) / (float)dimensions.X) + ((Math.Abs(point.Y - origin.Y)) / (float)dimensions.Y);
return val < 1;
}
/// <summary>
/// Gets the area of a triangle given 3 points
/// </summary>
/// <param name="point1">The first point</param>
/// <param name="point2">The second point</param>
/// <param name="point3">The third point</param>
/// <returns>the area of the triangle</returns>
public static float TriangleArea(Point point1, Point point2, Point point3)
{
return Math.Abs(point1.X * (point2.Y - point3.Y) + point2.X * (point3.Y - point1.Y) + point3.X * (point1.Y - point2.Y)) / 2f;
}
/// <summary>
/// Checks if a point is inside of a triangle with 3 given points
/// </summary>
/// <param name="point1">The first point</param>
/// <param name="point2">The second point</param>
/// <param name="point3">The third point</param>
/// <param name="toCheck">The point to check</param>
/// <returns>true if the point is inside</returns>
public static bool WithinTriangle(Point point1, Point point2, Point point3, Point toCheck)
{
float mainArea = TriangleArea(point1, point2, point3);
float areaOneTwo = TriangleArea(point1, point2, toCheck);
float areaTwoThree = TriangleArea(point2, point3, toCheck);
float areaOneThreeLikeTheUser = TriangleArea(point3, point1, toCheck);
return mainArea == areaOneTwo + areaTwoThree + areaOneThreeLikeTheUser;
}
/// <summary>
/// Checks if a point is inside of a quadrilateral with 4 given points. Points should be in a consistent clockwise or counter clockwise order
/// </summary>
/// <param name="point1">The first point</param>
/// <param name="point2">The second point</param>
/// <param name="point3">The third point</param>
/// <param name="point4">The fourth point</param>
/// <param name="toCheck">The point to check</param>
/// <returns>true if the point is inside</returns>
public static bool WithinQuad(Point point1, Point point2, Point point3, Point point4, Point toCheck)
{
return WithinTriangle(point1, point2, point3, toCheck) || WithinTriangle(point1, point3, point4, toCheck);
}
public enum PerlinEase
{
/// <summary>
/// No easing, all of the noise is consistent
/// </summary>
None = 0,
/// <summary>
/// Top starts solid and becomes noise
/// </summary>
EaseInTop = 1,
/// <summary>
/// Top is noise, bottom is air
/// </summary>
EaseOutBottom = 2,
/// <summary>
/// Top and bottom are solid, middle is noise
/// </summary>
EaseInOut = 3,
/// <summary>
/// Top and bottom are noise, middle is solid
/// </summary>
EaseOutIn = 4,
/// <summary>
/// Top is noise, bottom is solid
/// </summary>
EaseInBottom = 5,
/// <summary>
/// Top is air, bottom is noise
/// </summary>
EaseOutTop = 6,
/// <summary>
/// Top is air, middle is noise, bottom is solid
/// </summary>
EaseAirTopSolidBottom = 7,
/// <summary>
/// Top is solid, middle is noise, bottom is air
/// </summary>
EaseSolidTopAirBottom = 8,
}
/// <summary>
/// Generates a rectangle of tiles and/or walls using noise
/// </summary>
/// <param name="area">The rectangle</param>
/// <param name="noiseThreshold">How open should caves be? Scales between 0f and 1f</param>
/// <param name="noiseStrength">How strong the noise is. Weaker values look more like noodles</param>
/// <param name="noiseSize">The zoom of the noise. Higher values means more zoomed in. Set to 120, 180 by default, the same as the Baron Strait</param>
/// <param name="tileType">The tile to place</param>
/// <param name="wallType">The wall to place</param>
/// <param name="tileCondition">A condition for if a tile can be placed. Usually used in conjunction with shapes</param>
public static void PerlinGeneration(Rectangle area, float noiseThreshold = 0.56f, float noiseStrength = 0.1f, Vector2 noiseSize = default, int tileType = -1, int wallType = 0, PerlinEase ease = PerlinEase.None, float topStop = 0.3f, float bottomStop = 0.7f, Predicate<Point> tileCondition = null, bool overrideTiles = false, bool eraseWalls = true)
{
int sizeX = area.Width;
int sizeY = area.Height;
// Map to store what blocks should be converted
bool[,] map = new bool[sizeX, sizeY];
// default Baron Strait numbers
if (noiseSize == default)
{
noiseSize.X = 180f;
noiseSize.Y = 120f;
}
int seed = (int)Main.GlobalTimeWrappedHourly + WorldGen.genRand.Next(-1000, 1000);
// Create a perlin noise map
for (int i = 0; i < area.Width; i++)
{
for (int j = 0; j < area.Height; j++)
{
float noise = CalamityUtils.PerlinNoise2D(i / noiseSize.X, j / noiseSize.Y, 3, seed) * 0.5f + 0.5f;
float endPoint = noiseThreshold;
switch (ease)
{
case PerlinEase.EaseInTop:
endPoint = MathHelper.Lerp(noise, noiseThreshold, Utils.GetLerpValue(0, topStop, (j / (float)area.Height), true));
break;
case PerlinEase.EaseOutBottom:
endPoint = MathHelper.Lerp(noiseThreshold, 0, Utils.GetLerpValue(bottomStop, 1f, (j / (float)area.Height), true));
break;
case PerlinEase.EaseInOut:
if (j / (float)area.Height < 0.5f)
{
endPoint = MathHelper.Lerp(noise, noiseThreshold, Utils.GetLerpValue(0, topStop, (j / (float)area.Height), true));
}
else
{
endPoint = MathHelper.Lerp(noise, noiseThreshold, Utils.GetLerpValue(1f, bottomStop, (j / (float)area.Height), true));
}
break;
case PerlinEase.EaseOutTop:
endPoint = MathHelper.Lerp(0, noiseThreshold, Utils.GetLerpValue(0f, topStop, (j / (float)area.Height), true));
break;
case PerlinEase.EaseInBottom:
endPoint = MathHelper.Lerp(noiseThreshold, noise, Utils.GetLerpValue(bottomStop, 1f, (j / (float)area.Height), true));
break;
case PerlinEase.EaseOutIn:
if (j / (float)area.Height < 0.5f)
{
endPoint = MathHelper.Lerp(noise, noiseThreshold, Utils.GetLerpValue(0.5f, topStop, (j / (float)area.Height), true));
}
else
{
endPoint = MathHelper.Lerp(noise, noiseThreshold, Utils.GetLerpValue(0.5f, bottomStop, (j / (float)area.Height), true));
}
break;
case PerlinEase.EaseAirTopSolidBottom:
if (j / (float)area.Height < 0.5f)
{
endPoint = MathHelper.Lerp(0, noiseThreshold, Utils.GetLerpValue(0, topStop, (j / (float)area.Height), true));
}
else
{
endPoint = MathHelper.Lerp(noiseThreshold, noise, Utils.GetLerpValue(bottomStop, 1f, (j / (float)area.Height), true));
}
break;
case PerlinEase.EaseSolidTopAirBottom:
if (j / (float)area.Height < 0.5f)
{
endPoint = MathHelper.Lerp(noise, noiseThreshold, Utils.GetLerpValue(0, topStop, (j / (float)area.Height), true));
}
else
{
endPoint = MathHelper.Lerp(noiseThreshold, 0, Utils.GetLerpValue(bottomStop, 1f, (j / (float)area.Height), true));
}
break;
}
map[i, j] = MathHelper.Distance(noise, endPoint) < noiseStrength;
}
}
if (overrideTiles)
{
// Iterate through the map and remove blocks/walls accordingly
for (int gdv = 0; gdv < 1; gdv++)
{
for (int i = 0; i < area.Width; i++)
{
for (int j = 0; j < area.Height; j++)
{
if (!WorldGen.InWorld(area.X + i, area.Y + j))
{
continue;
}
Tile t = Main.tile[area.X + i, area.Y + j];
if (tileCondition != null)
{
if (!tileCondition.Invoke(new Point(area.X + i, area.Y + j)))
{
continue;
}
}
t.ClearEverything();
}
}
}
}
// Iterate through the map and add blocks/walls accordingly
for (int gdv = 0; gdv < 1; gdv++)
{
for (int i = 0; i < area.Width; i++)
{
for (int j = 0; j < area.Height; j++)
{
if (!WorldGen.InWorld(area.X + i, area.Y + j))
{
continue;
}
Tile t = Main.tile[area.X + i, area.Y + j];
if (t.HasTile && !overrideTiles)
{
continue;
}
if (tileCondition != null)
{
if (!tileCondition.Invoke(new Point(area.X + i, area.Y + j)))
{
continue;
}
}
// Cell stuff
int sur = SurroundingTileCounts(map, i, j, area.Width, area.Height);
// If there are more than 4 nearby nodes, place some
if (sur > 4 && (tileType != -1 || (wallType != 0 && eraseWalls)))
{
if (tileType != -1)
{
t.ResetToType((ushort)tileType);
//WorldGen.SquareTileFrame(area.X + i, area.Y + j);
}
if (wallType != 0)
{
t.WallType = (ushort)wallType;
//WorldGen.SquareWallFrame(area.X + i, area.Y + j);
}
map[i, j] = true;
}
// If there are less than 4 nodes nearby, remove
else if (sur < 4)
{
t.ClearEverything();
map[i, j] = false;
}
if (!eraseWalls && wallType != 0)
{
t.WallType = (ushort)wallType;
}
}
}
}
}
/// <summary>
/// Finds the topmost solid tile of a given x coordinate
/// </summary>
/// <param name="i">The x coordinate to check</param>
/// <param name="j">The y coordinate that will be found</param>
/// <param name="tileType">The type of tile to look for, defaults to -1 which means any block will count</param>
/// <param name="start">The vertical start of the loop, defaults to 0 (the top of the world)</param>
/// <returns>The tile</returns>
public static Tile FindTopTile(int i, out int j, int tileType = -1, int start = 0)
{
for (int y = start; y < Main.maxTilesY; y++)
{
Tile t = CalamityUtils.ParanoidTileRetrieval(i, y);
if (t.HasTile && t.IsTileSolid() && (tileType == -1 || t.TileType == tileType))
{
j = y;
return t;
}
}
j = 0;
return CalamityUtils.ParanoidTileRetrieval(i, 0);
}
//UGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
public static void ChargingMinionAI(this Projectile projectile, float range, float maxPlayerDist, float extraMaxPlayerDist, float safeDist, int initialUpdates, float chargeDelayTime, float goToSpeed, float goBackSpeed, Vector2 returnOffset, float chargeCounterMax, float chargeSpeed, bool tileVision, bool ignoreTilesWhenCharging, int updateDifference = 1)
{
Player player = Main.player[projectile.owner];
CalamityPlayer modPlayer = player.Calamity();
projectile.MinionAntiClump();
//Breather time between charges as like a reset
bool chargeDelay = false;
if (projectile.ai[0] == 2f)
{
projectile.ai[1] += 1f;
projectile.extraUpdates = initialUpdates + updateDifference;
if (projectile.ai[1] > chargeDelayTime)
{
projectile.ai[1] = 1f;
projectile.ai[0] = 0f;
projectile.extraUpdates = initialUpdates;
// CIT 2OCT2024: This line was breaking how the game counted minions,
// which resulted in minions being counted extra times and despawning other minions, most notoriously with Resurrection Butterfly.
// As such, I have commented it out.
// projectile.numUpdates = 0;
projectile.netUpdate = true;
}
else
{
chargeDelay = true;
}
}
if (chargeDelay)
{
return;
}
//Find a target
float maxDist = range;
Vector2 targetVec = projectile.position;
bool foundTarget = false;
bool isButterfly = projectile.type == ModContent.ProjectileType<PurpleButterfly>();
//Prioritize the targeted enemy if possible
if (player.HasMinionAttackTargetNPC)
{
NPC npc = Main.npc[player.MinionAttackTargetNPC];
bool fishronCheck = npc.type == NPCID.DukeFishron && npc.active && isButterfly;
if (npc.CanBeChasedBy(projectile, false) || fishronCheck)
{
//Check the size of the target to make it easier to hit fat targets like Levi
float extraDist = (npc.width / 2) + (npc.height / 2);
float targetDist = Vector2.Distance(npc.Center, projectile.Center);
//Some minions will ignore tiles when choosing a target like Ice Claspers, others will not
bool canHit = true;
if (extraDist < maxDist && !tileVision)
canHit = Collision.CanHit(projectile.Center, 1, 1, npc.Center, 1, 1);
if (!foundTarget && targetDist < (maxDist + extraDist) && canHit)
{
maxDist = targetDist;
targetVec = npc.Center;
foundTarget = true;
}
}
}
//If no npc is specifically targetted or the selected enemy can't be found, check through the entire array
if (!foundTarget)
{
for (int npcIndex = 0; npcIndex < Main.maxNPCs; npcIndex++)
{
NPC npc = Main.npc[npcIndex];
bool fishronCheck = npc.type == NPCID.DukeFishron && npc.active && isButterfly;
if (npc.CanBeChasedBy(projectile, false) || fishronCheck)
{
float extraDist = (npc.width / 2) + (npc.height / 2);
float targetDist = Vector2.Distance(npc.Center, projectile.Center);
bool canHit = true;
if (extraDist < maxDist && !tileVision)
canHit = Collision.CanHit(projectile.Center, 1, 1, npc.Center, 1, 1);
if (!foundTarget && targetDist < (maxDist + extraDist) && canHit)
{
maxDist = targetDist;
targetVec = npc.Center;
foundTarget = true;
}
}
}
}
//If the player is too far, return to the player. Range is increased while attacking something.
float distBeforeForcedReturn = maxPlayerDist;
if (foundTarget)
{
distBeforeForcedReturn = extraMaxPlayerDist;
}
if (Vector2.Distance(player.Center, projectile.Center) > distBeforeForcedReturn)
{
projectile.ai[0] = 1f;
projectile.netUpdate = true;
}
//Go to the target if you found one
if (foundTarget && projectile.ai[0] == 0f)
{
//Some minions don't ignore tiles while charging like brittle stars
projectile.tileCollide = !ignoreTilesWhenCharging;
Vector2 targetSpot = targetVec - projectile.Center;
float targetDist = targetSpot.Length();
targetSpot.Normalize();
//Tries to get the minion in the sweet spot of 200 pixels away but the minion also charges so idk what good it does
if (targetDist > 200f)
{
float speed = goToSpeed; //8
targetSpot *= speed;
projectile.velocity = (projectile.velocity * 40f + targetSpot) / 41f;
}
else
{
float speed = -goBackSpeed; //-4
targetSpot *= speed;
projectile.velocity = (projectile.velocity * 40f + targetSpot) / 41f; //41
}
}
//Movement for idle or returning to the player
else
{
//Ignore tiles so they don't get stuck everywhere like Optic Staff
projectile.tileCollide = false;
bool returningToPlayer = false;
if (!returningToPlayer)
{
returningToPlayer = projectile.ai[0] == 1f;
}
//Player distance calculations
Vector2 playerVec = player.Center - projectile.Center + returnOffset;
float playerDist = playerVec.Length();
//If the minion is actively returning, move faster
float playerHomeSpeed = 6f;
if (returningToPlayer)
{
playerHomeSpeed = 15f;
}
//Move somewhat faster if the player is kinda far~ish
if (playerDist > 200f && playerHomeSpeed < 8f)
{
playerHomeSpeed = 8f;
}
//Return to normal if close enough to the player
if (playerDist < safeDist && returningToPlayer && !Collision.SolidCollision(projectile.position, projectile.width, projectile.height))
{
projectile.ai[0] = 0f;
projectile.netUpdate = true;
}
//Teleport to the player if abnormally far
if (playerDist > 2000f)
{
projectile.position.X = player.Center.X - (float)(projectile.width / 2);
projectile.position.Y = player.Center.Y - (float)(projectile.height / 2);
projectile.netUpdate = true;
}
//If more than 70 pixels away, move toward the player
if (playerDist > 70f)
{
playerVec.Normalize();
playerVec *= playerHomeSpeed;
projectile.velocity = (projectile.velocity * 40f + playerVec) / 41f;
}
//Minions never stay still
else if (projectile.velocity.X == 0f && projectile.velocity.Y == 0f)
{
projectile.velocity.X = -0.15f;
projectile.velocity.Y = -0.05f;
}
}
//Increment attack counter randomly
if (projectile.ai[1] > 0f)
{
projectile.ai[1] += (float)Main.rand.Next(1, 4);
}
//If high enough, prepare to attack
if (projectile.ai[1] > chargeCounterMax)
{
projectile.ai[1] = 0f;
projectile.netUpdate = true;
}
//Charge at an enemy if not on cooldown
if (projectile.ai[0] == 0f)
{
if (projectile.ai[1] == 0f && foundTarget && maxDist < 500f)
{
projectile.ai[1] += 1f;
if (Main.myPlayer == projectile.owner)
{
projectile.ai[0] = 2f;
Vector2 targetPos = targetVec - projectile.Center;
targetPos.Normalize();
projectile.velocity = targetPos * chargeSpeed; //8
projectile.netUpdate = true;
}
}
}
}
/// <summary>
/// Generations perlin-based surface terrain
/// </summary>
/// <param name="area">The area to generate it</param>
/// <param name="tileType">The tile type</param>
/// <param name="iterations">How many iterations should be done</param>
/// <param name="variance">Height variance in tiles</param>
/// <param name="perlinBottom">Smoothen the bottom like the top</param>
public static void PerlinSurface(Rectangle area, int tileType, int iterations = 3, int variance = 20, bool perlinBottom = false)
{
int baseHeight = area.Y;
int noiseSeed = WorldGen.genRand.Next(0, int.MaxValue);
int noiseSeedBottom = WorldGen.genRand.Next(0, int.MaxValue);
for (int i = area.X; i < area.X + area.Width; i++)
{
float height = CalamityUtils.PerlinNoise2D(i / 380f, 0, iterations, noiseSeed);
float heightBottom = CalamityUtils.PerlinNoise2D(i / 380f, 0, iterations, noiseSeedBottom);
for (int j = area.Y; j < area.Y + area.Height; j++)
{
bool bottom = perlinBottom ? (j < area.Y + area.Height - (int)(heightBottom * variance)) : true;
if (j > baseHeight + 2 + (int)(height * variance) && bottom)
{
Tile t = Main.tile[i, j];
t.ResetToType((ushort)tileType);
}
}
}
}
// thank you random youtube video
// https://www.youtube.com/watch?v=v7yyZZjF1z4
public static int SurroundingTileCounts(bool[,] map, int x, int y, int checkDistX = 0, int chestDistY = 0)
{
int wallCount = 0;
for (int neighbourX = x - 1; neighbourX <= x + 1; neighbourX++)
{
for (int neighbourY = y - 1; neighbourY <= y + 1; neighbourY++)
{
if (neighbourX >= 0 && neighbourX < checkDistX && neighbourY >= 0 && neighbourY < chestDistY)
{
if (neighbourX != x || neighbourY != y)
{
wallCount += map[neighbourX, neighbourY].ToInt();
}
}
else