From 063870af238b1b4248fc3b956f03b6264a100d56 Mon Sep 17 00:00:00 2001 From: DominicKarma <51094361+DominicKarma@users.noreply.github.com> Date: Mon, 16 May 2022 22:02:13 -0500 Subject: [PATCH] Created a fluid system --- CalamityMod.cs | 11 + Effects/BasicPrimitiveShader.fx | 56 +++++ Effects/BasicPrimitiveShader.xnb | Bin 0 -> 2020 bytes Effects/CalamityShaders.cs | 7 + Effects/FluidShaders.fx | 174 +++++++++++++++ Effects/FluidShaders.xnb | Bin 0 -> 7152 bytes ExtraTextures/Pixel.png | Bin 0 -> 119 bytes FluidSimulation/FieldVertex2D.cs | 26 +++ FluidSimulation/FluidField.cs | 333 +++++++++++++++++++++++++++++ FluidSimulation/PixelQueueValue.cs | 23 ++ ILEditing/MechanicILChanges.cs | 1 + Utilities/DrawingUtils.cs | 20 +- 12 files changed, 650 insertions(+), 1 deletion(-) create mode 100644 Effects/BasicPrimitiveShader.fx create mode 100644 Effects/BasicPrimitiveShader.xnb create mode 100644 Effects/FluidShaders.fx create mode 100644 Effects/FluidShaders.xnb create mode 100644 ExtraTextures/Pixel.png create mode 100644 FluidSimulation/FieldVertex2D.cs create mode 100644 FluidSimulation/FluidField.cs create mode 100644 FluidSimulation/PixelQueueValue.cs diff --git a/CalamityMod.cs b/CalamityMod.cs index a49ae6e3c7..d10fa7c0b6 100644 --- a/CalamityMod.cs +++ b/CalamityMod.cs @@ -7,6 +7,7 @@ using CalamityMod.Cooldowns; using CalamityMod.DataStructures; using CalamityMod.Effects; using CalamityMod.Events; +using CalamityMod.FluidSimulation; using CalamityMod.ILEditing; using CalamityMod.Items; using CalamityMod.Items.Dyes.HairDye; @@ -373,10 +374,20 @@ namespace CalamityMod #endregion #region Render Target Management + + public static FluidField GasThing = null; + public static void PrepareRenderTargets(GameTime gameTime) { FusableParticleManager.PrepareFusableParticleTargets(); DeathAshParticle.PrepareRenderTargets(); + + if (!Main.gameMenu) + { + if (GasThing is null || Main.GameUpdateCount % 300 == 0) + GasThing = new(205, 2f, 8f); + GasThing.Update(); + } } #endregion Render Target Management diff --git a/Effects/BasicPrimitiveShader.fx b/Effects/BasicPrimitiveShader.fx new file mode 100644 index 0000000000..3d1e36fe99 --- /dev/null +++ b/Effects/BasicPrimitiveShader.fx @@ -0,0 +1,56 @@ +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; + float2 TextureCoordinates : TEXCOORD0; +}; + +struct VertexShaderOutput +{ + float4 Position : SV_POSITION; + float4 Color : COLOR0; + float2 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 +{ + return input.Color; +} + +technique Technique1 +{ + pass TrailPass + { + VertexShader = compile vs_2_0 VertexShaderFunction(); + PixelShader = compile ps_2_0 PixelShaderFunction(); + } +} diff --git a/Effects/BasicPrimitiveShader.xnb b/Effects/BasicPrimitiveShader.xnb new file mode 100644 index 0000000000000000000000000000000000000000..82e6f145674eb8a974db90b99ccfbf9bbd737ae4 GIT binary patch literal 2020 zcmb_cF>ljQ5Po)ANNG_S05L?u5=)V)C=CfprB;HbKoJ3=Bq|w@D%W{wOr1D5Hl?UT zegH#(4jqtSV5n3E2F4Ek0Z1@*=)lmi1HYi*JKN8FidqS&Ty*yLoxk(Dcki6)lbMx4 z<={MH$~)z;X*hPruDi)`UUrtyfcR_tZon$Bg?Mm@L4Cu%&K z%4TmdGGz+Y{T%+YbIGT{MH%WH{fGtl0&WBFL_ni!9LRgv)R%aQ3C*48X#kEj6O3M` zz+FirVp52q9OmV1%XV0lvn2^m%Awl5GB@m2O?Os<2D{hZ-m65QI5zP2KHu62W!ywqjhE_y{KE{ z)BPgl70jiETlR~jn9!|Bx&1Zz`|{_jY`(#aiJWi$oD<9($rF?u8ugLYWZSomYh$jh6Y+;}eY0yJ-DEIF&{D*Wkj&0Hy@Ny#Q}WybJtM;yb{55{1OJlvA#hwe>jZF4;#FW*;%|YsB)$v0FYz2UU6IaXC&aYm*ASEZ zeYmGCVr%dZA>RbvkaS^~^pd)hC$2Q&9-TAN1IHhZzm_S>0~;W$*}8K0qI>#!8+DeS$q`uV7=EvG&HJ7 z;OA7FdW4#?QB9xdA!781YJq8+xTN6pa+-}fcolx)jBjsm$1p_$_=&wkdM11IANoPP z!FSMA&>O;-^{xtx|9YI9vP*q}e-60nb0y*fK35|i_jwH5?=u_4cpd~jXR+VV`91#& Di4_Qt literal 0 HcmV?d00001 diff --git a/Effects/CalamityShaders.cs b/Effects/CalamityShaders.cs index a91e9fb32a..b29209a490 100644 --- a/Effects/CalamityShaders.cs +++ b/Effects/CalamityShaders.cs @@ -33,12 +33,15 @@ namespace CalamityMod.Effects public static Effect CircularAoETelegraph; public static Effect IntersectionClipShader; public static Effect LocalLinearTransformationShader; + public static Effect BasicPrimitiveShader; public static Effect BaseFusableParticleEdgeShader; public static Effect AdditiveFusableParticleEdgeShader; public static Effect DoGPortalShader; + public static Effect FluidShaders; + public static void LoadShaders() { if (Main.dedServ) @@ -68,12 +71,15 @@ namespace CalamityMod.Effects CircularAoETelegraph = CalamityMod.Instance.Assets.Request("Effects/CircularAoETelegraph", AssetRequestMode.ImmediateLoad).Value; IntersectionClipShader = CalamityMod.Instance.Assets.Request("Effects/IntersectionClipShader", AssetRequestMode.ImmediateLoad).Value; LocalLinearTransformationShader = CalamityMod.Instance.Assets.Request("Effects/LocalLinearTransformationShader", AssetRequestMode.ImmediateLoad).Value; + BasicPrimitiveShader = CalamityMod.Instance.Assets.Request("Effects/BasicPrimitiveShader", AssetRequestMode.ImmediateLoad).Value; BaseFusableParticleEdgeShader = CalamityMod.Instance.Assets.Request("Effects/ParticleFusion/BaseFusableParticleEdgeShader", AssetRequestMode.ImmediateLoad).Value; AdditiveFusableParticleEdgeShader = CalamityMod.Instance.Assets.Request("Effects/ParticleFusion/AdditiveFusableParticleEdgeShader", AssetRequestMode.ImmediateLoad).Value; DoGPortalShader = CalamityMod.Instance.Assets.Request("Effects/ScreenShaders/DoGPortalShader", AssetRequestMode.ImmediateLoad).Value; + FluidShaders = CalamityMod.Instance.Assets.Request("Effects/FluidShaders", AssetRequestMode.ImmediateLoad).Value; + Filters.Scene["CalamityMod:Astral"] = new Filter(new AstralScreenShaderData(new Ref(AstralFogShader), "AstralPass").UseColor(0.18f, 0.08f, 0.24f), EffectPriority.VeryHigh); Filters.Scene["CalamityMod:LightBurst"] = new Filter(new ScreenShaderData(new Ref(LightShader), "BurstPass"), EffectPriority.VeryHigh); @@ -100,6 +106,7 @@ namespace CalamityMod.Effects GameShaders.Misc["CalamityMod:CircularAoETelegraph"] = new MiscShaderData(new Ref(CircularAoETelegraph), "TelegraphPass"); GameShaders.Misc["CalamityMod:IntersectionClip"] = new MiscShaderData(new Ref(IntersectionClipShader), "ClipPass"); GameShaders.Misc["CalamityMod:LinearTransformation"] = new MiscShaderData(new Ref(LocalLinearTransformationShader), "TransformationPass"); + GameShaders.Misc["CalamityMod:PrimitiveDrawer"] = new MiscShaderData(new Ref(BasicPrimitiveShader), "TrailPass"); GameShaders.Misc["CalamityMod:BaseFusableParticleEdge"] = new MiscShaderData(new Ref(BaseFusableParticleEdgeShader), "ParticlePass"); GameShaders.Misc["CalamityMod:AdditiveFusableParticleEdge"] = new MiscShaderData(new Ref(AdditiveFusableParticleEdgeShader), "ParticlePass"); diff --git a/Effects/FluidShaders.fx b/Effects/FluidShaders.fx new file mode 100644 index 0000000000..d96fac6f20 --- /dev/null +++ b/Effects/FluidShaders.fx @@ -0,0 +1,174 @@ +sampler nextStates : register(s0); +sampler previousStates : register(s1); +sampler horizontalSpeeds : register(s2); +sampler verticalSpeeds : register(s3); +sampler divergencePBuffer : register(s4); +sampler redField : register(s5); +sampler greenField : register(s6); +sampler blueField : register(s7); + +bool horizontalCase_Divergence; +float size; +float diffusionFactor; +float deltaTime; + +float round(float n, float precision) +{ + return floor(n / precision) * precision; +} + +float2 round(float2 n, float precision) +{ + return float2(round(n.x, precision), round(n.y, precision)); +} + +float4 CalculateDiffusion(float4 sampleColor : TEXCOORD, float2 coords : TEXCOORD0) : COLOR0 +{ + // A naive way of diffusing values would be to linearly interpolate between the old and new state like so: + // nextField[i, j] = currentField[i, j] + diffusionFactor * (totalCardinalState - currentField[i, j]) + // However, this would considerably restrict the freedom of the simulation, as any visocity values above 1 would result + // in overshooting estimations and cause unstable behavior. + // Instead of doing this instead of using the current state to calculate the next one, we attempt to solve for a state that when + // done in reverse returns the original state. Mathematically, this is written like so: + + // currentField[i, j] = nextField[i, j] - diffusionFactor * (averageNextCardinalState - currentField[i, j]) + + // Rearranged such that nextField[i, j] is the given value, this results in the following equation: + // nextField[i, j] = (currentField[i, j] + diffusionFactor * averageNextCardinalState) / (diffusionFactor + 1f) + + // This equation is hyperbolic instead of linear, and will converge in a way that allows for arbitrarily large viscosities. + // However, as you may have noticed, this equation seeks averageNextCardinalState, which is not known. Fortunately, enough + // variables are known to find this via a system of equations. In this case, the Gauss-Seidel Method is utilized as an iterative + // solver + float step = 1.0 / size; + float4 currentValue = 0; + float4 previousValue = tex2D(previousStates, coords); + for (int i = 0; i < 4; i++) + { + float leftState = tex2D(nextStates, clamp(coords - float2(step, 0), step, 1 - step)); + float rightState = tex2D(nextStates, clamp(coords + float2(step, 0), step, 1 - step)); + float upState = tex2D(nextStates, clamp(coords - float2(0, step), step, 1 - step)); + float downState = tex2D(nextStates, clamp(coords + float2(0, step), step, 1 - step)); + float totalCardinalStateIteration = leftState + rightState + upState + downState; + currentValue = (previousValue + diffusionFactor * totalCardinalStateIteration) / (diffusionFactor * 4 + 1); + } + return currentValue; +} + +// TODO -- Discuss the details of this function a bit more. +float4 CalculateAdvection(float4 sampleColor : TEXCOORD, float2 coords : TEXCOORD0) : COLOR0 +{ + float step = 1.0 / size; + float2 roundedCoords = clamp(round(coords, step), step, 1 - step); + + float color; + float xSpeed = tex2D(horizontalSpeeds, roundedCoords).r; + float ySpeed = tex2D(verticalSpeeds, roundedCoords).r; + + if (coords.x <= step * 4 || coords.x >= 1 - step * 4) + xSpeed = 0; + + if (coords.y <= step * 4 || coords.y >= 1 - step * 4) + ySpeed = 0; + + float viscosity = deltaTime * size; + float X = clamp(roundedCoords.x - (viscosity * xSpeed) * step, step, 1 - step); + float Y = clamp(roundedCoords.y - (viscosity * ySpeed) * step, step, 1 - step); + + X = clamp(X, 0, 1 - step); + Y = clamp(Y, 0, 1 - step); + + float xGrid = round(X, step); + float xGrid1 = xGrid + step; + float YGrid = round(Y, step); + float yGrid = YGrid + step; + + xGrid = clamp(xGrid, 0, 1); + YGrid = clamp(YGrid, 0, 1); + xGrid1 = clamp(xGrid1, 0, 1); + yGrid = clamp(yGrid, 0, 1); + + float XRelative1 = (X - xGrid) / step; + float XRelative0 = 1 - XRelative1; + float YRelative1 = (Y - YGrid) / step; + float YRelative0 = 1 - YRelative1; + + float c1 = tex2D(previousStates, float2(xGrid, YGrid)).r; + float c2 = tex2D(previousStates, float2(xGrid, yGrid)).r; + float c3 = tex2D(previousStates, float2(xGrid1, YGrid)).r; + float c4 = tex2D(previousStates, float2(xGrid1, yGrid)).r; + + return XRelative0 * (YRelative0 * c1 + YRelative1 * c2) + + XRelative1 * (YRelative0 * c3 + YRelative1 * c4); +} + +// This should be applied twice to each velocity axis buffer. +float4 ClearDivergence(float4 sampleColor : TEXCOORD, float2 coords : TEXCOORD0) : COLOR0 +{ + float step = 1.0 / size; + float2 originalVelocity = float2(tex2D(horizontalSpeeds, coords).r, tex2D(verticalSpeeds, coords).r); + if (horizontalCase_Divergence) + { + float rightPValue = tex2D(divergencePBuffer, clamp(coords + float2(step, 0), step, 1 - step)); + float leftPValue = tex2D(divergencePBuffer, clamp(coords - float2(step, 0), step, 1 - step)); + return float4(originalVelocity.x, 0, 0, 0); + } + float upPValue = tex2D(divergencePBuffer, clamp(coords - float2(0, step), step, 1 - step)); + float downPValue = tex2D(divergencePBuffer, clamp(coords + float2(0, step), step, 1 - step)); + return float4(originalVelocity.y, 0, 0, 0); +} + +// According to the Navier-Stokes continuity equation, the divergence of the field is always zero, as anything else implies that matter is either being +// created from nothing or being destroyed. However, prior calculations may introduce divergence to the field. As such, this method exists as a means +// of clearing away the divergence in the field. +// According to Helmholtz's Theorem, any sufficiently smooth vector field can be expressed as the sum of two fields; one that is irrotational, and one that is solenoidal. +// This decomposition is used to get rid of the divergence part. +float4 PerformPoissonIteration(float4 sampleColor : TEXCOORD, float2 coords : TEXCOORD0) : COLOR0 +{ + float step = 1.0 / size; + float rightHorizontalSpeed = tex2D(horizontalSpeeds, clamp(coords + float2(step, 0), step, 1 - step)); + float leftHorizontalSpeed = tex2D(horizontalSpeeds, clamp(coords - float2(step, 0), step, 1 - step)); + float upVerticalSpeed = tex2D(verticalSpeeds, clamp(coords - float2(0, step), step, 1 - step)); + float downVerticalSpeed = tex2D(verticalSpeeds, clamp(coords + float2(0, step), step, 1 - step)); + float divergence = -step * (rightHorizontalSpeed - leftHorizontalSpeed + downVerticalSpeed - upVerticalSpeed) * 0.5; + + float rightPValue = tex2D(previousStates, clamp(coords + float2(step, 0), step, 1 - step)); + float leftPValue = tex2D(previousStates, clamp(coords - float2(step, 0), step, 1 - step)); + float upPValue = tex2D(previousStates, clamp(coords - float2(0, step), step, 1 - step)); + float downPValue = tex2D(previousStates, clamp(coords + float2(0, step), step, 1 - step)); + return (divergence + rightPValue + leftPValue + upPValue + downPValue) / 4; +} + +float4 DrawField(float4 sampleColor : TEXCOORD, float2 coords : TEXCOORD0) : COLOR0 +{ + float density = tex2D(nextStates, coords).r; + return float4(tex2D(redField, coords).r, tex2D(greenField, coords).r, tex2D(blueField, coords).r, 1) * density; +} + +technique Technique1 +{ + pass DiffusionPass + { + PixelShader = compile ps_3_0 CalculateDiffusion(); + } + + pass AdvectionPass + { + PixelShader = compile ps_3_0 CalculateAdvection(); + } + + pass ClearDivergencePass + { + PixelShader = compile ps_3_0 ClearDivergence(); + } + + pass PerformPoissonIterationPass + { + PixelShader = compile ps_3_0 PerformPoissonIteration(); + } + + pass DrawFluidPass + { + PixelShader = compile ps_3_0 DrawField(); + } +} \ No newline at end of file diff --git a/Effects/FluidShaders.xnb b/Effects/FluidShaders.xnb new file mode 100644 index 0000000000000000000000000000000000000000..77af90a54ddc661d9178b01c521a361a2cfe408e GIT binary patch literal 7152 zcmcgwOKcm*8UA-kQF1L?8t?4aOz03YNJY_SW+RN0UVlKMMP+l zU6QsM_^<+U5Rd>-&>nqQp*_hx^pFBM_)wrZ7^s07$R&py0)z(}NCF*t@F5`keKR|| z!xa@f4|k;D{;&C8^Y~|X<+n4}hn(FXi#YE&FIP%_y;)yvO|I06lXHIYs&~EazcD#m zueH2dYx4Z+s#j`V@``28pUCeg{cFG2SgVwp6ZzkHezQ`qot>VX;@?Dmwq0$teeZ0| zYq$Jjbt1pezEZ7}e&hXdss4snJ9}pORB83h74Kx(J3V#!^z*{zT!44~Ik1uu0Z;AuU7IFX4;qzA2cKX6@{#J z0I=_s=PF*cOtO)C*0F>DG7qo&o>z+`jof@nj`S$Qt5&o9Q7n6E+Ol>dJ5`dqbLDMvnW&X>H>TCMVjws%rw6gcDO z8q1;6hok7GO#nD&5Ik4Vs}{Zq_@;%w5BQFScK|=M@KG4c(_qx50bj82R{^hE_)Wkc zSoj^l9Si>o@KI}?k4B4&IVnVRivKCHHwD@RdSd|ZRnS(@Zw}yXg7y~r-2uE0KzkoO z8`-w)?SlS!G=@I0F~>bLh2ZDE9FXbty1hA>U3zJT^Zgl_pi!1MTK*IKF!vc5#+*GZ z>!hM_4laTr! z<~dcr_VB;$Tz7j7S-5n5(Q#Miy1i%PJp3NMlZM>uJUEhP4tPJ{#FKso{Q|nGABc&O z+iM!EzSdg*=4-Lr8-;(17i~qfZyNnzvuWMlVVRx3xHO_!kMX`&s{%fubv{kHC5jIm|x(^ki_)d~7-aT@%gvaNL|wzb{|Doz)1 zBgFxJpi?#sjwkdlTX}jA=gGuE-;F$F0dGJDRH^wQ4xbFZOn*0YUJZYTd8V8igZl?% zVw^tNIAT<|(y7i;%JxEYmO@Y8S<1VDK1*lfGvp(X(q}1aAZtKXKL_p0^jG-+nqc#>_8d`sR0Y7z9--UykP&M~|Xq z@ixaURdiD;1Hf!s=(;-OBqRZicO_SNN5Z`m{SNxa=w{CE17>@iIZVAf?x~ND zTce)TTIlxvVb$5GIEQZ|KGs?8CzV6g*-gL&bnXV`W&!;*^aeWRNLxpL4Ly0cdUXBW zF9+XOUB+1vH~PqC)4IK5sxFUe*7xvh>h}1#w6bn*Mb&M-pMUqdy?DMa;D>l4Ty1mDOKXT7I=Koj}`(X^|bJ2X>^7PaWEigm3IZUjR7N zG3xgw#%O$UWLez_TzN|Q2>Fnm<6YcKXp1|V6@$8)L@_9vwAaT^VodnPF7G~oRg750(7zMSV^+bi6~%Zo!X*^QbG$3r zfbs%d$9M!|cj9?;<#TmUn}ICvU9Q}Zao!A)?RkOeSJMCYr zT6;3i$GdPaU2ER~t$=Q7?GoTJI`5^}J1VXl5$&7C{-ol*3lx@ODT^_Ys&dX+InPxLZAtvC4=U}%&lZv;JEBXNF& z*wTG9a!P+^+ciF6m}-M+r~RFcb(Ck0`JTozhvyk~VE_do^x=Hr`!(xO@{X(DB~@+O zc16EWQ!WFTILETKV83&0=;9sMoP`d~Hhx>9Zv8&3bcd{|r0Ms0tveg(Ht+bvjc%Mf zN;lvAsav0`;6t~zt@$o$H~Hqff#JK6Z;t5qZQ9_uOTMdo*YDTx33SHd@(G*jo!PF1 t$c^Bi@vC|OANj5y=au6^o!2qQE{8u=$3bV;&?x^L0wd0InlbTw{vTWY^-TZ( literal 0 HcmV?d00001 diff --git a/ExtraTextures/Pixel.png b/ExtraTextures/Pixel.png new file mode 100644 index 0000000000000000000000000000000000000000..818c71d03f435db011069584cda25c1f66af1a85 GIT binary patch literal 119 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx1SBVv2j2s6ii6yp7}lMWc?smOq&xaLGB9lH z=l+w(3gmMZctjR6Fz_7)VaDV6D^h@hJf1F&Arj%qKmPx>XJGxu^l!OoV+&B6!PC{x JWt~$(69DNq9##MV literal 0 HcmV?d00001 diff --git a/FluidSimulation/FieldVertex2D.cs b/FluidSimulation/FieldVertex2D.cs new file mode 100644 index 0000000000..aca2e9645e --- /dev/null +++ b/FluidSimulation/FieldVertex2D.cs @@ -0,0 +1,26 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; + +namespace CalamityMod.FluidSimulation +{ + public struct FieldVertex2D : IVertexType + { + public Vector2 Position; + public Vector4 Color; + public Vector2 TextureCoordinates; + public VertexDeclaration VertexDeclaration => _vertexDeclaration; + + private static readonly VertexDeclaration _vertexDeclaration = new(new VertexElement[] + { + new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.Position, 0), + new VertexElement(8, VertexElementFormat.Vector4, VertexElementUsage.Color, 0), + new VertexElement(24, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0), + }); + public FieldVertex2D(Vector2 position, Vector4 color, Vector2 textureCoordinates) + { + Position = position; + Color = color; + TextureCoordinates = textureCoordinates; + } + } +} diff --git a/FluidSimulation/FluidField.cs b/FluidSimulation/FluidField.cs new file mode 100644 index 0000000000..d7d80e19a4 --- /dev/null +++ b/FluidSimulation/FluidField.cs @@ -0,0 +1,333 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CalamityMod.Effects; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.FluidSimulation +{ + public class FluidField + { + // TODO -- Try to make all of these specialized data structures. + internal RenderTarget2D TemporaryAuxilaryTarget; + + internal RenderTarget2D HorizontalFieldSpeed; + + internal RenderTarget2D VerticalFieldSpeed; + + internal RenderTarget2D DensityField; + + internal RenderTarget2D RedField; + + internal RenderTarget2D BlueField; + + internal RenderTarget2D GreenField; + + internal RenderTarget2D PreviousHorizontalFieldSpeed; + + internal RenderTarget2D PreviousVerticalFieldSpeed; + + internal RenderTarget2D PreviousDensityField; + + internal RenderTarget2D PreviousRedField; + + internal RenderTarget2D PreviousBlueField; + + internal RenderTarget2D PreviousGreenField; + + internal Queue DensityQueue = new(); + + internal Queue HorizontalSpeedQueue = new(); + + internal Queue VerticalSpeedQueue = new(); + + internal Queue RedFieldQueue = new(); + + internal Queue GreenFieldQueue = new(); + + internal Queue BlueFieldQueue = new(); + + public int Size; + + public float Viscosity; + + public float DiffusionFactor; + + public const float DeltaTime = 0.016666f; + + public const int GaussSeidelIterations = 8; + + internal static BasicEffect basicShader = null; + + public static BasicEffect BasicShader + { + get + { + if (Main.netMode != NetmodeID.Server && basicShader is null) + { + basicShader = new BasicEffect(Main.instance.GraphicsDevice) + { + VertexColorEnabled = true, + TextureEnabled = true + }; + } + return basicShader; + } + } + + public FluidField(int size, float viscosity, float diffusionFactor) + { + Size = size; + Viscosity = viscosity; + DiffusionFactor = diffusionFactor; + + HorizontalFieldSpeed = new(Main.instance.GraphicsDevice, Size, Size, false, SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + VerticalFieldSpeed = new(Main.instance.GraphicsDevice, Size, Size, false, SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + DensityField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + RedField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + GreenField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + BlueField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + + PreviousHorizontalFieldSpeed = new(Main.instance.GraphicsDevice, Size, Size, false, SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + PreviousVerticalFieldSpeed = new(Main.instance.GraphicsDevice, Size, Size, false, SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + PreviousDensityField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + PreviousRedField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + PreviousGreenField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + PreviousBlueField = new(Main.instance.GraphicsDevice, Size, Size, false, 0, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + + // A surface format of Vector4 is used here to allow for both 0-1 ranged colors and other things at the same time. + TemporaryAuxilaryTarget = new(Main.instance.GraphicsDevice, Size, Size, false, SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + } + + public void ApplyThingToTarget(RenderTarget2D currentField, Action shaderPreparationsAction) + { + Main.instance.GraphicsDevice.SetRenderTarget(TemporaryAuxilaryTarget); + Main.instance.GraphicsDevice.Clear(Color.Transparent); + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + + shaderPreparationsAction(); + Main.spriteBatch.Draw(currentField, currentField.Bounds, Color.White); + Main.spriteBatch.End(); + + currentField.CopyContentsFrom(TemporaryAuxilaryTarget); + Main.instance.GraphicsDevice.SetRenderTarget(null); + } + + public void FlushQueueToTarget(RenderTarget2D currentField, Queue queue) + { + ApplyThingToTarget(currentField, () => + { + int batchIndex = 0; + int pixelCount = queue.Count; + + // Get the FUCK out of here if the queue is empty. If this check isn't here the primitive drawing method will attempt to access + // memory that it shouldn't and the OS will tell the program to go fuck itself, resulting in a crash. + Texture2D pixel = ModContent.Request("CalamityMod/ExtraTextures/Pixel").Value; + if (pixelCount <= 0) + return; + + CalamityUtils.CalculatePerspectiveMatricies(out Matrix viewMatrix, out Matrix projectionMatrix); + BasicShader.View = viewMatrix; + BasicShader.Projection = projectionMatrix; + + // Go through all particles and draw them directly with primitives. + BasicShader.CurrentTechnique.Passes[0].Apply(); + + // Decide the vertices and indices. + FieldVertex2D[] vertices = new FieldVertex2D[pixelCount * 4]; + short[] indices = new short[pixelCount * 6]; + + // Go through the queue and prepare the vertices/indices. + while (queue.TryDequeue(out PixelQueueValue v)) + { + Color value = new(v.Value.X, v.Value.Y, v.Value.Z, v.Value.W); + Vector2 topLeft = v.Position; + Vector2 topRight = v.Position + Vector2.UnitX; + Vector2 bottomLeft = v.Position + Vector2.UnitY; + Vector2 bottomRight = v.Position + Vector2.One; + + vertices[batchIndex * 4] = new FieldVertex2D(topLeft, v.Value, new Vector2(0f, 0f)); + vertices[batchIndex * 4 + 1] = new FieldVertex2D(topRight, v.Value, new Vector2(1f, 0f)); + vertices[batchIndex * 4 + 2] = new FieldVertex2D(bottomRight, v.Value, new Vector2(1f, 1f)); + vertices[batchIndex * 4 + 3] = new FieldVertex2D(bottomLeft, v.Value, new Vector2(0f, 1f)); + + // Construct independent primitives by creating a square from two triangles defined by the edges of the particle. + indices[batchIndex * 6] = (short)(batchIndex * 4); + indices[batchIndex * 6 + 1] = (short)(batchIndex * 4 + 1); + indices[batchIndex * 6 + 2] = (short)(batchIndex * 4 + 2); + indices[batchIndex * 6 + 3] = (short)(batchIndex * 4); + indices[batchIndex * 6 + 4] = (short)(batchIndex * 4 + 2); + indices[batchIndex * 6 + 5] = (short)(batchIndex * 4 + 3); + batchIndex++; + + // I don't know why this is necessary to make the primitives render, but it is. + Main.spriteBatch.Draw(pixel, Vector2.Zero, null, Color.Transparent); + } + + // Flush the vertices and indices and draw them to the render target. + Main.instance.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, pixelCount * 4, indices, 0, pixelCount * 2); + }); + } + + public void CalculateDiffusion(float diffusionFactor, RenderTarget2D currentField, RenderTarget2D nextField, bool clamp = false) + { + diffusionFactor *= DeltaTime * Size; + ApplyThingToTarget(nextField, () => + { + Main.instance.GraphicsDevice.Textures[1] = currentField; + CalamityShaders.FluidShaders.Parameters["size"].SetValue(Size); + CalamityShaders.FluidShaders.Parameters["diffusionFactor"].SetValue(diffusionFactor); + CalamityShaders.FluidShaders.CurrentTechnique.Passes["DiffusionPass"].Apply(); + }); + } + + public void CalculateAdvection(RenderTarget2D currentField, RenderTarget2D nextField, RenderTarget2D horizontalVelocities, RenderTarget2D verticalVelocities) + { + ApplyThingToTarget(nextField, () => + { + Main.instance.GraphicsDevice.Textures[1] = currentField; + Main.instance.GraphicsDevice.Textures[2] = horizontalVelocities; + Main.instance.GraphicsDevice.Textures[3] = verticalVelocities; + CalamityShaders.FluidShaders.Parameters["size"].SetValue(Size); + CalamityShaders.FluidShaders.Parameters["deltaTime"].SetValue(DeltaTime); + CalamityShaders.FluidShaders.CurrentTechnique.Passes["AdvectionPass"].Apply(); + }); + } + + public void ClearDivergence(RenderTarget2D horizontalVelocities, RenderTarget2D verticalVelocities, RenderTarget2D p) + { + for (int i = 0; i < GaussSeidelIterations; i++) + { + ApplyThingToTarget(p, () => + { + Main.instance.GraphicsDevice.Textures[1] = p; + Main.instance.GraphicsDevice.Textures[2] = horizontalVelocities; + Main.instance.GraphicsDevice.Textures[3] = verticalVelocities; + CalamityShaders.FluidShaders.Parameters["size"].SetValue(Size); + CalamityShaders.FluidShaders.CurrentTechnique.Passes["PerformPoissonIterationPass"].Apply(); + }); + } + + ApplyThingToTarget(horizontalVelocities, () => + { + Main.instance.GraphicsDevice.Textures[1] = horizontalVelocities; + Main.instance.GraphicsDevice.Textures[2] = horizontalVelocities; + Main.instance.GraphicsDevice.Textures[3] = verticalVelocities; + Main.instance.GraphicsDevice.Textures[4] = p; + CalamityShaders.FluidShaders.Parameters["horizontalCase_Divergence"].SetValue(true); + CalamityShaders.FluidShaders.CurrentTechnique.Passes["ClearDivergencePass"].Apply(); + }); + + ApplyThingToTarget(verticalVelocities, () => + { + Main.instance.GraphicsDevice.Textures[1] = verticalVelocities; + Main.instance.GraphicsDevice.Textures[2] = horizontalVelocities; + Main.instance.GraphicsDevice.Textures[3] = verticalVelocities; + Main.instance.GraphicsDevice.Textures[4] = p; + CalamityShaders.FluidShaders.Parameters["horizontalCase_Divergence"].SetValue(false); + CalamityShaders.FluidShaders.CurrentTechnique.Passes["ClearDivergencePass"].Apply(); + }); + } + + public void CreateSource(int x, int y, float density, Color color, Vector2 velocity) + { + Vector2 pos = new(x, y); + + if (x < 0 || y < 0 || x >= Size || y >= Size) + return; + + RedFieldQueue.Enqueue(new PixelQueueValue(pos, new Color(color.R / 255f, 0f, 0f))); + GreenFieldQueue.Enqueue(new PixelQueueValue(pos, new Color(color.G / 255f, 0f, 0f))); + BlueFieldQueue.Enqueue(new PixelQueueValue(pos, new Color(color.B / 255f, 0f, 0f))); + + HorizontalSpeedQueue.Enqueue(new(pos, new Vector4(velocity.X, 0f, 0f, 0f))); + VerticalSpeedQueue.Enqueue(new(pos, new Vector4(velocity.Y, 0f, 0f, 0f))); + + DensityQueue.Enqueue(new PixelQueueValue(pos, new Color(density, 0f, 0f))); + } + + public void Update() + { + // Everything here involves heavy manipulation of render targets to work. Doing any of that on the server + // would certainly result in a crash due to a lack of a graphics device. + if (Main.netMode == NetmodeID.Server) + return; + + // Create a constant stream of fluid. + Color sprayColor = Color.Lerp(Color.Red, Color.Yellow, (float)Math.Sin(Main.GlobalTimeWrappedHourly * 2f) * 0.5f + 0.5f); + Vector2 sprayVelocity = (Main.GlobalTimeWrappedHourly * 1.6f).ToRotationVector2() * 0.2f; + + int x = (int)((Main.MouseScreen.X - Main.screenWidth * 0.2f) / 2f); + int y = (int)((Main.MouseScreen.Y - Main.screenHeight * 0.2f) / 2f); + for (int dx = -3; dx <= 3; dx++) + { + for (int dy = -3; dy <= 3; dy++) + CreateSource(x + dx, y + dy, 1f, sprayColor, sprayVelocity); + } + + // Clear queues. + FlushQueueToTarget(HorizontalFieldSpeed, HorizontalSpeedQueue); + FlushQueueToTarget(VerticalFieldSpeed, VerticalSpeedQueue); + FlushQueueToTarget(RedField, RedFieldQueue); + FlushQueueToTarget(GreenField, GreenFieldQueue); + FlushQueueToTarget(BlueField, BlueFieldQueue); + FlushQueueToTarget(DensityField, DensityQueue); + + UpdateVelocityFields(); + UpdateDensityFields(); + } + + public void UpdateVelocityFields() + { + Utils.Swap(ref PreviousHorizontalFieldSpeed, ref HorizontalFieldSpeed); + CalculateDiffusion(Viscosity, HorizontalFieldSpeed, PreviousHorizontalFieldSpeed); + Utils.Swap(ref PreviousVerticalFieldSpeed, ref VerticalFieldSpeed); + CalculateDiffusion(Viscosity, VerticalFieldSpeed, PreviousVerticalFieldSpeed); + + ClearDivergence(HorizontalFieldSpeed, VerticalFieldSpeed, PreviousHorizontalFieldSpeed); + + Utils.Swap(ref PreviousHorizontalFieldSpeed, ref HorizontalFieldSpeed); + Utils.Swap(ref PreviousVerticalFieldSpeed, ref VerticalFieldSpeed); + + CalculateAdvection(HorizontalFieldSpeed, PreviousHorizontalFieldSpeed, PreviousHorizontalFieldSpeed, PreviousVerticalFieldSpeed); + CalculateAdvection(VerticalFieldSpeed, PreviousVerticalFieldSpeed, PreviousHorizontalFieldSpeed, PreviousVerticalFieldSpeed); + + ClearDivergence(HorizontalFieldSpeed, VerticalFieldSpeed, PreviousHorizontalFieldSpeed); + } + + public void UpdateDensityFields() + { + Utils.Swap(ref PreviousDensityField, ref DensityField); + CalculateDiffusion(DiffusionFactor, DensityField, PreviousDensityField, true); + CalculateAdvection(PreviousDensityField, DensityField, HorizontalFieldSpeed, VerticalFieldSpeed); + + Utils.Swap(ref PreviousRedField, ref RedField); + CalculateDiffusion(DiffusionFactor, RedField, PreviousRedField, true); + CalculateAdvection(PreviousRedField, RedField, HorizontalFieldSpeed, VerticalFieldSpeed); + + Utils.Swap(ref PreviousGreenField, ref GreenField); + CalculateDiffusion(DiffusionFactor, GreenField, PreviousGreenField, true); + CalculateAdvection(PreviousGreenField, GreenField, HorizontalFieldSpeed, VerticalFieldSpeed); + + Utils.Swap(ref PreviousBlueField, ref BlueField); + CalculateDiffusion(DiffusionFactor, BlueField, PreviousBlueField, true); + CalculateAdvection(PreviousBlueField, BlueField, HorizontalFieldSpeed, VerticalFieldSpeed); + } + + public void Draw() + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + Main.instance.GraphicsDevice.Textures[5] = RedField; + Main.instance.GraphicsDevice.Textures[6] = GreenField; + Main.instance.GraphicsDevice.Textures[7] = BlueField; + CalamityShaders.FluidShaders.CurrentTechnique.Passes["DrawFluidPass"].Apply(); + Main.spriteBatch.Draw(DensityField, new Vector2(Main.screenWidth, Main.screenHeight) * 0.2f, null, Color.White, 0f, Vector2.Zero, 2f, 0, 0f); + Main.spriteBatch.End(); + } + } +} diff --git a/FluidSimulation/PixelQueueValue.cs b/FluidSimulation/PixelQueueValue.cs new file mode 100644 index 0000000000..6d0872bb88 --- /dev/null +++ b/FluidSimulation/PixelQueueValue.cs @@ -0,0 +1,23 @@ +using Microsoft.Xna.Framework; + +namespace CalamityMod.FluidSimulation +{ + public struct PixelQueueValue + { + public Vector2 Position; + + public Vector4 Value; + + public PixelQueueValue(Vector2 p, Color v) + { + Position = p; + Value = v.ToVector4(); + } + + public PixelQueueValue(Vector2 p, Vector4 v) + { + Position = p; + Value = v; + } + } +} diff --git a/ILEditing/MechanicILChanges.cs b/ILEditing/MechanicILChanges.cs index c5a0b87511..6bc4ce7408 100644 --- a/ILEditing/MechanicILChanges.cs +++ b/ILEditing/MechanicILChanges.cs @@ -460,6 +460,7 @@ namespace CalamityMod.ILEditing { GeneralParticleHandler.DrawAllParticles(Main.spriteBatch); DeathAshParticle.DrawAll(); + CalamityMod.GasThing?.Draw(); orig(self, gameTime); } diff --git a/Utilities/DrawingUtils.cs b/Utilities/DrawingUtils.cs index 29cf6538ca..d48d240045 100644 --- a/Utilities/DrawingUtils.cs +++ b/Utilities/DrawingUtils.cs @@ -229,6 +229,23 @@ namespace CalamityMod return true; } + /// + /// Copies the contents of one render target to another. + /// + public static void CopyContentsFrom(this RenderTarget2D to, RenderTarget2D from) + { + Main.instance.GraphicsDevice.SetRenderTarget(to); + Main.instance.GraphicsDevice.Clear(Color.Transparent); + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + Main.spriteBatch.Draw(from, from.Bounds, Color.White); + Main.spriteBatch.End(); + + Main.instance.GraphicsDevice.SetRenderTarget(from); + Main.instance.GraphicsDevice.Clear(Color.Transparent); + Main.instance.GraphicsDevice.SetRenderTarget(null); + } + /// /// Calculates perspective matrices for usage by vertex shaders. /// @@ -240,6 +257,7 @@ namespace CalamityMod Matrix zoomScaleMatrix = Matrix.CreateScale(zoom.X, zoom.Y, 1f); // Screen bounds. + int width = Main.instance.GraphicsDevice.Viewport.Width; int height = Main.instance.GraphicsDevice.Viewport.Height; // Get a matrix that aims towards the Z axis (these calculations are relative to a 2D world). @@ -258,7 +276,7 @@ namespace CalamityMod // And account for the current zoom. viewMatrix *= zoomScaleMatrix; - projectionMatrix = Matrix.CreateOrthographicOffCenter(0f, Main.screenWidth * zoom.X, 0f, Main.screenHeight * zoom.Y, 0f, 1f) * zoomScaleMatrix; + projectionMatrix = Matrix.CreateOrthographicOffCenter(0f, width * zoom.X, 0f, height * zoom.Y, 0f, 1f) * zoomScaleMatrix; } ///