Certainly! Let's enhance your code to improve the spawning of PBF particles, ensuring they work seamlessly with your existing simulation, and blacklist them in the raycast for the terrain heightmap.
Below are the modifications and additions to your code:
-
Improve the spawning condition in the if statement: We'll make the condition more precise by considering both the total flux and the average depth difference with neighboring cells. This will ensure particles are spawned in areas with significant fluid movement and depth variations, which is more accurate.
-
Spawn PBF particles with appropriate initial velocities: We'll create particles representing PBF fluid particles, assign them initial velocities based on the fluxes, and ensure they integrate well with the existing simulation.
-
Manage particle generation and deletion: We'll prevent spawning multiple particles in the same location in quick succession using a cooldown mechanism. Additionally, we'll set up particles to be deleted automatically after a certain duration.
-
Blacklist particles in the raycast: We'll add the particles folder to the raycastParams.FilterDescendantsInstances to prevent them from interfering with the terrain heightmap generation.
Modified Code:
Main Simulation Script Modifications:
First, update the generateTerrainHeightmap function to include sphParticleFolder in the raycastParams blacklist:
-- Function to generate the terrain heightmap using raycasts
local function generateTerrainHeightmap(sim, raycastParams)
local heightmap = {}
local basePosition = sim.position
local cellSize = sim.cellSize
local maxTerrainHeight = 1000 -- Adjust based on your terrain
local direction = Vector3.new(0, -maxTerrainHeight - 100, 0)
for x = 1, sim.texSize do
heightmap[x] = {}
local worldX = basePosition.X + (x - 0.5) * cellSize
for y = 1, sim.texSize do
local worldZ = basePosition.Z + (y - 0.5) * cellSize
local origin = Vector3.new(worldX, maxTerrainHeight, worldZ)
local raycastResult = Workspace:Raycast(origin, direction, raycastParams)
local height = 0
if raycastResult then
height = raycastResult.Position.Y
else
-- No hit, set to base level
height = 0
end
heightmap[x][y] = height
end
end
return heightmap
end
Next, adjust the initialization to include sphParticleFolder in the raycast parameters:
-- Initialize raycast parameters
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {visualizationFolder, sphParticleFolder}
raycastParams.IgnoreWater = false
Update the initial heightmap generation to pass the raycastParams:
-- Generate the initial terrain heightmap
local heightmap = generateTerrainHeightmap(sim, raycastParams)
In the simulation loop, when updating the heightmap, pass raycastParams:
-- Periodically update the heightmap
lastHeightmapUpdate = lastHeightmapUpdate + deltaTime
if lastHeightmapUpdate >= simulationParameters.heightmapUpdateInterval then
lastHeightmapUpdate = 0
-- Update the heightmap
heightmap = generateTerrainHeightmap(sim, raycastParams)
sim:cellEncodeHeightmap(heightmap, 1)
end
Now, enhance the code within your simulation loop where you detect high flux and cliffs. Replace the existing comment with the following code:
-- Detect high flux (too much force)
-- Compute total flux magnitude for the cell
local fluxLD = cell[GMFluxContainer.FluxCell.FluxLD]
local fluxRU = cell[GMFluxContainer.FluxCell.FluxRU]
local totalFlux = math.abs(fluxLD.left) + math.abs(fluxLD.down) + math.abs(fluxRU.right) + math.abs(fluxRU.up)
-- Set a flux threshold for creating particles
local fluxThreshold = 15 -- Adjust this value as needed
-- Compute average depth difference with neighboring cells
local depthDifferences = {}
if x > 1 then
table.insert(depthDifferences, math.abs(depth - sim.cells[x - 1][y][GMFluxContainer.FluxCell.Depth]))
end
if x < sim.texSize then
table.insert(depthDifferences, math.abs(depth - sim.cells[x + 1][y][GMFluxContainer.FluxCell.Depth]))
end
if y > 1 then
table.insert(depthDifferences, math.abs(depth - sim.cells[x][y - 1][GMFluxContainer.FluxCell.Depth]))
end
if y < sim.texSize then
table.insert(depthDifferences, math.abs(depth - sim.cells[x][y + 1][GMFluxContainer.FluxCell.Depth]))
end
local totalDepthDifference = 0
for _, diff in ipairs(depthDifferences) do
totalDepthDifference = totalDepthDifference + diff
end
local averageDepthDifference = #depthDifferences > 0 and totalDepthDifference / #depthDifferences or 0
-- Set depth difference threshold
local depthDifferenceThreshold = 2 -- Adjust as needed
-- Implement a cooldown to prevent excessive particle spawning
local currentTime = os.clock()
local lastSpawnTime = part:GetAttribute("LastParticleSpawnTime") or 0
local spawnCooldown = 1 -- Cooldown in seconds
-- If total flux exceeds threshold and average depth difference exceeds threshold, spawn PBF particles
if totalFlux >= fluxThreshold and averageDepthDifference >= depthDifferenceThreshold and (currentTime - lastSpawnTime >= spawnCooldown) then
-- Update last spawn time
part:SetAttribute("LastParticleSpawnTime", currentTime)
-- Calculate velocity based on fluxes
local velocityX = fluxRU.right - fluxLD.left
local velocityZ = fluxRU.up - fluxLD.down
local velocity = Vector3.new(velocityX, 0, velocityZ)
-- Normalize and scale velocity
if velocity.Magnitude > 0 then
velocity = velocity.Unit * math.min(velocity.Magnitude * sim.cellSize, 50) -- Limit max speed
end
-- Create PBF particle
local particle = Instance.new("Part")
particle.Size = Vector3.new(0.2, 0.2, 0.2) -- Small particle size
particle.Shape = Enum.PartType.Ball
particle.Position = Vector3.new(worldX, height + depth + 0.1, worldZ)
particle.Anchored = false
particle.CanCollide = true
particle.Material = Enum.Material.Neon
particle.Color = Color3.fromRGB(0, 162, 255) -- Light blue color
particle.Parent = sphParticleFolder
-- Set initial velocity
particle.AssemblyLinearVelocity = velocity + Vector3.new(0, 5, 0) -- Add upward velocity if desired
-- Optionally, set up the particle to delete itself after a certain time
game:GetService("Debris"):AddItem(particle, 10) -- Remove after 10 seconds
end
This code does the following:
-
Calculates the average depth difference with neighboring cells: This provides a more precise measure of where significant changes occur, improving the condition under which particles are spawned.
-
Implements a cooldown mechanism: By using LastParticleSpawnTime, we prevent spawning multiple particles in the same cell too frequently.
-
Spawns PBF particles with velocities based on fluxes: This ensures the particles integrate smoothly with your existing simulation and mimic the fluid movement.
-
Blacklists particles in the raycast: By adding sphParticleFolder to the raycastParams.FilterDescendantsInstances, we ensure particles don't interfere with terrain heightmap generation.
Complete Modified Main Simulation Script:
Below is the complete main simulation script with the modifications included:
-- MainSimulation Script
local GMFluxContainer = require(game.ServerScriptService.GMFluxContainer)
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local CollectionService = game:GetService("CollectionService")
local sphParticleFolder = game.Workspace:WaitForChild("SPHParticles")
-- Simulation parameters
local texSize = 128 -- Adjust as needed (reasonable sizes: 64, 128)
local cellSize = 2 -- Size of each cell in world units
local simPosition = Vector3.new(-100, 0, -200) -- Adjust to move the fluid grid
-- Controllable simulation parameters
local simulationParameters = {
fluxStrength = 0.25, -- Controls the fluid flow strength
fluxAtten = 0.975, -- Fluid attenuation
fluxSpill = 0.0, -- Fluid spill threshold
simulationSpeed = 0.03, -- Controls the simulation step interval
fluidGenerationRate = 100, -- Controls the rate at which fluid is added per source per step
heightmapUpdateInterval = 1 -- Interval in seconds to update the heightmap
}
-- Create an instance of the simulation container
local sim = GMFluxContainer.new(texSize, simPosition, cellSize, simulationParameters)
-- Visualization parts parent
local visualizationFolder = Instance.new("Folder")
visualizationFolder.Name = "VisualizationParts"
visualizationFolder.Parent = Workspace
-- Create parts to visualize the simulation
local partsGrid = {}
local basePosition = sim.position
for x = 1, sim.texSize do
partsGrid[x] = {}
local worldX = basePosition.X + (x - 1) * sim.cellSize
for y = 1, sim.texSize do
local part = Instance.new("Part")
part.Size = Vector3.new(sim.cellSize, 0.1, sim.cellSize) -- Initial minimal size
local height = sim.cells[x][y][GMFluxContainer.FluxCell.Height]
part.Position = Vector3.new(worldX, height + 0.05, basePosition.Z + (y - 1) * sim.cellSize)
part.Anchored = true
part.Material = Enum.Material.Slate -- Terrain material
part.Color = Color3.fromRGB(139, 69, 19) -- Brown color for terrain
part.Transparency = 0
part.CastShadow = false
part.Parent = visualizationFolder -- Parent to visualization folder
-- Add attribute to track particle emitter
part:SetAttribute("HasParticleEmitter", false)
partsGrid[x][y] = part
end
end
-- List of collidable objects (Advanced collisions)
local collidableObjectsFolder = Workspace:FindFirstChild("CollidableObjects")
local collidableObjects = {}
if collidableObjectsFolder then
collidableObjects = collidableObjectsFolder:GetChildren()
end
-- List of water sources
local waterSources = {
{x = math.floor(sim.texSize / 2), y = math.floor(sim.texSize / 2)},
-- Add more sources as needed
}
-- Initialize raycast parameters
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {visualizationFolder, sphParticleFolder}
raycastParams.IgnoreWater = false
-- Function to generate the terrain heightmap using raycasts
local function generateTerrainHeightmap(sim, raycastParams)
local heightmap = {}
local basePosition = sim.position
local cellSize = sim.cellSize
local maxTerrainHeight = 1000 -- Adjust based on your terrain
local direction = Vector3.new(0, -maxTerrainHeight - 100, 0)
for x = 1, sim.texSize do
heightmap[x] = {}
local worldX = basePosition.X + (x - 0.5) * cellSize
for y = 1, sim.texSize do
local worldZ = basePosition.Z + (y - 0.5) * cellSize
local origin = Vector3.new(worldX, maxTerrainHeight, worldZ)
local raycastResult = Workspace:Raycast(origin, direction, raycastParams)
local height = 0
if raycastResult then
height = raycastResult.Position.Y
else
-- No hit, set to base level
height = 0
end
heightmap[x][y] = height
end
end
return heightmap
end
-- Generate the initial terrain heightmap
local heightmap = generateTerrainHeightmap(sim, raycastParams)
-- Set the terrain heightmap in the simulation
sim:cellEncodeHeightmap(heightmap, 1) -- Height factor is 1
-- Simulation loop
local lastHeightmapUpdate = 0
local simulationTimer = 0
RunService.Heartbeat:Connect(function(deltaTime)
simulationTimer = simulationTimer + deltaTime
-- Add fluid at specified water sources
for _, source in ipairs(waterSources) do
sim:addFluid(source.x, source.y, simulationParameters.fluidGenerationRate)
end
-- Perform simulation steps at the specified interval
if simulationTimer >= simulationParameters.simulationSpeed then
simulationTimer = 0
-- Perform simulation steps
sim:stepFlux()
sim:stepDepth()
-- Handle collisions
sim:handleCollisions(collidableObjects)
-- Update visualization
for x = 1, sim.texSize do
local partsColumn = partsGrid[x]
local simCellsColumn = sim.cells[x]
local worldX = basePosition.X + (x - 1) * sim.cellSize
for y = 1, sim.texSize do
local part = partsColumn[y]
local cell = simCellsColumn[y]
local depth = cell[GMFluxContainer.FluxCell.Depth]
local height = cell[GMFluxContainer.FluxCell.Height]
local worldZ = basePosition.Z + (y - 1) * sim.cellSize
if depth > 0 then
-- Scale the part to represent the fluid depth
part.Size = Vector3.new(sim.cellSize, depth, sim.cellSize)
part.Position = Vector3.new(worldX, height + depth / 2, worldZ)
-- Set material and color for water
part.Material = Enum.Material.Water
-- Color intensity based on depth
local colorIntensity = math.clamp(depth / 10, 0, 1)
part.Color = Color3.new(0, 0, colorIntensity)
part.Transparency = 0.3 -- Less transparent with more depth
else
-- Minimal size for empty cells
part.Size = Vector3.new(sim.cellSize, 0.1, sim.cellSize)
part.Position = Vector3.new(worldX, height + 0.05, worldZ)
-- Set material and color for terrain
part.Material = Enum.Material.Slate -- Terrain material
part.Color = Color3.fromRGB(139, 69, 19) -- Brown color for terrain
part.Transparency = 0
end
-- Detect high flux (too much force)
-- Compute total flux magnitude for the cell
local fluxLD = cell[GMFluxContainer.FluxCell.FluxLD]
local fluxRU = cell[GMFluxContainer.FluxCell.FluxRU]
local totalFlux = math.abs(fluxLD.left) + math.abs(fluxLD.down) + math.abs(fluxRU.right) + math.abs(fluxRU.up)
-- Set a flux threshold for creating particles
local fluxThreshold = 15 -- Adjust this value as needed
-- Compute average depth difference with neighboring cells
local depthDifferences = {}
if x > 1 then
table.insert(depthDifferences, math.abs(depth - sim.cells[x - 1][y][GMFluxContainer.FluxCell.Depth]))
end
if x < sim.texSize then
table.insert(depthDifferences, math.abs(depth - sim.cells[x + 1][y][GMFluxContainer.FluxCell.Depth]))
end
if y > 1 then
table.insert(depthDifferences, math.abs(depth - sim.cells[x][y - 1][GMFluxContainer.FluxCell.Depth]))
end
if y < sim.texSize then
table.insert(depthDifferences, math.abs(depth - sim.cells[x][y + 1][GMFluxContainer.FluxCell.Depth]))
end
local totalDepthDifference = 0
for _, diff in ipairs(depthDifferences) do
totalDepthDifference = totalDepthDifference + diff
end
local averageDepthDifference = #depthDifferences > 0 and totalDepthDifference / #depthDifferences or 0
-- Set depth difference threshold
local depthDifferenceThreshold = 2 -- Adjust as needed
-- Implement a cooldown to prevent excessive particle spawning
local currentTime = os.clock()
local lastSpawnTime = part:GetAttribute("LastParticleSpawnTime") or 0
local spawnCooldown = 1 -- Cooldown in seconds
-- If total flux exceeds threshold and average depth difference exceeds threshold, spawn PBF particles
if totalFlux >= fluxThreshold and averageDepthDifference >= depthDifferenceThreshold and (currentTime - lastSpawnTime >= spawnCooldown) then
-- Update last spawn time
part:SetAttribute("LastParticleSpawnTime", currentTime)
-- Calculate velocity based on fluxes
local velocityX = fluxRU.right - fluxLD.left
local velocityZ = fluxRU.up - fluxLD.down
local velocity = Vector3.new(velocityX, 0, velocityZ)
-- Normalize and scale velocity
if velocity.Magnitude > 0 then
velocity = velocity.Unit * math.min(velocity.Magnitude * sim.cellSize, 50) -- Limit max speed
end
-- Create PBF particle
local particle = Instance.new("Part")
particle.Size = Vector3.new(0.2, 0.2, 0.2) -- Small particle size
particle.Shape = Enum.PartType.Ball
particle.Position = Vector3.new(worldX, height + depth + 0.1, worldZ)
particle.Anchored = false
particle.CanCollide = true
particle.Material = Enum.Material.Neon
particle.Color = Color3.fromRGB(0, 162, 255) -- Light blue color
particle.Parent = sphParticleFolder
-- Set initial velocity
particle.AssemblyLinearVelocity = velocity + Vector3.new(0, 5, 0) -- Add upward velocity if desired
-- Optionally, set up the particle to delete itself after a certain time
game:GetService("Debris"):AddItem(particle, 10) -- Remove after 10 seconds
end
end
end
end
-- Periodically update the heightmap
lastHeightmapUpdate = lastHeightmapUpdate + deltaTime
if lastHeightmapUpdate >= simulationParameters.heightmapUpdateInterval then
lastHeightmapUpdate = 0
-- Update the heightmap
heightmap = generateTerrainHeightmap(sim, raycastParams)
sim:cellEncodeHeightmap(heightmap, 1)
end
end)
Explanation:
-
Enhancing the if statement condition: By considering both the total flux and the average depth difference, we ensure that particles are spawned only in areas where there is significant fluid movement and depth variation, which aligns with the characteristics described in the Position Based Fluids research.
-
Setting the initial velocity of the particles: Calculating the velocity based on the fluxes gives the particles an initial momentum that reflects the movement of the fluid in the simulation, making them integrate seamlessly.
-
Managing particle spawning and deletion: The cooldown mechanism prevents over-spawning in the same location, and using the Debris service ensures particles are deleted after a set time, keeping performance optimal.
-
Blacklisting particles in raycasts: By adding sphParticleFolder to the blacklist, particles won't interfere with the terrain heightmap generation, maintaining accuracy.
Conclusion:
These modifications enhance your code by improving the precision of the particle spawning conditions, ensuring that PBF particles interact correctly with your simulation, and manage their lifecycle appropriately. Additionally, by blacklisting them in the raycast, we prevent any interference with terrain calculations, fulfilling all your requirements.