Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to Econ-Engine are documented here. The changelog records what changed in each update. Design rationale, experiments, observations, and lessons are documented separately in [Lab Notes](LAB_NOTES.md).

## [LIFE17-Sky-077] - (2026-11-08)

- The observer draws the year. The sun follows the solar declination for the day of the year at 52° N: about 61° high and 16½ hours of daylight at the summer solstice, 38° and 12 hours at the equinoxes, 15° and 7½ hours at the winter solstice. The run starts at the spring equinox. The day sky is paler in winter and warmer while the sun is low.
- Leaves follow the season: bilberry, hazel and birch blend from spring green through autumn yellow and brown to bare winter crowns; about half the trees are drawn as birches and half as evergreen pines, by a hash of the tree's number. The grass dulls in late autumn and winter. Colours change through shared shader uniforms, recoloured at most every tenth of a day.
- Observer only: the simulation's day still runs from `dawnHour` to `duskHour` all year, and trajectories and fingerprints are unchanged. New `seasonLook.ts` with unit tests; the fixed-day `daylightAt` and `sunAt` in `display.ts` are removed.

## [LIFE16-Routes-075] - (2026-10-30)

- Fixes a memory leak on long runs: the state kept every route ever walked, about 45,000 route segments a day, so the heap grew about 12 MB a day and a year's run ran out of memory, in Node and in the page's worker alike. Each step now frees the routes below the lowest one still being walked; route ids keep counting.
Expand Down
10 changes: 10 additions & 0 deletions LAB_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@

Every meaningful model, architecture, experimental, or design update should receive a newest-first entry. Use at most one base update number per Git commit. Refinements completed before that commit keep the same base number with a decimal suffix—for example, `003` and `003.1` belong to the same commit family. Allocate the next base number only for a later commit. Preserve the context, observed problem or research question, rationale, important implementation decisions, trade-offs, findings, and unresolved questions. Distinguish verified observations from hypotheses. If the original rationale is unknown, say so rather than inferring intent from the finished code.

## [LIFE17-Sky-077] - (2026-11-08)

The owner asked to see the seasons in the valley: the sun's path and day length changing through the year, and trees turning brown in autumn and losing their leaves in winter, without temperature or snow. This is drawn by the observer alone, from the displayed minute, so no trajectory changes.

**Sun.** The valley is placed at 52° N, the latitude of the North Sea plain and Star Carr in the Mesolithic. The declination is `23.44° · sin(2π · yearFraction)`, with the year fraction 0 at the spring equinox, and the sun's height `sin φ sin δ + cos φ cos δ cos H`. The hour angle is zero at the middle of the simulation's day and ±π at its dawn and dusk hours, so at the equinoxes the drawn sun rises and sets on them. Light eases in while the sun is within about 4° of the horizon.

**Leaves and grass.** Each deciduous plant has key colours and crown sizes through the year, blended smoothly so nothing steps on a season boundary. The engine has no tree species: birch or pine is the observer's choice per tree, from a hash that draws on no simulation stream.

**Left for later.** People still work from `dawnHour` to `duskHour` all year, so in midsummer they sleep in daylight and in midwinter they work after the drawn sunset. Making them follow the sun changes trajectories and needs its own step.

## [LIFE16-Routes-075] - (2026-10-30)

While measuring Life 17, a one-year run ran out of memory, and `main` grew at the same rate: running the canonical configuration day by day with `advanceValley` and collecting garbage every 25 days, the heap grew about 12 MB a day, to 2.4 GB by day 150. Node's default heap and the page's worker both fail before a year.
Expand Down
18 changes: 0 additions & 18 deletions src/valleyView/display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,6 @@ export function clockLabel(hours: number) {
return `Day ${day + 1} · ${hh}:${mm}`
}

/**
* 0 at night, 1 in full daylight, easing over the half hour either side of dawn and dusk. Only the picture fades; the
* simulation's night still starts exactly at dusk.
*/
export function daylightAt(hourOfDay: number, dawnHour: number, duskHour: number) {
const smooth = (edge: number, t: number) => {
const x = Math.min(1, Math.max(0, (t - (edge - 0.5)) / 1))
return x * x * (3 - 2 * x)
}
return Math.min(smooth(dawnHour, hourOfDay), 1 - smooth(duskHour, hourOfDay))
}

/** The sun's height (−1 to 1) and direction, rising at dawn in the east and setting at dusk in the west. */
export function sunAt(hourOfDay: number, dawnHour: number, duskHour: number) {
const angle = ((hourOfDay - dawnHour) / (duskHour - dawnHour)) * Math.PI
return { elevation: Math.sin(angle), azimuth: Math.cos(angle) }
}

/** Forager IDs count from 0; people count from 1. */
export const foragerName = (foragerId: number) => `Forager ${foragerId + 1}`

Expand Down
63 changes: 63 additions & 0 deletions src/valleyView/seasonLook.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest'
import { VALLEY_DEFAULT_CONFIG } from '../valley/config'
import { BIRCH, BILBERRY, dayLengthHours, foliageAt, grassTint, sunAt, yearFraction } from './seasonLook'

const config = VALLEY_DEFAULT_CONFIG
/** The run's minute of a given hour on the day at this fraction of the year, from the spring equinox. */
const minuteAt = (fraction: number, hour: number) => Math.round(fraction * config.daysPerYear) * 1_440 + hour * 60

describe('the sun through the year', () => {
it('counts the year from the spring equinox, where the run starts', () => {
expect(yearFraction(config, 0)).toBe(0)
expect(yearFraction(config, minuteAt(0.75, 0))).toBeCloseTo(
Math.round(0.75 * config.daysPerYear) / config.daysPerYear,
9,
)
})

it('stands highest at the summer solstice and lowest at the winter one', () => {
const summer = sunAt(config, minuteAt(0.25, 12))
const equinox = sunAt(config, minuteAt(0.5, 12))
const winter = sunAt(config, minuteAt(0.75, 12))
expect(Math.asin(summer.up) * (180 / Math.PI)).toBeCloseTo(61.4, 0)
// Half a day past the equinox, the declination is already about 1° south.
expect(Math.abs(Math.asin(equinox.up) * (180 / Math.PI) - 38)).toBeLessThan(1.5)
expect(Math.asin(winter.up) * (180 / Math.PI)).toBeCloseTo(14.6, 0)
// At noon the sun is due south.
expect(winter.north).toBeLessThan(0)
expect(Math.abs(winter.east)).toBeLessThan(1e-9)
})

it('rises in the east, and keeps longer days in summer', () => {
expect(sunAt(config, minuteAt(0.5, 8)).east).toBeGreaterThan(0)
expect(dayLengthHours(config, 0.25)).toBeCloseTo(16.5, 0)
expect(dayLengthHours(config, 0.5)).toBeCloseTo(12, 5)
expect(dayLengthHours(config, 0.75)).toBeCloseTo(7.5, 0)
expect(sunAt(config, minuteAt(0.25, 20)).light).toBeGreaterThan(0.5)
expect(sunAt(config, minuteAt(0.75, 16.5)).light).toBe(0)
})
})

describe('leaves through the year', () => {
it('are green in summer, turning in autumn and bare in winter', () => {
expect(foliageAt(BIRCH, 0.3)).toMatchObject({ colour: BIRCH.summer, cover: 1 })
expect(foliageAt(BIRCH, 0.3).scale).toBeCloseTo(1, 9)
expect(foliageAt(BIRCH, 0.56).colour).toBe(BIRCH.turning)
expect(foliageAt(BIRCH, 0.85)).toMatchObject({ colour: BIRCH.bare, cover: 0 })
expect(foliageAt(BIRCH, 0.85).scale).toBeCloseTo(BIRCH.bareScale, 9)
expect(foliageAt(BILBERRY, 0.02).colour).toBe(BILBERRY.bare)
})

it('blend smoothly from one day to the next, across the year end', () => {
for (let step = 0; step < 1_000; step += 1) {
const before = foliageAt(BIRCH, step / 1_000)
const after = foliageAt(BIRCH, (step + 1) / 1_000)
expect(Math.abs(before.cover - after.cover)).toBeLessThan(0.05)
}
})

it('leave the grass as drawn in summer and duller in winter', () => {
expect(grassTint(0.35)).toEqual([1, 1, 1])
expect(grassTint(0.85)[1]).toBeLessThan(1)
})
})
208 changes: 208 additions & 0 deletions src/valleyView/seasonLook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import type { Color, MeshStandardMaterial } from 'three'

import { MINUTES_PER_DAY } from '../valley/calendar'
import type { ValleyConfig } from '../valley/types'

// How the year looks: the sun's path and the colour of leaves and grass. The observer alone draws this, from the
// displayed minute; the simulation's day still runs from `dawnHour` to `duskHour` all year.

type SkyConfig = Pick<ValleyConfig, 'daysPerYear' | 'dawnHour' | 'duskHour'>

/** The valley's latitude for the sun's path: 52° N, Mesolithic northern Europe (the North Sea plain, Star Carr). */
export const LATITUDE_DEG = 52
/** The tilt of the Earth's axis, the solar declination at the solstices. */
const TILT_DEG = 23.44
const RADIANS = Math.PI / 180

/**
* The displayed moment's place in the year, 0 to 1, counted from the spring equinox: ¼ is the summer solstice, ½ the
* autumn equinox, ¾ the winter solstice. The run starts at the spring equinox, the first day of the calendar's spring.
* It moves smoothly through each day, so colours blend rather than step.
*/
export function yearFraction(config: Pick<ValleyConfig, 'daysPerYear'>, minute: number) {
const days = minute / MINUTES_PER_DAY
return (((days % config.daysPerYear) + config.daysPerYear) % config.daysPerYear) / config.daysPerYear
}

const smoothstep = (from: number, to: number, x: number) => {
const t = Math.min(1, Math.max(0, (x - from) / (to - from)))
return t * t * (3 - 2 * t)
}

/**
* Where the sun stands at the displayed minute, from the solar declination for the day of the year at
* {@link LATITUDE_DEG}: `δ = 23.44° · sin(2π · yearFraction)` and `sin(altitude) = sin φ sin δ + cos φ cos δ cos H`,
* with the hour angle `H` zero at the middle of the simulation's day and π at its dawn and dusk hours, so at the
* equinoxes the sun rises and sets on them. Days are about 16½ hours at the summer solstice and 7½ at the winter one.
*
* Returns the sun's direction as east, north and up components of a unit vector, and `light`: 0 at night, 1 in full
* daylight, easing while the sun is within about 4° of the horizon.
*/
export function sunAt(config: SkyConfig, minute: number) {
const fraction = yearFraction(config, minute)
const declination = TILT_DEG * RADIANS * Math.sin(2 * Math.PI * fraction)
const latitude = LATITUDE_DEG * RADIANS
const hour = (((minute / 60) % 24) + 24) % 24
const noon = (config.dawnHour + config.duskHour) / 2
const hourAngle = ((hour - noon) / (config.duskHour - config.dawnHour)) * Math.PI
const up =
Math.sin(latitude) * Math.sin(declination) + Math.cos(latitude) * Math.cos(declination) * Math.cos(hourAngle)
const east = -Math.cos(declination) * Math.sin(hourAngle)
const north =
Math.cos(latitude) * Math.sin(declination) - Math.sin(latitude) * Math.cos(declination) * Math.cos(hourAngle)
/** 1 at the summer solstice, 0 at the winter one. */
const summer = (Math.sin(2 * Math.PI * fraction) + 1) / 2
return { up, east, north, light: smoothstep(-0.07, 0.07, up), summer }
}

/** Hours of daylight (sun above the horizon) on a day with this year fraction, at {@link LATITUDE_DEG}. */
export function dayLengthHours(config: Pick<ValleyConfig, 'dawnHour' | 'duskHour'>, fraction: number) {
const declination = TILT_DEG * RADIANS * Math.sin(2 * Math.PI * fraction)
const cosHalf = Math.min(1, Math.max(-1, -Math.tan(LATITUDE_DEG * RADIANS) * Math.tan(declination)))
return ((2 * Math.acos(cosHalf)) / Math.PI) * (config.duskHour - config.dawnHour)
}

/** A plant's leaf colours through the year: fresh, summer, turning, fallen-brown and bare (its twigs or stems). */
export interface LeafPalette {
fresh: number
summer: number
turning: number
brown: number
bare: number
/** Its crown's size when bare, as a share of its full crown. */
bareScale: number
}

/** Bilberry: fresh green, red in autumn, its green stems left in winter. */
export const BILBERRY: LeafPalette = {
fresh: 0x5f9a45,
summer: 0x2f7a3c,
turning: 0xa8402e,
brown: 0x7a4a30,
bare: 0x55603e,
bareScale: 0.7,
}
/** Hazel: yellow in autumn, grey-brown twigs in winter. */
export const HAZEL: LeafPalette = {
fresh: 0x86b84d,
summer: 0x4c8a35,
turning: 0xc9a83a,
brown: 0x9a6a2e,
bare: 0x6b5a48,
bareScale: 0.45,
}
/** Birch: bright yellow in autumn, grey-white twigs in winter. */
export const BIRCH: LeafPalette = {
fresh: 0x8cbf55,
summer: 0x4f8a3a,
turning: 0xd4b23a,
brown: 0x9a7a40,
bare: 0x857c74,
bareScale: 0.45,
}

type Stage = keyof Omit<LeafPalette, 'bareScale'>
/**
* The deciduous year, by year fraction from the spring equinox: the stage the leaves are at, and how much of the crown
* is in leaf. Leaves open through April and May, stay green through summer, turn from mid-September, fall through
* October and November, and the crowns are bare from late November to early April.
*/
const LEAF_YEAR: [number, Stage, number][] = [
[0.04, 'bare', 0],
[0.1, 'fresh', 0.6],
[0.16, 'fresh', 1],
[0.27, 'summer', 1],
[0.46, 'summer', 1],
[0.56, 'turning', 1],
[0.64, 'brown', 0.55],
[0.72, 'bare', 0],
]

const channels = (rgb: number) => [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255] as const

/** A deciduous plant's leaf colour (as 0xRRGGBB) and crown scale on a day with this year fraction. */
export function foliageAt(palette: LeafPalette, fraction: number) {
const keys = LEAF_YEAR
let next = keys.findIndex(([at]) => at > fraction)
if (next < 0) next = 0
const previous = (next - 1 + keys.length) % keys.length
const [fromAt, fromStage, fromCover] = keys[previous]!
const [toAt, toStage, toCover] = keys[next]!
const span = (toAt - fromAt + 1) % 1 || 1
const t = smoothstep(0, 1, ((fraction - fromAt + 1) % 1) / span)
const from = channels(palette[fromStage])
const to = channels(palette[toStage])
const mixed = from.map((value, index) => Math.round(value + (to[index]! - value) * t))
const cover = fromCover + (toCover - fromCover) * t
return {
colour: (mixed[0]! << 16) | (mixed[1]! << 8) | mixed[2]!,
cover,
scale: palette.bareScale + (1 - palette.bareScale) * cover,
}
}

/**
* How the grass is tinted, as red, green and blue multipliers of its colour: greener in spring, as drawn in summer,
* duller and browner from late autumn through winter.
*/
export function grassTint(fraction: number): [number, number, number] {
const leaf = foliageAt(HAZEL, fraction).cover
// Spring flush peaks a little after the leaves open, and fades by midsummer.
const flush = smoothstep(0.04, 0.14, fraction) * (1 - smoothstep(0.2, 0.32, fraction))
const dull = 1 - leaf
return [1 - 0.06 * flush + 0.06 * dull, 1 + 0.1 * flush - 0.12 * dull, 1 - 0.08 * flush - 0.12 * dull]
}

/** The uniforms one deciduous material's shader reads: its leaf colour and its crown scale. */
export interface FoliageUniforms {
colour: { value: Color }
scale: { value: number }
}

/**
* Makes a material's colour and size follow the season without touching its instances: its colour becomes the leaf
* colour uniform, and each instance's crown shrinks about its centre by the scale uniform, across fully and upwards by
* `upShare` of that. With `evergreen`, only instances whose instance colour's red channel is 1 are deciduous; those at
* 0 keep the evergreen colour and size, so pines and birches can share one mesh. The depth material used for shadows
* shrinks the same way.
*/
export function seasonalFoliage(
THREE: typeof import('three'),
material: MeshStandardMaterial,
uniforms: FoliageUniforms,
upShare: number,
evergreen?: Color,
) {
const key = `foliage-${upShare}-${evergreen ? 'mixed' : 'all'}`
const deciduous = evergreen ? '(instanceColor.r)' : '1.0'
const shrink = `
#if ${evergreen ? 'defined( USE_INSTANCING_COLOR )' : '1'}
float leafScale = mix(1.0, uLeafScale, ${deciduous});
transformed.xz *= leafScale;
transformed.y *= mix(1.0, leafScale, ${upShare.toFixed(3)});
#endif`
const patchVertex = (shader: { vertexShader: string; uniforms: Record<string, { value: unknown }> }) => {
shader.uniforms.uLeafScale = uniforms.scale
shader.vertexShader =
'uniform float uLeafScale;\n' +
shader.vertexShader.replace('#include <begin_vertex>', `#include <begin_vertex>\n${shrink}`)
}
material.onBeforeCompile = (shader) => {
patchVertex(shader)
shader.uniforms.uLeafColour = uniforms.colour
if (evergreen) shader.uniforms.uEvergreen = { value: evergreen }
shader.fragmentShader =
`uniform vec3 uLeafColour;\n${evergreen ? 'uniform vec3 uEvergreen;\n' : ''}` +
shader.fragmentShader.replace(
'#include <color_fragment>',
evergreen
? '#if defined( USE_COLOR )\ndiffuseColor.rgb = mix(uEvergreen, uLeafColour, vColor.r);\n#endif'
: 'diffuseColor.rgb = uLeafColour;',
)
}
material.customProgramCacheKey = () => key
const depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking })
depth.onBeforeCompile = patchVertex
depth.customProgramCacheKey = () => `${key}-depth`
return depth
}
13 changes: 12 additions & 1 deletion src/valleyView/tiledInstances.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { BufferGeometry, Group, InstancedMesh, Material, Matrix4 } from 'three'
import type { BufferGeometry, Color, Group, InstancedMesh, Material, Matrix4 } from 'three'

type Three = typeof import('three')

Expand Down Expand Up @@ -77,6 +77,13 @@ export class TiledInstances {
this.dirty.add(tile)
}

/** Sets an instance's colour; call before the first draw, so each tile's shader is built with instance colours. */
setColorAt(index: number, color: Color) {
const mesh = this.tiles[this.tileOf[index]!]!
mesh.setColorAt(this.localOf[index]!, color)
mesh.instanceColor!.needsUpdate = true
}

/** Whether a plant's tile is drawn. */
shows(plant: number) {
return this.tiles[this.tileOfPlant[plant]!]!.visible
Expand Down Expand Up @@ -125,6 +132,10 @@ export class TiledInstances {
for (const tile of this.tiles) tile.receiveShadow = value
}

set customDepthMaterial(value: Material) {
for (const tile of this.tiles) tile.customDepthMaterial = value
}

computeBoundingSphere() {
for (const tile of this.tiles) tile.computeBoundingSphere()
}
Expand Down
Loading
Loading