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 0000000000..82e6f14567 Binary files /dev/null and b/Effects/BasicPrimitiveShader.xnb differ 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 0000000000..77af90a54d Binary files /dev/null and b/Effects/FluidShaders.xnb differ diff --git a/ExtraTextures/Pixel.png b/ExtraTextures/Pixel.png new file mode 100644 index 0000000000..818c71d03f Binary files /dev/null and b/ExtraTextures/Pixel.png differ 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; } ///