// Main Fragment Shader
const fsText = `#version 300 es
precision highp float;
uniform vec2 resolution;
uniform float time;
uniform int frame;
uniform vec4 mouse;
uniform int materialType;
uniform float brushRadius;
uniform float gravity; // New uniform for gravity
uniform sampler2D tex;
in vec2 outUv;
out vec4 fragColor;
constantsShader{commonShader}
ivec2 getOffset(int frame) {
int i = frame % 4;
if (i == 0) return ivec2(0, 0);
else if (i == 1) return ivec2(1, 1);
else if (i == 2) return ivec2(0, 1);
return ivec2(1, 0);
}
if (id == SMOKE) {
temperature = smokeTemperature;
velocityY = 1.0; // Upward initial velocity for smoke
}
else if (id == LAVA) {
temperature = lavaTemperature;
velocityY = -0.5; // Downward initial velocity for lava
}
else if (id == ICE) {
temperature = iceTemperature;
velocityY = -1.0; // Downward initial velocity for ice
}
else if (id == SAND || id == WATER) {
velocityY = -1.0; // Downward initial velocity for sand and water
}
return vec4(temperature, velocityY, 0.0, id);
}
void main() {
// Initial frame setup
if (frame == 0) {
float r = hash12(gl_FragCoord.xy);
float id = AIR;
return;
}
// Handle mouse input
if (mouse.x > 0.0) {
float d = length(gl_FragCoord.xy - mouse.xy);
if (d < brushRadius) {
fragColor = createParticle(float(materialType));
return;
}
}
// Main simulation logic
ivec2 offset = getOffset(frame);
ivec2 fc = ivec2(gl_FragCoord.xy) + offset;
ivec2 p = (fc / 2) * 2 - offset;
ivec2 xy = fc % 2;
int i = xy.x + xy.y * 2;
vec4 t00 = getData(p);
vec4 t10 = getData(p + ivec2(1, 0));
vec4 t01 = getData(p + ivec2(0, 1));
vec4 t11 = getData(p + ivec2(1, 1));
// Apply gravity and update velocities
if (t00.a != WALL && t00.a != AIR) {
// Update velocity based on gravity
t00.g -= gravity * 0.016; // Assuming 60fps, deltaTime = 1/60 ≈ 0.016
// Apply material-specific behavior
if (t00.a == SMOKE) {
// Smoke rises, so it resists gravity
t00.g += gravity * 0.032;
} else if (t00.a == LAVA) {
// Lava is affected by gravity but also has some upward force due to heat
t00.g += gravity * 0.008 * (t00.r / lavaTemperature);
}
// Clamp velocity to prevent excessive speeds
t00.g = clamp(t00.g, -10.0, 10.0);
}
// Temperature calculations
vec4 neighbors[4] = vec4[4](t00, t10, t01, t11);
for (int idx = 0; idx < 4; idx++) {
float tempDiff = neighbors[idx].r - t00.r;
neighbors[idx].r -= tempDiff * temperatureTransferRate;
t00.r += tempDiff * temperatureTransferRate;
}
// Material-specific temperature changes
if (t00.a == SMOKE) t00.r -= smokeCoolingRate;
else if (t00.a == LAVA) t00.r -= lavaCoolingRate;
// Phase transitions
if (t00.a == STONE && t00.r > stoneMeltingPoint) t00 = createParticle(LAVA);
else if (t00.a == SAND && t00.r > sandMeltingPoint) t00 = createParticle(STONE);
else if (t00.a == WATER && t00.r > waterBoilingPoint) t00 = createParticle(SMOKE);
else if (t00.a == WATER && t00.r <= waterFreezingPoint) t00 = createParticle(ICE);
else if (t00.a == LAVA && t00.r <= ambientTemperature + 50.0) t00 = createParticle(STONE);
else if (t00.a == ICE && t00.r > waterFreezingPoint) t00 = createParticle(WATER);
else if (t00.a == SMOKE && t00.r <= ambientTemperature + 10.0) t00 = createParticle(AIR);
// Temperature limits
t00.r = clamp(t00.r, -100.0, 1500.0);
fragColor = i == 0 ? t00 :
i == 1 ? t10 :
i == 2 ? t01 : t11;
The gravity system doesn't work, the particles arent falling down
The issue you're encountering stems from how particles are being moved (or, in this case, not being moved) in your shader code. While you've correctly implemented the gravity by updating the vertical velocity t00.g for each particle, there's currently no logic that actually uses this velocity to move the particles within the simulation grid. As a result, despite the velocities being updated, the particles remain stationary because their positions aren't being updated based on these velocities.
Here's what's happening:
Velocity Update: You're updating the vertical velocity (t00.g) of each particle based on gravity and material-specific behaviors. This is good and sets the foundation for simulating gravity.
// Apply gravity and update velocities
if (t00.a != WALL && t00.a != AIR) {
// Update velocity based on gravity
t00.g -= gravity * 0.016; // Assuming 60fps, deltaTime = 1/60 ≈ 0.016
// Apply material-specific behavior
if (t00.a == SMOKE) {
// Smoke rises, so it resists gravity
t00.g += gravity * 0.032;
} else if (t00.a == LAVA) {
// Lava is affected by gravity but also has some upward force due to heat
t00.g += gravity * 0.008 * (t00.r / lavaTemperature);
}
// Clamp velocity to prevent excessive speeds
t00.g = clamp(t00.g, -10.0, 10.0);
}
Missing Position Update: However, after updating velocities, there's no corresponding code that moves particles according to their velocities. In a particle simulation, updating velocity is only part of the process; you also need to update the particle's position based on that velocity. This typically involves checking whether the particle can move to a new position (e.g., the cell below is empty) and then performing the move if possible.
How to Fix It:
To make the particles fall (or rise, in the case of smoke), you need to implement logic that moves the particles based on their velocities. Here's how you can do it:
Calculate Target Position: For each particle, calculate the target position based on its velocity. Since we're dealing with a grid, you'll likely convert the velocity to an integer offset. For example:
int yOffset = int(floor(t00.g));
Attempt to Move the Particle: Check if the target position is within bounds and whether it's empty or contains a material that can be swapped. Then, move the particle to that position if possible.
ivec2 targetPos = p + ivec2(0, yOffset);
if (targetPos.y >= 0 && targetPos.y < int(resolution.y)) {
vec4 targetData = getData(targetPos);
if (targetData.a == AIR) {
// Move particle to the target position
setData(targetPos, t00);
// Set current position to AIR
setData(p, vec4(ambientTemperature, 0.0, 0.0, AIR));
}
}
Note: Since shaders can't write to arbitrary positions in a texture, you'll need to adjust your rendering logic to simulate this movement, perhaps by encoding the move in the output color or by using additional render passes.
Reset Velocity if Movement is Blocked: If the particle can't move (e.g., there's a wall or another particle below), you may want to reset its vertical velocity:
else {
// Reset velocity if movement is blocked
t00.g = 0.0;
}
Adjust for Fractional Velocities: Since velocities can be fractional, you may want to accumulate fractional movement over time or implement sub-stepping logic to handle precise movement.
Implementing Movement Logic:
Given the limitations of fragment shaders (especially regarding writing to textures), you might need to adapt your approach. Here’s how you might implement the movement:
Double Buffering: Use two textures: one for reading the current state and one for writing the next state. This way, you can simulate moving particles by writing to different positions in the output texture.
Compute Shader (If Available): If your environment supports compute shaders, they are better suited for this kind of simulation because they allow for more flexible read/write operations.
Obstacle Handling: Incorporate logic to handle obstacles (like walls) and interactions between different particle types when moving them.
Example Adjustment in Your Shader:
Here's how you might adjust your main function to include movement:
void main() {
// Existing code...
// For each cell, attempt to move the particle based on its velocity
if (t00.a != WALL && t00.a != AIR) {
// Calculate intended new position
int yOffset = int(floor(t00.g));
int xOffset = 0; // Assuming horizontal velocity is zero for now
ivec2 targetPos = p + ivec2(xOffset, yOffset);
// Ensure target position is within bounds
if (targetPos.y >= 0 && targetPos.y < int(resolution.y) &&
targetPos.x >= 0 && targetPos.x < int(resolution.x)) {
vec4 targetData = getData(targetPos);
// Check if the target cell is AIR
if (targetData.a == AIR) {
// Move particle to target position
setData(targetPos, t00);
// Clear current cell
setData(p, vec4(ambientTemperature, 0.0, 0.0, AIR));
return; // Early exit since we've moved the particle
}
}
// If can't move, reset velocity (optional)
t00.g = 0.0;
}
// Write the particle data back to the current position
fragColor = t00;
}
Note: In the context of a fragment shader, you cannot directly write to arbitrary positions in the texture (setData function is illustrative). To implement this, you may need to adjust your rendering pipeline to accommodate these kinds of updates, possibly involving multiple passes or using texture coordinate manipulation.
Conclusion:
Your gravity system isn't working because the particles' positions aren't being updated based on their velocities. By implementing logic that moves particles according to their velocities (and the rules of your simulation), you should see particles begin to fall under gravity. Remember to handle the limitations of shader programming when implementing this logic, possibly by restructuring how you process and store particle data.
Additional Tips:
Research Sand Simulation Shaders: Look into examples of sand or fluid simulations implemented in fragment shaders to see how others handle particle movements within the constraints of GLSL.
Consider Cellular Automata: Since you're working with a grid, thinking in terms of cellular automata rules might help structure your movement logic.
Optimize for Performance: Be mindful of performance implications. Simulations can be computationally intensive, so optimize where possible (e.g., minimizing texture fetches, simplifying calculations).