Skip to content

3D engine that AI agents drive

Draw the sun disc analytically in Glaze (#2164)

Nguyen Xuan Ande87dba0b5e0
diff --git a/changes/2164.md b/changes/2164.md
new file mode 100644
index 00000000..bc9e5132
--- /dev/null
+++ b/changes/2164.md
@@ -0,0 +1 @@
+- The Glaze sun disc is drawn per pixel at `sunAngularRadius` with a screen-space anti-aliased edge instead of baked into the 1024x512 sky map, so it stays a sharp round disc of the right size at any field of view (#2164)
diff --git a/changes/2164.size.md b/changes/2164.size.md
new file mode 100644
index 00000000..418f4c2b
--- /dev/null
+++ b/changes/2164.size.md
@@ -0,0 +1,12 @@
+- entry:core: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- entry:core+lazy: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- entry:hdri: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- scene:lit-box: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- scene:lit-box+lazy: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- scene:gltf-box: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- scene:gltf-box+lazy: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- scene:agent-scene: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- scene:agent-scene+lazy: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- goal:lit-box: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- goal:gltf-box: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
+- goal:agent-scene: about 400 bytes gzip for a sun disc that stays a sharp round disc of the right size at any zoom, instead of a stepped blur (#2164)
diff --git a/docs/agent-look.md b/docs/agent-look.md
index 0f961d04..460ceb24 100644
--- a/docs/agent-look.md
+++ b/docs/agent-look.md
@@ -123,7 +123,7 @@ Sky colors use display RGB, matching the renderer's existing environment contrac
| `ground` | on | Absent unless set. `false` removes the preview's automatic floor and contact shadow |
| `resolveCoplanar` | `'offset'` | Flush and near-flush faces, inside one mesh or across parts, are ranked per triangle and drawn with a small depth-only bias, so the face in front wins at every distance and nothing flickers. Geometry never moves. `false` opts out, and `scene_inspect` then lists each pair as a `coplanar-overlap` warning. Parts that set `decal` or `depthLayer` keep their own layer. Where an opaque face covers another on the same plane, or in front of it by at most a thousandth of the shared face (between a millimetre and a centimetre), the covered part is cut out of the drawn copy of the hidden face (the part and its geometry stay as you made them), so a stack of any depth is settled and the path tracer sees one face. What cannot be settled comes back as a `coplanar-overlap` warning with a `reason`: `rank-overflow` (more than 16 faces a wider gap apart), `double-sided-gap`, `unchecked` (past the triangle or pair budget, the part the search stopped at is named) or `collapsed-node` (an axis a millionth of the longest one; a 2 cm slab 400 m wide is a ground, not a collapse) |
| `objectReflections` | on | Absent unless set. Each smooth metal part (`metallic` 0.5 or more, `roughness` 0.6 or less; at most 8 such parts, in a scene with at most 1,024 other parts) gets a reflection probe of the scene around it, so a chrome sphere shows the floor and its neighbours. `false` turns it off. Probes are traced at rest, so a part that moves reflects the scene as it started. `scene_inspect` names them in `reflections` |
-| `sky` | absent | Absent unless set. `{ type: 'physical', preset, sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective, ozone, sunDisc }`: one time-of-day control. `sunElevation` -90 to 90 degrees (default 45), `sunRotation` degrees clockwise from -Z seen from above (0), `turbidity` 1 to 10 haze (3), `groundAlbedo` 0 to 1 (0.3), `aerialPerspective` 0 to 4 scales the distance haze (1; 0 for none), `ozone` 0 to 10 Chappuis-band absorption (1), `sunDisc` boolean (true). `preset` is `golden-hour` (sun 4 degrees up), `sunset` (1 degree) or `blue-hour` (4 degrees below the horizon), each with the sun turned to rotation 250: it supplies the sun only, fields beside it win, and a preset in a `set-environment` patch starts the sky again from its own sun with the other fields at their defaults. A sun below 14 degrees is fitted to Blender's sky (checked at 2, 6 and 15 degrees, comparison in `docs/golden-hour-comparison.jpg`): a narrow saturated orange band forms along the horizon, the zenith dims and the key warms and strengthens; at 14 degrees and above the sky is unchanged. The sky sets `lightDirection`, `keyColor` (the sun reddens and dims with air mass and sets below the horizon), `skyTop`, `skyBottom`, `fogColor` and `fogDensity`, and replaces the setup's environment map with the sky, so those fields no longer take your values while a sky is set. `environment` motion tracks can animate `sunElevation`, `sunRotation`, `turbidity`, `groundAlbedo`, `aerialPerspective` and `ozone` for time-of-day arcs. A `set-environment` patch changes the fields it names and keeps the rest; `sky: null` in a patch keeps the last derived values as plain fields. It is an analytic single-scattering approximation (Rayleigh, aerosol and ozone, Kasten-Young air mass), not Blender's Nishita integration: no clouds. Raster first: the path tracer backends read the same environment map and key light, but are not yet checked against it. |
+| `sky` | absent | Absent unless set. `{ type: 'physical', preset, sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective, ozone, sunDisc }`: one time-of-day control. `sunElevation` -90 to 90 degrees (default 45), `sunRotation` degrees clockwise from -Z seen from above (0), `turbidity` 1 to 10 haze (3), `groundAlbedo` 0 to 1 (0.3), `aerialPerspective` 0 to 4 scales the distance haze (1; 0 for none), `ozone` 0 to 10 Chappuis-band absorption (1), `sunDisc` boolean (true; the disc is drawn per pixel at `sunAngularRadius`, 0.5 degrees by default, so it stays a sharp round disc at any zoom, and it is not in the baked sky map). `preset` is `golden-hour` (sun 4 degrees up), `sunset` (1 degree) or `blue-hour` (4 degrees below the horizon), each with the sun turned to rotation 250: it supplies the sun only, fields beside it win, and a preset in a `set-environment` patch starts the sky again from its own sun with the other fields at their defaults. A sun below 14 degrees is fitted to Blender's sky (checked at 2, 6 and 15 degrees, comparison in `docs/golden-hour-comparison.jpg`): a narrow saturated orange band forms along the horizon, the zenith dims and the key warms and strengthens; at 14 degrees and above the sky is unchanged. The sky sets `lightDirection`, `keyColor` (the sun reddens and dims with air mass and sets below the horizon), `skyTop`, `skyBottom`, `fogColor` and `fogDensity`, and replaces the setup's environment map with the sky, so those fields no longer take your values while a sky is set. `environment` motion tracks can animate `sunElevation`, `sunRotation`, `turbidity`, `groundAlbedo`, `aerialPerspective` and `ozone` for time-of-day arcs. A `set-environment` patch changes the fields it names and keeps the rest; `sky: null` in a patch keeps the last derived values as plain fields. It is an analytic single-scattering approximation (Rayleigh, aerosol and ozone, Kasten-Young air mass), not Blender's Nishita integration: no clouds. Raster first: the path tracer backends read the same environment map and key light, but are not yet checked against it. |
| `floorSkyTrace` | on | Absent unless set. A closed room a sun lights gets the sky each floor texel sees traced into its floor (`applyFloorSkyVisibility`, strength 0.2), so shadowed floors under a roof or between walls get less world and sky light; it makes the dark end of halls closer to Cycles. Open scenes and rooms lit by lamps alone are left as they are. `false` turns it off; a value that is not a boolean is refused. It loads lazily with a recipe that names its sun (`keyColor` or `keyIntensity`), costs about 1 s of trace when the scene is built and adds triangles to the floor (0.1 to 0.4 ms per frame in the reference halls). |
| `specularAntiAliasing` | `1` | Absent unless set. `0` to `4`. Widens highlights where the shading normal or normal map detail changes within a pixel (geometric specular anti-aliasing plus a Toksvig term read from the filtered normal map length), so grainy or scanned metal stops sparkling from frame to frame at grazing angles. `0` gives a highlight that follows every texel; above `1` is softer. |
| `sunBounce` | `1` | Absent unless set. A number of 0 or more. A closed room a sun lights gets a few point lights at its sunlit patches (`withSunBounce`, found when the scene is prepared), so the floor, walls and pillars around a patch are lit by the light it bounces and the far end of the room less. `0` turns it off and gives the look without it; `1` is fitted to Cycles; above `1` is stronger. A value that is not a number of 0 or more is refused. Open scenes and rooms with no sun are left as they are. It loads lazily with the sun, and the lights take up to 6 of the 16 point light slots. |
diff --git a/src/environment-shading.js b/src/environment-shading.js
index 4c60609e..ccb7b642 100644
--- a/src/environment-shading.js
+++ b/src/environment-shading.js
@@ -21,6 +21,9 @@ vec2 equirectangularFromDirection(vec3 direction) {
}
`;
+/** The half-angle of the sun in radians when the environment gives no sunAngularRadius; the path tracer's sun uses the same default. */
+export const DEFAULT_SUN_ANGULAR_RADIUS = Math.PI / 360;
+
export const environmentLookupGlsl = `
uniform sampler2D environmentSpecular;
uniform vec2 environmentRotation;
diff --git a/src/environment.js b/src/environment.js
index 7ee0c2e8..cf523b7f 100644
--- a/src/environment.js
+++ b/src/environment.js
@@ -34,7 +34,17 @@ function requireNumberInRange(value, name, minimum, maximum) {
}
}
-export function createEnvironmentMap({ width, height, data, intensity = 1, rotation = 0, showBackground = false, backgroundBlur = 0 } = {}) {
+// A sun the background pass draws as a sharp disc on top of the baked map: a unit direction in map space and its linear radiance.
+function requireSunDisc(sunDisc) {
+ const { direction, radiance } = sunDisc;
+ const isTriple = value => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
+ if (!isTriple(direction) || !isTriple(radiance)) {
+ throw new TypeError('Environment map sunDisc must be { direction: [x, y, z], radiance: [r, g, b] } with finite numbers.');
+ }
+ return Object.freeze({ direction: Object.freeze([...direction]), radiance: Object.freeze([...radiance]) });
+}
+
+export function createEnvironmentMap({ width, height, data, intensity = 1, rotation = 0, showBackground = false, backgroundBlur = 0, sunDisc = null } = {}) {
requireIntegerInRange(width, 'width', 4, MAXIMUM_ENVIRONMENT_SIZE);
requireIntegerInRange(height, 'height', 2, MAXIMUM_ENVIRONMENT_SIZE);
if (!(data instanceof Float32Array)) throw new TypeError('Environment map data must be a Float32Array of linear RGB or RGBA values.');
@@ -48,7 +58,8 @@ export function createEnvironmentMap({ width, height, data, intensity = 1, rotat
requireNumberInRange(rotation, 'rotation', -1e6, 1e6);
requireNumberInRange(backgroundBlur, 'backgroundBlur', 0, 1);
if (typeof showBackground !== 'boolean') throw new TypeError('Environment map showBackground must be a boolean.');
- return Object.freeze({ kind: 'environment-map', width, height, channels, data, intensity, rotation, showBackground, backgroundBlur });
+ const resolvedSunDisc = sunDisc === null ? null : requireSunDisc(sunDisc);
+ return Object.freeze({ kind: 'environment-map', width, height, channels, data, intensity, rotation, showBackground, backgroundBlur, sunDisc: resolvedSunDisc });
}
// The renderer accepts descriptors that were spread from a created map (to animate rotation), so it re-checks the shape without rescanning the data.
@@ -397,6 +408,9 @@ uniform vec3 eye;
uniform float backgroundLevel;
uniform float exposure;
uniform float hdrEnabled;
+uniform vec3 sunMapDirection;
+uniform vec3 sunDiscRadiance;
+uniform float sunDiscRadius;
out vec4 outputColor;
${environmentLookupGlsl}
vec3 toneMap(vec3 color) {
@@ -406,6 +420,12 @@ void main() {
vec4 world = inverseViewProjection * vec4(textureCoordinate * 2.0 - 1.0, 1.0, 1.0);
vec3 direction = normalize(world.xyz / world.w - eye);
vec3 radiance = environmentRadiance(direction, backgroundLevel);
+ // The sun is a disc of sunDiscRadius radians drawn per pixel, not baked into the map, so a narrow lens still sees a sharp round edge.
+ vec3 mapDirection = environmentDirection(direction);
+ float sunAngle = atan(length(cross(mapDirection, sunMapDirection)), dot(mapDirection, sunMapDirection));
+ float edgeWidth = max(fwidth(sunAngle), 1e-7);
+ float discCoverage = clamp((sunDiscRadius - sunAngle) / edgeWidth + 0.5, 0.0, 1.0) * step(0.0, mapDirection.y) * (1.0 - clamp(backgroundLevel, 0.0, 1.0));
+ radiance += sunDiscRadiance * environmentIntensity * discCoverage;
outputColor = vec4(hdrEnabled > 0.5 ? min(radiance * exposure, vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), 1.0);
}`;
diff --git a/src/physical-sky.js b/src/physical-sky.js
index a8d428e1..9c8eee21 100644
--- a/src/physical-sky.js
+++ b/src/physical-sky.js
@@ -36,7 +36,6 @@ const OZONE_DEPTH = [0.02, 0.014, 0.0005];
const SUN_STRENGTH = 3.4;
const SKY_STRENGTH = 2.2;
const SUN_DISC_STRENGTH = 18;
-const SUN_DISC_COSINE = 0.9994;
const MAXIMUM_AIR_MASS = 20;
const AEROSOL_ANISOTROPY = 0.76;
const SHARED_SUN_MASS = 4;
@@ -183,16 +182,6 @@ export function applyPhysicalSky(input, environment, fail) {
const mapsByKey = new Map();
const MAXIMUM_CACHED_MAPS = 8;
-/**
- * A round disc with a flat bright top and a soft rim, by the angle from the sun's centre. A squared falloff over a map of a few
- * degrees per texel drew the sun as the texel grid (a rounded rectangle); the finer map and this profile keep it a circle.
- */
-function sunDiscWeight(sunCosine) {
- const rim = (sunCosine - SUN_DISC_COSINE) / (1 - SUN_DISC_COSINE);
- const edge = Math.min(Math.max(rim / 0.64, 0), 1);
- return edge * edge * (3 - 2 * edge) * SUN_DISC_STRENGTH;
-}
-
// Haze fills the first degrees under the horizon, so a finite sea or plane whose far edge ends short of the true horizon meets
// haze the colour of the sky, not a flat band of ground colour with a hard step at the horizon line.
const HORIZON_HAZE_SINE = 0.12;
@@ -205,21 +194,25 @@ function belowHorizonRadiance(sky, color, zenith, sun, direction) {
return ground.map((component, channel) => horizonSky[channel] + (component - horizonSky[channel]) * groundShare);
}
+/** The sun the background pass draws as a sharp disc, or null when the sky has none: the disc is not baked into the map. */
+function sunDiscOf(sky) {
+ if (sky.sunDisc === false || sky.sunElevation <= -1.5) {
+ return null;
+ }
+ const { sun, color } = colorAtZenithAndHorizon(sky);
+ return { direction: sun, radiance: color.map(component => component * SUN_DISC_STRENGTH) };
+}
+
function buildMapData(sky) {
const { sun, color, zenith } = colorAtZenithAndHorizon(sky);
- const drawDisc = sky.sunDisc !== false && sky.sunElevation > -1.5;
const data = new Float32Array(MAP_WIDTH * MAP_HEIGHT * 3);
for (let row = 0; row < MAP_HEIGHT; row++) {
const polar = ((row + 0.5) / MAP_HEIGHT) * Math.PI;
for (let column = 0; column < MAP_WIDTH; column++) {
const azimuth = ((column + 0.5) / MAP_WIDTH - 0.5) * 2 * Math.PI;
const direction = [Math.sin(polar) * Math.sin(azimuth), Math.cos(polar), -Math.sin(polar) * Math.cos(azimuth)];
- const sunCosine = direction[0] * sun[0] + direction[1] * sun[1] + direction[2] * sun[2];
- const discWeight = drawDisc && direction[1] > 0 && sunCosine > SUN_DISC_COSINE
- ? sunDiscWeight(sunCosine)
- : 0;
const radiance = direction[1] >= 0
- ? skyRadiance(sky, direction, sun).map((component, channel) => component + color[channel] * discWeight)
+ ? skyRadiance(sky, direction, sun)
: belowHorizonRadiance(sky, color, zenith, sun, direction);
data.set(radiance, (row * MAP_WIDTH + column) * 3);
}
@@ -234,7 +227,7 @@ export function createPhysicalSkyMap({ sky, environmentIntensity: intensity, env
if (mapsByKey.size >= MAXIMUM_CACHED_MAPS) {
mapsByKey.clear();
}
- mapsByKey.set(key, createEnvironmentMap({ width: MAP_WIDTH, height: MAP_HEIGHT, data: buildMapData(sky), intensity, rotation, showBackground }));
+ mapsByKey.set(key, createEnvironmentMap({ width: MAP_WIDTH, height: MAP_HEIGHT, data: buildMapData(sky), intensity, rotation, showBackground, sunDisc: sunDiscOf(sky) }));
}
return mapsByKey.get(key);
}
diff --git a/src/renderer.js b/src/renderer.js
index 2a3cdec3..7c8aaa92 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -17,7 +17,7 @@ import { createLightingState, updateLightingState } from './lighting.js';
import { RenderTargetLedger } from './render-target-ledger.js';
import { SHADOW_ATLAS_WIDTH, SHADOW_TILE_SIZE, SHADOW_TILES_PER_ROW, tileViewport, writeShadowTile } from './local-shadows.js';
import { resolveVolumeFog, validateFogField } from './volumetric.js';
-import { requireEnvironmentSupport } from './environment-shading.js';
+import { requireEnvironmentSupport, DEFAULT_SUN_ANGULAR_RADIUS } from './environment-shading.js';
import { materialLayerState, materialLayerValue } from './material-layers.js';
import { MaterialSnapshot } from './material-snapshot.js';
import { wearUniformValues } from './material-wear.js';
@@ -2257,7 +2257,7 @@ export class CrucibleRenderer {
const context = this.context;
if (!this.environmentBackgroundProgram) {
this.environmentBackgroundProgram = compileProgram(context, fullscreenVertex, this.withViewTransform(requireEnvironmentSupport().backgroundFragment, 'background'));
- const names = ['inverseViewProjection', 'eye', 'backgroundLevel', 'exposure', 'hdrEnabled', 'environmentSpecular', 'environmentRotation', 'environmentIntensity', 'environmentLevelMax'];
+ const names = ['inverseViewProjection', 'eye', 'backgroundLevel', 'exposure', 'hdrEnabled', 'environmentSpecular', 'environmentRotation', 'environmentIntensity', 'environmentLevelMax', 'sunMapDirection', 'sunDiscRadiance', 'sunDiscRadius'];
this.environmentBackgroundUniforms = Object.fromEntries(names.map(name => [name, context.getUniformLocation(this.environmentBackgroundProgram, name)]));
}
const uniforms = this.environmentBackgroundUniforms;
@@ -2275,6 +2275,10 @@ export class CrucibleRenderer {
context.uniform2f(uniforms.environmentRotation, Math.cos(map.rotation), Math.sin(map.rotation));
context.uniform1f(uniforms.environmentIntensity, map.intensity);
context.uniform1f(uniforms.environmentLevelMax, levelMax);
+ const sunDisc = map.sunDisc;
+ context.uniform3fv(uniforms.sunMapDirection, sunDisc?.direction ?? [0, -1, 0]);
+ context.uniform3fv(uniforms.sunDiscRadiance, sunDisc?.radiance ?? [0, 0, 0]);
+ context.uniform1f(uniforms.sunDiscRadius, frame.environment?.sunAngularRadius ?? this.environment?.sunAngularRadius ?? DEFAULT_SUN_ANGULAR_RADIUS);
context.drawArrays(context.TRIANGLES, 0, 3);
return true;
}
diff --git a/tests/physical-sky.test.js b/tests/physical-sky.test.js
index 7fd5519d..867dfd5e 100644
--- a/tests/physical-sky.test.js
+++ b/tests/physical-sky.test.js
@@ -78,7 +78,7 @@ test('set-environment changes one sky field and keeps the others', () => {
assert.ok(Math.abs(lightDirection[1] - Math.sin(10 * Math.PI / 180)) < 1e-9);
});
-test('ozone deepens twilight blue and sunDisc adds the solar disc to the sky map', () => {
+test('ozone deepens twilight blue and sunDisc hands the solar disc to the background pass', () => {
const noOzone = skyEnvironment({ sunElevation: 4, ozone: 0 });
const heavyOzone = skyEnvironment({ sunElevation: 4, ozone: 6 });
assert.ok(heavyOzone.keyColor[0] < noOzone.keyColor[0]);
@@ -86,8 +86,8 @@ test('ozone deepens twilight blue and sunDisc adds the solar disc to the sky map
const withDisc = agentEnvironmentMap(skyEnvironment({ sunElevation: 30, sunDisc: true }));
const withoutDisc = agentEnvironmentMap(skyEnvironment({ sunElevation: 30, sunDisc: false }));
- const peak = values => values.reduce((largest, value) => Math.max(largest, value), 0);
- assert.ok(peak(withDisc.data) > peak(withoutDisc.data) * 1.2);
+ assert.ok(withDisc.sunDisc.radiance[0] > 1);
+ assert.equal(withoutDisc.sunDisc, null);
assert.throws(() => skyEnvironment({ ozone: -1 }), /environment\.sky\.ozone/);
assert.throws(() => skyEnvironment({ sunDisc: 1 }), /environment\.sky\.sunDisc/);
});
diff --git a/tests/sun-disc-background.test.js b/tests/sun-disc-background.test.js
new file mode 100644
index 00000000..f91253d7
--- /dev/null
+++ b/tests/sun-disc-background.test.js
@@ -0,0 +1,65 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { CrucibleRenderer } from '../src/renderer.js';
+import { agentEnvironmentMap, normalizeAgentLook } from '../src/agent-look.js';
+import { environmentBackgroundFragment } from '../src/environment.js';
+import { DEFAULT_SUN_ANGULAR_RADIUS } from '../src/environment-shading.js';
+
+function skyEnvironment(sky, extra = {}) {
+ return normalizeAgentLook({ environment: { sky: { type: 'physical', ...sky }, ...extra } }).environment;
+}
+
+function peak(values) {
+ return values.reduce((largest, value) => Math.max(largest, value), 0);
+}
+
+test('the baked physical sky map holds no sun disc and hands the disc to the background pass', () => {
+ const withDisc = agentEnvironmentMap(skyEnvironment({ sunElevation: 30, sunDisc: true }));
+ const withoutDisc = agentEnvironmentMap(skyEnvironment({ sunElevation: 30, sunDisc: false }));
+ assert.deepEqual(Array.from(withDisc.data), Array.from(withoutDisc.data));
+ assert.ok(peak(withDisc.data) < 18, 'the map keeps the glow only; the bright disc is drawn per pixel');
+ assert.equal(withoutDisc.sunDisc, null);
+ const expectedSun = [0, Math.sin(Math.PI / 6), -Math.cos(Math.PI / 6)];
+ withDisc.sunDisc.direction.forEach((component, axis) => assert.ok(Math.abs(component - expectedSun[axis]) < 1e-9));
+ assert.ok(withDisc.sunDisc.radiance.every(component => component > 1));
+});
+
+test('a sun below the horizon draws no disc', () => {
+ assert.equal(agentEnvironmentMap(skyEnvironment({ sunElevation: -10 })).sunDisc, null);
+});
+
+test('the background shader draws the disc from a radius uniform with a screen-space edge', () => {
+ assert.match(environmentBackgroundFragment, /uniform float sunDiscRadius;/);
+ assert.match(environmentBackgroundFragment, /fwidth\(sunAngle\)/);
+});
+
+function recordBackgroundUniforms(map, environment) {
+ const values = {};
+ const recorder = (location, ...rest) => { values[location] = rest.length === 1 ? rest[0] : rest; };
+ const context = new Proxy({}, { get: (_, name) => (String(name).startsWith('uniform') ? recorder : () => {}) });
+ const names = ['inverseViewProjection', 'eye', 'backgroundLevel', 'exposure', 'hdrEnabled', 'environmentSpecular', 'environmentRotation', 'environmentIntensity', 'environmentLevelMax', 'sunMapDirection', 'sunDiscRadiance', 'sunDiscRadius'];
+ const renderer = {
+ context,
+ transparent: false,
+ hdr: false,
+ environment,
+ environmentBackgroundProgram: {},
+ environmentBackgroundUniforms: Object.fromEntries(names.map(name => [name, name])),
+ environmentResources: { levelCount: 4 },
+ inverseViewProjection: new Float32Array(16),
+ };
+ assert.equal(CrucibleRenderer.prototype.drawEnvironmentBackground.call(renderer, map, { eye: [0, 0, 0], environment: {} }, 1), true);
+ return values;
+}
+
+test('the renderer passes sunAngularRadius and the sun to the background pass', () => {
+ const map = agentEnvironmentMap(skyEnvironment({ sunElevation: 30 }, { world: true }));
+ const custom = recordBackgroundUniforms(map, { sunAngularRadius: 0.02 });
+ assert.equal(custom.sunDiscRadius, 0.02);
+ assert.deepEqual(Array.from(custom.sunMapDirection), Array.from(map.sunDisc.direction));
+ assert.deepEqual(Array.from(custom.sunDiscRadiance), Array.from(map.sunDisc.radiance));
+ assert.equal(recordBackgroundUniforms(map, {}).sunDiscRadius, DEFAULT_SUN_ANGULAR_RADIUS);
+ const noDisc = agentEnvironmentMap(skyEnvironment({ sunElevation: 30, sunDisc: false }, { world: true }));
+ assert.deepEqual(Array.from(recordBackgroundUniforms(noDisc, {}).sunDiscRadiance), [0, 0, 0]);
+});