Back to the app
The code
Jelly Orange Slice by GPT-6.2 Astra
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#faf9f5">
<title>Orange jelly · Soft Matter</title>
<link rel="icon" href="data:,">
<style>
:root{color-scheme:light;--paper:#faf9f5;--ink:#282a24;--muted:#676a60;--line:#dbdcd2;--accent:#c64d1d;--bright:#e76324;--mono:"IBM Plex Mono","SFMono-Regular",Consolas,"Liberation Mono",monospace;--sans:"DM Sans","Avenir Next","Segoe UI",Arial,sans-serif;--serif:"Instrument Serif","Iowan Old Style","Baskerville","Times New Roman",serif}
*{box-sizing:border-box}
body{margin:0;background:var(--paper);color:var(--ink);font-family:var(--sans);-webkit-font-smoothing:antialiased}
button,input{font:inherit}
button{color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent}
button:focus-visible,input:focus-visible,canvas:focus-visible{outline:3px solid #a24c25;outline-offset:4px}
button svg{flex:none}
.icons{position:absolute;width:0;height:0;overflow:hidden}
.icon{width:20px;height:20px;display:block;fill:none;stroke:currentColor;stroke-width:1.65;stroke-linecap:round;stroke-linejoin:round}
.shell{max-width:1550px;margin:0 auto;padding:0 clamp(24px,4.7vw,78px)}
.mast{min-height:88px;display:flex;align-items:center;justify-content:space-between;gap:20px;border-bottom:1px solid var(--line)}
.identity{display:flex;align-items:center;gap:12px}
.brand{font-size:24px;font-weight:680;letter-spacing:-1.4px;line-height:1}
.mark{display:block;width:36px;height:38px;color:var(--accent)}
.product{border-left:1px solid #cfcfc4;padding-left:19px;margin-left:8px;color:#66695f;font-size:13px;letter-spacing:.01em}
.demo{border:1px solid #cfcfc4;background:transparent;display:inline-flex;align-items:center;justify-content:center;gap:9px;padding:0 17px;height:42px;min-height:42px;border-radius:24px;font-weight:590;font-size:13px}
.demo .icon{width:15px;height:15px}
.demo:hover,.secondary:hover,.expand:hover{background:#f0eee6}
.demo[aria-pressed=true]{color:#9e3c16;background:#fff0df;border-color:#dfb394}
.workbench{display:grid;grid-template-columns:minmax(248px,.355fr) minmax(0,1fr);grid-template-rows:auto auto;grid-template-areas:"intro exhibit" "controls exhibit";column-gap:clamp(35px,4.6vw,82px);row-gap:30px;padding:clamp(32px,5.2vh,68px) 0 34px}
.intro{grid-area:intro;align-self:end}
.eyebrow{font:600 10px/1.4 var(--mono);letter-spacing:.15em;text-transform:uppercase;color:#8f4525;display:flex;align-items:center;gap:10px;margin:0 0 21px}
.eyebrow:before{content:"";width:23px;height:2px;background:var(--accent)}
h1{font-family:var(--serif);font-size:clamp(73px,6.8vw,107px);font-weight:400;line-height:.89;letter-spacing:-.064em;margin:0 0 23px}
h1 span,h1 em{display:block}
h1 em{font-weight:400;color:var(--accent);letter-spacing:-.075em}
.instructions{font-size:clamp(15px,1.13vw,18px);line-height:1.55;color:#62655c;max-width:305px;margin:0}
.settings{grid-area:controls;align-self:start;border-top:1px solid var(--line);padding-top:24px}
.control-head,.range-ends,.actions{display:flex;align-items:center;justify-content:space-between}
.control-head label{font-size:15px;font-weight:650;letter-spacing:-.025em}
output{font:600 12px/1 var(--mono);color:#9d411d;background:#f6e7d7;padding:6px 8px;border-radius:6px;font-variant-numeric:tabular-nums}
#firmness{display:block;width:100%;height:36px;margin:6px 0 -2px;appearance:none;-webkit-appearance:none;cursor:pointer;background:transparent;accent-color:var(--accent);touch-action:pan-y;--position:45%}
#firmness::-webkit-slider-runnable-track{height:5px;border-radius:10px;background:linear-gradient(to right,var(--bright) 0 var(--position),#deded3 var(--position) 100%)}
#firmness::-moz-range-track{height:5px;border-radius:10px;background:#deded3}
#firmness::-moz-range-progress{background:var(--bright);height:5px;border-radius:10px}
#firmness::-webkit-slider-thumb{-webkit-appearance:none;width:21px;height:21px;margin-top:-8px;border:4px solid var(--paper);border-radius:50%;background:var(--accent);box-shadow:0 0 0 1px #c9b7a6,0 2px 4px #69442b22}
#firmness::-moz-range-thumb{width:14px;height:14px;border:4px solid var(--paper);border-radius:50%;background:var(--accent);box-shadow:0 0 0 1px #c9b7a6}
.range-ends{font:11px/1.2 var(--mono);letter-spacing:.015em;color:var(--muted)}
.actions{margin-top:25px;gap:10px}
.primary,.secondary{border-radius:11px;height:49px;display:inline-flex;align-items:center;justify-content:center;gap:9px;font-size:14px;font-weight:640;touch-action:manipulation;user-select:none;-webkit-user-select:none}
.primary{flex:1;color:white;background:#ca4d1c;border:1px solid #b9471d;box-shadow:inset 0 1px 0 #ffffff26,0 2px 2px #72391912}
.primary:hover{background:#b9471b}
.primary.active,.primary:active{background:#a63e16;transform:translateY(1px);box-shadow:inset 0 2px 5px #7e2a183d}
.secondary{padding:0 16px;background:transparent;border:1px solid #d0d0c6}
.secondary .icon{width:16px}
.note{display:flex;align-items:center;gap:7px;margin:13px 0 0;color:#74766b;font-size:12px;line-height:1.4}
.note .icon{width:13px;height:15px;color:#918572}
.exhibit{grid-area:exhibit;align-self:center;min-width:0;margin:0}
.frame{overflow:hidden;border:1px solid #d9cdbc;border-radius:22px;background:#f7f5ed;box-shadow:0 3px 9px #4c331106}
.stage{isolation:isolate;position:relative;height:clamp(445px,min(64vh,48vw),650px);background:#f1d8bc;overflow:hidden}
#world{display:block;width:100%;height:100%;touch-action:none;cursor:grab;user-select:none;-webkit-user-select:none;outline-offset:-6px}
#world:active{cursor:grabbing}
.contact{position:absolute;pointer-events:none;z-index:1;width:26px;height:26px;border:1.5px solid #fffcf0;border-radius:50%;transform:translate(-50%,-50%);box-shadow:0 0 0 1px #93441880,0 2px 6px #72340e40;background:#fff9df23}.contact:after{content:"";position:absolute;inset:8px;border-radius:50%;background:#fffbea;box-shadow:0 1px 2px #90371277}
.stage-top,.stage-bottom{position:absolute;z-index:1;left:21px;right:21px;display:flex;align-items:center;justify-content:space-between;pointer-events:none}
.stage-top{top:18px}
.stage-bottom{bottom:16px;align-items:flex-end}
.state{display:inline-flex;align-items:center;gap:8px;border:1px solid #fff8;background:#fff9eecc;color:#535447;padding:0 11px;border-radius:30px;height:29px;font:11px var(--mono);box-shadow:0 1px 3px #643c1407}
.led{width:6px;height:6px;border-radius:100%;background:#667c4d;box-shadow:0 0 0 3px #64794b17}
.state[data-active=true] .led{background:#cc641f;box-shadow:0 0 0 3px #cc641f1a}
.expand{display:grid;place-items:center;width:42px;height:42px;pointer-events:auto;border:1px solid #fff9;border-radius:50%;background:#fff8edbc;color:#625748}
.expand .icon{width:17px;height:17px}
.orbit-help{display:flex;align-items:center;gap:7px;color:#5f5143;font-size:11px;line-height:1.3;letter-spacing:.005em}
.orbit-help .icon{width:18px;height:18px}
.gizmo{height:42px;width:48px;overflow:visible}
.gizmo text{font:bold 7px var(--mono)}
.readout{display:flex;align-items:center;gap:16px;height:47px;padding:0 19px;background:#f7f6ef;border-top:1px solid #d9cdbc;color:#62645a}
.readout-label{display:flex;align-items:center;gap:8px;font-size:11px;font-weight:560;white-space:nowrap}
.readout-label .icon{width:16px;height:16px;color:#797b6e}
.trace{display:block;flex:1;min-width:0;height:22px}
.reading{width:44px;flex:none;text-align:right;font:11px var(--mono);font-variant-numeric:tabular-nums;letter-spacing:.01em}
body.enlarged{overflow:hidden}
.frame.expanded{position:fixed;inset:12px;z-index:20;display:flex;flex-direction:column;box-shadow:0 0 0 30px #32271e80}
.expanded .stage{height:auto;flex:1}
.expanded .readout{flex:none}
@media(min-width:1500px){.mast{min-height:100px}.workbench{padding-top:6vh}.note{font-size:13px}}
@media(max-width:1000px) and (min-width:761px){.shell{padding:0 28px}.workbench{grid-template-columns:225px minmax(0,1fr);column-gap:28px;row-gap:23px}.stage{height:445px}.settings{padding-top:19px}h1{font-size:76px}.secondary{padding:0 12px}.readout{gap:10px}}
@media(max-width:760px){.mast{min-height:67px}.brand{font-size:21px}.mark{width:31px;height:34px}.identity{gap:8px}.product{font-size:12px;margin-left:4px;padding-left:12px}.demo{min-height:42px;height:42px;padding:0 13px;font-size:12px}.shell{padding:0 clamp(16px,4.5vw,28px)}.workbench{grid-template-columns:minmax(0,1fr);grid-template-areas:"intro" "exhibit" "controls";grid-template-rows:auto auto auto;row-gap:21px;padding:26px 0 31px}.eyebrow{font-size:9px;letter-spacing:.14em;margin-bottom:10px;gap:8px}.eyebrow:before{width:17px}h1{font-size:clamp(54px,10.8vw,75px);line-height:.99;margin-bottom:10px;letter-spacing:-.059em}h1 span,h1 em{display:inline}h1 em{margin-left:.025em}.instructions{max-width:480px;font-size:14px;line-height:1.48}.stage{height:clamp(260px,66vw,402px)}.frame{border-radius:17px}.stage-top{top:11px;left:12px;right:12px}.stage-bottom{bottom:10px;left:13px;right:12px}.state{height:25px;font-size:10px}.expand{height:40px;width:40px}.gizmo{width:37px;height:33px}.orbit-help{font-size:10px}.readout{height:37px;padding:0 13px;gap:12px}.readout-label,.reading{font-size:10px}.readout .icon{width:14px}.settings{border-top:0;padding:0}.actions{margin-top:18px}.primary,.secondary{height:47px}.secondary{min-width:100px}.note{margin-top:9px;font-size:11px}}
@media(max-width:430px){.product{display:none}.demo{gap:6px}.readout{gap:9px}}
@media(min-width:761px) and (max-height:660px){.mast{min-height:66px}.workbench{padding-top:24px;row-gap:21px}.stage{height:405px;min-height:0}.eyebrow{margin-bottom:15px}h1{font-size:73px;margin-bottom:17px}.settings{padding-top:17px}}
</style>
</head>
<body>
<svg class="icons" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><defs>
<symbol id="i-play" viewBox="0 0 24 24"><path d="m8 4.7 11.5 7.3L8 19.3z" fill="currentColor" stroke="none"/></symbol>
<symbol id="i-stop" viewBox="0 0 24 24"><rect x="5" y="5" width="14" height="14" rx="2" fill="currentColor" stroke="none"/></symbol>
<symbol id="i-expand" viewBox="0 0 24 24"><path d="M9 4H4v5m11-5h5v5M4 15v5h5m11-5v5h-5"/></symbol>
<symbol id="i-contract" viewBox="0 0 24 24"><path d="M4 9h5V4m6 0v5h5M9 20v-5H4m16 0h-5v5"/></symbol>
<symbol id="i-squeeze" viewBox="0 0 24 24"><path d="M12 2v5m-3-2 3 2.7L15 5M12 22v-5m-3 2 3-2.7 3 2M3.2 12c0-2 3.8-2.7 8.8-2.7s8.8.7 8.8 2.7-3.8 2.7-8.8 2.7-8.8-.7-8.8-2.7Z"/></symbol>
<symbol id="i-reset" viewBox="0 0 24 24"><path d="M4.5 5.8v5.1h5.2M5 10.5a7.4 7.4 0 1 1 .8 6.1"/></symbol>
<symbol id="i-orbit" viewBox="0 0 24 24"><ellipse cx="12" cy="14" rx="9" ry="4" transform="rotate(-19 12 14)"/><path d="m17.5 7.2 3.7 1.3-1.2 3.8"/><circle cx="11.6" cy="11.2" r="2.15" fill="currentColor" stroke="none"/></symbol>
<symbol id="i-wave" viewBox="0 0 24 24"><path d="M1 13h4l3-7 4 13 3-15 3 9h5"/></symbol>
<symbol id="i-drop" viewBox="0 0 24 24"><path d="M12 2.7c-1.3 3-6.4 8.8-6.4 12.2a6.4 6.4 0 0 0 12.8 0c0-3.4-5.1-9.2-6.4-12.2Z"/><path d="M9 15.5c.2 1.2.8 1.9 2 2.2"/></symbol>
</defs></svg>
<div class="shell">
<header class="mast">
<div class="identity">
<svg class="mark" viewBox="0 0 40 40" fill="none" aria-hidden="true"><path d="M3.3 23.1C3.1 13.2 10.4 4.6 20.1 4.6c9.1 0 16.4 7 17.1 16.1.2 2.4-1.2 3.8-3.5 4.2-7.7 1.5-20.4 2.7-27.1 1.7-2.1-.3-3.2-1.6-3.3-3.5Z" fill="currentColor"/><g stroke="#faf7ea" stroke-linecap="round" stroke-width="1.65"><path d="m9.4 19.2 7.9 2.4M12 11.8l6.1 8.1m1.7-11.4.3 10.6M28.3 11l-5.7 8.8m9.4-2.7-7.5 4.2"/></g><path d="M4.8 29.7c7.5 1.4 23.2.1 30.1-1.8M8.2 34.3c7.4.9 18.9-.3 24-1.5" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></svg>
<span class="brand">Soft Matter</span><span class="product">Physics playground</span>
</div>
<button class="demo" id="demo" type="button" aria-pressed="false"><svg class="icon" aria-hidden="true"><use id="demo-icon" href="#i-play"/></svg><span id="demo-label">Play demo</span></button>
</header>
<main class="workbench">
<section class="intro" aria-labelledby="title"><p class="eyebrow">Soft-body simulation</p><h1 id="title"><span>Orange</span> <em>jelly.</em></h1><p class="instructions">Poke the pulp or drag the slice to stretch it. Let go and watch it wobble back into shape.</p></section>
<figure class="exhibit" aria-label="Interactive three-dimensional orange jelly on a porcelain plate">
<div class="frame" id="frame"><div class="stage" id="stage">
<canvas id="world" tabindex="0" aria-label="Orange jelly. Touch or drag the slice. Drag the plate to rotate. Press Space to poke."></canvas><i class="contact" id="contact" aria-hidden="true" hidden></i>
<div class="stage-top"><span class="state" id="state" data-active="false"><i class="led"></i><span id="state-label" aria-live="polite">At rest</span></span><button class="expand" id="expand" type="button" aria-label="Expand view" title="Expand view" aria-pressed="false"><svg class="icon" aria-hidden="true"><use id="expand-icon" href="#i-expand"/></svg></button></div>
<div class="stage-bottom"><span class="orbit-help"><svg class="icon" aria-hidden="true"><use href="#i-orbit"/></svg>Drag the plate to rotate</span><svg class="gizmo" viewBox="0 0 48 42" aria-hidden="true"><g id="axes" stroke-linecap="round"><path/><path/><path/><text>X</text><text>Y</text><text>Z</text></g></svg></div>
</div>
<div class="readout"><span class="readout-label"><svg class="icon" aria-hidden="true"><use href="#i-wave"/></svg>Deformation</span><canvas class="trace" id="trace" aria-hidden="true"></canvas><span class="reading" id="reading">0.0%</span></div>
</div></figure>
<section class="settings" aria-label="Jelly controls"><div class="control-head"><label for="firmness">Firmness</label><output id="amount" for="firmness">45%</output></div><input id="firmness" type="range" min="0" max="100" value="45" aria-valuetext="45 percent"><div class="range-ends" aria-hidden="true"><span>Soft</span><span>Firm</span></div>
<div class="actions"><button class="primary" id="squeeze" type="button"><svg class="icon" aria-hidden="true"><use href="#i-squeeze"/></svg>Squeeze</button><button class="secondary" id="reset" type="button"><svg class="icon" aria-hidden="true"><use href="#i-reset"/></svg>Reset</button></div><p class="note"><svg class="icon" aria-hidden="true"><use href="#i-drop"/></svg>Hold Squeeze to press out juice.</p></section>
</main></div>
<script type="x-shader/glsl" id="gl-cam">
uniform vec3 uEye, uRight, uUp, uForward;
uniform vec2 uLens;
vec4 projectWorld(vec3 p){
vec3 q=p-uEye;
float w=dot(q,uForward);
return vec4(dot(q,uRight)*uLens.x,dot(q,uUp)*uLens.y,1.0080321*w-.3212851,w);
}
</script>
<script type="x-shader/glsl" id="gl-light">
float sat(float a){return clamp(a,0.0,1.0);}
float hash(vec2 p){vec3 q=fract(vec3(p.xyx)*vec3(.1031,.1030,.0973));q+=dot(q,q.yzx+33.33);return fract((q.x+q.y)*q.z);}
float valueNoise(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.0-2.0*f);return mix(mix(hash(i),hash(i+vec2(1.,0.)),f.x),mix(hash(i+vec2(0.,1.)),hash(i+1.0),f.x),f.y);}
float windowLight(vec3 ray,vec3 center,vec2 halfSize,float softness){
center=normalize(center);
vec3 x=normalize(cross(vec3(0.,1.,0.),center)),y=cross(center,x);
float d=dot(ray,center);
vec2 uv=vec2(dot(ray,x),dot(ray,y))/max(.015,d);
vec2 outside=abs(uv)-halfSize;
float edge=max(outside.x,outside.y);
return (1.0-smoothstep(-softness,softness,edge))*smoothstep(.05,.35,d);
}
float studio(vec3 reflection,float blur){
return windowLight(reflection,vec3(-.62,.62,.70),vec2(.51,.27),blur)
+.74*windowLight(reflection,vec3(.75,.44,-.40),vec2(.18,.71),blur)
+.53*windowLight(reflection,vec3(-.37,-.23,.91),vec2(.46,.051),blur*.75)
+.30*windowLight(reflection,vec3(-.12,.94,-.45),vec2(.62,.13),blur);
}
</script>
<script type="x-shader/glsl" id="gl-screen">
attribute vec2 aPosition;
varying vec2 vUV;
void main(){vUV=aPosition*.5+.5;gl_Position=vec4(aPosition,0.,1.);}
</script>
<script type="x-shader/glsl" id="gl-geo">
attribute vec3 aPosition,aNormal;
attribute vec4 aParam;
varying vec3 vWorld,vNormal;
varying vec4 vParam;
void main(){vWorld=aPosition;vNormal=aNormal;vParam=aParam;gl_Position=projectWorld(aPosition);}
</script>
<script type="x-shader/glsl" id="gl-dropvertex">
attribute vec3 aPosition;
uniform vec3 uCenter,uScale;
varying vec3 vWorld,vNormal;
void main(){
vWorld=uCenter+aPosition*uScale;
vNormal=normalize(aPosition/max(uScale,vec3(.00001)));
gl_Position=projectWorld(vWorld);
}
</script>
<script type="x-shader/glsl" id="gl-floor">
varying vec2 vUV;
void main(){
vec2 xy=vUV*2.-1.;
vec3 ray=normalize(uForward+uRight*xy.x/uLens.x+uUp*xy.y/uLens.y);
vec2 ground=(uEye+ray*(-uEye.y/min(ray.y,-.0001))).xz;
float swath=sat(.14+.56*vUV.y+.28*(1.-vUV.x));
vec3 base=mix(vec3(.897,.735,.606),vec3(.983,.898,.774),swath);
base+=vec3(.018,.014,.011)*exp(-2.6*dot(vUV-vec2(.18,.76),vUV-vec2(.18,.76)));
vec2 d=ground-vec2(.24,.23);
float radius=length(d*vec2(.995,1.035));
float shade=.33*exp(-pow(radius/2.31,4.0))+.24*exp(-pow(length(ground-vec2(.06,.07))/1.66,5.0));
base=mix(base,vec3(.42,.336,.245),shade);
float grain=hash(gl_FragCoord.xy+19.5)-.5;
gl_FragColor=vec4(base+grain*.0075,1.);
}
</script>
<script type="x-shader/glsl" id="gl-plate">
varying vec3 vWorld,vNormal;
uniform vec2 uShift;
uniform float uPress;
uniform sampler2D uFruit;
uniform vec3 uSpots[8];
float footprint(vec2 p,vec2 size,float radius){
vec2 q=abs(p)-size+radius;
return length(max(q,vec2(0)))+min(max(q.x,q.y),0.)-radius;
}
void main(){
vec3 n=normalize(vNormal),view=normalize(uEye-vWorld),refl=reflect(-view,n);
float radial=length(vWorld.xz);
float lambert=max(dot(n,normalize(vec3(-.64,.90,.28))),0.);
float lift=max(0.,n.y);
vec3 col=vec3(.974,.974,.953)*(.739+.172*lambert+.128*lift);
col+=vec3(.040,.020,.002)*(1.-lift);
col+=.013*vec3(1.,.98,.93)*exp(-pow(abs(radial-2.31)/.036,2.));
vec2 p=vWorld.xz-uShift;
float shadow=0.;
for(int i=0;i<7;i++){
float h=(float(i)+.09)/7.;
float ht=h*1.54*(1.-uPress*.34);
float wide=1.62*(1.+uPress*.06)*sqrt(max(.002,1.-h*h));
float dist=footprint(p-vec2(.52,.47)*ht,vec2(wide,.405),.23);
float blur=.073+.37*ht;
shadow=max(shadow,1.-smoothstep(-blur,blur,dist));
}
float nearContact=1.-smoothstep(-.016,.17,footprint(p,vec2(1.61,.409),.14));
float wash=exp(-pow(abs(p.y-.72)/.38,2.)-pow(abs(p.x-.24)/1.5,4.));
float caustic=wash*(.48+.52*valueNoise(p*vec2(3.7,8.2)));
col=mix(col,vec3(1.,.743,.414),caustic*.26*lift);
col*=mix(vec3(1.),vec3(.757,.661,.563),shadow*lift);
col*=1.-.235*nearContact*lift;
if(abs(refl.z)>.08&&n.y>.65){
float face=refl.z<0.?.42:-.42;
float t=(face-p.y)/refl.z;
vec2 uv=vec2((p.x+refl.x*t)/1.64,(vWorld.y+refl.y*t-.177)/(1.56*(1.-.3*uPress)));
float mask=(1.-smoothstep(.80,1.13,length(uv)))*smoothstep(-.09,.09,uv.y)*step(.012,t)*exp(-.64*max(t,0.));
vec3 orange=texture2D(uFruit,clamp(vec2(.5+.5*uv.x,uv.y),0.,1.),4.).rgb;
col=mix(col,orange,.145*mask*lift);
}
for(int j=0;j<8;j++){
vec3 spot=uSpots[j];
vec2 d=(vWorld.xz-spot.xy)/max(.0001,spot.z);
col*=1.-vec3(.085,.14,.225)*exp(-dot(d,d)*1.8)*step(.0001,spot.z);
}
float glaze=studio(refl,.15);
col=mix(col,vec3(1.,.997,.97),sat(.15*glaze+.086*pow(1.-sat(dot(n,view)),3.)));
col+=(hash(gl_FragCoord.xy)-.5)*.0028;
gl_FragColor=vec4(col,1.);
}
</script>
<script type="x-shader/glsl" id="gl-depth">
varying vec3 vWorld;
void main(){
float d=length(vWorld-uEye)/25.;
vec2 enc=fract(vec2(1.,255.)*d);enc.x-=enc.y/255.;
gl_FragColor=vec4(enc,0.,1.);
}
</script>
<script type="x-shader/glsl" id="gl-copy">
uniform sampler2D uScene;
varying vec2 vUV;
void main(){gl_FragColor=texture2D(uScene,vUV);}
</script>
<script type="x-shader/glsl" id="gl-fruit">
varying vec3 vWorld,vNormal;
varying vec4 vParam;
uniform vec2 uPixels;
uniform sampler2D uFruit,uRelief,uScene,uBack;
void main(){
vec3 N=normalize(vNormal),V=normalize(uEye-vWorld);
vec2 uv=clamp(vec2(.5+.5*vParam.x,vParam.y),vec2(.0008),vec2(.9992));
vec2 screen=gl_FragCoord.xy/uPixels;
vec2 depth=texture2D(uBack,screen).rg;
float thickness=clamp(dot(depth,vec2(1.,1./255.))*25.-length(vWorld-uEye),.009,3.45);
vec3 pigment,detailN=N;
float opaque,rough,vesicle;
bool flesh=vParam.w<.5;
if(flesh){
vec4 map=texture2D(uRelief,uv);
pigment=texture2D(uFruit,uv).rgb;
float sgn=vParam.z<0.?-1.:1.;
vec3 T=normalize(vec3(N.z+.0001,0.,-N.x))*sgn,B=normalize(cross(N,T))*sgn;
vec2 slope=(map.rg*2.-1.)*(.67-.23*map.b);
detailN=normalize(N+T*slope.x+B*slope.y);
opaque=map.b;rough=.095+.27*opaque;vesicle=map.a;
vec2 deeper=uv+vec2(dot(V,T)*.012,-dot(V,B)*.029)*thickness;
vec3 inner=texture2D(uFruit,clamp(deeper,.001,.999),.7).rgb;
pigment=mix(pigment,inner,.135*(1.-opaque));
}else{
float a=atan(max(0.,vParam.y),vParam.x);
vec2 coord=vec2(a*47.,vParam.z*11.8+2.2*sin(a*2.));
vec2 f=fract(coord),id=floor(coord),oil=vec2(0.);
float nearest=5.,pick=0.;
for(int j=-1;j<=1;j++)for(int i=-1;i<=1;i++){
vec2 g=vec2(float(i),float(j));
vec2 v=f-g-.12-.76*vec2(hash(id+g),hash(id+g+47.91));
float d=dot(v,v);
if(d<nearest){nearest=d;oil=v;pick=hash(id+g+9.7);}
}
float pit=exp(-nearest*(19.+15.*pick));
float zest=.62*valueNoise(coord*.153)+.38*valueNoise(coord*1.21);
pigment=mix(vec3(.913,.361,.022),vec3(1.,.609,.051),zest);
pigment-=pit*vec3(.044,.063,.009);
vec3 T=normalize(vec3(-sin(a),cos(a),.017)),B=normalize(cross(N,T));
detailN=normalize(N-(T*oil.x+B*oil.y)*pit*2.7);
opaque=.85;rough=.155;vesicle=.52;
if(vParam.w>1.5){pigment=vec3(.984,.604,.153);opaque=.35;}
}
vec3 L=normalize(vec3(-.57,.78,.58));
float direct=max(0.,dot(detailN,L)),high=max(0.,N.y);
float sideLight=max(0.,dot(detailN,normalize(vec3(.78,.46,-.3))));
vec3 color=pigment*(.814+.166*direct+.055*high+.042*sideLight);
vec2 refractOffset=vec2(dot(detailN,uRight),dot(detailN,uUp))*(.011+.015*thickness)
-vec2(dot(V,uRight),dot(V,uUp))*.007*thickness;
vec3 behind=texture2D(uScene,clamp(screen-refractOffset,.002,.998)).rgb;
vec3 Tlight=exp(-vec3(.14,1.85,6.1)*(.16+thickness*(.86+.18*(1.-vesicle))));
vec3 transmission=behind*Tlight+pigment*(1.-Tlight)*.87;
float thin=exp(-thickness*2.);
color=mix(color,transmission,(.255+.36*thin)*(1.-opaque));
float border=smoothstep(.68,1.,length(vParam.xy));
color+=vec3(.045,.041,.006)*(thin*.86+.36*border)*(1.-.62*opaque);
float ndv=sat(dot(N,V)),fres=.032+.968*pow(1.-ndv,5.);
float shell=studio(reflect(-V,N),rough),wet=studio(reflect(-V,detailN),rough*.55);
float spec=pow(max(dot(detailN,normalize(L+V)),0.),57.);
float gleam=.26*shell*(.74+.34*fres)+wet*(.105+.135*vesicle)+.17*spec+.19*fres;
if(!flesh)gleam+=.12*shell;
float foot=smoothstep(.173,.39,vWorld.y);
color*=mix(vec3(.893,.837,.802),vec3(1.),foot);
color=mix(color,vec3(1.,.978,.879),sat(gleam));
color+=vec3(.026,.017,.006)*min(wet,1.);
gl_FragColor=vec4(clamp(color,0.,1.),1.);
}
</script>
<script type="x-shader/glsl" id="gl-juice">
varying vec3 vWorld,vNormal;
uniform sampler2D uScene;
uniform vec2 uPixels;
void main(){
vec3 N=normalize(vNormal),V=normalize(uEye-vWorld);
float rim=pow(1.-sat(dot(N,V)),2.);
vec2 offset=vec2(dot(N,uRight),dot(N,uUp))*.009;
vec3 bg=texture2D(uScene,clamp(gl_FragCoord.xy/uPixels-offset,.001,.999)).rgb;
float m=sat(.52+.38*N.y-.14*N.x);
vec3 col=mix(vec3(.79,.326,.026),vec3(1.,.726,.167),m);
col=mix(col,bg*vec3(1.,.79,.35),.32);
float highlight=studio(reflect(-V,N),.064);
col=mix(col,vec3(1.,.985,.892),sat(highlight*.81+.27*rim));
gl_FragColor=vec4(col,1.);
}
</script>
<script>
(function(){
'use strict';
const byId = id => document.getElementById(id);
const PI = Math.PI, TAU = 2*PI;
const clamp = (v,lo,hi) => Math.min(hi,Math.max(lo,v));
const mix = (a,b,t) => a+(b-a)*t;
function smooth(lo,hi,v){const t=clamp((v-lo)/(hi-lo),0,1);return t*t*(3-2*t)}
function unit(a){const s=Math.hypot(a[0],a[1],a[2])||1;return [a[0]/s,a[1]/s,a[2]/s]}
function cross(a,b){return [a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]]}
function dot(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]}
let randomState=0xc17aef5;
function rand(){randomState=(Math.imul(1664525,randomState)+1013904223)>>>0;return randomState/4294967296}
const field=new Float32Array(16384), jx=new Float32Array(16384), jy=new Float32Array(16384);
for(let k=0;k<field.length;k++){field[k]=rand();jx[k]=.11+.78*rand();jy[k]=.11+.78*rand()}
const key=(x,y)=>(x&127)+((y&127)<<7);
function noise(x,y){
const i=Math.floor(x),j=Math.floor(y);let u=x-i,v=y-j;u=u*u*(3-2*u);v=v*v*(3-2*v);
return mix(mix(field[key(i,j)],field[key(i+1,j)],u),mix(field[key(i,j+1)],field[key(i+1,j+1)],u),v)
}
const cuts=[0,.444,1.006,1.489,2.051,2.598,PI];
const directions=cuts.slice(1).map((a,i)=>{const b=(a+cuts[i])*.5;return [Math.cos(b),Math.sin(b)]});
function cutAngle(a,r){return a+Math.sin(a)*(.022*Math.sin(r*5.3+a*2.7)+.015*(1-r)*Math.cos(a*4.6))}
function segment(a){let s=0;while(s<cuts.length-2&&a>cuts[s+1])s++;return s}
// Each juice vesicle has an optical colour, an elongated cell wall and a relief normal.
function makeFruitMaps(){
const w=1024,h=512,n=w*h,rgba=new Uint8Array(n*4),material=new Uint8Array(n*4),relief=new Float32Array(n);
for(let j=0;j<h;j++){
const y=(j+.5)/h;
for(let i=0;i<w;i++){
const x=2*(i+.5)/w-1,k=j*w+i,o=4*k,r=Math.sqrt(x*x+y*y),a=Math.atan2(y,x),bent=cutAngle(a,r),s=segment(bent),dir=directions[s];
const along=x*dir[0]+y*dir[1], side=-x*dir[1]+y*dir[0];
const cloud=noise(x*6.2+17,y*6.2+4),grain=field[key(i*3+j,j*5-i)],fiber=noise(side*141+51,along*48+17);
const boundary=Math.min(bent-cuts[s],cuts[s+1]-bent)*r;
const fringe=(noise(along*54+s*11,side*89)-.5)*.007;
const G=(side+.021*Math.sin(along*12+s*1.43)+.007*Math.sin(along*32+side*12))*51+13*s;
const H=along*15.5+.27*Math.sin(side*74+along*8)+.46*noise(side*12+95,along*9)+s*14;
const ix=Math.floor(G),iy=Math.floor(H),fx=G-ix,fy=H-iy;
let d1=10,d2=10,cell=0,cx=0,cy=0;
for(let v=-1;v<=1;v++)for(let u=-1;u<=1;u++){
const id=key(ix+u,iy+v),dx=fx-u-jx[id],dy=fy-v-jy[id],d=dx*dx+dy*dy;
if(d<d1){d2=d1;d1=d;cx=dx;cy=dy;cell=id}else if(d<d2)d2=d
}
const gap=Math.sqrt(d2)-Math.sqrt(d1),wall=1-smooth(.006,.135,gap);
const dome=smooth(.008,.23,gap)*Math.sqrt(Math.max(0,1-.97*d1));
const cellTone=field[cell],under=noise(side*26+s*19,along*10+14);
const tone=clamp(.45+.55*(cellTone-.5)+.29*(under-.5)+.21*(cloud-.5)-.34*cx+.14*cy+.11*dome+.09*r+.08*Math.sin(s*3.5),0,1);
const catchlight=Math.max(0,1-31*(cx+.22)*(cx+.22)-11*(cy-.02)*(cy-.02))*(.30+.70*cellTone)*(.35+.65*fiber);
let red=232+20*tone+4*dome,green=72+101*tone+10*r+9*fiber,blue=5+28*tone+7*fiber;
const film=wall*(.19+.32*under);
red=mix(red,255,film);green=mix(green,190+24*cloud,film);blue=mix(blue,63+45*fiber,film);
green+=18*catchlight;blue+=21*catchlight;
const rim=r+.012*(noise(x*15+21,y*15+7)-.5)+.006*(fiber-.5)+.004*Math.sin(23*a);
const innerCore=.071+.025*Math.pow(Math.abs(Math.sin(6.1*a+.4)),3)+.012*(cloud-.5);
const membrane=1-smooth(.0015,.0095+.006*(1-r),boundary+fringe);
const membraneHalo=1-smooth(.002,.028,boundary+fringe);
const core=1-smooth(innerCore-.011,innerCore+.007,r);
const pith=Math.max(membrane,core,smooth(.931,.946,rim));
const peel=smooth(.971,.982,rim);
const pithGrain=.46*noise(x*111,y*111)+.32*fiber+.22*grain;
red=mix(red,255,membraneHalo*.15);green=mix(green,202,membraneHalo*.15);blue=mix(blue,100,membraneHalo*.15);
red=mix(red,248+7*pithGrain,pith);green=mix(green,207+34*pithGrain,pith);blue=mix(blue,133+68*pithGrain,pith);
red=mix(red,248+5*fiber,peel);green=mix(green,117+37*cloud+14*grain,peel);blue=mix(blue,13+14*cloud,peel);
rgba[o]=clamp(red,0,255);rgba[o+1]=clamp(green,0,255);rgba[o+2]=clamp(blue,0,255);rgba[o+3]=255;
relief[k]=mix(.0046*dome+.0014*(fiber-.5)+.00055*grain,-.0015+.0025*pithGrain,pith)+.001*peel*grain;
material[o+2]=Math.round(255*clamp(.035+.07*wall+.79*pith+.12*peel,0,1));
material[o+3]=Math.round(255*clamp(.18+.53*dome+.17*catchlight,0,1))
}
}
for(let j=0;j<h;j++)for(let i=0;i<w;i++){
const k=i+j*w,o=4*k;
const nx=(relief[j*w+Math.max(0,i-1)]-relief[j*w+Math.min(w-1,i+1)])*w*.25;
const ny=(relief[Math.max(0,j-1)*w+i]-relief[Math.min(h-1,j+1)*w+i])*h*.5;
material[o]=Math.round(127.5+127.5*clamp(nx,-1,1));material[o+1]=Math.round(127.5+127.5*clamp(ny,-1,1))
}
return {w,h,rgba,material}
}
const RADIUS=1.64,HEIGHT=1.56,BASE=.177,PLATE=2.39;
function plateTop(r){return .174+.151*smooth(1.73,2.34,r)+.009*Math.exp(-Math.pow((r-2.32)/.050,2))}
function restPoint(r,a,q){
const nx=r*Math.cos(a),ny=r*Math.sin(a),bend=cutAngle(a,r),s=segment(bend);
const lobe=Math.sin(PI*clamp((bend-cuts[s])/(cuts[s+1]-cuts[s]),0,1));
const organic=1+.006*Math.sin(3*a+.85)+.005*Math.sin(7*a+.3);
const bevel=1-.018*Math.pow(Math.abs(q),8),curve=Math.sin(PI*Math.min(1,r));
const depth=.418+.024*nx+.055*(1-r*r)+.050*lobe*curve-.032*smooth(.952,1,r)*Math.pow(Math.abs(q),4);
return [RADIUS*nx*organic*bevel,BASE+HEIGHT*ny*organic*bevel+.013*(1-ny)*Math.pow(Math.abs(q),6),q*depth-.045*ny+.021*nx]
}
let canvas=byId('world');
const stage=byId('stage');
let gl=null;
try{gl=canvas.getContext('webgl',{alpha:false,antialias:true,depth:true,stencil:false,premultipliedAlpha:false,powerPreference:'high-performance'})}catch(ignore){}
const fruitMaps=makeFruitMaps();
// A triangular-prism lattice split into conforming tetrahedra. Edge elasticity
// and signed tetrahedron volumes are solved implicitly with XPBD multipliers.
const NA=16,NR=4,NZ=2,STRIDE=1+NR*(NA+1),COUNT=STRIDE*(NZ+1),STEP=1/100;
const rest=new Float64Array(3*COUNT),pos=new Float64Array(3*COUNT),vel=new Float64Array(3*COUNT),prev=new Float64Array(3*COUNT),adhesion=new Float64Array(COUNT);
const node=(l,r,a)=>l*STRIDE+(r===0?0:1+(r-1)*(NA+1)+a);
for(let l=0;l<=NZ;l++)for(let r=0;r<=NR;r++)for(let a=0;a<=(r?NA:0);a++){
const n=node(l,r,a),p=restPoint(r/NR,PI*a/NA,2*l/NZ-1);rest.set(p,3*n);adhesion[n]=Math.exp(-15*(p[1]-BASE))
}
pos.set(rest);
const tets=[],edges=[],edgeSet=new Set();
function addEdge(i,j){
const tag=Math.min(i,j)*COUNT+Math.max(i,j);if(edgeSet.has(tag))return;edgeSet.add(tag);
const a=3*i,b=3*j,len=Math.hypot(rest[a]-rest[b],rest[a+1]-rest[b+1],rest[a+2]-rest[b+2]);
edges.push({a,b,len,lambda:0,reference:len})
}
function addTet(i,j,k,l){
const a=i*3,b=j*3,c=k*3,d=l*3;
const B=[rest[b]-rest[a],rest[b+1]-rest[a+1],rest[b+2]-rest[a+2]],C=[rest[c]-rest[a],rest[c+1]-rest[a+1],rest[c+2]-rest[a+2]],D=[rest[d]-rest[a],rest[d+1]-rest[a+1],rest[d+2]-rest[a+2]];
const gb=cross(C,D),gc=cross(D,B),gd=cross(B,C),ga=gb.map((v,n)=>-v-gc[n]-gd[n]);
tets.push({a,b,c,d,six:dot(B,gb),scale:dot(ga,ga)+dot(gb,gb)+dot(gc,gc)+dot(gd,gd),lambda:0});
addEdge(i,j);addEdge(i,k);addEdge(i,l);addEdge(j,k);addEdge(j,l);addEdge(k,l)
}
function prism(i,j,k){
const tri=[i,j,k].sort((a,b)=>a-b);
for(let z=0;z<NZ;z++){
const a=tri[0]+z*STRIDE,b=tri[1]+z*STRIDE,c=tri[2]+z*STRIDE;
addTet(a,b,c,c+STRIDE);addTet(a,b,b+STRIDE,c+STRIDE);addTet(a,a+STRIDE,b+STRIDE,c+STRIDE)
}
}
for(let a=0;a<NA;a++){
prism(0,node(0,1,a),node(0,1,a+1));
for(let r=1;r<NR;r++){
const i=node(0,r,a),j=node(0,r,a+1),k=node(0,r+1,a),l=node(0,r+1,a+1);
prism(i,k,l);prism(i,l,j)
}
}
function binding(rad,theta,q){
const r=clamp(rad*NR,0,NR),a=clamp(theta*NA/PI,0,NA),z=clamp((q+1)*NZ*.5,0,NZ);
const ri=Math.min(NR-1,Math.floor(r)),ai=Math.min(NA-1,Math.floor(a)),zi=Math.min(NZ-1,Math.floor(z));
const fr=r-ri,fa=a-ai,fz=z-zi,ids=[],weights=[];
for(let l=0;l<2;l++)for(let j=0;j<2;j++)for(let i=0;i<2;i++){
ids.push(node(zi+l,ri+j,ai+i)*3);weights.push((l?fz:1-fz)*(j?fr:1-fr)*(i?fa:1-fa))
}
return {ids,weights}
}
function skinPoint(r,a,q){
const p=restPoint(r,a,q),map=binding(r,a,q);
for(let k=0;k<8;k++){const n=map.ids[k],w=map.weights[k];for(let c=0;c<3;c++)p[c]+=w*(pos[n+c]-rest[n+c])}
p[1]=Math.max(p[1],plateTop(Math.hypot(p[0],p[2]))+.0008);return p
}
function makeSkin(detailed){
const xs=[],params=[],ids=[],weights=[],indices=[];
function grid(na,nr,point,flip){
const offset=xs.length/3;
for(let j=0;j<=nr;j++)for(let i=0;i<=na;i++){
const [r,a,q,kind]=point(i/na,j/nr),b=binding(r,a,q);
xs.push(...restPoint(r,a,q));params.push(r*Math.cos(a),r*Math.sin(a),q,kind);
ids.push(...b.ids);weights.push(...b.weights)
}
for(let j=0;j<nr;j++)for(let i=0;i<na;i++){
const a=offset+j*(na+1)+i,b=a+1,c=a+na+1,d=c+1;
if(flip)indices.push(a,c,b,b,c,d);else indices.push(a,b,c,b,d,c)
}
}
const a=detailed?108:32,r=detailed?29:8,z=detailed?14:6;
grid(a,r,(u,v)=>[v,u*PI,1,0],true);
grid(a,r,(u,v)=>[v,u*PI,-1,0],false);
grid(a,z,(u,v)=>[1,u*PI,2*v-1,1],false);
grid(detailed?56:20,z,(u,v)=>[Math.abs(2*u-1),u<.5?PI:0,2*v-1,2],false);
return {original:new Float32Array(xs),p:new Float32Array(xs),n:new Float32Array(xs.length),uv:new Float32Array(params),ids:new Uint16Array(ids),w:new Float32Array(weights),idx:new Uint16Array(indices)}
}
let skin=makeSkin(!!gl);
const displacement=new Float32Array(3*COUNT);
function updateSkin(){
const m=skin,p=m.p,n=m.n,idx=m.idx;
for(let i=0;i<pos.length;i++)displacement[i]=pos[i]-rest[i];
for(let v=0,i=0;v<p.length/3;v++,i+=3){
let x=m.original[i],y=m.original[i+1],z=m.original[i+2];
for(let j=v*8,end=j+8;j<end;j++){
const w=m.w[j];if(w===0)continue;const id=m.ids[j];
x+=w*displacement[id];y+=w*displacement[id+1];z+=w*displacement[id+2]
}
const r2=x*x+z*z,floor=r2<2.9929 ? .174 : plateTop(Math.sqrt(r2));
p[i]=x;p[i+1]=Math.max(y,floor+.0006);p[i+2]=z
}
n.fill(0);
for(let i=0;i<idx.length;i+=3){
const a=idx[i]*3,b=idx[i+1]*3,c=idx[i+2]*3;
const bx=p[b]-p[a],by=p[b+1]-p[a+1],bz=p[b+2]-p[a+2],cx=p[c]-p[a],cy=p[c+1]-p[a+1],cz=p[c+2]-p[a+2];
const nx=by*cz-bz*cy,ny=bz*cx-bx*cz,nz=bx*cy-by*cx;
n[a]+=nx;n[a+1]+=ny;n[a+2]+=nz;n[b]+=nx;n[b+1]+=ny;n[b+2]+=nz;n[c]+=nx;n[c+1]+=ny;n[c+2]+=nz
}
for(let j=0,i=0;i<n.length;i+=3,j+=4){
const d=Math.hypot(n[i],n[i+1],n[i+2]);
if(d<1e-9){n[i]=0;n[i+1]=m.uv[j+3]===2?-1:0;n[i+2]=m.uv[j+3]===0?Math.sign(m.uv[j+2]):0}
else{n[i]/=d;n[i+1]/=d;n[i+2]/=d}
}
}
let firm=.45,grab=null,pressed=false,minPress=0,pressure=0,doseTime=0,doseCount=0;
let asleep=true,quietTime=0,speed=0,strain=0,equilibrium=null,shadowShift=[0,0],droplets=[];
let meshDirty=true,sceneDirty=true,simAge=0;
function wake(){asleep=false;quietTime=0;sceneDirty=true}
function touchBody(point,inward,artificial){
const weights=new Float32Array(COUNT),start=new Float64Array(pos);
for(let i=0;i<COUNT;i++){
const k=i*3,dx=pos[k]-point[0],dy=pos[k+1]-point[1],dz=pos[k+2]-point[2];
const w=Math.exp(-(dx*dx+dy*dy+1.05*dz*dz)/.39);weights[i]=w;
vel[k]+=w*inward[0]*2.0;vel[k+1]+=w*(inward[1]*1.9-.54);vel[k+2]+=w*inward[2]*2.0
}
grab={weights,start,origin:point.slice(),offset:[0,0,0],inward,age:0,until:Infinity,dragged:false,artificial:!!artificial};wake()
}
function releaseBody(immediate){
if(!grab)return;
if(!immediate&&!grab.dragged&&grab.age<.145){grab.until=.145;return}
grab=null;wake()
}
function startPress(){
if(pressed)return;pressed=true;minPress=.62;doseTime=0;doseCount=0;wake();
byId('squeeze').classList.add('active')
}
function finishPress(){pressed=false}
function solveVolumes(alpha){
for(let i=0;i<tets.length;i++){
const t=tets[i],a=t.a,b=t.b,c=t.c,d=t.d;
const bx=pos[b]-pos[a],by=pos[b+1]-pos[a+1],bz=pos[b+2]-pos[a+2],cx=pos[c]-pos[a],cy=pos[c+1]-pos[a+1],cz=pos[c+2]-pos[a+2],dx=pos[d]-pos[a],dy=pos[d+1]-pos[a+1],dz=pos[d+2]-pos[a+2];
const ux=cy*dz-cz*dy,uy=cz*dx-cx*dz,uz=cx*dy-cy*dx,vx=dy*bz-dz*by,vy=dz*bx-dx*bz,vz=dx*by-dy*bx,wx=by*cz-bz*cy,wy=bz*cx-bx*cz,wz=bx*cy-by*cx;
const ax=-ux-vx-wx,ay=-uy-vy-wy,az=-uz-vz-wz,A=t.scale*alpha;
const den=ax*ax+ay*ay+az*az+ux*ux+uy*uy+uz*uz+vx*vx+vy*vy+vz*vz+wx*wx+wy*wy+wz*wz+A;
const dl=(t.six-(bx*ux+by*uy+bz*uz)-A*t.lambda)/(den+1e-12);t.lambda+=dl;
pos[a]+=ax*dl;pos[a+1]+=ay*dl;pos[a+2]+=az*dl;pos[b]+=ux*dl;pos[b+1]+=uy*dl;pos[b+2]+=uz*dl;
pos[c]+=vx*dl;pos[c+1]+=vy*dl;pos[c+2]+=vz*dl;pos[d]+=wx*dl;pos[d+1]+=wy*dl;pos[d+2]+=wz*dl
}
}
function integrate(h,warming){
simAge+=h;
const driving=pressed||minPress>0;minPress=Math.max(0,minPress-h);
pressure+=((driving?1:0)-pressure)*(1-Math.exp(-h*(driving?9:19)));
if(!driving&&pressure<.001)pressure=0;
if(driving){
doseTime+=h;
if(doseCount<4&&doseTime>.17+doseCount*.132){emitJuice(doseCount);doseCount++}
}
if(grab){grab.age+=h;if(grab.age>=grab.until)grab=null}
const offset=grab?grab.offset:[0,0,0],amount=grab?.inward;
const indent=grab && grab.dragged ? .032 : (.25-.055*firm);
prev.set(pos);
for(let i=0;i<COUNT;i++){
const k=i*3,bond=adhesion[i],memory=8+firm*19,baseSpring=135*bond;
let ax=(rest[k]-pos[k])*(memory+baseSpring),ay=(rest[k+1]-pos[k+1])*memory-2.8,az=(rest[k+2]-pos[k+2])*(memory+baseSpring);
const w=grab?grab.weights[i]:0;
if(w>.001){
const gain=w*(660+firm*150),damp=w*22;
ax+=gain*(grab.start[k]+offset[0]+amount[0]*indent-pos[k])-damp*vel[k];
ay+=gain*(grab.start[k+1]+offset[1]+(amount[1]-.26)*indent-pos[k+1])-damp*vel[k+1];
az+=gain*(grab.start[k+2]+offset[2]+amount[2]*indent-pos[k+2])-damp*vel[k+2]
}
const damping=1/(1+h*(1.63+firm*.91+bond*1.6));
vel[k]=(vel[k]+ax*h)*damping;vel[k+1]=(vel[k+1]+ay*h)*damping;vel[k+2]=(vel[k+2]+az*h)*damping;
pos[k]+=vel[k]*h;pos[k+1]+=vel[k+1]*h;pos[k+2]+=vel[k+2]*h
}
for(let i=0;i<edges.length;i++)edges[i].lambda=0;
for(let i=0;i<tets.length;i++)tets[i].lambda=0;
const softness=1-firm,edgeAlpha=(.00029+.0038*softness*softness)/(h*h),volumeAlpha=.048+.16*softness;
const lid=BASE+HEIGHT*(1-pressure*(.40-.115*firm));
for(let iteration=0;iteration<4;iteration++){
for(let e=0;e<edges.length;e++){
const edge=edges[iteration%2?edges.length-1-e:e],a=edge.a,b=edge.b;
const x=pos[b]-pos[a],y=pos[b+1]-pos[a+1],z=pos[b+2]-pos[a+2],d=Math.sqrt(x*x+y*y+z*z)||1e-9;
const dl=(edge.len-d-edgeAlpha*edge.lambda)/(2+edgeAlpha);edge.lambda+=dl;const g=dl/d;
pos[a]-=x*g;pos[a+1]-=y*g;pos[a+2]-=z*g;pos[b]+=x*g;pos[b+1]+=y*g;pos[b+2]+=z*g
}
solveVolumes(volumeAlpha);
for(let k=0;k<pos.length;k+=3){
const x=pos[k],z=pos[k+2],r2=x*x+z*z;
if(pressure>.002)pos[k+1]=Math.min(pos[k+1],lid+.095*x*x+.065*z*z);
const floor=r2<2.9929 ? .174 : plateTop(Math.sqrt(r2));
if(pos[k+1]<floor)pos[k+1]=floor;
if(r2>5.24){const scale=2.289/Math.sqrt(r2);pos[k]*=scale;pos[k+2]*=scale}
}
}
let kinetic=0,dxSum=0,dzSum=0;
for(let k=0;k<pos.length;k+=3){
let x=(pos[k]-prev[k])/h,y=(pos[k+1]-prev[k+1])/h,z=(pos[k+2]-prev[k+2])/h;
const r2=pos[k]*pos[k]+pos[k+2]*pos[k+2];
if(pos[k+1]<=(r2<2.9929 ? .174 : plateTop(Math.sqrt(r2)))+.00035){x*=.87;z*=.87;if(y<0)y=0}
const v2=x*x+y*y+z*z,cap=v2>49?7/Math.sqrt(v2):1;
vel[k]=x*cap;vel[k+1]=y*cap;vel[k+2]=z*cap;kinetic+=v2;
dxSum+=pos[k]-rest[k];dzSum+=pos[k+2]-rest[k+2]
}
speed=Math.sqrt(kinetic/COUNT);shadowShift[0]=dxSum/COUNT;shadowShift[1]=dzSum/COUNT;
quietTime=!grab&&!driving&&pressure===0&&speed<.013?quietTime+h:0;
if(!warming&&quietTime>.55){asleep=true;vel.fill(0)}
meshDirty=true;sceneDirty=true
}
function measure(){
let total=0;
for(let i=0;i<edges.length;i++){
const e=edges[i],a=e.a,b=e.b,d=Math.hypot(pos[a]-pos[b],pos[a+1]-pos[b+1],pos[a+2]-pos[b+2])/e.reference-1;
total+=d*d
}
strain=100*Math.sqrt(total/edges.length)
}
function emitJuice(n){
const sign=n%3===1?-1:1;
const u=sign*(.26+.42*rand()),v=.19+.31*rand(),r=.048+rand()*.038;
droplets.push({u,v,sign,r,phase:0,fall:.06+rand()*.09,age:0,land:0,p:[0,0,0],vx:sign*(.22+.24*rand()),vz:.72+.46*rand(),size:[r,r,r]});
if(droplets.length>28)droplets.shift()
}
function moveDrops(dt){
for(let i=droplets.length-1;i>=0;i--){
const d=droplets[i];d.age+=dt;
if(d.phase===0){
d.fall+=1.45*dt;d.v=Math.max(.009,d.v-d.fall*dt);d.u+=d.sign*.065*dt;
const r=Math.hypot(d.u,d.v),a=Math.atan2(d.v,d.u),p=skinPoint(r,a,1);
d.p=[p[0],p[1]+.008,p[2]+d.r*.45];d.size=[d.r*.74,d.r*(1.18+.49*d.fall),d.r*.83];
if(d.v<.011||d.p[1]<=plateTop(Math.hypot(d.p[0],d.p[2]))+d.r*.68){d.phase=1;d.land=0}
}else{
d.land+=dt;d.p[0]+=d.vx*dt;d.p[2]+=d.vz*dt;
const radius=Math.hypot(d.p[0],d.p[2]);
if(radius>1.7){const slope=smooth(1.7,2.3,radius)*2.4;d.vx-=slope*d.p[0]/radius*dt;d.vz-=slope*d.p[2]/radius*dt}
const drag=Math.exp(-dt*2.15);d.vx*=drag;d.vz*=drag;
if(d.land>2.7){d.vx=0;d.vz=0}
const spread=1-Math.exp(-6*d.land),fade=1-smooth(10,12,d.land);
d.size=[d.r*(1.05+spread*.43)*fade,d.r*(.67-.36*spread)*fade,d.r*(1.12+spread*.62)*fade];
d.p[1]=plateTop(radius)+d.size[1]*.56+.001;
if(d.land>=12)droplets.splice(i,1)
}
}
}
const camera={az:.405,el:.455,dist:9.8,target:[0,.39,0],eye:[0,0,0],forward:[0,0,-1],right:[1,0,0],up:[0,1,0],lx:1,ly:1};
let W=1,H=1,aspect=1;
function updateCamera(){
const c=camera,ca=Math.cos(c.az),sa=Math.sin(c.az),ce=Math.cos(c.el),se=Math.sin(c.el);
const d=[sa*ce,se,ca*ce];c.eye=c.target.map((v,i)=>v+d[i]*c.dist);c.forward=d.map(v=>-v);c.right=[ca,0,-sa];c.up=cross(c.right,c.forward);
const film=Math.max(3.65,5.88/aspect);c.ly=2*c.dist/film;c.lx=c.ly/aspect;
const axes=byId('axes').children,styles=['#9b543c','#676c48','#7b7f83'];
for(let i=0;i<3;i++){
const x=24+c.right[i]*14,y=23-c.up[i]*14;
axes[i].setAttribute('d','M24 23L'+x.toFixed(2)+' '+y.toFixed(2));axes[i].setAttribute('stroke',styles[i]);axes[i].setAttribute('stroke-width','1.5');
axes[i+3].setAttribute('x',24+c.right[i]*20-2);axes[i+3].setAttribute('y',25-c.up[i]*20);axes[i+3].setAttribute('fill',styles[i])
}
sceneDirty=true
}
function project(p){
const c=camera,q=[p[0]-c.eye[0],p[1]-c.eye[1],p[2]-c.eye[2]],d=dot(q,c.forward);
return [(1+dot(q,c.right)*c.lx/d)*W*.5,(1-dot(q,c.up)*c.ly/d)*H*.5,d]
}
function rayAt(sx,sy){
const c=camera;return unit(c.forward.map((f,i)=>f+c.right[i]*sx/c.lx+c.up[i]*sy/c.ly))
}
function pick(sx,sy){
const ray=rayAt(sx,sy),eye=camera.eye,m=skin,p=m.p;
let best=Infinity;
for(let n=0;n<m.idx.length;n+=3){
const a=m.idx[n]*3,b=m.idx[n+1]*3,c=m.idx[n+2]*3,e1x=p[b]-p[a],e1y=p[b+1]-p[a+1],e1z=p[b+2]-p[a+2],e2x=p[c]-p[a],e2y=p[c+1]-p[a+1],e2z=p[c+2]-p[a+2];
const hx=ray[1]*e2z-ray[2]*e2y,hy=ray[2]*e2x-ray[0]*e2z,hz=ray[0]*e2y-ray[1]*e2x,det=e1x*hx+e1y*hy+e1z*hz;
if(Math.abs(det)<1e-9)continue;
const inv=1/det,tx=eye[0]-p[a],ty=eye[1]-p[a+1],tz=eye[2]-p[a+2],u=(tx*hx+ty*hy+tz*hz)*inv;
if(u<0||u>1)continue;
const qx=ty*e1z-tz*e1y,qy=tz*e1x-tx*e1z,qz=tx*e1y-ty*e1x,v=(ray[0]*qx+ray[1]*qy+ray[2]*qz)*inv;
if(v<0||u+v>1)continue;
const dist=(e2x*qx+e2y*qy+e2z*qz)*inv;if(dist>.01&&dist<best)best=dist
}
return Number.isFinite(best)?{point:eye.map((x,i)=>x+ray[i]*best),ray,depth:best*dot(ray,camera.forward)}:null
}
function makePlate(){
const profile=[];
for(let k=0;k<=52;k++){const r=2.342*k/52;profile.push([r,plateTop(r)])}
profile.push([2.357,.332],[2.372,.328],[2.383,.318],[PLATE,.304],[2.388,.287],[2.38,.274],[2.365,.260],[2.340,.250],[2.30,.243],[2.21,.222],[2.08,.183],[1.91,.139],[1.76,.104],[1.61,.083],[1.49,.068],[1.46,.055],[1.449,.025],[1.435,.011],[1.408,.005],[1.368,.005],[1.343,.015],[1.331,.039],[1.316,.053],[1.26,.061],[.92,.066],[.5,.070],[0,.072]);
const p=[],n=[],idx=[],sides=144;
for(let j=0;j<profile.length;j++){
const a=profile[Math.max(j-1,0)],b=profile[Math.min(j+1,profile.length-1)],dr=b[0]-a[0],dy=b[1]-a[1],len=Math.hypot(dr,dy)||1;
for(let i=0;i<=sides;i++){
const t=i*TAU/sides,x=Math.cos(t),z=Math.sin(t);p.push(profile[j][0]*x,profile[j][1],profile[j][0]*z);n.push(-dy*x/len,dr/len,-dy*z/len);
if(i<sides&&j+1<profile.length){const k=j*(sides+1)+i;idx.push(k,k+1,k+sides+1,k+1,k+sides+2,k+sides+1)}
}
}
return {p:new Float32Array(p),n:new Float32Array(n),idx:new Uint16Array(idx)}
}
function makeBead(){
const p=[],idx=[],nx=24,ny=16;
for(let j=0;j<=ny;j++)for(let i=0;i<=nx;i++){
const t=j*PI/ny,a=i*TAU/nx;p.push(Math.sin(t)*Math.cos(a),Math.cos(t),Math.sin(t)*Math.sin(a));
if(i<nx&&j<ny){const k=j*(nx+1)+i;idx.push(k,k+1,k+nx+1,k+1,k+nx+2,k+nx+1)}
}
return {p:new Float32Array(p),idx:new Uint16Array(idx)}
}
function makeGLRenderer(g){
const precision=g.getShaderPrecisionFormat(g.FRAGMENT_SHADER,g.HIGH_FLOAT).precision?'highp':'mediump';
const prefix='precision '+precision+' float;\n';
const source=id=>byId('gl-'+id).textContent;
function compile(type,src){
const s=g.createShader(type);g.shaderSource(s,prefix+src);g.compileShader(s);
if(!g.getShaderParameter(s,g.COMPILE_STATUS))throw new Error(g.getShaderInfoLog(s)||'Shader compilation failed');
return s
}
function program(v,f,lighting){
const p=g.createProgram(),vs=compile(g.VERTEX_SHADER,(v==='screen'?'':source('cam'))+source(v)),fs=compile(g.FRAGMENT_SHADER,(f==='copy'?'':source('cam'))+(lighting?source('light'):'')+source(f));
g.attachShader(p,vs);g.attachShader(p,fs);g.bindAttribLocation(p,0,'aPosition');g.bindAttribLocation(p,1,'aNormal');g.bindAttribLocation(p,2,'aParam');g.linkProgram(p);
if(!g.getProgramParameter(p,g.LINK_STATUS))throw new Error(g.getProgramInfoLog(p)||'Shader linking failed');
g.deleteShader(vs);g.deleteShader(fs);
const u={};for(let k=0;k<g.getProgramParameter(p,g.ACTIVE_UNIFORMS);k++){const n=g.getActiveUniform(p,k).name;u[n.split('[')[0]]=g.getUniformLocation(p,n)}
return {p,u}
}
const floor=program('screen','floor',true),ceramic=program('geo','plate',true),depth=program('geo','depth',false),copy=program('screen','copy',false),orange=program('geo','fruit',true),juice=program('dropvertex','juice',true);
function use(m){
g.useProgram(m.p);const u=m.u,c=camera;
if(u.uEye)g.uniform3fv(u.uEye,c.eye);if(u.uRight)g.uniform3fv(u.uRight,c.right);if(u.uUp)g.uniform3fv(u.uUp,c.up);
if(u.uForward)g.uniform3fv(u.uForward,c.forward);if(u.uLens)g.uniform2f(u.uLens,c.lx,c.ly);if(u.uPixels)g.uniform2f(u.uPixels,W,H)
}
function buffer(data,type,usage){
const b=g.createBuffer();g.bindBuffer(type,b);g.bufferData(type,data,usage);return b
}
function upload(m,dynamic){
const flag=dynamic?g.DYNAMIC_DRAW:g.STATIC_DRAW;
return {p:buffer(m.p,g.ARRAY_BUFFER,flag),n:m.n?buffer(m.n,g.ARRAY_BUFFER,flag):null,uv:m.uv?buffer(m.uv,g.ARRAY_BUFFER,g.STATIC_DRAW):null,idx:buffer(m.idx,g.ELEMENT_ARRAY_BUFFER,g.STATIC_DRAW),count:m.idx.length}
}
function attribute(k,b,size){if(b){g.bindBuffer(g.ARRAY_BUFFER,b);g.enableVertexAttribArray(k);g.vertexAttribPointer(k,size,g.FLOAT,false,0,0)}else g.disableVertexAttribArray(k)}
function drawMesh(m){attribute(0,m.p,3);attribute(1,m.n,3);attribute(2,m.uv,4);g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,m.idx);g.drawElements(g.TRIANGLES,m.count,g.UNSIGNED_SHORT,0)}
const quad=buffer(new Float32Array([-1,-1,1,-1,-1,1,1,1]),g.ARRAY_BUFFER,g.STATIC_DRAW);
function drawQuad(){attribute(0,quad,2);attribute(1,null,3);attribute(2,null,4);g.drawArrays(g.TRIANGLE_STRIP,0,4)}
function texture(data){
const t=g.createTexture();g.bindTexture(g.TEXTURE_2D,t);
g.texImage2D(g.TEXTURE_2D,0,g.RGBA,fruitMaps.w,fruitMaps.h,0,g.RGBA,g.UNSIGNED_BYTE,data);
g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MIN_FILTER,g.LINEAR_MIPMAP_LINEAR);g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MAG_FILTER,g.LINEAR);
g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE);g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE);g.generateMipmap(g.TEXTURE_2D);return t
}
function bindTexture(u,t,slot){g.activeTexture(g.TEXTURE0+slot);g.bindTexture(g.TEXTURE_2D,t);g.uniform1i(u,slot)}
function target(linear){
const tex=g.createTexture(),fb=g.createFramebuffer(),rb=g.createRenderbuffer();
g.bindTexture(g.TEXTURE_2D,tex);g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MIN_FILTER,linear?g.LINEAR:g.NEAREST);
g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MAG_FILTER,linear?g.LINEAR:g.NEAREST);g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE);g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE);
return {tex,fb,rb}
}
const colorMap=texture(fruitMaps.rgba),normalMap=texture(fruitMaps.material),scene=target(true),far=target(false);
const body=upload(skin,true),plate=upload(makePlate(),false),bead=upload(makeBead(),false),spots=new Float32Array(8*3);
function resize(){
for(const t of [scene,far]){
g.bindTexture(g.TEXTURE_2D,t.tex);g.texImage2D(g.TEXTURE_2D,0,g.RGBA,W,H,0,g.RGBA,g.UNSIGNED_BYTE,null);
g.bindRenderbuffer(g.RENDERBUFFER,t.rb);g.renderbufferStorage(g.RENDERBUFFER,g.DEPTH_COMPONENT16,W,H);
g.bindFramebuffer(g.FRAMEBUFFER,t.fb);g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,t.tex,0);
g.framebufferRenderbuffer(g.FRAMEBUFFER,g.DEPTH_ATTACHMENT,g.RENDERBUFFER,t.rb);
if(g.checkFramebufferStatus(g.FRAMEBUFFER)!==g.FRAMEBUFFER_COMPLETE)throw new Error('Framebuffer unavailable')
}
g.bindFramebuffer(g.FRAMEBUFFER,null);g.viewport(0,0,W,H)
}
function sync(){
g.bindBuffer(g.ARRAY_BUFFER,body.p);g.bufferSubData(g.ARRAY_BUFFER,0,skin.p);
g.bindBuffer(g.ARRAY_BUFFER,body.n);g.bufferSubData(g.ARRAY_BUFFER,0,skin.n)
}
function draw(){
g.disable(g.BLEND);g.disable(g.DITHER);g.disable(g.CULL_FACE);g.depthMask(true);g.colorMask(true,true,true,true);
g.bindFramebuffer(g.FRAMEBUFFER,scene.fb);g.clearDepth(1);g.clearColor(.94,.845,.726,1);g.clear(g.COLOR_BUFFER_BIT|g.DEPTH_BUFFER_BIT);g.depthFunc(g.LEQUAL);
g.disable(g.DEPTH_TEST);use(floor);drawQuad();
g.enable(g.DEPTH_TEST);use(ceramic);g.uniform2fv(ceramic.u.uShift,shadowShift);g.uniform1f(ceramic.u.uPress,pressure);
spots.fill(0);for(let i=droplets.length-1,j=0;i>=0&&j<8;i--){const d=droplets[i];if(d.phase===1){spots[j*3]=d.p[0];spots[j*3+1]=d.p[2];spots[j*3+2]=d.size[0]*1.6;j++}}
g.uniform3fv(ceramic.u.uSpots,spots);bindTexture(ceramic.u.uFruit,colorMap,0);drawMesh(plate);
// The far surface measures the actual optical path through the deformed jelly.
g.bindFramebuffer(g.FRAMEBUFFER,far.fb);g.clearDepth(0);g.depthFunc(g.GREATER);g.clearColor(0,0,0,0);g.clear(g.COLOR_BUFFER_BIT|g.DEPTH_BUFFER_BIT);
use(depth);drawMesh(body);
g.bindFramebuffer(g.FRAMEBUFFER,null);g.depthFunc(g.LEQUAL);g.clearDepth(1);g.clear(g.DEPTH_BUFFER_BIT);
g.disable(g.DEPTH_TEST);use(copy);bindTexture(copy.u.uScene,scene.tex,0);drawQuad();
g.enable(g.DEPTH_TEST);g.colorMask(false,false,false,false);use(depth);drawMesh(plate);g.colorMask(true,true,true,true);
use(orange);bindTexture(orange.u.uFruit,colorMap,0);bindTexture(orange.u.uRelief,normalMap,1);bindTexture(orange.u.uScene,scene.tex,2);bindTexture(orange.u.uBack,far.tex,3);drawMesh(body);
if(droplets.length){
use(juice);bindTexture(juice.u.uScene,scene.tex,0);
for(const d of droplets){if(d.size[0]<.001)continue;g.uniform3fv(juice.u.uCenter,d.p);g.uniform3fv(juice.u.uScale,d.size);drawMesh(bead)}
}
}
return {draw,resize,sync}
}
// The software renderer projects the same moving body and cell atlas when a GPU context is unavailable.
function makePainter(){
const ctx=canvas.getContext('2d',{alpha:false}),face=document.createElement('canvas'),rind=document.createElement('canvas');
face.width=fruitMaps.w;face.height=fruitMaps.h;const cut=face.getContext('2d');
const img=cut.createImageData(face.width,face.height);
img.data.set(fruitMaps.rgba);
for(let i=0;i<img.data.length;i+=4){
const nx=fruitMaps.material[i]/127.5-1,ny=fruitMaps.material[i+1]/127.5-1,gloss=clamp((-nx*.60+ny*.42-.14)*.57,0,.33);
const intensity=.967+.053*ny-.031*nx;
for(let c=0;c<3;c++)img.data[i+c]=mix(img.data[i+c]*intensity,[255,246,216][c],gloss)
}
cut.putImageData(img,0,0);
rind.width=768;rind.height=128;const peel=rind.getContext('2d'),peelImg=peel.createImageData(rind.width,rind.height);
for(let j=0;j<rind.height;j++)for(let i=0;i<rind.width;i++){
const k=4*(i+rind.width*j),id=key(Math.floor(i/6),Math.floor(j/5)),x=i/6%1-jx[id],y=j/5%1-jy[id],pit=Math.exp(-21*(x*x+y*y)),v=noise(i/43,j/32),sp=field[key(i,j)];
peelImg.data[k]=247+6*v-17*pit;peelImg.data[k+1]=102+47*v+11*sp-16*pit;peelImg.data[k+2]=8+13*v+8*sp;peelImg.data[k+3]=255
}
peel.putImageData(peelImg,0,0);
function disc(radius,height){
ctx.beginPath();for(let k=0;k<=100;k++){const a=k*TAU/100,p=project([radius*Math.cos(a),height,radius*Math.sin(a)]);if(k===0)ctx.moveTo(p[0],p[1]);else ctx.lineTo(p[0],p[1])}ctx.closePath()
}
function oval(p,rx,rz,inner,outer){
const a=project(p),b=project([p[0]+rx,p[1],p[2]]),c=project([p[0],p[1],p[2]+rz]);
ctx.save();ctx.transform(b[0]-a[0],b[1]-a[1],c[0]-a[0],c[1]-a[1],a[0],a[1]);const gr=ctx.createRadialGradient(0,0,0,0,0,1);gr.addColorStop(0,inner);gr.addColorStop(1,outer);ctx.fillStyle=gr;ctx.fillRect(-1,-1,2,2);ctx.restore()
}
function triangle(image,s,t,u,a,b,c,shade,light){
const ax=t[0]-s[0],ay=t[1]-s[1],bx=u[0]-s[0],by=u[1]-s[1],det=ax*by-ay*bx;if(Math.abs(det)<.00001)return;
const x1=b[0]-a[0],x2=c[0]-a[0],y1=b[1]-a[1],y2=c[1]-a[1],m0=(x1*by-x2*ay)/det,m1=(y1*by-y2*ay)/det,m2=(ax*x2-bx*x1)/det,m3=(ax*y2-bx*y1)/det;
const mx=(a[0]+b[0]+c[0])/3,my=(a[1]+b[1]+c[1])/3;
ctx.save();ctx.beginPath();
for(let j=0;j<3;j++){const p=[a,b,c][j],dx=p[0]-mx,dy=p[1]-my,f=.54/(Math.hypot(dx,dy)||1);if(j===0)ctx.moveTo(p[0]+dx*f,p[1]+dy*f);else ctx.lineTo(p[0]+dx*f,p[1]+dy*f)}
ctx.closePath();ctx.clip();ctx.setTransform(m0,m1,m2,m3,a[0]-m0*s[0]-m2*s[1],a[1]-m1*s[0]-m3*s[1]);ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0);
const x=Math.min(a[0],b[0],c[0])-1,y=Math.min(a[1],b[1],c[1])-1,w=Math.max(a[0],b[0],c[0])-x+2,h=Math.max(a[1],b[1],c[1])-y+2;
if(shade>.005){ctx.fillStyle='rgba(76,29,8,'+shade+')';ctx.fillRect(x,y,w,h)}
if(light>.004){ctx.fillStyle='rgba(255,246,202,'+light+')';ctx.fillRect(x,y,w,h)}
ctx.restore()
}
function draw(){
ctx.setTransform(1,0,0,1,0,0);const bg=ctx.createLinearGradient(0,0,W,H);bg.addColorStop(0,'#fae8d1');bg.addColorStop(1,'#e7c3a5');ctx.fillStyle=bg;ctx.fillRect(0,0,W,H);
oval([.23,0,.24],2.85,2.72,'rgba(94,67,44,.46)','rgba(92,66,44,0)');
const edge=ctx.createLinearGradient(0,H*.45,0,H*.79);edge.addColorStop(0,'#d9d7c8');edge.addColorStop(1,'#b6b0a0');disc(2.355,.241);ctx.fillStyle=edge;ctx.fill();
disc(PLATE,.302);ctx.fillStyle='#f5f4e9';ctx.fill();disc(2.346,.33);ctx.fillStyle='#fffdf3';ctx.fill();
for(let j=0;j<22;j++){const r=2.29-j*.025,t=j/21;disc(r,plateTop(r));const v=Math.round(243-10*Math.sin(t*PI)+5*t);ctx.fillStyle='rgb('+v+','+(v-1)+','+(v-9)+')';ctx.fill()}
ctx.save();disc(2.32,.30);ctx.clip();oval([shadowShift[0]+.23,.184,shadowShift[1]+.3],1.94,1.05,'rgba(121,77,39,.43)','rgba(158,93,25,0)');
oval([shadowShift[0],.183,shadowShift[1]],1.9,.68,'rgba(96,52,20,.57)','rgba(110,64,30,0)');ctx.restore();
const projected=[],uvs=[],tri=[],m=skin;
for(let v=0;v<m.p.length/3;v++){
const j=3*v,k=4*v,kind=m.uv[k+3];projected.push(project([m.p[j],m.p[j+1],m.p[j+2]]));
uvs.push(kind===0?[(m.uv[k]*.5+.5)*face.width,m.uv[k+1]*face.height]:[(kind===1?Math.atan2(Math.max(0,m.uv[k+1]),m.uv[k])/PI:.5+.5*m.uv[k])*rind.width,(m.uv[k+2]*.5+.5)*rind.height])
}
for(let i=0;i<m.idx.length;i+=3){
const ia=m.idx[i],ib=m.idx[i+1],ic=m.idx[i+2],a=projected[ia],b=projected[ib],c=projected[ic];
if((b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0])<-.001)tri.push([i,a[2]+b[2]+c[2]])
}
tri.sort((a,b)=>b[1]-a[1]);
for(const el of tri){
const i=el[0],a=m.idx[i],b=m.idx[i+1],c=m.idx[i+2],kind=m.uv[4*a+3],n=unit([0,1,2].map(k=>m.n[3*a+k]+m.n[3*b+k]+m.n[3*c+k]));
const l=dot(n,[-.52,.77,.48]),glint=Math.pow(Math.max(0,dot(n,unit([-.16,.63,.87]))),32);
triangle(kind===0?face:rind,uvs[a],uvs[b],uvs[c],projected[a],projected[b],projected[c],clamp(.135-.13*l,0,.27),clamp(glint*.39+Math.max(0,n[1])*.032,0,.45))
}
for(const d of droplets){
const p=project(d.p),unitPx=H*camera.ly/(2*p[2]),rx=Math.max(.2,unitPx*d.size[0]),ry=Math.max(.2,unitPx*(d.size[1]*Math.cos(camera.el)+d.size[2]*Math.sin(camera.el)));
if(d.phase===0&&Math.cos(camera.az)<-.05)continue;
ctx.save();ctx.translate(p[0],p[1]);ctx.scale(rx,ry);const g=ctx.createRadialGradient(-.3,-.45,.06,.08,.14,1.18);g.addColorStop(0,'#fff7bb');g.addColorStop(.18,'#ffd166');g.addColorStop(.69,'#ee9627');g.addColorStop(1,'#bb6016');ctx.fillStyle=g;ctx.beginPath();ctx.arc(0,0,1,0,TAU);ctx.fill();ctx.restore()
}
}
return {draw,resize(){},sync(){}}
}
let renderer=null;
function usePainter(){
if(gl){const next=canvas.cloneNode(false);canvas.parentNode.replaceChild(next,canvas);canvas=next;gl=null;skin=makeSkin(false)}
updateSkin();renderer=makePainter();sceneDirty=true;meshDirty=true
}
if(gl){
try{renderer=makeGLRenderer(gl)}catch(error){usePainter()}
}else usePainter();
canvas.addEventListener('webglcontextlost',function(event){event.preventDefault();if(gl){usePainter();resizeScene()}});
function resizeScene(){
const box=stage.getBoundingClientRect(),ratio=Math.min(window.devicePixelRatio||1,gl?1.9:1.4,Math.sqrt(1780000/Math.max(1,box.width*box.height)));
const w=Math.max(2,Math.round(box.width*ratio)),h=Math.max(2,Math.round(box.height*ratio));
if(canvas.width===w&&canvas.height===h&&W===w&&H===h)return;
W=w;H=h;aspect=w/h;canvas.width=w;canvas.height=h;
try{renderer.resize()}catch(error){if(gl){usePainter();canvas.width=w;canvas.height=h;renderer.resize()}else throw error}
updateCamera();meshDirty=true;sceneDirty=true
}
const firmInput=byId('firmness'),squeezeButton=byId('squeeze'),demoButton=byId('demo'),frame=byId('frame'),expandButton=byId('expand');
const trace=byId('trace'),traceCtx=trace.getContext('2d'),samples=new Float32Array(144);
let traceIndex=0,traceTimer=0,traceDirty=true,feedbackTime=0,gesture=null,squeezePointer=null;
let demoOn=false,demoTime=0,savedFirm=45,demoStoppedOnButton=false;
function setFirm(value){
const v=Math.round(clamp(value,0,100)),change=Math.abs(firm-v/100)>.00001;
firm=v/100;firmInput.value=String(v);firmInput.style.setProperty('--position',v+'%');
byId('amount').textContent=v+'%';firmInput.setAttribute('aria-valuetext',v+' percent');
if(change)wake()
}
function resetMaterial(showFeedback){
pressed=false;minPress=0;pressure=0;doseTime=0;doseCount=0;grab=null;gesture=null;squeezePointer=null;droplets.length=0;
setFirm(45);pos.set(equilibrium||rest);prev.set(pos);vel.fill(0);asleep=true;speed=0;strain=0;quietTime=0;
shadowShift[0]=0;shadowShift[1]=0;camera.az=.405;camera.el=.455;updateCamera();
meshDirty=true;sceneDirty=true;samples.fill(0);traceIndex=0;traceDirty=true;feedbackTime=showFeedback ? .75 : 0;
squeezeButton.classList.remove('active')
}
function setExpanded(value){
frame.classList.toggle('expanded',value);document.body.classList.toggle('enlarged',value);expandButton.setAttribute('aria-pressed',String(value));
expandButton.setAttribute('aria-label',value?'Close expanded view':'Expand view');expandButton.title=value?'Close expanded view':'Expand view';
byId('expand-icon').setAttribute('href',value?'#i-contract':'#i-expand');resizeScene();traceDirty=true
}
expandButton.addEventListener('click',()=>setExpanded(!frame.classList.contains('expanded')));
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&frame.classList.contains('expanded')){setExpanded(false);expandButton.focus()}});
function demoUI(){
demoButton.setAttribute('aria-pressed',String(demoOn));byId('demo-icon').setAttribute('href',demoOn?'#i-stop':'#i-play');byId('demo-label').textContent=demoOn?'Stop demo':'Play demo'
}
function stopDemo(){
if(!demoOn)return;
demoOn=false;if(grab&&grab.artificial)releaseBody(true);finishPress();minPress=0;setFirm(savedFirm);demoUI()
}
function startDemo(){
if(demoOn)return;
savedFirm=Math.round(firm*100);resetMaterial(false);demoOn=true;demoTime=0;demoUI()
}
document.addEventListener('pointerdown',e=>{
demoStoppedOnButton=demoOn&&demoButton.contains(e.target);
if(demoOn)stopDemo()
},{capture:true,passive:true});
document.addEventListener('touchstart',e=>{
if(demoOn){demoStoppedOnButton=demoButton.contains(e.target);stopDemo()}
},{capture:true,passive:true});
demoButton.addEventListener('click',e=>{
if(demoStoppedOnButton&&e.detail!==0){demoStoppedOnButton=false;return}
demoStoppedOnButton=false;if(demoOn)stopDemo();else startDemo()
});
function coords(e){
const box=canvas.getBoundingClientRect();return [2*(e.clientX-box.left)/box.width-1,1-2*(e.clientY-box.top)/box.height]
}
stage.addEventListener('pointerdown',e=>{
if(e.target!==canvas||gesture||e.button!==0)return;
e.preventDefault();feedbackTime=0;
const point=coords(e),hit=pick(point[0],point[1]);
gesture={id:e.pointerId,mode:hit?'material':'orbit',sx:point[0],sy:point[1],clientX:e.clientX,clientY:e.clientY,depth:hit?hit.depth:0,az:camera.az,el:camera.el};
try{canvas.setPointerCapture(e.pointerId)}catch(ignore){}
if(hit)touchBody(hit.point,hit.ray,false)
});
stage.addEventListener('pointermove',e=>{
const g=gesture;if(!g||g.id!==e.pointerId)return;e.preventDefault();
const dx=e.clientX-g.clientX,dy=e.clientY-g.clientY;
if(g.mode==='orbit'){
camera.az=g.az-dx*.008;camera.el=clamp(g.el+dy*.005,.235,1.15);updateCamera();return
}
if(!grab)return;
const p=coords(e),x=(p[0]-g.sx)*g.depth/camera.lx,y=(p[1]-g.sy)*g.depth/camera.ly;
const scale=Math.min(1,(1.5-.20*firm)/(Math.hypot(x,y)||1));
for(let i=0;i<3;i++)grab.offset[i]=(camera.right[i]*x+camera.up[i]*y)*scale;
if(Math.hypot(dx,dy)>4)grab.dragged=true;wake()
});
function endGesture(e){
if(!gesture||e.pointerId!==gesture.id)return;
if(gesture.mode==='material')releaseBody(e.type==='pointercancel');gesture=null
}
stage.addEventListener('pointerup',endGesture);stage.addEventListener('pointercancel',endGesture);stage.addEventListener('lostpointercapture',endGesture);
stage.addEventListener('contextmenu',e=>{if(e.target===canvas)e.preventDefault()});
function autoTouch(r,a){
const p=skinPoint(r,a,1),ray=unit(p.map((v,i)=>v-camera.eye[i]));touchBody(p,ray,true)
}
stage.addEventListener('keydown',e=>{
if(e.target!==canvas)return;
if(e.code==='Space'||e.key==='Enter'){
e.preventDefault();if(e.repeat)return;stopDemo();autoTouch(.67,1.68);grab.artificial=false;grab.until=.17
}else if(e.key==='ArrowLeft'||e.key==='ArrowRight'){
e.preventDefault();stopDemo();camera.az+=(e.key==='ArrowRight'?1:-1)*.13;updateCamera()
}
});
firmInput.addEventListener('input',()=>{const value=+firmInput.value;if(demoOn)stopDemo();feedbackTime=0;setFirm(value)});
squeezeButton.addEventListener('pointerdown',e=>{
if(e.button!==0||squeezePointer!==null)return;e.preventDefault();feedbackTime=0;squeezePointer=e.pointerId;
try{squeezeButton.setPointerCapture(e.pointerId)}catch(ignore){}startPress()
});
function endButton(e){if(squeezePointer===e.pointerId){squeezePointer=null;finishPress()}}
squeezeButton.addEventListener('pointerup',endButton);squeezeButton.addEventListener('pointercancel',endButton);squeezeButton.addEventListener('lostpointercapture',endButton);
squeezeButton.addEventListener('contextmenu',e=>e.preventDefault());
squeezeButton.addEventListener('keydown',e=>{
if(e.code==='Space'||e.key==='Enter'){e.preventDefault();if(!e.repeat){stopDemo();feedbackTime=0;startPress()}}
});
squeezeButton.addEventListener('keyup',e=>{if(e.code==='Space'||e.key==='Enter'){e.preventDefault();finishPress()}});
squeezeButton.addEventListener('click',e=>{if(e.detail===0&&!pressed&&minPress<=0){stopDemo();startPress();finishPress()}});
byId('reset').addEventListener('click',()=>{stopDemo();resetMaterial(true)});
function clearInput(){
gesture=null;squeezePointer=null;if(grab)releaseBody(true);finishPress();minPress=0
}
window.addEventListener('blur',clearInput);
document.addEventListener('visibilitychange',()=>{if(document.hidden)clearInput()});
function runDemo(dt){
if(!demoOn)return;
const previous=demoTime;demoTime+=dt;const t=demoTime,passed=n=>previous<n&&t>=n;
if(passed(.82))autoTouch(.69,1.93);
if(passed(1.02))releaseBody(true);
if(passed(2.22))autoTouch(.70,.83);
if(passed(2.41))releaseBody(true);
if(passed(4.16))autoTouch(.78,2.13);
if(t>=4.16&&t<6.02&&grab){
const k=smooth(4.16,5.19,t);grab.dragged=k>.04;grab.offset=[-.81*k,.68*k,.29*k]
}
if(passed(6.02))releaseBody(true);
if(t>=7.52&&t<=8.38)setFirm(mix(45,22,smooth(7.52,8.34,t)));
if(passed(8.75))startPress();
if(passed(10.25))finishPress();
if(t>10.6&&t<13.15){camera.az=.405+.32*smooth(10.6,13.12,t);camera.el=.455+.073*smooth(10.6,13.12,t);updateCamera()}
if(t>=12.9&&t<13.84)setFirm(mix(22,79,smooth(12.9,13.80,t)));
if(passed(14.05))autoTouch(.74,1.27);
if(grab&&t>14.05&&t<15.31){const k=smooth(14.05,14.77,t);grab.dragged=k>.04;grab.offset=[.57*k,.42*k,.14*k]}
if(passed(15.31))releaseBody(true);
if(passed(16.78))startPress();
if(passed(17.29))finishPress();
if(passed(18.78))resetMaterial(true);
if(t>=20)demoTime=t-20
}
function marker(){
const el=byId('contact');
if(!demoOn||!grab||!grab.artificial){el.hidden=true;return}
const p=grab.origin.slice();let dx=0,dy=0,dz=0,total=0;
for(let j=0;j<COUNT;j++){
const k=3*j,w=Math.pow(grab.weights[j],4);dx+=w*(pos[k]-grab.start[k]);dy+=w*(pos[k+1]-grab.start[k+1]);dz+=w*(pos[k+2]-grab.start[k+2]);total+=w
}
p[0]+=dx/(total||1);p[1]+=dy/(total||1);p[2]+=dz/(total||1);const s=project(p);
el.style.left=s[0]*100/W+'%';el.style.top=s[1]*100/H+'%';el.hidden=false
}
let lastState='';
function showState(){
const force=pressed||minPress>0;
const label=force?'Squeezing':grab?(grab.dragged?'Stretching':'Poking'):feedbackTime>0?'Reset':!asleep?(speed>.15?'Wobbling':'Settling'):'At rest';
if(label!==lastState){byId('state-label').textContent=label;byId('state').dataset.active=String(label!=='At rest'&&label!=='Reset');lastState=label}
squeezeButton.classList.toggle('active',force);marker()
}
function drawTrace(){
const box=trace.getBoundingClientRect(),dpr=Math.min(window.devicePixelRatio||1,2),w=Math.max(2,Math.round(box.width*dpr)),h=Math.max(2,Math.round(box.height*dpr));
if(trace.width!==w||trace.height!==h){trace.width=w;trace.height=h}
const ctx=traceCtx;if(!ctx)return;
ctx.clearRect(0,0,w,h);const base=h*.70;
ctx.strokeStyle='#d7d6c9';ctx.lineWidth=dpr;ctx.setLineDash([dpr,3*dpr]);ctx.beginPath();ctx.moveTo(0,base);ctx.lineTo(w,base);ctx.stroke();ctx.setLineDash([]);
ctx.fillStyle='#d9d7c8';for(let x=0;x<w;x+=18*dpr)ctx.fillRect(x,base-2*dpr,dpr,4*dpr);
ctx.beginPath();
for(let i=0;i<samples.length;i++){
const value=samples[(traceIndex+i)%samples.length],x=i*(w-3*dpr)/(samples.length-1),y=base-Math.min(1,Math.log1p(value*.47)/2.5)*h*.61;
if(i===0)ctx.moveTo(x,y);else ctx.lineTo(x,y)
}
ctx.lineWidth=1.45*dpr;ctx.strokeStyle=strain>.12||!asleep?'#bf5727':'#a8a696';ctx.lineJoin='round';ctx.stroke();
const y=base-Math.min(1,Math.log1p(samples[(traceIndex+samples.length-1)%samples.length]*.47)/2.5)*h*.61;
ctx.fillStyle='#be5728';ctx.beginPath();ctx.arc(w-2.7*dpr,y,2*dpr,0,TAU);ctx.fill();
byId('reading').textContent=(strain<.045?0:strain).toFixed(1)+'%'
}
for(let i=0;i<105;i++)integrate(STEP,true);
equilibrium=new Float64Array(pos);
for(const e of edges)e.reference=Math.hypot(pos[e.a]-pos[e.b],pos[e.a+1]-pos[e.b+1],pos[e.a+2]-pos[e.b+2]);
resetMaterial(false);resizeScene();updateSkin();renderer.sync();meshDirty=false;renderer.draw();sceneDirty=false;drawTrace();
if(typeof ResizeObserver!=='undefined'){const observer=new ResizeObserver(()=>{resizeScene();traceDirty=true});observer.observe(stage);observer.observe(trace)}else window.addEventListener('resize',()=>{resizeScene();traceDirty=true});
window.addEventListener('resize',()=>{resizeScene();traceDirty=true},{passive:true});
function readDemoHash(){if(location.hash.toLowerCase()==='#demo')startDemo();else if(demoOn)stopDemo()}
window.addEventListener('hashchange',readDemoHash);readDemoHash();
let last=performance.now(),bank=0;
function animate(now){
const dt=clamp((now-last)/1000,0,.055);last=now;
if(!document.hidden){
runDemo(dt);feedbackTime=Math.max(0,feedbackTime-dt);
if(!asleep){bank+=dt;while(bank>=STEP&&!asleep){integrate(STEP,false);bank-=STEP}}else bank=0;
if(droplets.length){moveDrops(dt);sceneDirty=true}
if(meshDirty){updateSkin();renderer.sync();measure();meshDirty=false}
if(sceneDirty){renderer.draw();sceneDirty=false}
traceTimer+=dt;
if(traceTimer>=.066){traceTimer%=.066;samples[traceIndex]=strain;traceIndex=(traceIndex+1)%samples.length;traceDirty=true}
if(traceDirty){drawTrace();traceDirty=false}
showState()
}
requestAnimationFrame(animate)
}
requestAnimationFrame(animate);
})();
</script>
</body>
</html>
