Update 1.4.4-release for 2.1.2

This commit is contained in:
Ozzatron committed 2026-02-25 20:41:47 -05:00
commit 40e6b18f1d
276 files changed
+7319 -1855

No files matched your search

+6 -6
View File
@@ -204,12 +204,12 @@ namespace CalamityMod.Balancing
// 50% resist to true melee.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.AstrumDeus, Do(ResistTrueMelee(0.5f))));
// 50% resist to Charged Blaster Cannon.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.AstrumDeus, Do(new ProjectileResistBalancingRule(0.5f, ProjectileID.ChargedBlasterLaser))));
// 50% resist to Atlantis (Atlantis gaming!).
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.AstrumDeus, Do(new ProjectileResistBalancingRule(0.5f, ProjectileType<AtlantisSpear>()))));
// 50% resist to Charged Blaster Cannon.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.AstrumDeus, Do(new ProjectileResistBalancingRule(0.5f, ProjectileID.ChargedBlasterLaser))));
// 35% resist to Aerial Bane.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.AstrumDeus, Do(new ProjectileResistBalancingRule(0.65f, ProjectileID.DD2BetsyArrow))));
@@ -293,11 +293,11 @@ namespace CalamityMod.Balancing
// 65% resist to Wave Pounder.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.DevourerOfGods, Do(new ProjectileResistBalancingRule(0.35f, ProjectileType<WavePounderBoom>()))));
// 35% resist to Sulphuric Acid Cannon's explosions.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.DevourerOfGods, Do(new ProjectileResistBalancingRule(0.65f, ProjectileType<SulphuricAcidCannonExplosion>()))));
// 60% resist to Corinth Prime's grenades.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.DevourerOfGods, Do(new ProjectileResistBalancingRule(0.4f, ProjectileType<CorinthPrimeAirburst>()))));
// 35% resist to Sulphuric Acid Cannon's explosions.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.DevourerOfGods, Do(new ProjectileResistBalancingRule(0.65f, ProjectileType<SulphuricAcidCannonExplosion>()))));
// 20% resist to Valediction's typhoons; will catch Nuclear Fury as well but that doesn't matter.
NPCSpecificBalancingChanges.AddRange(Bundle(CalamityNPCTypeSets.DevourerOfGods, Do(new ProjectileResistBalancingRule(0.8f, ProjectileType<NuclearFuryProjectile>()))));
+7 -6
View File
@@ -3,6 +3,7 @@ using CalamityMod.Particles;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.ModLoader;
@@ -40,14 +41,14 @@ namespace CalamityMod.Buffs.DamageOverTime
if (Main.rand.NextBool(3))
{
Vector2 randVel = new Vector2(5, 5).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 1f);
Dust dust = Dust.NewDustPerfect(modPlayer.RandomDebuffVisualSpot, DustID.Blood, randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.6f, 0.9f));
Dust dust = Dust.NewDustPerfect(modPlayer.RandomDebuffVisualSpot, (!ChildSafety.Disabled ? DustID.Cloud : DustID.Blood), randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.6f, 0.9f));
dust.noGravity = false;
Particle spark = new AltSparkParticle(modPlayer.RandomDebuffVisualSpot, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), Color.DarkRed * 0.5f);
Particle spark = new AltSparkParticle(modPlayer.RandomDebuffVisualSpot, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.5f);
GeneralParticleHandler.SpawnParticle(spark);
}
if (Main.rand.NextBool(8))
{
Particle spark = new GlowOrbParticle(modPlayer.RandomDebuffVisualSpot, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), Color.DarkRed * 0.8f, false, false, false);
Particle spark = new GlowOrbParticle(modPlayer.RandomDebuffVisualSpot, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.8f, false, false, false);
GeneralParticleHandler.SpawnParticle(spark);
}
}
@@ -58,17 +59,17 @@ namespace CalamityMod.Buffs.DamageOverTime
Vector2 randVel = new Vector2(5, 5).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 1f);
if (Main.rand.NextBool(5))
{
Particle spark = new AltSparkParticle(npcSize, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), Color.DarkRed * 0.5f);
Particle spark = new AltSparkParticle(npcSize, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.5f);
GeneralParticleHandler.SpawnParticle(spark);
}
else
{
Dust dust = Dust.NewDustPerfect(npcSize, DustID.Blood, randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.2f, 0.6f));
Dust dust = Dust.NewDustPerfect(npcSize, (!ChildSafety.Disabled ? DustID.Cloud : DustID.Blood), randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.2f, 0.6f));
dust.noGravity = false;
}
if (Main.rand.NextBool(8))
{
Particle spark = new GlowOrbParticle(npcSize, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), Color.DarkRed * 0.8f, false, false, false);
Particle spark = new GlowOrbParticle(npcSize, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.8f, false, false, false);
GeneralParticleHandler.SpawnParticle(spark);
}
}
+7 -6
View File
@@ -3,6 +3,7 @@ using CalamityMod.Particles;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.ModLoader;
@@ -40,14 +41,14 @@ namespace CalamityMod.Buffs.DamageOverTime
if (Main.rand.NextBool())
{
Vector2 randVel = new Vector2(6, 6).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 1f);
Dust dust = Dust.NewDustPerfect(modPlayer.RandomDebuffVisualSpot, DustID.Blood, randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.6f, 0.9f));
Dust dust = Dust.NewDustPerfect(modPlayer.RandomDebuffVisualSpot, (!ChildSafety.Disabled ? DustID.Cloud : DustID.Blood), randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.6f, 0.9f));
dust.noGravity = false;
Particle spark = new AltSparkParticle(modPlayer.RandomDebuffVisualSpot, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), Color.DarkRed * 0.5f);
Particle spark = new AltSparkParticle(modPlayer.RandomDebuffVisualSpot, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.5f);
GeneralParticleHandler.SpawnParticle(spark);
}
if (Main.rand.NextBool(8))
{
Particle spark = new GlowOrbParticle(modPlayer.RandomDebuffVisualSpot, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), Color.DarkRed * 0.8f, false, false, false);
Particle spark = new GlowOrbParticle(modPlayer.RandomDebuffVisualSpot, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.8f, false, false, false);
GeneralParticleHandler.SpawnParticle(spark);
}
}
@@ -58,17 +59,17 @@ namespace CalamityMod.Buffs.DamageOverTime
Vector2 randVel = new Vector2(6, 6).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 1f);
if (Main.rand.NextBool(3))
{
Particle spark = new AltSparkParticle(npcSize, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), Color.DarkRed * 0.5f);
Particle spark = new AltSparkParticle(npcSize, randVel + new Vector2(0, -4), true, 12, Main.rand.NextFloat(0.25f, 0.6f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.5f);
GeneralParticleHandler.SpawnParticle(spark);
}
else
{
Dust dust = Dust.NewDustPerfect(npcSize, DustID.Blood, randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.2f, 0.6f));
Dust dust = Dust.NewDustPerfect(npcSize, (!ChildSafety.Disabled ? DustID.Cloud : DustID.Blood), randVel * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.2f, 0.6f));
dust.noGravity = false;
}
if (Main.rand.NextBool(8))
{
Particle spark = new GlowOrbParticle(npcSize, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), Color.DarkRed * 0.8f, false, false, false);
Particle spark = new GlowOrbParticle(npcSize, new Vector2(0, 4) * Main.rand.NextFloat(0.5f, 0.7f), true, 16, Main.rand.NextFloat(0.55f, 0.8f), (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed) * 0.8f, false, false, false);
GeneralParticleHandler.SpawnParticle(spark);
}
}
+17 -2
View File
@@ -1,4 +1,5 @@
using CalamityMod.DataStructures;
using System;
using CalamityMod.DataStructures;
using Terraria;
using Terraria.ModLoader;
@@ -10,8 +11,22 @@ namespace CalamityMod.Buffs.DamageOverTime
public static DebuffData debuffData = new DebuffData()
{
EnemyLostRegen = 40,
HeatDebuffScaling = 2
HeatDebuffScaling = 2,
NPCLifeRegenMethod = CragsLavaScaling
};
public static void CragsLavaScaling(NPC npc, int buffType, ref int buffIndex, ref int damage)
{
//Applies the double Heat scaling but completely ignores NPC weakness/resistance to heat.
//We need to apply slimed as that isn't included in HeatDebuffMultiplier due to needing to dynamically update if slimed is applied
StatModifier multiplier = npc.Calamity().HeatDebuffMultiplier;
if (npc.drippingSlime || npc.drippingSparkleSlime)
multiplier += 1f;
int dotValue = (int)DebuffData.ApplyScalingToStatModifer(multiplier, debuffData.HeatDebuffScaling).ApplyTo(debuffData.EnemyLostRegen);
npc.Calamity().ApplyDPSDebuff(dotValue, (int)Math.Max(dotValue * debuffData.MultiplierDamageTickSize, debuffData.MinimumDamageTickSize), ref npc.lifeRegen, ref damage);
}
public override void SetStaticDefaults()
{
Main.buffNoTimeDisplay[Type] = true;
+3 -2
View File
@@ -5,6 +5,7 @@ using CalamityMod.Projectiles;
using CalamityMod.Projectiles.Typeless;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.GameContent;
using Terraria.ModLoader;
namespace CalamityMod.Buffs.DamageOverTime
@@ -100,7 +101,7 @@ namespace CalamityMod.Buffs.DamageOverTime
int bloodLifetime = Main.rand.Next(22, 36);
float bloodScale = Main.rand.NextFloat(0.6f, 0.8f);
Color bloodColor = Color.Lerp(Color.Red, Color.DarkRed, Main.rand.NextFloat());
bloodColor = Color.Lerp(bloodColor, new Color(51, 22, 94), Main.rand.NextFloat(0.65f));
bloodColor = (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.Lerp(bloodColor, new Color(51, 22, 94), Main.rand.NextFloat(0.65f)));
if (Main.rand.NextBool(20))
bloodScale *= 2f;
@@ -114,7 +115,7 @@ namespace CalamityMod.Buffs.DamageOverTime
for (int i = 0; i < exactBloodCount / 3; ++i)
{
float bloodScale = Main.rand.NextFloat(0.2f, 0.33f);
Color bloodColor = Color.Lerp(Color.Red, Color.DarkRed, Main.rand.NextFloat(0.5f, 1f));
Color bloodColor = (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.Lerp(Color.Red, Color.DarkRed, Main.rand.NextFloat(0.5f, 1f)));
Vector2 bloodVelocity = Main.rand.NextVector2Unit() * velStackMult * Main.rand.NextFloat(1f, 2f);
bloodVelocity.Y -= 2.3f;
BloodParticle2 blood = new BloodParticle2(npc.Center, bloodVelocity, 20, bloodScale, bloodColor);
+5 -5
View File
@@ -1,4 +1,5 @@
using CalamityMod.DataStructures;
using System;
using CalamityMod.DataStructures;
using CalamityMod.Projectiles.Magic;
using Terraria;
using Terraria.ID;
@@ -33,10 +34,9 @@ namespace CalamityMod.Buffs.StatDebuffs
Player player = Main.player[playerIndex];
if (player.active)
{
float playerRangedDamage = player.GetTotalDamage(DamageClass.Ranged).ApplyTo(baseIrradiatedDoTValue * (1 + player.GetTotalCritChance(DamageClass.Ranged) * 0.01f));
if (playerRangedDamage > baseIrradiatedDoTValue && player.Calamity().scionsCurio)
if (player.Calamity().scionsCurioDebuffDamage > baseIrradiatedDoTValue && player.Calamity().scionsCurio)
{
baseIrradiatedDoTValue = (int)playerRangedDamage;
baseIrradiatedDoTValue = (int)player.Calamity().scionsCurioDebuffDamage;
}
}
}
@@ -44,7 +44,7 @@ namespace CalamityMod.Buffs.StatDebuffs
if (projectileCount > 0)
cnpc.ApplyDPSDebuff(projectileCount * baseIrradiatedDoTValue, projectileCount * 4, ref npc.lifeRegen, ref damage);
else
cnpc.ApplyDPSDebuff(baseIrradiatedDoTValue, baseIrradiatedDoTValue / 20, ref npc.lifeRegen, ref damage);
cnpc.ApplyDPSDebuff(baseIrradiatedDoTValue, Math.Max((int)(baseIrradiatedDoTValue * debuffData.MultiplierDamageTickSize),debuffData.MinimumDamageTickSize), ref npc.lifeRegen, ref damage);
}
public override void SetStaticDefaults()
{
+2 -2
View File
@@ -37,8 +37,8 @@ namespace CalamityMod.Buffs.Summon
public override void Update(Player player, ref int buffIndex)
{
BuffOwner ??= player;
BuffModdedOwner ??= player.Calamity();
BuffOwner = player;
BuffModdedOwner = player.Calamity();
if (player.ownedProjectileCounts[MinionProjectileType] > 0)
MinionBool = true;
+20 -4
View File
@@ -194,7 +194,7 @@ namespace CalamityMod.CalPlayer
DevourerofCods //Not a fishing minigame but uses the same code as the rest
}
public FishingMinigames SelectedFishingMinigame = FishingMinigames.None;
public bool countsAsAnyWet => (Player.armor[0].type == ItemID.FishBowl || (Main.raining && Player.Center.Y < Main.worldSurface * 16.0) || Player.dripping || Player.wetCount > 0 || Player.wet || Player.honeyWet || Player.lavaWet);
public bool countsAsAnyWet => (Player.armor[0].type == ItemID.FishBowl || (Main.IsItRaining && Player.Center.Y < Main.worldSurface * 16.0) || Player.dripping || Player.wetCount > 0 || Player.wet || Player.honeyWet || Player.lavaWet);
/// <summary>
/// How many Starbursts the player has
@@ -544,6 +544,8 @@ namespace CalamityMod.CalPlayer
/// <summary> An additional damage multiplier applied to rogue stealth strikes. Used by Filthy Glove, Rotten Dogtooth and their upgrades. </summary>
public double bonusStealthDamage = 0;
public float rogueVelocity = 1f;
public int focusFlurryAttackCount = 0;
#endregion
#region Mount
@@ -1113,6 +1115,7 @@ namespace CalamityMod.CalPlayer
public bool scionsCurio = false;
public bool scionsCurioGotHit = false;
public bool scionsCurioVisuals = false;
public float scionsCurioDebuffDamage = 0;
public bool miniOldDuke = false;
public bool miniOldDukeVanity = false;
public bool starbusterCore = false;
@@ -1448,7 +1451,6 @@ namespace CalamityMod.CalPlayer
public bool redWine = false;
public float redWineStoredY = 0;
public bool grapeBeer = false;
public int grapeBeerTimer = 0;
public bool moonshine = false;
public bool rum = false;
public bool whiskey = false;
@@ -2527,6 +2529,7 @@ namespace CalamityMod.CalPlayer
fairyBoots = false;
flameWakerBoots = false;
hellfireTreads = false;
bootLevel = 0;
sSpiritAmulet = false;
dOfTheDeep = false;
oceanCrest = false;
@@ -2730,8 +2733,6 @@ namespace CalamityMod.CalPlayer
vodka = false;
redWine = false;
grapeBeer = false;
if (grapeBeerTimer > 0)
grapeBeerTimer--;
moonshine = false;
rum = false;
whiskey = false;
@@ -3783,6 +3784,14 @@ namespace CalamityMod.CalPlayer
if (godSlayer && !Player.pulley && Player.grappling[0] == -1 && !Player.tongued && !Player.mount.Active && !Player.HasCooldown(GodSlayerDash.ID) && Player.dashDelay == 0)
{
godSlayerDashHotKeyPressed = true;
foreach (Projectile p in Main.ActiveProjectiles)
{
if (p.type == ProjectileType<RelicOfDeliveranceSpear>() && Player.whoAmI == p.owner)
{
(p.ModProjectile as RelicOfDeliveranceSpear).KillProj();
return;
}
}
}
}
@@ -4927,6 +4936,13 @@ namespace CalamityMod.CalPlayer
}
}
if (scionsCurio)
{
scionsCurioDebuffDamage = Player.GetTotalDamage(DamageClass.Ranged).ApplyTo(Irradiated.debuffData.EnemyLostRegen * (1 + Player.GetTotalCritChance(DamageClass.Ranged) * 0.01f));
}
else
scionsCurioDebuffDamage = 0;
// True melee damage from various vanilla equipment placed here.
// Titan Glove and ALL upgrades.
+16 -7
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CalamityMod.Events;
using CalamityMod.Items.Accessories;
using CalamityMod.Items.Accessories.Vanity;
@@ -30,7 +31,6 @@ using Terraria.DataStructures;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.UI;
namespace CalamityMod.CalPlayer
{
@@ -49,15 +49,15 @@ namespace CalamityMod.CalPlayer
// If the player does get a crate (can be from the reroll above), give it increased chances of being rarer
if (attempt.crate)
{
int uncommonRate = Math.Clamp(240 / attempt.fishingLevel, 3, 240); // Iron/Mythril (originally 300)
int uncommonRate = Math.Clamp(240 / attempt.fishingLevel, 3, 240); // Iron/Mythril (originally 300)
attempt.uncommon = Main.rand.NextBool(uncommonRate);
// These roll result bools are individually stored for the rarifying visuals
int rareRate = Math.Clamp(840 / attempt.fishingLevel, 4, 840); // Biome (originally 1050)
int rareRate = Math.Clamp(840 / attempt.fishingLevel, 4, 840); // Biome (originally 1050)
bool rareRoll = Main.rand.NextBool(rareRate);
attempt.rare = rareRoll;
int veryRareRate = Math.Clamp(1800 / attempt.fishingLevel, 5, 1800); // Golden/Titanium (originally 2250)
int veryRareRate = Math.Clamp(1800 / attempt.fishingLevel, 5, 1800); // Golden/Titanium (originally 2250)
bool veryRareRoll = Main.rand.NextBool(veryRareRate);
attempt.veryrare = veryRareRoll;
@@ -86,6 +86,13 @@ namespace CalamityMod.CalPlayer
}
#endregion
public override bool? CanConsumeBait(Item bait)
{
if (bait.type == ModContent.ItemType<BloodwormItem>())
return true;
return null;
}
#region Catch Fish
public override void CatchFish(FishingAttempt attempt, ref int itemDrop, ref int npcSpawn, ref AdvancedPopupRequest sonar, ref Vector2 sonarPosition)
{
@@ -128,7 +135,7 @@ namespace CalamityMod.CalPlayer
// Fishing in lava overrides the rest of logic
if (lava)
{
// Don't do anything if you can't fish in lava
// Don't do anything if you can't fish in lava
if (!attempt.CanFishInLava)
return;
@@ -173,8 +180,10 @@ namespace CalamityMod.CalPlayer
// Old Duke spawn
if (canSulphurFish && bait == ModContent.ItemType<BloodwormItem>() && !BossRushEvent.BossRushActive)
{
CalamityGlobalNPC.OldDukeSpawn(Player.whoAmI, ModContent.NPCType<OldDuke>(), bait);
if (!Main.projectile.Any(x => x.active && x.aiStyle == ProjAIStyleID.Bobber && x.ai[1] != 0 && x.localAI[1] == ModContent.NPCType<OldDuke>() * -1))
npcSpawn = ModContent.NPCType<OldDuke>();
itemDrop = -1;
sonar.Text = "";
return;
}
@@ -242,7 +251,7 @@ namespace CalamityMod.CalPlayer
return;
// Add top priorities of our own
if (DownedBossSystem.downedLeviathan && attempt.legendary && poolSize > 1000)
if (DownedBossSystem.downedLeviathan && attempt.legendary && poolSize > 1000 && !Main.rand.NextBool(3))
{
itemDrop = ModContent.ItemType<Floodtide>();
return;
+10 -5
View File
@@ -174,7 +174,7 @@ namespace CalamityMod.CalPlayer
// Xyk vanity death animation
if (XykVisualsBlue || XykVisualsOrange)
{
Projectile.NewProjectile(Player.GetSource_FromThis(), Player.Center, Vector2.Zero, ModContent.ProjectileType<XykDeathAnim>(), Main.zenithWorld ? Main.rand.Next(5000, 50000 + 1) : 0, 0, Player.whoAmI);
Projectile.NewProjectile(Player.GetSource_FromThis(), Player.Center, Vector2.Zero, ModContent.ProjectileType<XykDeathAnim>(), 0, 0, Player.whoAmI);
}
if (holyInferno)
@@ -857,7 +857,7 @@ namespace CalamityMod.CalPlayer
int mirrorDamage = (int)MathHelper.Min(actualProjDamage, 1000) * 50;
for (var i = 0; i < 5; i++)
{
Projectile.NewProjectile(source, Player.Center + Vector2.UnitX.RotatedBy(MathHelper.TwoPi * (i / 10f)), Vector2.Zero, ModContent.ProjectileType<MirrorBlast>(), mirrorDamage, 5, Main.myPlayer, 1);
Projectile.NewProjectile(source, Player.Center + Vector2.UnitX.RotatedBy(MathHelper.TwoPi * (i / 5f)), Vector2.Zero, ModContent.ProjectileType<MirrorBlast>(), mirrorDamage, 5, Main.myPlayer, 1);
}
}
projTypeJustHitBy = proj.type;
@@ -1308,7 +1308,7 @@ namespace CalamityMod.CalPlayer
if (alchFlask)
{
for (int i = 0; i < 9; i++)
for (int i = 0; i < (Player.strongBees ? 12 : 9); i++)
{
int seekerDamage = (int)Player.GetBestClassDamage().ApplyTo(15);
@@ -1675,6 +1675,10 @@ namespace CalamityMod.CalPlayer
private void ModifyHurtInfo_Calamity(ref Player.HurtInfo info)
{
// Don't run any of this code if the hit was cancelled.
if (info.Cancelled)
return;
// Boss Rush's damage floor is implemented as a dirty modifier
// TODO -- implementing this correctly would require fully reimplementing all of DR and ADR
if (BossRushEvent.BossRushActive)
@@ -1987,7 +1991,7 @@ namespace CalamityMod.CalPlayer
double halfDefense = Player.statDefense / 2.0;
if (bloodflareCore)
specialDefenseDmgMinimum += halfDefense;
if (moonshine) //Moonshine also halves defense damage recovery alongside forcing 50% of defense as defense damage
if (moonshine) //Moonshine also reduces defense damage recovery by 2/3 alongside forcing 50% of defense as defense damage
specialDefenseDmgMinimum += halfDefense;
int netMitigation = hurtInfo.SourceDamage - hurtInfo.Damage;
double standardDefenseDamage = netMitigation * defenseDamageRatio;
@@ -2806,7 +2810,8 @@ namespace CalamityMod.CalPlayer
defenseDamageRecoveryFrames = 0;
// Directly add the base defense damage recovery time to whatever recovery time the player already has.
totalDefenseDamageRecoveryFrames = defenseDamageRecoveryFrames + DefenseDamageBaseRecoveryTime;
int baseTime = DefenseDamageBaseRecoveryTime * (moonshine ? 3 : 1);
totalDefenseDamageRecoveryFrames = defenseDamageRecoveryFrames + baseTime;
if (totalDefenseDamageRecoveryFrames > DefenseDamageMaxRecoveryTime)
totalDefenseDamageRecoveryFrames = DefenseDamageMaxRecoveryTime;
+29 -29
View File
@@ -49,6 +49,7 @@ using CalamityMod.NPCs;
using CalamityMod.NPCs.AcidRain;
using CalamityMod.NPCs.Astral;
using CalamityMod.NPCs.Crags;
using CalamityMod.NPCs.DevourerofGods;
using CalamityMod.NPCs.NormalNPCs;
using CalamityMod.NPCs.Other;
using CalamityMod.NPCs.PlagueEnemies;
@@ -634,7 +635,7 @@ namespace CalamityMod.CalPlayer
}
if (cinnamonRoll)
if (cinnamonRoll && !(Main.getGoodWorld && Main.npc.Any(x=> x.active && x.type == ModContent.NPCType<DevourerofGodsHead>())))
{
if (dashStart)
Player.velocity.X *= 3;
@@ -1398,6 +1399,9 @@ namespace CalamityMod.CalPlayer
Player.lavaTime++;
}
}
// Extra DoT in the lava of the crags. Negated by Flame-licked Shell.
else if (ZoneCalamity && !flameLickedShell)
Player.AddBuff(ModContent.BuffType<SearingLava>(), 2, false);
// Release irradiated slimes from the sky during the Acid Rain event.
if (Player.whoAmI == Main.myPlayer)
@@ -1688,10 +1692,9 @@ namespace CalamityMod.CalPlayer
}
// The fire boots debuff boosts
if (hellfireTreads)
HeatDebuffMultiplier += 0.5f;
else if (flameWakerBoots)
HeatDebuffMultiplier += 0.25f;
// bootLevel exists SO THAT THEY DO NOT STACK. Please help me maintain my sanity so we're not "fixing" this issue seventy times
if (bootLevel > 0)
HeatDebuffMultiplier += 0.25f * bootLevel;
if (rOfResilienceEffect > 0)
rOfResilienceEffect--;
@@ -1859,7 +1862,7 @@ namespace CalamityMod.CalPlayer
if (sSpiritAmulet)
{
int spawnTime = 65; // Time between energy spawns
int spawnTime = 75; // Time between energy spawns
int energyCap = 8; // Max number of energies that can be alive at a time
Projectile projectile = null;
@@ -1876,7 +1879,7 @@ namespace CalamityMod.CalPlayer
}
}
if (energyCount > 0)
sSpiritAmuletTimer = -spawnTime; // The spawn cooldown after launching energies is twice as long
sSpiritAmuletTimer = -spawnTime * 3; // The spawn cooldown after launching energies is much longer
}
int numOfEnergy = 0;
for (int x = 0; x < Main.maxProjectiles; x++) // Get a count of energies in idle mode
@@ -1889,7 +1892,7 @@ namespace CalamityMod.CalPlayer
{
if (numOfEnergy < energyCap)
{
int energyDamage = (int)Player.GetBestClassDamage().ApplyTo(22);
int energyDamage = (int)Player.GetBestClassDamage().ApplyTo(8);
Projectile energy = Projectile.NewProjectileDirect(Player.GetSource_FromThis(), Player.Center, (Vector2.One * 4).RotatedByRandom(MathHelper.TwoPi), ModContent.ProjectileType<AmuletEnergy>(), energyDamage, 0f, Player.whoAmI, 0, numOfEnergy);
if (numOfEnergy + 1 == energyCap && Player.Calamity().sSpiritAmuletVisual)
{
@@ -2072,29 +2075,26 @@ namespace CalamityMod.CalPlayer
zapActivity += 1;
if (zapActivity <= 300 && zapActivity % 30 == 0)
{
for (int arcProjCount = 0; arcProjCount < 3; arcProjCount++)
float maxDistance = 300f;
int target = -1;
foreach (NPC npc in Main.ActiveNPCs)
{
float maxDistance = 300f;
int target = -1;
foreach (NPC npc in Main.ActiveNPCs)
float targetDist = Vector2.Distance(npc.Center, Player.Center);
if (targetDist < maxDistance && npc.Calamity().arcZapCooldown == 0 && npc.CanBeChasedBy())
{
float targetDist = Vector2.Distance(npc.Center, Player.Center);
if (targetDist < maxDistance && npc.Calamity().arcZapCooldown == 0 && npc.CanBeChasedBy())
{
maxDistance = targetDist;
target = npc.whoAmI;
}
maxDistance = targetDist;
target = npc.whoAmI;
}
}
if (target > 0)
{
unstableSelectedTarget = Main.npc[target];
unstableSelectedTarget.Calamity().arcZapCooldown = 18;
int damage = (int)Player.GetBestClassDamage().ApplyTo(18);
if (target > 0)
{
unstableSelectedTarget = Main.npc[target];
unstableSelectedTarget.Calamity().arcZapCooldown = 25;
int damage = (int)Player.GetBestClassDamage().ApplyTo(15);
Projectile.NewProjectile(Player.GetSource_FromThis(), new Vector2(Player.Center.X, Player.Center.Y - 20f), new Vector2(0f, -2f), ModContent.ProjectileType<ArcZap>(), damage, 0f, Player.whoAmI, target, 3f);
target = -1;
}
Projectile.NewProjectile(Player.GetSource_FromThis(), new Vector2(Player.Center.X, Player.Center.Y - 20f), new Vector2(0f, -2f), ModContent.ProjectileType<ArcZap>(), damage, 0f, Player.whoAmI, target, 5f);
target = -1;
}
}
else if (zapActivity > 600)
@@ -2201,8 +2201,6 @@ namespace CalamityMod.CalPlayer
if (arsenalCooldown > 0)
arsenalCooldown--;
if (Main.zenithWorld)
arsenalCooldown = 0;
if (killModeCooldown > 0)
killModeCooldown--;
if (ascendantInsigniaCooldown > 0 && ascendantInsigniaBuffTime <= 0)
@@ -2243,6 +2241,8 @@ namespace CalamityMod.CalPlayer
raiderSoundCooldown--;
if (astralStarRainCooldown > 0)
astralStarRainCooldown--;
if (AbaddonCooldown > 0)
AbaddonCooldown--;
if (VoidCooldown > 0)
VoidCooldown--;
if (ursaSergeantCooldown > 0)
@@ -4778,7 +4778,7 @@ namespace CalamityMod.CalPlayer
{
totalDefenseDamage = 0;
defenseDamageRecoveryFrames = 0;
totalDefenseDamageRecoveryFrames = DefenseDamageBaseRecoveryTime * (moonshine ? 2 : 1);
totalDefenseDamageRecoveryFrames = DefenseDamageBaseRecoveryTime;
defenseDamageDelayFrames = 0;
}
}
+4 -4
View File
@@ -205,7 +205,7 @@ namespace CalamityMod.CalPlayer
bool spawnChance = (Main.rand.Next(100) < ArcFlashRing.LightningSpawnPercent);
if (arcFlashRing && spawnChance)
{
int damage = (int)(hit.Damage * ArcFlashRing.LightningDamageMult * (hit.Crit ? 0.5f : 1) / (Player.Calamity().adrenalineModeActive ? Player.Calamity().GetAdrenalineDamage() + 1 : 1)); // 400% damage (uneffected by crits and adrenaline)
int damage = (int)(hit.Damage * ArcFlashRing.LightningDamageMult * (hit.Crit ? (1 / (Player.Calamity().critDamage + 2)) : 1) / (Player.Calamity().adrenalineModeActive ? Player.Calamity().GetAdrenalineDamage() + 1 : 1)); // 400% damage (uneffected by crits and adrenaline)
Projectile bolt = Projectile.NewProjectileDirect(source, target.Center, Vector2.Zero, ProjectileType<FlashBolt>(), damage, 0f, Player.whoAmI, target.whoAmI);
bolt.DamageType = hit.DamageType;
@@ -411,7 +411,7 @@ namespace CalamityMod.CalPlayer
{
proj.active = true; // Okay so if a projectile manually kills itself on hit, it totally breaks the bolts. to prevent this we set them to active
int damage = (int)(hit.Damage * ArcFlashRing.LightningDamageMult * (hit.Crit ? 0.5f : 1) / (Player.Calamity().adrenalineModeActive ? Player.Calamity().GetAdrenalineDamage() + 1 : 1)); // 400% damage (uneffected by crits and adrenaline)
int damage = (int)(hit.Damage * ArcFlashRing.LightningDamageMult * (hit.Crit ? (1 / (Player.Calamity().critDamage + 2)) : 1) / (Player.Calamity().adrenalineModeActive ? Player.Calamity().GetAdrenalineDamage() + 1 : 1)); // 400% damage (uneffected by crits and adrenaline)
Projectile bolt = Projectile.NewProjectileDirect(source, target.Center, Vector2.Zero, ProjectileType<FlashBolt>(), damage, 0f, Player.whoAmI, target.whoAmI, (globalProj.showArcFlash ? 0 : 1));
bolt.DamageType = hit.DamageType;
@@ -702,7 +702,7 @@ namespace CalamityMod.CalPlayer
bee.ArmorPenetration = 20;
bee.penetrate = 2;
bee.extraUpdates = 1;
AlchFlaskCooldown = 7;
AlchFlaskCooldown = Player.strongBees ? 6 : 7;
}
bool lifeAndShieldCondition = Player.statLife >= Player.statLifeMax2 && (!HasAnyEnergyShield || TotalEnergyShielding >= TotalMaxShieldDurability);
@@ -1344,7 +1344,7 @@ namespace CalamityMod.CalPlayer
if (manaOverloader)
{
double healMult = 0.1D - proj.numHits * 0.025D;
Player.SpawnLifeStealProjectile(target, proj, ProjectileType<ManaPolarizerHealOrb>(), (int)Math.Round(damage * healMult), 1.5f);
Player.SpawnLifeStealProjectile(target, proj, ProjectileType<ManaPolarizerHealOrb>(), (int)Math.Round(damage * healMult), 1.75f);
}
if (ataxiaMage)
+1 -5
View File
@@ -300,12 +300,8 @@ namespace CalamityMod
BossHealthBoost = Utils.Clamp(BossHealthBoost, MinBossHealthBoost, MaxBossHealthBoost);
}
[Header("Gameplay")]
#region General Gameplay Changes
[BackgroundColor(192, 54, 64, 192)]
[DefaultValue(true)]
public bool SimplifyAccessoryReforge { get; set; }
[Header("Gameplay")]
[BackgroundColor(192, 54, 64, 192)]
[DefaultValue(true)]
+16
View File
@@ -8,6 +8,8 @@ using Terraria.ModLoader;
namespace CalamityMod.Effects
{
// TODO -- This can be made into a ModSystem with simple OnModLoad and Unload hooks.
// TODO: SOURCEGEN: Get rid of this loader and replace references with sourcegenned references
[Autoload(Side = ModSide.Client)]
public sealed class CalamityShaders : ModSystem
{
@@ -262,6 +264,14 @@ namespace CalamityMod.Effects
internal static Asset<Effect> BrainOfCthulhuForcefield;
#endregion
#region jasper's shaders
internal static Asset<Effect> NanoblackSlashShader;
// static gaussian bloom, cannot change parameters. do not reuse this if that binds you.
internal static Asset<Effect> GaussianBloomShader;
#endregion
internal static Asset<Effect> SunkenSeaMenuLogoWater;
@@ -519,6 +529,12 @@ namespace CalamityMod.Effects
RegisterScreenShader(BrainOfCthulhuForcefield, "BoCShieldPass", "BrainOfCthulhuForcefield");
#endregion
NanoblackSlashShader = LoadShader("SlashEffects/NanoblackSlash");
RegisterMiscShader(NanoblackSlashShader, "SlashPass", "NanoblackSlash");
GaussianBloomShader = LoadShader("SlashEffects/GaussianBloom");
RegisterMiscShader(GaussianBloomShader, "BloomShader", "GaussianBloom");
SunkenSeaMenuLogoWater = LoadShader("UI/SunkenSeaMenuLogoWater");
}
Binary file not shown.
Binary file not shown.
+75
View File
@@ -0,0 +1,75 @@
sampler uImage0 : register(s0);
float uTime;
float uHoverIntensity;
float uPixel;
float uColorResolution;
float uGrayness;
float uSpeed;
float4 uSource;
float3 uInColor;
// variations of this need to be purpose built because of hlsl limitations
// this one only does a basic gaussian bloom at fixed parameters
float gaussian(float2 i, float sigma2, float pisigma2) {
float top = exp(-((i.x * i.x) + (i.y * i.y)) / sigma2);
float bot = pisigma2;
return top / bot;
}
float2 AspectCorrectedGBlurScale(float2 resolution, float blurIntensity) {
return (1.0f.xx / resolution) * blurIntensity;
}
float4 gauss_blur(sampler sp, float2 uv, float2 scale, int samples) {
const float pi = radians(180.);
const float sigma = float(samples) * 0.25;
const float sigma2 = 2. * sigma * sigma;
const float pisigma2 = pi * sigma2;
float2 offset = float2(0, 0);
float weight = gaussian(offset, sigma2, pisigma2);
float4 color_av = tex2D(sp, uv) * weight;
float accum = weight;
for (int x = 0; x <= samples / 2; ++x) {
for (int y = 1; y <= samples / 2; ++y) {
offset = float2(x, y);
weight = gaussian(offset, sigma2, pisigma2);
color_av += tex2D(sp, uv + scale * offset) * weight;
accum += weight;
color_av += tex2D(sp, uv - scale * offset) * weight;
accum += weight;
offset = float2(-y, x);
color_av += tex2D(sp, uv + scale * offset) * weight;
accum += weight;
color_av += tex2D(sp, uv - scale * offset) * weight;
accum += weight;
}
}
float4 final = color_av / accum;
// gamma correction
final = pow(final, (1.0 / 2.2).xxxx);
return final;
}
float4 gauss_bloom(sampler sp, float2 uv, float2 scale, int samples, float4 exposure, float thresh) {
float4 bright = clamp(gauss_blur(sp, uv, scale, samples) - thresh.xxxx, 0.0f.xxxx, 1.0f.xxxx) * (1.0f / (1.0f - thresh));
return bright * exposure;
}
float4 main(float4 sampleColor : COLOR0, float2 coords : TEXCOORD0) : COLOR0
{
return gauss_bloom(uImage0, coords, AspectCorrectedGBlurScale(uSource, 4.0f), 8, 1., 0.3f);
}
technique Technique1
{
pass BloomShader
{
PixelShader = compile ps_3_0 main();
}
}
Binary file not shown.
+147
View File
@@ -0,0 +1,147 @@
// Judgement Cut–style horizontal slash
// HLSL for use with SanePrimitiveRenderer's custom Effect path. This shader needs to be compensated for before use.
// Specifically SanePrimitiveRenderer. This won't work with the regular PrimitiveRenderer.
// You have been warned.
matrix uTransformMatrix;
float uTime;
float3 uColor;
float uBrightness;
struct VertexShaderInput
{
float4 Position : POSITION0;
float4 Color : COLOR0;
float2 TextureCoordinates : TEXCOORD0;
};
struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
float2 TextureCoordinates : TEXCOORD0;
};
VertexShaderOutput VertexShaderFunction(in VertexShaderInput input)
{
VertexShaderOutput output;
output.Position = mul(input.Position, uTransformMatrix);
output.Color = input.Color;
output.TextureCoordinates = input.TextureCoordinates;
return output;
}
float hash21(float2 p)
{
p = frac(p * float2(123.34, 456.21));
p += dot(p, p + 45.32);
return frac(p.x * p.y);
}
float noise(float2 p)
{
float2 i = floor(p);
float2 f = frac(p);
float2 u = f * f * (3.0 - 2.0 * f);
return lerp(
lerp(hash21(i), hash21(i + float2(1.0, 0.0)), u.x),
lerp(hash21(i + float2(0.0, 1.0)), hash21(i + float2(1.0, 1.0)), u.x),
u.y
);
}
float slashMask(float2 uv, float thickness, float feather)
{
float d = abs(uv.y);
return smoothstep(thickness + feather, thickness, d);
}
float3 chromaSlash(float2 uv, float time)
{
float thickness = 0.02;
float feather = 0.08;
float widthPulse = 1.0 + 0.35 * sin(uv.x * 18.0 - time * 14.0);
float localThickness = thickness * widthPulse;
float distortA = noise(float2(uv.x * 8.0 - time * 1.3, time * 6.0));
float distortB = noise(float2(uv.x * 16.0 + time * 0.9, time * 11.0));
float distort = (distortA - 0.5) * 0.06 + (distortB - 0.5) * 0.035;
uv.y += distort * slashMask(uv, localThickness * 2.0, feather);
float aberr = 0.015;
float r = slashMask(uv + float2( aberr, 0.0), localThickness, feather);
float g = slashMask(uv, localThickness, feather);
float b = slashMask(uv + float2(-aberr, 0.0), localThickness, feather);
float3 col = float3(r, g, b);
float core = slashMask(uv, localThickness * 0.38, feather * 0.22);
col += core * float3(1.4, 1.4, 1.5);
float glow = slashMask(uv, localThickness * 3.8, feather * 2.4);
col += glow * uColor * 0.7;
float veinNoise = noise(float2(uv.x * 22.0 - time * 3.0, uv.y * 48.0 + time * 10.0));
float veins = smoothstep(0.7, 0.98, veinNoise) * glow;
col += veins * uColor * 0.9;
float shock = exp(-abs(uv.y * 13.0 + sin(uv.x * 11.0 + time * 9.0) * 1.7));
col += shock * glow * uColor * 0.25;
return col;
}
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
float2 uv = input.TextureCoordinates * 2.0 - 1.0;
float time = uTime;
float3 col = chromaSlash(uv, time);
float2 bloomUV = float2(uv.x * 0.85, uv.y * 2.4);
float centerBloom = exp(-dot(bloomUV, bloomUV) * 3.8);
float bloomNoise = noise(float2(uv.x * 10.0 + time * 0.6, uv.y * 5.0));
centerBloom *= lerp(0.92, 1.08, bloomNoise);
centerBloom = saturate(centerBloom);
col += centerBloom * float3(0.18, 0.2, 0.25);
float sweepPos = frac(time * 1.25) * 2.0 - 1.0;
float sweep = exp(-abs(uv.x - sweepPos) * 18.0) * slashMask(uv, 0.12, 0.18);
col += sweep * lerp(float3(1.0, 1.0, 1.0), uColor, 0.2) * 0.55;
float sparkNoise = noise(float2(uv.x * 30.0 + time * 7.0, uv.y * 7.0 - time * 2.0));
float sparkMask = smoothstep(0.92, 0.995, sparkNoise) * slashMask(uv, 0.20, 0.24);
col += sparkMask * lerp(float3(1.0, 1.0, 1.0), uColor, 0.25) * 0.45;
float chromaPulse = 0.5 + 0.5 * sin(time * 6.0 + uv.x * 8.0);
float3 pulseTint = lerp(float3(0.9, 0.9, 0.9), float3(1.1, 1.1, 1.1), chromaPulse);
col *= pulseTint;
float flicker = 0.85 + 0.15 * sin(time * 40.0);
col *= flicker;
float edgeFade = smoothstep(1.0, 0.3, abs(uv.x));
col *= edgeFade;
float3 rawCol = col;
col *= input.Color.rgb;
col *= uBrightness;
float structureAlpha = max(rawCol.r, max(rawCol.g, rawCol.b));
float alpha = structureAlpha * input.Color.a;
return float4(col, alpha);
}
technique Technique1
{
pass SlashPass
{
VertexShader = compile vs_2_0 VertexShaderFunction();
PixelShader = compile ps_3_0 PixelShaderFunction();
}
}
Binary file not shown.
+4
View File
@@ -525,6 +525,10 @@ namespace CalamityMod.Events
// Handle dialogue as appropriate.
BossRushDialogueSystem.Tick();
// Tier 1 animation between Xeroc's initial dialogue and the first boss.
if (BossRushSpawnCountdown == 179 && EndTimer == 0 && CurrentlyFoughtBoss == NPCID.KingSlime)
CreateTierAnimation(1);
// Disable the stupid credits sequence.
if (CreditsRollEvent.IsEventOngoing)
CreditsRollEvent.SetRemainingTimeDirect(1);
+3 -2
View File
@@ -5,6 +5,7 @@ using CalamityMod.Enums;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent;
using Terraria.ModLoader;
namespace CalamityMod.Graphics.Metaballs
@@ -96,9 +97,9 @@ namespace CalamityMod.Graphics.Metaballs
Vector2 scale = Vector2.One * particle.Size / tex.Size();
float pureRedInterpolant = Utils.GetLerpValue(25f, 60f, particle.Size, true) * pureRedIntensity;
Color drawColor = Color.Lerp(EdgeColor, Color.DarkRed, pureRedInterpolant).MultiplyRGBA(new Color(1f, 1f, 1f, opacity));
Color drawColor = Color.Lerp(!ChildSafety.Disabled ? Color.CornflowerBlue : EdgeColor, (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed), pureRedInterpolant).MultiplyRGBA(new Color(1f, 1f, 1f, opacity));
Main.spriteBatch.Draw(tex, drawPosition, null, drawColor, 0f, origin, scale, SpriteEffects.None, 0f);
Main.spriteBatch.Draw(tex, drawPosition, null, (!ChildSafety.Disabled ? Color.CornflowerBlue : drawColor), 0f, origin, scale, SpriteEffects.None, 0f);
}
}
}
+3 -2
View File
@@ -5,6 +5,7 @@ using CalamityMod.Enums;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent;
using Terraria.ModLoader;
namespace CalamityMod.Graphics.Metaballs
@@ -96,9 +97,9 @@ namespace CalamityMod.Graphics.Metaballs
Vector2 scale = Vector2.One * particle.Size / tex.Size();
float pureRedInterpolant = Utils.GetLerpValue(25f, 60f, particle.Size, true) * pureRedIntensity;
Color drawColor = Color.Lerp(EdgeColor, Color.DarkRed, pureRedInterpolant).MultiplyRGBA(new Color(1f, 1f, 1f, opacity));
Color drawColor = Color.Lerp(!ChildSafety.Disabled ? Color.CornflowerBlue : EdgeColor, (!ChildSafety.Disabled ? Color.CornflowerBlue : Color.DarkRed), pureRedInterpolant).MultiplyRGBA(new Color(1f, 1f, 1f, opacity));
Main.spriteBatch.Draw(tex, drawPosition, null, drawColor, 0f, origin, scale, SpriteEffects.None, 0f);
Main.spriteBatch.Draw(tex, drawPosition, null, (!ChildSafety.Disabled ? Color.CornflowerBlue : drawColor), 0f, origin, scale, SpriteEffects.None, 0f);
}
}
}
+3 -2
View File
@@ -5,6 +5,7 @@ using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ReLogic.Content;
using Terraria;
using Terraria.GameContent;
using Terraria.ModLoader;
namespace CalamityMod.Graphics.Metaballs
@@ -80,7 +81,7 @@ namespace CalamityMod.Graphics.Metaballs
}
public override GeneralDrawLayer DrawLayer => GeneralDrawLayer.BeforeProjectiles;
public override Color EdgeColor => new Color(67, 17, 17);
public override Color EdgeColor => !ChildSafety.Disabled ? Color.CornflowerBlue : new Color(67, 17, 17);
public override void Update()
{
@@ -117,7 +118,7 @@ namespace CalamityMod.Graphics.Metaballs
Vector2 scale = modScale * particle.Size / texture2d.Width;
var frame = texture2d.Frame(1, particle.MaxFrames, 0, particle.CurrentFrame);
Vector2 origin = frame.Size() * 0.5f;
Main.spriteBatch.Draw(texture2d, drawPosition, frame, Color.White, particle.rotation, origin, scale, SpriteEffects.None, 0f);
Main.spriteBatch.Draw(texture2d, drawPosition, frame, !ChildSafety.Disabled ? Color.Black : Color.White, particle.rotation, origin, scale, SpriteEffects.None, 0f);
}
}
}
+9 -2
View File
@@ -120,8 +120,15 @@ namespace CalamityMod.Graphics.Metaballs
Main.screenPosition -= offset;
// Draw the metaball's raw contents with the shader.
Main.spriteBatch.Draw(metaball.LayerTargets[i].Target, offset, Color.White);
// If using Odd Mushroom, clone the drawing to each point.
Color metaballDraw = Main.LocalPlayer.Calamity().trippy ? Main.DiscoColor : Color.White;
Main.spriteBatch.Draw(metaball.LayerTargets[i].Target, offset, metaballDraw);
if (Main.LocalPlayer.Calamity().trippy)
{
Main.spriteBatch.Draw(metaball.LayerTargets[i].Target, offset, null, metaballDraw, 0f, Vector2.Zero, 1f, SpriteEffects.FlipHorizontally, 0f);
Main.spriteBatch.Draw(metaball.LayerTargets[i].Target, offset, null, metaballDraw, 0f, Vector2.Zero, 1f, SpriteEffects.FlipVertically, 0f);
Main.spriteBatch.Draw(metaball.LayerTargets[i].Target, offset, null, metaballDraw, 0f, Vector2.Zero, 1f, SpriteEffects.FlipHorizontally | SpriteEffects.FlipVertically, 0f);
}
}
}
@@ -0,0 +1,14 @@
Hi, if you are a Calamity addon or other mod dev, do not steal this directory.
I can almost guarantee that you will benefit from a simpler, less feature complete mesh renderer or simple shader.
This system is designed for easy debugging, completeness, correctness, ease of use, and arbitrary reuse.
It is not designed for ease of understanding or compactness. It is unreasonable to expect that you will be able to maintain it as a beginner.
You have been warned.
contact 'undeathlyghost' on discord for more information
notes:
all non-strip meshgen generates correct UVs but incorrect 'distorted' uvs may be desired sometimes for effects
i use 1e-6 as my primary epsilon value in this system, and i suggest you do the same for consistency
it is entirely possible to reuse meshes and you are encouraged to do so rather than reconstructing one if your mesh has no reason to be modified again
pooled meshes are preferred to avoid garbage collection for non-persistent/constantly changing meshes
@@ -0,0 +1,51 @@
#nullable enable
using System;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public readonly struct PooledPrimitiveMesh : IDisposable
{
private readonly PrimitiveMeshCache? _cache;
private readonly VertexPositionColorTexture[]? _textured;
private readonly VertexPositionColor[]? _colored;
private readonly short[] _indices;
internal PooledPrimitiveMesh(
PrimitiveMeshCache cache,
VertexPositionColorTexture[]? textured,
VertexPositionColor[]? colored,
short[] indices,
int vertexCount,
int indexCount,
PrimitiveType primitiveType,
bool usesTexture)
{
_cache = cache;
_textured = textured;
_colored = colored;
_indices = indices ?? throw new ArgumentNullException(nameof(indices));
VertexCount = vertexCount;
IndexCount = indexCount;
PrimitiveType = primitiveType;
UsesTexture = usesTexture;
}
public bool UsesTexture { get; }
public int VertexCount { get; }
public int IndexCount { get; }
public PrimitiveType PrimitiveType { get; }
public VertexPositionColorTexture[] TexturedVertices => _textured ?? throw new InvalidOperationException("Mesh lease does not contain textured vertices.");
public VertexPositionColor[] ColorVertices => _colored ?? throw new InvalidOperationException("Mesh lease does not contain color-only vertices.");
public short[] Indices => _indices;
public PrimitiveMeshView View => UsesTexture
? new PrimitiveMeshView(_textured!, _indices, PrimitiveType, 0, VertexCount, 0, IndexCount)
: new PrimitiveMeshView(_colored!, _indices, PrimitiveType, 0, VertexCount, 0, IndexCount);
public void Dispose()
{
_cache?.Return(_textured, _colored, _indices, UsesTexture);
}
}
@@ -0,0 +1,86 @@
#nullable enable
using System;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public readonly struct PrimitiveMesh
{
private readonly VertexPositionColorTexture[]? _texturedVertices;
private readonly VertexPositionColor[]? _colorVertices;
public PrimitiveMesh(VertexPositionColorTexture[] vertices, short[] indices, PrimitiveType primitiveType)
{
_texturedVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
_colorVertices = null;
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
if (_texturedVertices.Length == 0 || Indices.Length == 0)
throw new ArgumentException("Mesh must contain vertices and indices.");
if (_texturedVertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
UsesTexture = true;
}
public PrimitiveMesh(VertexPositionColor[] vertices, short[] indices, PrimitiveType primitiveType)
{
_texturedVertices = null;
_colorVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
if (_colorVertices.Length == 0 || Indices.Length == 0)
throw new ArgumentException("Mesh must contain vertices and indices.");
if (_colorVertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
UsesTexture = false;
}
public bool UsesTexture { get; }
public int VertexCount => UsesTexture ? _texturedVertices!.Length : _colorVertices!.Length;
public VertexPositionColorTexture[] TexturedVertices => _texturedVertices ?? throw new InvalidOperationException("Mesh does not contain textured vertices.");
public VertexPositionColor[] ColorVertices => _colorVertices ?? throw new InvalidOperationException("Mesh does not contain color-only vertices.");
public short[] Indices { get; }
public PrimitiveType PrimitiveType { get; }
public bool IsValid => VertexCount > 0 && Indices.Length > 0;
public PrimitiveMeshView AsView()
{
return UsesTexture
? new PrimitiveMeshView(_texturedVertices!, Indices, PrimitiveType, 0, _texturedVertices!.Length, 0, Indices.Length)
: new PrimitiveMeshView(_colorVertices!, Indices, PrimitiveType, 0, _colorVertices!.Length, 0, Indices.Length);
}
public static PrimitiveMesh FromSequential(VertexPositionColorTexture[] vertices, PrimitiveType primitiveType)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length == 0)
throw new ArgumentException("Vertices collection is empty.", nameof(vertices));
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
var indices = new short[vertices.Length];
PrimitiveSimd.FillSequentialIndices(indices.AsSpan());
return new PrimitiveMesh(vertices, indices, primitiveType);
}
public static PrimitiveMesh FromSequential(VertexPositionColor[] vertices, PrimitiveType primitiveType)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length == 0)
throw new ArgumentException("Vertices collection is empty.", nameof(vertices));
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
var indices = new short[vertices.Length];
PrimitiveSimd.FillSequentialIndices(indices.AsSpan());
return new PrimitiveMesh(vertices, indices, primitiveType);
}
}
@@ -0,0 +1,93 @@
#nullable enable
using System;
using System.Buffers;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public sealed class PrimitiveMeshCache
{
public static PrimitiveMeshCache Shared { get; } = new PrimitiveMeshCache();
private readonly ArrayPool<VertexPositionColorTexture> _texturedPool;
private readonly ArrayPool<VertexPositionColor> _colorPool;
private readonly ArrayPool<short> _indexPool;
private readonly bool _clearOnReturn;
public PrimitiveMeshCache(
ArrayPool<VertexPositionColorTexture>? texturedPool = null,
ArrayPool<VertexPositionColor>? colorPool = null,
ArrayPool<short>? indexPool = null,
bool clearOnReturn = false)
{
_texturedPool = texturedPool ?? ArrayPool<VertexPositionColorTexture>.Shared;
_colorPool = colorPool ?? ArrayPool<VertexPositionColor>.Shared;
_indexPool = indexPool ?? ArrayPool<short>.Shared;
_clearOnReturn = clearOnReturn;
}
public PooledPrimitiveMesh RentTextured(int vertexCount, int indexCount, PrimitiveType primitiveType)
{
if (vertexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Cannot meaningfully rent zero vertices.");
if (indexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(indexCount), "Cannot meaningfully rent an index buffer of size zero.");
if (vertexCount > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex count exceeds index buffer range.");
var vertices = _texturedPool.Rent(vertexCount);
var indices = _indexPool.Rent(indexCount);
return new PooledPrimitiveMesh(this, vertices, null, indices, vertexCount, indexCount, primitiveType, true);
}
public PooledPrimitiveMesh RentColored(int vertexCount, int indexCount, PrimitiveType primitiveType)
{
if (vertexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Cannot meaningfully rent zero vertices.");
if (indexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(indexCount), "Cannot meaningfully rent an index buffer of size zero.");
if (vertexCount > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex count exceeds index buffer range.");
var vertices = _colorPool.Rent(vertexCount);
var indices = _indexPool.Rent(indexCount);
return new PooledPrimitiveMesh(this, null, vertices, indices, vertexCount, indexCount, primitiveType, false);
}
public PooledPrimitiveMesh RentFromMesh(in PrimitiveMesh mesh)
{
if (!mesh.IsValid)
throw new ArgumentException("Mesh is invalid.", nameof(mesh));
if (mesh.UsesTexture)
{
var lease = RentTextured(mesh.VertexCount, mesh.Indices.Length, mesh.PrimitiveType);
Array.Copy(mesh.TexturedVertices, lease.TexturedVertices, mesh.VertexCount);
Array.Copy(mesh.Indices, lease.Indices, mesh.Indices.Length);
return lease;
}
else
{
var lease = RentColored(mesh.VertexCount, mesh.Indices.Length, mesh.PrimitiveType);
Array.Copy(mesh.ColorVertices, lease.ColorVertices, mesh.VertexCount);
Array.Copy(mesh.Indices, lease.Indices, mesh.Indices.Length);
return lease;
}
}
internal void Return(VertexPositionColorTexture[]? textured, VertexPositionColor[]? colored, short[] indices, bool usesTexture)
{
if (usesTexture)
{
if (textured != null)
_texturedPool.Return(textured, _clearOnReturn);
}
else
{
if (colored != null)
_colorPool.Return(colored, _clearOnReturn);
}
_indexPool.Return(indices, _clearOnReturn);
}
}
@@ -0,0 +1,492 @@
#nullable enable
// 10FEB2026: jasper: you probably don't need this file for casual mesh use.
// you should be careful with mesh transformations, they are intended for advanced users.
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public static class PrimitiveMeshExtensions
{
public static PrimitiveMesh Transform(this in PrimitiveMesh mesh, in Matrix transform)
{
if (!mesh.IsValid)
return mesh;
var indices = (short[])mesh.Indices.Clone();
if (mesh.UsesTexture)
{
var source = mesh.TexturedVertices;
var transformed = new VertexPositionColorTexture[source.Length];
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
transformed[i] = new VertexPositionColorTexture(
Vector3.Transform(v.Position, transform),
v.Color,
v.TextureCoordinate);
}
return new PrimitiveMesh(transformed, indices, mesh.PrimitiveType);
}
{
var source = mesh.ColorVertices;
var transformed = new VertexPositionColor[source.Length];
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
transformed[i] = new VertexPositionColor(
Vector3.Transform(v.Position, transform),
v.Color);
}
return new PrimitiveMesh(transformed, indices, mesh.PrimitiveType);
}
}
public static PrimitiveMesh Translate(this in PrimitiveMesh mesh, in Vector3 offset) =>
mesh.Transform(Matrix.CreateTranslation(offset));
public static PrimitiveMesh Scale(this in PrimitiveMesh mesh, in Vector3 scale) =>
mesh.Transform(Matrix.CreateScale(scale));
public static PrimitiveMesh Rotate(this in PrimitiveMesh mesh, in Quaternion rotation) =>
mesh.Transform(Matrix.CreateFromQuaternion(rotation));
public static PrimitiveMesh Extrude(this in PrimitiveMesh mesh, in Vector3 direction, bool closeCaps = true)
{
if (!mesh.IsValid)
throw new InvalidOperationException("Cannot extrude an invalid mesh.");
if (mesh.PrimitiveType != PrimitiveType.TriangleList)
throw new NotSupportedException("Extrusion currently supports triangle list meshes only.");
if (direction.LengthSquared() <= 1e-6f)
return mesh;
return mesh.UsesTexture
? ExtrudeTextured(mesh, direction, closeCaps)
: ExtrudeColored(mesh, direction, closeCaps);
}
private static PrimitiveMesh ExtrudeTextured(in PrimitiveMesh mesh, Vector3 direction, bool closeCaps)
{
var top = mesh.TexturedVertices;
var baseIndices = mesh.Indices;
int originalVertexCount = top.Length;
var vertices = new List<VertexPositionColorTexture>(originalVertexCount * 2);
vertices.AddRange(top);
for (int i = 0; i < originalVertexCount; i++)
{
var v = top[i];
vertices.Add(new VertexPositionColorTexture(
v.Position + direction,
v.Color,
v.TextureCoordinate));
}
var indices = new List<short>(closeCaps ? baseIndices.Length * 2 : baseIndices.Length + originalVertexCount * 6);
indices.AddRange(baseIndices);
if (closeCaps)
{
for (int i = 0; i < baseIndices.Length; i += 3)
{
short a = (short)(baseIndices[i] + originalVertexCount);
short b = (short)(baseIndices[i + 1] + originalVertexCount);
short c = (short)(baseIndices[i + 2] + originalVertexCount);
indices.Add(c);
indices.Add(b);
indices.Add(a);
}
}
var positions = new Vector3[originalVertexCount];
for (int i = 0; i < originalVertexCount; i++)
positions[i] = top[i].Position;
var loops = BuildBoundaryLoops(positions, baseIndices);
foreach (var loop in loops)
{
float perimeter = 0f;
for (int i = 0; i < loop.Count; i++)
perimeter += loop[i].Length;
if (perimeter <= 1e-6f)
continue;
float accumulated = 0f;
foreach (var edge in loop)
{
float u0 = accumulated / perimeter;
accumulated += edge.Length;
float u1 = accumulated / perimeter;
var startTop = top[edge.Start];
var endTop = top[edge.End];
var startBottomPos = startTop.Position + direction;
var endBottomPos = endTop.Position + direction;
short topStartIndex = AddVertex(vertices, new VertexPositionColorTexture(startTop.Position, startTop.Color, new Vector2(u0, 0f)));
short bottomStartIndex = AddVertex(vertices, new VertexPositionColorTexture(startBottomPos, startTop.Color, new Vector2(u0, 1f)));
short topEndIndex = AddVertex(vertices, new VertexPositionColorTexture(endTop.Position, endTop.Color, new Vector2(u1, 0f)));
short bottomEndIndex = AddVertex(vertices, new VertexPositionColorTexture(endBottomPos, endTop.Color, new Vector2(u1, 1f)));
indices.Add(topStartIndex);
indices.Add(topEndIndex);
indices.Add(bottomEndIndex);
indices.Add(topStartIndex);
indices.Add(bottomEndIndex);
indices.Add(bottomStartIndex);
}
}
return new PrimitiveMesh(vertices.ToArray(), indices.ToArray(), PrimitiveType.TriangleList);
}
private static PrimitiveMesh ExtrudeColored(in PrimitiveMesh mesh, Vector3 direction, bool closeCaps)
{
var top = mesh.ColorVertices;
var baseIndices = mesh.Indices;
int originalVertexCount = top.Length;
var vertices = new List<VertexPositionColor>(originalVertexCount * 2);
vertices.AddRange(top);
for (int i = 0; i < originalVertexCount; i++)
{
var v = top[i];
vertices.Add(new VertexPositionColor(v.Position + direction, v.Color));
}
var indices = new List<short>(closeCaps ? baseIndices.Length * 2 : baseIndices.Length + originalVertexCount * 6);
indices.AddRange(baseIndices);
if (closeCaps)
{
for (int i = 0; i < baseIndices.Length; i += 3)
{
short a = (short)(baseIndices[i] + originalVertexCount);
short b = (short)(baseIndices[i + 1] + originalVertexCount);
short c = (short)(baseIndices[i + 2] + originalVertexCount);
indices.Add(c);
indices.Add(b);
indices.Add(a);
}
}
var positions = new Vector3[originalVertexCount];
for (int i = 0; i < originalVertexCount; i++)
positions[i] = top[i].Position;
var loops = BuildBoundaryLoops(positions, baseIndices);
foreach (var loop in loops)
{
float perimeter = 0f;
for (int i = 0; i < loop.Count; i++)
perimeter += loop[i].Length;
if (perimeter <= 1e-6f)
continue;
float accumulated = 0f;
foreach (var edge in loop)
{
float u0 = accumulated / perimeter;
accumulated += edge.Length;
float u1 = accumulated / perimeter;
var startTop = top[edge.Start];
var endTop = top[edge.End];
var startBottomPos = startTop.Position + direction;
var endBottomPos = endTop.Position + direction;
short topStartIndex = AddVertex(vertices, new VertexPositionColor(startTop.Position, startTop.Color));
short bottomStartIndex = AddVertex(vertices, new VertexPositionColor(startBottomPos, startTop.Color));
short topEndIndex = AddVertex(vertices, new VertexPositionColor(endTop.Position, endTop.Color));
short bottomEndIndex = AddVertex(vertices, new VertexPositionColor(endBottomPos, endTop.Color));
indices.Add(topStartIndex);
indices.Add(topEndIndex);
indices.Add(bottomEndIndex);
indices.Add(topStartIndex);
indices.Add(bottomEndIndex);
indices.Add(bottomStartIndex);
}
}
return new PrimitiveMesh(vertices.ToArray(), indices.ToArray(), PrimitiveType.TriangleList);
}
public static PrimitiveMesh CurveEdges(this in PrimitiveMesh mesh, in Vector3 axis, float magnitude, float exponent = 2f)
{
if (!mesh.IsValid)
return mesh;
if (axis.LengthSquared() <= 1e-6f)
throw new ArgumentException("Axis must be non-zero.", nameof(axis));
if (mesh.PrimitiveType != PrimitiveType.TriangleList && mesh.PrimitiveType != PrimitiveType.TriangleStrip)
throw new NotSupportedException("CurveEdges supports triangle-based meshes.");
float clampedExponent = Math.Max(exponent, 1e-3f);
Vector3 axisDir = Vector3.Normalize(axis);
var indices = (short[])mesh.Indices.Clone();
if (mesh.UsesTexture)
{
var source = mesh.TexturedVertices;
var vertices = new VertexPositionColorTexture[source.Length];
ComputeCentroidAndRadius(source, out var centroid, out float radius);
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
Vector3 diff = v.Position - centroid;
float radial = radius <= 1e-6f ? 0f : diff.Length() / radius;
float factor = MathF.Pow(MathHelper.Clamp(radial, 0f, 1f), clampedExponent);
Vector3 offset = axisDir * magnitude * factor;
vertices[i] = new VertexPositionColorTexture(v.Position + offset, v.Color, v.TextureCoordinate);
}
return new PrimitiveMesh(vertices, indices, mesh.PrimitiveType);
}
else
{
var source = mesh.ColorVertices;
var vertices = new VertexPositionColor[source.Length];
ComputeCentroidAndRadius(source, out var centroid, out float radius);
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
Vector3 diff = v.Position - centroid;
float radial = radius <= 1e-6f ? 0f : diff.Length() / radius;
float factor = MathF.Pow(MathHelper.Clamp(radial, 0f, 1f), clampedExponent);
Vector3 offset = axisDir * magnitude * factor;
vertices[i] = new VertexPositionColor(v.Position + offset, v.Color);
}
return new PrimitiveMesh(vertices, indices, mesh.PrimitiveType);
}
}
private static void ComputeCentroidAndRadius(VertexPositionColorTexture[] vertices, out Vector3 centroid, out float radius)
{
centroid = Vector3.Zero;
for (int i = 0; i < vertices.Length; i++)
centroid += vertices[i].Position;
centroid /= vertices.Length;
radius = 1e-6f;
for (int i = 0; i < vertices.Length; i++)
{
float length = Vector3.Distance(centroid, vertices[i].Position);
if (length > radius)
radius = length;
}
}
private static void ComputeCentroidAndRadius(VertexPositionColor[] vertices, out Vector3 centroid, out float radius)
{
centroid = Vector3.Zero;
for (int i = 0; i < vertices.Length; i++)
centroid += vertices[i].Position;
centroid /= vertices.Length;
radius = 1e-6f;
for (int i = 0; i < vertices.Length; i++)
{
float length = Vector3.Distance(centroid, vertices[i].Position);
if (length > radius)
radius = length;
}
}
/// <summary>
/// Builds boundary loops from a triangle list.
/// Each loop is a sequence of connected boundary edges that form a closed path along the mesh surface.
/// Loops are returned in no particular order, and may be nested or intersecting.
/// Edges are oriented consistently within each loop, but not across different loops.
/// Only zero-length edges are discarded, and loops must close to be included.
/// </summary>
/// <param name="positions">Vertex positions for the mesh.</param>
/// <param name="indices">Triangle-list indices (groups of 3).</param>
/// <returns>Closed boundary loops built from boundary edges.</returns>
private static List<List<OrientedEdge>> BuildBoundaryLoops(IReadOnlyList<Vector3> positions, short[] indices)
{
var edgeMap = new Dictionary<EdgeKey, EdgeAccumulator>();
for (int i = 0; i < indices.Length; i += 3)
{
RegisterEdge(edgeMap, indices[i], indices[i + 1]);
RegisterEdge(edgeMap, indices[i + 1], indices[i + 2]);
RegisterEdge(edgeMap, indices[i + 2], indices[i]);
}
var edges = new List<OrientedEdge>();
foreach (var pair in edgeMap)
{
if (pair.Value.Count == 1)
{
var oriented = pair.Value.Orientation;
float length = Vector3.Distance(positions[oriented.Start], positions[oriented.End]);
if (length > 1e-6f)
edges.Add(new OrientedEdge(oriented.Start, oriented.End, length));
}
}
var loops = new List<List<OrientedEdge>>();
var used = new bool[edges.Count];
for (int i = 0; i < edges.Count; i++)
{
if (used[i])
continue;
var loop = new List<OrientedEdge>();
used[i] = true;
loop.Add(edges[i]);
short head = edges[i].End;
bool closed = head == loop[0].Start;
while (!closed)
{
bool found = false;
for (int j = 0; j < edges.Count; j++)
{
if (used[j])
continue;
var candidate = edges[j];
if (candidate.Start == head)
{
used[j] = true;
loop.Add(candidate);
head = candidate.End;
found = true;
}
else if (candidate.End == head)
{
candidate = candidate.Reversed();
edges[j] = candidate;
used[j] = true;
loop.Add(candidate);
head = candidate.End;
found = true;
}
if (found)
{
closed = head == loop[0].Start;
break;
}
}
if (!found)
break;
}
if (loop.Count > 1 && closed)
loops.Add(loop);
}
return loops;
}
private static void RegisterEdge(Dictionary<EdgeKey, EdgeAccumulator> edgeMap, short start, short end)
{
var key = new EdgeKey(Math.Min(start, end), Math.Max(start, end));
if (edgeMap.TryGetValue(key, out var accumulator))
{
accumulator.Count++;
edgeMap[key] = accumulator;
}
else
{
edgeMap[key] = new EdgeAccumulator
{
Count = 1,
Orientation = new OrientedEdge(start, end, 0f)
};
}
}
/// <summary>
/// Adds a vertex to the list and returns its index. Most likely, you do not need to use this directly.
/// </summary>
/// <param name="vertices">The vertex list to add to.</param>
/// <param name="vertex">The vertex to add.</param>
private static short AddVertex(List<VertexPositionColorTexture> vertices, VertexPositionColorTexture vertex)
{
if (vertices.Count >= short.MaxValue)
throw new InvalidOperationException("Primitive mesh exceeded 16-bit vertex capacity.");
vertices.Add(vertex);
return (short)(vertices.Count - 1);
}
/// <summary>
/// Adds a vertex to the list and returns its index. Most likely, you do not need to use this directly.
/// </summary>
/// <param name="vertices">The vertex list to add to.</param>
/// <param name="vertex">The vertex to add.</param>
private static short AddVertex(List<VertexPositionColor> vertices, VertexPositionColor vertex)
{
if (vertices.Count >= short.MaxValue)
throw new InvalidOperationException("Primitive mesh exceeded 16-bit vertex capacity.");
vertices.Add(vertex);
return (short)(vertices.Count - 1);
}
private readonly struct EdgeKey : IEquatable<EdgeKey>
{
public readonly short Min;
public readonly short Max;
public EdgeKey(short min, short max)
{
Min = min;
Max = max;
}
public bool Equals(EdgeKey other) => Min == other.Min && Max == other.Max;
public override bool Equals(object? obj) => obj is EdgeKey other && Equals(other);
public override int GetHashCode()
{
unchecked
{
return (Min * 397) ^ Max;
}
}
}
private struct EdgeAccumulator
{
public int Count;
public OrientedEdge Orientation;
}
private struct OrientedEdge
{
public short Start;
public short End;
public float Length;
public OrientedEdge(short start, short end, float length)
{
Start = start;
End = end;
Length = length;
}
public OrientedEdge Reversed() => new OrientedEdge(End, Start, Length);
}
}
@@ -0,0 +1,87 @@
#nullable enable
using System;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public readonly struct PrimitiveMeshView
{
private readonly VertexPositionColorTexture[]? _texturedVertices;
private readonly VertexPositionColor[]? _colorVertices;
public PrimitiveMeshView(
VertexPositionColorTexture[] vertices,
short[] indices,
PrimitiveType primitiveType,
int vertexOffset,
int vertexCount,
int indexOffset,
int indexCount)
{
_texturedVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
_colorVertices = null;
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
ValidateRanges(vertices.Length, indices.Length, vertexOffset, vertexCount, indexOffset, indexCount);
VertexOffset = vertexOffset;
VertexCount = vertexCount;
IndexOffset = indexOffset;
IndexCount = indexCount;
UsesTexture = true;
}
public PrimitiveMeshView(
VertexPositionColor[] vertices,
short[] indices,
PrimitiveType primitiveType,
int vertexOffset,
int vertexCount,
int indexOffset,
int indexCount)
{
_texturedVertices = null;
_colorVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
ValidateRanges(vertices.Length, indices.Length, vertexOffset, vertexCount, indexOffset, indexCount);
VertexOffset = vertexOffset;
VertexCount = vertexCount;
IndexOffset = indexOffset;
IndexCount = indexCount;
UsesTexture = false;
}
public bool UsesTexture { get; }
public int VertexOffset { get; }
public int VertexCount { get; }
public int IndexOffset { get; }
public int IndexCount { get; }
public PrimitiveType PrimitiveType { get; }
public bool IsValid => VertexCount > 0 && IndexCount > 0;
public VertexPositionColorTexture[] TexturedVertices => _texturedVertices ?? throw new InvalidOperationException("Mesh view does not contain textured vertices.");
public VertexPositionColor[] ColorVertices => _colorVertices ?? throw new InvalidOperationException("Mesh view does not contain color-only vertices.");
public short[] Indices { get; }
private static void ValidateRanges(int vertexArrayLength, int indexArrayLength, int vertexOffset, int vertexCount, int indexOffset, int indexCount)
{
if (vertexOffset < 0)
throw new ArgumentOutOfRangeException(nameof(vertexOffset));
if (vertexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(vertexCount));
if (indexOffset < 0)
throw new ArgumentOutOfRangeException(nameof(indexOffset));
if (indexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(indexCount));
if (vertexOffset + vertexCount > vertexArrayLength)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex range exceeds the vertex buffer length.");
if (indexOffset + indexCount > indexArrayLength)
throw new ArgumentOutOfRangeException(nameof(indexCount), "Index range exceeds the index buffer length.");
if (vertexCount > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex count exceeds index buffer range.");
}
}
@@ -0,0 +1,23 @@
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Graphics.Primitives;
public sealed class PrimitiveRenderSystem : ModSystem
{
public override void Load()
{
if (Main.dedServ)
return;
Main.QueueMainThreadAction(() =>
{
SanePrimitiveRenderer.Initialize();
});
}
public override void Unload()
{
SanePrimitiveRenderer.Dispose();
}
}
@@ -0,0 +1,503 @@
#nullable enable
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public static class PrimitiveShapeBuilder
{
public static PrimitiveMesh BuildRectangularQuad(
Vector3 center,
Vector2 size,
Color color,
Vector3 normal,
Vector3 upHint,
bool textured = false)
{
BuildFrame(normal, upHint, out var right, out var up);
var halfRight = right * (size.X * 0.5f);
var halfUp = up * (size.Y * 0.5f);
if (textured)
{
var vertices = new[]
{
new VertexPositionColorTexture(center - halfRight - halfUp, color, new Vector2(0f, 1f)),
new VertexPositionColorTexture(center + halfRight - halfUp, color, new Vector2(1f, 1f)),
new VertexPositionColorTexture(center + halfRight + halfUp, color, new Vector2(1f, 0f)),
new VertexPositionColorTexture(center - halfRight + halfUp, color, new Vector2(0f, 0f))
};
var indices = new short[] { 0, 1, 2, 0, 2, 3 };
return new PrimitiveMesh(vertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new[]
{
new VertexPositionColor(center - halfRight - halfUp, color),
new VertexPositionColor(center + halfRight - halfUp, color),
new VertexPositionColor(center + halfRight + halfUp, color),
new VertexPositionColor(center - halfRight + halfUp, color)
};
var colorIndices = new short[] { 0, 1, 2, 0, 2, 3 };
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
/// <summary>
/// Builds a regular polygon with the specified number of sides, centered at the given position, and oriented according to the normal and up hint.
/// The polygon is constructed in a single triangle fan, with the center vertex as the first element and subsequent vertices arranged in a clockwise order around the normal.
/// If you need a different vertex order or a more complex polygon, consider <see cref="BuildArbitraryPolygon(IReadOnlyList{Vector3}, Color, bool)"/>
/// </summary>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <param name="sides"></param>
/// <param name="color"></param>
/// <param name="normal"></param>
/// <param name="upHint"></param>
/// <param name="textured"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static PrimitiveMesh BuildRegularPolygon(
Vector3 center,
float radius,
int sides,
Color color,
Vector3 normal,
Vector3 upHint,
bool textured = false)
{
if (sides < 3)
throw new ArgumentOutOfRangeException(nameof(sides), "Polygon requires at least three sides.");
BuildFrame(normal, upHint, out var right, out var up);
if (textured)
{
var texturedVertices = new VertexPositionColorTexture[sides + 1];
texturedVertices[0] = new VertexPositionColorTexture(center, color, new Vector2(0.5f, 0.5f));
float safeRadius = Math.Max(radius, 1e-6f);
for (int i = 0; i < sides; i++)
{
var direction = PolarToCartesian(i, sides, right, up) * radius;
var point = center + direction;
float u = 0.5f + 0.5f * MathHelper.Clamp(Vector3.Dot(direction, right) / safeRadius, -1f, 1f);
float v = 0.5f - 0.5f * MathHelper.Clamp(Vector3.Dot(direction, up) / safeRadius, -1f, 1f);
texturedVertices[i + 1] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[sides * 3];
for (int i = 0; i < sides; i++)
{
int next = (i + 1) % sides;
int baseIndex = i * 3;
indices[baseIndex] = 0;
indices[baseIndex + 1] = (short)(i + 1);
indices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(texturedVertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[sides + 1];
colorVertices[0] = new VertexPositionColor(center, color);
for (int i = 0; i < sides; i++)
{
var direction = PolarToCartesian(i, sides, right, up) * radius;
colorVertices[i + 1] = new VertexPositionColor(center + direction, color);
}
var colorIndices = new short[sides * 3];
for (int i = 0; i < sides; i++)
{
int next = (i + 1) % sides;
int baseIndex = i * 3;
colorIndices[baseIndex] = 0;
colorIndices[baseIndex + 1] = (short)(i + 1);
colorIndices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildArbitraryPolygon(IReadOnlyList<Vector3> points, Color color, bool textured = false)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (points.Count < 3)
throw new ArgumentOutOfRangeException(nameof(points), "Polygon requires at least three points.");
if (textured)
{
float minX = points[0].X, maxX = points[0].X;
float minY = points[0].Y, maxY = points[0].Y;
for (int i = 1; i < points.Count; i++)
{
var p = points[i];
if (p.X < minX) minX = p.X;
if (p.X > maxX) maxX = p.X;
if (p.Y < minY) minY = p.Y;
if (p.Y > maxY) maxY = p.Y;
}
float width = Math.Max(maxX - minX, 1e-6f);
float height = Math.Max(maxY - minY, 1e-6f);
var texturedVertices = new VertexPositionColorTexture[points.Count];
for (int i = 0; i < points.Count; i++)
{
var point = points[i];
float u = (point.X - minX) / width;
float v = (point.Y - minY) / height;
texturedVertices[i] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[(points.Count - 2) * 3];
for (int i = 0; i < points.Count - 2; i++)
{
indices[i * 3] = 0;
indices[i * 3 + 1] = (short)(i + 1);
indices[i * 3 + 2] = (short)(i + 2);
}
return new PrimitiveMesh(texturedVertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[points.Count];
for (int i = 0; i < points.Count; i++)
{
var point = points[i];
colorVertices[i] = new VertexPositionColor(point, color);
}
var colorIndices = new short[(points.Count - 2) * 3];
for (int i = 0; i < points.Count - 2; i++)
{
colorIndices[i * 3] = 0;
colorIndices[i * 3 + 1] = (short)(i + 1);
colorIndices[i * 3 + 2] = (short)(i + 2);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildEllipse(
Vector3 center,
Vector2 radii,
int segments,
Color color,
Vector3 normal,
Vector3 upHint,
bool textured = false)
{
if (segments < 3)
throw new ArgumentOutOfRangeException(nameof(segments), "Ellipse requires at least three segments.");
BuildFrame(normal, upHint, out var right, out var up);
if (textured)
{
var vertices = new VertexPositionColorTexture[segments + 1];
vertices[0] = new VertexPositionColorTexture(center, color, new Vector2(0.5f, 0.5f));
float safeX = Math.Max(radii.X, 1e-6f);
float safeY = Math.Max(radii.Y, 1e-6f);
for (int i = 0; i < segments; i++)
{
var offset = EllipseDirection(i, segments, right, up, radii);
var point = center + offset;
float u = 0.5f + 0.5f * MathHelper.Clamp(Vector3.Dot(offset, right) / safeX, -1f, 1f);
float v = 0.5f - 0.5f * MathHelper.Clamp(Vector3.Dot(offset, up) / safeY, -1f, 1f);
vertices[i + 1] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int next = (i + 1) % segments;
int baseIndex = i * 3;
indices[baseIndex] = 0;
indices[baseIndex + 1] = (short)(i + 1);
indices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(vertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[segments + 1];
colorVertices[0] = new VertexPositionColor(center, color);
for (int i = 0; i < segments; i++)
{
colorVertices[i + 1] = new VertexPositionColor(center + EllipseDirection(i, segments, right, up, radii), color);
}
var colorIndices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int next = (i + 1) % segments;
int baseIndex = i * 3;
colorIndices[baseIndex] = 0;
colorIndices[baseIndex + 1] = (short)(i + 1);
colorIndices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildSphere(
Vector3 center,
float radius,
int latitudeSegments,
int longitudeSegments,
Func<Vector3, Color>? colorFunc = null,
bool textured = false)
{
if (latitudeSegments < 2)
throw new ArgumentOutOfRangeException(nameof(latitudeSegments), "Sphere requires at least two latitude segments.");
if (longitudeSegments < 3)
throw new ArgumentOutOfRangeException(nameof(longitudeSegments), "Sphere requires at least three longitude segments.");
colorFunc ??= static _ => Color.White;
int vertexRows = latitudeSegments + 1;
int vertexCols = longitudeSegments + 1;
int vertexCount = vertexRows * vertexCols;
if (vertexCount > short.MaxValue)
throw new InvalidOperationException("Sphere produced more vertices than supported by the index buffer.");
if (textured)
{
var vertices = new VertexPositionColorTexture[vertexCount];
int v = 0;
for (int lat = 0; lat <= latitudeSegments; lat++)
{
float phi = MathF.PI * lat / latitudeSegments;
float sinPhi = MathF.Sin(phi);
float cosPhi = MathF.Cos(phi);
float vCoord = 1f - (float)lat / latitudeSegments;
for (int lon = 0; lon <= longitudeSegments; lon++)
{
float theta = MathHelper.TwoPi * lon / longitudeSegments;
var normal = SphericalDirection(sinPhi, cosPhi, theta);
float uCoord = (float)lon / longitudeSegments;
vertices[v++] = new VertexPositionColorTexture(center + normal * radius, colorFunc(normal), new Vector2(uCoord, vCoord));
}
}
var indices = new List<short>(latitudeSegments * longitudeSegments * 6);
for (int lat = 0; lat < latitudeSegments; lat++)
{
for (int lon = 0; lon < longitudeSegments; lon++)
{
int current = lat * vertexCols + lon;
int next = current + vertexCols;
indices.Add((short)current);
indices.Add((short)(current + 1));
indices.Add((short)next);
indices.Add((short)(current + 1));
indices.Add((short)(next + 1));
indices.Add((short)next);
}
}
return new PrimitiveMesh(vertices, indices.ToArray(), PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[vertexCount];
int vIndex = 0;
for (int lat = 0; lat <= latitudeSegments; lat++)
{
float phi = MathF.PI * lat / latitudeSegments;
float sinPhi = MathF.Sin(phi);
float cosPhi = MathF.Cos(phi);
for (int lon = 0; lon <= longitudeSegments; lon++)
{
float theta = MathHelper.TwoPi * lon / longitudeSegments;
var normal = SphericalDirection(sinPhi, cosPhi, theta);
colorVertices[vIndex++] = new VertexPositionColor(center + normal * radius, colorFunc(normal));
}
}
var colorIndices = new List<short>(latitudeSegments * longitudeSegments * 6);
for (int lat = 0; lat < latitudeSegments; lat++)
{
for (int lon = 0; lon < longitudeSegments; lon++)
{
int current = lat * vertexCols + lon;
int next = current + vertexCols;
colorIndices.Add((short)current);
colorIndices.Add((short)(current + 1));
colorIndices.Add((short)next);
colorIndices.Add((short)(current + 1));
colorIndices.Add((short)(next + 1));
colorIndices.Add((short)next);
}
}
return new PrimitiveMesh(colorVertices, colorIndices.ToArray(), PrimitiveType.TriangleList);
}
// Heres your vertice, sir. You probably don't need to call this directly.
public static PrimitiveMesh BuildTriangle(Vector3 a, Vector3 b, Vector3 c, Color color, bool textured = false)
{
if (textured)
{
var vertices = new[]
{
new VertexPositionColorTexture(a, color, new Vector2(0f, 1f)),
new VertexPositionColorTexture(b, color, new Vector2(1f, 1f)),
new VertexPositionColorTexture(c, color, new Vector2(0.5f, 0f))
};
return new PrimitiveMesh(vertices, new short[] { 0, 1, 2 }, PrimitiveType.TriangleList);
}
var colorVertices = new[]
{
new VertexPositionColor(a, color),
new VertexPositionColor(b, color),
new VertexPositionColor(c, color)
};
return new PrimitiveMesh(colorVertices, new short[] { 0, 1, 2 }, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildSemiCircle(
Vector3 center,
float radius,
int segments,
Color color,
Vector3 normal,
Vector3 forward,
bool textured = false)
{
if (segments < 2)
throw new ArgumentOutOfRangeException(nameof(segments), "Semi-circle requires at least two segments.");
var n = normal.LengthSquared() < 1e-6f ? Vector3.Backward : Vector3.Normalize(normal);
var f = forward.LengthSquared() < 1e-6f ? Vector3.Forward : Vector3.Normalize(forward);
if (MathF.Abs(Vector3.Dot(f, n)) > 0.999f)
f = Vector3.Normalize(Vector3.Cross(n, Vector3.Right));
var right = Vector3.Normalize(Vector3.Cross(n, f));
var tangent = Vector3.Normalize(Vector3.Cross(right, n));
if (textured)
{
var texturedVertices = new VertexPositionColorTexture[segments + 2];
texturedVertices[0] = new VertexPositionColorTexture(center, color, new Vector2(0.5f, 1f));
float safeRadius = Math.Max(radius, 1e-6f); // todo: remove
float newStep = MathF.PI / segments;
for (int i = 0; i <= segments; i++)
{
float angle = newStep * i;
Vector3 offset = right * MathF.Cos(angle) + tangent * MathF.Sin(angle);
Vector3 point = center + offset * radius;
float x = MathHelper.Clamp(Vector3.Dot(offset, right), -1f, 1f);
float y = MathHelper.Clamp(Vector3.Dot(offset, tangent), 0f, 1f);
float u = 0.5f + 0.5f * x;
float v = 1f - y;
texturedVertices[i + 1] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int baseIndex = i * 3;
indices[baseIndex] = 0;
indices[baseIndex + 1] = (short)(i + 1);
indices[baseIndex + 2] = (short)(i + 2);
}
return new PrimitiveMesh(texturedVertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[segments + 2];
colorVertices[0] = new VertexPositionColor(center, color);
float step = MathF.PI / segments;
for (int i = 0; i <= segments; i++)
{
float angle = step * i;
Vector3 offset = right * MathF.Cos(angle) + tangent * MathF.Sin(angle);
colorVertices[i + 1] = new VertexPositionColor(center + offset * radius, color);
}
var colorIndices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int baseIndex = i * 3;
colorIndices[baseIndex] = 0;
colorIndices[baseIndex + 1] = (short)(i + 1);
colorIndices[baseIndex + 2] = (short)(i + 2);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
/// <summary>
/// Given a normal and an up hint, builds an orthonormal basis where the normal is the "forward" direction,
/// the right vector is perpendicular to both, and the up vector is perpendicular to the normal.
/// The implementation normalizes the inputs, handles near-parallel cases, and then re-orthogonalizes the up vector
/// from the computed right vector (so it is not guaranteed to be the closest possible to <paramref name="upHint"/>).
/// </summary>
/// <param name="normal">The forward/normal direction (fallbacks to <see cref="Vector3.Backward"/> if near-zero).</param>
/// <param name="upHint">A preferred up direction (fallbacks to <see cref="Vector3.Up"/> if near-zero).</param>
/// <param name="right">The computed right vector.</param>
/// <param name="up">The computed up vector.</param>
private static void BuildFrame(Vector3 normal, Vector3 upHint, out Vector3 right, out Vector3 up)
{
var n = normal.LengthSquared() < 1e-6f ? Vector3.Backward : Vector3.Normalize(normal);
up = upHint.LengthSquared() < 1e-6f ? Vector3.Up : Vector3.Normalize(upHint);
if (MathF.Abs(Vector3.Dot(n, up)) > 0.999f)
up = Vector3.Normalize(Vector3.Cross(n, Vector3.Right));
right = Vector3.Cross(up, n);
if (right.LengthSquared() < 1e-6f)
right = Vector3.Cross(Vector3.Forward, n);
right.Normalize();
up = Vector3.Normalize(Vector3.Cross(n, right));
}
private static Vector3 PolarToCartesian(int index, int total, Vector3 right, Vector3 up)
{
float angle = MathHelper.TwoPi * index / total;
return right * MathF.Cos(angle) + up * MathF.Sin(angle);
}
private static Vector3 EllipseDirection(int index, int total, Vector3 right, Vector3 up, Vector2 radii)
{
float angle = MathHelper.TwoPi * index / total;
return right * (MathF.Cos(angle) * radii.X) + up * (MathF.Sin(angle) * radii.Y);
}
private static Vector3 SphericalDirection(float sinPhi, float cosPhi, float theta)
{
float cosTheta = MathF.Cos(theta);
float sinTheta = MathF.Sin(theta);
return new Vector3(sinPhi * cosTheta, cosPhi, sinPhi * sinTheta);
}
}
@@ -0,0 +1,40 @@
using System;
namespace CalamityMod.Graphics.Primitives;
internal static class PrimitiveSimd
{
private static readonly System.Numerics.Vector<int> LaneOffsets = CreateLaneOffsets();
public static void FillSequentialIndices(Span<short> indices)
{
int i = 0;
if (System.Numerics.Vector.IsHardwareAccelerated)
{
int width = System.Numerics.Vector<int>.Count;
Span<int> temp = width <= 16
? stackalloc int[width]
: new int[width];
while (i <= indices.Length - width)
{
(LaneOffsets + new System.Numerics.Vector<int>(i)).CopyTo(temp);
for (int lane = 0; lane < width; lane++)
indices[i + lane] = (short)temp[lane];
i += width;
}
}
for (; i < indices.Length; i++)
indices[i] = (short)i;
}
private static System.Numerics.Vector<int> CreateLaneOffsets()
{
int width = System.Numerics.Vector<int>.Count;
Span<int> lanes = stackalloc int[width];
for (int i = 0; i < width; i++)
lanes[i] = i;
return new System.Numerics.Vector<int>(lanes);
}
}
@@ -0,0 +1,805 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent;
namespace CalamityMod.Graphics.Primitives;
public static class SanePrimitiveRenderer
{
private static GraphicsDevice _graphicsDevice => Main.graphics.GraphicsDevice;
private static BasicEffect? _effect;
public readonly struct ShaderScope : IDisposable
{
private readonly GraphicsDevice _device;
private readonly Effect _effect;
private readonly bool _useBasicEffect;
private readonly Matrix _world;
private readonly Matrix _view;
private readonly Matrix _projection;
private readonly string? _transformMatrixParam;
private readonly RasterizerState _previousRasterizer;
private readonly DepthStencilState _previousDepth;
private readonly BlendState _previousBlend;
private readonly SamplerState? _previousSampler;
internal ShaderScope(
GraphicsDevice device,
Effect effect,
bool useBasicEffect,
in Matrix world,
in Matrix view,
in Matrix projection,
string? transformMatrixParam,
RasterizerState? rasterizerState,
DepthStencilState? depthState,
BlendState? blendState,
SamplerState? samplerState)
{
_device = device;
_effect = effect;
_useBasicEffect = useBasicEffect;
_world = world;
_view = view;
_projection = projection;
_transformMatrixParam = transformMatrixParam;
_previousRasterizer = device.RasterizerState;
_previousDepth = device.DepthStencilState;
_previousBlend = device.BlendState;
_previousSampler = device.SamplerStates[0];
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
device.SamplerStates[0] = samplerState ?? SamplerState.PointWrap;
if (_useBasicEffect)
{
var basic = (BasicEffect)_effect;
basic.World = world;
basic.View = view;
basic.Projection = projection;
}
else if (transformMatrixParam != null)
{
var param = _effect.Parameters[transformMatrixParam];
if (param != null)
param.SetValue(world * view * projection);
}
}
public void Draw(in PrimitiveMesh mesh)
{
if (!mesh.IsValid)
return;
if (_useBasicEffect)
{
var basic = (BasicEffect)_effect;
bool textured = mesh.UsesTexture;
basic.TextureEnabled = textured;
basic.Texture = textured ? TextureAssets.MagicPixel.Value : null;
}
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.Indices.Length);
bool usesTexture = mesh.UsesTexture;
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (usesTexture)
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
else
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
}
}
public void Draw(in PrimitiveMeshView mesh)
{
if (!mesh.IsValid)
return;
if (_useBasicEffect)
{
var basic = (BasicEffect)_effect;
bool textured = mesh.UsesTexture;
basic.TextureEnabled = textured;
basic.Texture = textured ? TextureAssets.MagicPixel.Value : null;
}
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.IndexCount);
bool usesTexture = mesh.UsesTexture;
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (usesTexture)
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
else
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
}
}
public void Dispose()
{
_device.RasterizerState = _previousRasterizer;
_device.DepthStencilState = _previousDepth;
_device.BlendState = _previousBlend;
if (_previousSampler != null)
_device.SamplerStates[0] = _previousSampler;
}
}
public static bool IsReady =>
_graphicsDevice != null &&
!_graphicsDevice.IsDisposed &&
_effect != null &&
!_effect.IsDisposed;
public static void Initialize()
{
Main.RunOnMainThread(() =>
{
if (_graphicsDevice == null)
throw new ArgumentNullException(nameof(_graphicsDevice));
_effect?.Dispose();
_effect = new BasicEffect(_graphicsDevice)
{
VertexColorEnabled = true,
TextureEnabled = true,
LightingEnabled = false,
FogEnabled = false,
Texture = TextureAssets.Logo.Value
};
});
}
public static void Dispose()
{
Main.RunOnMainThread(() =>
_effect?.Dispose()
);
}
/// <summary>
/// Draws the specified mesh using the provided world, view, and projection matrices.
/// </summary>
/// <param name="world">World matrix.</param>
/// <param name="view">View matrix.</param>
/// <param name="projection">Projection matrix.</param>
/// <param name="mesh">The mesh to draw.</param>
/// <param name="rasterizerState">The rasterizer state to use. If null, defaults to <see cref="RasterizerState.CullNone"/>.</param>
/// <param name="depthState">The depth stencil state to use. If null, defaults to <see cref="DepthStencilState.Default"/>.</param>
/// <param name="blendState">The blend state to use. If null, defaults to <see cref="BlendState.AlphaBlend"/>.</param>
/// <exception cref="InvalidOperationException">The renderer is not initialized.</exception>
/// <exception cref="NotSupportedException">The primitive type is not supported. Supported types are: TriangleList, TriangleStrip, LineList, LineStrip, and PointListEXT.</exception>
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMesh mesh,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (!IsReady)
throw new InvalidOperationException("SanePrimitiveRenderer is not initialized.");
if (!mesh.IsValid)
return;
Debug.Assert(_effect is not null);
bool textured = mesh.UsesTexture;
_effect.TextureEnabled = textured;
_effect.Texture = textured ? TextureAssets.MagicPixel.Value : null;
_graphicsDevice.SamplerStates[0] = SamplerState.PointWrap;
_effect.World = world;
_effect.View = view;
_effect.Projection = projection;
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.Indices.Length);
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
/// <summary>
/// Draws the specified mesh using an arbitrary <see cref="Effect"/> instead of the built-in <see cref="BasicEffect"/>.<br/>
/// The caller is responsible for setting all shader parameters (including any transform matrices) before calling this method.<br/>
/// A convenience parameter, <paramref name="transformMatrixParam"/>, can be used to automatically set a <c>uTransformMatrix</c>
/// parameter on the effect to <c>world * view * projection</c>.
/// </summary>
/// <param name="world">World matrix.</param>
/// <param name="view">View matrix.</param>
/// <param name="projection">Projection matrix.</param>
/// <param name="mesh">The mesh to draw.</param>
/// <param name="effect">The custom effect to use for rendering.</param>
/// <param name="transformMatrixParam">
/// If non-null, the name of an <see cref="EffectParameter"/> on <paramref name="effect"/> that will be set to <c>world * view * projection</c>.
/// Defaults to <c>"uTransformMatrix"</c>. Pass <c>null</c> to skip automatic matrix assignment.
/// </param>
/// <param name="rasterizerState">The rasterizer state to use. If null, defaults to <see cref="RasterizerState.CullNone"/>.</param>
/// <param name="depthState">The depth stencil state to use. If null, defaults to <see cref="DepthStencilState.Default"/>.</param>
/// <param name="blendState">The blend state to use. If null, defaults to <see cref="BlendState.AlphaBlend"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="effect"/> is null.</exception>
/// <exception cref="NotSupportedException">The primitive type is not supported.</exception>
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMesh mesh,
Effect effect,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (!mesh.IsValid)
return;
if (transformMatrixParam != null)
{
var param = effect.Parameters[transformMatrixParam];
if (param != null)
param.SetValue(world * view * projection);
}
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.Indices.Length);
bool textured = mesh.UsesTexture;
foreach (var pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
/** <summary>
Draws a triangle strip using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle strip' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleStrip(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColorTexture[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleStrip),
rasterizerState,
depthState,
blendState);
}
/** <summary>
Draws a triangle strip using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle strip' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleStrip(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColor[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleStrip),
rasterizerState,
depthState,
blendState);
}
/** <summary>
Draws a triangle list using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle list' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleList(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColorTexture[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3 || vertices.Length % 3 != 0)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleList),
rasterizerState,
depthState,
blendState);
}
/** <summary>
Draws a triangle list using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle list' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleList(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColor[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3 || vertices.Length % 3 != 0)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleList),
rasterizerState,
depthState,
blendState);
}
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMeshView mesh,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (!IsReady)
throw new InvalidOperationException("SanePrimitiveRenderer is not initialized.");
if (!mesh.IsValid)
return;
Debug.Assert(_effect is not null);
bool textured = mesh.UsesTexture;
_effect.TextureEnabled = textured;
_effect.Texture = textured ? TextureAssets.MagicPixel.Value : null;
_graphicsDevice.SamplerStates[0] = SamplerState.PointWrap;
_effect.World = world;
_effect.View = view;
_effect.Projection = projection;
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.IndexCount);
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMeshView mesh,
Effect effect,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (!mesh.IsValid)
return;
if (transformMatrixParam != null)
{
var param = effect.Parameters[transformMatrixParam];
if (param != null)
param.SetValue(world * view * projection);
}
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.IndexCount);
bool textured = mesh.UsesTexture;
foreach (var pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
public static ShaderScope BeginShaderScope(
in Matrix world,
in Matrix view,
in Matrix projection,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (!IsReady)
throw new InvalidOperationException("SanePrimitiveRenderer is not initialized.");
Debug.Assert(_effect is not null);
return new ShaderScope(
_graphicsDevice,
_effect,
true,
world,
view,
projection,
null,
rasterizerState,
depthState,
blendState,
samplerState);
}
public static ShaderScope BeginShaderScope(
Effect effect,
in Matrix world,
in Matrix view,
in Matrix projection,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
return new ShaderScope(
_graphicsDevice,
effect,
false,
world,
view,
projection,
transformMatrixParam,
rasterizerState,
depthState,
blendState,
samplerState);
}
public static void DrawMeshes(
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMesh> meshes,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(world, view, projection, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
public static void DrawMeshes(
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMeshView> meshes,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(world, view, projection, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
public static void DrawMeshes(
Effect effect,
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMesh> meshes,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(effect, world, view, projection, transformMatrixParam, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
public static void DrawMeshes(
Effect effect,
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMeshView> meshes,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(effect, world, view, projection, transformMatrixParam, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
private static int GetPrimitiveCount(PrimitiveType primitiveType, int indexCount)
{
return primitiveType switch
{
PrimitiveType.TriangleList => indexCount / 3,
PrimitiveType.TriangleStrip => Math.Max(indexCount - 2, 0),
PrimitiveType.LineList => indexCount / 2,
PrimitiveType.LineStrip => Math.Max(indexCount - 1, 0),
PrimitiveType.PointListEXT => indexCount,
_ => throw new NotSupportedException(primitiveType.ToString())
};
}
}
@@ -0,0 +1,16 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Determines the shape of end caps for strip primitives. This is used to give a more polished look to the start and end of strips, especially when they are thick. The cap is drawn at the end of the strip, centered on the last vertex, and oriented to match the strip's direction at that point. The options are:
/// <list type="bullet">
/// <item><description><see cref="None"/>: No cap is drawn, leaving the strip to end abruptly at the last vertex. This is the default and most performant option.</description></item>
/// <item><description><see cref="Triangle"/>: A simple triangular cap is drawn, extending the strip in a pointed shape. The triangle's base is aligned with the last segment of the strip, and its height is proportional to the strip's width.</description></item>
/// <item><description><see cref="HalfCircle"/>: A semicircular cap is drawn, creating a rounded end to the strip.</description></item>
/// </list>
/// </summary>
public enum StripCapStyle
{
None,
Triangle,
HalfCircle
}
@@ -0,0 +1,18 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Specifies the type of curve interpolation to use when generating a strip mesh from a sequence of points.
///
/// <remarks>
/// The curve type determines how the strip will be shaped between the control points.
/// Different curve types can produce smoother or sharper results, and may have different performance characteristics.
/// </remarks>
/// </summary>
public enum StripCurveType
{
CatmullRom,
Linear,
CubicBezier,
Hermite
}
@@ -0,0 +1,15 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Specifies how to join segments in a strip mesh.
///
/// <list type="bullet">
/// <item><description><see cref="Perpendicular"/>: Uses the averaged per-segment right vectors to build a perpendicular join at corners. This is the default and most performant option.</description></item>
/// <item><description><see cref="Miter"/>: Uses a miter join that extends the edges to their intersection, with a built-in miter limit to avoid extreme spikes on sharp angles.</description></item>
/// </list>
/// </summary>
public enum StripJoinStyle
{
Perpendicular,
Miter
}
@@ -0,0 +1,15 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Controls how strip width is attenuated along the path.
///
/// <list type="bullet">
/// <item><description><see cref="None"/>: No attenuation is applied; width comes solely from the provided width function/constant.</description></item>
/// <item><description><see cref="ContinuitySquared"/>: Attenuates width based on directional continuity between consecutive tangents.</description></item>
/// </list>
/// </summary>
public enum StripWidthAttenuation
{
None,
ContinuitySquared
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -9,7 +9,7 @@ namespace CalamityMod.Items.Accessories
{
public new string LocalizationCategory => "Items.Accessories";
public static int cooldown = 600;
public static int damage = 225;
public static int damage = 100;
public override void SetDefaults()
{
Item.width = 36;
+1 -1
View File
@@ -9,7 +9,7 @@ namespace CalamityMod.Items.Accessories
{
public new string LocalizationCategory => "Items.Accessories";
public static int cooldown = 300;
public static int damage = 32;
public static int damage = 20;
public override void SetDefaults()
{
Item.width = 30;
+1 -1
View File
@@ -10,7 +10,7 @@ namespace CalamityMod.Items.Accessories
public class ChaosStone : ModItem, ILocalizedModType
{
public static float LostRegenPer100Mana => 8;
public static float DamageMultPer100Mana => 0.03f;
public static float DamageMultPer100Mana => 0.04f;
public new string LocalizationCategory => "Items.Accessories";
public override void ModifyTooltips(List<TooltipLine> tooltips)
{
+1 -9
View File
@@ -427,17 +427,9 @@ namespace CalamityMod.Items.Accessories
player.Calamity().profanedSoulWeaponUsage = 0;
}
int manaCost = (int)(100 * player.manaCost);
if (player.statMana < manaCost && player.Calamity().profanedSoulWeaponUsage == 0)
{
if (player.manaFlower)
{
player.QuickMana();
}
}
if (player.statMana >= manaCost && player.Calamity().profanedSoulWeaponUsage == 0 && !player.silence)
if (player.Calamity().profanedSoulWeaponUsage == 0 && !player.silence && player.CheckMana(manaCost, true))
{
player.manaRegenDelay = (int)player.maxRegenDelay;
player.statMana -= manaCost;
correctedVelocity *= 25f;
SoundEngine.PlaySound(SoundID.Item20, player.Center);
int magefireBaseDamage = 900;
+1 -1
View File
@@ -9,7 +9,7 @@ namespace CalamityMod.Items.Accessories
{
public new string LocalizationCategory => "Items.Accessories";
public static int cooldown = 420;
public static int damage = 68;
public static int damage = 60;
public override void SetDefaults()
{
Item.width = 34;
+9 -1
View File
@@ -1,4 +1,6 @@
using CalamityMod.CalPlayer;
using System.Collections.Generic;
using CalamityMod.Buffs.DamageOverTime;
using CalamityMod.CalPlayer;
using CalamityMod.Projectiles.Typeless;
using Microsoft.Xna.Framework;
using Terraria;
@@ -34,5 +36,11 @@ namespace CalamityMod.Items.Accessories
Projectile.NewProjectileDirect(player.GetSource_FromThis(), player.Center, Vector2.Zero, ProjectileType<ScionsCurioMini>(), 0, 0f, player.whoAmI);
}
}
public override void ModifyTooltips(List<TooltipLine> list)
{
Player player = Main.LocalPlayer;
if (Main.LocalPlayer != null)
list.FindAndReplace("[DAMAGE]", ((int)(player.Calamity().scionsCurioDebuffDamage / 2)).ToString() + " DPS");
}
}
}
+5 -5
View File
@@ -39,11 +39,11 @@ namespace CalamityMod.Items.Accessories
modPlayer.rBrain = true; // Handles shaderain cloud spawning on hit
modPlayer.amalgam = true;
player.brainOfConfusionItem = Item;
modPlayer.HeatDebuffMultiplier += 3f;
modPlayer.ColdDebuffMultiplier += 3f;
modPlayer.SicknessDebuffMultiplier += 3f;
modPlayer.WaterDebuffMultiplier += 3f;
modPlayer.ElectricDebuffMultiplier += 3f;
modPlayer.HeatDebuffMultiplier += 2f;
modPlayer.ColdDebuffMultiplier += 2f;
modPlayer.SicknessDebuffMultiplier += 2f;
modPlayer.WaterDebuffMultiplier += 2f;
modPlayer.ElectricDebuffMultiplier += 2f;
}
public override void AddRecipes()
+1
View File
@@ -152,6 +152,7 @@ namespace CalamityMod.Items.Accessories.Wings
player.jumpBoost = true;
player.autoJump = true;
player.jumpSpeedBoost += 1.6f;
player.noFallDmg = true;
// Mirrors the +5% luck from Lucky Horseshoe (vanilla behavior).
player.Calamity().calamityBonusLuck += 0.05f;
@@ -39,7 +39,7 @@ namespace CalamityMod.Items.Armor.SnowRuffian
Item.height = 18;
Item.value = CalamityGlobalItem.RarityBlueBuyPrice;
Item.rare = ItemRarityID.Blue;
Item.defense = 5; //12
Item.defense = 4; //9
}
public override void UpdateEquip(Player player) => player.GetCritChance<RangedDamageClass>() += RangedCritBoost;
@@ -10,8 +10,8 @@ namespace CalamityMod.Items.Armor.SnowRuffian
{
public new string LocalizationCategory => "Items.Armor.PreHardmode";
public static int RangedCritBoost = 4;
public override LocalizedText Tooltip => base.Tooltip.WithFormatArgs(RangedCritBoost);
public static float RangedDamageBoost = 0.05f;
public override LocalizedText Tooltip => base.Tooltip.WithFormatArgs(RangedDamageBoost.ToPercent());
public override void SetDefaults()
{
@@ -19,10 +19,10 @@ namespace CalamityMod.Items.Armor.SnowRuffian
Item.height = 18;
Item.value = CalamityGlobalItem.RarityBlueBuyPrice;
Item.rare = ItemRarityID.Blue;
Item.defense = 4; //12
Item.defense = 3; //9
}
public override void UpdateEquip(Player player) => player.GetCritChance<RangedDamageClass>() += RangedCritBoost;
public override void UpdateEquip(Player player) => player.GetDamage<RangedDamageClass>() += RangedDamageBoost;
public override void AddRecipes()
{
+5 -5
View File
@@ -10,12 +10,12 @@ namespace CalamityMod.Items.Armor.SnowRuffian
{
public new string LocalizationCategory => "Items.Armor.PreHardmode";
public static int RangedCritBoost = 4;
public override LocalizedText Tooltip => base.Tooltip.WithFormatArgs(RangedCritBoost);
public static float RangedDamageBoost = 0.05f;
public override LocalizedText Tooltip => base.Tooltip.WithFormatArgs(RangedDamageBoost.ToPercent());
// Set Bonus
public static float GlideFallSpeedMult = 0.9f;
public static int SetBonusFrostburnDuration = CalamityUtils.SecondsToFrames(3);
public static int SetBonusFrostburnDuration = CalamityUtils.SecondsToFrames(2);
public override void Load()
{
@@ -31,7 +31,7 @@ namespace CalamityMod.Items.Armor.SnowRuffian
Item.height = 18;
Item.value = CalamityGlobalItem.RarityBlueBuyPrice;
Item.rare = ItemRarityID.Blue;
Item.defense = 3; // 12
Item.defense = 2; // 9
}
public override bool IsArmorSet(Item head, Item body, Item legs) => body.type == ModContent.ItemType<SnowRuffianChestplate>() && legs.type == ModContent.ItemType<SnowRuffianGreaves>();
@@ -43,7 +43,7 @@ namespace CalamityMod.Items.Armor.SnowRuffian
player.setBonus = this.GetLocalization("SetBonus").Format(SetBonusFrostburnDuration.FramesToSeconds());
}
public override void UpdateEquip(Player player) => player.GetCritChance<RangedDamageClass>() += RangedCritBoost;
public override void UpdateEquip(Player player) => player.GetDamage<RangedDamageClass>() += RangedDamageBoost;
public override void AddRecipes()
{
+2 -16
View File
@@ -177,22 +177,8 @@ namespace CalamityMod.Items.BaseItems
{
currentTransformation.ModifyDrawInfo(ref drawInfo);
if (currentTransformation.EquipSlots.Any(s => s.Type == EquipType.Head))
{
drawInfo.headGlowMask = -1;
drawInfo.helmetOffset = Vector2.Zero;
}
if (currentTransformation.EquipSlots.Any(s => s.Type == EquipType.Body))
{
drawInfo.bodyGlowMask = -1;
}
if (currentTransformation.EquipSlots.Any(s => s.Type == EquipType.Legs))
{
drawInfo.legsGlowMask = -1;
drawInfo.legsOffset = Vector2.Zero;
}
// CIT 24FEB2026: Previously, this hook also reset glowmasks and offsets on the head, body, and legs.
// This has been removed, as it resulted in index OOB crashes due to the original armor being drawn for one frame.
}
}
-44
View File
@@ -1049,31 +1049,9 @@ namespace CalamityMod.Items
player.GetAttackSpeed<MeleeDamageClass>() += 0.05f;
break;
case ItemID.SquireGreaves:
player.GetDamage<SummonDamageClass>() -= 0.05f;
break;
case ItemID.HuntressWig:
player.GetCritChance<RangedDamageClass>() += 5;
break;
case ItemID.HuntressJerkin:
player.GetDamage<RangedDamageClass>() -= 0.05f;
player.GetDamage<SummonDamageClass>() -= 0.05f;
break;
case ItemID.ApprenticeHat:
player.GetDamage<MagicDamageClass>() -= 0.1f;
break;
case ItemID.ApprenticeRobe:
player.GetDamage<SummonDamageClass>() -= 0.05f;
player.GetDamage<MagicDamageClass>() += 0.05f;
break;
case ItemID.ApprenticeTrousers:
player.GetCritChance<MagicDamageClass>() -= 5;
break;
case ItemID.ShroomiteBreastplate:
player.GetDamage<RangedDamageClass>() -= 0.05f;
@@ -1094,28 +1072,6 @@ namespace CalamityMod.Items
player.GetDamage<SummonDamageClass>() -= 0.05f;
break;
case ItemID.HuntressAltShirt:
player.GetDamage<RangedDamageClass>() -= 0.05f;
player.GetDamage<SummonDamageClass>() -= 0.05f;
break;
case ItemID.HuntressAltPants:
player.GetDamage<SummonDamageClass>() -= 0.05f;
break;
case ItemID.ApprenticeAltHead:
player.GetDamage<MagicDamageClass>() -= 0.05f;
player.GetDamage<SummonDamageClass>() -= 0.05f;
break;
case ItemID.ApprenticeAltShirt:
player.GetDamage<SummonDamageClass>() -= 0.05f;
break;
case ItemID.ApprenticeAltPants:
player.GetCritChance<MagicDamageClass>() -= 10;
break;
case ItemID.SolarFlareHelmet:
player.GetCritChance<MeleeDamageClass>() -= 6;
break;
+5 -32
View File
@@ -941,20 +941,6 @@ namespace CalamityMod.Items
#region DD2 Armor
// Nerf sets that are too strong
if (item.type == ItemID.SquireGreaves)
EditTooltipByNum(0, (line) => line.Text = EditedTooltip("SquireGreaves"));
if (item.type == ItemID.HuntressWig)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("10%", "15%"));
if (item.type == ItemID.HuntressJerkin)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("20%", "15%"));
if (item.type == ItemID.ApprenticeHat)
EditTooltipByNum(0, (line) => line.Text = EditedTooltip("ApprenticeHat"));
if (item.type == ItemID.ApprenticeRobe)
EditTooltipByNum(0, (line) => line.Text = EditedTooltip("ApprenticeRobe"));
if (item.type == ItemID.ApprenticeTrousers)
EditTooltipByNum(0, (line) => line.Text = EditedTooltip("ApprenticeTrousers"));
if (item.type == ItemID.SquireAltHead)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("10%", "15%"));
@@ -963,18 +949,6 @@ namespace CalamityMod.Items
if (item.type == ItemID.SquireAltPants)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("20%", "15%"));
if (item.type == ItemID.HuntressAltShirt)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("25%", "20%"));
if (item.type == ItemID.HuntressAltPants)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("25%", "20%"));
if (item.type == ItemID.ApprenticeAltHead)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("15%", "10%"));
if (item.type == ItemID.ApprenticeAltShirt)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("25%", "20%"));
if (item.type == ItemID.ApprenticeAltPants)
EditTooltipByNum(0, (line) => line.Text = line.Text.Replace("25%", "15%"));
// Tweaks into Rogue
// Monk armor
if (item.type == ItemID.MonkBrows)
@@ -1199,12 +1173,11 @@ namespace CalamityMod.Items
AddWingStats(item.wingSlot, 0.5f, 0.1f, 0.5f, 1.5f, 0.1f);
// All developer wings have identical stats and no special effects
if (item.type == ItemID.Yoraiz0rWings || item.type == ItemID.JimsWings || item.type == ItemID.SkiphsWings ||
item.type == ItemID.LokisWings || item.type == ItemID.ArkhalisWings || item.type == ItemID.LeinforsWings ||
item.type == ItemID.BejeweledValkyrieWing || item.type == ItemID.RedsWings || item.type == ItemID.DTownsWings ||
item.type == ItemID.WillsWings || item.type == ItemID.CrownosWings || item.type == ItemID.CenxsWings ||
item.type == ItemID.FoodBarbarianWings || item.type == ItemID.GroxTheGreatWings || item.type == ItemID.GhostarsWings ||
item.type == ItemID.SafemanWings)
if (item.type == ItemID.Yoraiz0rWings || item.type == ItemID.JimsWings || item.type == ItemID.LokisWings ||
item.type == ItemID.ArkhalisWings || item.type == ItemID.LeinforsWings || item.type == ItemID.RedsWings ||
item.type == ItemID.DTownsWings || item.type == ItemID.WillsWings || item.type == ItemID.CrownosWings ||
item.type == ItemID.CenxsWings || item.type == ItemID.FoodBarbarianWings || item.type == ItemID.GroxTheGreatWings ||
item.type == ItemID.GhostarsWings || item.type == ItemID.SafemanWings)
{
AddWingStats(item.wingSlot, 0.5f, 0.1f, 0.5f, 1.5f, 0.1f);
}
@@ -18,7 +18,7 @@ namespace CalamityMod.Items.Critters
Item.DefaultToCapturedCritter(ModContent.NPCType<BabyCannonballJellyfish>());
Item.value = Item.sellPrice(silver: 10);
Item.rare = ItemRarityID.Green;
Item.damage = 400;
Item.damage = 300;
}
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ namespace CalamityMod.Items.Fishing.AstralCatches
public static int CooldownReducedPerKill = 180;
public static int MaxCooldown = 300;
public static int BaseSwipeDamage = 200;
public static int BaseSwipeDamage = 325; // About 65 dps
public override void SetDefaults()
{
Binary file not shown.

Before

Width:  |  Height:  |  Size: 342 B

After

Width:  |  Height:  |  Size: 266 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 361 B

After

Width:  |  Height:  |  Size: 284 B

+1 -1
View File
@@ -19,7 +19,7 @@ namespace CalamityMod.Items.Materials
Item.width = 30;
Item.height = 24;
Item.maxStack = Item.CommonMaxStack;
Item.value = Item.sellPrice(silver: 6);
Item.value = Item.sellPrice(silver: 36);
Item.rare = ItemRarityID.Green;
}
public override void AddRecipes()
+1 -1
View File
@@ -32,7 +32,7 @@ namespace CalamityMod.Items.PermanentBoosters
Item.useAnimation = Item.useTime = 30;
Item.UseSound = UseSound;
Item.useStyle = ItemUseStyleID.HoldUp;
Item.value = Item.sellPrice(gold: 30);
Item.value = Item.sellPrice(gold: 24);
Item.rare = ItemRarityID.Yellow;
}
+1 -1
View File
@@ -35,7 +35,7 @@ namespace CalamityMod.Items.PermanentBoosters
Item.useAnimation = Item.useTime = 30;
Item.UseSound = UseSound;
Item.useStyle = ItemUseStyleID.HoldUp;
Item.value = Item.sellPrice(gold: 48);
Item.value = Item.sellPrice(gold: 36);
Item.rare = ModContent.RarityType<BurnishedAuric>();
}
+1 -1
View File
@@ -33,7 +33,7 @@ namespace CalamityMod.Items.PermanentBoosters
Item.useAnimation = Item.useTime = 30;
Item.UseSound = UseSound;
Item.useStyle = ItemUseStyleID.HoldUp;
Item.value = Item.sellPrice(gold: 24);
Item.value = Item.sellPrice(gold: 16);
Item.rare = ItemRarityID.LightPurple;
}
+1 -1
View File
@@ -34,7 +34,7 @@ namespace CalamityMod.Items.PermanentBoosters
Item.useAnimation = Item.useTime = 30;
Item.UseSound = UseSound;
Item.useStyle = ItemUseStyleID.HoldUp;
Item.value = Item.sellPrice(gold: 36);
Item.value = Item.sellPrice(gold: 28);
Item.rare = ModContent.RarityType<Turquoise>();
}
@@ -78,6 +78,7 @@ namespace CalamityMod.Items.Placeables.Furniture.Paintings
"PokerFace",
"Raesh",
"Sagittariod",
"sixtydegrees",
"StipulateVenus",
"Sunny",
"_tofu",
+16 -2
View File
@@ -1,7 +1,10 @@
using CalamityMod.NPCs.AcidRain;
using System.Collections.Generic;
using System.Linq;
using CalamityMod.NPCs.AcidRain;
using CalamityMod.Rarities;
using Terraria;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
namespace CalamityMod.Items.SummonItems
@@ -9,6 +12,8 @@ namespace CalamityMod.Items.SummonItems
public class BloodwormItem : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.SummonItems";
public const int SpoofBaitNumber = 4444;
public override void SetStaticDefaults()
{
Item.ResearchUnlockCount = 3;
@@ -20,7 +25,10 @@ namespace CalamityMod.Items.SummonItems
Item.width = 28;
Item.height = 28;
Item.maxStack = Item.CommonMaxStack;
Item.bait = 4444;
// Why spoof this in the tooltip?
// To fix bugs related to how bait power affects hooking fish.
// Vanilla gets around this for Truffle Worm with a hundred hardcoded checks but we don't have the full luxury to do that.
Item.bait = 50;
Item.useStyle = ItemUseStyleID.Swing;
Item.autoReuse = true;
Item.useTurn = true;
@@ -38,5 +46,11 @@ namespace CalamityMod.Items.SummonItems
{
itemGroup = ContentSamples.CreativeHelper.ItemGroup.BossItem;
}
public override void ModifyTooltips(List<TooltipLine> tooltips)
{
TooltipLine bait = tooltips.FirstOrDefault(x => x.Mod == "Terraria" && x.Name == "BaitPower");
bait?.Text = Language.GetTextValue("GameUI.BaitPower", SpoofBaitNumber);
}
}
}
+65 -12
View File
@@ -13,8 +13,8 @@ namespace CalamityMod.Items.SummonItems
public new string LocalizationCategory => "Items.SummonItems";
public override void SetDefaults()
{
Item.width = Main.zenithWorld ? 54 : 28;
Item.height = Main.zenithWorld ? 78 : 28;
Item.width = Main.zenithWorld ? 54 : 70;
Item.height = Main.zenithWorld ? 78 : 80;
Item.rare = ItemRarityID.Blue;
Item.useAnimation = 45;
Item.useTime = 45;
@@ -31,17 +31,67 @@ namespace CalamityMod.Items.SummonItems
Item.SetNameOverride(this.GetLocalizedValue("GFBName"));
}
public override bool PreDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frameI, Color drawColor, Color itemColor, Vector2 origin, float scale)
public override void ModifyResearchSorting(ref ContentSamples.CreativeHelper.ItemGroup itemGroup)
{
// The wiki classifies Boss Rush as an event
itemGroup = ContentSamples.CreativeHelper.ItemGroup.EventItem;
}
#region Sprite Drawing
public static void DrawTerminusGlow(SpriteBatch spriteBatch, Vector2 baseDrawPosition, Rectangle frame, float rotation, float baseScale)
{
Texture2D glowTexture = ModContent.Request<Texture2D>("CalamityMod/Items/SummonItems/TerminusGlow").Value;
Vector2 origin = frame.Size() * 0.5f;
float pulseRate = Main.GlobalTimeWrappedHourly % 5f;
float slowingRate = Main.GlobalTimeWrappedHourly * 0.4f;
float orbitRadius = baseScale != 1f ? 4f : 7f;
float glowCount = 3f;
pulseRate /= 2.5f;
if (pulseRate >= 1f)
pulseRate = 2f - pulseRate;
pulseRate *= 0.6f;
for (int i = 0; i < glowCount; i++)
{
float progress = i / glowCount;
float pulseRotation = (progress + slowingRate) * MathHelper.TwoPi;
Vector2 offset = Vector2.UnitY * orbitRadius;
offset = offset.RotatedBy(pulseRotation) * pulseRate;
spriteBatch.Draw(glowTexture, baseDrawPosition + offset, frame, new Color(56, 12, 115, 33), rotation, origin, baseScale, 0, 0);
}
spriteBatch.Draw(glowTexture, baseDrawPosition, frame, Color.White, rotation, origin, baseScale, 0, 0);
}
public static void DrawGlowInWorld(SpriteBatch spriteBatch, Vector2 baseDrawPosition, float rotation, float baseScale)
{
Texture2D glowTexture = ModContent.Request<Texture2D>("CalamityMod/Items/SummonItems/TerminusGlow").Value;
Rectangle frame = glowTexture.Bounds;
DrawTerminusGlow(spriteBatch, baseDrawPosition + new Vector2(0, -1), frame, rotation, baseScale);
}
public override bool PreDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frame, Color drawColor, Color itemColor, Vector2 origin, float scale)
{
Texture2D texture;
float invScale = scale * 1.4f;
if (Main.zenithWorld)
{
Texture2D texture = ModContent.Request<Texture2D>("CalamityMod/Items/SummonItems/Terminus_GFB").Value;
Color overlay = Color.White;
spriteBatch.Draw(texture, position, null, overlay, 0f, origin, scale, 0, 0);
return false;
texture = ModContent.Request<Texture2D>("CalamityMod/Items/SummonItems/Terminus_GFB").Value;
spriteBatch.Draw(texture, position - new Vector2(-4, -1), null, Color.White, 0f, origin, invScale - 0.04f, 0, 0);
}
else
return true;
{
texture = ModContent.Request<Texture2D>("CalamityMod/Items/SummonItems/Terminus").Value;
spriteBatch.Draw(texture, position, null, Color.White, 0f, origin, invScale, 0, 0);
DrawTerminusGlow(spriteBatch, position, frame, 0f, invScale);
}
return false;
}
public override bool PreDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, ref float rotation, ref float scale, int whoAmI)
@@ -49,17 +99,20 @@ namespace CalamityMod.Items.SummonItems
if (Main.zenithWorld)
{
Texture2D texture = ModContent.Request<Texture2D>("CalamityMod/Items/SummonItems/Terminus_GFB").Value;
spriteBatch.Draw(texture, Item.position - Main.screenPosition, null, lightColor, 0f, Vector2.Zero, 1f, 0, 0);
spriteBatch.Draw(texture, Item.position - Main.screenPosition, null, lightColor, rotation, Vector2.Zero, scale, 0, 0);
return false;
}
else
return true;
}
public override void ModifyResearchSorting(ref ContentSamples.CreativeHelper.ItemGroup itemGroup)
public override void PostDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, float rotation, float scale, int whoAmI)
{
// The wiki classifies Boss Rush as an event
itemGroup = ContentSamples.CreativeHelper.ItemGroup.EventItem;
if (!Main.zenithWorld)
{
DrawGlowInWorld(spriteBatch, Item.Center - Main.screenPosition, rotation, scale);
}
}
#endregion
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 673 B

+2 -2
View File
@@ -15,9 +15,9 @@ namespace CalamityMod.Items.Tools
Item.height = 48;
Item.damage = 19;
Item.knockBack = 2.5f;
Item.useTime = 6;
Item.useTime = 9;
Item.useAnimation = 12;
Item.pick = 90;
Item.pick = 105;
Item.tileBoost += 1;
Item.DamageType = DamageClass.Melee;
@@ -24,14 +24,13 @@ namespace CalamityMod.Items.VanillaArmorChanges
public override void ApplyHeadPieceEffect(Player player)
{
player.GetAttackSpeed<MeleeDamageClass>() -= 0.2f;
player.Calamity().rogueVelocity += 0.15f; // Replace melee speed with rogue velocity.
player.Calamity().rogueVelocity += 0.2f; // Replace melee speed with rogue velocity.
}
public override void ApplyBodyPieceEffect(Player player)
{
player.GetDamage<MeleeDamageClass>() -= 0.2f;
player.GetDamage<RogueDamageClass>() += 0.15f; // Replace melee damage with rogue damage.
player.GetDamage<SummonDamageClass>() -= 0.05f; // Small nerf to summon damage.
player.GetDamage<RogueDamageClass>() += 0.2f; // Replace melee damage with rogue damage.
}
public override void ApplyLegPieceEffect(Player player)
@@ -14,7 +14,7 @@ namespace CalamityMod.Items.VanillaArmorChanges
public override string ArmorSetName => "MonkTier3";
public static float SetBonusRogueStealth = 1f;
public static float SetBonusRogueStealth = 1.1f;
public override void UpdateSetBonusText(ref string setBonusText)
{
@@ -38,8 +38,7 @@ namespace CalamityMod.Items.VanillaArmorChanges
public override void ApplyLegPieceEffect(Player player)
{
player.GetCritChance<MeleeDamageClass>() -= 20;
player.GetCritChance<RogueDamageClass>() += 10; // Replace melee crit with rogue crit.
player.GetDamage<SummonDamageClass>() -= 0.1f; // Small nerf to summon damage.
player.GetCritChance<RogueDamageClass>() += 20; // Replace melee crit with rogue crit.
}
public override void ApplyArmorSetBonus(Player player)
+10 -6
View File
@@ -33,26 +33,30 @@ namespace CalamityMod.Items.Weapons.Magic
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
for (int i = 0; i <= 3; i++)
int beeAmount = player.strongBees ? 3 : 2;
for (int i = 0; i <= beeAmount; i++)
{
float SpeedX = velocity.X + (float)Main.rand.Next(-35, 36) * 0.05f;
float SpeedY = velocity.Y + (float)Main.rand.Next(-35, 36) * 0.05f;
int wasps = Projectile.NewProjectile(source, position.X, position.Y, SpeedX, SpeedY, type, damage, 0f, player.whoAmI);
int wasps = Projectile.NewProjectile(source, position.X, position.Y, SpeedX, SpeedY, type, player.strongBees ? damage+5 : damage, 0f, player.whoAmI);
if (wasps.WithinBounds(Main.maxProjectiles))
{
Main.projectile[wasps].penetrate = 1;
{;
Main.projectile[wasps].DamageType = DamageClass.Magic;
Main.projectile[wasps].idStaticNPCHitCooldown = 5;
if (player.strongBees)
Main.projectile[wasps].ArmorPenetration += 5;
}
}
for (int i = 0; i <= 3; i++)
for (int i = 0; i <= beeAmount; i++)
{
float SpeedX2 = velocity.X + (float)Main.rand.Next(-35, 36) * 0.05f;
float SpeedY2 = velocity.Y + (float)Main.rand.Next(-35, 36) * 0.05f;
int bees = Projectile.NewProjectile(source, position.X, position.Y, SpeedX2, SpeedY2, player.beeType(), player.beeDamage(Item.damage), player.beeKB(0f), player.whoAmI);
if (bees.WithinBounds(Main.maxProjectiles))
{
Main.projectile[bees].penetrate = 1;
Main.projectile[bees].DamageType = DamageClass.Magic;
Main.projectile[bees].idStaticNPCHitCooldown = 5;
}
}
return false;
+1 -1
View File
@@ -8,7 +8,7 @@ namespace CalamityMod.Items.Weapons.Melee
public class Bonebreaker : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Weapons.Melee";
public const int BaseDamage = 45;
public const int BaseDamage = 55;
public override void SetDefaults()
{
+1 -1
View File
@@ -33,7 +33,7 @@ namespace CalamityMod.Items.Weapons.Melee
{
Item.width = 70;
Item.height = 70;
Item.damage = 900;
Item.damage = 700;
Item.knockBack = 9f;
Item.useAnimation = Item.useTime = 24;
Item.DamageType = DamageClass.Melee;
+1 -1
View File
@@ -73,7 +73,7 @@ namespace CalamityMod.Items.Weapons.Melee
}
if (player.Calamity().demonSwordKillMode && player.ownedProjectileCounts[ModContent.ProjectileType<ExaltedOathbladeHoldout>()] <= 0 && player.Calamity().killModeCooldown == KillMode.cooldownMax + KillMode.buffMax)
{
Projectile.NewProjectile(player.GetSource_FromThis(), player.MountedCenter, Vector2.Zero, ModContent.ProjectileType<ExaltedOathbladeHoldout>(), Item.damage * 14, Item.knockBack, player.whoAmI, 0, throwCount); //This used to be 23x damage.
Projectile.NewProjectile(player.GetSource_FromThis(), player.MountedCenter, Vector2.Zero, ModContent.ProjectileType<ExaltedOathbladeHoldout>(), Item.damage * 16, Item.knockBack, player.whoAmI, 0, throwCount);
}
}
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
+1 -1
View File
@@ -72,7 +72,7 @@ namespace CalamityMod.Items.Weapons.Melee
}
if (player.Calamity().demonSwordKillMode && player.ownedProjectileCounts[ModContent.ProjectileType<ForbiddenOathbladeHoldout>()] <= 0 && player.Calamity().killModeCooldown == KillMode.cooldownMax + KillMode.buffMax)
{
Projectile blade = Projectile.NewProjectileDirect(player.GetSource_FromThis(), player.MountedCenter,Vector2.Zero, ModContent.ProjectileType<ForbiddenOathbladeHoldout>(), Item.damage * 10, Item.knockBack, player.whoAmI, 0, throwCount); // This used to be 12x damage.
Projectile blade = Projectile.NewProjectileDirect(player.GetSource_FromThis(), player.MountedCenter,Vector2.Zero, ModContent.ProjectileType<ForbiddenOathbladeHoldout>(), Item.damage * 12, Item.knockBack, player.whoAmI, 0, throwCount);
}
}
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
+5 -2
View File
@@ -75,7 +75,8 @@ namespace CalamityMod.Items.Weapons.Melee
if (time == 0 && Item.velocity.Y != 0)
{
oldVel = Item.velocity;
Item.velocity = new Vector2(Math.Sign(Item.velocity.X) * 20, -10);
if (!hitFloor)
Item.velocity = new Vector2(Math.Sign(Item.velocity.X) * 20, -10);
}
if (oldVel.Y != 0 && Item.velocity.Y == 0)
{
@@ -87,6 +88,7 @@ namespace CalamityMod.Items.Weapons.Melee
float blastSize = 150 * power;
float minMultiplier = 0.3f;
int hitsToMinMult = 8;
hitFloor = true;
Projectile blast = Projectile.NewProjectileDirect(Item.GetSource_FromThis(), place, Vector2.Zero, ModContent.ProjectileType<BasicBurst>(), (int)(Item.damage * 2 * power), -35 * power, -1, blastSize, minMultiplier, hitsToMinMult);
blast.timeLeft = 5;
@@ -123,7 +125,8 @@ namespace CalamityMod.Items.Weapons.Melee
highestSpeed = Item.velocity.Y;
}
gravity = 0;
if (Item.velocity.Y != 0)
gravity = 0;
maxFallSpeed = 75;
oldVel = Item.velocity;
}
+14 -7
View File
@@ -23,6 +23,7 @@ namespace CalamityMod.Items.Weapons.Melee
public bool canHit => (completion >= 0.35f && completion <= 0.8f);
public int swingCount = 0;
public bool spawnProj = true;
public bool spawnTrueMeleeProj = true;
public bool playSound = true;
public Color clr = Color.MediumOrchid;
@@ -70,6 +71,7 @@ namespace CalamityMod.Items.Weapons.Melee
bladeHitboxPos = player.Center;
bladeRotation = 0;
spawnProj = true;
spawnTrueMeleeProj = true;
playSound = true;
int dir = -Math.Sign(player.Center.X - player.Calamity().mouseWorld.X);
float startRot = MathHelper.ToRadians(-90) * dir * (swingCount % 2 == 0 ? 1 : -1);
@@ -106,7 +108,8 @@ namespace CalamityMod.Items.Weapons.Melee
}
if (completion >= 0.65f && spawnProj)
{
Projectile.NewProjectile(player.GetSource_FromThis(), player.Center, shootDir, Item.shoot, Item.damage, Item.knockBack, player.whoAmI, 0f);
if (!player.Calamity().bladeArmEnchant) // Manually remove projectiles when Tainted
Projectile.NewProjectile(player.GetSource_FromThis(), player.Center, shootDir, Item.shoot, Item.damage, Item.knockBack, player.whoAmI, 0f);
Particle swipe = new CustomSpark(player.Center - shootDir * 5, shootDir.RotatedBy(0.4f * (dir * (swingCount % 2 == 0 ? 1 : -1))) * 2.5f, "CalamityMod/Particles/VerticalSmearLarge", false, (int)(14 / player.GetAttackSpeed(DamageClass.Melee)), 0.6f, clr, new Vector2(1f, 1f), true, false, 0, false, false);
GeneralParticleHandler.SpawnParticle(swipe);
@@ -132,13 +135,17 @@ namespace CalamityMod.Items.Weapons.Melee
}
public override void OnHitNPC(Player player, NPC target, NPC.HitInfo hit, int damageDone)
{
int beamDamage = player.CalcIntDamage<MeleeDamageClass>(Item.damage * 0.4f);
Vector2 mouseClamped = player.ClampedMouseWorld();
SoundEngine.PlaySound(SoundID.Item84 with { Volume = 1f, Pitch = Main.rand.NextFloat(0.5f, 0.7f) }, player.Center);
for (int i = 0; i < 2; i++)
if (spawnTrueMeleeProj)
{
Vector2 vel = player.Center.DirectionFrom(target.Center).RotatedByRandom(0.7f) * Main.rand.NextFloat(18, 20);
Projectile.NewProjectile(player.GetSource_ItemUse(Item), player.Center, vel, ModContent.ProjectileType<StarofJudgement>(), beamDamage, 0, player.whoAmI, 0, (i == 0 ? -1 : 1), 1);
int beamDamage = player.CalcIntDamage<MeleeDamageClass>(Item.damage * 0.35f);
Vector2 mouseClamped = player.ClampedMouseWorld();
SoundEngine.PlaySound(SoundID.Item84 with { Volume = 1f, Pitch = Main.rand.NextFloat(0.5f, 0.7f) }, player.Center);
for (int i = 0; i < 2; i++)
{
Vector2 vel = player.Center.DirectionFrom(target.Center).RotatedByRandom(0.7f) * Main.rand.NextFloat(18, 20);
Projectile.NewProjectile(player.GetSource_ItemUse(Item), player.Center, vel, ModContent.ProjectileType<StarofJudgement>(), beamDamage, 0, player.whoAmI, 0, (i == 0 ? -1 : 1), 1);
}
spawnTrueMeleeProj = false;
}
}
public override void PostDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, float rotation, float scale, int whoAmI)
+1 -1
View File
@@ -19,7 +19,7 @@ namespace CalamityMod.Items.Weapons.Melee
{
Item.width = 114;
Item.height = 146;
Item.damage = 3140;
Item.damage = 2900;
Item.DamageType = TrueMeleeDamageClass.Instance;
Item.useAnimation = 45;
Item.useStyle = ItemUseStyleID.Swing;
+1 -1
View File
@@ -21,7 +21,7 @@ namespace CalamityMod.Items.Weapons.Melee
Item.width = 54;
Item.height = 54;
Item.useStyle = ItemUseStyleID.Shoot;
Item.damage = 170;
Item.damage = 150;
Item.DamageType = DamageClass.Melee;
Item.useAnimation = Item.useTime = 34;
Item.shootSpeed = 10f;
+1 -1
View File
@@ -14,7 +14,7 @@ namespace CalamityMod.Items.Weapons.Melee
{
Item.width = 18;
Item.height = 20;
Item.damage = 9;
Item.damage = 8;
Item.DamageType = DamageClass.MeleeNoSpeed;
Item.noMelee = true;
Item.noUseGraphic = true;
+27 -18
View File
@@ -29,11 +29,12 @@ namespace CalamityMod.Items.Weapons.Melee
public bool canHit => (completion >= 0.35f && completion <= 0.8f);
public int swingCount = 0;
public bool spawnProj = true;
public bool spawnTrueMeleeProj = true;
public bool playSound = true;
public override void SetDefaults()
{
Item.width = Item.height = 112;
Item.damage = 840;
Item.damage = 800;
Item.DamageType = DamageClass.Melee;
Item.useAnimation = Item.useTime = 16;
Item.useStyle = ItemUseStyleID.Swing;
@@ -72,6 +73,7 @@ namespace CalamityMod.Items.Weapons.Melee
bladeHitboxPos = player.Center;
bladeRotation = 0;
spawnProj = true;
spawnTrueMeleeProj = true;
playSound = true;
int dir = -Math.Sign(player.Center.X - player.Calamity().mouseWorld.X);
float startRot = MathHelper.ToRadians(-90) * dir * (swingCount % 2 == 0 ? 1 : -1);
@@ -106,13 +108,16 @@ namespace CalamityMod.Items.Weapons.Melee
}
if (completion >= 0.65f && spawnProj)
{
Projectile.NewProjectile(player.GetSource_FromThis(), player.Center, shootDir, Item.shoot, Item.damage, Item.knockBack, player.whoAmI, 0f);
for (int i = 0; i < 4; i++)
if (!player.Calamity().bladeArmEnchant) // Manually remove projectiles when Tainted
{
float rot = Main.rand.NextFloat(0.5f, 0.65f) * (Main.rand.NextBool() ? 1 : -1);
Vector2 vel = (shootDir * 2.5f).RotatedByRandom(0.6f);
Projectile.NewProjectile(player.GetSource_FromThis(), player.ClampedMouseWorld() - (shootDir * 40) + Main.rand.NextVector2Circular(130, 130), vel.RotatedBy(rot) * Main.rand.NextFloat(0.9f, 1.2f), ModContent.ProjectileType<StarofOrder>(), (int)(Item.damage * 0.12f), (int)(Item.knockBack * 0.2f), player.whoAmI, 0, rot, 1);
Projectile.NewProjectile(player.GetSource_FromThis(), player.Center, shootDir, Item.shoot, Item.damage, Item.knockBack, player.whoAmI, 0f);
for (int i = 0; i < 4; i++)
{
float rot = Main.rand.NextFloat(0.5f, 0.65f) * (Main.rand.NextBool() ? 1 : -1);
Vector2 vel = (shootDir * 2.5f).RotatedByRandom(0.6f);
Projectile.NewProjectile(player.GetSource_FromThis(), player.ClampedMouseWorld() - (shootDir * 40) + Main.rand.NextVector2Circular(130, 130), vel.RotatedBy(rot) * Main.rand.NextFloat(0.9f, 1.2f), ModContent.ProjectileType<StarofOrder>(), (int)(Item.damage * 0.12f), (int)(Item.knockBack * 0.2f), player.whoAmI, 0, rot, 1);
}
}
Particle swipe = new CustomSpark(player.Center - shootDir * 5, shootDir.RotatedBy(0.4f * (dir * (swingCount % 2 == 0 ? 1 : -1))) * 2.5f, "CalamityMod/Particles/VerticalSmearLarge", false, (int)(14 / player.GetAttackSpeed(DamageClass.Melee)), 0.8f, player.Calamity().lightRGB, new Vector2(1f, 1f), true, false, 0, false, false);
@@ -140,19 +145,23 @@ namespace CalamityMod.Items.Weapons.Melee
}
public override void OnHitNPC(Player player, NPC target, NPC.HitInfo hit, int damageDone)
{
int beamDamage = player.CalcIntDamage<MeleeDamageClass>(Item.damage * 0.4f);
Vector2 mouseClamped = player.ClampedMouseWorld();
SoundEngine.PlaySound(SoundID.Item84 with { Volume = 1f, Pitch = Main.rand.NextFloat(0.5f, 0.7f)}, player.Center);
for (int i = 0; i < 2; i++)
if (spawnTrueMeleeProj)
{
Vector2 targetPos = Main.MouseWorld;
NPC target2 = Main.MouseWorld.ClosestNPCAt(650);
if (target2 != null)
targetPos = target2.Center;
int beamDamage = player.CalcIntDamage<MeleeDamageClass>(Item.damage * 0.35f);
Vector2 mouseClamped = player.ClampedMouseWorld();
SoundEngine.PlaySound(SoundID.Item84 with { Volume = 1f, Pitch = Main.rand.NextFloat(0.5f, 0.7f) }, player.Center);
for (int i = 0; i < 2; i++)
{
Vector2 targetPos = Main.MouseWorld;
NPC target2 = Main.MouseWorld.ClosestNPCAt(650);
if (target2 != null)
targetPos = target2.Center;
Vector2 spawnPos = mouseClamped + new Vector2(Main.rand.NextFloat(-300, 300), -900);
Vector2 vel = (targetPos - spawnPos).SafeNormalize(Vector2.UnitY) * 10;
Projectile.NewProjectile(player.GetSource_ItemUse(Item), spawnPos, vel, ModContent.ProjectileType<OrderbringerBeam>(), beamDamage, 0, player.whoAmI);
Vector2 spawnPos = mouseClamped + new Vector2(Main.rand.NextFloat(-300, 300), -900);
Vector2 vel = (targetPos - spawnPos).SafeNormalize(Vector2.UnitY) * 10;
Projectile.NewProjectile(player.GetSource_ItemUse(Item), spawnPos, vel, ModContent.ProjectileType<OrderbringerBeam>(), beamDamage, 0, player.whoAmI);
}
spawnTrueMeleeProj = false;
}
}
public override void ModifyTooltips(List<TooltipLine> list)
+3
View File
@@ -6,6 +6,7 @@ using Microsoft.Xna.Framework;
using Terraria;
using Terraria.Audio;
using Terraria.DataStructures;
using Terraria.GameContent.Prefixes;
using Terraria.ID;
using Terraria.ModLoader;
@@ -44,6 +45,8 @@ namespace CalamityMod.Items.Weapons.Melee
Item.value = CalamityGlobalItem.RarityVioletBuyPrice;
Item.rare = ModContent.RarityType<BurnishedAuric>();
}
public override bool RangedPrefix() => true; //class identity is fake
public override bool MeleePrefix() => false;
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
+3 -3
View File
@@ -12,8 +12,8 @@ namespace CalamityMod.Items.Weapons.Melee
public class TheOracle : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Weapons.Melee";
public const int AuraBaseDamage = 68;
public const int AuraMaxDamage = 150;
public const float AuraBaseDamageMult = 0.35f;
public const float AuraMaxDamageMult = 0.8f;
public static float Reach = 800f;
public static float Speed = 60f;
@@ -31,7 +31,7 @@ namespace CalamityMod.Items.Weapons.Melee
Item.width = 58;
Item.height = 50;
Item.DamageType = DamageClass.MeleeNoSpeed;
Item.damage = 192;
Item.damage = 201;
Item.knockBack = 4f;
Item.useTime = 20;
Item.useAnimation = 20;
+1 -1
View File
@@ -25,7 +25,7 @@ namespace CalamityMod.Items.Weapons.Ranged
{
Item.width = 56;
Item.height = 28;
Item.damage = 17;
Item.damage = 15;
Item.DamageType = DamageClass.Ranged;
Item.useTime = Item.useAnimation = 11;
Item.knockBack = 1.5f;
+3 -3
View File
@@ -40,9 +40,9 @@ namespace CalamityMod.Items.Weapons.Ranged
{
SoundEngine.PlaySound(SoundID.Item38, player.Center);
// Really jammed in GFB
if (Main.zenithWorld)
return Main.rand.NextBool(5);
// Really jammed in GFB (only fires 20% of the time)
if (Main.zenithWorld && Main.rand.Next(5) < 4)
return false;
int bulletAmt = Main.rand.Next(25, 36);
for (int index = 0; index < bulletAmt; ++index)
+6 -3
View File
@@ -20,13 +20,13 @@ namespace CalamityMod.Items.Weapons.Ranged
public static readonly SoundStyle ShootSound = new("CalamityMod/Sounds/Item/HalleysInfernoShoot") { Volume = 0.68f };
public static readonly SoundStyle Hit = new("CalamityMod/Sounds/Item/HalleysInfernoHit") { Volume = 0.75f };
public static float MaxStarburstPerComet => 1;
public static float MaxStarburstPerStar => 0.25f;
public static float MaxStarburstPerStar => 0.5f;
public static float LostAccuracyPerMiss => 4;
public static float MaxAccuracy => 50;
public static float StarburstDmgMult => 1.25f;
public static float StarburstDmgMult => 2.5f;
public static float StarburstVelMult = 0.75f;
public static float StarburstVelMult => 0.75f;
public override void SetDefaults()
{
Item.width = 84;
@@ -62,6 +62,9 @@ namespace CalamityMod.Items.Weapons.Ranged
public override void ModifyWeaponCrit(Player player, ref float crit) => crit += 20;
public override void HoldItem(Player player)
{
if (player.mount.Type == MountID.Drill)
return;
if (Main.LocalPlayer == player)
{
if (!Main.projectile.Any(x=> x.active && x.owner == player.whoAmI && x.type == Item.shoot))
+1 -1
View File
@@ -31,7 +31,7 @@ namespace CalamityMod.Items.Weapons.Ranged
Item.useAmmo = AmmoID.Bullet;
Item.noUseGraphic = true;
Item.value = CalamityGlobalItem.RarityOrangeBuyPrice;
Item.value = Item.buyPrice(gold: 20); // Sold by Arms Dealer
Item.rare = ItemRarityID.Orange;
}
+1 -1
View File
@@ -25,7 +25,7 @@ namespace CalamityMod.Items.Weapons.Ranged
{
Item.width = 66;
Item.height = 26;
Item.damage = 82;
Item.damage = 85;
Item.DamageType = DamageClass.Ranged;
Item.useTime = Item.useAnimation = 11;
Item.knockBack = 1.5f;
+1 -1
View File
@@ -13,7 +13,7 @@ namespace CalamityMod.Items.Weapons.Rogue
{
Item.width = 109;
Item.height = 128;
Item.damage = 192;
Item.damage = 222;
Item.noMelee = true;
Item.noUseGraphic = true;
// Due to the amazing sound engine, having multiple crosses embedded in enemies cuts off the sound
+6 -6
View File
@@ -38,7 +38,7 @@ namespace CalamityMod.Items.Weapons.Rogue
{
if (player.Calamity().StealthStrikeAvailable())
{
player.Calamity().amputatorBuff = 30;
player.Calamity().focusFlurryAttackCount = 30;
player.Calamity().ConsumeStealthByAttacking();
SoundStyle buff = new("CalamityMod/Sounds/Custom/ProfanedGuardians/GuardianRay");
SoundEngine.PlaySound(buff with { Volume = 1f, Pitch = Main.rand.NextFloat(0.2f, 0.3f) }, player.Center);
@@ -67,24 +67,24 @@ namespace CalamityMod.Items.Weapons.Rogue
}
public override float UseSpeedMultiplier(Player player)
{
return (player.Calamity().amputatorBuff > 0 ? 3f : 1);
return (player.Calamity().focusFlurryAttackCount > 0 ? 3f : 1);
}
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
bool fastToss = player.Calamity().amputatorBuff > 0;
bool fastToss = player.Calamity().focusFlurryAttackCount > 0;
SoundStyle fire = new("CalamityMod/Sounds/Item/SpearofDestiny");
SoundEngine.PlaySound(fire with { Volume = 0.5f, Pitch = (player.Calamity().amputatorBuff > 0 ? -0.4f + (player.Calamity().amputatorBuff * 0.02f) : Main.rand.NextFloat(-0.4f, -0.65f)) }, position);
SoundEngine.PlaySound(fire with { Volume = 0.5f, Pitch = (player.Calamity().focusFlurryAttackCount > 0 ? -0.4f + (player.Calamity().focusFlurryAttackCount * 0.02f) : Main.rand.NextFloat(-0.4f, -0.65f)) }, position);
// Since the positioning of the scythe is important, its velocity is based on your mouse position
Vector2 staticSpeed = Utils.DirectionTo(position, position + velocity) * Utils.Distance(position, player.ClampedMouseWorld()) * 0.022f;
// "fast toss" is the stealth, if you need to change stealth values, change those
int fastTossDamage = (int)(damage * 0.65f);
Projectile scythe = Projectile.NewProjectileDirect(source, position, staticSpeed.RotatedByRandom((player.Calamity().amputatorBuff > 0 ? 0.7f : 0)), type, fastToss ? fastTossDamage : damage, knockback, player.whoAmI, 0, 0, 0);
Projectile scythe = Projectile.NewProjectileDirect(source, position, staticSpeed.RotatedByRandom((player.Calamity().focusFlurryAttackCount > 0 ? 0.7f : 0)), type, fastToss ? fastTossDamage : damage, knockback, player.whoAmI, 0, 0, 0);
if (fastToss)
{
scythe.extraUpdates = 6;
scythe.Calamity().stealthStrike = true;
player.Calamity().amputatorBuff--;
player.Calamity().focusFlurryAttackCount--;
}
player.Calamity().ConsumeStealthByAttacking();
+116 -10
View File
@@ -1,19 +1,37 @@
using CalamityMod.Items.Materials;
using CalamityMod.CalPlayer;
using CalamityMod.Items.Materials;
using CalamityMod.Particles;
using CalamityMod.Projectiles.Rogue;
using CalamityMod.Rarities;
using CalamityMod.Tiles.Furniture.CraftingStations;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.Audio;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Weapons.Rogue
{
// Deny me no longer!
// Bleak, directionless slaughter.
// A celebration of the vices that brought Her to this point.
[LegacyName("NanoblackReaperMelee", "NanoblackReaperRogue")]
public class NanoblackReaper : RogueWeapon, IHoldShiftTooltipItem
{
// Right triangles, and like triangles.
internal const float PiOver3 = MathHelper.Pi / 3f;
internal const float TwoPiOver3 = MathHelper.TwoPi / 3f;
internal static readonly Color NanoblackSlashColor1 = new Color(47, 248, 211); // #2FF8D4
internal static readonly Color NanoblackSlashColor2 = new Color(15, 15, 15); // #0F0F0F
internal static readonly Color NanoblackDustColor1 = new Color(52, 239, 184); // #34EFB8
internal static readonly Color TesselationParticleColor = new Color(79, 240, 168); // 4FF0A8
internal static readonly Color ZeroPointLineColor = new Color(24, 191, 160); // #1FBFA0
internal static readonly Color ZeroPointImpactColor = new Color(31, 223, 128, 96); // #1FDF80
internal static readonly Color PiercingStrikeColor = new Color(36, 252, 212); // #24FCD4
internal static readonly Color LightspeedCarveColor1 = new Color(68, 242, 242); // #44F2F2
internal static readonly Color LightspeedCarveColor2 = new Color(66, 219, 173); // #42DBAD
public bool ShowExtensionIndicator => false;
public bool HasFlavorTooltip => true;
public Color? TooltipExtensionColor => new Color(31, 223, 128); // #1FDF80
@@ -22,14 +40,28 @@ namespace CalamityMod.Items.Weapons.Rogue
public static float Knockback = 9f;
public static float Speed = 16f;
public static int FocusFlurryAttacks = 12;
public static int PerfectLightspeedCarveFrames = 4;
public static int ImperfectLightspeedCarveFrames = 8; // This frame window is immediately after the perfect window.
public static float LightspeedCarveKnockback = 7f;
public static int ArmorPenetration = 30;
// Armor pen declared on projectiles will be added to that of the parent projectile or, failing that, item that spawned it.
public static int ZeroPointArmorPenetration = 120; // Total: 150.
public static int LightspeedCarveArmorPenetration = 120; // Total: 150.
public static float TesselationDamageRatio = 0.25f;
public static float TesselationKnockback = 1.5f;
public override float StealthDamageMultiplier => 1.0f;
public override void SetDefaults()
{
Item.width = 78;
Item.height = 64;
Item.damage = 130;
Item.damage = 315;
Item.knockBack = Knockback;
Item.useTime = 6;
Item.useAnimation = 6;
Item.ArmorPenetration = ArmorPenetration;
Item.useTime = Item.useAnimation = 19;
Item.autoReuse = true;
Item.noMelee = true;
Item.noUseGraphic = true;
@@ -46,23 +78,97 @@ namespace CalamityMod.Items.Weapons.Rogue
Item.shootSpeed = Speed;
}
public override void HoldItem(Player player)
{
CalamityPlayer modPlayer = player.Calamity();
modPlayer.mouseWorldListener = true;
// Safeguard because focus flurries are currently cross-weapon.
if (modPlayer.focusFlurryAttackCount > FocusFlurryAttacks)
modPlayer.focusFlurryAttackCount = FocusFlurryAttacks;
// Remainder of behavior should only be called on owning client
if (player.whoAmI != Main.myPlayer)
return;
// Right click behavior: activate Focus Flurry as applicable
if (modPlayer.mouseRight && modPlayer.StealthStrikeAvailable())
{
// "Stealth strikes" with Nanoblack Reaper are Focus Flurries: the next 30 attacks come out very, very quickly.
modPlayer.ConsumeStealthByAttacking();
modPlayer.focusFlurryAttackCount = FocusFlurryAttacks;
SoundStyle flurryActivationSound1 = new("CalamityMod/Sounds/Item/StygianDash");
SoundStyle flurryActivationSound2 = new("CalamityMod/Sounds/Item/HeliumFlashCoreImpact");
float sound2Pitch = Main.rand.NextFloat(0.08f, 0.2f);
SoundEngine.PlaySound(flurryActivationSound1 with { Volume = 1f }, player.Center);
SoundEngine.PlaySound(flurryActivationSound2 with { Volume = 0.3f, Pitch = sound2Pitch }, player.Center);
// Spawn a dramatic void slash particle over the player when this is activated
{
Color color = NanoblackSlashColor1;
float scale = 0.33f;
Vector2 slashDir = (Main.rand.NextBool() ? -1f : 1f) * Vector2.UnitX;
Vector2 vel = 0.01f * slashDir.RotatedByRandom(MathHelper.Pi / 8f);
// scale of void sparks is arbitrarily multiplied by 0.357f. thanks!
float voidScale = scale / 0.357f;
Particle blackSpark = new VoidSparkParticle(player.Center, vel, false, 12, voidScale, color, 1f);
GeneralParticleHandler.SpawnParticle(blackSpark);
float glowScale = scale * 0.333f;
Vector2 squashStretch = new(1.3333f, 0.8f);
Particle innerSpark = new GlowSparkParticle(player.Center, vel, false, 11, glowScale, color, squashStretch, true, true, 1f);
GeneralParticleHandler.SpawnParticle(innerSpark);
}
}
// Negative-edge left click behavior: attempt light-speed carves
// This will evaluate to true for exactly one frame when the player lets go of the left mouse button.
bool leftMouseJustReleased = Main.mouseLeft && Main.mouseLeftRelease;
if (leftMouseJustReleased)
{
int scytheID = ModContent.ProjectileType<NanoblackMain>();
for (int i = 0; i < Main.maxProjectiles; ++i)
{
Projectile p = Main.projectile[i];
if (!p.active || p.type != scytheID || p.owner != player.whoAmI)
continue;
NanoblackMain nr = p.ModProjectile as NanoblackMain;
nr.AttemptLightspeedCarve();
}
}
}
// Nanoblack Reaper's attack speed triples (similar to its classic speed) during a Focus Flurry.
public override float UseSpeedMultiplier(Player player) => player.Calamity().focusFlurryAttackCount > 0 ? 3f : 1f;
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
if (player.Calamity().StealthStrikeAvailable())
// Focus flurries produce a different sound and set the stealth strike flag to change behavior.
CalamityPlayer modPlayer = player.Calamity();
bool focusFlurry = modPlayer.focusFlurryAttackCount > 0;
if (focusFlurry)
{
int stealth = Projectile.NewProjectile(source, position, velocity, type, damage, knockback, player.whoAmI);
if (stealth.WithinBounds(Main.maxProjectiles))
Main.projectile[stealth].Calamity().stealthStrike = player.Calamity().StealthStrikeAvailable();
SoundStyle flurryThrowSound = new("CalamityMod/Sounds/Item/DemonSwordSwing2");
float pitch = Main.rand.NextFloat(-0.24f, -0.12f) + modPlayer.focusFlurryAttackCount * 0.01f;
SoundEngine.PlaySound(flurryThrowSound with { Volume = 0.2f, Pitch = pitch, MaxInstances = 12 }, player.Center);
Projectile focusReaper = Projectile.NewProjectileDirect(source, position, velocity, type, damage, knockback, player.whoAmI);
focusReaper.Calamity().stealthStrike = true;
--modPlayer.focusFlurryAttackCount;
return false;
}
return true;
}
public override void AddRecipes()
{
CreateRecipe().
AddIngredient<GhoulishGouger>().
AddIngredient<MoltenAmputator>().
AddIngredient<GhoulishGouger>().
AddIngredient<ShadowspecBar>(5).
AddIngredient<EndothermicEnergy>(40).
AddIngredient<PlagueCellCanister>(20).
+1 -1
View File
@@ -14,7 +14,7 @@ namespace CalamityMod.Items.Weapons.Rogue
{
Item.width = 30;
Item.height = 30;
Item.damage = 20;
Item.damage = 16;
Item.noMelee = true;
Item.noUseGraphic = true;
Item.useAnimation = 16;
-1
View File
@@ -43,7 +43,6 @@ namespace CalamityMod.Items.Weapons.Rogue
}
return true;
}
public override void ModifyTooltips(List<TooltipLine> list) => list.FindAndReplace("[GFB]", this.GetLocalizedValue(Main.zenithWorld ? "TooltipGFB" : "TooltipNormal"));
public override void AddRecipes()
{
+3 -4
View File
@@ -15,12 +15,11 @@ namespace CalamityMod.Items.Weapons.Rogue
{
Item.width = 48;
Item.height = 48;
Item.damage = 144;
Item.damage = 111;
Item.noMelee = true;
Item.noUseGraphic = true;
Item.useAnimation = 17;
Item.useTime = Item.useAnimation = 17;
Item.useStyle = ItemUseStyleID.Swing;
Item.useTime = 17;
Item.knockBack = 8f;
Item.UseSound = SoundID.Item1;
Item.autoReuse = true;
@@ -31,7 +30,7 @@ namespace CalamityMod.Items.Weapons.Rogue
Item.DamageType = RogueDamageClass.Instance;
}
public override float StealthDamageMultiplier => 0.65f;
public override float StealthDamageMultiplier => 0.7f;
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
+1 -1
View File
@@ -14,7 +14,7 @@ namespace CalamityMod.Items.Weapons.Rogue
{
Item.width = 30;
Item.height = 30;
Item.damage = 20;
Item.damage = 16;
Item.noMelee = true;
Item.noUseGraphic = true;
Item.useAnimation = 16;
+1 -1
View File
@@ -23,7 +23,7 @@ namespace CalamityMod.Items.Weapons.Summon
Item.UseSound = SoundID.DD2_DarkMageHealImpact;
Item.DamageType = DamageClass.Summon;
Item.mana = 10;
Item.damage = 43;
Item.damage = 35;
Item.knockBack = 2f;
Item.autoReuse = true;
Item.useAnimation = Item.useTime = 24;
+3 -3
View File
@@ -14,8 +14,8 @@ namespace CalamityMod.Items.Weapons.Summon
{
public class IgneousExaltation : ModItem, ILocalizedModType
{
public static int ChargeDuration = 30;
public static int ChargeCooldown = 120;
public static int ChargeDuration => 25;
public static int ChargeCooldown => 120;
public new string LocalizationCategory => "Items.Weapons.Summon";
private static Texture2D BladeOutline = null;
public static Texture2D GetBladeOutlineTex()
@@ -45,7 +45,7 @@ namespace CalamityMod.Items.Weapons.Summon
{
Item.width = 52;
Item.height = 50;
Item.damage = 34;
Item.damage = 30;
Item.mana = 10;
Item.useAnimation = Item.useTime = 36;
Item.useStyle = ItemUseStyleID.Shoot;
+1 -1
View File
@@ -20,7 +20,7 @@ namespace CalamityMod.Items.Weapons.Summon
{
Item.width = 66;
Item.height = 68;
Item.damage = 128;
Item.damage = 100;
Item.DamageType = DamageClass.Summon;
Item.sentry = true;
Item.mana = 100;
+1 -1
View File
@@ -20,7 +20,7 @@ namespace CalamityMod.Items.Weapons.Summon
public override void SetDefaults()
{
Item.width = Item.height = 62;
Item.damage = 150;
Item.damage = 90;
Item.useAnimation = Item.useTime = 24;
Item.mana = 10;
Item.knockBack = 10f;
Loaded 100 of 276 files, more files were not shown because too many files have changed in this diff. Show more