Sylvestaff

This commit is contained in:
GinYuH committed 2025-05-28 18:48:13 -07:00
1 parent 5ea29ad93a
commit 275fccfede
54 files changed
+1524 -351

No files matched your search

+16 -4
View File
@@ -19,9 +19,9 @@ namespace CalamityMod.Effects
internal static Effect AstralFogShader;
//
// All below shaders created by Dominic Karma
// All below shaders created by Lucille Karma
//
#region Dominic's Shaders
#region Lucille's Shaders
// The Dance of Light's Blinding Light
internal static Effect DanceOfLightBlindingShader;
@@ -92,7 +92,7 @@ namespace CalamityMod.Effects
// Was previously used by Dom's Bladecrest Oathsword. Appears to govern the swing animation.
internal static Effect LocalLinearTransformationShader;
// UNUSED -- Probably leftover from Dominic's experiments with applying shaders to primitives (arbitrary GPU-rendered triangles)
// UNUSED -- Probably leftover from Lucille's experiments with applying shaders to primitives (arbitrary GPU-rendered triangles)
internal static Effect BasicPrimitiveShader;
// Artemis Ohio Beam. Also used by get fixed boi Nuclear Terror's "G-FUEL BEAM"
@@ -145,6 +145,12 @@ namespace CalamityMod.Effects
// Used to render the results of Navier-Stokes fluid simulations.
internal static Effect FluidShaders;
// Used by projectiles fired by the Sylvestaff.
internal static Effect SylvestaffProjectileShader;
// Used by the ribbons on the Sylvestaff.
internal static Effect SylvestaffRibbonShader;
#endregion
//
@@ -237,7 +243,7 @@ namespace CalamityMod.Effects
var astralPassReg = new AstralScreenShaderData(new Ref<Effect>(AstralFogShader), "AstralPass").UseColor(0.18f, 0.08f, 0.24f);
RegisterSceneFilter(astralPassReg, "Astral", EffectPriority.VeryHigh);
#region Loading Dominic's Shaders
#region Loading Lucille's Shaders
DanceOfLightBlindingShader = LoadShader("LightBurstShader");
RegisterScreenShader(DanceOfLightBlindingShader, "BurstPass", "LightBurst");
@@ -360,6 +366,12 @@ namespace CalamityMod.Effects
// This shader is not registered with the game but is invoked directly to render the results of fluid simulation.
FluidShaders = LoadShader("FluidShaders");
SylvestaffProjectileShader = LoadShader("SylvestaffProjectileShader");
RegisterMiscShader(SylvestaffProjectileShader, "TrailPass", "SylvestaffProjectile");
SylvestaffRibbonShader = LoadShader("SylvestaffRibbonShader");
RegisterMiscShader(SylvestaffRibbonShader, "AutoloadPass", "SylvestaffRibbon");
#endregion
#region Loading Iban's Shaders
+76
View File
@@ -0,0 +1,76 @@
sampler uImage0 : register(s0);
sampler uImage1 : register(s1);
float3 uColor;
float3 uSecondaryColor;
float uOpacity;
float uSaturation;
float uRotation;
float uTime;
float4 uSourceRect;
float2 uWorldPosition;
float uDirection;
float3 uLightSource;
float2 uImageSize0;
float2 uImageSize1;
matrix uWorldViewProjection;
float4 uShaderSpecificData;
struct VertexShaderInput
{
float4 Position : POSITION0;
float4 Color : COLOR0;
float3 TextureCoordinates : TEXCOORD0;
};
struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
float3 TextureCoordinates : TEXCOORD0;
};
VertexShaderOutput VertexShaderFunction(in VertexShaderInput input)
{
VertexShaderOutput output = (VertexShaderOutput) 0;
float4 pos = mul(input.Position, uWorldViewProjection);
output.Position = pos;
output.Color = input.Color;
output.TextureCoordinates = input.TextureCoordinates;
return output;
}
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
float4 color = input.Color;
float2 coords = input.TextureCoordinates;
// Account for texture distortion artifacts.
coords.y = (coords.y - 0.5) / input.TextureCoordinates.z + 0.5;
float bump = sin(coords.y * 3.141);
// Calculate the amount of additive glow for this pixel, using a combination of a scrolling texture and an extreme
// exponential squash of the prior 0-1-0 bump, creating a "center" to the glow and ensuring that the
// ray doesn't look like just a scrolling gradient.
float streakColor = tex2D(uImage1, coords + float2(uTime * -2.75, 0));
float glow = streakColor.r + pow(bump, 20) * 0.4;
// Determine opacity based on a weaker exponential squash of the bump in order to create faded horizontal edges.
float opacity = pow(bump, 5);
// Apply glow.
opacity += glow * opacity;
return color * opacity;
}
technique Technique1
{
pass TrailPass
{
VertexShader = compile vs_2_0 VertexShaderFunction();
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}
Binary file not shown.
+89
View File
@@ -0,0 +1,89 @@
sampler noiseTextureA : register(s1);
float pixelationFactor;
float uSaturation;
float4 uShaderSpecificData;
matrix uWorldViewProjection;
struct VertexShaderInput
{
float4 Position : POSITION0;
float4 Color : COLOR0;
float3 TextureCoordinates : TEXCOORD0;
};
struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
float3 TextureCoordinates : TEXCOORD0;
};
VertexShaderOutput VertexShaderFunction(in VertexShaderInput input)
{
VertexShaderOutput output = (VertexShaderOutput) 0;
float4 pos = mul(input.Position, uWorldViewProjection);
output.Position = pos;
output.Color = input.Color;
output.TextureCoordinates = input.TextureCoordinates;
return output;
}
float QuadraticBump(float x)
{
return x * (4 - x * 4);
}
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
float4 color = 1;
float2 coords = input.TextureCoordinates;
coords.y = (coords.y - 0.5) / input.TextureCoordinates.z + 0.5;
float feelerColorStart = 0.61;
float colorSpacingFactor = 1.9;
float4 outlineColor = float4(91, 114, 119, 255) / 255;
float erasePixelInterpolant = coords.x - 0.9 - distance(coords.y, 0.5) * 0.1;
// Band 1: Outline color.
color = lerp(color, outlineColor, coords.x >= feelerColorStart);
// Band 2: Pink.
float pinkStart = feelerColorStart + colorSpacingFactor * 0.01;
color = lerp(color, float4(221, 150, 179, 255) / 255, coords.x >= pinkStart);
// Band 3: Outline color.
float outlineAStart = pinkStart + colorSpacingFactor * 0.04;
color = lerp(color, outlineColor, coords.x >= outlineAStart);
// Band 4: Blue.
float blueStart = outlineAStart + colorSpacingFactor * 0.01;
color = lerp(color, float4(48, 117, 222, 255) / 255, coords.x >= blueStart);
// Band 5: Baby blue.
float babyBlueStart = blueStart + colorSpacingFactor * 0.04;
color = lerp(color, float4(167, 222, 255, 255) / 255, coords.x >= babyBlueStart);
// Add an outline to the ends of the feeler.
float horizontalDistanceFromCenter = distance(coords.y, 0.5);
color = lerp(color, outlineColor, horizontalDistanceFromCenter >= 0.3);
color = lerp(color, outlineColor, erasePixelInterpolant >= -0.02);
float permittedDirection = sign(uSaturation);
float direction = sign(dot(input.Position.xy - uShaderSpecificData.xy, uShaderSpecificData.zw));
erasePixelInterpolant *= direction == permittedDirection || coords.x < 0.5;
return color * (erasePixelInterpolant < 0) * input.Color;
}
technique Technique1
{
pass AutoloadPass
{
VertexShader = compile vs_3_0 VertexShaderFunction();
PixelShader = compile ps_3_0 PixelShaderFunction();
}
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

@@ -15,6 +15,6 @@ namespace CalamityMod.Graphics.Primitives
/// <summary>
/// Render primitives that use pixelation here.
/// </summary>
void RenderPixelatedPrimitives(SpriteBatch spriteBatch);
void RenderPixelatedPrimitives(SpriteBatch spriteBatch, PixelationPrimitiveLayer layer);
}
}
@@ -1,15 +1,17 @@
using Microsoft.Xna.Framework.Graphics;
using System;
namespace CalamityMod.Graphics.Primitives
{
/// <summary>
/// Controls what layer the <see cref="IPixelatedPrimitiveRenderer.RenderPixelatedPrimitives"/> renders to.
/// </summary>
[Flags]
public enum PixelationPrimitiveLayer
{
BeforeNPCs,
AfterNPCs,
BeforeProjectiles,
AfterProjectiles
BeforeNPCs = 1,
AfterNPCs = 2,
BeforeProjectiles = 4,
AfterProjectiles = 8,
AfterPlayers = 16
}
}
@@ -18,6 +18,8 @@ namespace CalamityMod.Graphics.Primitives
private static ManagedRenderTarget PixelationTarget_AfterProjectiles;
private static ManagedRenderTarget PixelationTarget_AfterPlayers;
private static RenderTarget2D CreatePixelTarget(int width, int height) => new(Main.instance.GraphicsDevice, width / 2, height / 2);
/// <summary>
@@ -36,11 +38,13 @@ namespace CalamityMod.Graphics.Primitives
On_Main.CheckMonoliths += DrawToTargets;
On_Main.DoDraw_DrawNPCsOverTiles += DrawTarget_NPCs;
On_Main.DrawProjectiles += DrawTarget_Projectiles;
On_Main.DrawPlayers_AfterProjectiles += DrawTarget_Players;
PixelationTarget_BeforeNPCs = new(true, CreatePixelTarget);
PixelationTarget_AfterNPCs = new(true, CreatePixelTarget);
PixelationTarget_BeforeProjectiles = new(true, CreatePixelTarget);
PixelationTarget_AfterProjectiles = new(true, CreatePixelTarget);
PixelationTarget_AfterPlayers = new(true, CreatePixelTarget);
}
public override void Unload()
@@ -63,6 +67,7 @@ namespace CalamityMod.Graphics.Primitives
var afterNPCs = new List<IPixelatedPrimitiveRenderer>();
var beforeProjectiles = new List<IPixelatedPrimitiveRenderer>();
var afterProjectiles = new List<IPixelatedPrimitiveRenderer>();
var afterPlayers = new List<IPixelatedPrimitiveRenderer>();
// Check every active projectile.
foreach (Projectile projectile in Main.ActiveProjectiles)
@@ -70,14 +75,14 @@ namespace CalamityMod.Graphics.Primitives
// If the projectile is active, a mod projectile, and uses the interface, add it to the list of primitives to draw this frame.
if (projectile.ModProjectile != null && projectile.ModProjectile is IPixelatedPrimitiveRenderer pixelPrimitiveProjectile)
{
var listToUse = pixelPrimitiveProjectile.LayerToRenderTo switch
{
PixelationPrimitiveLayer.BeforeNPCs => beforeNPCs,
PixelationPrimitiveLayer.AfterNPCs => afterNPCs,
PixelationPrimitiveLayer.BeforeProjectiles => beforeProjectiles,
_ => afterProjectiles
};
listToUse.Add(pixelPrimitiveProjectile);
if (pixelPrimitiveProjectile.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.BeforeNPCs))
beforeNPCs.Add(pixelPrimitiveProjectile);
if (pixelPrimitiveProjectile.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.AfterNPCs))
afterNPCs.Add(pixelPrimitiveProjectile);
if (pixelPrimitiveProjectile.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.BeforeProjectiles))
beforeProjectiles.Add(pixelPrimitiveProjectile);
if (pixelPrimitiveProjectile.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.AfterPlayers))
afterPlayers.Add(pixelPrimitiveProjectile);
}
}
@@ -87,23 +92,24 @@ namespace CalamityMod.Graphics.Primitives
// If the NPC is active, a mod NPC, and uses the interface, add it to the list of primitives to draw this frame.
if (npc.ModNPC != null && npc.ModNPC is IPixelatedPrimitiveRenderer pixelPrimitiveNPC)
{
var listToUse = pixelPrimitiveNPC.LayerToRenderTo switch
{
PixelationPrimitiveLayer.BeforeNPCs => beforeNPCs,
PixelationPrimitiveLayer.AfterNPCs => afterNPCs,
PixelationPrimitiveLayer.BeforeProjectiles => beforeProjectiles,
_ => afterProjectiles
};
listToUse.Add(pixelPrimitiveNPC);
if (pixelPrimitiveNPC.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.BeforeNPCs))
beforeNPCs.Add(pixelPrimitiveNPC);
if (pixelPrimitiveNPC.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.AfterNPCs))
afterNPCs.Add(pixelPrimitiveNPC);
if (pixelPrimitiveNPC.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.BeforeProjectiles))
beforeProjectiles.Add(pixelPrimitiveNPC);
if (pixelPrimitiveNPC.LayerToRenderTo.HasFlag(PixelationPrimitiveLayer.AfterPlayers))
afterPlayers.Add(pixelPrimitiveNPC);
}
}
CurrentlyRendering = true;
DrawPrimsToRenderTarget(PixelationTarget_BeforeNPCs, beforeNPCs);
DrawPrimsToRenderTarget(PixelationTarget_AfterNPCs, afterNPCs);
DrawPrimsToRenderTarget(PixelationTarget_BeforeProjectiles, beforeProjectiles);
DrawPrimsToRenderTarget(PixelationTarget_AfterProjectiles, afterProjectiles);
DrawPrimsToRenderTarget(PixelationTarget_BeforeNPCs, PixelationPrimitiveLayer.BeforeNPCs, beforeNPCs);
DrawPrimsToRenderTarget(PixelationTarget_AfterNPCs, PixelationPrimitiveLayer.AfterNPCs, afterNPCs);
DrawPrimsToRenderTarget(PixelationTarget_BeforeProjectiles, PixelationPrimitiveLayer.BeforeProjectiles, beforeProjectiles);
DrawPrimsToRenderTarget(PixelationTarget_AfterProjectiles, PixelationPrimitiveLayer.AfterProjectiles, afterProjectiles);
DrawPrimsToRenderTarget(PixelationTarget_AfterPlayers, PixelationPrimitiveLayer.AfterPlayers, afterPlayers);
Main.instance.GraphicsDevice.SetRenderTarget(null);
@@ -111,7 +117,7 @@ namespace CalamityMod.Graphics.Primitives
orig();
}
private static void DrawPrimsToRenderTarget(RenderTarget2D renderTarget, List<IPixelatedPrimitiveRenderer> pixelPrimitives)
private static void DrawPrimsToRenderTarget(RenderTarget2D renderTarget, PixelationPrimitiveLayer layer, List<IPixelatedPrimitiveRenderer> pixelPrimitives)
{
// Swap to the target regardless, in order to clear any leftover content from last frame. Not doing this results in the final frame lingering once it stops rendering.
renderTarget.SwapTo();
@@ -121,7 +127,7 @@ namespace CalamityMod.Graphics.Primitives
Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null);
foreach (var pixelPrimitiveDrawer in pixelPrimitives)
pixelPrimitiveDrawer.RenderPixelatedPrimitives(Main.spriteBatch);
pixelPrimitiveDrawer.RenderPixelatedPrimitives(Main.spriteBatch, layer);
Main.spriteBatch.End();
}
@@ -143,6 +149,12 @@ namespace CalamityMod.Graphics.Primitives
DrawTargetScaled(PixelationTarget_AfterProjectiles);
}
private void DrawTarget_Players(On_Main.orig_DrawPlayers_AfterProjectiles orig, Main self)
{
orig(self);
DrawTargetScaled(PixelationTarget_AfterPlayers);
}
private static void DrawTargetScaled(ManagedRenderTarget target)
{
Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix);
+2 -2
View File
@@ -295,8 +295,8 @@ namespace CalamityMod.Items
nameLine.OverrideColor = new Color(Main.DiscoR, Main.DiscoG, Main.DiscoB);
// Developer items
if (item.type == ModContent.ItemType<Fabstaff>())
nameLine.OverrideColor = new Color(Main.DiscoR, 100, 255);
if (item.type == ModContent.ItemType<Sylvestaff>())
nameLine.OverrideColor = new Color(249, 197, 255);
if (item.type == ModContent.ItemType<StaffofBlushie>())
nameLine.OverrideColor = new Color(0, 0, 255);
if (item.type == ModContent.ItemType<TheDanceofLight>())
-53
View File
@@ -1,53 +0,0 @@
using CalamityMod.Items.Materials;
using CalamityMod.Projectiles.Magic;
using CalamityMod.Rarities;
using CalamityMod.Tiles.Furniture.CraftingStations;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Weapons.Magic
{
public class Fabstaff : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Weapons.Magic";
public override void SetStaticDefaults()
{
Item.staff[Type] = true;
}
public override void SetDefaults()
{
Item.width = 84;
Item.height = 84;
Item.damage = 140;
Item.DamageType = DamageClass.Magic;
Item.mana = 35;
Item.useAnimation = Item.useTime = 20;
Item.useStyle = ItemUseStyleID.Shoot;
Item.noMelee = true;
Item.knockBack = 5f;
Item.value = CalamityGlobalItem.RarityHotPinkBuyPrice;
Item.rare = ModContent.RarityType<HotPink>();
Item.Calamity().devItem = true;
Item.UseSound = SoundID.Item60;
Item.autoReuse = true;
Item.shoot = ModContent.ProjectileType<FabRay>();
Item.shootSpeed = 13.5f;
}
public override void AddRecipes()
{
CreateRecipe().
AddIngredient(ItemID.RainbowRod).
AddIngredient<ShadowspecBar>(5).
AddIngredient<Necroplasm>(10).
AddTile<DraedonsForge>().
Register();
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

+121
View File
@@ -0,0 +1,121 @@
using CalamityMod.Items.Materials;
using CalamityMod.Projectiles.Magic;
using CalamityMod.Rarities;
using CalamityMod.Tiles.Furniture.CraftingStations;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Weapons.Magic
{
[LegacyName("Fabstaff")]
public class Sylvestaff : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Weapons.Magic";
/// <summary>
/// The amount by which the staff recoils after firing.
/// </summary>
public static float StaffRecoilForce => 0.04f;
/// <summary>
/// The rate at which rays from the staff can release bolts.
/// </summary>
public static int RayBoltShootRate => CalamityUtils.SecondsToFrames(0.0667f);
/// <summary>
/// The distance range that targets need to be within relative to a ray's evaluation points in order to shoot bolts.
/// </summary>
public static float RayBoltTargetingRange => 272f;
/// <summary>
/// The turn speed interpolant that dictates how fast or slow the staff can move to aim towards the mouse.
/// </summary>
public static float TurnSpeedInterpolant => 0.276f;
/// <summary>
/// The sound played when Sylvestaff rays are fired.
/// </summary>
public static readonly SoundStyle FireSound = new SoundStyle("CalamityMod/Sounds/Item/SylvestaffFire", 3) with { MaxInstances = 5 };
/// <summary>
/// The sound played when Sylvestaff rays bounce off of tiles.
/// </summary>
public static readonly SoundStyle BounceSound = new SoundStyle("CalamityMod/Sounds/Item/SylvestaffProjectileBounce", 3) with { MaxInstances = 5 };
public override string Texture
{
get
{
if (WorldGen.SavedOreTiers.Gold == TileID.Gold || Main.gameMenu)
return "CalamityMod/Items/Weapons/Magic/SylvestaffGold";
return "CalamityMod/Items/Weapons/Magic/SylvestaffPlatinum";
}
}
public override void SetStaticDefaults()
{
Item.staff[Item.type] = true;
}
public override void SetDefaults()
{
Item.width = 84;
Item.height = 84;
Item.damage = 125;
Item.DamageType = DamageClass.Magic;
Item.mana = 50;
Item.useTime = 20;
Item.useAnimation = 20;
Item.useStyle = ItemUseStyleID.Shoot;
Item.noMelee = true;
Item.channel = true;
Item.noUseGraphic = true;
Item.knockBack = 5f;
Item.value = CalamityGlobalItem.RarityHotPinkBuyPrice;
Item.rare = ModContent.RarityType<HotPink>();
Item.Calamity().devItem = true;
Item.autoReuse = true;
Item.shoot = ModContent.ProjectileType<SylvestaffHoldout>();
Item.shootSpeed = 13.5f;
}
public override void ModifyManaCost(Player player, ref float reduce, ref float mult)
{
if (player.ownedProjectileCounts[Item.shoot] <= 0)
mult *= 0;
}
public override void AddRecipes()
{
CreateRecipe().
AddIngredient(ItemID.RainbowRod).
AddIngredient(ItemID.GenderChangePotion).
AddRecipeGroup("AnyGoldBar", 5).
AddIngredient<Necroplasm>(10).
AddIngredient<ShadowspecBar>(5).
AddTile<DraedonsForge>().
Register();
}
public override bool PreDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frame, Color drawColor, Color itemColor, Vector2 origin, float scale)
{
Texture2D texture = ModContent.Request<Texture2D>(Texture).Value;
spriteBatch.Draw(texture, position, frame, drawColor, 0f, origin, scale, SpriteEffects.None, 0);
return false;
}
public override bool PreDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, ref float rotation, ref float scale, int whoAmI)
{
Texture2D texture = ModContent.Request<Texture2D>(Texture).Value;
spriteBatch.Draw(texture, Item.position - Main.screenPosition, null, lightColor, 0f, Vector2.Zero, scale, SpriteEffects.None, 0);
return false;
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -308,11 +308,6 @@ EvergladeSpray: {
Tooltip: Fires a stream of burning green ichor
}
Fabstaff: {
DisplayName: Fabstaff
Tooltip: Casts a bouncing beam that splits when enemies are near it
}
FaceMelter: {
DisplayName: Face Melter
Tooltip:
@@ -856,6 +851,15 @@ SubsumingVortex: {
'''
}
Sylvestaff: {
DisplayName: Sylvestaff
Tooltip:
'''
Casts a bouncing beam that splits when enemies are near it
'Also known as the Karma Staff!'
'''
}
TacticiansTrumpCard: {
DisplayName: Tactician's Trump Card
Tooltip:
@@ -466,7 +466,7 @@ BrimstoneWitch: {
}
EnchantButton: Enchant
DonorButton: Donors
DonorButton: Donors
DonorShoutout: Hey {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22}, {23} and {24}. You guys are good people.
TownNPCMood: {
@@ -66,8 +66,6 @@ EventHorizonStar.DisplayName: Event Horizon Star
EvergladeSprayProjectile.DisplayName: Everglade Spray
ExoVortex.DisplayName: Subsuming Vortex
ExoVortex2.DisplayName: Subsuming Vortex
FabBolt.DisplayName: Fab Bolt
FabRay.DisplayName: Fab Ray
FatesRevealFlame.DisplayName: Fate's Reveal
FireImplosion.DisplayName: Swirling Backdraft
FlareBoltProjectile.DisplayName: Flare Bolt
@@ -216,6 +214,8 @@ SpiritDust.DisplayName: Spirit Dust
Starblast.DisplayName: Star
StardustElementalBeam.DisplayName: Stardust Beam
StickyFeather.DisplayName: Feather
SylveBolt.DisplayName: Sylv Bolt
SylveRay.DisplayName: Sylv Ray
TacticiansElectricBoom.DisplayName: Electric Explosion
TacticiansTrumpCardProj.DisplayName: Trump Beam
TearsofHeavenProjectile.DisplayName: Tears of Heaven
@@ -261,3 +261,5 @@ WyvernFeatherPurple.DisplayName: Feather
WyvernProjectile.DisplayName: Wyvern
YharimsCrystalBeam.DisplayName: Yharim's Beam
YharimsCrystalPrism.DisplayName: Yermes Christal
SylvBolt.DisplayName: Sylv Bolt
SylvRay.DisplayName: Sylv Ray
+229
View File
@@ -0,0 +1,229 @@
using System;
using Microsoft.Xna.Framework;
using Terraria;
namespace CalamityMod.Physics;
internal class Rope
{
/// <summary>
/// A 0-1 interpolant which dictates a dampning factor for velocity integration increments.
/// </summary>
private float MovementSpeedDampingCoefficient
{
get;
set;
}
/// <summary>
/// A timer that increments in respond to wind, assuming wind response is enabled in the <see cref="Settings"/>.
/// </summary>
private float WindTime
{
get;
set;
}
/// <summary>
/// The set of segments that compose this rope.
/// </summary>
public RopeSegment[] Segments
{
get;
set;
}
/// <summary>
/// The set of positions that compose this rope.
/// </summary>
public Vector2[] SegmentPositions
{
get;
private set;
}
/// <summary>
/// The desired distance between each segment on the rope.
/// </summary>
public float DistancePerSegment
{
get;
set;
}
/// <summary>
/// The gravity force to exert on the rope when updating.
/// </summary>
public Vector2 Gravity
{
get;
set;
}
/// <summary>
/// The amount of steps to perform when constraining tiles to their desired lengths. Higher values equate to greater accuracy, but reduced performance.
/// </summary>
public int ConstraintSteps
{
get;
private set;
}
/// <summary>
/// Sets of settings that dictate how this rope should behave.
/// </summary>
public RopeSettings Settings
{
get;
set;
}
/// <summary>
/// Whether this rope should collide with tiles or not.
/// </summary>
public bool InteractWithTiles => Settings.TileColliderArea is not null;
public Rope(Vector2 start, Vector2 end, int segmentCount, float distancePerSegment, Vector2 gravity, RopeSettings settings, int constraintSteps = 10)
{
Segments = new RopeSegment[segmentCount];
SegmentPositions = new Vector2[segmentCount];
for (var i = 0; i < segmentCount; i++)
{
var segmentPos = Vector2.Lerp(start, end, i / (segmentCount - 1f));
Segments[i] = new RopeSegment(segmentPos);
}
Segments[0].FixedInPlace = settings.StartIsFixed;
Segments[^1].FixedInPlace = settings.EndIsFixed;
RecalculateSegmentPositions();
DistancePerSegment = distancePerSegment;
Gravity = gravity;
ConstraintSteps = constraintSteps;
Settings = settings;
}
/// <summary>
/// Recalculates the <see cref="SegmentPositions"/> cache based on <see cref="Segments"/> positions.
/// </summary>
private void RecalculateSegmentPositions()
{
for (var i = 0; i < Segments.Length; i++)
SegmentPositions[i] = Segments[i].Position;
}
/// <summary>
/// Moves a given position around, obeying tile interaction rules if this rope requires them.
/// </summary>
/// <param name="position">The position vector to move.</param>
/// <param name="baseVelocity">The base velocity to consider.</param>
private void Move(ref Vector2 position, Vector2 baseVelocity)
{
// Apply standard Eulerian integration if tile interactions are not required.
if (!InteractWithTiles || Settings.TileColliderArea is null)
{
position += baseVelocity;
return;
}
// If tile interactions *are* required, handle them before moving forward.
var width = (int)Settings.TileColliderArea.Value.X;
var height = (int)Settings.TileColliderArea.Value.Y;
var newVelocity = Collision.noSlopeCollision(position, baseVelocity, width, height + 2, true, true);
newVelocity = Collision.noSlopeCollision(position, newVelocity, width, height, true, true);
var finalVelocity = baseVelocity;
if (Math.Abs(baseVelocity.X) > Math.Abs(newVelocity.X))
finalVelocity.X = 0f;
if (Math.Abs(baseVelocity.Y) > Math.Abs(newVelocity.Y))
finalVelocity.Y = 0f;
position += finalVelocity;
}
/// <summary>
/// Updates this rope, making it move around.
/// </summary>
public void Update()
{
for (var i = 0; i < Segments.Length; i++)
{
var movementStep = (Segments[i].Position - Segments[i].OldPosition) * (1f - MovementSpeedDampingCoefficient);
if (movementStep.Length() < 0.02f)
movementStep = Vector2.Zero;
Segments[i].OldPosition = Segments[i].Position;
if (!Segments[i].FixedInPlace)
Move(ref Segments[i].Position, movementStep + Gravity);
}
for (var i = 0; i < ConstraintSteps; i++)
Constrain();
RecalculateSegmentPositions();
if (Settings.RespondToEntityMovement)
HandleEntityMovementResponse();
if (Settings.RespondToWind)
HandleWindResponse();
}
/// <summary>
/// Makes this rope respond to the movement of entities.
/// </summary>
private void HandleEntityMovementResponse()
{
for (var i = 0; i < Segments.Length; i++)
{
ref RopeSegment ropeSegment = ref Segments[i];
if (ropeSegment.FixedInPlace)
continue;
foreach (var player in Main.ActivePlayers)
{
float playerProximityInterpolant = Utils.GetLerpValue(37f, 10f, player.Distance(ropeSegment.Position), true);
ropeSegment.Position += player.velocity * playerProximityInterpolant / Settings.Mass * 0.08f;
}
}
}
/// <summary>
/// Makes this entity respond to wind.
/// </summary>
private void HandleWindResponse()
{
WindTime += Main.windSpeedCurrent / 60f;
if (MathF.Abs(WindTime) >= 4000f)
WindTime = 0f;
var windSpeed = Math.Clamp(Main.WindForVisuals * 2f, -1.3f, 1.3f);
var windWave = MathF.Cos(WindTime * 3.42f + Segments[0].Position.Length() * 0.06f);
var wind = Vector2.UnitX * (windWave + Main.windSpeedCurrent) * -0.2f;
Segments[^1].Position += wind * Utils.GetLerpValue(0.3f, 0.75f, windSpeed, true) / Settings.Mass;
}
/// <summary>
/// Constrains segments on this rope, conserving their overall length.
/// </summary>
public void Constrain()
{
for (var i = 0; i < Segments.Length - 1; i++)
{
// Determine how much each segment has to move in order to return to its desired resting distance.
var segmentLength = Segments[i].Position.Distance(Segments[i + 1].Position);
var distanceFromIdealLength = segmentLength - DistancePerSegment;
Vector2 correctiveForce = (Segments[i].Position - Segments[i + 1].Position).SafeNormalize(Vector2.Zero) * distanceFromIdealLength;
var pinned = Segments[i].FixedInPlace;
var nextPinned = Segments[i + 1].FixedInPlace;
correctiveForce *= pinned || nextPinned ? 1f : 0.5f;
if (!pinned)
Move(ref Segments[i].Position, -correctiveForce);
if (!nextPinned)
Move(ref Segments[i + 1].Position, correctiveForce);
}
}
}
+73
View File
@@ -0,0 +1,73 @@
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria.ModLoader;
namespace CalamityMod.Physics;
// Yes, I was silently reading over the Nightshade dev channels when learning about this.
// So, thanks Tomat and 1-3 for the idea! -Lucille
/// <summary>
/// A handle that contains a reference to a given globally managed rope instance.
/// </summary>
public readonly struct RopeHandle
{
/// <summary>
/// The value used to identify this handle's associated rope managed by the central system.
/// </summary>
private readonly int Identifier;
/// <summary>
/// The rope associated with this handle.
/// </summary>
private readonly Rope Rope => ModContent.GetInstance<RopeManagerSystem>().Ropes[Identifier]!;
/// <summary>
/// The set of all positions maintained by the underlying rope.
/// </summary>
public readonly IEnumerable<Vector2> Positions => Rope.SegmentPositions;
/// <summary>
/// The amount of segments this rope has.
/// </summary>
public int SegmentCount => Rope.Segments.Length;
/// <summary>
/// The starting position of the underlying rope.
/// </summary>
public ref Vector2 Start => ref Rope.Segments[0].Position;
/// <summary>
/// The ending position of the underlying rope.
/// </summary>
public ref Vector2 End => ref Rope.Segments[^1].Position;
/// <summary>
/// The gravity associated with the rope.
/// </summary>
public Vector2 Gravity
{
get => Rope.Gravity;
set => Rope.Gravity = value;
}
internal RopeHandle(int identifier) => Identifier = identifier;
/// <summary>
/// Forces this rope to settle by performing a series of constrained updates.
/// </summary>
public void Settle()
{
for (var i = 0; i < 20; i++)
Rope.Update();
}
/// <summary>
/// Indicates that the rope associated with this handle should be returned back to the pool.
/// </summary>
public void Dispose()
{
var chunkIndex = Identifier / RopeManagerSystem.BitsPerChunk;
var bitIndex = Identifier % RopeManagerSystem.BitsPerChunk;
ModContent.GetInstance<RopeManagerSystem>().ToggleActivityIndex(chunkIndex, bitIndex);
}
}
+132
View File
@@ -0,0 +1,132 @@
using System;
using Microsoft.Xna.Framework;
using Terraria.ModLoader;
using BitOperations = System.Numerics.BitOperations;
namespace CalamityMod.Physics;
public sealed class RopeManagerSystem : ModSystem
{
/// <summary>
/// The set of all maintained ropes in the world.
/// </summary>
internal readonly Rope[] Ropes = new Rope[MaxRopeCount];
/// <summary>
/// The internal binary mappings that determine whether ropes are active or not.
/// </summary>
internal readonly ulong[] ActivityBitChunks = new ulong[(int)Math.Ceiling((double)MaxRopeCount / BitsPerChunk)];
/// <summary>
/// The maximum amount of ropes to maintain across the world.
/// </summary>
public const int MaxRopeCount = 2048;
/// <summary>
/// The amount of bits contained within each chunk in the <see cref="ActivityBitChunks"/> array.
/// </summary>
public const int BitsPerChunk = sizeof(ulong) * 8;
public override void ClearWorld()
{
for (var i = 0; i < ActivityBitChunks.Length; i++)
ActivityBitChunks[i] = 0uL;
}
public override void PostUpdateWorld()
{
for (var i = 0; i < Ropes.Length; i++)
{
var bitIndex = i % BitsPerChunk;
var active = (ActivityBitChunks[i / BitsPerChunk] >> bitIndex & 1) == 1;
if (active)
Ropes[i].Update();
}
}
/// <summary>
/// Toggles a given activity index.
/// </summary>
/// <param name="chunkIndex">The index of the <see cref="ActivityBitChunks"/> to toggle.</param>
/// <param name="bitIndex">The bit index in the chunk to toggle.</param>
internal void ToggleActivityIndex(int chunkIndex, int bitIndex) => ActivityBitChunks[chunkIndex] ^= 1uL << bitIndex;
/// <summary>
/// Attempts to find and return the first available index for a new rope.
/// </summary>
private int? SelectFirstAvailableIndex()
{
for (var i = 0; i < ActivityBitChunks.Length; i++)
{
// This comment can be deleted later if it's deemed a bit too verbose. I'm half doing it for myself to test my understanding, half doing it for any future readers who might
// not immediately understand what the bit operations do here. -Lucille
// As a simplified example, assume the following for the activity bits, where zero means inactive and one means active:
// 0110 1111
// This means the first four indices are occupied, but the fifth index is free. Note that in this case bits are counted from right to left.
// In order to find the first new index, we simply need to count the amount of ones until the first zero.
// Conveniently, BitOperations.TrailingZeroCount exists for this purpose. We just need to invert the binary in order to convert the ones into zeroes.
var offset = BitOperations.TrailingZeroCount(~ActivityBitChunks[i]);
// Check if the index offset is equal to the amount of bits in the chunk.
// If so, that means that every single bit is a one, and that there's no available index in the chunk to use.
var allBitsAreOccupied = offset == BitsPerChunk;
if (allBitsAreOccupied)
continue;
return offset + i * BitsPerChunk;
}
// No valid index found across the activity bit chunks. Return null.
return null;
}
/// <summary>
/// Requests a new rope, returning a handle to it, or null if for some reason the rope couldn't be created.
/// </summary>
public RopeHandle? RequestNew(Vector2 start, Vector2 end, int segmentCount, float distancePerSegment, Vector2 gravity, RopeSettings settings, int constraintSteps = 10)
{
var index = SelectFirstAvailableIndex();
if (index is null)
return null;
// Mark the newly selected index as active by toggling its activity state on.
ToggleActivityIndex(index.Value / BitsPerChunk, index.Value % BitsPerChunk);
Ropes[index.Value] = new Rope(start, end, segmentCount, distancePerSegment, gravity, settings, constraintSteps);
return new RopeHandle(index.Value);
}
/// <summary>
/// Calculates the overall segment length of a rope based on the horizontal span between its two end points and a desired sag distance.
/// </summary>
public static float CalculateSegmentLength(float ropeSpan, float sag, int iterations = 12)
{
// A rope at rest is defined via a catenary curve, which exists in the following mathematical form:
// y(x) = a * cosh(x / a)
// Furthermore, the length of a rope, given the horizontal width w for a rope, is defined as follows:
// L = 2a * sinh(w / 2a)
// In order to use the above equation, the value of a must be determined for the catenary that this rope will form.
// To do so, a numerical solution will need to be found based on the known width and sag values.
// Suppose the two supports are at equal height at distances -w/2 and w/2.
// From this, sag (which will be denoted with h) can be defined in the following way: h = y(w/2) - y(0)
// Reducing this results in the following equation:
// h = a(cosh(w / 2a) - 1)
// a(cosh(w / 2a) - 1) - h = 0
// This can be used to numerically find a.
var initialGuessA = sag;
var a = (float)CalamityUtils.IterativelySearchForRoot(x =>
{
return x * (Math.Cosh(ropeSpan / (x * 2D)) - 1D) - sag;
}, initialGuessA, iterations);
// Now that a is known, it's just a matter of plugging it back into the original equation to find L.
return MathF.Sinh(ropeSpan / a * 0.5f) * a * 2f;
}
}
+30
View File
@@ -0,0 +1,30 @@
using Microsoft.Xna.Framework;
namespace CalamityMod.Physics;
/// <summary>
/// A representation of a rope segment, containing physical data such as position, velocity, etc., as well as a value which determines whether the rope is fixed in place and not subject to standard physics.
/// </summary>
public struct RopeSegment
{
/// <summary>
/// The current position of this segment.
/// </summary>
public Vector2 Position;
/// <summary>
/// The previous position of this segment.
/// </summary>
public Vector2 OldPosition;
/// <summary>
/// Whether this segment is fixed in place and not subject to standard physics, such as gravity.
/// </summary>
public bool FixedInPlace;
public RopeSegment(Vector2 position)
{
Position = position;
OldPosition = position;
}
}
+11
View File
@@ -0,0 +1,11 @@
using Microsoft.Xna.Framework;
namespace CalamityMod.Physics;
public readonly record struct RopeSettings(bool StartIsFixed, bool EndIsFixed, bool RespondToEntityMovement, bool RespondToWind, Vector2? TileColliderArea, float Mass = 1f)
{
public RopeSettings() : this(false, false, false, false, null, 1f)
{
}
}
@@ -186,7 +186,7 @@ namespace CalamityMod.Projectiles.DraedonsArsenal
Vector2 origin = frame.Size() * 0.5f;
Main.EntitySpriteDraw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, SpriteEffects.None, 0);
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(PrimitiveWidthFunction, PrimitiveColorFunction, (_) => Projectile.Size * 0.5f, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 92);
return false;
}
+1 -1
View File
@@ -60,7 +60,7 @@ namespace CalamityMod.Projectiles.Enemy
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
Vector2 overallOffset = Projectile.Size / 2;
int numPoints = 92;
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(PrimitiveWidthFunction, PrimitiveColorFunction, (_) => overallOffset, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), numPoints);
+1 -1
View File
@@ -226,7 +226,7 @@ namespace CalamityMod.Projectiles.Magic
Vector2 origin = texture.Size() * 0.5f;
Main.spriteBatch.EnterShaderRegion();
GameShaders.Misc["CalamityMod:ArtAttack"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:ArtAttack"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
GameShaders.Misc["CalamityMod:ArtAttack"].Apply();
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(TrailWidth, TrailColor, (_) => Projectile.Size * 0.5f, shader: GameShaders.Misc["CalamityMod:ArtAttack"]), 180);
-110
View File
@@ -1,110 +0,0 @@
using System;
using CalamityMod.Graphics.Primitives;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Magic
{
public class FabBolt : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Magic";
public override string Texture => "CalamityMod/Projectiles/InvisibleProj";
public bool FadingOut
{
get => Projectile.ai[0] == 1f;
set => Projectile.ai[0] = value.ToInt();
}
public override void SetStaticDefaults()
{
ProjectileID.Sets.CultistIsResistantTo[Type] = true;
ProjectileID.Sets.TrailingMode[Type] = 2;
ProjectileID.Sets.TrailCacheLength[Type] = 23;
}
public override void SetDefaults()
{
Projectile.width = 4;
Projectile.height = 4;
Projectile.friendly = true;
Projectile.extraUpdates = 2;
Projectile.penetrate = 12;
Projectile.timeLeft = 90 * Projectile.extraUpdates;
Projectile.DamageType = DamageClass.Magic;
Projectile.ignoreWater = true;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 0;
}
public override void AI()
{
if (FadingOut)
{
Projectile.Opacity = MathHelper.Lerp(Projectile.Opacity, 0f, 0.27f);
if (Projectile.Opacity <= 0.05f)
Projectile.Kill();
}
else
Projectile.velocity *= 1.004f;
Projectile.rotation = Projectile.velocity.ToRotation();
// Emit light.
Lighting.AddLight(Projectile.Center, Vector3.One * Projectile.Opacity * 0.45f);
}
internal Color ColorFunction(float completionRatio)
{
float fadeToEnd = MathHelper.Lerp(0.25f, 0.5f, (float)Math.Cos(-Main.GlobalTimeWrappedHourly * 3f) * 0.5f + 0.5f);
fadeToEnd *= 1f - Utils.GetLerpValue(0.35f, 0f, completionRatio, true);
Color endColor = Color.Lerp(Color.Cyan, Color.HotPink, Projectile.identity % 2);
return Color.Lerp(Color.White, endColor, fadeToEnd) * Projectile.Opacity * 0.7f;
}
internal float WidthFunction(float completionRatio)
{
float expansionCompletion = 1f - (float)Math.Pow(1f - Utils.GetLerpValue(0f, 0.2f, completionRatio, true), 2D);
return MathHelper.Lerp(0f, 22f, expansionCompletion) * Projectile.Opacity;
}
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(WidthFunction, ColorFunction, (_) => Projectile.Size * 0.5f, smoothen: false, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 80);
return false;
}
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
if (!FadingOut && Projectile.penetrate < 2)
{
FadingOut = true;
Projectile.velocity *= 0.1f;
Projectile.extraUpdates = 0;
Projectile.netUpdate = true;
}
}
public override bool OnTileCollide(Vector2 oldVelocity)
{
if (!FadingOut)
{
FadingOut = true;
Projectile.velocity *= 0.1f;
Projectile.extraUpdates = 0;
Projectile.netUpdate = true;
}
return false;
}
public override bool? CanDamage()
{
if (FadingOut)
return false;
return null;
}
}
}
-122
View File
@@ -1,122 +0,0 @@
using System;
using CalamityMod.Buffs.Alcohol;
using CalamityMod.Graphics.Primitives;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Magic
{
public class FabRay : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Magic";
public override string Texture => "CalamityMod/Projectiles/InvisibleProj";
public override void SetStaticDefaults()
{
ProjectileID.Sets.TrailCacheLength[Type] = 54;
ProjectileID.Sets.TrailingMode[Type] = 2;
}
public override void SetDefaults()
{
Projectile.width = 4;
Projectile.height = 4;
Projectile.friendly = true;
Projectile.DamageType = DamageClass.Magic;
Projectile.ignoreWater = true;
Projectile.penetrate = 70;
Projectile.extraUpdates = 3;
Projectile.timeLeft = 60 * Projectile.extraUpdates;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 10;
}
public override void AI()
{
Lighting.AddLight(Projectile.Center, 0.2f, 0.01f, 0.1f);
Projectile.ai[0] += 1f;
Projectile.Opacity = Utils.GetLerpValue(0f, 10f * Projectile.MaxUpdates, Projectile.timeLeft, true);
int shootRate = Projectile.npcProj ? 40 : 12;
if (Projectile.owner == Main.myPlayer && Projectile.ai[0] % shootRate == 0f)
{
NPC potentialTarget = Projectile.Center.ClosestNPCAt(180f, false);
if (potentialTarget != null)
{
Vector2 shootVelocity = Projectile.SafeDirectionTo(potentialTarget.Center) * 13f;
Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center - shootVelocity * 2.5f, shootVelocity, ModContent.ProjectileType<FabBolt>(), Projectile.damage, Projectile.knockBack, Projectile.owner);
}
for (int i = 0; i < Projectile.oldPos.Length / 4; i += 3)
{
potentialTarget = Projectile.oldPos[i].ClosestNPCAt(280f, false);
if (potentialTarget != null)
{
Vector2 shootVelocity = (potentialTarget.Center - Projectile.oldPos[i]).SafeNormalize(Vector2.UnitY) * 13f;
Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.oldPos[i] - shootVelocity * 2.5f, shootVelocity, ModContent.ProjectileType<FabBolt>(), Projectile.damage, Projectile.knockBack, Projectile.owner);
break;
}
}
}
// Emit light.
if (!Projectile.hostile)
Lighting.AddLight(Projectile.Center, Vector3.One * Projectile.Opacity * 0.7f);
}
internal Color ColorFunction(float completionRatio)
{
float fadeToEnd = MathHelper.Lerp(0.65f, 1f, (float)Math.Cos(-Main.GlobalTimeWrappedHourly * 3f) * 0.5f + 0.5f);
float fadeOpacity = Utils.GetLerpValue(1f, 0.64f, completionRatio, true) * Projectile.Opacity;
Color endColor = Color.Lerp(Color.Cyan, Color.HotPink, (float)Math.Sin(completionRatio * MathHelper.Pi * 1.6f - Main.GlobalTimeWrappedHourly * 4f) * 0.5f + 0.5f);
return Color.Lerp(Color.White, endColor, fadeToEnd) * fadeOpacity;
}
internal float WidthFunction(float completionRatio)
{
float expansionCompletion = 1f - (float)Math.Pow(1f - Utils.GetLerpValue(0f, 0.3f, completionRatio, true), 2D);
return MathHelper.Lerp(0f, 32f * Projectile.Opacity, expansionCompletion);
}
internal Vector2 OffsetFunction(float completionRatio) => Projectile.Size * 0.5f;
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/ScarletDevilStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new PrimitiveSettings(WidthFunction, ColorFunction, OffsetFunction, pixelate: false, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 32);
return false;
}
public override bool OnTileCollide(Vector2 oldVelocity)
{
Projectile.penetrate--;
if (Projectile.penetrate <= 0)
{
Projectile.Kill();
}
else
{
if (Projectile.velocity.X != oldVelocity.X)
{
Projectile.velocity.X = -oldVelocity.X;
}
if (Projectile.velocity.Y != oldVelocity.Y)
{
Projectile.velocity.Y = -oldVelocity.Y;
}
}
return false;
}
public override void OnHitPlayer(Player target, Player.HurtInfo info)
{
if (Projectile.hostile)
target.AddBuff(ModContent.BuffType<PurpleHazeBuff>(), 54000);
}
}
}
+2 -2
View File
@@ -378,9 +378,9 @@ namespace CalamityMod.Projectiles.Magic
return Color.Lerp(endColor, Color.White, deathInterpolant);
}
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch)
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch, PixelationPrimitiveLayer layer)
{
GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(PlasmaBallWidthFunction, PlasmaBallColorFunction, (_) => Projectile.Size * 0.5f, true, true, GameShaders.Misc["CalamityMod:ImpFlameTrail"]), Projectile.oldPos.Length * 2);
}
}
+2 -2
View File
@@ -137,10 +137,10 @@ namespace CalamityMod.Projectiles.Magic
return Color.Lerp(startColor, bodyColor, completion);
}
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch)
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch, PixelationPrimitiveLayer layer)
{
// Render the main trail for the body for the laser.
GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(LaserWidthFunction, LaserColorFunction, (_) => Projectile.Size * 0.5f, true, true, GameShaders.Misc["CalamityMod:ImpFlameTrail"]), Projectile.oldPos.Length * 2);
// Render a smaller, pure white trail in the same position to represent condensed energy in the core of the laser.
+2 -2
View File
@@ -234,7 +234,7 @@ namespace CalamityMod.Projectiles.Magic
return Color.Lerp(Color.White, tipColor, completion);
}
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch)
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch, PixelationPrimitiveLayer layer)
{
// Render the main trail for the body for the soul.
GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/ScarletDevilStreak"));
@@ -242,7 +242,7 @@ namespace CalamityMod.Projectiles.Magic
// Render a smaller, pure white trail in the same position to represent the glowing white core of the soul.
Vector2[] soulCoreLength = Projectile.oldPos.Take(8).ToArray();
GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(soulCoreLength, new(SoulCoreWidthFunction, SoulCoreColorFunction, (_) => Projectile.Size * 0.5f, true, true, GameShaders.Misc["CalamityMod:ImpFlameTrail"]), soulCoreLength.Length * 2);
}
}
+155
View File
@@ -0,0 +1,155 @@
using System;
using CalamityMod.Graphics.Primitives;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Magic
{
public class SylvBolt : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Magic";
public override string Texture => "CalamityMod/Projectiles/InvisibleProj";
/// <summary>
/// The color hue interpolant for this bolt.
/// </summary>
public ref float HueInterpolant => ref Projectile.ai[0];
/// <summary>
/// How many natural frames have elapsed so far throughout the duration of this bolt's life. Extra updates do not affect this timer.
/// </summary>
public int Time
{
get => (int)Projectile.ai[1];
set => Projectile.ai[1] = value;
}
/// <summary>
/// Whether this bolt is vanishing due to the a collision.
/// </summary>
public bool Vanishing
{
get => Projectile.ai[2] == 1f;
set => Projectile.ai[2] = value.ToInt();
}
public override void SetStaticDefaults()
{
ProjectileID.Sets.TrailingMode[Projectile.type] = 2;
ProjectileID.Sets.TrailCacheLength[Projectile.type] = 23;
}
public override void SetDefaults()
{
Projectile.width = 4;
Projectile.height = 4;
Projectile.friendly = true;
Projectile.extraUpdates = 2;
Projectile.penetrate = 12;
Projectile.timeLeft = Projectile.extraUpdates * 90;
Projectile.DamageType = DamageClass.Magic;
Projectile.ignoreWater = true;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 0;
}
public override void AI()
{
Projectile.velocity *= 1.004f;
if (Vanishing)
Vanish();
if (Projectile.FinalExtraUpdate())
Time++;
Projectile.scale = Utils.GetLerpValue(0f, 7f, Time, true);
CreateMagicDust();
// Emit light.
Lighting.AddLight(Projectile.Center, Vector3.One * Projectile.Opacity * 0.45f);
}
/// <summary>
/// Makes this bolt vanish.
/// </summary>
private void Vanish()
{
Projectile.Opacity = MathHelper.Lerp(Projectile.Opacity, 0f, 0.24f);
Projectile.velocity = Vector2.Zero;
Projectile.tileCollide = false;
if (Projectile.Opacity <= 0.1f)
Projectile.Kill();
}
/// <summary>
/// Idly emits magic dust off this bolt.
/// </summary>
private void CreateMagicDust()
{
if (Main.rand.NextBool(4))
{
Dust magic = Dust.NewDustPerfect(Projectile.Center, 264);
magic.color = ColorFunction(0f);
magic.scale *= 0.56f;
magic.noGravity = true;
}
}
/// <summary>
/// The function responsible for dictating the color of this bolt.
/// </summary>
internal Color ColorFunction(float completionRatio)
{
float opacity = (1f - completionRatio) * Projectile.Opacity;
return CalamityUtils.MulticolorLerp(HueInterpolant, new Color(255, 193, 255), Color.White, new Color(127, 242, 255)) * opacity;
}
/// <summary>
/// The function responsible for dictating the width of this bolt.
/// </summary>
internal float WidthFunction(float completionRatio)
{
float tip = 1f - MathF.Pow(1f - Utils.GetLerpValue(0.05f, 0.2f, completionRatio * Projectile.Opacity, true), 2f);
return tip * Projectile.Opacity * Projectile.scale * 22f;
}
public override bool PreDraw(ref Color lightColor)
{
MiscShaderData boltShader = GameShaders.Misc["CalamityMod:SylvestaffProjectile"];
boltShader.SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(WidthFunction, ColorFunction, (_) => Projectile.Size * 0.5f, smoothen: false, shader: boltShader), 80);
return false;
}
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
if (!Vanishing && Projectile.penetrate < 2)
{
Vanishing = true;
Projectile.velocity *= 0.02f;
Projectile.extraUpdates = 0;
Projectile.netUpdate = true;
}
}
public override bool OnTileCollide(Vector2 oldVelocity)
{
if (!Vanishing)
{
Vanishing = true;
Projectile.velocity = Vector2.Zero;
Projectile.extraUpdates = 0;
Projectile.netUpdate = true;
}
return false;
}
public override bool? CanDamage() => !Vanishing;
}
}
+217
View File
@@ -0,0 +1,217 @@
using System;
using System.IO;
using CalamityMod.Graphics.Primitives;
using CalamityMod.Items.Weapons.Magic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Magic
{
public class SylvRay : ModProjectile, ILocalizedModType
{
/// <summary>
/// The position from which this ray's glow effect appears.
/// </summary>
public Vector2 GlowCenter
{
get;
set;
}
/// <summary>
/// How many natural frames have elapsed so far throughout the duration of this ray's life. Extra updates do not affect this timer.
/// </summary>
public int Time
{
get => (int)Projectile.ai[0];
set => Projectile.ai[0] = value;
}
public new string LocalizationCategory => "Projectiles.Magic";
public override string Texture => "CalamityMod/Projectiles/InvisibleProj";
public override void SetStaticDefaults()
{
ProjectileID.Sets.TrailCacheLength[Projectile.type] = 54;
ProjectileID.Sets.TrailingMode[Projectile.type] = 2;
}
public override void SetDefaults()
{
Projectile.width = 4;
Projectile.height = 4;
Projectile.friendly = true;
Projectile.DamageType = DamageClass.Magic;
Projectile.ignoreWater = true;
Projectile.penetrate = 70;
Projectile.extraUpdates = 3;
Projectile.timeLeft = 60 * Projectile.extraUpdates;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 10;
}
public override void SendExtraAI(BinaryWriter writer) => writer.WriteVector2(GlowCenter);
public override void ReceiveExtraAI(BinaryReader reader) => GlowCenter = reader.ReadVector2();
public override void AI()
{
if (Projectile.FinalExtraUpdate())
Time++;
Projectile.Opacity = Utils.GetLerpValue(0f, Projectile.MaxUpdates * 10f, Projectile.timeLeft, true);
Projectile.scale = Utils.GetLerpValue(1f, 9.5f, Time, true) * Projectile.Opacity;
if (GlowCenter == Vector2.Zero)
GlowCenter = Projectile.Center + Projectile.velocity.SafeNormalize(Vector2.Zero) * 74f;
HandleBoltFiring();
CreateGlowyDust();
Lighting.AddLight(Projectile.Center, Vector3.One * Projectile.Opacity * 0.7f);
}
/// <summary>
/// Handles the firing of bolts across this ray.
/// </summary>
private void HandleBoltFiring()
{
int shootRate = Sylvestaff.RayBoltShootRate;
if (Time % shootRate == 0 && Projectile.FinalExtraUpdate())
{
int trailSearchPositions = 13;
for (int i = 0; i < trailSearchPositions; i += 3)
TryToFireBolt(Projectile.oldPos[i] + Projectile.Size * 0.5f, i / (float)trailSearchPositions);
}
}
/// <summary>
/// Attempts to fire a given bolt projectile from a given position at the closest enemy to said position, assuming one exists.
/// </summary>
private void TryToFireBolt(Vector2 searchPosition, float hue)
{
NPC potentialTarget = searchPosition.ClosestNPCAt(Sylvestaff.RayBoltTargetingRange, false);
if (potentialTarget is null)
return;
SoundEngine.PlaySound(Sylvestaff.BounceSound with { MaxInstances = 12, Volume = 0.4f, Pitch = 0.4f }, Projectile.Center);
float shootSpeed = Projectile.velocity.Length();
Vector2 shootVelocity = (potentialTarget.Center - searchPosition).SafeNormalize(Vector2.UnitY) * shootSpeed;
if (Projectile.owner == Main.myPlayer)
Projectile.NewProjectile(Projectile.GetSource_FromThis(), searchPosition, shootVelocity, ModContent.ProjectileType<SylvBolt>(), Projectile.damage, Projectile.knockBack, Projectile.owner, hue);
float burstSpeed = Main.rand.NextFloat(1f, 3f);
for (int i = 0; i < 4; i++)
{
Dust magicBurst = Dust.NewDustPerfect(searchPosition, 264);
magicBurst.velocity = Projectile.velocity.RotatedBy(MathHelper.TwoPi * i / 4f + MathHelper.PiOver4).SafeNormalize(Vector2.Zero) * burstSpeed;
magicBurst.color = Color.White;
magicBurst.noLight = true;
magicBurst.noGravity = true;
}
}
/// <summary>
/// Emits dust particles at the glow center of this ray, to help sell the notion that it's appearing from a concentrated ball of queer magic energy.
/// </summary>
private void CreateGlowyDust()
{
if (Time <= 9 && Main.rand.NextBool())
{
Color colorAccent = Main.rand.NextBool() ? Color.HotPink : Color.Aqua;
Dust transMagic = Dust.NewDustPerfect(GlowCenter, 264);
transMagic.velocity = Main.rand.NextVector2Circular(4.6f, 4.6f) + Projectile.velocity * 0.25f;
transMagic.color = Color.Lerp(Color.White, colorAccent, Main.rand.NextFloat(0.23f));
transMagic.scale *= 1.1f;
transMagic.fadeIn = 0.75f;
transMagic.noGravity = true;
}
}
/// <summary>
/// The function responsible for dictating the color of this ray.
/// </summary>
internal Color ColorFunction(float completionRatio)
{
float opacity = MathF.Pow(Utils.GetLerpValue(1f, 0.64f, completionRatio, true), 3f) * Projectile.Opacity;
float colorInterpolant = MathF.Cos(MathHelper.Pi * completionRatio - Main.GlobalTimeWrappedHourly * 7.2f) * 0.5f + 0.5f;
Color pink = new Color(255, 147, 255);
Color blue = new Color(109, 224, 255);
Color baseColor = CalamityUtils.MulticolorLerp(colorInterpolant, pink, Color.White, blue, Color.White);
return baseColor * opacity;
}
/// <summary>
/// The function responsible for dictating the width of this ray.
/// </summary>
internal float WidthFunction(float completionRatio)
{
float expansionCompletion = 1f - MathF.Pow(1f - Utils.GetLerpValue(0f, 0.3f, completionRatio, true), 2f);
float undulation = MathF.Cos(MathHelper.Pi * completionRatio * 5f - Main.GlobalTimeWrappedHourly * 23f) * 2.4f;
float maxWidth = undulation + 32f;
return MathHelper.Lerp(0f, Projectile.scale * maxWidth, expansionCompletion);
}
/// <summary>
/// The function responsible for dictating the render offset of this ray.
/// </summary>
internal Vector2 OffsetFunction(float completionRatio) => Projectile.Size * 0.5f;
/// <summary>
/// Renders the front-glow for this ray, to help make it look like it has a defined origin of concentrated magic.
/// </summary>
private void RenderFrontGlow()
{
float glowAnimationProgress = Utils.GetLerpValue(0f, 9.5f, Time, true);
float glowBump = CalamityUtils.Convert01To010(glowAnimationProgress);
float glowRotation = Projectile.velocity.ToRotation();
Vector2 glowScale = new Vector2(1f + glowBump * 0.8f, 1f) * glowBump;
Vector2 startingPosition = GlowCenter - Main.screenPosition;
Texture2D lightTexture = ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/BloomCirclePinpoint").Value;
Main.spriteBatch.Draw(lightTexture, startingPosition, null, ColorFunction(0f) with { A = 0 }, glowRotation, lightTexture.Size() * 0.5f, glowScale, 0, 0f);
Main.spriteBatch.Draw(lightTexture, startingPosition, null, ColorFunction(0f) with { A = 0 }, glowRotation, lightTexture.Size() * 0.5f, glowScale * 0.4f, 0, 0f);
}
public override bool PreDraw(ref Color lightColor)
{
RenderFrontGlow();
MiscShaderData rayShader = GameShaders.Misc["CalamityMod:SylvestaffProjectile"];
rayShader.SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/ScarletDevilStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new PrimitiveSettings(WidthFunction, ColorFunction, OffsetFunction, pixelate: false, shader: rayShader), 32);
return false;
}
public override bool OnTileCollide(Vector2 oldVelocity)
{
Projectile.penetrate--;
if (Projectile.penetrate <= 0)
{
Projectile.Kill();
}
else
{
SoundEngine.PlaySound(Sylvestaff.BounceSound, Projectile.Center);
if (Projectile.velocity.X != oldVelocity.X)
Projectile.velocity.X = -oldVelocity.X;
if (Projectile.velocity.Y != oldVelocity.Y)
Projectile.velocity.Y = -oldVelocity.Y;
}
return false;
}
}
}
+262
View File
@@ -0,0 +1,262 @@
using System;
using CalamityMod.Graphics.Primitives;
using CalamityMod.Items.Weapons.Magic;
using CalamityMod.Physics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.Graphics.Shaders;
using Terraria.Localization;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Magic
{
public class SylvestaffHoldout : ModProjectile, IPixelatedPrimitiveRenderer
{
public PixelationPrimitiveLayer LayerToRenderTo => PixelationPrimitiveLayer.BeforeProjectiles | PixelationPrimitiveLayer.AfterPlayers;
public override LocalizedText DisplayName => CalamityUtils.GetItemName<Sylvestaff>();
/// <summary>
/// The left ribbon on this holdout.
/// </summary>
public RopeHandle? LeftRibbon;
/// <summary>
/// The right ribbon on this holdout.
/// </summary>
public RopeHandle? RightRibbon;
/// <summary>
/// The player owner of this holdout staff.
/// </summary>
public Player Owner => Main.player[Projectile.owner];
/// <summary>
/// A general purpose, ever-increment timer used by this holdout staff.
/// </summary>
public ref float Time => ref Projectile.ai[0];
/// <summary>
/// The point of attachment for ribbons on this staff.
/// </summary>
public Vector2 RibbonAttachPoint => Projectile.Center + Projectile.velocity * Projectile.scale * Projectile.width * 0.34f;
/// <summary>
/// The length of ribbons attached to this staff.
/// </summary>
private static float RibbonLength => 70f;
public override string Texture => ModContent.GetInstance<Sylvestaff>().Texture;
public override void SetDefaults()
{
Projectile.width = Projectile.height = 94;
Projectile.friendly = true;
Projectile.penetrate = -1;
Projectile.DamageType = DamageClass.Magic;
Projectile.tileCollide = false;
Projectile.ignoreWater = true;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 10;
Projectile.timeLeft = 72000;
}
public override void AI()
{
if (!Owner.channel)
Projectile.Kill();
if (LeftRibbon is null && RightRibbon is null)
InitializeRibbons();
AimTowardsMouse();
HandleHoldoutLogic();
OrientOwnerArms();
FireAwesomeMagicRays();
UpdateRibbon(LeftRibbon, Projectile.velocity.RotatedBy(-MathHelper.PiOver2));
UpdateRibbon(RightRibbon, Projectile.velocity.RotatedBy(MathHelper.PiOver2));
Time++;
}
/// <summary>
/// Initializes the ribbons attached to this staff.
/// </summary>
private void InitializeRibbons()
{
int ribbonSegmentCount = 12;
float distancePerSegment = RibbonLength / ribbonSegmentCount;
RopeSettings ribbonSettings = new RopeSettings()
{
StartIsFixed = true,
Mass = 0.72f,
RespondToEntityMovement = true,
RespondToWind = true
};
LeftRibbon = ModContent.GetInstance<RopeManagerSystem>().RequestNew(RibbonAttachPoint, Projectile.Center, ribbonSegmentCount, distancePerSegment, Vector2.Zero, ribbonSettings, 25);
RightRibbon = ModContent.GetInstance<RopeManagerSystem>().RequestNew(RibbonAttachPoint, Projectile.Center, ribbonSegmentCount, distancePerSegment, Vector2.Zero, ribbonSettings, 25);
}
/// <summary>
/// Handles all logic pertaining to making this staff act as a holdout projectile.
/// </summary>
private void HandleHoldoutLogic()
{
Vector2 center = Owner.MountedCenter + Vector2.UnitY * 7f + Projectile.velocity * Projectile.width * 0.31f;
Projectile.rotation = Projectile.velocity.ToRotation();
Projectile.Center = Owner.RotatedRelativePoint(center) - Vector2.UnitY * Owner.gfxOffY;
Projectile.spriteDirection = (Math.Cos(Projectile.rotation) > 0).ToDirectionInt();
// The staff is a holdout projectile; change the player's variables to reflect this.
Owner.ChangeDir(Projectile.spriteDirection);
Owner.SetDummyItemTime(2);
Owner.heldProj = Projectile.whoAmI;
Projectile.rotation += MathHelper.PiOver4;
if (Projectile.spriteDirection == -1)
Projectile.rotation += MathHelper.PiOver2;
}
/// <summary>
/// Orients the owner player's arm rotation to help make it look like they're actually holding the staff.
/// </summary>
private void OrientOwnerArms()
{
float baseRotation = Projectile.velocity.ToRotation() - MathHelper.PiOver2;
float directionVerticality = MathF.Abs(Projectile.velocity.X);
Owner.SetCompositeArmFront(true, Player.CompositeArmStretchAmount.Full, baseRotation + Owner.direction * directionVerticality * MathHelper.PiOver4);
Owner.SetCompositeArmBack(true, Player.CompositeArmStretchAmount.Full, baseRotation + Owner.direction * directionVerticality * 0.33f);
}
/// <summary>
/// Makes this staff aim towards the owner's mouse.
/// </summary>
private void AimTowardsMouse()
{
if (Main.myPlayer != Projectile.owner)
return;
Vector2 idealDirection = Projectile.SafeDirectionTo(Main.MouseWorld);
Vector2 newDirection = Vector2.Lerp(Projectile.velocity, idealDirection, Sylvestaff.TurnSpeedInterpolant).SafeNormalize(Vector2.UnitX * Owner.direction);
if (Projectile.velocity != newDirection)
{
Projectile.velocity = newDirection;
Projectile.netUpdate = true;
Projectile.netSpam = 0;
}
}
/// <summary>
/// Updates a given ribbon.
/// </summary>
private void UpdateRibbon(RopeHandle? ribbon, Vector2 gravityDirection)
{
// Ensure that the handle is properly initialized before proceeding any further.
if (ribbon is not RopeHandle rope)
return;
rope.Start = RibbonAttachPoint;
rope.Gravity = gravityDirection * 0.15f - Projectile.velocity * 0.4f;
}
/// <summary>
/// Handles the firing of magic ray projectiles for this staff.
/// </summary>
private void FireAwesomeMagicRays()
{
Item heldItem = Owner.ActiveItem();
if (heldItem is null)
return;
if (Time % heldItem.useAnimation == heldItem.useAnimation - 1 && Owner.CheckMana(heldItem.mana, true))
{
SoundEngine.PlaySound(Sylvestaff.FireSound, Projectile.Center);
if (Main.myPlayer == Projectile.owner)
{
int damage = Owner.GetWeaponDamage(heldItem);
Vector2 shootVelocity = Projectile.velocity * heldItem.shootSpeed;
Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, shootVelocity, ModContent.ProjectileType<SylvRay>(), damage, heldItem.knockBack, Projectile.owner);
// Apply a minor amount of recoil.
Projectile.velocity -= Projectile.velocity.RotatedBy(Projectile.spriteDirection * MathHelper.PiOver2) * Sylvestaff.StaffRecoilForce;
}
}
}
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch, PixelationPrimitiveLayer layer)
{
bool backLayer = layer == PixelationPrimitiveLayer.BeforeProjectiles;
RenderRibbon(LeftRibbon, -1, backLayer);
RenderRibbon(RightRibbon, 1, backLayer);
}
/// <summary>
/// The function responsible for dictating the width of this staff's ribbons.
/// </summary>
private float RibbonWidthFunction(float completionRatio) => Projectile.scale * Utils.GetLerpValue(0f, 0.2f, completionRatio, true) * 3.6f;
/// <summary>
/// The function responsible for dictating the color of this staff's ribbons.
/// </summary>
private Color RibbonColorFunction(float completionRatio)
{
Color light = Lighting.GetColor(RibbonAttachPoint.ToTileCoordinates());
return Projectile.GetAlpha(light);
}
/// <summary>
/// Renders one of this staff's ribbons.
/// </summary>
private void RenderRibbon(RopeHandle? ribbon, int direction, bool backLayer)
{
// Ensure that the handle is properly initialized before proceeding any further.
if (ribbon is not RopeHandle rope)
return;
Vector2 forwardDirection = Projectile.velocity;
Vector2 sideDirection = forwardDirection.RotatedBy(MathHelper.PiOver2 * direction);
Vector2 attachmentPoint = RibbonAttachPoint;
Vector2[] ribbonPositions = [.. rope.Positions];
int positionCount = ribbonPositions.Length;
for (int i = 0; i < ribbonPositions.Length; i++)
{
float completionRatio = i / (float)positionCount;
float wave = MathF.Cos(MathHelper.Pi * completionRatio * 1.5f - MathHelper.TwoPi * Time / 97f) * completionRatio;
Vector2 backwardsOffset = forwardDirection * i * -RibbonLength / positionCount;
Vector2 sideWavyOffset = sideDirection * wave * RibbonLength * 0.5f;
Vector2 rigidPosition = attachmentPoint + backwardsOffset + sideWavyOffset;
ribbonPositions[i] = Vector2.Lerp(ribbonPositions[i], rigidPosition, 0.76f);
}
Vector2 intersectionPosition = Vector2.Transform((Projectile.Center - Main.screenPosition) * 0.5f, Main.GameViewMatrix.TransformationMatrix);
MiscShaderData ribbonShader = GameShaders.Misc["CalamityMod:SylvestaffRibbon"];
ribbonShader.UseShaderSpecificData(new Vector4(intersectionPosition.X, intersectionPosition.Y, sideDirection.X, sideDirection.Y));
ribbonShader.UseSaturation(backLayer ? -1f : 1f);
PrimitiveSettings primitiveSettings = new PrimitiveSettings(RibbonWidthFunction, RibbonColorFunction, pixelate: true, shader: ribbonShader);
PrimitiveRenderer.RenderTrail(ribbonPositions, primitiveSettings, 33);
}
public override bool PreDraw(ref Color lightColor)
{
Texture2D texture = ModContent.Request<Texture2D>(Texture).Value;
Vector2 drawPosition = Projectile.Center - Main.screenPosition;
SpriteEffects direction = Projectile.spriteDirection == 1 ? SpriteEffects.None : SpriteEffects.FlipHorizontally;
Main.spriteBatch.Draw(texture, drawPosition, null, Projectile.GetAlpha(lightColor), Projectile.rotation, texture.Size() * 0.5f, Projectile.scale, direction, 0f);
return false;
}
public override void OnKill(int timeLeft)
{
LeftRibbon?.Dispose();
RightRibbon?.Dispose();
}
public override bool? CanDamage() => false;
}
}
+1 -1
View File
@@ -325,7 +325,7 @@ namespace CalamityMod.Projectiles.Melee
Main.spriteBatch.EnterShaderRegion();
GameShaders.Misc["CalamityMod:ArtAttack"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:ArtAttack"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
GameShaders.Misc["CalamityMod:ArtAttack"].Apply();
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(TrailWidth, TrailColor, (_) => Projectile.Size * 0.5f, shader: GameShaders.Misc["CalamityMod:ArtAttack"]), TrailLength);
+1 -1
View File
@@ -63,7 +63,7 @@ namespace CalamityMod.Projectiles.Melee
internal Color ColorFunction(float completionRatio) => new Color(91, 62, 153) * Projectile.Opacity;
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(WidthFunction, ColorFunction, (_) => Projectile.Size * 0.5f, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 8);
return true;
}
@@ -199,7 +199,7 @@ namespace CalamityMod.Projectiles.Melee
}
public bool JavelinPreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
// Not cloning the points causes the below operations to be applied to the original oldPos value by reference
// and thus causes it to be consistently added over and over, which is not intended behavior.
@@ -419,7 +419,7 @@ namespace CalamityMod.Projectiles.Melee
}
public bool YoyoPreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
Texture2D spearProjectile = Terraria.GameContent.TextureAssets.Projectile[Type].Value;
+1 -1
View File
@@ -110,7 +110,7 @@ namespace CalamityMod.Projectiles.Ranged
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
Vector2 overallOffset = Projectile.Size * 0.5f;
overallOffset += Projectile.velocity * 1.4f;
int numPoints = 46;
+1 -1
View File
@@ -219,7 +219,7 @@ namespace CalamityMod.Projectiles.Ranged
Vector2 rotationPoint = frame.Size() * 0.5f;
// 29FEB2024: Ozzatron: hopefully ported this correctly to the new prim system by Toasty
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(TrailWidthFunction, TrailColorFunction, (_) => Projectile.Size * 0.5f, smoothen: false, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 25);
Main.EntitySpriteDraw(texture, drawPosition, frame, drawColor, drawRotation, rotationPoint, Projectile.scale, SpriteEffects.None);
+1 -1
View File
@@ -171,7 +171,7 @@ namespace CalamityMod.Projectiles.Ranged
if (Time >= TimeToLaunch)
{
// 29FEB2024: Ozzatron: hopefully ported this correctly to the new prim system by Toasty
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(TrailWidthFunction, TrailColorFunction, (_) => Projectile.Size * 0.5f, smoothen: false, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 25);
}
+1 -1
View File
@@ -75,7 +75,7 @@ namespace CalamityMod.Projectiles.Ranged
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(WidthFunction, ColorFunction, (_) => Projectile.Size * 0.5f, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 20);
Texture2D glow = TextureAssets.Projectile[Type].Value;
Main.EntitySpriteDraw(glow, Projectile.Center - Main.screenPosition, null, Color.White, Projectile.rotation, glow.Size() * 0.5f, Projectile.scale, SpriteEffects.None);
+1 -1
View File
@@ -167,7 +167,7 @@ namespace CalamityMod.Projectiles.Ranged
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
Vector2 overallOffset = Projectile.Size * 0.5f;
overallOffset += Projectile.velocity * 1.4f;
int numPoints = 92;
+2 -2
View File
@@ -60,9 +60,9 @@ namespace CalamityMod.Projectiles.Summon
private Color PrimitiveColorFunction(float completionRatio) => Color.Lerp(Color.DarkGoldenrod, Color.LightGoldenrodYellow, completionRatio);
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch)
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch, PixelationPrimitiveLayer layer)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(PrimitiveWidthFunction, PrimitiveColorFunction, (_) => Projectile.Size * 0.5f, pixelate: true, shader: GameShaders.Misc["CalamityMod:TrailStreak"]));
}
}
+2 -2
View File
@@ -64,9 +64,9 @@ namespace CalamityMod.Projectiles.Summon
private Color PrimitiveColorFunction(float completionRatio) => Color.Lerp(Color.DarkGoldenrod, Color.LightGoldenrodYellow, completionRatio);
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch)
public void RenderPixelatedPrimitives(SpriteBatch spriteBatch, PixelationPrimitiveLayer layer)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(PrimitiveWidthFunction, PrimitiveColorFunction, (_) => Projectile.Size * 0.5f, pixelate: true, shader: GameShaders.Misc["CalamityMod:TrailStreak"]));
}
}
+1 -1
View File
@@ -83,7 +83,7 @@ namespace CalamityMod.Projectiles.Typeless
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(WidthFunction, ColorFunction, (_) => Projectile.Size * 0.5f, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 25);
Main.spriteBatch.EnterShaderRegion(BlendState.Additive);
@@ -60,7 +60,7 @@ namespace CalamityMod.Projectiles.Typeless
public override bool PreDraw(ref Color lightColor)
{
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/FabstaffStreak"));
GameShaders.Misc["CalamityMod:TrailStreak"].SetShaderTexture(ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/Trails/SylvestaffStreak"));
PrimitiveRenderer.RenderTrail(Projectile.oldPos, new(WidthFunction, ColorFunction, (_) => Projectile.Size * 0.5f, shader: GameShaders.Misc["CalamityMod:TrailStreak"]), 8);
Main.spriteBatch.EnterShaderRegion(BlendState.Additive);
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+31
View File
@@ -225,6 +225,37 @@ namespace CalamityMod
/// <param name="x">The input value.</param>
public static int DirectionalSign(this float x) => (x > 0f).ToDirectionInt();
/// <summary>
/// Approximates the derivative of a function at a given point based on a central-difference formula.
/// </summary>
/// <param name="fx">The function to take the derivative of.</param>
/// <param name="x">The value to evaluate the derivative at.</param>
public static double ApproximateDerivative(this Func<double, double> fx, double x)
{
double left = fx(x + 1e-7);
double right = fx(x - 1e-7);
return (left - right) * 5e6;
}
/// <summary>
/// Searches for an approximate for a root of a given function.
/// </summary>
/// <param name="fx">The function to find the root for.</param>
/// <param name="initialGuess">The initial guess for what the root could be.</param>
/// <param name="iterations">The amount of iterations to perform. The higher this is, the more generally accurate the result will be.</param>
public static double IterativelySearchForRoot(Func<double, double> fx, double initialGuess, int iterations)
{
double result = initialGuess;
for (int i = 0; i < iterations; i++)
{
double derivative = (float)fx.ApproximateDerivative(result);
result -= fx(result) / derivative;
}
return result;
}
public static List<Point> GetIntersectingPointsInLine(Point start, Point end)
{
List<Point> intersectingCells = [];