Emery Estate / Three.js
Building Emery Estate in Three.js
Notes on the walls, camera path, and siding shader.
Emery Estate is a reconstruction of a historic house that you can walk through in a browser. The walls, openings, stairs and furniture are generated in TypeScript with Three.js. They're based on historic floor plans and photographs, plus my own interpretation where those sources don't say.
01
Doors and windows
Each wall is split into a grid of rectangles. The cuts go at the wall ends and at every door and window edge, so a rectangle is never part opening and part wall. That means testing its center is enough to classify the whole rectangle. If the center is inside an opening, the loop skips it. Otherwise it becomes a solid wall piece.
Each solid piece also gets a collision box. The visible wall and the collision both come from the same test, so I don't have to maintain a separate collision layout and keep it lined up with the geometry.
const = ([] + [ + 1]) / 2,
= ([] + [ + 1]) / 2;
if (( =>
( - ) < / 2 &&
> && <
)) ;Hover, focus, or tap dotted code. Open the variable guide below for the full walkthrough.
From the wall-cell loop. Material assignment happens after the opening test.
FOR each wall cell:
center = midpoint(cell)
IF center is inside a door or window:
skip this cell
ELSE:
build solid wall + collision boxSimplified steps for the same idea.
Build the wall around its openings.
- Split the wall into rectangles at its ends and at every door and window edge.
- Skip any rectangle whose center is inside an opening.
- Turn each remaining rectangle into a wall piece with its own collision box.
Similar to framing a real wall, where the door opening is laid out before the studs go in.
Variables & walkthrough7 definitions
Before this excerpt, the builder collects wall ends and opening edges into two sorted arrays. Neighboring cuts form rectangular cells, and the nested loops visit each cell once.
What the variables mean
us / ys- Arrays of cut positions.
usruns along the wall andysruns vertically. They include door and window edges, wall ends and finish boundaries. i / j- Current column and row indexes. The cell lies between
us[i]andus[i + 1]horizontally, and betweenys[j]andys[j + 1]vertically. u- The cell's horizontal center along this wall, in model coordinates. Depending on the wall's orientation, it maps to world X or Z.
y- The cell's vertical center, found by averaging its lower and upper edges.
openings / oopeningsis the list of door and window rectangles. Inside.some(...),ois the opening currently being tested.o.u / o.width- The opening's horizontal center and full width. Its side edges are at
o.u - o.width / 2ando.u + o.width / 2. o.bottom / o.top- The opening's lower and upper heights in model coordinates. These are two bounds, not a height and a width.
Read the code step by step
- Find the center
(us[i] + us[i + 1]) / 2averages the cell's left and right edges. The next expression does the same for its vertical edges. - Try the openings
.some(o => ...)returns true as soon as one opening passes the test.o =>names the input to that small test function. - Check both dimensions
Math.abs(u - o.u)is the horizontal distance from the opening's center, and it has to be less than half the opening's width. The twoycomparisons check the vertical bounds.&&requires all three conditions to hold. - Leave the gap
continuemoves to the next cell before any geometry is created. If the test fails, the laterboxFaces(...)call builds the solid wall piece and records its collision bounds.
Worked example · illustrative values
Try one cell
Illustrative numbers: an opening centered at 3, width 2, bottom 0 and top 2.2. Test a cell centered at (3.5, 1).
horizontal: |3.5 - 3| < 2 / 2
0.5 < 1 → true
vertical: 0 < 1 < 2.2 → true
result: skip this wall cellA cell centered at 4.5 fails the width test and stays solid. Opening edges are already in the cut arrays, so no cell straddles an opening boundary. That's why checking the center is enough to classify the whole cell.
Skipping a cell happens before either the mesh or the collision box is made, so the visible wall and the walkable space can't drift apart.
Source context: world.ts · Opening type at 163; cut arrays and loop at 235–239; solid-cell construction at 259; collision bounds at 94–111.
Reviewed source snapshot · lib/tour/world.ts · lines 238–239
The Code tab preserves the source; formatting only.
02
Smoothing the camera path
The guided tour moves the camera along a list of authored waypoints. Each channel is interpolated per segment with a fifth-degree polynomial. Neighboring segments share the slope at their common endpoint, and the second derivative is zero at both ends of every segment, so velocity and acceleration match where segments meet. The source comments mention that an earlier cubic version produced jolts at those joins.
The slopes are limited before the curve runs, to reduce overshoot, and the sampled position and orientation are filtered afterward. The continuity above describes the raw interpolator, before those filters. The curve doesn't keep speed constant or avoid obstacles. The waypoints are placed so the route goes through the doorways and up the narrow stair.
const = ;
return
+ ( - )*
+ *( - 6* + 8* - 3*)
+ *(-4* + 7* - 3*);Hover, focus, or tap dotted code. Open the variable guide below for the full walkthrough.
Curve excerpt. u is normalized segment time, h is the segment duration in seconds, and d holds the signed per-second slopes shared between segments.
limit slopes to curb overshoot
FOR each segment of the tour:
start with the slope shared with the previous segment
blend from start value to end value with a quintic curve
keep acceleration at zero at both ends
filter the sampled position and orientationSimplified steps for the same idea.
Keep velocity and acceleration continuous from one segment to the next.
- Limit the slopes first to reduce overshoot between waypoints.
- Start each segment with the slope the previous segment ended with.
- Make the curve hit both waypoint values with zero acceleration at each end.
The camera can speed up or slow down within a segment. Its velocity just has to match on both sides of each join.
Variables & walkthrough8 definitions
This function evaluates one tour channel: X, Y, Z, yaw or pitch. Earlier code builds the waypoint values and shared slopes, and the current segment supplies its index, duration and normalized progress.
What the variables mean
values- Waypoint numbers for one channel: model positions for X/Y/Z, or angles in radians for yaw and pitch.
i / i + 1- Start and end waypoint indexes. The next segment starts where this one ends.
u- Progress from 0 at the start of the segment to 1 at the end. Earlier code divides elapsed segment time by the duration and clamps the result to that range.
u3 / u4 / u5- Reusable powers
u³,u⁴andu⁵. Just above the excerpt,u2 = u*u,u3 = u2*uand so on compute them once. blend- The fifth-degree polynomial's 0-to-1 weight. On its own, it has zero first and second derivatives at both endpoints.
h- Segment duration in seconds: end waypoint time minus start waypoint time. It converts per-second slopes to the scale of normalized progress.
d- Shared endpoint slopes, in model units per second for positions and radians per second for angles. They can be positive, negative or zero.
h*d[i] / h*d[i+1]- Duration-scaled start and end slopes. Their basis functions shape how the curve leaves and approaches each waypoint without moving the waypoint values.
Read the code step by step
- Start at the starting value
values[i]is the baseline, and the other terms add changes to it. - Blend toward the destination
(values[i+1] - values[i])*blendadds a fraction of the total change. That fraction is 0 atu = 0and 1 atu = 1. - Carry velocity through the join
The last two terms impose the start and end slopes. Both are zero at the endpoints, so the waypoint values stay put while the curve's shape between them changes.
- Meet the constraints
The full curve matches two positions, two velocities and zero acceleration at both ends, and neighboring segments reuse the same shared slope. Slope limiting, done earlier, keeps each coordinate monotone within a segment. Filtering, done later during sampling, further smooths positions and view angles.
Worked example · illustrative values
At halfway
Illustrative numbers for one X channel: start at 0, end at 10, over 2 seconds. Both endpoint slopes are 2 units per second. Evaluate at u = 0.5.
blend = 0.5
position term = 10 × 0.5 = 5
start correction = +0.625
end correction = -0.625
result = 0 + 5 + 0.625 - 0.625
= 5At u = 0 and u = 1 the result is exactly 0 and 10, and the velocity at both ends is 2 units per second. Between them, velocity varies. With unequal endpoint slopes, the two corrections don't cancel, so halfway in time won't generally be halfway in position.
The coefficients look odd because they're solved from the endpoint constraints. The slope terms are zero at both ends, so they change the curve's shape between waypoints without moving the waypoints.
Source context: guided.ts · slopes and limiting at 429–445; channel setup at 448–449; curve at 450–454; normalized progress at 460.
Reviewed source snapshot · lib/tour/guided.ts · lines 452–453
The Code tab preserves the source; formatting only.
03
Reducing shimmer in the siding
The clapboard siding has thin lap shadows that shimmer once the boards get small on screen. To deal with that, a short GLSL fragment is injected into the standard Three.js material through onBeforeCompile. It calls fwidth(vClap), which adds the absolute screen-space derivatives of the board coordinate, to estimate how fast that coordinate changes between neighboring pixels. It's a screen-space measure, so it isn't the same thing as camera distance.
While clapWidth is small, the shader draws the shadow along each board plus a slight gradient. Between clapWidth values of .12 and .4, it blends toward a flat multiplier of .966, a tuned value used as a stand-in for the pattern's average. The multiplier scales the base color before lighting, so the boards' geometry stays the same.
float = ;
float = 1.0
- *(.8-, 1.0, )
+ *(.5-);
*= (
, ,
);Hover, focus, or tap dotted code. Open the variable guide below for the full walkthrough.
Fragment-shader excerpt. vClap is the 0-to-1 height within each board.
footprint = change in board coordinate per pixel
lap = edge shadow + gradient along each board
AS the footprint grows:
fade lap toward a tuned flat multiplier
GEOMETRY is unchanged; only base color is scaledSimplified steps for the same idea.
Only draw as much siding detail as the screen can resolve.
- When the boards are large on screen, draw the shadow line along each one.
- Estimate how fast the board coordinate changes between neighboring pixels.
- As that rate grows, blend the lines into a flat tone to reduce shimmer.
Like a mipmapped texture getting softer as it shrinks on screen, except it's done by hand for one procedural pattern.
Variables & walkthrough7 definitions
Each board has a clapV attribute copied from its UV height coordinate. The vertex shader passes it to the fragment shader as vClap, and onBeforeCompile inserts this shading into the existing Three.js material.
What the variables mean
vClap- Interpolated height within one board, from 0 to 1. It comes from the custom
clapVvertex attribute, which is copied from the board's UV Y coordinate. clapWidth- Per-pixel footprint of the board coordinate, estimated with
fwidth(vClap). A larger value means each pixel covers more of a board, so fine detail is harder to resolve. lap- Close-up brightness multiplier. It starts at 1, darkens near one edge of the board, then adds a small gradient across it.
diffuseColor.rgb- The material's red, green and blue base-color components at this fragment.
*=scales them by the shading factor; alpha is left alone. .8 / .42 / .05 / .5- Tuned values.
.8is the nominal edge position; the transition actually starts at.8 - clapWidth, so the pixel footprint widens it,.42sets how strongly it darkens, and.05sets the strength of a gradient centered on.5. .966- Tuned fallback multiplier used once the fine shading has fully faded. It keeps 96.6% of the base-color components. The code uses it as a stand-in for the lap pattern's average.
.12 / .4- Fade thresholds. At or below
.12the full lap shading is used; at or above.4the flat multiplier is used. Between them, the transition is smooth.
Read the code step by step
- Measure the pixel footprint
fwidth(vClap)adds the absolute screen-X and screen-Y derivatives of the coordinate. It estimates how much the coordinate changes between neighboring fragments. It doesn't measure distance to the camera. - Shade the board edge
The first
smoothstepgoes from 0 to 1 between.8 - clapWidthand1.0. Subtracting.42times that value darkens this region, and the footprint widens the transition as boards shrink on screen. - Add a subtle gradient
.05*(.5-vClap)adds a small positive amount near coordinate 0 and a small negative amount near coordinate 1. - Fade detail before it shimmers
The second
smoothstepproduces a fade weight.mix(lap, .966, weight)blends between the close-up shading and the flat multiplier, and multiplyingdiffuseColor.rgbapplies the result to the base color.
Worked example · illustrative values
Three viewing scales
Illustrative footprint values. The middle column is the fade weight, not the final pixel brightness.
clapWidth fade multiplier
0.05 0 lap
0.26 0.5 50/50 blend
0.50 1 0.966At .26, halfway between .12 and .4, smoothstep gives a weight of .5. The footprint depends on perspective, viewing angle and screen resolution. The boards stay where they are; only the shading on their base color becomes less pronounced.
Basing the fade on the per-pixel footprint means it also responds to viewing angle and screen resolution, which a camera-distance check wouldn't.
Source context: world.ts · board UV attribute at 263–266. materials.ts · attribute handoff and shader injection at 148–155.
Function references: GLSL built-in functions · Three.js onBeforeCompile
Reviewed source snapshot · lib/tour/materials.ts · lines 153–155
The Code tab preserves the source; formatting only.