I had Claude fuse the new Mercury example project and the Pool Balls project.
If balls roll into each other fast enough, one of them will explode into mercury and roll around the table a little before drawing itself back together and becoming a pool ball again.
Just add this code as the last tab in the pool balls project:
--# Main
-- Mercury Pool
-- Pool balls on a felt table. Hit one hard enough and it may burst into liquid
-- mercury, which slithers around under the tilt of each half, then pulls
-- itself back into the ball. Drag a ball to place it, or flick it into others.
function setup()
viewer.mode = FULLSCREEN
pool = Table()
local s = RADIUS * 2.15
balls = {
Ball(pool, 1, color(250, 196, 30), vec2(0, 0)),
Ball(pool, 2, color(30, 90, 210), vec2(-s, -s)),
Ball(pool, 3, color(215, 45, 40), vec2(s, -s)),
Ball(pool, 12, color(115, 50, 175), vec2(-s, s)),
Ball(pool, 13, color(240, 105, 25), vec2(s, s)),
}
liquid = Liquid()
metal = Metal()
lampFalloff = radialShade(128, function(d) return 0.72 * d ^ 1.7 end)
end
-- true when the fold runs up the screen, false across it, nil without a hinge
function foldVertical()
local halves = hinge.halves
if #halves < 2 then return nil end
return halves[1].bounds.width < WIDTH
end
function updateBalls(dt)
for _, ball in ipairs(balls) do ball:step(dt) end
for iter = 1, 3 do
for i = 1, #balls do
for j = i + 1, #balls do balls[i]:collide(balls[j]) end
balls[i]:bounce()
end
end
for _, ball in ipairs(balls) do ball:place() end
end
function draw()
local fold = foldVertical()
if pool.width ~= WIDTH or pool.height ~= HEIGHT or pool.foldVertical ~= fold then
pool:build(fold)
liquid:clear()
for _, ball in ipairs(balls) do ball:reset() end
end
local dt = math.min(DeltaTime, 1 / 30)
updateBalls(dt)
liquid:update(dt, hinge.halves, pool)
local mercury = #liquid.particles > 0
if mercury then metal:splat(liquid.particles) end
pool.scene:draw()
if mercury then metal:draw() end
sprite(lampFalloff, WIDTH / 2, HEIGHT / 2, WIDTH * 1.15, HEIGHT * 1.15)
end
function touched(touch)
local p = vec2(touch.x, touch.y)
if touch.state == BEGAN then
local closest, bestDist = nil, RADIUS * 2
for _, ball in ipairs(balls) do
local d = p:distance(ball.pos)
if not ball.held and not ball.molten and d < bestDist then
closest, bestDist = ball, d
end
end
if closest then
closest.held = true
closest.touchId = touch.id
closest.vel = vec2()
closest:dragTo(touch.x, touch.y)
end
else
for _, ball in ipairs(balls) do
if ball.held and ball.touchId == touch.id then
if touch.state == ENDED or touch.state == CANCELLED then
ball.held = false
ball.touchId = nil
else
ball:dragTo(touch.x, touch.y)
end
end
end
end
end
--# Ball
-- Ball
-- Rolls in screen points under each half's gravity; drawn as a 3D pool ball
-- that turns as it rolls. A hard hit can melt the struck ball into mercury.
RADIUS = 39 -- points
GRAVITY = 2400 -- points / s^2 at 1g
ROLLING = 5 / 7 -- a rolling solid sphere feels 5/7 of the slope's pull
ROLLING_DRAG = 0.35 -- per second
CUSHION_BOUNCE = 0.7
BALL_BOUNCE = 0.92
MELT_SPEED = 450 -- closing speed (points/s) a hit needs to risk a melt
MELT_CHANCE = 0.25 -- chance that such a hit does melt the struck ball
Ball = class()
function Ball:init(tbl, number, ballColor, offset)
self.table = tbl
self.offset = offset or vec2()
self.pos = vec2(WIDTH / 2, HEIGHT / 2) + self.offset
self.vel = vec2()
self.molten = false
local finish = material.lit()
finish.map = poolBallTexture(number, ballColor)
finish.roughness = 0.12
finish.reflectance = 0.6
finish.enableClearCoat = true
finish.clearCoat = vec2(1, 0.03)
local s = tbl.scene
self.entity = s:entity("ball " .. number)
local sphere = mesh.sphere(RADIUS / SCALE, 64, 32)
sphere.material = finish
self.entity:add(sphere)
self.entity.rotation = quat.eulerAngles(number * 37, number * 73, number * 19)
-- Darkens the cloth right where the ball touches it
local contact = material.unlit()
contact.map = radialShade(64, function(d) return (1 - d) ^ 2.5 * 0.85 end)
contact.blend = 2 -- transparent
self.contact = s:entity("contact shadow " .. number)
local blob = mesh.plane(vec2(RADIUS * 1.3 / SCALE))
blob.material = contact
self.contact:add(blob)
self.contact.rotation = quat.eulerAngles(-90, 0, 0)
end
-- A molten ball is shrunk to nothing, so it neither draws nor casts a shadow
function Ball:show(on)
local k = on and 1 or 0.001
self.entity.scale = vec3(k, k, k)
self.contact.scale = vec3(k, k, k)
end
function Ball:reset()
self.pos = vec2(WIDTH / 2, HEIGHT / 2) + self.offset
self.vel = vec2()
self.lastCentre = nil
self.molten = false
self:show(true)
end
function Ball:melt()
self.molten = true
self:show(false)
liquid:melt(self, self.vel)
end
-- The mercury has gathered again: the ball reappears where it pooled
function Ball:reform(x, y, vel)
self.pos = vec2(x, y)
self.vel = vel
self.molten = false
self.lastCentre = nil
self:show(true)
end
function Ball:step(dt)
if self.held or self.molten then return end
local half = hinge.halfAt(self.pos)
if half then
local g = half.gravity
self.vel = self.vel + vec2(g.x, g.y) * GRAVITY * ROLLING * dt
end
self.vel = self.vel * (1 - ROLLING_DRAG * dt)
self.pos = self.pos + self.vel * dt
self:bounce()
end
function Ball:bounce()
if self.molten then return end
local x0, y0, x1, y1 = self.table:playArea()
local r = RADIUS
if self.pos.x < x0 + r then self.pos.x = x0 + r; self.vel.x = math.abs(self.vel.x) * CUSHION_BOUNCE end
if self.pos.x > x1 - r then self.pos.x = x1 - r; self.vel.x = -math.abs(self.vel.x) * CUSHION_BOUNCE end
if self.pos.y < y0 + r then self.pos.y = y0 + r; self.vel.y = math.abs(self.vel.y) * CUSHION_BOUNCE end
if self.pos.y > y1 - r then self.pos.y = y1 - r; self.vel.y = -math.abs(self.vel.y) * CUSHION_BOUNCE end
end
function Ball:collide(other)
if self.molten or other.molten then return end
local delta = other.pos - self.pos
local d = delta:len()
local minDist = RADIUS * 2
if d <= 0.0001 or d >= minDist then return end
local n = delta / d
local overlap = minDist - d
if self.held and not other.held then
other.pos = other.pos + n * overlap
elseif other.held and not self.held then
self.pos = self.pos - n * overlap
else
self.pos = self.pos - n * (overlap * 0.5)
other.pos = other.pos + n * (overlap * 0.5)
end
local vn = (other.vel - self.vel):dot(n)
local sa, sb = self.vel:len(), other.vel:len()
if vn < 0 then
if self.held and not other.held then
other.vel = other.vel - n * (vn * (1 + BALL_BOUNCE))
elseif other.held and not self.held then
self.vel = self.vel + n * (vn * (1 + BALL_BOUNCE))
else
local impulse = n * (vn * 0.5 * (1 + BALL_BOUNCE))
self.vel = self.vel + impulse
other.vel = other.vel - impulse
end
-- the slower ball is the one that got hit
if -vn > MELT_SPEED and math.random() < MELT_CHANCE then
local victim = sa <= sb and self or other
if victim.held then victim = (victim == self) and other or self end
if not victim.held and liquid:canMelt() then victim:melt() end
end
end
end
-- Moves the 3D ball to match, pulled in slightly so perspective puts it under
-- the same screen point, and rolls it without slipping
function Ball:place()
if self.molten then return end
local r = RADIUS / SCALE
local d = self.table:cameraDistance()
local onBed = self.table:toWorld(self.pos)
local centre = vec3(onBed.x * (d - r) / d, onBed.y * (d - r) / d, -r)
local moved = centre - (self.lastCentre or centre)
self.lastCentre = centre
local distance = math.sqrt(moved.x * moved.x + moved.y * moved.y)
if distance > 0 then
local axis = vec3(moved.y, -moved.x, 0) / distance
local spin = quat.angleAxis(math.deg(distance / r), axis)
self.entity.rotation = spin * self.entity.rotation
end
self.entity.position = centre
self.contact.position = vec3(onBed.x, onBed.y, -0.002)
end
function Ball:dragTo(x, y)
local x0, y0, x1, y1 = self.table:playArea()
local target = vec2(
math.clamp(x, x0 + RADIUS, x1 - RADIUS),
math.clamp(y, y0 + RADIUS, y1 - RADIUS)
)
-- Smoothed so a flick carries its speed when released
self.vel = self.vel * 0.5 + (target - self.pos) / math.max(DeltaTime, 1 / 120) * 0.5
self.pos = target
end
--# Liquid
-- Liquid
-- Position-based mercury. Neighbours closer than SPACING push apart; a little
-- further out they pull together, which holds droplets whole. Each melted ball
-- is a blob of MELT_PARTS particles, each with a slot in a ball-sized disc.
-- After a delay the blob pulls its particles into those slots, and once they
-- sit there the ball comes back.
SPACING = 15 -- rest distance between particles, in points
COHESION_RANGE = 1.6 -- pull reaches out to this many spacings
MERC_GRAVITY = 1700 -- points / s^2 at 1g
SUBSTEPS = 2
ITERATIONS = 2
MELT_PARTS = 25 -- about a ball's worth of mercury at this spacing
MAX_MOLTEN = 2 -- balls that may be liquid at once
REFORM_DELAY = 1.6 -- seconds of free slithering before gathering starts
REFORM_RAMP = 1.5 -- seconds for the gathering pull to reach full strength
PULL = 10 -- gathering strength
SLOTS = {}
do
local mx, my = 0, 0
for i = 1, MELT_PARTS do
local r = SPACING * 0.52 * math.sqrt(i)
local a = i * 2.39996
SLOTS[i] = {r * math.cos(a), r * math.sin(a)}
mx, my = mx + SLOTS[i][1], my + SLOTS[i][2]
end
for i = 1, MELT_PARTS do
SLOTS[i][1], SLOTS[i][2] = SLOTS[i][1] - mx / MELT_PARTS, SLOTS[i][2] - my / MELT_PARTS
end
end
Liquid = class()
function Liquid:init()
self.particles = {}
self.blobs = {}
self.play = {0, 0, WIDTH, HEIGHT}
end
function Liquid:clear()
self.particles, self.blobs = {}, {}
end
function Liquid:canMelt()
return #self.blobs < MAX_MOLTEN
end
-- Bursts a ball into mercury: out from its middle, plus a share of its motion
function Liquid:melt(ball, vel)
local blob = {ball = ball, parts = {}, age = 0}
local k = 1 / (60 * SUBSTEPS)
for i = 1, MELT_PARTS do
local ox, oy = SLOTS[i][1], SLOTS[i][2]
local r = math.max(math.sqrt(ox * ox + oy * oy), 1)
local out = (0.4 + r / RADIUS) * 260 * k
local x, y = ball.pos.x + ox, ball.pos.y + oy
local vx, vy = ox / r * out + vel.x * 0.6 * k, oy / r * out + vel.y * 0.6 * k
local p = {x = x, y = y, px = x - vx, py = y - vy, loose = 0.5, ox = ox, oy = oy, ramp = 0, blob = blob}
blob.parts[i] = p
self.particles[#self.particles + 1] = p
end
self.blobs[#self.blobs + 1] = blob
end
local function gravityAt(halves, x, y)
for _, half in ipairs(halves) do
local b = half.bounds
if x >= b.x and x <= b.x + b.width and y >= b.y and y <= b.y + b.height then
return half.gravity
end
end
return halves[1].gravity
end
function Liquid:update(dt, halves, tbl)
if #self.particles == 0 then return end
self.play = {tbl:playArea()}
local h = dt / SUBSTEPS
for s = 1, SUBSTEPS do
self:integrate(h, halves)
for i = 1, ITERATIONS do self:relax() end
self:pull(h)
self:confine()
end
for _, p in ipairs(self.particles) do p.loose = math.max(0, p.loose - dt) end
for i = #self.blobs, 1, -1 do self:age(self.blobs[i], dt) end
end
function Liquid:integrate(h, halves)
for _, p in ipairs(self.particles) do
local g = gravityAt(halves, p.x, p.y)
local damping = 0.996 - 0.04 * p.ramp
local vx, vy = (p.x - p.px) * damping, (p.y - p.py) * damping
p.px, p.py = p.x, p.y
p.x = p.x + vx + g.x * MERC_GRAVITY * h * h
p.y = p.y + vy + g.y * MERC_GRAVITY * h * h
end
end
-- Neighbours within reach of each other, found through a grid of reach-sized cells
function Liquid:neighbours()
local reach = SPACING * COHESION_RANGE
local cells = {}
for i, p in ipairs(self.particles) do
local key = math.floor(p.x / reach) * 4096 + math.floor(p.y / reach)
local cell = cells[key]
if not cell then cell = {}; cells[key] = cell end
cell[#cell + 1] = i
end
local found = {}
local reach2 = reach * reach
for i, p in ipairs(self.particles) do
local cx, cy = math.floor(p.x / reach), math.floor(p.y / reach)
for ox = -1, 1 do
for oy = -1, 1 do
local cell = cells[(cx + ox) * 4096 + cy + oy]
if cell then
for _, j in ipairs(cell) do
if j > i then
local q = self.particles[j]
local dx, dy = q.x - p.x, q.y - p.y
if dx * dx + dy * dy < reach2 then found[#found + 1] = {p, q} end
end
end
end
end
end
end
return found
end
function Liquid:relax()
local reach = SPACING * COHESION_RANGE
for _, pair in ipairs(self:neighbours()) do
local p, q = pair[1], pair[2]
local dx, dy = q.x - p.x, q.y - p.y
local d = math.sqrt(dx * dx + dy * dy)
if d > 0.0001 and d < reach then
local move = 0
if d < SPACING then
move = (SPACING - d) * 0.25
elseif p.loose == 0 and q.loose == 0 then
local t = (d - SPACING) / (reach - SPACING)
move = -(d - SPACING) * 0.12 * (1 - t)
end
local mx, my = dx / d * move, dy / d * move
p.x, p.y = p.x - mx, p.y - my
q.x, q.y = q.x + mx, q.y + my
end
end
end
-- Where a blob wants its disc: its own middle, kept far enough from the rails
function Liquid:target(b)
local cx, cy = 0, 0
for _, p in ipairs(b.parts) do cx, cy = cx + p.x, cy + p.y end
cx, cy = cx / #b.parts, cy / #b.parts
local x0, y0, x1, y1 = self.play[1], self.play[2], self.play[3], self.play[4]
return math.clamp(cx, x0 + RADIUS, x1 - RADIUS), math.clamp(cy, y0 + RADIUS, y1 - RADIUS), cx, cy
end
-- Hands out disc slots by rank, innermost particle to innermost slot, so the
-- gathering doesn't have to cross itself
function Liquid:assign(b, cx, cy)
b.assigned = true
local order = {}
for i, p in ipairs(b.parts) do
order[i] = p
p.d = (p.x - cx) ^ 2 + (p.y - cy) ^ 2
end
table.sort(order, function(a, c) return a.d < c.d end)
for i, p in ipairs(order) do p.ox, p.oy = SLOTS[i][1], SLOTS[i][2] end
end
function Liquid:pull(h)
for _, b in ipairs(self.blobs) do
if b.age > REFORM_DELAY then
local ramp = math.min(1, (b.age - REFORM_DELAY) / REFORM_RAMP)
local tx, ty, cx, cy = self:target(b)
if not b.assigned then self:assign(b, cx, cy) end
local k = math.min(0.4, PULL * h * ramp)
for _, p in ipairs(b.parts) do
p.ramp = ramp
local ex, ey = (tx + p.ox - p.x) * k, (ty + p.oy - p.y) * k
p.x, p.y, p.px, p.py = p.x + ex, p.y + ey, p.px + ex, p.py + ey
end
end
end
end
function Liquid:age(b, dt)
b.age = b.age + dt
if b.age < REFORM_DELAY + 0.5 then return end
local tx, ty = self:target(b)
local worst, vx, vy = 0, 0, 0
for _, p in ipairs(b.parts) do
worst = math.max(worst, math.sqrt((tx - p.x) ^ 2 + (ty - p.y) ^ 2))
vx, vy = vx + p.x - p.px, vy + p.y - p.py
end
if worst > RADIUS * 1.3 then return end
local k = 60 * SUBSTEPS / #b.parts
local kept = {}
for _, p in ipairs(self.particles) do
if p.blob ~= b then kept[#kept + 1] = p end
end
self.particles = kept
for i, other in ipairs(self.blobs) do
if other == b then table.remove(self.blobs, i) break end
end
b.ball:reform(tx, ty, vec2(vx * k, vy * k))
end
-- Keeps mercury on the cloth and out of the balls that are still solid
function Liquid:confine()
local x0, y0, x1, y1 = self.play[1], self.play[2], self.play[3], self.play[4]
local r = SPACING * 0.5
local reach = RADIUS + r * 0.6
for _, p in ipairs(self.particles) do
p.x = math.clamp(p.x, x0 + r, x1 - r)
p.y = math.clamp(p.y, y0 + r, y1 - r)
for _, ball in ipairs(balls) do
if not ball.molten then
local dx, dy = p.x - ball.pos.x, p.y - ball.pos.y
local d2 = dx * dx + dy * dy
if d2 < reach * reach and d2 > 0.000001 then
local k = reach / math.sqrt(d2)
p.x, p.y = ball.pos.x + dx * k, ball.pos.y + dy * k
end
end
end
end
end
--# Metal
-- Metal
-- Draws the mercury as polished metal over the 3D table. Particles are splatted
-- into two fields: a tight one whose threshold gives the outline, and a wide,
-- soft one that swells into a dome over each droplet. A full screen shader
-- shades the dome as liquid metal reflecting the HDR room, and leaves
-- everything that isn't liquid transparent apart from a soft shadow.
SPLAT = SPACING * 2.1 -- reach of each particle in the outline field
SWELL = SPACING * 4.5 -- reach of each particle in the dome field
THRESHOLD = 0.85 -- outline field value at the liquid's surface
Metal = class()
function Metal:init()
local size = 64
self.bump = image.pixel(size, size, false, 1, image.rgba16f)
local c = (size + 1) / 2
for y = 1, size do
for x = 1, size do
local d2 = ((x - c) ^ 2 + (y - c) ^ 2) / (size / 2) ^ 2
local v = math.max(0, 1 - d2) ^ 2
self.bump:setValue(x, y, v, v, v, v)
end
end
self.bump:apply()
self.env = image.read(asset.builtin.hdr["Warehouse.hdr"])
self.shader = shader.builder()
:sprite()
:texture{"field"}
:texture{"swell"}
:texture{"env"}
:vec2{"texel", value = vec2()}
:vec2{"aspect", value = vec2(1, 1)}
:number{"threshold", value = THRESHOLD}
:func
[[
float heightAt(vec2 uv)
{
float s = texture(swell, uv).r;
return s / (s + 1.2);
}
vec3 environment(vec3 d)
{
float u = atan(d.x, -d.z) / (2.0 * PI) + 0.5;
float v = acos(clamp(d.y, -1.0, 1.0)) / PI;
return textureLod(env, vec2(u, v), 0.0).rgb;
}
float softbox(vec2 r, vec2 centre, vec2 halfSize, float softness)
{
vec2 d = abs(r - centre) - halfSize;
return 1.0 - smoothstep(0.0, softness, max(d.x, d.y));
}
]]
:material
[[
vec2 uv = getUV0();
float f = texture(field, uv).r;
float shadow = smoothstep(threshold * 0.4, threshold * 1.4, texture(field, uv + vec2(-0.012, -0.018) * vec2(1.0, aspect.x / aspect.y)).r);
vec2 step = texel * 3.0;
float hl = heightAt(uv - vec2(step.x, 0.0));
float hr = heightAt(uv + vec2(step.x, 0.0));
float hd = heightAt(uv - vec2(0.0, step.y));
float hu = heightAt(uv + vec2(0.0, step.y));
vec3 n = normalize(vec3((hl - hr) * 14.0, (hu - hd) * 14.0, 1.0));
vec3 view = vec3(0.0, 0.0, 1.0);
vec3 r = reflect(-view, n);
float facing = clamp(n.z, 0.0, 1.0);
float fresnel = 0.25 + 0.75 * pow(1.0 - facing, 4.0);
vec3 seen = environment(r);
seen = mix(vec3(dot(seen, vec3(0.3, 0.59, 0.11))), seen, 0.7) * vec3(0.94, 0.97, 1.03);
vec3 metal = seen * fresnel * 1.4;
vec3 key = normalize(vec3(-0.45, 0.55, 0.7));
metal *= mix(0.6, 1.2, max(dot(n, key), 0.0));
metal += vec3(1.0, 0.95, 0.88) * softbox(r.xy, vec2(-0.42, 0.42), vec2(0.16, 0.1), 0.06) * 2.2;
metal += vec3(0.8, 0.9, 1.0) * softbox(r.xy, vec2(0.38, -0.5), vec2(0.28, 0.025), 0.03) * 1.8;
float keyHalf = max(dot(n, normalize(key + view)), 0.0);
metal += vec3(1.0, 0.97, 0.92) * pow(keyHalf, 400.0) * 14.0;
metal += vec3(0.65, 0.8, 1.0) * pow(1.0 - facing, 6.0) * 1.2;
metal *= mix(0.6, 1.0, smoothstep(threshold, threshold + 0.5, f));
metal = metal / (1.0 + metal);
float edge = smoothstep(threshold - 0.04, threshold + 0.04, f);
vec3 col = edge > 0.0 ? metal : vec3(0.0);
material.baseColor = vec4(col, max(edge, shadow * 0.55));
]]
:build()
self.shader.env = self.env
end
function Metal:resize()
self.width, self.height = WIDTH, HEIGHT
self.field = image.pixel(math.ceil(WIDTH / 2), math.ceil(HEIGHT / 2), false, 1, image.rgba16f)
self.field.wrap = image.wrap.clamp
self.swell = image.pixel(math.ceil(WIDTH / 4), math.ceil(HEIGHT / 4), false, 1, image.rgba16f)
self.swell.wrap = image.wrap.clamp
self.shader.field = self.field
self.shader.swell = self.swell
self.shader.texel = vec2(1 / self.field.width, 1 / self.field.height)
self.shader.aspect = vec2(WIDTH / HEIGHT, 1)
end
-- Adds a bump for each particle into a field drawn at 1 / reduction of the screen
function Metal:field_(target, particles, reduction, reach)
local size = reach * 2 / reduction
context.push(target)
background(0, 0, 0, 0)
style.push().blend(ADDITIVE)
for _, p in ipairs(particles) do
sprite(self.bump, p.x / reduction, p.y / reduction, size, size)
end
style.pop()
context.pop()
end
-- Call before the scene draws, so the fields are ready for draw()
function Metal:splat(particles)
if self.width ~= WIDTH or self.height ~= HEIGHT then self:resize() end
self:field_(self.field, particles, 2, SPLAT)
self:field_(self.swell, particles, 4, SWELL)
end
-- Call after the scene draws: the mercury goes over the table
function Metal:draw()
sprite(self.shader, WIDTH / 2, HEIGHT / 2, WIDTH, HEIGHT)
end
![]()
!! lol
