| =bugReportDir= | =-De3d.bugreport.dir= | =~/.local/share/aukio/bugreports= | where bug reports are written |
| =logDir= | =-De3d.log.dir= | =~/.cache/aukio/logs= | persistent rolling log location |
| =telemetryIntervalSeconds= | =-De3d.telemetry.interval= | 5 | seconds between telemetry log lines |
+| =giStage2Radius= | =-De3d.gi.stage2Radius= | 0 (unlimited) | [[file:Global illumination/][GI]] centroid-bounce bubble radius (world units) |
+| =giStage3Radius= | =-De3d.gi.stage3Radius= | 0 (unlimited) | GI coarse-lightmap bubble radius; also enables mesh-block lightmaps when > 0 |
+| =giStage4Radius= | =-De3d.gi.stage4Radius= | 0 (unlimited) | GI fine-refinement bubble radius |
+| =giMeshUnitsPerTexel= | =-De3d.gi.meshUnitsPerTexel= | 2.1 | mesh-block lightmap texel density at final resolution |
+| =giLightmapCacheEntries= | =-De3d.gi.lightmapCacheEntries= | 65536 | cap on the baked-lightmap cache (stream-out survival) |
#+CAPTION: Resolution order for every engine key: the system property wins; otherwise the config file; otherwise the built-in default.
[[file:Config precedence.svg]]
decoupled from GI quality: you can crank lightmap resolution up and the
only cost is CPU time on the worker threads, not frame time.
-* Lightmaps: a texture per triangle
+* Progressive global illumination
:PROPERTIES:
-:CUSTOM_ID: lightmaps
+:CUSTOM_ID: progressive-gi
:END:
-Flat shading can only color a polygon uniformly — shadows and gradients
-need resolution *inside* the polygon. Every lightmapped triangle
-therefore owns a small generated texture, its *lightmap*, whose texels
-map onto the triangle surface by an affine rule:
+The render loop never traces a ray. All ray work happens in
+[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/gi/GlobalIllumination.html][GlobalIllumination]],
+a set of dedicated low-priority daemon threads (=e3d-gi-0=, =e3d-gi-1=,
+...; two by default, started with =ViewPanel.enableGlobalIllumination()=).
+The workers bake lighting into per-surface caches; render threads only
+read finished results, so frame rate stays decoupled from GI cost. This
+section walks through what gets baked, in what order, and when it stops.
-#+INCLUDE: "Lightmap mapping.svg" export html
+** Polygons are illuminated in the following order
+:PROPERTIES:
+:CUSTOM_ID: illumination-order
+:END:
-The triangle's UVs are pinned to (0,0), (1,0), (0,1), so the valid
-texel region is the half where u+v <= 1; the other half of the square
-texture is flood-filled from valid neighbors so that nearest sampling
-near the hypotenuse never picks up garbage.
+The bake progresses by /spatial resolution/, coarse to fine. Each stage
+walks all snapshot entries near-to-far from the camera and ends at a
+global barrier — no entry starts stage k+1 before every entry has
+finished stage k. After each stage, what is on screen is a complete
+lighting solution at that stage's resolution; later stages only add
+detail.
+
+The bake works against a /snapshot/ of the scene. Whenever the global
+render-list version or the light signature (positions, colors,
+intensities) changes, one worker collects every render triangle and
+mesh block, builds a
+[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/gi/TriangleBvh.html][TriangleBvh]]
+over them (top-down median split along the longest axis; two-sided
+Möller–Trumbore intersection: nearest-hit queries for bounce rays,
+any-hit with early out for shadow rays), copies the light list and the
+ambient color, and publishes the result atomically. Rebuilds are
+single-flighted — one worker builds, the rest keep sampling the old
+snapshot — and rate-limited to one per =e3d.gi.minRebuildMs= (default
+1000 ms), because streaming worlds bump the render-list version per
+loaded cell and back-to-back BVH rebuilds would starve the actual ray
+work. Every rebuild clears all progressive state and restarts the bake
+from stage 1.
+
+The snapshot's entries form a work queue sorted near-to-far from the
+camera, workers grab entries with an atomic cursor, and the barrier
+between passes waits for the cursor to drain and every in-flight entry
+to finish: nothing starts pass k+1 before everything has finished
+pass k.
+
+AITODO: describe stage rings, how they follow observer and where is
+their radius specified.
+
+
+*** Stage 0: polygons are unlit and appear as-is
+:PROPERTIES:
+:CUSTOM_ID: stage-0-unlit
+:END:
-During the bake each texel carries four kinds of state, written only
-by GI threads:
+Before the bake produces anything, every surface renders exactly as it
+would without GI:
-- *Indirect total* (RGB floats) — the accumulated bounced light, the
- sum of all completed generations. This is what the composite texture
- displays.
-- *Previous-generation delta* (RGB floats) — the last completed
- generation's contribution: the gather source for the generation
- currently being traced.
-- *Current-generation accumulator* (RGB floats) — the running mean of
- the generation in progress, shown as a live preview.
-- *Per-light visibility bytes* — whether the shadow ray from this
- texel reached each lamp (written in generation 1; direct light is
- always derived from these, never stored separately).
+- Mesh blocks paint their plain texture: the =giLight= array is null,
+ and starts at 255 (full brightness) once allocated.
+- Plain shaded polygons get ordinary Lambert shading with every lamp
+ treated as visible — the GI shadow bits answer "visible" until
+ computed, and the indirect add is zero.
+- Lightmapped triangles show composite textures initialized at
+ =e3d.gi.initialIrradiance= (default 255): their true base color,
+ unlit.
-All of it lives on the triangle's
-[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/gi/Lightmap.html][Lightmap]]
-as flat arrays indexed by texel (=texel = j * width + i=):
+The stage costs nothing and lasts only until the first snapshot is
+built and the bake starts landing — but it means enabling GI never
+produces a dark or gray flash: the world looks identical to a no-GI
+run, and the lighting refines on top of it.
-#+BEGIN_SRC java
-/** Accumulated indirect total and the two generation buffers
- (pre-albedo light units), width * height entries each. All arrays
- are null before the bake reaches this lightmap and after the bake
- completes — a finished lightmap keeps only its final texture. */
-public volatile float[] indirectR, indirectG, indirectB; // total
-public volatile float[] deltaPrevR, deltaPrevG, deltaPrevB; // gen k-1
-public volatile float[] deltaCurR, deltaCurG, deltaCurB; // gen k
+*** Stage 1: per-polygon centroid, direct light
+:PROPERTIES:
+:CUSTOM_ID: stage-1-direct
+:ID: d317446c-4cf1-4089-8ebc-3bcb8893f517
+:END:
-/** Per-texel per-light visibility: texelCount * lightCount bytes,
- indexed [texel * lightCount + lampIndex]. One byte per pair:
- 0 = unknown, 1 = shadow ray reached the lamp, 2 = blocked. */
-public byte[] lightVisibility;
-public int lightCount;
+1) One sample point per polygon: the centroid, nudged 0.5 world units
+ off the surface along the normal.
+2) From it, one shadow ray toward each tracked lamp (any-hit against
+ the BVH; lamps behind the surface rejected without spending a ray).
+3) Illumination = ambient + the sum over reached lamps of cosine x
+ attenuation x intensity x light color — the same formula the
+ flat-shading path uses.
+4) The result is one RGB triplet per polygon: its uniform direct
+ illumination.
+
+*No lightmap texture is generated at this stage.* The painter
+multiplies the polygon's existing texture (or flat color) by the
+triplet per pixel — the mechanism mesh blocks already use (=giLight=
+stamped per triangle, span writers multiply each sampled texel by
+triplet / 255). A texture premultiplied with a /uniform/ value would
+cost memory for zero visual difference: multiplying after sampling
+commutes with mip averaging.
+
+This stage costs at most =e3d.gi.maxLights= short rays per polygon, so
+the whole scene flips from the placeholder gray to per-polygon shading
+with shadows almost immediately.
+
+*Implemented as generation 0 of the bake.* Every entry — lightmapped or
+not — gets one centroid evaluation against every tracked lamp:
+
+- *Plain polygons and mesh-block triangles*: the centroid is their
+ final sampling resolution, so this pass IS their direct-light state
+ (recorded in their per-polygon floats / the block's =giLight= array).
+- *Lightmapped triangles*: the triplet is stamped on the triangle
+ (=setGiShade=) and the painters multiply every sampled texel of the
+ composite — which still holds the initial base-color fill — by
+ triplet / 255. No lightmap texel work happens in this pass, so the
+ whole scene shows per-polygon direct light with shadows within the
+ first seconds. The stamp is cleared the moment the triangle's first
+ real composite lands.
+
+A lightmap that has already shown traced lighting
+(=Lightmap.everComposited=) is not stamped: on rebake the old composite
+stays on screen until the new per-texel direct lands, so a moving lamp
+never flashes the scene back to the flat preview.
+
+*** Stage 2: per-polygon centroid, indirect light (first bounce)
+:PROPERTIES:
+:CUSTOM_ID: stage-2-indirect
+:END:
-/** Bake progress: 0 = nothing, 1 = direct done, k = k generations. */
-public volatile int generation;
-#+END_SRC
+1) Same centroid point. =e3d.gi.samples= cosine-weighted bounce rays.
+2) A ray landing at Q reads Q's /stage-1/ illumination (the frozen
+ stage-1 field — no new shadow rays), multiplied by Q's albedo and
+ the =1/pi= diffuse gain.
+3) A ray that hits nothing escapes to the sky dome: it contributes the
+ scene's sky color (=LightingManager.skyColor=) times the diffuse
+ gain and =e3d.gi.skyScale= (default 0.5 — display-picked sky colors
+ read far brighter than lamp-lit surfaces, so the raw color floods
+ shadows; ~0.65+ starts to look foggy at aerial poses). Sky
+ unset/black or scale 0 = the historical behavior,
+ escapes contribute zero and shadowed faces fall back to ambient.
+ =-De3d.gi.sky=RRGGBB= overrides the scene's sky color.
+4) The samples average to the polygon's uniform first-bounce indirect
+ light.
+
+Display: texture x (ambient + direct + first bounce). Color bleeding
+appears, uniformly per polygon.
+
+*Implemented, exactly as described.* Runs as generation 2 of the bake:
+every entry — lightmapped or not — bounces at the centroid, and rays
+read the frozen stage-1 per-polygon field at all hits. The combined
+centroid value is the mean of =e3d.gi.samples= (default 8)
+cosine-weighted rays. Sky sampling is implemented as described above:
+the miss paths of =gatherTarget= and =gatherTotal= emit the dome
+radiance, and =lightSignature= folds in the sky color so changing it
+rebakes. Verified headlessly on the House scene: every
+lightmapped triangle's stamp is exactly direct + first-bounce indirect,
+and bleed shows at centroid resolution (indirect near the red sofa is
+far redder than far away: R/B 2.77 vs 1.69).
+
+*** Stage 3: low-resolution lightmaps
+:PROPERTIES:
+:CUSTOM_ID: stage-3-lowres
+:END:
-Two footnotes for the precise reader: visibility is a whole byte per
-texel-lamp pair, not a packed bitfield (the plain-polygon path is the
-one using literal bits — a =visibleBits= / =knownBits= pair of =long=
-masks, one bit per lamp), and at most the first 16 lamps are tracked
-per scene.
+Lightmapped triangles allocate their composite textures at coarse
+resolution: 4x the final units-per-texel (1/16 of the final texel
+count, rounded to the nearest texel count per axis).
-*The arrays are bake scaffolding, not permanent state.* They are
-allocated lazily when the bake reaches a lightmap — a lightmapped
-scene that never enables GI pays only the two composite textures per
-triangle — and they are freed scene-wide the moment the bake
-completes. What remains per triangle is exactly the two
-double-buffered textures (one shown, one spare). A scene or light
-change restarts the bake and re-allocates them.
-
-Resolution is set in world units per texel
-(=LightmappedCompositeShape.setLightmapUnitsPerTexel()=, default 12):
-a 100-unit wall cell gets an 8x8 lightmap. Halving the units
-quadruples the tracing work.
-
-*What you trace is what you see:* the composite texture the painter
-samples is the lightmap itself, at native texel resolution — there is
-no upscaling step. Shadow-edge smoothness comes from tracing at finer
-resolution, never from interpolation.
-
-* Bounce generations
+**** Texel size: the square-texel rule
:PROPERTIES:
-:CUSTOM_ID: generations
+:CUSTOM_ID: square-texel-rule
:END:
-The scene is lit in strict global generations, each walking all
-entries near-to-far from the camera, with a barrier between
-generations: no texel starts generation k+1 before every texel has
-finished generation k.
-
-** Generation 1 — direct light
+Texel density is proportional to the triangle's size *in world
+space*, measured after all rotations and transforms — the lightmap is
+built from the same post-transform =world= vertices the painter
+renders (=TriangleMeshBlock.triangleWorld=).
+
+The lightmap grid is an ORTHOGONAL frame on the triangle's plane, not
+the triangle's own edge frame: the longest edge becomes the u-axis,
+the v-axis is the in-plane perpendicular, and the texture covers the
+triangle's axis-aligned bounding rectangle in that frame (corners
+=(0,0)=, =(width,0)=, =(apexU*width, height)=). One texel therefore
+covers =unitsPerTexel= x =unitsPerTexel= world units on BOTH axes of
+EVERY triangle — square in world space, never sheared into diamonds
+by an acute corner. (The edge frame was the bugreport-20261005-192002
+failure: on sliver/fan triangles it sheared texels into long diagonal
+streaks.) The bounding rect on the longest edge is exactly 2x the
+triangle's area, so squareness costs nothing extra: the old
+half-empty edge-frame texture had the same 2x overhead.
+
+Square is the efficiency optimum, not an aesthetic choice: an
+elongated texel wastes RAM and bake rays along its long axis
+(resolution that carries no new information) while aliasing along its
+short axis, so for any fixed texel budget the square shape delivers
+the best possible image. Dimensions are fitted JOINTLY: the ideal
+aspect is scaled into the 1..128 bounds and the 4-texel long-axis
+floor BEFORE integer fitting (bounds change density, never shape),
+then a small neighborhood search picks the integer (width, height)
+pair with the best aspect, tie-broken toward the ideal texel count.
+Stage 4 inherits the same frame at the final density
+(=e3d.gi.meshUnitsPerTexel=).
+
+Residual deviations, all small or unavoidable:
+
+1) *Integer rounding.* The width's own rounding error is the only
+ anisotropy left: at most half a texel, i.e. <= ~1.1:1 above 5
+ texels and shrinking as counts grow.
+2) *Doubly extreme slivers.* A strip that is both far thinner than
+ one texel AND longer than ~128 x aspect can't get enough texels
+ under the 128 cap; its single row stretches (huge + thin is
+ pathological at any RAM budget).
+3) *The 128-texel cap* on huge triangles lowers DENSITY there (both
+ axes proportionally, so texels stay square) — a RAM guard, not a
+ shape choice.
+
+**** Per-texel direct (generation 1)
:PROPERTIES:
:CUSTOM_ID: gen-1-direct
:END:
-Every lightmap texel casts one *shadow ray* toward each lamp, nudged
-0.5 world units off the surface along the normal so the ray does not
-self-intersect. The ray is an any-hit query against the BVH: if any
-triangle intersects the segment between the texel and the lamp, the
-lamp is occluded and this texel lies in its shadow. The outcome is
-cached as the texel's visibility bytes. Lamps behind the surface are
-rejected outright, without spending a ray.
-
-Direct light is never stored as a value: whenever it is needed (by
-the compositor, or by generation-2 bounce rays), it is recomputed from
-the cached visibility bytes as ambient + the usual
-cosine x attenuation x intensity sum over visible lamps. That keeps
-the direct term exactly consistent with the shadow cache at all
-times.
-
-Plain polygons and mesh-block triangles get the same evaluation once
-at their centroid — that is their final resolution; they skip the
-lightmap machinery entirely.
-
-** Generation k >= 2 — one more bounce
+Scheduled after the stage-2 centroid bounce, at coarse resolution.
+Every lightmap texel casts one *shadow ray* toward each tracked lamp,
+nudged 0.5 world units off the surface along the normal so the ray does
+not self-intersect, and terminating 1.0 world units before the lamp so
+geometry touching the light does not count as occluding it. The ray is
+an any-hit query against the BVH: if any triangle intersects the
+segment, the lamp is occluded and the texel lies in its shadow. Lamps
+behind the surface are rejected outright, without spending a ray. The
+outcome is cached as the texel's visibility bytes. Shadows gain edges
+/inside/ polygons for the first time.
+
+Direct light is never stored as a value: whenever it is needed — by the
+compositor, or by bounce rays — it is recomputed from the cached
+visibility as ambient + the usual cosine × attenuation × intensity sum
+over visible lamps, the same formula the flat-shading path uses (see
+[[file:../Shading/][Shading & Lighting]]). That keeps the direct term
+exactly consistent with the shadow cache at all times.
+
+Plain polygons and mesh-block triangles skip this pass: they were
+already centroid-evaluated in stage 1, which is their final sampling
+resolution.
+
+AITODO: Plain polygons and mesh block triangles should not skip this
+pass. They should get lightmap too. It must be possible to go GI
+against plain polygons.
+
+**** Per-texel bounces (generation 3+)
:PROPERTIES:
:CUSTOM_ID: gen-k-bounce
:END:
+AITODO: Get rid of generations. When shooting rays all around in Stage
+3, they can bounce against sky or when they bounce against polygon
+(textured or not) it should use that polygon pixel value/brightness as
+can be deducted from Stage 2. When computing Stage 3, all nearby
+polygons are anyway lit using Stage 2 algorithm. Note, if ray baunces
+against polygon really really far away, and Stage 2 was not computed
+for it, it can then at least use stage 1 brightness. Let's make it so
+that Stage is the generation. In essence Stage 3 kind of resolves
+almost 3 bounces already, because Stage 2 already accumulates indirect
+light that is 2 bounces. And Stage 1 is direct light only, so Stage 1
+is one bounce. So what happens is that each stage in general keeps at
+the same time increasing resolution of the texel and mounce counts
+bucause it bounces rays against textures/polygonsn whose color was
+computed already at the prewious stage. Do you get my idea ?
+
+
+------- Old Stage 3 documentation, adjust or remove as appropriate:
+
+
Every texel casts =e3d.gi.samples= (default 8) *bounce rays* in random
cosine-weighted directions around the normal, and averages them as a
-plain running mean. What a ray reads where it lands (point Q) depends
-on the generation:
-
-- *Generation 2* reads Q's *direct* light (from Q's cached visibility
- — no new shadow rays). Result: light that has bounced exactly once.
-- *Generation k >= 3* reads only Q's *generation-(k-1) delta*. Result:
- light that has bounced exactly k-1 times.
+plain running mean. The first per-texel bounce (generation 3) gathers
+the *stage-2 total* at the hit — direct + stage-2 indirect — folding
+bounces 1 and 2 into one coarse generation. Every further generation
+reads only the hit surface's *previous-generation delta*, so each
+generation adds exactly one more bounce: generation k's result is light
+that has bounced exactly k-1 times.
+
+The gathered value is multiplied by the hit surface's albedo — the
+lightmap's base color, the polygon's flat color, or the average color
+of a mesh triangle's texture — and by the =1/pi= diffuse gain. The gain
+keeps the loop gain below one, so each generation is smaller than the
+last and bounce light fades geometrically with depth. The readout is
+also clamped to display range: light near a lamp can sum far beyond
+255, and feeding unbounded energy into the bounce loop would saturate
+the scene.
The strict barrier is what makes this well-defined: generation k only
ever reads completed generation-(k-1) output, never a half-written
current value. And because the sampled field is frozen for the whole
-generation, the samples are independent — a plain average is the
-right estimator, with no exponential moving average and no blend
-factors to tune.
+generation, the samples are independent — a plain average is the right
+estimator, with no exponential moving average and no blend factors to
+tune.
#+INCLUDE: "Bounce estimator.svg" export html
-At the barrier the finished delta folds into the texel's accumulated
-total (what the composite texture displays), the delta buffers swap,
-and the next generation begins. The =1/pi= diffuse gain keeps each
-generation smaller than the last: the loop gain is below one, so
-bounce light fades geometrically with depth.
+Display: composite = baseColor x (per-texel direct + accumulated
+indirect). The uniform stage 1-2 triplet is discarded for these
+triangles; the coarse field replaces it both on screen and as the
+gather source of the next stage.
+
+*** Stage 4: high-resolution lightmaps, then converge
+:PROPERTIES:
+:CUSTOM_ID: stage-4-highres
+:END:
-** Termination and teardown
+AITODO: review in similar spirit as Stage 3
+
+------------------------------
+
+When the coarse bake terminates (the same mean-delta rule as below),
+every radius-eligible lightmap =refine()=s to the final units-per-texel
+— 4x finer per axis than stage 3, 16x the texels — and the shown
+composite is upscaled, so the display does not regress at the
+transition. The solver itself restarts from zero at generation 1: the
+coarse field seeds the DISPLAY only, never the solver — carrying it
+into the accumulated indirect would count the Neumann series twice.
+
+The fine bake then runs the plain generation chain at full resolution:
+generation 1 per-texel direct, generation 2 reading the fine *direct*
+at hits (plain-polygon hits contribute their frozen stage-2 total
+once), generations k >= 3 reading the previous delta — the same bounce
+estimator as stage 3. Lightmaps beyond the stage-4 radius finalize at
+coarse resolution: the coarse composite is their terminal display
+(re-armed for a fine catch-up if the camera approaches later).
+
+**** Termination and teardown
:PROPERTIES:
:CUSTOM_ID: termination
:END:
-The bake ends when a generation's mean absolute per-texel delta falls
-below =e3d.gi.deltaThreshold= (default 0.5 light units — later
+At the barrier the finished delta folds into the texel's accumulated
+total (what the composite texture displays), the delta buffers swap so
+the finished generation becomes the next one's gather source, and
+mesh-block triangles receive their updated light total (direct +
+accumulated indirect) in the block's paint array.
+
+Each phase's bake ends when a generation's mean delta — the largest
+channel change per texel, averaged over all texels and polygon states —
+falls below =e3d.gi.deltaThreshold= (default 0.5 light units; later
generations can only be smaller, so they cannot move the picture) or
when =e3d.gi.generations= generations have run (default 6 = direct +
-up to 5 bounce generations). Then every lightmap composites one final
-time and all per-texel arrays are freed. The workers idle at a low
-cadence, watching for scene changes.
+up to 5 bounce generations). The coarse bake's termination triggers the
+refine above; the fine bake's termination composites every lightmap one
+final time and frees all per-texel arrays scene-wide. The workers then
+idle, polling for scene changes four times a second.
The generation cap is an honest trade: a hard stop at 6 generations
discards the remaining series tail — single-digit percent of the
white room. Raise the knob for such scenes; the cost is one more
full-scene pass per extra generation.
-* What you see while it bakes
+*** Radius gating: bounding the stages around the camera
+:PROPERTIES:
+:CUSTOM_ID: radius-gating
+:END:
+
+In a huge streaming world (millions of triangles), the global barrier
+between stages makes later stages unreachable in practice: stage 2 must
+bounce /every/ triangle before any lightmap work starts. Radius gating
+bounds each stage to a distance bubble around the camera:
+
+| Key (config.yaml =e3d= section) | System property | Stage bounded |
+|---------------------------------+-----------------+---------------|
+| =giStage2Radius= | =-De3d.gi.stage2Radius= | centroid bounce |
+| =giStage3Radius= | =-De3d.gi.stage3Radius= | coarse lightmaps |
+| =giStage4Radius= | =-De3d.gi.stage4Radius= | fine refinement |
+
+A radius of 0 (the default) means unlimited — the historical global
+bake. Stage 1 is deliberately never gated: bounce rays read the hit
+surface's stage-1 visibility bits everywhere, so every polygon keeps
+its correct direct light and only /indirect/ detail falls off with
+distance.
+
+Eligibility is re-evaluated from the *live* camera position at every
+generation barrier — the bubble follows the camera through the bake.
+Entries that become eligible only after the bake converged (you walked
+up to a new building) get a /local catch-up/ on the idle GI threads:
+their own direct trace plus one bounce against the frozen converged
+field, never a global generation restart (re-running a generation would
+double-count its energy in entries that already received it).
+
+The catch-up preserves the staged look wherever the camera goes: a
+mesh-block triangle entering the *stage-3 ring* gets a COARSE lightmap
+(the =stage3TexelFactor= density, upgraded to fine by the refine
+catch-up if you approach into the stage-4 disc), while a triangle
+entering the stage-4 disc directly joins at fine resolution. The same
+applies to standalone lightmapped triangles that sat outside the
+stage-3 radius for the whole bake — they hold only the stage-1 shade
+until the bubble reaches them, then trace their direct + bounce at
+their constructed resolution. Only fully-baked composites enter the
+lightmap cache, so a shade-only fill is never resurrected as "final".
+
+*Mesh-block triangles gain lightmaps inside the stage-3 bubble.* Lean
+=TriangleMeshBlock= geometry (the only kind streaming game worlds use)
+otherwise finishes at the per-triangle stage-2 shade. A block triangle
+inside the bubble gets a regular per-triangle Lightmap whose composite
+resamples the block's /photo texture/ (not a flat albedo) so texture
+detail survives, at =giMeshUnitsPerTexel= units per texel (default 2.1)
+for the final resolution. Block lightmapping is enabled by a positive
+stage-3 radius only — at 0, blocks behave exactly as before. Triangles
+with alpha textures (cutout foliage) never get lightmaps: a composite
+is opaque and would render the card as a solid slab — they keep the
+per-triangle shade.
+
+Baked composites are kept in a RAM cache (=LightmapCache=, capped by
+=giLightmapCacheEntries=, default 65536) keyed by a hash of the
+triangle's world geometry. When a streamed-out cell streams back in,
+its lightmaps restore bit-exactly without a rebake — invalidation rides
+the same light signature that triggers snapshot rebuilds.
+
+The stage-1/stage-2 CENTROID values (per-triangle direct color and
+first-bounce color — just two RGB triples per triangle) get the same
+treatment through =GiCentroidCache= (capped by
+=giCentroidCacheEntries=, default 4M — ~120 bytes per entry, sized to
+hold a full streamed FO4 world). A snapshot rebuild —
+triggered by every cell stream-in/out — used to re-run stage 1
+(millions of shadow rays) and stage 2 (100k+ centroid bounces) for
+geometry that had not changed at all. Now the old snapshot's values
+are harvested before the state map drops, and entries whose geometry
+hash and light signature match are restored before the new snapshot
+is published: stage 1 and the stage-2 bounce skip them, and their
+display colors are written back immediately, so a re-entering cell
+never shows an unlit frame (bugreport-20261005-220333). Restored
+shadows may briefly reflect occluders that streamed away — the same
+tradeoff the lightmap cache takes; the per-texel stages (3+) still
+recompute normally.
+
+** Lightmaps: a texture per triangle
+:PROPERTIES:
+:CUSTOM_ID: lightmaps
+:END:
+
+Flat shading can only color a polygon uniformly — shadows and gradients
+need resolution /inside/ the polygon. Every lightmapped triangle
+therefore owns a small generated texture, its
+[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/gi/Lightmap.html][Lightmap]],
+whose texels map onto the triangle surface by the affine rule
+p(u,v) = origin + edge1·u + edge2·v. The frame is ORTHOGONAL: the
+longest edge is the u-axis, the v-axis is the in-plane perpendicular,
+and the texture covers the triangle's bounding rectangle in that
+frame, so the UVs pin to the corners (0,0), (width,0),
+(apexU·width, height):
+
+#+INCLUDE: "Lightmap mapping.svg" export html
+
+(The figure shows the conceptual edge1/edge2 mapping; in the shipped
+frame edge2 is the perpendicular remainder, and the third corner sits
+at (apexU, 1) rather than (0, 1).)
+
+The valid texel region is the inside of the triangle in that frame
+(right of the left edge, left of the right edge, above the base). The
+rest of the rectangle is never traced; at composite time it is
+flood-filled from valid neighbors so that bilinear sampling and mip
+resampling near the edges never pick up garbage. The bounding rect on
+the longest edge is exactly 2x the triangle's area, and texels are
+square in world space on EVERY triangle shape — no sheared diamonds
+on acute fan triangles (bugreport-20261005-192002).
+
+Width and height are fitted JOINTLY for square texels: the ideal
+aspect is scaled into the 1..128 bounds and the 4-texel long-axis
+floor before integer fitting, then the width is fitted to the rounded
+height's aspect with a small neighborhood search — residual
+anisotropy is the width's own rounding error, <= ~1.1:1 above 5
+texels and shrinking as counts grow.
+=LightmappedCompositeShape.setLightmapUnitsPerTexel()= (default 12)
+sets the world-unit size of one texel. A 100-unit wall cell gets an
+8x8 lightmap. Halving the units quadruples the tracing work. *What you
+trace is what you see:* the composite texture the painter samples is
+the lightmap itself, at native texel resolution — shadow-edge
+smoothness comes from tracing finer, never from interpolation.
+
+During the bake each valid texel carries four kinds of state, stored as
+flat arrays indexed by texel number (~j * width + i~) and written only
+by GI threads:
+
+- *Indirect total* (RGB floats) — the accumulated bounced light, the
+ sum of all completed generations. This is what the composite texture
+ displays.
+- *Previous-generation delta* (RGB floats) — the last completed
+ generation's contribution: the gather source for the generation
+ currently being traced.
+- *Current-generation accumulator* (RGB floats) — the running mean of
+ the generation in progress, shown as a live preview.
+- *Per-light visibility bytes* — whether the shadow ray from this texel
+ reached each lamp (written in generation 1; direct light is always
+ derived from these bytes, never stored separately).
+
+The fields, on
+[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/gi/Lightmap.html][Lightmap]]:
+
+#+BEGIN_SRC java
+/** Accumulated indirect total and the two generation buffers
+ (pre-albedo light units), width * height entries each. All arrays
+ are null before the bake reaches this lightmap and after the bake
+ completes — a finished lightmap keeps only its final texture. */
+public volatile float[] indirectR, indirectG, indirectB; // total
+public volatile float[] deltaPrevR, deltaPrevG, deltaPrevB; // gen k-1
+public volatile float[] deltaCurR, deltaCurG, deltaCurB; // gen k
+
+/** Per-texel per-light visibility: texelCount * lightCount bytes,
+ indexed [texel * lightCount + lampIndex]. One byte per pair:
+ 0 = unknown, 1 = shadow ray reached the lamp, 2 = blocked. */
+public byte[] lightVisibility;
+public int lightCount;
+
+/** Bake progress: 0 = nothing, 1 = direct done, k = k generations. */
+public volatile int generation;
+#+END_SRC
+
+Two footnotes for the precise reader. Visibility is a whole byte per
+texel-lamp pair here, not a packed bitfield — the plain-polygon path is
+the one using literal bits (a =visibleBits= / =knownBits= pair of
+=long= masks, one bit per lamp, 64 lamps hard maximum there). And only
+the first =e3d.gi.maxLights= lamps (default 16) are tracked at all:
+lamps past the cap cast no shadows and contribute no direct light in
+composites.
+
+*The arrays are bake scaffolding, not permanent state.* They are
+allocated lazily by =Lightmap.ensureArrays()= when the bake first
+reaches a lightmap — a lightmapped scene that never enables GI pays
+only the two composite textures per triangle — and freed scene-wide by
+=Lightmap.freeArrays()= the moment the bake completes. What remains per
+triangle is exactly the two double-buffered textures (one shown, one
+spare). A scene or light change restarts the bake and re-allocates
+them.
+
+** What you see while it bakes
:PROPERTIES:
:CUSTOM_ID: display
:END:
-The world starts at a *uniform medium irradiance*
-(=e3d.gi.initialIrradiance=, default 128): the scene is visible from
-the very first frame. Each lightmap then flips to its traced direct
-lighting when generation 1 reaches it — near-to-far, so the change
-sweeps across the view as a wave — and bounce light deepens generation
-by generation after that.
+The world is visible from the very first frame, exactly as without GI:
+lightmap textures start at their true base color
+(=e3d.gi.initialIrradiance=, default 255), and mesh-block light arrays
+start at 255 (full texture brightness). Stage 1 then stamps every
+polygon with its uniform direct light — near-to-far, so per-polygon
+shading with shadows sweeps across the view within the first seconds —
+and each lightmap upgrades to per-texel traced direct lighting when
+generation 1 reaches it (the uniform stamp hands over to the first
+composite). Bounce light deepens generation by generation after that.
During the bake the composite textures regenerate at most every
-500 ms, showing the accumulated total plus the in-progress
-generation's mean. There is deliberately no display smoothing: within
-a generation the values only get less noisy, and at the barrier they
-only grow toward the final solution, so steps are small and always in
-the right direction.
+500 ms, always into the spare buffer, swapped in atomically — painters
+never see a half-updated texture. The displayed indirect term is the
+accumulated total plus the in-progress generation's mean. There is
+deliberately no display smoothing: within a generation the values only
+get less noisy, and at the barrier they only grow toward the final
+solution, so steps are small and always in the right direction.
- *Despeckle*: at composite time the indirect channel is blended 50/50
with the mean of its valid 4-neighbors, killing single-texel Monte
- Carlo spikes without blurring real gradients.
+ Carlo spikes without blurring real gradients
+ (=-De3d.gi.despeckle=false= disables it).
- *Scene changes*: any geometry or light change rebuilds the snapshot
- and restarts the bake from generation 1. The old textures stay on
- screen until the new direct pass lands — a visible step, not a
- gradual fade (the price of freeing all solver state between bakes).
+ and restarts the bake from stage 1. The old textures stay on screen
+ until the new direct pass lands — a visible step, not a gradual fade
+ (the price of freeing all solver state between bakes). Lightmaps that
+ have already shown traced lighting keep their old composite: the
+ uniform preview only plays on the very first bake.
-* Plain polygons get GI too
+** Plain polygons get GI too
:PROPERTIES:
:CUSTOM_ID: plain-polygons
:END:
interface that =GlobalIllumination= installs into the
[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/LightingManager.html][LightingManager]]:
-- =isLightVisible(polygon, light)= answers from cached shadow bits —
- direct-light shadows fade in on flat-shaded geometry.
+- =isLightVisible(polygon, light)= answers from the cached shadow bits
+ — direct-light shadows fade in on flat-shaded geometry.
- =addIndirectLight(polygon, baseColor, result)= adds the polygon's
- bounced-light estimate into the flat-shaded color.
+ accumulated bounced-light estimate into the flat-shaded color, scaled
+ by the polygon's own albedo.
Both are called from parallel render-pool threads, so they only read
-volatile caches — never trace. Unlike lightmap texel arrays, these
-few per-polygon floats are permanent: the renderer reads them every
-frame.
+volatile caches — never trace, never allocate. Unlike the lightmap
+texel arrays, these few per-polygon floats are permanent: the renderer
+reads them every frame.
-* Mesh blocks get GI too
+** Mesh blocks get GI too
:PROPERTIES:
:CUSTOM_ID: mesh-blocks
:END:
-Lean =TriangleMeshBlock= shapes (bulk static geometry: streamed game
-maps, imported models) participate without lightmaps. The block
-allocates one integer triplet per triangle (direct + indirect light,
-255 = full) on the first GI snapshot; =MeshTriangle.paint= copies its
-triangle's triplet into the painted =TexturedTriangle= before the span
-loop, and the span writers multiply every sampled texel by
-triplet / 255 — per-triangle baked shading at a branch per pixel.
+Lean
+[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TriangleMeshBlock.html][TriangleMeshBlock]]
+shapes (bulk static geometry: streamed game maps, imported models)
+participate without lightmaps. When a block first enters a GI snapshot
+it allocates one float triplet per triangle (=giLight=, 255 = full
+texture brightness, so enabling GI shows no dark age). Generation 1
+stamps the centroid's direct light; each later barrier adds the bounce
+delta on top, so the array always holds ambient + direct + accumulated
+indirect. Before painting, the triangle's handle copies its triplet
+into the span-writer fields, and the span loops multiply every sampled
+texel by triplet / 255 — per-triangle baked shading at three multiplies
+and a clamp per pixel. While no GI system has stamped the block, the
+array is null and painting is bit-identical to the unlit path.
On the tracing side a mesh-block triangle is a =TriangleBvh.Entry=
whose =polygon= is null; the entry instead carries the block reference
and the triangle index, and its progressive state lives in the same
-per-state map, keyed by the entry rather than the polygon. Generation
-1 writes the triangle's direct light into the block's array; each
-generation barrier adds the latest bounce delta on top. Albedo for
-bounce coloring comes from each block's average texture color, so warm
-walls warm up the shade near them.
-
-Because streaming worlds bump the render-list version on every loaded
-cell, snapshot rebuilds are single-flighted (one worker builds, the
-rest keep sampling the old snapshot) and rate-limited
-(=-De3d.gi.minRebuildMs=, default 1000 ms) — no back-to-back BVH
-rebuilds while the camera moves.
+per-state map, keyed by the entry rather than the polygon. Albedo for
+bounce coloring comes from the average color of the triangle's texture,
+cached per texture — so warm walls warm up the shade near them.
* Two-sided surfaces
:PROPERTIES:
- =SolidPolygon= computes a second shaded color with the negated
normal every frame; the painter picks front or reverse color by the
signed screen area, the same test backface culling uses.
-- =LightmappedCompositeShape= wraps a two-sided source into a
- lightmapped front triangle /plus/ a plain solid triangle of reversed
- winding for the back, and turns culling on for both halves: the
- lightmap only knows its front side, so the back side renders with
- ordinary one-sided direct lighting. Each side's pixels are owned by
- exactly one surface, so nothing z-fights and no holes appear even
- when the source model's winding is inconsistent.
+- =LightmappedCompositeShape= wraps a two-sided source into TWO
+ lightmapped triangles — front, plus a reversed-winding back whose
+ negated normal gives it its own lightmap — and turns culling on for
+ both halves (2026-10-04; previously the back was a plain solid
+ triangle with per-polygon light only). Each side's pixels are owned
+ by exactly one surface, so nothing z-fights and no holes appear
+ even when the source model's winding is inconsistent, and both
+ sides bake their own lighting: exteriors catch street lamps and
+ moonlight instead of borrowing the interior's light.
* Enabling GI
:PROPERTIES:
|| =e3d.gi.generations= | 6 | total generations: 1 = direct, each more = +1 bounce ||
|| =e3d.gi.samples= | 8 | bounce rays per texel per generation, averaged ||
|| =e3d.gi.deltaThreshold= | 0.5 | early stop: generation mean delta (light units) ||
-|| =e3d.gi.initialIrradiance=| 128 | uniform medium start (0..255 light units) ||
+|| =e3d.gi.initialIrradiance=| 255 | initial un-baked brightness (255 = true colors) ||
|| =e3d.gi.despeckle= | true | neighbor-smoothing of indirect at composite time ||
|| =e3d.gi.minRebuildMs= | 1000 | snapshot rebuild rate limit (streaming worlds) ||
+|| =e3d.gi.stage3TexelFactor=| 4 | stage-3 lightmap coarsening: units-per-texel multiplier ||
|| =e3d.gi.debug= | false | generation statistics to stdout ||
|| =e3d.gi.dumpLightmaps= | (unset) | dump composite lightmaps as PNGs to the given dir ||
the root composite is never frustum-tested (it's always rendered), so
the "Total" count excludes it.
+** Global Illumination
+:PROPERTIES:
+:CUSTOM_ID: developer-tools-gi
+:END:
+
+Two status rows that report what the [[file:Global illumination/][global
+illumination]] system is doing, updated every 200 ms. The rows reflect
+[[https://www3.svjatoslav.eu/projects/aukio-3d/apidocs/eu/svjatoslav/aukio/e3d/renderer/raster/gi/GlobalIllumination.html][GlobalIllumination]]'s
+live =Status= snapshot, so they also respect per-instance radius
+overrides — the numbers describe the *effective* configuration, not
+just the global defaults.
+
+Example (all four possible row states):
+
+#+BEGIN_EXAMPLE
+Stage: 3 (gen 12) queue 1841/5202 Covered: 96 u / cap 150
+Eligible S2/S3/S4: 222 / 22 / 0 Cache: 0 lm + 63444 centr. catch-up 0
+#+END_EXAMPLE
+
+*** Stage line
+:PROPERTIES:
+:CUSTOM_ID: gi-stage-line
+:END:
+
+=Stage: <text> queue <done>/<length>=
+
+The stage text is one of:
+
+| Text | Meaning |
+|------+---------|
+| =disabled= | No GI system attached to the view (GI not enabled) |
+| =starting…= | GI thread running but nothing baked yet (also shown when the entry count is 0) |
+| =<n> (gen <g>)= | Bake in progress: currently baking stage =n= (1 = direct light + coverage; 2, 3, 4 = indirect bounce passes, tightest radius first) of generation =g= |
+| =done (catch-up watch)= | Every entry fully baked; the GI thread is idle except for watching for newly streamed-in polygons that need catch-up baking |
+
+=queue <done>/<length>= shows how many work items of the current stage
+have been completed out of how many were queued. The queue is filtered
+per generation (bugreport-20261005-212907): entries already holding a
+current value are skipped when the queue is built, so a light change
+or a newly streamed cell does not re-enqueue the whole world. While
+=done=, the queue reads =0/0=.
+
+*** Coverage line
+:PROPERTIES:
+:CUSTOM_ID: gi-coverage-line
+:END:
+
+=Covered: <d> u / cap <r>= (or =Covered: — u (no cap)=)
+
+- =<d> u= — how far from the camera, in world units, the bake has
+ spread: the distance to the farthest polygon that already holds a
+ fully baked value. Shows =— u= until the coverage walk has a
+ measurement (briefly after startup or a light change).
+- =/ cap <r>= — the radius cap of the *currently active* stage
+ (stage 2/3/4 radius respectively), again the effective value after
+ per-instance overrides. =(no cap)= means the active stage is
+ unlimited (cap 0) — typically stage 1, which covers everything, or
+ a stage whose radius was set to 0.
+
+Watch this line to answer "is the light done spreading to where I'm
+looking?": when =<d>= stops growing and reaches (or exceeds) the cap,
+the visible scene is fully baked out to that stage's radius.
+
+*** Eligible and cache line
+:PROPERTIES:
+:CUSTOM_ID: gi-eligible-cache-line
+:END:
+
+=Eligible S2/S3/S4: <a> / <b> / <c>=
+
+How many polygons fall inside each indirect stage's radius right now —
+i.e. how much work each remaining bounce pass still has to do. These
+counts move as you walk around (streaming changes what is near) and as
+radii are reconfigured. All zeroes with a non-=done= stage means the
+bake is draining its current queue and will advance shortly.
+
+=Cache: <n> lm + <m> centr. catch-up <k>=
+
+- =<n> lm= — entries in the lightmap cache (=LightmapCache=, see
+ [[file:Global illumination/index.org::#lightmaps][Lightmaps: a texture
+ per triangle]]): fully baked lightmaps kept by their light
+ signature, so a polygon whose light inputs have not changed never
+ re-rasterizes its lightmap.
+- =<m> centr.= — entries in the centroid cache: per-polygon stage-1
+ and stage-2 results (direct RGB, indirect RGB, delta and visibility
+ bits) keyed by geometry identity. A polygon that streams out and
+ back in — the normal case in a streamed world — restores both
+ finished stages from RAM and is never recomputed twice within a run.
+ The cache is capped at 4,000,000 entries by default (≈ 0.5 GB worst
+ case, sized for a fully streamed FO4 world), tunable via
+ =e3d.gi.centroidCacheEntries= / =-De3d.gi.centroidCacheEntries=.
+- =catch-up <k>= — polygons that arrived *after* their generation was
+ already baked (streamed in late) and are queued for catch-up baking.
+ A nonzero value here while the stage line says =done (catch-up
+ watch)= is normal right after fast movement; it should drain back
+ to 0 within seconds. If it never drains, those polygons are being
+ re-discovered faster than the catch-up thread bakes them.
+
** Render threads
:PROPERTIES:
:CUSTOM_ID: render-threads
Use the *Clear Logs* button to reset the log buffer for fresh
diagnostic captures.
+** Make Bug Report
+:PROPERTIES:
+:CUSTOM_ID: make-bug-report
+:END:
+
+The *Make Bug Report...* button (next to *Clear Logs*) asks "What
+happened / what looks wrong?" and then writes a self-contained
+=bugreport-<timestamp>= directory (default root
+=~/.local/share/aukio/bugreports=, configurable via
+=bugreport.dir= / =-De3d.bugreport.dir=) you can hand to a developer — or to an AI assistant,
+which can work through it fully automatically:
+
+| File | Contents |
+|------+----------|
+| =description.txt= | The text typed into the popup |
+| =info.txt= | Camera pose, view/screen resolution, heap, telemetry snapshot, java/os versions, effective config |
+| =screenshot.png= | A copy of the last rendered frame |
+| =aukio.log= / =aukio.log.1= | Persistent logs, including output from a session that froze before the report could be made |
+| =histogram.txt= | Live-object histogram from =jcmd <pid> GC.class_histogram= (the OOM smoking gun; skipped when =jcmd= is unavailable) |
+| =threads.txt= | Full thread dump for hang diagnosis |
+
+The =camera = (...)= line in =info.txt= is the authoritative pose —
+paste it straight into a headless reproduction
+([[#snapshot][Snapshot]], Fo4Shot's =-Daukio.fo4.spawnAt=) to render
+exactly what the reporter saw. After writing, a dialog shows the
+report path with *Copy Path* and *Open Folder* buttons.
+
** Headless & agentic tooling
:PROPERTIES:
:CUSTOM_ID: headless-agentic
+++ /dev/null
-# Architecture & maintainability review — aukio-3d
-
-Scope: 152 main-source files, ~31.7k LOC at `/home/n0/workspace/Aukio/aukio-3d`.
-Read fully: ViewPanel, TexturedTriangle, AbstractCompositeShape, OctreeVolume, RenderAggregator,
-RenderingContext, AbstractCoordinateShape, ShapeCollection, SolidPolygon, LineInterpolator,
-PolygonBorderInterpolator, SegmentRenderingContext, AbstractShape; skimmed the rest.
-Dead-code claims verified by grep across aukio-3d (main+test), aukio-3d-demos, aukio,
-aukio-environment-fo4 (no reflection usage found in consumers; demos touch 64 engine classes,
-aukio 24, fo4 17 — the API surface is genuinely exercised).
-
----
-
-## [HIGH] 1. ViewPanel is a god class — 10 distinct responsibilities
-
-`gui/ViewPanel.java` (1611 lines). Responsibilities, with evidence:
-
-1. AWT/Swing integration — `getPreferredSize/getMinimumSize/getMaximumSize` (420-432),
- `paint/update` overrides (537-543), `initializeCanvas` (545-556), `addNotify` (558-562),
- `ensureBufferStrategy` (564-594).
-2. Frame-loop & FPS pacing — `renderLoop` (1444-1456), `maintainTargetFps` (1464-1485),
- `ensureThatViewIsUpToDate` (1494-1521), `noteFrameBlitted` (987-1001).
-3. Pipeline scheduling (transform/sort/bin/paint triple-buffered passes) — `renderFrame`
- (598-652), `transformPass` (1094-1132), `submitPaintPass` (1146-1273),
- `flushPendingPaint` (800-877), `flushCompletedPasses` (889-901), `PendingPaint`/`PresentJob`
- (240-266).
-4. Presentation thread + mailbox — `presentFrame` (671-684), `presentLoop` (703-742),
- `blitFrame` (744-791), mailbox fields (198-208), `PRESENT_RATE_LIMIT_FPS` (223-224).
-5. Stereo configuration & eye-offset math — fields (1029-1039), `transformPass` IPD offset
- (1100-1104), stereo accessors (1046-1080).
-6. Thread-pool lifecycle — `getOrCreateTransformExecutor` (1295-1321),
- `defaultRenderThreadCount` (1284-1287), plus the dead `renderExecutor` machinery
- (see finding 7).
-7. Input device hot-plug — `initializeHeadTracking` (1346-1352), `initializeSpaceMouse`
- (1360-1366).
-8. Developer tools integration — `showDeveloperToolsPanel` (516-535), segment-boundary
- overlay drawn inline into the framebuffer (849-869).
-9. Lighting & GI lifecycle — `lightingManager` (145), `enableGlobalIllumination` (490-510).
-10. Raster helpers that belong to the renderer — `clearSegmentPixels` (911-926),
- `combineMouseResults` (928-941).
-
-Refactor sketch: extract (a) `PipelineScheduler` owning renderFrame/transformPass/
-submitPaintPass/flush* + pendingPaints/passCounter/frameContexts (~550 lines), (b)
-`FramePresenter` owning mailbox/presentLoop/blitFrame/PresentJob (~150 lines), (c)
-`DeviceHotplug` for headtrack+spacemouse init/stop (~60 lines). ViewPanel keeps AWT glue,
-public API delegating to the three. The four participants communicate through
-RenderingContext fields that already exist.
-
-Risk: HIGH but contained to the engine — no rasterizer math touched, so golden pixels are
-untouched by construction. The risk is concurrency regression in the pipeline itself; mitigated
-by the `aukio3d.pipeline=false` kill switch (232-233) and the existing
-ParallelTransformTest/SegmentBinningTest. Move code verbatim first (no logic edits),
-verify with the demos' HouseGoldens + Fo4Shot runs.
-
-## [HIGH] 2. Package structure is fictional — total cycle, renderer↔gui inverted
-
-The import graph over top-level packages contains every possible cycle: gui↔renderer,
-geometry↔renderer, geometry↔gui, math↔gui, math↔geometry (computed over all 152 files).
-
-Root cause: the renderer's core types live in `gui`:
-- `gui/RenderingContext.java`, `gui/SegmentRenderingContext.java`, `gui/HiZPyramid.java`,
- `gui/CullingStatistics.java`, `gui/ThreadActivityRecorder.java`.
-- 15 renderer files import `gui.*`, e.g. `renderer/raster/RenderAggregator.java:7`,
- `renderer/raster/ShapeCollection.java:9-12` (imports gui.CullingStatistics, gui.Camera,
- **gui.ViewPanel** — the renderer depends on the AWT Canvas),
- `renderer/raster/shapes/basic/texturedpolygon/TriangleMeshBlock.java:6` (gui.HiZPyramid).
-- 5 gui files import renderer (ViewPanel:21-23, RenderingContext:11+18, GuiComponent:14-16,
- LookAndFeel:7, TextEditComponent:13) → direct gui↔renderer cycle.
-- geometry depends upward: `geometry/BspTree.java:7` and `geometry/Plane.java:8` import
- renderer...SolidPolygon; `geometry/Frustum.java:7` imports gui.Camera;
- `geometry/Point3D.java:7` imports renderer.octree.IntegerPoint (for one convenience
- constructor, Point3D.java:121).
-- `math/Vertex.java:9` imports gui.RenderingContext.
-
-Refactor sketch (mechanical, move-only): relocate RenderingContext, SegmentRenderingContext,
-HiZPyramid, CullingStatistics, ThreadActivityRecorder, StereoEye to `renderer.raster` (or a new
-`renderer.core`); move `gui.Camera`+`gui.ViewSpaceTracker` to geometry/math (Camera is pure
-transform state). Break geometry→renderer by moving BspTree to
-renderer...shapes.basic.solidpolygon (it stores SolidPolygon) or abstracting its element type.
-Fix Point3D→IntegerPoint by moving that constructor to IntegerPoint or a small adapter.
-ShapeCollection's ViewPanel dependency is only `viewPanel.getCamera()`
-(ShapeCollection.java:302-305) — the Camera overload already exists (314), so the ViewPanel
-overload is a convenience that could delegate from gui side or take a Camera.
-After moves, the intended order math ← geometry ← renderer ← gui/headless becomes real.
-
-Risk: LOW for correctness (no code changes, only moves + import updates), MEDIUM for consumers:
-three downstream repos must update imports. Public API breakage is the cost; do it in one sweep
-with a consumer-side sed. Golden tests unaffected (no FP code moves between classes in a way
-that changes execution order — class relocation has no runtime effect).
-
-## [HIGH] 3. Verified dead code — 6 classes + 2 fields (~340 lines)
-
-Grepped simple-name references across engine main+test and all three consumer repos:
-
-- `geometry/Circle.java` (30 LOC) — no references anywhere.
-- `gui/ViewUpdateTimerTask.java` (31 LOC) — no references; legacy of the pre-render-thread
- design (its `run()` calls the now-package-private `ensureThatViewIsUpToDate`).
-- `gui/humaninput/Connexion3D.java` (48 LOC) — standalone /dev/hidraw experiment with its own
- `main()`; superseded by `gui/spacemouse/SpaceNavigatorHid`.
-- `renderer/octree/raytracer/RayHit.java` (56 LOC) — unreferenced even inside the raytracer.
-- `renderer/raster/shapes/composite/solid/SolidPolygonMesh.java` (60 LOC) — unreferenced.
-- `renderer/raster/shapes/composite/wireframe/WireframeDrawing.java` (75 LOC) — unreferenced.
-- `ViewPanel.renderExecutor` + `ensureExecutorMatchesThreadCount()` (ViewPanel.java:121,
- 1327-1339, 1406): created, resized, shut down — but **never used to submit a single task**;
- `submitPaintPass` uses `getOrCreateTransformExecutor()` (1155). Legacy of the pre-ForkJoinPool
- design. ~35 dead lines including the eager `Executors.newFixedThreadPool(...)` allocation at
- construction time (121) — a real thread pool allocated and thrown away per ViewPanel.
-- `ViewPanel.renderFrameCount` (596, incremented at 607): static, write-only, never read.
-
-Refactor sketch: delete all of the above.
-Risk: ZERO for the classes/fields (no references exist, no reflection in consumers). Keep a
-note that Connexion3D's main() is a hardware experiment if the maintainer wants it archived.
-
-## [HIGH] 4. AbstractCompositeShape carries an embeddable CSG engine + parallel-transform machinery
-
-`renderer/raster/shapes/composite/base/AbstractCompositeShape.java` (1295 lines). Responsibilities:
-
-1. Sub-shape registry + group visibility (88-133, 179-195, 335-377, 756-764).
-2. Render-list caching & triangulation (775-821, 886-910).
-3. CSG boolean engine (~240 lines, fully self-contained): `extractSolidPolygons` (304-315),
- `union` (549-574), `subtract` (597-631), `intersect` (654-683), `clonePolygons` (694-700),
- `replaceSolidPolygons` (709-725), `mergeNonPolygonChildrenFrom` (735-748).
-4. Bounding-box aggregation (230-280).
-5. Frustum culling inline in `transform` (912-997; AABB corner transform at 929-971).
-6. Parallel-transform machinery (~280 lines): weight-cache fields (1026-1077),
- `getTransformWeight` (1095-1120), `shouldForkTransform` (1132-1140),
- `transformChildrenParallel` (1192-1275), constants (1003-1020, 1147).
-7. Bulk property fan-out via instanceof chains — 8 sites: `setColor` (397-409),
- `setShadingEnabled` (494-504), `setBackfaceCulling` (514-526),
- `setMouseInteractionController` (422-432), plus 254, 308-311, 478, 791-807, 851-856.
-
-Also: `transformChildrenParallel(…, aggregator, …)` takes a **dead parameter** — its own
-javadoc admits it (1187-1190: "unused in the parallel path"), and the body never uses it.
-
-Refactor sketch: (a) move the CSG block to a new `Csg` utility class in the same package —
-all methods take/return `List<SolidPolygon>` plus the registry mutations already isolated in
-`replaceSolidPolygons`/`mergeNonPolygonChildrenFrom`; AbstractCompositeShape keeps three
-one-line delegating methods for API compatibility. (b) Extract the weight/fork machinery into
-`ParallelTransformPlanner` (fields + getTransformWeight + shouldForkTransform + chunking),
-leaving `transform()` as orchestration. (c) Drop the dead `aggregator` parameter from
-`transformChildrenParallel`. Result: ~1295 → ~700 lines.
-
-Risk: LOW-MEDIUM. CSG is call-graph-isolated (only BspTree + registry), no FP-order-sensitive
-output (CSG is geometry, not rasterization — pixel risk none; geometry-identical because the
-code moves verbatim). The parallel planner touches concurrency — move verbatim, keep field
-semantics; verified by ParallelTransformTest.
-
-## [MEDIUM] 5. RenderAggregator: cohesive, but three separable machines
-
-`renderer/raster/RenderAggregator.java` (861 lines). Responsibilities:
-
-1. Shape queue + merge: `queueShapeForRendering` (703-706), `mergeFrom` (716-720),
- `mergeAllParallel` (734-795), `reset` (831-838).
-2. Sorting with three strategies (~210 lines): `tryRadixSort` (187-228), `parallelMergeSort`
- (235-280), `runSortTasks` (283-308), `mergeRuns` (311-322), `awaitAll` (324-334), driver
- `sort` (131-174).
-3. Tile binning CSR (~280 lines): fields (400-418), `matchingBinIndex` (427-439), `matchAxis`
- (452-463), `binForTiles` (500-523), `buildBins` (543-593), `binPhase` (596-634),
- `binRangeCsr` (642-683).
-4. Two-pass paint orchestration: `paintSorted` (353-366), `paintRange` (370-397).
-
-Refactor sketch: extract `ShapeSortMachine` (sort strategies + scratch arrays) and
-`TileBinMachine` (CSR fields + build/match), aggregator keeps queue + paint and holds one of
-each. Also drop `implements Serializable` on the comparator (844) — nothing serializes it.
-Note the sort order contract (Z desc, shapeId asc) is the bit-exactness backbone for
-binning/paint; extraction must move code verbatim.
-
-Risk: LOW (pure control flow, no FP math; order preserved by construction). Verified by
-SegmentBinningTest + HouseGoldens.
-
-## [MEDIUM] 6. Rasterizer duplication: 7 span writers, 3 interpolator classes, 2 blend formulas
-
-Interpolators — three classes with byte-identical cores:
-`LineInterpolator` (solidpolygon), `PolygonBorderInterpolator` (texturedpolygon),
-`PerspectiveBorderInterpolator` (texturedpolygon). Identical: `containsY` (LineInterpolator:
-84-88 = PolygonBorderInterpolator: 85-89 = PerspectiveBorderInterpolator: 101-105), the
-`getX` formula (`round(p1.x + (width*(y-p1.y))/height)`, LineInterpolator:100-105 vs
-PolygonBorderInterpolator:129-134), `setPointsZW` (LineInterpolator:130-134 =
-PolygonBorderInterpolator:182-186 = PerspectiveBorderInterpolator:137+).
-
-Span/line writers — 7 sites: TexturedTriangle's `drawHorizontalLinePerspectiveZ` (223-405),
-`drawHorizontalLineSdf` (968-1086), `drawHorizontalLinePerspectiveSdf` (1093-1263),
-`drawHorizontalLineZ` (1312-1429); SolidPolygon's `drawHorizontalLine` (305-386); Line's two
-single-pixel painters (180-233, 242-298). Within TexturedTriangle alone:
-- the SDF bilinear-fetch + coverage block is byte-identical twice (1023-1066 vs 1197-1240, ~45 lines);
-- the adaptive-interval ladder is byte-identical twice (322-335 vs 1163-1177);
-- the edge-pair Y-scan loop appears 4× (698-708, 927-937, 950-960, 1293-1303), a 5th in
- SolidPolygon (456-468);
-- the yTop/yBottom clamp block appears 2× in-file (467-486 vs 596-615), a 3rd in SolidPolygon
- (425-440);
-- the swap-left/right + clamp preamble appears 4× (239-260, 986-994, 1117-1127, 1327-1346).
-
-Two *different* alpha-blend approximations exist: SolidPolygon/Line use
-`((dest*bgAlpha) + src*alpha) >> 8` (SolidPolygon:376-378, Line:223-225, 289-291);
-TexturedTriangle uses `dest + ((alpha*(src-dest) - dest) >> 8)` (386-388 and 3 more sites).
-**They are not pixel-equivalent** — unifying span writers would change golden output.
-
-Refactor sketch (ordered by safety):
-(a) SAFE: unify the three interpolators into one `EdgeInterpolator` — keep the exact FP
-expression shapes (`(width * (y - p1.y)) / height`, midpoint for `|height| < EPSILON`), only
-collapsing storage. No arithmetic changes → bit-exact.
-(b) SAFE: extract the SDF bilinear fetch + coverage evaluation into one private static helper
-called from both SDF writers — it is already byte-identical, so extraction cannot change
-output if the expression text moves verbatim (watch implicit constant folding: keep `int`
-casts and shifts identical).
-(c) SAFE: single-source the edge-pair Y-scan loop as a small static helper taking the three
-interpolators + a span callback — control-flow only.
-(d) UNSAFE without re-golden: merging the two blend formulas. Don't — instead add a comment at
-each site naming the formula and why they differ, or standardize deliberately and re-bless
-goldens as a separate, announced change.
-
-Risk: (a)-(c) LOW if done as verbatim text motion (FP op order preserved); (d) is a visible
-output change — treat as a feature, not a refactor. HouseGoldens/Fo4Shot are the gate.
-
-## [MEDIUM] 7. RenderingContext: ~45 fields in the wrong package
-
-`gui/RenderingContext.java` (707 lines). 43 instance fields + 2 statics; 22 public non-final
-(measured). Natural clusters:
-
-- Framebuffer: bufferedImage (158), pixels (91), depth (99), graphics (78), segmentGraphics
- (85), width/height (126/131).
-- Projection: centerCoordinate (137), projectionScale (144), nearPlaneDistance (184),
- frustum (289), viewerPosition (298).
-- Tile/viewport geometry: tilesX/tilesY/viewportCount/numRenderSegments (63-72),
- renderMinY/MaxY (150/156, **final**), renderMinX/MaxX (274/281, **mutable** — asymmetric,
- mutated post-construction at ViewPanel:1224-1225), stereo* (255-267).
-- Pipeline bookkeeping: vertexSlot (176), frameNumber (190), transformCycleId (166),
- presentGate (344), depthPass (109), transformExecutor (324), transformCoordinator (333),
- lastTransformTaskCount (350).
-- Culling: subpixelCullingThreshold/Epoch (198/208), cullingStatistics (306),
- occlusionPyramid (316).
-- Mouse picking (~120 lines incl. methods 627-705): mouseEvent (222),
- objectPreviouslyUnderMouseCursor (213), currentObjectUnderMouseCursor (226),
- currentMouseTextureU/V (231-232).
-- Services smuggled through: developerTools (237), debugLogBuffer (243), lightingManager (250).
-
-Belongs elsewhere: mouse-picking state+methods → `MousePickState` (owned by context, one
-field); `presentGate` → pipeline glue owned by the scheduler/ViewPanel (it is only written at
-ViewPanel:617-619 and awaited in the paint continuation); `depthPass` → RenderAggregator
-passes it to shapes via context purely as a side-channel; `lastTransformTaskCount` →
-diagnostics bundle; `lightingManager`/`developerTools`/`debugLogBuffer` → a small
-`FrameServices` bag would cut constructor/copy-constructor duplication.
-
-Also note the two copy constructors (442-470, 482-521) enumerate fields by hand and already
-diverge (the pass copy omits frustum "by design" — comment 520 — and silently drops
-presentGate/lastTransformTaskCount). Every new field must be added in up to 3 places; this is
-where the next pipeline bug comes from.
-
-Refactor sketch: (1) move class to renderer.raster (see finding 2); (2) extract MousePickState
-(whole methods move); (3) move presentGate to the scheduler; (4) cluster remaining fields into
-final sub-objects (Framebuffer, ViewportGeometry) so the copy constructors shrink to field
-copies of immutable parts + shallow shares.
-
-Risk: LOW-MEDIUM — all mechanical, but the class is read by ~every shape; keep accessors as
-delegates so shape code (`renderBuffer.pixels`, `.depth`, `.renderMinX`…) is untouched until a
-second pass updates call sites. No FP code → goldens safe. The public-field style means
-consumers may read these fields directly; keep the same field names visible during transition.
-
-## [MEDIUM] 8. OctreeVolume: 560-line copy-paste tracer + fully public internals
-
-`renderer/octree/OctreeVolume.java` (1102 lines), used only by demos' OctreeDemo.
-
-- Raw storage exposed: `public int[] cell1..cell8` (42-56), `public int cellAllocationPointer`
- (61), `usedCellsCount` (64), `masterCellSize` (67), plus `initWorld` (298) re-allocating the
- arrays under any concurrent reader. Invariants (cell state encoding -1/-2, 0 = null child)
- are unenforceable.
-- `doesIntersect` (133-248): 7 near-identical ~16-line face slabs.
-- `traceCell` (512-1100): 8 octant branches × up to 7 recursive-probe stanzas each (~12 lines
- per stanza) — ~560 lines of mechanical copy-paste with hand-maintained visit orders
- ("// 6 8 3 5 2 4 1", 533).
-- `getNewCellPointer` (335-350): linear-scan allocator with wraparound; infinite-loops when the
- buffer is full (no exhaustion check) — a latent hang, not just style.
-
-Refactor sketch: (a) represent the 8 children as `int[][] children` or one `int[8]` per cell
-indexed by octant — the putCell sub-cube selection (411-461) and traceCell collapse to loops
-over octant index with a precomputed per-ray-octant visit-order table (8 orders × 8 octants,
-64 entries, generated once). That alone removes ~500 lines. (b) Encapsulate arrays; add
-exhaustion failure in getNewCellPointer (return -1 / throw) instead of an infinite loop.
-(c) Optionally extract the ray-trace half (doesIntersect/traceCell) into `OctreeRayWalker`.
-
-Risk: LOW correctness-wise for (b) and the hang fix; MEDIUM for (a) — visit order affects
-*which* cell is returned first for ties, and OctreeDemo visuals depend on it. Not covered by
-golden tests (octree is not in the golden harnesses), so verify by side-by-side OctreeDemo
-screenshots. This subsystem is demo-only; alternatively quarantine it as-is and spend effort
-elsewhere.
-
-## [LOW] 9. AbstractCoordinateShape: slot-explosion + internal duplication
-
-- 12 scalar fields + 3 lists encode "screen state × 3 slots" (83-110, 165-175); accessors
- repeat the same 3-way ternary 7 times (218-271).
-- `setSlotScreenState` (126-148) and the write block inside `transform` (503-521) are the same
- 3-way branch twice — `transform` could call `setSlotScreenState(slot, …)` (one-line fix).
-- Stale docs: six accessors say "slot (0 or 1)" (226, 236, 246, 256, 266, 276) though slots are
- 0/1/2.
-
-Refactor sketch: introduce `private final ScreenState[] slots = {new ScreenState(), …}` (z,
-minY, maxY, minX, maxX, clippedVertices) — collapses 15 fields to 1 array + deletes 7 branchy
-accessors. Keep public method signatures. Risk: ZERO pixel risk (pure storage, no FP
-expressions), LOW merge risk; internal-only.
-
-## [LOW] 10. API surface & documentation drift
-
-- `ViewPanel.setFrameRate` (957) vs `getTargetFPS` (966) — setter/getter name mismatch
- (setTargetFPS expected).
-- TexturedTriangle javadoc links to methods that no longer exist: `{@link
- #drawHorizontalLinePerspective}` (214), `{@link #drawHorizontalLine}` (318, 1090, 1308,
- 1354, 1381) — the class has only the …Z/…Sdf variants (verified: no `drawHorizontalLine(`
- definition). Javadoc build emits warnings for these.
-- Stale pipeline comments on the most subtle code: "Double-buffered frame contexts" (ViewPanel
- 160) over a 3-element array (165); "Parity (0/1)" (167) while `frameParity = (frameParity +
- 1) % 3` (645); duplicated/orphaned javadoc stub above `getInputManager` (394-402).
-- ShapeCollection slot docs say "(0 or 1)" (428, 469); a commented-out code block + TODO
- (336-337); slot-0-only helpers (`sortShapes()` 421, `getQueuedShapeCount` 499,
- `getBinSizes` 520) beside slot-parameterized siblings — test-only callers, fine, but mark
- them as such.
-- Direct field poke across classes: `AbstractCompositeShape.setColor` writes
- `((Line) shape).color = color` (404) into Line's public field (Line.java:61) instead of a
- setter — bypasses any future invalidation logic.
-- `RenderingContext.bufferedImageType` (48) — constant not in CONSTANT_CASE.
-- `RenderAggregator.ShapesZIndexComparator implements Serializable` (844) — nothing
- serializes it; also `import java.io.Serializable` (10).
-
-Risk: ZERO-LOW. All are comment/name/mechanical fixes; renaming setFrameRate would break
-consumers — prefer adding a correctly-named alias and deprecating.
-
----
-
-## Verdict
-
-**Yes — the architecture is sound for a software rasterizer of this size.** The load-bearing
-structure (transform/sort/bin/paint phases, triple-buffered pipeline with per-slot vertex
-state, painter + z-buffer two-pass visibility, Hi-Z, SoA TriangleMeshBlock) is deliberately
-designed, and unusually well documented: the comments record *measurements and dates* (e.g.
-ViewPanel:113-116, 219-221, 1299-1309; AbstractCompositeShape:1009-1012), which is exactly the
-evidence-based culture that keeps a performance codebase honest. The problems are not the
-design but **entropy concentrated in identifiable places**: ViewPanel's ten responsibilities,
-RenderingContext's 45-field blob sitting in the wrong package (which drags the whole import
-graph into cycles), and hand-maintained copy-paste in the span writers and the octree tracer.
-None of these threaten correctness today; all of them raise the cost of the *next* change.
-The recommended program is: (1) delete the verified dead code (free), (2) package relocation +
-RenderingContext/ViewPanel extraction (mechanical, no FP risk), (3) safe de-duplication only —
-interpolators, identical SDF block, scan-loop helper — leaving the two blend formulas alone,
-(4) extract CSG and the transform planner from AbstractCompositeShape. Every step except
-octree rework is gateable by the existing golden harnesses with bit-exact expectations.
+++ /dev/null
-# aukio-3d performance review — what's left on the table
-
-Read-only static analysis, 2026-09-20. Scope: span writers, AoS-vs-SoA split, sort/bin/transform,
-memory layout, threading, SDF text path, GI/octree. All line numbers against current HEAD.
-
-Known-good state (verified, not re-litigated): parallel chunk transform with pooled scratch,
-radix sort over packed long keys, CSR tile bins, tiled MT paint with two-pass z-buffer,
-Hi-Z block culling, subpixel epoch cache, TriangleMeshBlock SoA transform loop.
-
----
-
-## Tier 1 — multi-ms/frame class at 500k queued triangles
-
-### 1. Radix sort runs single-threaded; the executor handed to `sort()` is ignored in the radix path
-`RenderAggregator.sort(ExecutorService)` (`RenderAggregator.java:162-165`):
-```java
-if (executor != null && sortedCount >= PARALLEL_SORT_THRESHOLD) {
- if (!tryRadixSort(sortedArray, sortedCount)) // <- executor NOT passed
- parallelMergeSort(sortedArray, sortedCount, comparator, executor);
-```
-`tryRadixSort` (`RenderAggregator.java:187-228`) is one serial loop: key build
-(`:193-196`, one virtual `getZ(slot)` per shape), then `RadixLongSort.sortPairs`
-(`RadixLongSort.java:66-98`) = 8 LSD passes, each streaming 500k×(8B key + 4B idx) read +
-12B scatter-write ≈ 96 MB of traffic on ONE core, then a serial random-gather permute
-(`:224-226`) plus a full `System.arraycopy` back. This is the measured ~17 ms sort.
-Bonus: `tryRadixSort` ends `return true` unconditionally — `parallelMergeSort` is dead code.
-
-- Why slow: serial memory-bound passes on one core while 17 workers idle (sort sits between
- drain and bin in the paint continuation — `ViewPanel.java:1200-1205` — so it directly
- delays paint-task submission every pass).
-- Change sketch: parallel LSD radix on the same pool — per-chunk 256-bin histograms (parallel),
- serial 256×chunks prefix, parallel stable scatter with per-(chunk,digit) offsets. Fixed chunk
- boundaries + stability = bit-identical output to today (keys exact, equal-key order preserved,
- tie-run shapeId fix unchanged). Also: permute into the *other* grow-only buffer and swap
- references instead of `arraycopy` back (saves one 4 MB serial copy). Even simpler first step:
- parallelize only the key build by folding it into `mergeAllParallel`'s already-parallel copy
- (`RenderAggregator.java:755-790`) — compute `zSortKey` while copying each part.
-- Impact class: sort 17 ms → ~4-6 ms wall. The largest single remaining pipeline lever.
-
-### 2. Per-triangle raster setup is recomputed per overlapped tile, per frame
-`TexturedTriangle.paintFlat` (`TexturedTriangle.java:621-628`):
-```java
-final double edge12 = projectedPoint1.getDistanceTo(projectedPoint2); // sqrt
-final double edge13 = projectedPoint1.getDistanceTo(projectedPoint3); // sqrt
-final double edge23 = projectedPoint2.getDistanceTo(projectedPoint3); // sqrt
-final double scaleFactor = (totalVisibleDistance / totalTextureDistance) * 1.2d;
-final TextureBitmap mipmap = texture.getMipmapForScale(scaleFactor);
-```
-plus the perspective setup (`:673-682`, three `1d/z` divides + muls) and the per-span curvature
-ladder (`:322-335`, ~7 divides per span). All of this depends only on transform-phase outputs,
-yet `paint()` runs once per overlapped tile — a triangle in 4 tiles pays it 4×.
-Worse on the object path: `paintTriangle` (`:492-497`) computes the same three `getDistanceTo`
-values, then `paintFlat` recomputes them — 6 sqrt per tile-paint for non-SDF triangles.
-And `MeshTriangle.paint` (`MeshTriangle.java:109`) calls `block.origTtd(index)`
-(`TriangleMeshBlock.java:444-456`) = 3 sqrt over the *final, build-time* `uv[]` array,
-recomputed every paint of every tile of every frame.
-
-- Why slow: sqrt ~15-20c each; at ~150k painted triangles × ~1.5 tiles × (3-6 sqrt + divides)
- ≈ 30-60M cycles/frame aggregate paint-side setup that is definitionally redundant.
-- Change sketch (bit-exact — same expressions, evaluated once instead of N times):
- compute `scaleFactor`/mip level/affine-vs-perspective flag once per triangle per slot in
- `TriangleMeshBlock.transform` (mesh path) / `AbstractCoordinateShape.transform` (object path),
- stash in per-slot handle state, pass into `paintFlat`. Precompute `origTtd` into a
- `double[]` at block build (uv is final). In `paintTriangle`, pass the already-computed
- `scaleFactor` down instead of recomputing.
-- Impact class: ~1-3 ms/frame aggregate at FO4 queue sizes; larger for big-screen triangles
- (text quads, terrain near the camera) that span tens of tiles.
-
-### 3. Scanline edge evaluation: per-getter divisions + per-scanline edge re-selection
-`PerspectiveBorderInterpolator.getSU/getSV/getSW/getZW` (`PerspectiveBorderInterpolator.java:112-148`)
-each call `interpolationT()` = `(currentY - p1.y) / height` — a **double division per getter**.
-`drawHorizontalLinePerspectiveZ` (`TexturedTriangle.java:233-259`) calls getX + 4 channel getters
-per edge per scanline: up to 10 divisions/scanline if C2 doesn't CSE them across the inlined
-getters, 4 if it does (getX's `(width * (currentY - p1.y)) / height` is a different expression
-than `width*t`, so it never shares). Same shape in `PolygonBorderInterpolator`
-(`:98-119,129-134,189-194`) and `LineInterpolator.getX/getZW` (`:100-105,144-149`).
-Additionally `containsY` (`PerspectiveBorderInterpolator.java:101-105`) recomputes
-`Math.min/max(p1.y,p2.y)` per call, and the triangle y-loop (`TexturedTriangle.java:698-708`)
-re-tests 2-3 `containsY` per scanline to re-derive which edge pair is active — when the pair
-only changes once, at the middle vertex.
-
-- Why slow: double div ~13-20c; even at the CSE-friendly 4/scanline that's 50-80c/scanline of
- division alone. At 500k queued tris with mean height ~5-15 scanlines, several M scanlines/frame
- → multiple ms of pure edge math, concentrated on exactly the small distant triangles that
- dominate the FO4 scene.
-- Change sketch:
- a) bit-exact: cache `minY/maxY` at `setPoints`; make one explicit `t = (currentY-p1.y)/height`
- per edge per scanline and pass it to the four channel reads (identical expression →
- identical bits, and no longer JIT-CSE-dependent).
- b) needs-tolerance: express `x = p1.x + width*t` (removes the second div; differs by ≤1ulp
- from `(width*dy)/height` — golden tolerance should absorb, verify).
- c) bit-exact with care: split the y-loop into [yTop..yMid] and (yMid..yBottom] halves with the
- edge pair fixed per half (the current inclusive `containsY` semantics pin which pair owns
- the seam scanline — replicate). Removes ~3 containsY + min/max per scanline.
-- Impact class: ~2-5 ms/frame aggregate at small-triangle-heavy views.
-
----
-
-## Tier 2 — ~0.5-2% frame time each, cheap and safe
-
-### 4. Depth margin costs 2 muls + 1 sub per pixel even though it defaults to 0
-All four z-buffered span writers test
-```java
-if (zw > depth[offset] - RenderingContext.DEPTH_MARGIN_DZ * zw * zw)
-```
-`TexturedTriangle.java:356` (perspective-Z), `:1386` (affine-Z), `SolidPolygon.java:354,370`.
-`DEPTH_MARGIN_DZ` (`RenderingContext.java:120-121`) parses `-Daukio.zbuffer.margin`, default `"0"`.
-It's `static final` so C2 folds the constant to 0.0, but `0.0 * zw * zw` is NOT eliminable
-(NaN semantics), so every z-tested pixel pays two dependent muls + a sub for a disabled feature.
-
-- Change sketch (bit-exact: `0.0*zw*zw == +0.0` and `d - 0.0 == d` exactly for finite zw, which
- near-plane clipping guarantees): hoist once per span —
- `final boolean strict = DEPTH_MARGIN_DZ == 0;` and branch to a margin-free loop copy, or
- duplicate the pixel loops under one perfectly-predicted branch. If margin>0 is ever used,
- the quadratic term can also be strength-reduced (`m += (2*c*dzw)*zw + c*dzw*dzw`, both
- coefficients span-invariant) — that variant reassociates FP, so tolerance-check it.
-- Impact class: ~1-1.5c/pixel on every z-tested pixel; at 2-4M tested pixels/frame ≈ 0.5-1%
- frame time, for near-zero code risk.
-
-### 5. Hi-Z pyramid build is a serial full-depth-buffer sweep on the render thread; `occluded()` is `synchronized`
-`ViewPanel.flushPendingPaint` (`:825-829`) calls `HiZPyramid.buildFrom` on the render thread
-after each pass. `buildFrom` (`HiZPyramid.java:61-108`) min-pools the entire float depth buffer
-(8×8 tiles) single-threaded: 8.3 MB @1080p, ~14.7 MB @1440p, ~58 MB at the 4920×2960 stereo
-buffer — ~1-2 ms, up to ~5 ms, serial, before the next transform fork can start.
-And `occluded()` (`:121`) is `synchronized` — every `TriangleMeshBlock.transform` on every
-parallel chunk thread (`TriangleMeshBlock.java:184-216`) takes the same monitor, serializing
-block tests against each other and against the multi-ms build.
-
-- Change sketch: build level 0 per tile in the paint workers' epilogue (depth just written is
- still in L2), reduce upper levels serially (tiny); publish the pyramid as an immutable
- per-build snapshot behind a volatile reference and drop `synchronized` from `occluded()`
- (reads are all from the snapshot). Telemetry `AtomicLong`s → LongAdder.
-- Impact class: ~1-2% @1440p mono, ~5% at 4K-class buffers; removes a contention edge that
- scales with block count × worker count.
-
-### 6. SDF text path: 257×Math.pow + LUT allocation + 2×hypot + 2×log per triangle **per tile** per frame
-`TexturedTriangle.paintSdf` (`:789-961`) runs per tile-paint (a text canvas quad overlapping
-N tiles paints N times). Per call:
-- `Math.hypot` ×2 for footprints (`:820-821`) — hypot pays overflow-safe scaling;
- `sqrt(x*x+y*y)` is 3-5× cheaper (≤1ulp difference: tolerance-check),
-- auto-gamma does `Math.log` ×2 (`:863-864`),
-- when minified (any text past arm's length): `covLut = new int[257]` + 257×`Math.pow`
- (`:865-869`). For a terminal-sized canvas (~2 triangles × 50-100 tiles) that's
- ~200 × (257 pow + 1 KB alloc) ≈ 2M cycles per frame per canvas.
-
-- Change sketch: cache the LUT — gamma is a smooth function of `maxFootprint`; quantize gamma
- to 1/256 steps and keep a per-thread last-LUT (or a tiny `ConcurrentHashMap<Integer,int[]>`).
- Hoist footprint/gamma/aaK to once per triangle per frame (paint-margin-free, so it's
- tile-invariant). This is computation caching, not allocation pooling.
-- Inner loop: the fixed-point bilinear (`:1037-1038` and `:1211-1212`) uses 8 int muls; the
- two-lerp form `top = m00*(256-fx)+m10*fx; bot = m01*(256-fx)+m11*fx; d=(top*(256-fy)+bot*fy)>>16`
- is **bit-identical** (integer associativity; worst case 33.4M < 2^31, no overflow) at 4 muls.
- Halves the mask-eval multiply count on every text pixel.
-- Impact class: workspace/terminal views (aukio TerminalPanel renders through this path):
- ~1-3 ms/frame with several text canvases; FO4: negligible.
-
----
-
-## Tier 3 — smaller or situational
-
-### 7. Two-pass paint visits every bin entry twice
-`RenderAggregator.paintSorted` (`:353-366`) iterates each tile's bin twice;
-`paintRange` (`:370-397`) virtual-calls `paint()` on every entry in both passes and the shape
-early-outs (`TexturedTriangle.paintFlat:563-565`, `SolidPolygon.paint:703-705`) only after a
-volatile texture load + field reads. One of the two visits is always waste: ~queue×tiles
-no-op dispatches per frame (~750k at 500k×1.5 tiles ≈ 0.5-1% frame).
-- Sketch: split each bin into [opaque|alpha] segments at CSR build time (two counts per tile —
- binning order within each class preserved, so pixels are bit-identical); pass 1 walks the
- opaque segment reversed, pass 2 the alpha segment forward.
-
-### 8. Mip-chain lazy build races across paint threads; level selection loops per paint
-`Texture.getDownscaledBitmap` (`Texture.java:278-291`) checks `downSampled[i] == null` and
-builds unsynchronized while 18 paint threads may first-touch the same level on the same frame
-→ duplicated full box-filter chain builds per texture (startup stutter on texture-heavy loads),
-and the array-slot write has no happens-before edge. `getDownscaleMipmapLevel` (`:180-189`)
-loops ≤8 iterations per triangle per tile-paint.
-- Sketch: synchronize per-texture on build (or prebuild chains at texture-load time in the
- FO4 `TextureSource`); publish via the array only after construction (final fields make the
- bitmap itself safe). Replace the halving loop with an exponent-based level pick
- (`Math.getExponent`) — verify threshold equivalence for exact powers of two.
-
-### 9. Octree ray tracer (OctreeDemo path): allocation-per-face-test and non-parametric traversal
-`OctreeVolume.doesIntersect` (`OctreeVolume.java:133-248`) allocates a `new Point3D` (or
-`clone()`) on *every* face candidate — up to 6 allocations per cell visit — and
-`traceCell` (`:512-1100`) orders children by the **origin's octant**, not by parametric
-distance along the ray. Because the first solid hit returns immediately, this is both slower
-(no near-first pruning; every level re-runs 6-division slab tests per child from scratch) and
-suspect (can return a farther voxel over a nearer one when the origin is outside the parent
-cell). `RayTracer.run` (`RayTracer.java:157-175`) allocates a `Ray` + 2 `Point3D` + `Color`
-per pixel and does 3 divides/pixel for view-plane interpolation (`(x3p * x) / width` — should
-be incremental adds); `traceRay` then fires 6 shadow rays × 2 Point3D + Ray allocations per
-light. `getNewCellPointer` (`:335-350`) is a linear scan for a free cell — O(cells) per
-allocation, so filling big voxel volumes is O(n²).
-- Sketch (only if OctreeDemo matters; nothing in FO4 touches this): slab test with precomputed
- per-ray inverse direction, hit point computed once from the winning t (no per-face allocs),
- Revelles-style parametric child ordering, free-list for cells.
-- Impact: background/progressive demo renderer — not frame-critical.
-
-### 10. GI package: BVH build and query constant factors
-`TriangleBvh.build` (`TriangleBvh.java:92-96`) sorts at every tree level with a comparator →
-O(n log² n) build per snapshot rebuild (median selection via quickselect is O(n log n) and
-lambda-free). `rayBox` (`:172-198`) does 6 divisionss per node visit + NaN fixup branches —
-precompute `1/dx,1/dy,1/dz` once per ray and multiply (not bit-identical to division; GI
-output feeds lightmaps, not golden pixels — still verify). `nearestNode` (`:123-140`) visits
-left before right unconditionally; ordering children by nearer-box-first makes the `hit.t`
-bound prune the far child far more often (typically ~2× fewer node visits on nearest-hit).
-`GlobalIllumination.updateComposites` (`:610-637`) fills invalid lightmap texels with a
-`while(progressed)` whole-map rescan — O(texels × map diameter); a BFS/multi-source queue is
-O(texels). Per-sample `new double[3]` returns (`:537`, `:890`) churn on the GI threads —
-background threads, so low stakes, but free to remove.
-- Impact: GI convergence latency and background CPU burn only; render path is unaffected
- (render-side GI cost is already ~zero by design).
-
----
-
-## Question 2 answer: how much AoS is left, and is extending SoA worth it?
-
-FO4 (the 500k-tri target): **~100% mesh blocks.** `NifSceneBuilder.java:169-222` (nif parts) and
-`WorldStreamer.java:1309-1348` (terrain cells) both emit `TriangleMeshBlock` by default
-(`aukio.fo4.meshBlocks`, default true); the `new TexturedTriangle` fallbacks
-(`NifSceneBuilder.java:244`, `WorldStreamer.java:1420`) are behind the same flag.
-`SolidPolygon` is imported in WorldStreamer but never instantiated for geometry.
-
-AoS `Vertex`-graph shapes (SolidPolygon, Line, Billboard, SDF text quads, lightmapped
-triangles) carry 8-9 heap objects per vertex with per-slot pointer chasing — they remain in:
-- demos/benchmarks: SolidCubesTest 16³ cubes ≈ 49k triangles, LitSolidCubesTest, sphere scenes;
-- the Aukio workspace UI (TerminalPanel → TextCanvas → 2 SDF triangles per panel);
-- CSG/lightmapped content where per-shape objects are semantically needed.
-
-Verdict: extending SoA to a `SolidPolygonMeshBlock` would only move the cube/sphere demos —
-not the FO4 number. **Not worth it** for the stated target; the remaining AoS cost is in
-small-N UI/demo scenes where per-shape setup, not pointer chasing, dominates anyway.
-
-## Question 4 answer: memory layout
-
-Pixel buffer and depth buffer are both row-major with identical addressing
-(`y*width + x` everywhere) — span writes are unit-stride in both, tile clears use
-`Arrays.fill` per row (intrinsic-vectorized). No column-major striding anywhere in the hot
-paths. Texture reads (`ity*texW+itx`) stride by texture row — inherent to UV mapping and
-already mitigated by the mip chain. The only structural note: pixels and depth are two
-separate arrays, so each z-tested pixel write touches two cache lines; interleaving them
-would break `BufferedImage` blit interop — not recommended.
-
-## Question 5 answer: thread utilization
-
-Tiles = 10×workers, near-square (`ViewPanel.java:1548-1552`, TILES_PER_THREAD=10) with one
-task per tile on a work-stealing ForkJoinPool (75% of cores, measured choice) — sound.
-Per-pass `CountDownLatch(segments)` is one await per frame, negligible. Two notes: the paint
-continuation (`ViewPanel.java:1177-1268`) blocks a worker on `previousGate.await`
-(`CountDownLatch` — no FJP compensation) — at most a few parked workers, fine; and the
-serial sort inside that continuation is the real utilization gap (finding 1).
-
----
-
-## Verdict
-
-The architecture is **not** at the pure-Java ceiling. The big structural pieces are right
-(SoA transform, radix keys, CSR bins, tiled two-pass z, Hi-Z), but there is one large and
-several medium wins left, all compatible with bit-exactness or within stated tolerance:
-
-**Top 3:**
-1. **Parallelize the radix sort** (it's single-threaded inside a pool it was explicitly
- handed): ~17 ms → ~4-6 ms at 500k shapes. `RenderAggregator.java:162-228`.
-2. **Hoist per-triangle raster setup out of per-tile paint** (mip metric sqrt×3, `origTtd`,
- perspective divides — computed once per slot, not once per tile-overlap):
- `TexturedTriangle.java:492-497,621-682`, `MeshTriangle.java:109`. Plus the guaranteed-safe
- half of the scanline-divide fix (cached min/max, one explicit shared `t` per edge).
-3. **Kill the default-disabled depth-margin math in the four z-span writers**
- (strict-loop specialization, bit-exact) — ~0.5-1% of frame for a few lines;
- and **de-serialize the Hi-Z build + lock-free `occluded()`** — ~1-2% at 1440p, more at 4K.
-
-(3 is two cheap items bundled; if forced to pick three single items: parallel radix, setup
-hoisting, scanline edge-evaluation restructure.)
* {@code telemetryIntervalSeconds} — how often the telemetry line is
* written to the log, default 5.</p>
*
+ * <p>Global illumination radius gating (see
+ * {@code Documentation/Global illumination/index.org}): {@code
+ * giStage2Radius} / {@code giStage3Radius} / {@code giStage4Radius} —
+ * world-unit distance from the camera beyond which entries skip the
+ * centroid bounce (stage 2), the coarse per-texel lightmap bake
+ * (stage 3) and the fine per-texel refinement (stage 4). 0 (default)
+ * means unlimited: every entry gets every stage, the historical
+ * behavior. {@code giMeshUnitsPerTexel} — units per lightmap texel for
+ * mesh-block triangles at the FINAL resolution, default 2.1 (the
+ * stage-3 coarse bake uses {@code e3d.gi.stage3TexelFactor} times
+ * that). {@code giLightmapCacheEntries} — cap on the baked-lightmap
+ * composite cache that restores lightmaps after cell stream-out/in,
+ * default 65536.</p>
+ *
* <p>Every key can also be set as a system property
* ({@code -De3d.ipd=6.3}, {@code -De3d.bugreport.dir=...},
- * {@code -De3d.log.dir=...}, {@code -De3d.telemetry.interval=...});
- * system properties win over the config file.</p>
+ * {@code -De3d.log.dir=...}, {@code -De3d.telemetry.interval=...},
+ * {@code -De3d.gi.stage2Radius=...} and likewise for the other GI
+ * keys); system properties win over the config file.</p>
*/
public final class EngineConfig {
null)), 5);
}
+ /**
+ * GI stage-2 radius in world units: beyond it, entries skip the
+ * centroid bounce and keep their stage-1 direct stamp. 0 (default)
+ * = unlimited.
+ */
+ public static double getGiStage2Radius() {
+ return parseDouble(System.getProperty("e3d.gi.stage2Radius",
+ AukioConfig.get().getString("e3d.giStage2Radius", null)), 0);
+ }
+
+ /**
+ * GI stage-3 radius in world units: beyond it, triangles never get
+ * a lightmap (mesh blocks keep their per-triangle shade). 0
+ * (default) = unlimited for lightmapped shapes — and mesh blocks
+ * then never get lightmaps at all: per-texel work on every lean
+ * triangle of a huge world is exactly what the radius exists to
+ * avoid, so block lightmapping is enabled by a POSITIVE radius.
+ */
+ public static double getGiStage3Radius() {
+ return parseDouble(System.getProperty("e3d.gi.stage3Radius",
+ AukioConfig.get().getString("e3d.giStage3Radius", null)), 0);
+ }
+
+ /**
+ * GI stage-4 radius in world units: beyond it, lightmaps are not
+ * refined to the final texel density and keep the coarse composite.
+ * 0 (default) = unlimited.
+ */
+ public static double getGiStage4Radius() {
+ return parseDouble(System.getProperty("e3d.gi.stage4Radius",
+ AukioConfig.get().getString("e3d.giStage4Radius", null)), 0);
+ }
+
+ /**
+ * Units per lightmap texel for mesh-block triangles at the final
+ * (stage-4) resolution, default 2.1. The stage-3 coarse bake runs
+ * at {@code e3d.gi.stage3TexelFactor} times this.
+ */
+ public static double getGiMeshUnitsPerTexel() {
+ return parseDouble(System.getProperty("e3d.gi.meshUnitsPerTexel",
+ AukioConfig.get().getString("e3d.giMeshUnitsPerTexel",
+ null)), 2.1);
+ }
+
+ /**
+ * Cap on the baked-lightmap composite cache that restores lightmaps
+ * instantly after a cell streams out and back in, default 65536.
+ */
+ public static int getGiLightmapCacheEntries() {
+ return (int) parseDouble(System.getProperty(
+ "e3d.gi.lightmapCacheEntries",
+ AukioConfig.get().getString("e3d.giLightmapCacheEntries",
+ null)), 65536);
+ }
+
+ /**
+ * Cap on the stage-1/2 centroid-value cache that restores direct
+ * and first-bounce lighting instantly when a cell streams out and
+ * back in, default 4 000 000. Sized to hold a full FO4 streamed
+ * world (~1.8-2.7M triangles) so any region you revisit is a hit;
+ * worst-case RAM is roughly half a gigabyte (about 120 bytes per
+ * entry), evicting least-recently-used beyond the cap.
+ */
+ public static int getGiCentroidCacheEntries() {
+ return (int) parseDouble(System.getProperty(
+ "e3d.gi.centroidCacheEntries",
+ AukioConfig.get().getString("e3d.giCentroidCacheEntries",
+ null)), 4_000_000);
+ }
+
+ /**
+ * Master switch for atmospheric distance haze (see
+ * {@code renderer/raster/lighting/Atmosphere.java}), default false.
+ * Environment modules may enable it per scene at runtime.
+ */
+ public static boolean isAtmosphereEnabled() {
+ final String v = System.getProperty("e3d.atmosphere",
+ AukioConfig.get().getString("e3d.atmosphere", null));
+ return v != null && Boolean.parseBoolean(v);
+ }
+
+ /**
+ * Atmospheric haze scale in world units: the camera depth at which
+ * the haze factor reaches ~63% (1 - 1/e), default 100000.
+ */
+ public static double getAtmosphereScale() {
+ return parseDouble(System.getProperty("e3d.atmosphereScale",
+ AukioConfig.get().getString("e3d.atmosphereScale",
+ null)), 100000);
+ }
+
+ /**
+ * Atmospheric haze target color as RRGGBB, default empty = fade
+ * toward the scene's sky color.
+ */
+ public static String getAtmosphereColor() {
+ return System.getProperty("e3d.atmosphereColor",
+ AukioConfig.get().getString("e3d.atmosphereColor", ""));
+ }
+
private static double parseDouble(final String value,
final double fallback) {
if (value == null || value.isBlank())
final long used = rt.totalMemory() - rt.freeMemory();
final StringBuilder sb = new StringBuilder();
sb.append("time = ").append(LocalDateTime.now()).append('\n');
+ // Which app this report is about: the exact launch command
+ // (main class + arguments) and the working directory.
+ sb.append("app.command = ")
+ .append(System.getProperty("sun.java.command", "unknown"))
+ .append('\n');
+ sb.append("app.user.dir = ")
+ .append(System.getProperty("user.dir", "unknown"))
+ .append('\n');
if (viewPanel != null) {
final Camera camera = viewPanel.getCamera();
* The label showing the measured FPS.
*/
private final JLabel measuredFpsLabel;
+ /**
+ * The label showing the GI stage and coverage distance.
+ */
+ private final JLabel giStageLabel;
+ /**
+ * The label showing GI queue progress and bubble sizes.
+ */
+ private final JLabel giDetailLabel;
+ /**
+ * The label showing per-stage eligible entry counts.
+ */
+ private final JLabel giEligibleLabel;
+ /**
+ * The label showing the GI cache size and pending catch-up count.
+ */
+ private final JLabel giCacheLabel;
/**
* Toggle button switching between target FPS and unlimited FPS.
*/
targetFpsLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
measuredFpsLabel = new JLabel(" ");
measuredFpsLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
+
+ // Global illumination row
+ giStageLabel = new JLabel(" ");
+ giStageLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
+ giDetailLabel = new JLabel(" ");
+ giDetailLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
+ giEligibleLabel = new JLabel(" ");
+ giEligibleLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
+ giCacheLabel = new JLabel(" ");
+ giCacheLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
unlockFpsButton = new JToggleButton("Unlock FPS");
unlockFpsButton.setToolTipText(
"Disable the frame rate cap so the application renders as fast as it can (benchmark mode)");
topPanel.add(createSettingsPanel());
topPanel.add(createCameraPanel());
topPanel.add(createCullingPanel());
+ topPanel.add(createGiPanel());
topPanel.add(createRenderThreadsPanel());
topPanel.add(createFrameRatePanel());
topPanel.add(createThreadTimelinePanel());
return panel;
}
+ /**
+ * The Global Illumination row: current bake stage and how far from
+ * the camera the active stage has covered. The queue drains
+ * nearest-first, so a coverage distance that stops growing with work
+ * remaining means the bake is stuck.
+ */
+ private JPanel createGiPanel() {
+ final JPanel panel = new JPanel();
+ panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
+ panel.setBorder(BorderFactory.createCompoundBorder(
+ BorderFactory.createEmptyBorder(0, 8, 8, 8),
+ BorderFactory.createTitledBorder("Global Illumination")
+ ));
+
+ final JPanel stageRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 2));
+ stageRow.add(new JLabel("Stage:"));
+ stageRow.add(giStageLabel);
+ stageRow.add(new JLabel(" Covered:"));
+ stageRow.add(giDetailLabel);
+
+ final JPanel detailRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 2));
+ detailRow.add(new JLabel("Eligible S2/S3/S4:"));
+ detailRow.add(giEligibleLabel);
+ detailRow.add(new JLabel(" Cache:"));
+ detailRow.add(giCacheLabel);
+
+ panel.add(stageRow);
+ panel.add(detailRow);
+ return panel;
+ }
+
private JPanel createRenderThreadsPanel() {
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
try {
updateCameraLabel();
updateCullingStatistics();
+ updateGiRow();
updateRenderThreadsLabel();
updateFrameRateLabels();
updateLogDisplay();
pos.x, pos.y, pos.z, angles[0], angles[1], angles[2]));
}
+ /**
+ * Refreshes the Global Illumination row. Shows the mapped display
+ * stage (1 = centroid direct, 2 = centroid bounce, 3 = coarse
+ * lightmaps, 4 = fine refinement), the queue progress within the
+ * stage, and the camera distance the stage has covered so far vs
+ * the configured radius cap for that stage.
+ */
+ private void updateGiRow() {
+ if (viewPanel == null) {
+ return;
+ }
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination gi =
+ viewPanel.getGlobalIllumination();
+ if (gi == null) {
+ giStageLabel.setText("disabled");
+ giDetailLabel.setText(" ");
+ giEligibleLabel.setText(" ");
+ giCacheLabel.setText(" ");
+ return;
+ }
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination.Status
+ status = gi.getStatus();
+ if (!status.running || status.entries == 0 && !status.baked) {
+ giStageLabel.setText("starting…");
+ giDetailLabel.setText(" ");
+ giEligibleLabel.setText(" ");
+ giCacheLabel.setText(" ");
+ return;
+ }
+
+ final String stageText;
+ if (status.baked)
+ stageText = "done (catch-up watch)";
+ else
+ stageText = status.stage + " (gen " + status.generation + ")";
+
+ // Radius cap of the active stage (0 = unlimited); effective
+ // values from the GI system, aware of per-instance overrides.
+ final double cap;
+ switch (status.stage) {
+ case 2:
+ cap = status.stage2Radius;
+ break;
+ case 3:
+ cap = status.stage3Radius;
+ break;
+ case 4:
+ cap = status.stage4Radius;
+ break;
+ default:
+ cap = 0;
+ break;
+ }
+ final String covered = Double.isNaN(status.coveredDistance)
+ ? "—" : String.format("%.0f", status.coveredDistance);
+ final String capText = cap > 0
+ ? String.format(" / cap %.0f", cap) : " (no cap)";
+
+ giStageLabel.setText(String.format("%s queue %d/%d",
+ stageText, status.queueDone, status.queueLength));
+ giDetailLabel.setText(String.format("%s u%s", covered, capText));
+ giEligibleLabel.setText(String.format("%d / %d / %d",
+ status.stage2eligible, status.stage3eligible,
+ status.stage4eligible));
+ giCacheLabel.setText(String.format("%d lm + %d centr. catch-up %d",
+ status.cacheSize, status.centroidCacheSize,
+ status.catchUpPending));
+ }
+
private void updateCullingStatistics() {
if (viewPanel == null) {
return;
*/
public synchronized eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination enableGlobalIllumination(
final int threadCount) {
+ return enableGlobalIllumination(threadCount, null);
+ }
+
+ /**
+ * Enables progressive global illumination, applying the given
+ * configurer (radius/density overrides) BEFORE the worker threads
+ * start — the first eligibility evaluation already sees them.
+ * Needed when one JVM hosts scenes of different scales (the demo
+ * launcher): per-instance overrides instead of global -D properties.
+ * Calling again returns the already-running system (configurer
+ * ignored).
+ *
+ * @param threadCount worker threads for ray tracing
+ * @param configurer applied to the new GI system before start;
+ * may be null
+ * @return the running GI system
+ */
+ public synchronized eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination enableGlobalIllumination(
+ final int threadCount,
+ final java.util.function.Consumer<eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination> configurer) {
if (globalIllumination == null) {
globalIllumination = new eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination(
rootShapeCollection, lightingManager, threadCount,
() -> getCamera().getTransform().getTranslation());
+ if (configurer != null)
+ configurer.accept(globalIllumination);
globalIllumination.start();
}
return globalIllumination;
}
+ /**
+ * The running global illumination system, or null when GI was never
+ * enabled for this view. Read-only; for the developer tools panel.
+ *
+ * @return the GI system or null
+ */
+ public eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination getGlobalIllumination() {
+ return globalIllumination;
+ }
+
/**
* Shows the developer tools panel, toggling it if already open.
* Called when F12 is pressed.
/**
* Calling these methods tells 3D engine that current 3D view needs to be
* repainted on first opportunity.
+ *
+ * <p>Also (re)starts the render thread when the component is showable:
+ * the thread is otherwise started only from componentShown/Resized,
+ * which under window managers without reparenting (bare Xvfb) can fire
+ * before the panel is displayable — leaving the view dark forever
+ * despite pending repaints. Idempotent; the render thread guards on
+ * {@code renderThread != null}.</p>
*/
public void repaintDuringNextViewUpdate() {
viewRepaintNeeded = true;
+ startRenderThreadIfReady();
}
/**
* @return measured frames per second
*/
public double getMeasuredFPS() {
+ // The window rolls over only when a frame is blitted; once frames
+ // stop (on-demand renderer idling), the stale rate would report
+ // forever. No blit within two windows => the pipeline is idle.
+ if (fpsWindowStartNanos != 0
+ && System.nanoTime() - fpsWindowStartNanos > 1_000_000_000L)
+ return 0;
return measuredFPS;
}
--- /dev/null
+/*
+ * Aukio 3D engine. Author: Svjatoslav Agejenko.
+ * This project is released under Creative Commons Zero (CC0) license.
+ */
+package eu.svjatoslav.aukio.e3d.renderer.raster.gi;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * RAM cache of per-triangle CENTROID lighting (stage-1 direct plus
+ * stage-2 first-bounce indirect), keyed by the same 64-bit geometry
+ * hash as the lightmap cache. Streaming worlds (FO4 cells) rebuild
+ * the GI snapshot on every cell swap, which used to re-run stage 1
+ * (millions of shadow rays) and stage 2 (100k+ centroid bounces) for
+ * triangles that had not changed at all; a cache hit restores both
+ * single-color results instantly (bugreport-20261005-220333).
+ * RAM-only, per GI instance — nothing is persisted to disk.
+ *
+ * <p>Values are validated against the light signature: any light or
+ * sky change misses. Neighboring geometry is NOT part of the key —
+ * the same tradeoff the lightmap cache already takes: a restored
+ * shadow/bounce may briefly reflect occluders that streamed away;
+ * the per-texel stages (3+) still recompute normally.</p>
+ *
+ * <p>Capacity is capped ({@code e3d.giCentroidCacheEntries}, default
+ * 4 000 000 — ~120 bytes per entry, sized to hold a full streamed
+ * FO4 world); eviction is least-recently-used. Thread-safe.</p>
+ */
+final class GiCentroidCache {
+
+ /** One triangle's centroid record. */
+ static final class Entry {
+ float directR, directG, directB;
+ float indirectR, indirectG, indirectB;
+ /** Stage-2 delta: the gather source of the next bounce. */
+ float deltaPrevR, deltaPrevG, deltaPrevB;
+ long visibleBits, knownBits;
+ /** True when the stage-2 centroid bounce had run. */
+ boolean bounced;
+ /** Lighting signature under which the values were computed. */
+ double lightSignature;
+ }
+
+ private final LinkedHashMap<Long, Entry> map;
+
+ GiCentroidCache(final int capacity) {
+ map = new LinkedHashMap<>(1024, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(
+ // qualify: inside a Map subclass the simple name
+ // Entry binds to java.util.Map.Entry, not ours
+ final Map.Entry<Long, GiCentroidCache.Entry> e) {
+ return size() > capacity;
+ }
+ };
+ }
+
+ /** Looks up a centroid record; marks it recently used. */
+ synchronized Entry get(final long key) {
+ return map.get(key);
+ }
+
+ /** Stores a centroid record (the entry is adopted, not copied). */
+ synchronized void put(final long key, final Entry entry) {
+ map.put(key, entry);
+ }
+
+ synchronized int size() {
+ return map.size();
+ }
+}
import eu.svjatoslav.aukio.e3d.renderer.raster.lighting.LightingManager;
import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.AbstractCoordinateShape;
import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.basic.solidpolygon.SolidPolygon;
+import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.basic.texturedpolygon.TriangleMeshBlock;
import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.composite.base.AbstractCompositeShape;
import eu.svjatoslav.aukio.e3d.renderer.raster.texture.Texture;
+import eu.svjatoslav.aukio.e3d.renderer.raster.texture.TextureBitmap;
+import eu.svjatoslav.aukio.e3d.diag.EngineConfig;
import java.util.ArrayList;
import java.util.Comparator;
* CPU global illumination baked in strict bounce generations, running on
* dedicated low-priority threads (never on the render ForkJoinPool).
*
- * <p><b>Generations:</b> the scene is lit generation by generation, each
- * walking all snapshot entries near-to-far from the camera, with a
- * global barrier between generations:</p>
+ * <p><b>Generations:</b> the scene is lit pass by pass, each walking
+ * all snapshot entries near-to-far from the camera, with a global
+ * barrier between passes:</p>
* <ol>
- * <li><b>Generation 1 — direct:</b> every lightmap texel casts a
- * shadow ray toward every light; the outcome is cached in the
- * texel's visibility bytes. Plain polygons and mesh-block
- * triangles get one centroid evaluation instead (their final
- * resolution). Direct light is always derived from the cached
- * visibility, never stored separately.</li>
+ * <li><b>Stage 1 (generation 0) — uniform centroid direct:</b> every
+ * entry gets one centroid evaluation against every tracked lamp.
+ * Plain polygons and mesh-block triangles record it as their
+ * final-resolution direct state; lightmapped triangles display it
+ * immediately through the per-triangle GI shade stamped on the
+ * triangle (no texel work — the painters multiply texels by the
+ * triplet until the first real composite lands). The whole scene
+ * shows per-polygon direct light with shadows within the first
+ * seconds.</li>
+ * <li><b>Generation 1 — per-texel direct:</b> every lightmap texel
+ * casts a shadow ray toward every light; the outcome is cached in
+ * the texel's visibility bytes. Direct light is always derived
+ * from the cached visibility, never stored separately.</li>
* <li><b>Generation k >= 2 — one more bounce:</b> every texel casts
* {@code e3d.gi.samples} cosine-weighted bounce rays and averages
* them (a plain running mean — within a generation the sampled
* texture. Plain polygons keep their handful of per-polygon floats
* (render threads read them every frame through {@link GiLightProvider}).
* A scene or light change rebuilds the snapshot and restarts the bake
- * from generation 1; the old textures stay on screen until the new
- * direct pass lands.</p>
+ * from stage 1; the old textures stay on screen until the new
+ * direct pass lands (a lightmap that has already shown traced lighting
+ * keeps it — no uniform preview on rebake).</p>
*
* <p><b>Two sampling resolutions:</b></p>
* <ul>
* composite-local space, so scenes combining composites with
* non-identity transforms are traced incorrectly.</p>
*
+ * <p><b>Radius gating</b> ({@code e3d.giStage2Radius/ giStage3Radius/
+ * giStage4Radius} in {@code ~/.config/aukio/config.yaml}, or the
+ * corresponding {@code -De3d.gi.stage*Radius} properties): in huge
+ * streaming worlds the full-scene stages would never reach the camera
+ * area, so each stage past 1 can be limited to a distance bubble around
+ * the camera. Entries beyond the stage-2 radius keep their stage-1
+ * direct stamp; lightmapped triangles beyond the stage-3 radius keep
+ * the stage-2 display and never allocate texels; lightmaps beyond the
+ * stage-4 radius are never refined to full density. Eligibility is
+ * re-evaluated from the LIVE camera position at every generation
+ * barrier, so the bubble follows the camera; entries that become
+ * eligible after the bake converged get a local catch-up (one bounce
+ * against the frozen converged field). Stage 1 stays global on purpose:
+ * bounce rays read the hit surface's stage-1 visibility bits
+ * everywhere. Mesh-block triangles additionally gain per-texel
+ * lightmaps inside the stage-3 bubble (they are the only geometry kind
+ * in streaming game worlds); their composites carry the block's photo
+ * texture resampled into lightmap space, and finished composites are
+ * kept in a geometry-keyed {@link LightmapCache} so a cell that streams
+ * out and back in restores its lightmaps instantly. A stage-3 radius of
+ * 0 disables mesh-block lightmapping entirely (the historical
+ * behavior).</p>
+ *
* <p><b>Usage:</b></p>
* <pre>{@code
* GlobalIllumination gi = viewPanel.enableGlobalIllumination(); // 2 threads
/** Minimum interval between composite texture updates. */
private static final long COMPOSITE_INTERVAL_MS = 500;
- /** Per-light visibility is tracked for at most this many lights. */
- private static final int MAX_TRACKED_LIGHTS = 16;
+ /**
+ * Per-light visibility is tracked for at most this many lights
+ * (lights beyond the cap are ignored by GI: no shadow rays, no
+ * direct contribution in composites). Read per use so a demo can
+ * size it to its scene before the bake starts.
+ * {@code -De3d.gi.maxLights}.
+ */
+ private static int maxTrackedLights() {
+ return Integer.getInteger("e3d.gi.maxLights", 16);
+ }
/** Debug statistics with {@code -De3d.gi.debug}. */
private static final boolean DEBUG = Boolean.getBoolean("e3d.gi.debug");
+ /**
+ * Sky dome illumination scale: the displayed sky color is usually
+ * picked for looks, and reads far brighter than lamp-lit surfaces
+ * (7AA3D8 ~ 200 vs a sun-lit wall ~ 110) — feeding it raw as dome
+ * radiance floods shadowed faces to near-white. The bounce
+ * contribution of an escaped ray is
+ * {@code BOUNCE_GAIN x sky x this scale}. {@code -De3d.gi.skyScale},
+ * default 0.5 (sky clearly lifts shadowed faces, sun stays dominant;
+ * ~0.65+ starts to look foggy at aerial poses).
+ */
+ private static final double SKY_SCALE =
+ Double.parseDouble(System.getProperty("e3d.gi.skyScale", "0.5"));
+
/** Albedo for snapshot entries that carry no flat color (textured triangles). */
private static final Color FALLBACK_ALBEDO = new Color(128, 128, 128);
private static final int MAX_GENERATIONS =
Integer.parseInt(System.getProperty("e3d.gi.generations", "6"));
+ // The bake always runs the full staged pipeline (Documentation/
+ // Global illumination, "Polygons are illuminated in the following
+ // order"): stage 1 uniform centroid direct → stage 2 centroid
+ // bounce → stage 3 coarse per-texel lightmap bake → stage 4
+ // full-resolution refine. The coarse bake converges first
+ // (progressive display within seconds), then every radius-eligible
+ // lightmap refine()s and the fine bake converges at the configured
+ // units-per-texel. The coarse field seeds the DISPLAY only, never
+ // the solver: carrying it into the accumulated indirect would
+ // count the Neumann series twice.
+
+ /**
+ * Stage-3 lightmap coarsening: units-per-texel multiplier (4 = 1/16
+ * of the full-resolution texel count, before power-of-two rounding
+ * and the 4-texel floor). {@code -De3d.gi.stage3TexelFactor}.
+ */
+ private static final double STAGE3_TEXEL_FACTOR =
+ Double.parseDouble(System.getProperty("e3d.gi.stage3TexelFactor", "4"));
+
+ /**
+ * Units-per-texel that lightmap construction should use while the
+ * pipeline starts coarse (stage 3): the configured value scaled by
+ * {@link #STAGE3_TEXEL_FACTOR}. Callers pass the fine value when
+ * constructing at final resolution (fine phase, or late entrants
+ * after the bake). Read at {@link LightmappedTriangle} construction
+ * time — changing it takes effect on the next render-list rebuild.
+ *
+ * @param base the composite's configured units per texel
+ * @return the effective units per texel for new lightmaps
+ */
+ public static double lightmapUnitsPerTexel(final double base) {
+ return base * STAGE3_TEXEL_FACTOR;
+ }
+
/**
* Bounce rays per texel (or polygon) per generation, averaged as a
* plain mean. Total rays per texel over a full bake is roughly this
/** Serializes generation barriers. */
private final Object genLock = new Object();
+ /**
+ * Status snapshot for the developer-tools GI row (also handy in
+ * logs). Distances are in world units, derived from the near-to-far
+ * work queue: the queue drains nearest-first, so
+ * {@link #coveredDistance} grows as the active stage progresses — a
+ * frozen value with work remaining means the bake is stuck.
+ */
+ public static final class Status {
+ /** True after {@link #start()} and before {@link #stop()}. */
+ public boolean running;
+ /** True once the bake converged (workers idle / catch-up watch). */
+ public boolean baked;
+ /** Coarse (stage 3) vs fine (stage 4) phase of the staged pipeline. */
+ public boolean finePhase;
+ /** Raw generation counter (0 = stage 1, 1 = per-texel direct, >=2 = bounces). */
+ public int generation;
+ /** Display stage 1-4 mapped from generation/phase (0 = none yet). */
+ public int stage;
+ /** Triangles in the current snapshot. */
+ public int entries;
+ /** Work items in the active generation's queue. */
+ public int queueLength;
+ /** Items already drained from it (progress within the stage). */
+ public int queueDone;
+ /** Camera distance of the entry the queue cursor sits at; NaN
+ * when distance ordering is disabled. */
+ public double coveredDistance = Double.NaN;
+ /** Entries inside each stage's radius at the last evaluation. */
+ public int stage2eligible, stage3eligible, stage4eligible;
+ /** Late radius entrants waiting for catch-up. */
+ public int catchUpPending;
+ /** Baked lightmaps preserved for stream-out/in restore. */
+ public int cacheSize;
+ /** Stage-1/2 centroid records preserved across snapshot rebuilds. */
+ public int centroidCacheSize;
+ /** Effective (override-aware) stage radii, 0 = unlimited. */
+ public double stage2Radius, stage3Radius, stage4Radius;
+ }
+
+ /**
+ * Reads a consistent-enough status snapshot for display; safe to
+ * call from any thread (UI polls it a few times a second).
+ *
+ * @return the current GI status
+ */
+ public Status getStatus() {
+ final Status status = new Status();
+ status.running = running;
+ status.cacheSize = lightmapCache.size();
+ status.centroidCacheSize = centroidCache.size();
+ status.stage2Radius = stage2Radius();
+ status.stage3Radius = stage3Radius();
+ status.stage4Radius = stage4Radius();
+ final Snapshot snap = snapshot;
+ if (snap == null)
+ return status;
+ status.entries = snap.entries.size();
+ status.baked = snap.baked;
+ status.finePhase = snap.finePhase;
+ status.generation = snap.generation;
+ if (status.baked)
+ status.stage = 0;
+ else if (snap.finePhase)
+ status.stage = 4;
+ else if (snap.generation == 0)
+ status.stage = 1;
+ else if (snap.generation == 2)
+ status.stage = 2;
+ else
+ status.stage = 3;
+ status.queueLength = snap.queue.length;
+ final int cursor = Math.min(snap.cursor.get(), snap.queue.length);
+ status.queueDone = cursor;
+ if (cameraPosition != null && snap.queue.length > 0) {
+ final TriangleBvh.Entry at = snap.queue[
+ cursor < snap.queue.length ? cursor : snap.queue.length - 1];
+ status.coveredDistance = Math.sqrt(at.distance);
+ }
+ status.stage2eligible = snap.eligible2;
+ status.stage3eligible = snap.eligible3;
+ status.stage4eligible = snap.eligible4;
+ status.catchUpPending = snap.catchUpQueue.size();
+ return status;
+ }
+
+ /** Baked-composite cache for radius-created lightmaps (cell stream-out survival). */
+ private final LightmapCache lightmapCache =
+ new LightmapCache(EngineConfig.getGiLightmapCacheEntries());
+ /** Stage-1/2 centroid cache for snapshot-rebuild survival
+ * (bugreport-20261005-220333): single-color values, cheap to keep. */
+ private final GiCentroidCache centroidCache =
+ new GiCentroidCache(EngineConfig.getGiCentroidCacheEntries());
+
+ // --- Catch-up watcher state (baked snapshots, radii active) ---
+ /** Wall time of the last catch-up eligibility evaluation. */
+ private long lastCatchUpEval;
+ /** Camera position at the last catch-up evaluation (NaN = never). */
+ private double lastEvalCamX = Double.NaN, lastEvalCamY, lastEvalCamZ;
+ /** Single-flights the catch-up eligibility scan across idle workers. */
+ private final java.util.concurrent.atomic.AtomicBoolean catchUpScanInFlight =
+ new java.util.concurrent.atomic.AtomicBoolean();
+
private static class Snapshot {
List<TriangleBvh.Entry> entries;
TriangleBvh bvh;
List<LightSource> lights;
IdentityHashMap<LightSource, Integer> lightIndex;
double ambientR, ambientG, ambientB;
- /** All lightmaps in the snapshot (for composite updates). */
- List<Lightmap> lightmaps;
+ /** Sky dome color (bounce rays that escape the scene sample it);
+ * zeroed when sky sampling is off. */
+ double skyR, skyG, skyB;
+ /** True when a non-black sky color is declared for this snapshot. */
+ boolean skyEnabled;
+ /** All lightmaps in the snapshot (for composite updates).
+ * Copy-on-write: the barrier appends radius-created lightmaps
+ * while timed composite updates iterate. */
+ java.util.concurrent.CopyOnWriteArrayList<Lightmap> lightmaps;
/** Work queue of the active generation, sorted near-to-far. */
TriangleBvh.Entry[] queue;
+ /** The full distance-sorted candidate list (every entry);
+ * {@link #queue} is the per-generation eligible subset of it. */
+ TriangleBvh.Entry[] queueAll;
/** Next queue index to sample (workers overshoot into nulls once drained). */
final AtomicInteger cursor = new AtomicInteger();
/** Entries currently being sampled (the barrier waits for zero). */
final AtomicInteger inFlight = new AtomicInteger();
- /** The generation currently being sampled: 1 = direct, k = k-th bounce. */
- volatile int generation = 1;
+ /** True once a per-texel direct pass has completed for this
+ * snapshot (late-created lightmaps must trace their own
+ * direct). */
+ volatile boolean directDone;
+ /** Entries that became radius-eligible after the bake converged;
+ * drained by idle workers (local catch-up). */
+ final java.util.concurrent.ConcurrentLinkedQueue<TriangleBvh.Entry>
+ catchUpQueue = new java.util.concurrent.ConcurrentLinkedQueue<>();
+ /** Entries inside each stage's radius at the last
+ * {@link GlobalIllumination#evalEligibility} (status display). */
+ volatile int eligible2, eligible3, eligible4;
+ /**
+ * The pass currently being sampled: 0 = stage 1 (uniform
+ * centroid direct preview for ALL entries), 1 = per-texel
+ * direct (lightmaps only; never scheduled while stages beyond
+ * 2 are deactivated), k >= 2 = the (k-1)-th bounce.
+ */
+ volatile int generation = 0;
+ /**
+ * Stage 4: false while the COARSE bake runs, true after
+ * {@link Lightmap#refine()} switched the lightmaps to final
+ * resolution and the bake restarted from generation 1. Other
+ * stages: always false.
+ */
+ volatile boolean finePhase;
/** True once the bake has completed; workers idle until the next rebuild. */
volatile boolean baked;
}
float deltaCurR, deltaCurG, deltaCurB;
volatile long visibleBits; // per-light: shadow ray says visible
volatile long knownBits; // per-light: visibility computed at least once
+ /** True once a centroid bounce (stage 2 or catch-up) has run for
+ * this entry; the catch-up watcher uses it to find entries that
+ * became eligible only after the bake. */
+ volatile boolean bounced;
+ /** True once stage 1 has written the direct stamp (centroid
+ * cache harvests only completed values). */
+ volatile boolean directDone;
+ /** True when stage-1/2 values came from the centroid cache at
+ * snapshot build instead of being traced (bugreport-20261005-220333):
+ * stage 1 and the stage-2 centroid bounce skip this entry. */
+ volatile boolean restored;
}
/**
this.cameraPosition = cameraPosition;
}
+ /** Per-instance radius-gating overrides (null = EngineConfig value).
+ * Volatile: set by the UI thread before {@link #start()}, read by
+ * the GI workers. */
+ private volatile Double stage2RadiusOverride;
+ private volatile Double stage3RadiusOverride;
+ private volatile Double stage4RadiusOverride;
+ /** Per-instance mesh-block lightmap density override (null =
+ * EngineConfig giMeshUnitsPerTexel). */
+ private volatile Double meshUnitsPerTexelOverride;
+
+ /**
+ * Overrides the radius-gating config values for THIS GI system only
+ * (EngineConfig giStage2/3/4Radius untouched). Needed when one JVM
+ * hosts scenes of wildly different scales (the demo launcher: an FO4
+ * cell at 1 unit = 1.43 cm vs a 48 000-unit procedural district) —
+ * a global -D/config.yaml value cannot fit both. Pass null to keep
+ * the configured value for a stage.
+ *
+ * <p>Call BEFORE {@link #start()} (or via the ViewPanel
+ * enable-overload that applies it pre-start) so the first
+ * eligibility evaluation already uses the overrides.</p>
+ */
+ public void setRadiusOverrides(final Double stage2, final Double stage3,
+ final Double stage4) {
+ stage2RadiusOverride = stage2;
+ stage3RadiusOverride = stage3;
+ stage4RadiusOverride = stage4;
+ }
+
+ /**
+ * Overrides the mesh-block lightmap texel density for THIS GI system
+ * (EngineConfig giMeshUnitsPerTexel untouched). Call before
+ * {@link #start()}; see {@link #setRadiusOverrides}.
+ */
+ public void setMeshUnitsPerTexelOverride(final Double unitsPerTexel) {
+ meshUnitsPerTexelOverride = unitsPerTexel;
+ }
+
+ /** Effective stage-2 radius: override when set, else EngineConfig. */
+ private double stage2Radius() {
+ final Double o = stage2RadiusOverride;
+ return o != null ? o : EngineConfig.getGiStage2Radius();
+ }
+
+ /** Effective stage-3 radius: override when set, else EngineConfig. */
+ private double stage3Radius() {
+ final Double o = stage3RadiusOverride;
+ return o != null ? o : EngineConfig.getGiStage3Radius();
+ }
+
+ /** Effective stage-4 radius: override when set, else EngineConfig. */
+ private double stage4Radius() {
+ final Double o = stage4RadiusOverride;
+ return o != null ? o : EngineConfig.getGiStage4Radius();
+ }
+
+ /** Effective mesh-block texel density: override, else EngineConfig. */
+ private double meshUnitsPerTexel() {
+ final Double o = meshUnitsPerTexelOverride;
+ return o != null ? o : EngineConfig.getGiMeshUnitsPerTexel();
+ }
+
/** Registers the GI provider and starts the worker threads. */
public void start() {
if (running)
if (snap.baked) {
// Bake complete: idle until a scene/light change
// rebuilds the snapshot and restarts from generation 1.
- Thread.sleep(IDLE_SLEEP_MS);
+ // With radius gating, idle workers first drain the
+ // catch-up queue (entries that became eligible when
+ // the camera moved into them after convergence).
+ final TriangleBvh.Entry late = snap.catchUpQueue.poll();
+ if (late != null) {
+ runCatchUp(snap, late, hit, pos, target);
+ } else {
+ scanCatchUp(snap);
+ Thread.sleep(IDLE_SLEEP_MS);
+ }
continue;
}
// The generation cannot advance while this entry is in flight
// (the barrier waits for zero in-flight entries), so the read is
// stable for the whole pass.
- if (snap.generation == 1)
+ final int generation = snap.generation;
+ if (generation == 0) {
+ stage1Pass(snap, entry, pos); // stage 1 is deliberately global
+ return;
+ }
+ // Radius gating: the queue was already filtered to this
+ // generation's eligible subset at the barrier; this is the
+ // belt-and-braces re-check (masks are stable for the whole
+ // generation, re-evaluated only at barriers). Skipped entries
+ // leave their accumulators at zero and do not count toward the
+ // termination mean.
+ if (!generationIncludes(entry, generation, snap.finePhase))
+ return;
+ if (generation == 1)
directPass(snap, entry, pos);
else
- bouncePass(snap, entry, snap.generation, hit, pos, target);
+ bouncePass(snap, entry, generation, hit, pos, target);
+ }
+
+ /**
+ * Would {@link #processEntry} do real work for this entry in the
+ * given generation? Single source of truth for radius gating: the
+ * barrier filters the work queue with it AND the worker re-checks
+ * with it. Generation 0 (stage 1) is deliberately global.
+ */
+ private static boolean generationIncludes(final TriangleBvh.Entry entry,
+ final int generation,
+ final boolean finePhase) {
+ if (generation == 0)
+ return true;
+ final Lightmap lightmap = entry.lightmap;
+ final boolean perTexel = lightmap != null
+ && (generation >= 3 || finePhase && generation >= 2);
+ if (perTexel || generation == 1)
+ // Per-texel pass: stage-3 bit in the coarse phase,
+ // stage-4 bit in the fine phase.
+ return (entry.eligibleStages & (finePhase ? 4 : 2)) != 0;
+ return (entry.eligibleStages & 1) != 0; // centroid bounce: stage-2 bit
+ }
+
+ /**
+ * The work list for one generation: the full distance-sorted
+ * candidate array filtered down to the entries the generation will
+ * actually process ({@link #generationIncludes}). Beyond-radius
+ * entries were previously queued anyway and skipped one by one at
+ * consume time — a million-entry no-op scan per generation that
+ * also made the dev-panel "queue x/y" read the whole scene instead
+ * of the eligible subset (bugreport-20261005-212907).
+ */
+ private static TriangleBvh.Entry[] eligibleQueue(final Snapshot snap,
+ final int generation,
+ final boolean finePhase) {
+ if (generation == 0)
+ return snap.queueAll; // stage 1 is deliberately global
+ return java.util.Arrays.stream(snap.queueAll)
+ .filter(e -> generationIncludes(e, generation, finePhase))
+ .toArray(TriangleBvh.Entry[]::new);
}
// ------------------------------------------------------------------
- // Generation 1: direct light. Lightmaps trace every texel against
- // every light and cache the visibility bytes; plain polygons and
- // mesh blocks get one centroid evaluation (their final resolution).
+ // Stage 1 (generation 0): uniform centroid direct preview for EVERY
+ // entry — the whole scene shows per-polygon direct light with
+ // shadows before any per-texel work begins. Lightmapped triangles
+ // display it through the per-triangle GI shade stamped on the
+ // triangle (no texel work); plain polygons and mesh blocks record
+ // their final-resolution state exactly as before.
// ------------------------------------------------------------------
- private void directPass(final Snapshot snap, final TriangleBvh.Entry entry,
+ private void stage1Pass(final Snapshot snap, final TriangleBvh.Entry entry,
final double[] pos) {
- final int lightCount = snap.lights.size();
- final int tracked = Math.min(lightCount, MAX_TRACKED_LIGHTS);
+ final GiState cached = states.get(stateKey(entry));
+ if (cached != null && cached.restored)
+ return; // restored at snapshot build; display already written
final Lightmap lightmap = entry.lightmap;
- if (lightmap != null) {
- lightmap.ensureArrays(lightCount);
- for (final int texel : lightmap.validTexels) {
- lightmap.texelWorldPosition(texel, pos);
- final double ox = pos[0] + lightmap.normalX * ORIGIN_EPSILON;
- final double oy = pos[1] + lightmap.normalY * ORIGIN_EPSILON;
- final double oz = pos[2] + lightmap.normalZ * ORIGIN_EPSILON;
- for (int i = 0; i < tracked; i++)
- lightmap.lightVisibility[texel * lightCount + i] =
- shadowTest(snap, ox, oy, oz,
- lightmap.normalX, lightmap.normalY, lightmap.normalZ,
- snap.lights.get(i))
- ? Lightmap.VISIBILITY_VISIBLE : Lightmap.VISIBILITY_OCCLUDED;
- }
- lightmap.generation = 1;
- return;
- }
-
- // Plain polygon / mesh-block triangle: one centroid evaluation.
final double nx = entry.normal[0];
final double ny = entry.normal[1];
final double nz = entry.normal[2];
final double oy = entry.centroidY + ny * ORIGIN_EPSILON;
final double oz = entry.centroidZ + nz * ORIGIN_EPSILON;
- double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
+ final int tracked = Math.min(snap.lights.size(), maxTrackedLights());
final boolean[] visible = new boolean[tracked];
+ double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
for (int i = 0; i < tracked; i++) {
final LightSource light = snap.lights.get(i);
visible[i] = shadowTest(snap, ox, oy, oz, nx, ny, nz, light);
state.deltaPrevR = 0;
state.deltaPrevG = 0;
state.deltaPrevB = 0;
+ state.bounced = false;
+ state.directDone = true;
}
if (entry.block != null)
entry.block.setGiLight(entry.blockTri,
state.directR, state.directG, state.directB);
+ // The uniform stamp is the lightmapped triangle's ONLY
+ // lighting display until the first composite lands (stage 3),
+ // so stamp it from the recorded stage-1 state — the same
+ // centroid direct value, plus the per-lamp visibility bits
+ // that stage-2 bounce rays read at hits on this triangle.
+ if (lightmap != null && !lightmap.everComposited && lightmap.owner != null)
+ lightmap.owner.setGiShade(state.directR, state.directG, state.directB);
+ }
+
+ // ------------------------------------------------------------------
+ // Generation 1: per-texel direct light for lightmaps. Every texel
+ // casts shadow rays against every light and caches the visibility
+ // bytes. Plain polygons and mesh-block triangles were already
+ // evaluated at their (final) centroid resolution in stage 1.
+ // ------------------------------------------------------------------
+
+ private void directPass(final Snapshot snap, final TriangleBvh.Entry entry,
+ final double[] pos) {
+ final int lightCount = snap.lights.size();
+ final int tracked = Math.min(lightCount, maxTrackedLights());
+ final Lightmap lightmap = entry.lightmap;
+
+ if (lightmap == null)
+ return; // centroid-evaluated in stage 1: final resolution
+ if (lightmap.directBaked)
+ // Cache-restored or already traced this phase: finished
+ // lightmaps stay out of the bake. (Guard on directBaked,
+ // not baked: a lightmap that sat outside the stage-3
+ // radius all bake long is baked=true from the terminal
+ // freeArrays yet still needs its direct trace.)
+ return;
+
+ lightmap.ensureArrays(lightCount);
+ for (final int texel : lightmap.validTexels) {
+ lightmap.texelWorldPosition(texel, pos);
+ final double ox = pos[0] + lightmap.normalX * ORIGIN_EPSILON;
+ final double oy = pos[1] + lightmap.normalY * ORIGIN_EPSILON;
+ final double oz = pos[2] + lightmap.normalZ * ORIGIN_EPSILON;
+ for (int i = 0; i < tracked; i++)
+ lightmap.lightVisibility[texel * lightCount + i] =
+ shadowTest(snap, ox, oy, oz,
+ lightmap.normalX, lightmap.normalY, lightmap.normalZ,
+ snap.lights.get(i))
+ ? Lightmap.VISIBILITY_VISIBLE : Lightmap.VISIBILITY_OCCLUDED;
+ }
+ lightmap.generation = 1;
+ lightmap.directBaked = true;
}
// ------------------------------------------------------------------
final int generation, final TriangleBvh.Hit hit,
final double[] pos, final double[] target) {
final Lightmap lightmap = entry.lightmap;
- if (lightmap != null) {
+ // Per-texel bounce: coarse phase from generation 3 on, fine
+ // phase (stage 4) from its generation 2 on — the coarse
+ // phase's generation 2 is a CENTROID bounce for every entry.
+ if (lightmap != null && (generation >= 3
+ || snap.finePhase && generation >= 2)) {
+ if (lightmap.baked)
+ return; // cache-restored: finished lightmaps stay out of the bake
final double nx = lightmap.normalX;
final double ny = lightmap.normalY;
final double nz = lightmap.normalZ;
return;
}
+ // Plain polygons and mesh blocks finish at stage 2 — coarse
+ // generations 3+ and the ENTIRE fine phase are lightmap-only
+ // work. Skipping also freezes their deltaPrev at zero (the
+ // barrier publishes the untouched zero accumulator), so later
+ // bounce generations never re-gather their exhausted stage-2
+ // delta.
+ if (lightmap == null && (generation >= 3 || snap.finePhase))
+ return;
+
+ // Centroid bounce (generation 2 — the pipeline's stage 2 is
+ // per-polygon uniform): every plain polygon, mesh-block
+ // triangle and lightmapped entry.
+ final GiState prior = states.get(stateKey(entry));
+ if (prior != null && prior.restored && prior.bounced)
+ return; // stage-2 value restored at snapshot build; keep deltaCur zero
final double nx = entry.normal[0];
final double ny = entry.normal[1];
final double nz = entry.normal[2];
state.deltaCurR = meanR;
state.deltaCurG = meanG;
state.deltaCurB = meanB;
+ state.bounced = true;
}
}
* hit surface's previous-generation delta, so each generation adds
* exactly one more light bounce.
*
- * @param out receives the radiance contribution {r, g, b}; zeros on a miss
+ * @param out receives the radiance contribution {r, g, b}; the sky
+ * dome color on an escape (miss) when sky sampling is
+ * on, zeros otherwise
*/
private void gatherTarget(final Snapshot snap, final int generation,
final double nx, final double ny, final double nz,
out[1] = 0;
out[2] = 0;
final double[] dir = cosineHemisphere(nx, ny, nz, ThreadLocalRandom.current());
- if (!snap.bvh.nearest(ox, oy, oz, dir[0], dir[1], dir[2], hit))
+ if (!snap.bvh.nearest(ox, oy, oz, dir[0], dir[1], dir[2], hit)) {
+ // Ray escaped the scene: the sky dome emits its displayed
+ // color — the same convention as a white surface irradiated
+ // to that color (radiance = BOUNCE_GAIN x color), tamed by
+ // SKY_SCALE because display-picked sky colors read far
+ // brighter than lamp-lit surfaces.
+ if (snap.skyEnabled) {
+ out[0] = BOUNCE_GAIN * snap.skyR * SKY_SCALE;
+ out[1] = BOUNCE_GAIN * snap.skyG * SKY_SCALE;
+ out[2] = BOUNCE_GAIN * snap.skyB * SKY_SCALE;
+ }
return;
+ }
final double eR, eG, eB;
- if (generation == 2) {
+ // Coarse phase's first per-texel bounce (generation 3) gathers
+ // the stage-2 TOTAL at the hit — direct + stage-2 indirect —
+ // folding bounces 1 and 2 into one coarse generation. The fine
+ // phase runs the plain generation chain (its generation 2
+ // gathers fine direct only); its plain-polygon hits read the
+ // polygon's frozen total once (direct + stage-2 indirect), then
+ // never again. Lightmapped hits in the fine phase never read the
+ // stale stage-2 GiState — the coarse field lives on in their
+ // seeded arrays, and re-adding it would double-count.
+ final boolean gathersStage2Total = !snap.finePhase && generation == 3;
+ final boolean gathersPlainTotal = gathersStage2Total
+ || snap.finePhase && generation == 2
+ && hit.entry.lightmap == null;
+ if (generation == 2 || gathersStage2Total) {
// Direct irradiance at the hit point (clamped to display
// range): light near a lamp can sum far beyond 255, and
// feeding unbounded energy into the bounce loop saturates
// the scene.
- final double[] irr = directIrradiance(snap, hit);
- eR = irr[0];
- eG = irr[1];
- eB = irr[2];
+ final double[] irr = directIrradiance(snap, hit, generation);
+ double r = irr[0], g = irr[1], b = irr[2];
+ if (gathersPlainTotal) {
+ final GiState hitState = states.get(stateKey(hit.entry));
+ if (hitState != null) {
+ r += hitState.indirectR;
+ g += hitState.indirectG;
+ b += hitState.indirectB;
+ }
+ }
+ eR = r;
+ eG = g;
+ eB = b;
} else {
final TriangleBvh.Entry hitEntry = hit.entry;
if (hitEntry.lightmap != null) {
double energy = 0;
long units = 0;
if (finished >= 2) {
+ // Lightmap texel arrays only exist once the per-texel
+ // direct pass has run (generation 1 is scheduled AFTER
+ // the stage-2 centroid bounce). Skip lightmaps whose
+ // arrays were never allocated — rollover() would
+ // dereference null.
+ // Per-texel passes of the finished generation were
+ // gated by this eligibility bit (radius gating).
+ final int bit = snap.finePhase ? 4 : 2;
for (final Lightmap lightmap : snap.lightmaps) {
+ if (lightmap.deltaCurR == null)
+ continue;
energy += lightmap.rollover();
- units += lightmap.validTexels.length;
+ // Radius-skipped lightmaps contribute no units:
+ // their zero deltas must not dilute the
+ // termination mean.
+ if ((lightmap.eligibleStages & bit) != 0)
+ units += lightmap.validTexels.length;
}
- for (final GiState state : states.values()) {
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final GiState state = states.get(stateKey(entry));
+ if (state == null)
+ continue;
synchronized (state) {
energy += Math.max(Math.abs(state.deltaCurR),
Math.max(Math.abs(state.deltaCurG), Math.abs(state.deltaCurB)));
- units++;
+ if (centroidWorked(finished, entry, snap.finePhase)
+ && (entry.eligibleStages & 1) != 0)
+ units++;
state.indirectR += state.deltaCurR;
state.indirectG += state.deltaCurG;
state.indirectB += state.deltaCurB;
state.directG + state.indirectG,
state.directB + state.indirectB);
}
+ // Stage 2 done: raise every lightmapped triangle's
+ // uniform stamp to the stage-2 display (direct +
+ // first-bounce indirect) until its first composite
+ // lands.
+ if (finished == 2)
+ publishStage2Display(snap);
}
+ if (finished == 1)
+ snap.directDone = true;
+ // Refresh the radius-gating masks from the LIVE camera
+ // position: what comes next (refine set, next generation's
+ // skips, new lightmap creation) follows the camera.
+ evalEligibility(snap);
final double meanDelta = units == 0 ? 0 : energy / units;
- if (finished >= MAX_GENERATIONS || (finished >= 2 && meanDelta < DELTA_THRESHOLD)) {
+ if (finished >= generationCap() || (finished >= 2 && meanDelta < DELTA_THRESHOLD)) {
// Final composite with no sampling in flight, then free
// all per-texel state. Holding the composite single-flight
// keeps a concurrent timed updateComposites from racing
while (!compositeUpdateInFlight.compareAndSet(false, true))
Thread.yield();
try {
- for (final Lightmap lightmap : snap.lightmaps) {
- compositeLightmap(snap, lightmap);
- lightmap.freeArrays();
+ if (!snap.finePhase) {
+ // Stage 4: the coarse bake converged — switch
+ // radius-eligible lightmaps to their final
+ // resolution and restart the bake from
+ // generation 1 (direct). refine() upscales the
+ // shown composite, so the display does not
+ // regress at the transition; the solver itself
+ // restarts from zero. Lightmaps beyond the
+ // stage-4 radius finalize at coarse resolution:
+ // the coarse composite is their terminal display
+ // (re-armed for a fine catch-up if the camera
+ // approaches later).
+ for (final Lightmap lightmap : snap.lightmaps) {
+ if ((lightmap.eligibleStages & 4) != 0) {
+ lightmap.refine();
+ } else {
+ compositeLightmap(snap, lightmap);
+ cacheStore(lightmap);
+ lightmap.freeArrays();
+ }
+ }
+ snap.finePhase = true;
+ snap.generation = 1;
+ snap.directDone = false;
+ // Queue BEFORE the cursor reset: workers see the
+ // new cursor only via the AtomicInteger's
+ // volatile write, which publishes the queue
+ // assignment that precedes it.
+ snap.queue = eligibleQueue(snap, 1, true);
+ snap.cursor.set(0);
+ createBlockLightmaps(snap);
+ if (DEBUG)
+ System.out.println("[GI] coarse bake done after generation "
+ + finished + " — refining to final resolution");
+ } else {
+ for (final Lightmap lightmap : snap.lightmaps) {
+ compositeLightmap(snap, lightmap);
+ cacheStore(lightmap);
+ lightmap.freeArrays();
+ }
+ snap.baked = true;
}
- snap.baked = true;
} finally {
compositeUpdateInFlight.set(false);
}
- if (DEBUG)
+ if (DEBUG && snap.baked)
System.out.println("[GI] bake done after generation " + finished
+ ", mean delta " + String.format("%.3f", meanDelta)
+ " — texel arrays freed");
} else {
- snap.generation = finished + 1;
+ final int next = nextGeneration(finished, snap.finePhase);
+ snap.generation = next;
+ // Queue BEFORE the cursor reset (visibility ordering,
+ // see the fine-phase restart above).
+ snap.queue = eligibleQueue(snap, next, snap.finePhase);
snap.cursor.set(0);
+ // Newly radius-eligible block triangles get their
+ // lightmaps now, so the upcoming generations see them.
+ createBlockLightmaps(snap);
if (DEBUG)
- System.out.println("[GI] generation " + finished + " done, mean delta "
+ System.out.println("[GI] " + (finished == 0 ? "stage 1 (uniform direct preview)"
+ : "generation " + finished) + " done, mean delta "
+ String.format("%.3f", meanDelta)
- + " -> generation " + (finished + 1));
+ + " -> generation " + next);
}
}
}
+ /**
+ * Generation at which each phase's bake stops. Applies per phase:
+ * the coarse bake and the fine bake each get the full allowance;
+ * either may stop earlier on the delta threshold.
+ */
+ private static int generationCap() {
+ return MAX_GENERATIONS;
+ }
+
+ /**
+ * The pass to schedule after {@code finished}. The coarse phase
+ * inserts the centroid bounce before the per-texel work: 0 -> 2
+ * -> 1 -> 3 -> 4 -> ... (generation 3 is the first
+ * per-texel bounce). The fine phase runs plain 0 -> 1 -> 2
+ * -> ....
+ */
+ private static int nextGeneration(final int finished, final boolean finePhase) {
+ if (finePhase)
+ return finished + 1;
+ if (finished == 0)
+ return 2; // stage 2: centroid bounce, every entry
+ if (finished == 2)
+ return 1; // per-texel direct (lightmaps)
+ if (finished == 1)
+ return 3; // first per-texel bounce
+ return finished + 1;
+ }
+
+ /**
+ * Stage-2 display hand-off: at the generation-2 barrier every
+ * lightmapped triangle's uniform stamp is raised from its stage-1
+ * direct triplet to direct + first-bounce indirect — the stage-2
+ * display, texture x (ambient + direct + first bounce). Lightmaps
+ * that once showed a real composite keep it.
+ */
+ private void publishStage2Display(final Snapshot snap) {
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final Lightmap lightmap = entry.lightmap;
+ if (lightmap == null || lightmap.owner == null || lightmap.everComposited)
+ continue;
+ final GiState state = states.get(stateKey(entry));
+ if (state == null)
+ continue;
+ lightmap.owner.setGiShade(
+ state.directR + state.indirectR,
+ state.directG + state.indirectG,
+ state.directB + state.indirectB);
+ }
+ }
+
+ // ------------------------------------------------------------------
+ // Radius gating (stage radii from EngineConfig / -De3d.gi.stage*Radius)
+ // ------------------------------------------------------------------
+
+ /**
+ * Whether the finished generation did centroid-bounce work for this
+ * entry (the termination mean must count only such entries). Mirrors
+ * the dispatch conditions in {@link #processEntry}.
+ */
+ private static boolean centroidWorked(final int finished,
+ final TriangleBvh.Entry entry,
+ final boolean finePhase) {
+ if (finePhase)
+ return false; // fine phase is lightmap-only work
+ return finished == 2; // coarse phase: generation 2 for all
+ }
+
+ /**
+ * Re-evaluates every entry's radius-gating mask from the current
+ * camera position. Called at snapshot build and at each generation
+ * barrier (the masks are stable while a generation runs), plus by
+ * the catch-up watcher on camera movement after convergence. Radius
+ * 0 means unlimited for that stage. Without a camera supplier, or
+ * with all radii at 0, every entry stays eligible for everything.
+ */
+ private void evalEligibility(final Snapshot snap) {
+ final double r2 = stage2Radius();
+ final double r3 = stage3Radius();
+ final double r4 = stage4Radius();
+ final Point3D cam = cameraPosition == null ? null : cameraPosition.get();
+ if (cam == null || (r2 <= 0 && r3 <= 0 && r4 <= 0)) {
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ entry.eligibleStages = 7;
+ if (entry.lightmap != null)
+ entry.lightmap.eligibleStages = 7;
+ }
+ snap.eligible2 = snap.entries.size();
+ snap.eligible3 = snap.entries.size();
+ snap.eligible4 = snap.entries.size();
+ return;
+ }
+ final double r2sq = r2 > 0 ? r2 * r2 : Double.POSITIVE_INFINITY;
+ final double r3sq = r3 > 0 ? r3 * r3 : Double.POSITIVE_INFINITY;
+ final double r4sq = r4 > 0 ? r4 * r4 : Double.POSITIVE_INFINITY;
+ int count2 = 0, count3 = 0, count4 = 0;
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final double dx = entry.centroidX - cam.x;
+ final double dy = entry.centroidY - cam.y;
+ final double dz = entry.centroidZ - cam.z;
+ final double distSq = dx * dx + dy * dy + dz * dz;
+ final int mask = (distSq <= r2sq ? 1 : 0)
+ | (distSq <= r3sq ? 2 : 0)
+ | (distSq <= r4sq ? 4 : 0);
+ entry.eligibleStages = mask;
+ if (entry.lightmap != null)
+ entry.lightmap.eligibleStages = mask;
+ if ((mask & 1) != 0) count2++;
+ if ((mask & 2) != 0) count3++;
+ if ((mask & 4) != 0) count4++;
+ }
+ snap.eligible2 = count2;
+ snap.eligible3 = count3;
+ snap.eligible4 = count4;
+ if (DEBUG)
+ System.out.println("[GI] eligibility from " + cam + ": stage2 "
+ + count2 + "/" + snap.entries.size() + ", stage3 " + count3
+ + ", stage4 " + count4);
+ }
+
+ /**
+ * Creates lightmaps for mesh-block triangles inside the active
+ * radius bubble that don't have one yet. In the coarse phase every
+ * stage-3-eligible triangle gets one; in the fine phase only
+ * stage-4-eligible ones (stage-3-only work is over by then).
+ */
+ private void createBlockLightmaps(final Snapshot snap) {
+ if (stage3Radius() <= 0)
+ return;
+ final double[] pos = new double[3];
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ if (entry.block == null)
+ continue;
+ final int mask = entry.eligibleStages;
+ final boolean want = snap.finePhase ? (mask & 4) != 0 : (mask & 2) != 0;
+ if (!want || entry.block.lightmapAt(entry.blockTri) != null)
+ continue;
+ attachBlockLightmap(snap, entry, pos);
+ }
+ }
+
+ /**
+ * Attaches a fresh per-triangle lightmap to a mesh-block triangle
+ * (or re-attaches the existing one to this snapshot's entry) and
+ * either restores its baked composite from the {@link LightmapCache}
+ * or — when the bake's per-texel direct pass has already run —
+ * traces its direct light immediately so it can join the current
+ * generation. Post-bake creations are queued for a catch-up bounce.
+ */
+ private void attachBlockLightmap(final Snapshot snap,
+ final TriangleBvh.Entry entry,
+ final double[] pos) {
+ final TriangleMeshBlock block = entry.block;
+ if (block == null)
+ return;
+ final Lightmap existing = block.lightmapAt(entry.blockTri);
+ if (existing != null) {
+ entry.lightmap = existing;
+ return;
+ }
+ final double[] w9 = new double[9];
+ block.triangleWorld(entry.blockTri, w9);
+ // Cutout foliage & co: alpha textures keep per-triangle shading.
+ // A lightmap composite is opaque — resampling the texture's
+ // transparent-black regions into it would render the card as a
+ // solid dark slab.
+ final Texture baseTexture = block.texture(entry.blockTri);
+ if (baseTexture == null || baseTexture.hasAlpha)
+ return;
+ final double baseUpt = meshUnitsPerTexel();
+ // Mirror LightmappedTriangle: coarse resolution while the
+ // pipeline starts coarse. Post-bake, a late entrant matches its
+ // ring: stage-4-eligible joins at the final density, a
+ // stage-3-only entrant gets the coarse stage-3 density (the
+ // needsRefine catch-up upgrades it if the camera approaches).
+ final boolean coarseNow = !snap.finePhase && !snap.baked
+ || snap.baked && (entry.eligibleStages & 4) == 0;
+ final double upt = coarseNow ? lightmapUnitsPerTexel(baseUpt) : baseUpt;
+ final Lightmap lightmap = new Lightmap(
+ new Point3D(w9[0], w9[1], w9[2]),
+ new Point3D(w9[3], w9[4], w9[5]),
+ new Point3D(w9[6], w9[7], w9[8]),
+ block.albedo(entry.blockTri), upt,
+ entry.normal[0], entry.normal[1], entry.normal[2]);
+ lightmap.fineUnitsPerTexel = baseUpt;
+ final double[] uv6 = new double[6];
+ block.triangleUv(entry.blockTri, uv6);
+ lightmap.setBaseTextureMapping(baseTexture, uv6);
+ if (block.attachLightmapIfAbsent(entry.blockTri, lightmap) != lightmap) {
+ // Lost a creation race: adopt the winner (same geometry).
+ entry.lightmap = block.lightmapAt(entry.blockTri);
+ return;
+ }
+ entry.lightmap = lightmap;
+ snap.lightmaps.add(lightmap);
+
+ final long key = lightmapKey(lightmap);
+ final LightmapCache.Entry cached = lightmapCache.get(key);
+ if (cached != null && cached.lightSignature == lastLightSignature) {
+ // The cache may hold the FINE composite while a rebuild
+ // re-creates the lightmap at coarse dims: switch resolution
+ // first, then restore.
+ if (cached.width != lightmap.width || cached.height != lightmap.height)
+ lightmap.refine();
+ if (cached.width == lightmap.width && cached.height == lightmap.height) {
+ lightmap.restoreComposite(cached.pixels);
+ if (DEBUG)
+ System.out.println("[GI] lightmap cache hit (" + lightmap.width
+ + "x" + lightmap.height + ") — restored without bake");
+ return;
+ }
+ }
+ if (snap.directDone || snap.baked) {
+ // The global per-texel direct pass already ran: this lightmap
+ // must trace its own direct light before any bounce work.
+ directPass(snap, entry, pos);
+ if (snap.baked)
+ snap.catchUpQueue.add(entry);
+ }
+ }
+
+ /**
+ * Geometry signature for the lightmap cache: origin and edge vectors
+ * (the same 9 doubles the constructor derives from the triangle
+ * vertices, so the key is bit-stable across block rebuilds).
+ */
+ private static long lightmapKey(final Lightmap lightmap) {
+ return LightmapCache.key(new double[]{
+ lightmap.originX, lightmap.originY, lightmap.originZ,
+ lightmap.edge1X, lightmap.edge1Y, lightmap.edge1Z,
+ lightmap.edge2X, lightmap.edge2Y, lightmap.edge2Z});
+ }
+
+ /**
+ * Stores a finished mesh-block lightmap's composite in the cache.
+ * Only the shown composite pixels survive; bake state is transient.
+ */
+ private void cacheStore(final Lightmap lightmap) {
+ if (lightmap.owner != null)
+ return; // cache scope is mesh-block lightmaps
+ if (!lightmap.everComposited)
+ return;
+ if (!lightmap.directBaked)
+ // Shade-only composite (the lightmap sat outside the stage-3
+ // radius for the whole bake): not a GI solution — caching it
+ // would resurrect the unlit fill as "final" on rebuilds.
+ return;
+ final int[] pixels = lightmap.shownTexture().primaryBitmap.pixels;
+ lightmapCache.put(lightmapKey(lightmap), lightmap.width, lightmap.height,
+ java.util.Arrays.copyOf(pixels, pixels.length),
+ lastLightSignature);
+ }
+
+ // ------------------------------------------------------------------
+ // Catch-up: late radius entrants after the bake converged
+ // ------------------------------------------------------------------
+
+ /**
+ * Idle-time scan on a baked snapshot (throttled to the idle cadence):
+ * when the camera moved more than a quarter of the smallest active
+ * radius since the last evaluation, re-evaluate eligibility and queue
+ * every entry that newly entered its bubble. Stage-2 entrants get a
+ * single local bounce against the frozen converged field; new
+ * stage-3 block triangles get a lightmap (cache-restored when known);
+ * coarse-baked lightmaps entering the stage-4 radius refine and
+ * re-bake at fine resolution.
+ */
+ private void scanCatchUp(final Snapshot snap) {
+ if (cameraPosition == null)
+ return;
+ final double r2 = stage2Radius();
+ final double r3 = stage3Radius();
+ final double r4 = stage4Radius();
+ if (r2 <= 0 && r3 <= 0 && r4 <= 0)
+ return;
+ final long now = System.currentTimeMillis();
+ if (now - lastCatchUpEval < IDLE_SLEEP_MS)
+ return;
+ final Point3D cam = cameraPosition.get();
+ if (cam == null)
+ return;
+ if (!Double.isNaN(lastEvalCamX)) {
+ double smallest = Double.POSITIVE_INFINITY;
+ if (r2 > 0) smallest = Math.min(smallest, r2);
+ if (r3 > 0) smallest = Math.min(smallest, r3);
+ if (r4 > 0) smallest = Math.min(smallest, r4);
+ final double threshold = Math.max(1.0, smallest / 4);
+ final double dx = cam.x - lastEvalCamX;
+ final double dy = cam.y - lastEvalCamY;
+ final double dz = cam.z - lastEvalCamZ;
+ if (dx * dx + dy * dy + dz * dz <= threshold * threshold) {
+ lastCatchUpEval = now;
+ return;
+ }
+ }
+ if (!catchUpScanInFlight.compareAndSet(false, true))
+ return;
+ try {
+ if (snap != snapshot || !snap.baked)
+ return;
+ lastCatchUpEval = now;
+ lastEvalCamX = cam.x;
+ lastEvalCamY = cam.y;
+ lastEvalCamZ = cam.z;
+ evalEligibility(snap);
+ final double[] pos = new double[3];
+ int queued = 0;
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final int mask = entry.eligibleStages;
+ final Lightmap lightmap = entry.lightmap;
+ if (entry.block != null && lightmap == null && (mask & 2) != 0) {
+ attachBlockLightmap(snap, entry, pos);
+ // Fresh (cache-missed) lightmaps queue themselves for
+ // the bounce catch-up inside attachBlockLightmap.
+ if (entry.lightmap != null && !entry.lightmap.baked)
+ queued++;
+ } else if (lightmap != null && lightmap.baked
+ && (mask & 4) != 0 && lightmap.needsRefine()) {
+ snap.catchUpQueue.add(entry);
+ queued++;
+ } else if (lightmap != null && !lightmap.directBaked
+ && (mask & 2) != 0) {
+ // Has a lightmap that sat outside the stage-3 radius
+ // for the whole bake (standalone lightmapped
+ // triangles, or block lightmaps created but never
+ // reached): it still shows only the stage-1 shade.
+ // Queue it for direct + one bounce.
+ snap.catchUpQueue.add(entry);
+ queued++;
+ } else if (lightmap == null && (mask & 1) != 0) {
+ final GiState state = states.get(stateKey(entry));
+ if (state == null || !state.bounced) {
+ snap.catchUpQueue.add(entry);
+ queued++;
+ }
+ }
+ }
+ if (DEBUG && queued > 0)
+ System.out.println("[GI] catch-up: " + queued
+ + " entries entered the radius bubble");
+ } finally {
+ catchUpScanInFlight.set(false);
+ }
+ }
+
+ /**
+ * Runs the local catch-up for one late-entrant entry, reading only
+ * the frozen converged field (never restarting global generations —
+ * re-running a generation would double-count its energy in entries
+ * that already received it).
+ */
+ private void runCatchUp(final Snapshot snap, final TriangleBvh.Entry entry,
+ final TriangleBvh.Hit hit, final double[] pos,
+ final double[] target) {
+ if (snap != snapshot)
+ return; // snapshot replaced while queued
+ final Lightmap lightmap = entry.lightmap;
+ if (lightmap != null) {
+ if (lightmap.baked && lightmap.needsRefine()
+ && (entry.eligibleStages & 4) != 0) {
+ // Approached a coarse-baked lightmap: switch to the
+ // final texel density and re-bake at it.
+ lightmap.refine();
+ directPass(snap, entry, pos);
+ } else if (!lightmap.directBaked
+ && (entry.eligibleStages & 2) != 0) {
+ // Outside the stage-3 radius for the whole bake: the
+ // lightmap shows only the stage-1 shade. Trace its
+ // per-texel direct now; the bounce against the
+ // converged field follows below.
+ directPass(snap, entry, pos);
+ }
+ if (!lightmap.baked && lightmap.generation >= 1) {
+ // One bounce against the converged field, then finalize.
+ catchUpBounce(snap, entry, lightmap, hit, pos, target);
+ lightmap.rollover();
+ while (!compositeUpdateInFlight.compareAndSet(false, true))
+ Thread.yield();
+ try {
+ compositeLightmap(snap, lightmap);
+ } finally {
+ compositeUpdateInFlight.set(false);
+ }
+ lightmap.freeArrays();
+ cacheStore(lightmap);
+ }
+ return;
+ }
+ // Centroid catch-up for plain polygons and mesh-block triangles.
+ if ((entry.eligibleStages & 1) == 0)
+ return;
+ final GiState state = states.get(stateKey(entry));
+ if (state == null || state.bounced)
+ return;
+ final double nx = entry.normal[0];
+ final double ny = entry.normal[1];
+ final double nz = entry.normal[2];
+ final double ox = entry.centroidX + nx * ORIGIN_EPSILON;
+ final double oy = entry.centroidY + ny * ORIGIN_EPSILON;
+ final double oz = entry.centroidZ + nz * ORIGIN_EPSILON;
+ float meanR = 0, meanG = 0, meanB = 0;
+ for (int s = 1; s <= SAMPLES_PER_GENERATION; s++) {
+ gatherTotal(snap, nx, ny, nz, ox, oy, oz, hit, target);
+ meanR += (target[0] - meanR) / s;
+ meanG += (target[1] - meanG) / s;
+ meanB += (target[2] - meanB) / s;
+ }
+ synchronized (state) {
+ state.indirectR += meanR;
+ state.indirectG += meanG;
+ state.indirectB += meanB;
+ state.bounced = true;
+ }
+ if (entry.block != null)
+ entry.block.setGiLight(entry.blockTri,
+ state.directR + state.indirectR,
+ state.directG + state.indirectG,
+ state.directB + state.indirectB);
+ }
+
+ /**
+ * Per-texel catch-up bounce for a late lightmap: every texel
+ * averages one sample generation against the converged total field
+ * (direct + indirect at the hit). A single generation: the sampled
+ * field is frozen, so further iterations would re-read it unchanged.
+ */
+ private void catchUpBounce(final Snapshot snap, final TriangleBvh.Entry entry,
+ final Lightmap lightmap, final TriangleBvh.Hit hit,
+ final double[] pos, final double[] target) {
+ final double nx = lightmap.normalX;
+ final double ny = lightmap.normalY;
+ final double nz = lightmap.normalZ;
+ for (final int texel : lightmap.validTexels) {
+ lightmap.texelWorldPosition(texel, pos);
+ final double ox = pos[0] + nx * ORIGIN_EPSILON;
+ final double oy = pos[1] + ny * ORIGIN_EPSILON;
+ final double oz = pos[2] + nz * ORIGIN_EPSILON;
+ float meanR = 0, meanG = 0, meanB = 0;
+ for (int s = 1; s <= SAMPLES_PER_GENERATION; s++) {
+ gatherTotal(snap, nx, ny, nz, ox, oy, oz, hit, target);
+ meanR += (target[0] - meanR) / s;
+ meanG += (target[1] - meanG) / s;
+ meanB += (target[2] - meanB) / s;
+ }
+ lightmap.deltaCurR[texel] = meanR;
+ lightmap.deltaCurG[texel] = meanG;
+ lightmap.deltaCurB[texel] = meanB;
+ }
+ }
+
+ /**
+ * One cosine-weighted bounce ray from the given surface point,
+ * gathering the hit surface's converged TOTAL (direct + indirect).
+ * The catch-up variant of {@link #gatherTarget}: baked lightmaps are
+ * read through their composite texture (irradiance estimated as
+ * composite x 255 / base color), plain entries through their
+ * recorded direct + indirect totals.
+ *
+ * @param out receives the radiance contribution {r, g, b}; the sky
+ * dome color on an escape (miss) when sky sampling is
+ * on, zeros otherwise
+ */
+ private void gatherTotal(final Snapshot snap,
+ final double nx, final double ny, final double nz,
+ final double ox, final double oy, final double oz,
+ final TriangleBvh.Hit hit, final double[] out) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ final double[] dir = cosineHemisphere(nx, ny, nz, ThreadLocalRandom.current());
+ if (!snap.bvh.nearest(ox, oy, oz, dir[0], dir[1], dir[2], hit)) {
+ if (snap.skyEnabled) {
+ out[0] = BOUNCE_GAIN * snap.skyR * SKY_SCALE;
+ out[1] = BOUNCE_GAIN * snap.skyG * SKY_SCALE;
+ out[2] = BOUNCE_GAIN * snap.skyB * SKY_SCALE;
+ }
+ return;
+ }
+
+ final TriangleBvh.Entry hitEntry = hit.entry;
+ final Lightmap hitLightmap = hitEntry.lightmap;
+ double eR = snap.ambientR, eG = snap.ambientG, eB = snap.ambientB;
+ if (hitLightmap != null && hitLightmap.everComposited) {
+ // Sample the shown composite at ITS OWN dimensions. The GI
+ // catch-up runs this on one worker while another worker's
+ // runCatchUp refine()s this very lightmap: width/height and
+ // the composite buffers are swapped non-atomically, and
+ // indexing by lightmap dims tore against the buffer swap
+ // (ArrayIndexOutOfBounds, bugreport-20261005-153054). The
+ // parametric (u, v) is resolution-independent, and the
+ // captured Texture reference is immutable — always in
+ // bounds, possibly at the pre-refine resolution, which
+ // carries the same irradiance content.
+ final TextureBitmap shown = hitLightmap.shownTexture().primaryBitmap;
+ final double[] uv = new double[2];
+ hitLightmap.uvAt(hit.pointX, hit.pointY, hit.pointZ, uv);
+ int i = (int) (uv[0] * shown.width);
+ int j = (int) (uv[1] * shown.height);
+ if (i < 0) i = 0;
+ if (i >= shown.width) i = shown.width - 1;
+ if (j < 0) j = 0;
+ if (j >= shown.height) j = shown.height - 1;
+ final int px = shown.pixels[j * shown.width + i];
+ final int base = hitLightmap.baseColorAtUv(uv[0], uv[1]);
+ eR = irradianceFromComposite((px >> 16) & 255, (base >> 16) & 255, eR);
+ eG = irradianceFromComposite((px >> 8) & 255, (base >> 8) & 255, eG);
+ eB = irradianceFromComposite(px & 255, base & 255, eB);
+ } else {
+ final GiState state = states.get(stateKey(hitEntry));
+ if (state != null) {
+ eR = state.directR + state.indirectR;
+ eG = state.directG + state.indirectG;
+ eB = state.directB + state.indirectB;
+ }
+ }
+
+ final Color hitColor = colorOf(hitEntry);
+ out[0] = BOUNCE_GAIN * hitColor.r * Math.min(255, eR) / 255.0;
+ out[1] = BOUNCE_GAIN * hitColor.g * Math.min(255, eG) / 255.0;
+ out[2] = BOUNCE_GAIN * hitColor.b * Math.min(255, eB) / 255.0;
+ }
+
+ /**
+ * Irradiance estimate from a composite texel: the composite is
+ * base x irradiance / 255, so irradiance ~= pixel x 255 / base.
+ * Near-black bases carry no reliable signal; fall back to the
+ * ambient level there (the albedo multiply at the gatherer kills
+ * the contribution anyway).
+ */
+ private static double irradianceFromComposite(final int pixelChannel,
+ final int baseChannel,
+ final double fallback) {
+ if (baseChannel < 8)
+ return fallback;
+ return Math.min(255, pixelChannel * 255.0 / baseChannel);
+ }
+
// ------------------------------------------------------------------
// Ray primitives
// ------------------------------------------------------------------
/**
* Direct irradiance at a ray hit point, same scale as LightingManager,
* clamped to display range. Uses the hit surface's CACHED visibility
- * (no new shadow rays).
+ * (no new shadow rays): per-texel bytes once the per-texel direct
+ * pass has run at that surface (coarse phase from generation 3 on,
+ * fine phase from its generation 2 on), the stage-1 per-polygon
+ * bits before that.
*/
- private double[] directIrradiance(final Snapshot snap, final TriangleBvh.Hit hit) {
+ private double[] directIrradiance(final Snapshot snap, final TriangleBvh.Hit hit,
+ final int generation) {
final TriangleBvh.Entry entry = hit.entry;
final Lightmap lightmap = entry.lightmap;
double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
final int lightCount = snap.lights.size();
- final int hitTexel = lightmap != null
+ // Per-texel visibility bytes only exist once the per-texel
+ // direct pass has run at the hit surface's current resolution:
+ // coarse phase from generation 3 on, fine phase from its
+ // generation 2 on. Earlier generations (stage 2's centroid
+ // bounce) read the stage-1 per-polygon bits at ALL hits.
+ final boolean perTexel = lightmap != null
+ && (generation >= 3 || snap.finePhase && generation >= 2);
+ final int hitTexel = perTexel
? lightmap.texelAt(hit.pointX, hit.pointY, hit.pointZ) : -1;
- final GiState hitState = lightmap == null ? states.get(stateKey(entry)) : null;
+ final GiState hitState = perTexel ? null : states.get(stateKey(entry));
- for (int i = 0; i < lightCount && i < MAX_TRACKED_LIGHTS; i++) {
+ for (int i = 0; i < lightCount && i < maxTrackedLights(); i++) {
final LightSource light = snap.lights.get(i);
- if (lightmap != null) {
+ if (perTexel) {
if (lightmap.lightVisibility != null
&& lightmap.lightVisibility[hitTexel * lightCount + i] == Lightmap.VISIBILITY_OCCLUDED)
continue;
for (final int texel : lightmap.validTexels) {
lightmap.texelWorldPosition(texel, pos);
double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
- for (int i = 0; i < lightCount && i < MAX_TRACKED_LIGHTS; i++) {
+ for (int i = 0; i < lightCount && i < maxTrackedLights(); i++) {
if (lightmap.lightVisibility[texel * lightCount + i] == Lightmap.VISIBILITY_OCCLUDED)
continue;
final LightSource light = snap.lights.get(i);
for (int j = 0; j < height; j++)
for (int i = 0; i < width; i++) {
final int t = j * width + i;
- pixels[t] = compositePixel(lightmap, irrR[t], irrG[t], irrB[t]);
+ pixels[t] = compositePixel(lightmap, t, irrR[t], irrG[t], irrB[t]);
}
back.resetResampledBitmapCache();
if (lightmap.owner != null) {
lightmap.owner.setTexture(back);
- lightmap.swapBuffers();
+ // The composite now carries real traced lighting; the
+ // stage-1 uniform preview multiply must go away.
+ lightmap.owner.clearGiShade();
}
+ // Mesh-block lightmaps have no owner: the paint path reads
+ // shownTexture() per frame, so the swap must happen here for
+ // every lightmap kind, not just owned ones.
+ lightmap.swapBuffers();
+ lightmap.everComposited = true;
// Debug: -De3d.gi.dumpLightmaps=/tmp/lm dumps composites as PNGs.
if (DUMP_DIR != null)
}
private static boolean isValid(final Lightmap lightmap, final int texel) {
- final double u = ((texel % lightmap.width) + 0.5) / lightmap.width;
- final double v = ((texel / lightmap.width) + 0.5) / lightmap.height;
- return u + v <= 1.0;
+ return lightmap.isValidTexel(texel % lightmap.width, texel / lightmap.width);
}
- /** Composite texel: baseColor scaled by total irradiance, clamped. */
- private static int compositePixel(final Lightmap lightmap,
+ /** Composite texel: per-texel base color scaled by total irradiance, clamped. */
+ private static int compositePixel(final Lightmap lightmap, final int texel,
final double irrR, final double irrG, final double irrB) {
- final int r = Math.min(255, (int) (irrR * lightmap.baseColor.r / 255));
- final int g = Math.min(255, (int) (irrG * lightmap.baseColor.g / 255));
- final int b = Math.min(255, (int) (irrB * lightmap.baseColor.b / 255));
+ final int base = lightmap.baseColorAt(texel);
+ final int r = Math.min(255, (int) (irrR * ((base >> 16) & 255) / 255));
+ final int g = Math.min(255, (int) (irrG * ((base >> 8) & 255) / 255));
+ final int b = Math.min(255, (int) (irrB * (base & 255) / 255));
return 0xFF000000 | (r << 16) | (g << 8) | b;
}
private void rebuildSnapshot(final int version,
final double lightSignature,
final long now) {
+ // Captured up front: harvestCentroids tags the OLD snapshot's
+ // values with the signature they were baked under, and the
+ // field moves to the new signature during this build.
+ final Snapshot old = snapshot;
+ final double oldSignature = lastLightSignature;
if (DEBUG)
System.out.println("[GI] rebuild trigger: renderListVersion "
+ lastSeenRenderListVersion + " -> " + version
final Snapshot snap = new Snapshot();
snap.entries = new ArrayList<>(triangles.size());
- snap.lightmaps = new ArrayList<>();
+ snap.lightmaps = new java.util.concurrent.CopyOnWriteArrayList<>();
for (final AbstractCoordinateShape triangle : triangles) {
if (triangle.vertices.size() < 3)
continue;
for (final eu.svjatoslav.aukio.e3d.renderer.raster.shapes
.basic.texturedpolygon.TriangleMeshBlock block : meshBlocks) {
block.ensureGiLight();
- for (int t = 0; t < block.triCount(); t++)
- snap.entries.add(buildBlockEntry(block, t));
+ for (int t = 0; t < block.triCount(); t++) {
+ final TriangleBvh.Entry entry = buildBlockEntry(block, t);
+ snap.entries.add(entry);
+ if (entry.lightmap != null)
+ snap.lightmaps.add(entry.lightmap);
+ }
}
if (!snap.entries.isEmpty())
snap.bvh = new TriangleBvh(snap.entries);
snap.ambientR = ambient.r;
snap.ambientG = ambient.g;
snap.ambientB = ambient.b;
+ final Color sky = skyColor();
+ snap.skyEnabled = sky != null && (sky.r | sky.g | sky.b) != 0;
+ if (snap.skyEnabled) {
+ snap.skyR = sky.r;
+ snap.skyG = sky.g;
+ snap.skyB = sky.b;
+ }
// Near-to-far bake order from the camera position at build time.
final Point3D cam = cameraPosition == null ? null : cameraPosition.get();
final double dz = entry.centroidZ - cam.z;
entry.distance = (float) (dx * dx + dy * dy + dz * dz);
}
- snap.queue = snap.entries.stream()
+ snap.queueAll = snap.entries.stream()
.sorted(Comparator.comparingDouble(e -> e.distance))
.toArray(TriangleBvh.Entry[]::new);
+ snap.queue = snap.queueAll; // generation 0 is deliberately global
} else {
- snap.queue = snap.entries.toArray(new TriangleBvh.Entry[0]);
+ snap.queueAll = snap.entries.toArray(new TriangleBvh.Entry[0]);
+ snap.queue = snap.queueAll;
}
- snapshot = snap;
+ // Radius gating: masks from the build-time camera position, then
+ // lightmaps for block triangles already inside the bubble (they
+ // join the bake from generation 0; the per-texel direct pass
+ // reaches them in generation 1). The light signature must be
+ // current before creation: cache restores compare against it.
+ evalEligibility(snap);
+ lastLightSignature = lightSignature;
+ createBlockLightmaps(snap);
+
+ // Harvest stage-1/2 centroid values of the OLD snapshot under
+ // the OLD signature (both captured at method entry), then
+ // restore what the new snapshot recognizes: streamed cells
+ // re-enter with identical geometry, so their direct light and
+ // first bounce come back for free (bugreport-20261005-220333).
+ // The state map is rebuilt BEFORE the snapshot is published,
+ // so workers never race the swap.
+ harvestCentroids(old, oldSignature);
states.clear();
+ restoreCentroids(snap);
+ snapshot = snap;
lastSeenRenderListVersion = version;
- lastLightSignature = lightSignature;
lastRebuildTime = now;
if (DEBUG)
+ snap.lights.size() + " lights, generation bake");
}
+ /**
+ * Saves the old snapshot's completed centroid values (stage-1
+ * direct; stage-2 bounce when it ran) into {@link #centroidCache}
+ * before the rebuild drops the state map.
+ *
+ * @param old the snapshot being replaced, null on the first build
+ * @param oldSignature the light signature the old values were baked under
+ */
+ private void harvestCentroids(final Snapshot old, final double oldSignature) {
+ if (old == null)
+ return;
+ for (final TriangleBvh.Entry entry : old.entries) {
+ final GiState s = states.get(stateKey(entry));
+ if (s == null || !s.directDone)
+ continue;
+ final GiCentroidCache.Entry c = new GiCentroidCache.Entry();
+ c.directR = s.directR;
+ c.directG = s.directG;
+ c.directB = s.directB;
+ c.indirectR = s.indirectR;
+ c.indirectG = s.indirectG;
+ c.indirectB = s.indirectB;
+ c.deltaPrevR = s.deltaPrevR;
+ c.deltaPrevG = s.deltaPrevG;
+ c.deltaPrevB = s.deltaPrevB;
+ c.visibleBits = s.visibleBits;
+ c.knownBits = s.knownBits;
+ c.bounced = s.bounced;
+ c.lightSignature = oldSignature;
+ centroidCache.put(LightmapCache.key(entry.v), c);
+ }
+ }
+
+ /**
+ * Pre-populates {@link #states} with cached stage-1/2 centroid
+ * values for entries whose geometry is known from a previous
+ * snapshot (cell stream-out/in with an unchanged light field) and
+ * applies their display write-backs immediately, so streamed-in
+ * blocks never show an unlit frame. Runs before the snapshot is
+ * published; workers see the restored states from the start and
+ * skip the corresponding passes.
+ */
+ private void restoreCentroids(final Snapshot snap) {
+ int restored = 0;
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final GiCentroidCache.Entry c =
+ centroidCache.get(LightmapCache.key(entry.v));
+ if (c == null || c.lightSignature != lastLightSignature)
+ continue;
+ final GiState s = new GiState();
+ s.directR = c.directR;
+ s.directG = c.directG;
+ s.directB = c.directB;
+ s.indirectR = c.indirectR;
+ s.indirectG = c.indirectG;
+ s.indirectB = c.indirectB;
+ s.deltaPrevR = c.deltaPrevR;
+ s.deltaPrevG = c.deltaPrevG;
+ s.deltaPrevB = c.deltaPrevB;
+ s.visibleBits = c.visibleBits;
+ s.knownBits = c.knownBits;
+ s.directDone = true;
+ s.bounced = c.bounced;
+ s.restored = true;
+ states.put(stateKey(entry), s);
+ // Display write-back (stage 1 is skipped for this entry):
+ // the stage-2 display formula is direct + first bounce.
+ final float dr = c.bounced ? s.directR + s.indirectR : s.directR;
+ final float dg = c.bounced ? s.directG + s.indirectG : s.directG;
+ final float db = c.bounced ? s.directB + s.indirectB : s.directB;
+ if (entry.block != null)
+ entry.block.setGiLight(entry.blockTri, dr, dg, db);
+ final Lightmap lightmap = entry.lightmap;
+ if (lightmap != null && lightmap.owner != null
+ && !lightmap.everComposited)
+ lightmap.owner.setGiShade(dr, dg, db);
+ restored++;
+ }
+ if (DEBUG && restored > 0)
+ System.out.println("[GI] centroid cache: restored " + restored
+ + "/" + snap.entries.size() + " stage-1/2 values");
+ }
+
private double lightSignature() {
double signature = 0;
for (final LightSource light : lightingManager.getLights()) {
final Color c = light.getColor();
signature += p.x + p.y + p.z + c.r + c.g + c.b + light.getIntensity() * 31.0;
}
+ // Sky color feeds the bounce field, so a sky change rebakes.
+ // Black sky contributes nothing either way — keep the signature
+ // identical for unset and black.
+ final Color sky = skyColor();
+ if (sky != null && (sky.r | sky.g | sky.b) != 0)
+ signature += sky.r * 3.0 + sky.g * 5.0 + sky.b * 7.0 + 1.0;
return signature;
}
+ /**
+ * Sky dome color for bounce rays that escape the scene:
+ * {@code -De3d.gi.sky=RRGGBB} wins, else the scene's
+ * {@link LightingManager#getSkyColor()}. May be null (no sky
+ * sampling — the historical behavior).
+ *
+ * @return the sky color or null
+ */
+ private Color skyColor() {
+ final String prop = System.getProperty("e3d.gi.sky");
+ if (prop != null)
+ return Color.hex(prop);
+ return lightingManager.getSkyColor();
+ }
+
private TriangleBvh.Entry buildEntry(final AbstractCoordinateShape triangle) {
final TriangleBvh.Entry entry = new TriangleBvh.Entry(triangle);
if (triangle instanceof LightmappedShape)
entry.v[0], entry.v[1], entry.v[2],
entry.v[3], entry.v[4], entry.v[5],
entry.v[6], entry.v[7], entry.v[8]);
+ // Re-attach a lightmap that survives on the block from an
+ // earlier snapshot (snapshot rebuilds recreate all entries).
+ entry.lightmap = block.lightmapAt(tri);
return entry;
}
import eu.svjatoslav.aukio.e3d.geometry.Point3D;
import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
import eu.svjatoslav.aukio.e3d.renderer.raster.texture.Texture;
+import eu.svjatoslav.aukio.e3d.renderer.raster.texture.TextureBitmap;
/**
* Per-triangle lightmap: a small generated texture whose texels map onto the
- * triangle surface. The triangle's UVs (in texture pixel units) are
- * (0,0), (width,0), (0,height), so the valid texel region is the half
- * where u+v <= 1 in normalized coordinates; the other half is filled
- * by mirroring to keep mipmaps and edge sampling clean.
+ * triangle surface. The grid is an ORTHOGONAL frame on the triangle's
+ * plane, not the triangle's own edge frame (that sheared texels into
+ * diamonds on acute triangles — bugreport-20261005-192002): the longest
+ * edge is the u-axis, the v-axis is the in-plane perpendicular, and the
+ * texture covers the triangle's bounding rectangle in that frame. The
+ * triangle's UVs (texture pixel units) are (0,0), (width,0),
+ * (apexU*width, height); texels outside the triangle are filled from
+ * valid neighbors to keep mipmaps and edge sampling clean. Texels are
+ * square in world space on every triangle, and the bounding rect is
+ * exactly 2x the triangle's area — the same overhead class as the old
+ * half-empty edge-frame texture.
*
* <p>What you trace is what you see: the composite texture the painter
* samples IS the lightmap, at native texel resolution. Shadow-edge
/** Visibility value: shadow ray was blocked. */
public static final byte VISIBILITY_OCCLUDED = 2;
- /** Texture size limits, power of two. */
+ /** Texel-count limits per axis. */
private static final int MIN_SIZE = 4;
private static final int MAX_SIZE = 128;
/**
- * Uniform irradiance the composite texture starts at (light units,
- * display scale 0..255): the world begins medium-lit and visible,
- * then each lightmap flips to its traced direct light when the bake
- * reaches it. {@code -De3d.gi.initialIrradiance}.
+ * Irradiance the composite texture starts at (light units, display
+ * scale 0..255): the default 255 shows every lightmapped triangle in
+ * its true base color from frame one ("unlit, as-is"), then each
+ * lightmap flips to its traced lighting when the bake reaches it.
+ * Lower values make un-baked surfaces visibly dimmer placeholders.
+ * {@code -De3d.gi.initialIrradiance}.
*/
public static final double INITIAL_IRRADIANCE =
- Double.parseDouble(System.getProperty("e3d.gi.initialIrradiance", "128"));
+ Double.parseDouble(System.getProperty("e3d.gi.initialIrradiance", "255"));
- public final int width;
- public final int height;
+ public int width;
+ public int height;
/** Unlit surface color of the triangle. */
public final Color baseColor;
/** Unit surface normal. */
public final double normalX, normalY, normalZ;
- /** Valid (u+v <= 1) texel indices, for generation sampling. */
- public final int[] validTexels;
+ /** Valid (inside-the-triangle) texel indices, for generation sampling. */
+ public int[] validTexels;
+
+ /**
+ * Frame-space (u, v) of each CONSTRUCTOR vertex (a, b, c order),
+ * 0..1: one is (0,0), one is (1,0), one is ({@link #apexU}, 1).
+ * Painters pin per-vertex UVs to (cornerU[k]*width,
+ * cornerV[k]*height).
+ */
+ public final double[] cornerU = new double[3];
+ public final double[] cornerV = new double[3];
+ /** Parametric u of the apex vertex in the bounding-rect frame. */
+ public double apexU;
+
+ // Frame-space barycentric solver for base-texture resampling:
+ // P=(u,v) -> weights along input edges a->b and a->c, via the
+ // precomputed inverse of the 2x2 [Fb-Fa | Fc-Fa] system.
+ private double baryU0, baryV0, bary11, bary12, bary21, bary22;
+
+ /** Units-per-texel of the FINAL (stage-4) resolution: the raw
+ * configured value, before the stage-3 coarsening factor.
+ * {@link LightmappedTriangle} overwrites this after construction
+ * with the composite's configured value; defaults to the
+ * construction value (no coarsening -> {@link #refine()} is a
+ * no-op). */
+ public double fineUnitsPerTexel;
/**
* Accumulated indirect irradiance total, pre-albedo light units: the
/** True once the bake has finished and the texel arrays are freed. */
public volatile boolean baked;
+ /**
+ * True once this lightmap has traced its per-texel direct light
+ * (engine {@code directPass}) or had a fully-baked composite
+ * restored from the lightmap cache. False for lightmaps that only
+ * ever received the stage-1 uniform shade (outside the stage-3
+ * radius for the whole bake): the catch-up watcher uses it to give
+ * them their direct + bounce when the radius bubble reaches them,
+ * and the cache refuses to store their shade-only composites.
+ */
+ public volatile boolean directBaked;
+
+ /**
+ * Radius-gating mask of the owning triangle, mirroring
+ * {@code TriangleBvh.Entry.eligibleStages} (set at every generation
+ * barrier from the live camera position). Read at the coarse→fine
+ * transition (bit 2 = stage-4 eligible) and in termination
+ * accounting (current-phase bit).
+ */
+ public volatile int eligibleStages = 7;
+
+ /**
+ * True once a real composite (traced lighting) has been swapped in.
+ * Until then the texture still holds the initial base-color fill,
+ * and the stage-1 uniform preview may stamp the owner's per-triangle
+ * GI shade on top of it. Sticky across rebakes: a lightmap that has
+ * shown traced lighting keeps its old composite until the new
+ * direct pass lands — no uniform preview on rebake.
+ */
+ public volatile boolean everComposited;
+
/** Double-buffered composite textures; the triangle shows one, GI fills the other. */
private final Texture[] buffers = new Texture[2];
private int shownBuffer;
/** The triangle currently displaying this lightmap (for texture swaps). */
public volatile LightmappedTriangle owner;
+ /**
+ * Mesh-block lightmaps: the triangle's base texture and its UVs
+ * (primary-texture pixel units, as stored in the block). When set,
+ * the composite is generated from {@link #baseTexels} — the photo
+ * texture resampled into lightmap space — instead of the flat
+ * {@link #baseColor}, preserving texture detail under GI.
+ */
+ private Texture baseTexture;
+ private final double[] baseUv = new double[6];
+ /** Per-texel base color sampled from {@link #baseTexture}; null in flat-color mode.
+ * Held as an immutable (pixels, width, height) triple so cross-thread
+ * readers (GI catch-up gathering on one worker while another
+ * {@link #refine()}s this lightmap) never see a torn resize. */
+ private volatile BaseTexels baseTexels;
+
+ /** Immutable base-texel array with its dimensions. */
+ private static final class BaseTexels {
+ final int[] pixels;
+ final int width;
+ final int height;
+
+ BaseTexels(final int[] pixels, final int width, final int height) {
+ this.pixels = pixels;
+ this.width = width;
+ this.height = height;
+ }
+ }
+
+ /**
+ * UV perimeter of this lightmap in primary-texture pixels — the
+ * mipmap metric's texture side for triangles painted from this
+ * lightmap (UVs (0,0), (width,0), (0,height)).
+ *
+ * @return width + height + hypot(width, height)
+ */
+ public double uvPerimeter() {
+ return width + height + Math.sqrt(width * width + height * height);
+ }
+
+ /**
+ * Base color of one texel for compositing: the photo-texture sample
+ * when {@link #baseTexels} exists (mesh-block lightmaps), the flat
+ * {@link #baseColor} otherwise.
+ *
+ * @param texel texel index (j * width + i)
+ * @return ARGB base color
+ */
+ public int baseColorAt(final int texel) {
+ final BaseTexels bt = baseTexels;
+ return bt != null ? bt.pixels[texel]
+ : 0xFF000000 | (baseColor.r << 16) | (baseColor.g << 8) | baseColor.b;
+ }
+
+ /**
+ * Base color at a parametric (u, v), sampled at the base array's
+ * OWN dimensions. Race-safe against a concurrent {@link #refine()}:
+ * the (pixels, width, height) triple is swapped atomically, so the
+ * sample is always in bounds — possibly at the pre-refine
+ * resolution, which carries the same photo content.
+ *
+ * @param u parametric u, 0..1
+ * @param v parametric v, 0..1
+ * @return ARGB base color
+ */
+ public int baseColorAtUv(final double u, final double v) {
+ final BaseTexels bt = baseTexels;
+ if (bt == null)
+ return 0xFF000000 | (baseColor.r << 16) | (baseColor.g << 8) | baseColor.b;
+ int i = (int) (u * bt.width);
+ int j = (int) (v * bt.height);
+ if (i < 0) i = 0;
+ if (i >= bt.width) i = bt.width - 1;
+ if (j < 0) j = 0;
+ if (j >= bt.height) j = bt.height - 1;
+ return bt.pixels[j * bt.width + i];
+ }
+
+ /**
+ * Switches this lightmap to photo-texture compositing (mesh-block
+ * triangles): samples the base texture into per-texel base colors
+ * at the current resolution. Bilinear with wrap-aware fetch, over
+ * ALL texels — the mirrored (u+v > 1) half maps to the mirrored
+ * triangle region and is filled by the compositor's neighbor fill,
+ * so it must carry plausible colors too.
+ *
+ * @param texture the block triangle's base texture
+ * @param uv 6 UV doubles (u0,v0,u1,v1,u2,v2), primary-texture pixels
+ */
+ public void setBaseTextureMapping(final Texture texture, final double[] uv) {
+ baseTexture = texture;
+ System.arraycopy(uv, 0, baseUv, 0, 6);
+ resampleBaseTexels();
+ }
+
+ /** Resamples {@link #baseTexels} at the current dimensions. */
+ private void resampleBaseTexels() {
+ if (baseTexture == null)
+ return;
+ final TextureBitmap bitmap = baseTexture.primaryBitmap;
+ final int tw = bitmap.width, th = bitmap.height;
+ final int[] src = bitmap.pixels;
+ final boolean wrap = baseTexture.wrap;
+ final double u0 = baseUv[0], v0 = baseUv[1];
+ final double du1 = baseUv[2] - u0, dv1 = baseUv[3] - v0;
+ final double du2 = baseUv[4] - u0, dv2 = baseUv[5] - v0;
+ baseTexels = null;
+ final int[] out = new int[width * height];
+ for (int j = 0; j < height; j++)
+ for (int i = 0; i < width; i++) {
+ final double u = (i + 0.5) / width;
+ final double v = (j + 0.5) / height;
+ // Frame (u, v) -> barycentric weights along the input
+ // edges a->b and a->c (the base UVs are per input
+ // vertex, and the bounding-rect frame reorders them).
+ final double pu = u - baryU0, pv = v - baryV0;
+ final double beta1 = bary11 * pu + bary12 * pv;
+ final double beta2 = bary21 * pu + bary22 * pv;
+ double tx = u0 + du1 * beta1 + du2 * beta2 - 0.5;
+ double ty = v0 + dv1 * beta1 + dv2 * beta2 - 0.5;
+ if (wrap) {
+ tx = ((tx % tw) + tw) % tw;
+ ty = ((ty % th) + th) % th;
+ } else {
+ tx = Math.min(tw - 1.001, Math.max(0.0, tx));
+ ty = Math.min(th - 1.001, Math.max(0.0, ty));
+ }
+ final int x0 = (int) tx, y0 = (int) ty;
+ final int x1 = wrap ? (x0 + 1) % tw : Math.min(tw - 1, x0 + 1);
+ final int y1 = wrap ? (y0 + 1) % th : Math.min(th - 1, y0 + 1);
+ out[j * width + i] = bilinear(src[y0 * tw + x0],
+ src[y0 * tw + x1], src[y1 * tw + x0], src[y1 * tw + x1],
+ tx - x0, ty - y0);
+ }
+ baseTexels = new BaseTexels(out, width, height);
+ }
+
+ /**
+ * Cache restore: replaces both composite buffers with the given
+ * baked pixels (dimensions must match — the cache checks before
+ * calling) and marks the lightmap baked. No texel arrays are
+ * allocated; the lightmap is display-complete without any bake.
+ *
+ * @param pixels ARGB composite, width * height ints
+ */
+ public void restoreComposite(final int[] pixels) {
+ System.arraycopy(pixels, 0, buffers[0].primaryBitmap.pixels, 0,
+ width * height);
+ System.arraycopy(pixels, 0, buffers[1].primaryBitmap.pixels, 0,
+ width * height);
+ buffers[0].resetResampledBitmapCache();
+ buffers[1].resetResampledBitmapCache();
+ everComposited = true;
+ directBaked = true; // the cache only holds fully-baked composites
+ baked = true;
+ }
+
/**
* Creates a lightmap for a triangle.
*
final Color baseColor, final double unitsPerTexel,
final double normalX, final double normalY, final double normalZ) {
this.baseColor = baseColor;
- originX = a.x;
- originY = a.y;
- originZ = a.z;
- edge1X = b.x - a.x;
- edge1Y = b.y - a.y;
- edge1Z = b.z - a.z;
- edge2X = c.x - a.x;
- edge2Y = c.y - a.y;
- edge2Z = c.z - a.z;
this.normalX = normalX;
this.normalY = normalY;
this.normalZ = normalZ;
- final double len1 = Math.sqrt(edge1X * edge1X + edge1Y * edge1Y + edge1Z * edge1Z);
- final double len2 = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
- width = powerOfTwo(len1 / unitsPerTexel);
- height = powerOfTwo(len2 / unitsPerTexel);
+ // Orthogonal bounding-rect frame (see the class javadoc): the
+ // LONGEST edge becomes the u-axis — that keeps the apex's
+ // projection inside the base segment, so the bounding rect is
+ // tight (exactly 2x the triangle area).
+ final double abx = b.x - a.x, aby = b.y - a.y, abz = b.z - a.z;
+ final double bcx = c.x - b.x, bcy = c.y - b.y, bcz = c.z - b.z;
+ final double cax = a.x - c.x, cay = a.y - c.y, caz = a.z - c.z;
+ final double lenAB = Math.sqrt(abx * abx + aby * aby + abz * abz);
+ final double lenBC = Math.sqrt(bcx * bcx + bcy * bcy + bcz * bcz);
+ final double lenCA = Math.sqrt(cax * cax + cay * cay + caz * caz);
- final int[] valid = new int[width * height];
- int count = 0;
- for (int j = 0; j < height; j++)
- for (int i = 0; i < width; i++) {
- final double u = (i + 0.5) / width;
- final double v = (j + 0.5) / height;
- if (u + v <= 1.0)
- valid[count++] = j * width + i;
- }
- validTexels = new int[count];
- System.arraycopy(valid, 0, validTexels, 0, count);
+ final int oi, ui, pi; // input-order indices: origin, u-end, apex
+ if (lenAB >= lenBC && lenAB >= lenCA) { oi = 0; ui = 1; pi = 2; }
+ else if (lenBC >= lenCA) { oi = 1; ui = 2; pi = 0; }
+ else { oi = 2; ui = 0; pi = 1; }
+ final double[] vx = {a.x, b.x, c.x};
+ final double[] vy = {a.y, b.y, c.y};
+ final double[] vz = {a.z, b.z, c.z};
- // Both buffers start at the uniform medium INITIAL_IRRADIANCE:
- // the world is visible from frame one; each lightmap flips to
- // its traced lighting when the bake reaches it.
+ originX = vx[oi];
+ originY = vy[oi];
+ originZ = vz[oi];
+ // u-axis: the base vector itself (u in 0..1 spans the base).
+ edge1X = vx[ui] - vx[oi];
+ edge1Y = vy[ui] - vy[oi];
+ edge1Z = vz[ui] - vz[oi];
+ final double baseLen = Math.max(lenAB, Math.max(lenBC, lenCA));
+
+ // Apex decomposition: s along the base, remainder perpendicular.
+ final double apx = vx[pi] - vx[oi];
+ final double apy = vy[pi] - vy[oi];
+ final double apz = vz[pi] - vz[oi];
+ final double s = baseLen > 1e-12
+ ? (apx * edge1X + apy * edge1Y + apz * edge1Z) / (baseLen * baseLen)
+ : 0;
+ // v-axis: the perpendicular remainder (v in 0..1 spans the height).
+ edge2X = apx - s * edge1X;
+ edge2Y = apy - s * edge1Y;
+ edge2Z = apz - s * edge1Z;
+ final double heightLen = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
+ apexU = Math.min(1, Math.max(0, s));
+
+ cornerU[oi] = 0; cornerV[oi] = 0;
+ cornerU[ui] = 1; cornerV[ui] = 0;
+ cornerU[pi] = apexU; cornerV[pi] = 1;
+
+ // Frame-space barycentric solver for base-texture resampling
+ // (input vertices a, b, c sit at cornerU/V; the matrix is a
+ // permutation of [(1,0)-(0,0) | (apexU,1)-(0,0)], |det| = 1).
+ baryU0 = cornerU[0];
+ baryV0 = cornerV[0];
+ final double m11 = cornerU[1] - baryU0, m12 = cornerU[2] - baryU0;
+ final double m21 = cornerV[1] - baryV0, m22 = cornerV[2] - baryV0;
+ final double det = m11 * m22 - m12 * m21;
+ if (Math.abs(det) > 1e-12) {
+ bary11 = m22 / det;
+ bary12 = -m12 / det;
+ bary21 = -m21 / det;
+ bary22 = m11 / det;
+ }
+
+ final int[] dims = dimsFor(baseLen, heightLen, unitsPerTexel);
+ width = dims[0];
+ height = dims[1];
+ fineUnitsPerTexel = unitsPerTexel;
+
+ validTexels = computeValidTexels(width, height, apexU);
+
+ // Both buffers start at the uniform INITIAL_IRRADIANCE (255 =
+ // true base color, "as-is"): each lightmap flips to its traced
+ // lighting when the bake reaches it.
buffers[0] = createTexture();
buffers[1] = createTexture();
}
- private static int powerOfTwo(final double size) {
- int result = MIN_SIZE;
- while (result < size && result < MAX_SIZE)
- result <<= 1;
+ /**
+ * Lightmap dimensions for a {@code len1 x len2} bounding rect at the
+ * given density. Aspect comes FIRST (texels must be square on every
+ * triangle shape): the height rounds to a whole texel count and the
+ * width is then fitted to the ROUNDED height's aspect, and a small
+ * neighborhood search picks the best (w, h) pair. The ideal aspect
+ * is scaled into the [1, {@link #MAX_SIZE}] bounds and the
+ * {@link #MIN_SIZE}-texel long-axis floor BEFORE integer fitting,
+ * so bounds never distort the aspect — they change density, not
+ * shape. Residual anisotropy is the width's own rounding error,
+ * ~half a texel (<= ~1.1:1 above 5 texels, better as counts grow).
+ */
+ private static int[] dimsFor(final double len1, final double len2,
+ final double unitsPerTexel) {
+ if (len1 < 1e-12 || len2 < 1e-12)
+ return new int[]{MIN_SIZE, 1};
+ double b = len1 / unitsPerTexel; // ideal width in texels
+ double hh = len2 / unitsPerTexel; // ideal height in texels
+ double s = 1;
+ if (b < MIN_SIZE)
+ s = MIN_SIZE / b; // tiny triangle: raise density to the floor
+ if (b * s > MAX_SIZE)
+ s = MAX_SIZE / b; // huge triangle: lower density to the cap
+ if (hh * s > MAX_SIZE)
+ s = Math.min(s, MAX_SIZE / hh);
+ if (hh * s < 1)
+ s = Math.min(1 / hh, MAX_SIZE / b); // at least one texel high
+ b *= s;
+ hh *= s;
+
+ // Integer fit: for each candidate height near the ideal, fit the
+ // width to that height's aspect. Score = aspect deviation plus a
+ // small penalty for drifting from the ideal texel count (breaks
+ // aspect ties away from degenerate strips).
+ int bestW = MIN_SIZE, bestH = 1;
+ double bestScore = Double.MAX_VALUE;
+ final double idealArea = b * hh;
+ final int h0 = Math.max(1, (int) Math.round(hh));
+ for (int h = Math.max(1, h0 - 1); h <= Math.min(MAX_SIZE, h0 + 1); h++) {
+ final int w = Math.min(MAX_SIZE, Math.max(1,
+ (int) Math.round(b * h / hh)));
+ final double aspect = (len1 / w) / (len2 / h);
+ final double score = Math.abs(Math.log(aspect))
+ + 0.05 * Math.abs(Math.log(w * h / idealArea));
+ if (score < bestScore - 1e-9) {
+ bestScore = score;
+ bestW = w;
+ bestH = h;
+ }
+ }
+ return new int[]{bestW, bestH};
+ }
+
+ /**
+ /**
+ * Inside-triangle test in texture space for smoothing/neighborhood
+ * queries — the same region {@link #validTexels} was built from
+ * (bounding-rect frame: NOT the whole texture, NOT the old
+ * half-square).
+ */
+ public boolean isValidTexel(final int i, final int j) {
+ if (i < 0 || i >= width || j < 0 || j >= height)
+ return false;
+ final double u = (i + 0.5) / width;
+ final double v = (j + 0.5) / height;
+ return insideTriangle(u, v, apexU);
+ }
+
+ /** Valid texel indices for a w x h lightmap: texel centers inside
+ * the triangle, which sits in the bounding-rect frame at
+ * (0,0), (1,0), ({@code apexU},1).
+ */
+ private static int[] computeValidTexels(final int w, final int h, final double apexU) {
+ final int[] valid = new int[w * h];
+ int count = 0;
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++) {
+ final double u = (i + 0.5) / w;
+ final double v = (j + 0.5) / h;
+ if (insideTriangle(u, v, apexU))
+ valid[count++] = j * w + i;
+ }
+ final int[] result = new int[count];
+ System.arraycopy(valid, 0, result, 0, count);
return result;
}
+ /**
+ * Point-in-triangle test in frame space, triangle (0,0), (1,0),
+ * (apexU,1). Inside = right of the left edge (u >= apexU*v), left
+ * of the right edge (u <= 1-(1-apexU)*v), above the base. A right
+ * triangle with apexU=0 or 1 collapses one constraint, matching the
+ * old u+v<=1 half-square region.
+ */
+ private static boolean insideTriangle(final double u, final double v, final double apexU) {
+ if (u < 0 || u > 1 || v < 0 || v > 1)
+ return false;
+ return u >= apexU * v - 1e-9 && u <= 1.0 - (1.0 - apexU) * v + 1e-9;
+ }
+
+ /**
+ * Stage 4: reallocates this lightmap at {@link #fineUnitsPerTexel}
+ * after the coarse bake converged. The shown composite is upscaled
+ * into the new buffers (the display does not regress at the
+ * transition itself), then the texel arrays drop to null and the
+ * fine bake rebuilds them from direct. Visibility is dropped:
+ * generation 1 re-traces shadow rays at the final resolution.
+ * No-op when the coarse and fine resolutions coincide (tiny
+ * lightmaps at the 4-texel floor).
+ *
+ * <p>The coarse field seeds the DISPLAY only, never the solver:
+ * the fine Neumann chain rebuilds every bounce path at fine
+ * resolution, and carrying the coarse total into the accumulated
+ * indirect would count the whole series twice (measured: floor
+ * probes at 44.0 instead of the correct 27.7).</p>
+ */
+ public void refine() {
+ final double len1 = Math.sqrt(edge1X * edge1X + edge1Y * edge1Y + edge1Z * edge1Z);
+ final double len2 = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
+ final int[] dims = dimsFor(len1, len2, fineUnitsPerTexel);
+ final int newW = dims[0], newH = dims[1];
+ if (newW == width && newH == height)
+ return;
+
+ final int oldW = width, oldH = height;
+ final Texture oldShown = shownTexture();
+
+ width = newW;
+ height = newH;
+ validTexels = computeValidTexels(newW, newH, apexU);
+ buffers[0] = upscale(oldShown.primaryBitmap.pixels, oldW, oldH, newW, newH);
+ buffers[1] = upscale(oldShown.primaryBitmap.pixels, oldW, oldH, newW, newH);
+ shownBuffer = 0;
+
+ // Texel arrays drop to null: ensureArrays re-allocates them at
+ // fine size when generation 1 reaches this lightmap, and the
+ // fine bake accumulates its own series from zero. The coarse
+ // total is deliberately NOT carried into the solver: the fine
+ // Neumann chain rebuilds paths 1..N at fine resolution, and
+ // adding them onto the coarse total would count the indirect
+ // twice (measured: floor probes 44.0 vs the correct 27.7).
+ // The coarse solution survives ONLY in the upscaled composite
+ // texture above — display continuity, never solver input.
+ indirectR = null;
+ indirectG = null;
+ indirectB = null;
+ deltaPrevR = null;
+ deltaPrevG = null;
+ deltaPrevB = null;
+ deltaCurR = null;
+ deltaCurG = null;
+ deltaCurB = null;
+ lightVisibility = null;
+ generation = 0;
+ baked = false; // a resize invalidates the bake: fine pass pending
+ directBaked = false; // fine-phase generation 1 re-traces direct
+ resampleBaseTexels();
+ if (owner != null) {
+ // The triangle's UVs are pinned to the lightmap corners in
+ // TEXTURE PIXELS — re-pin them to the fine dimensions or
+ // the painter would sample only the coarse-sized corner of
+ // the fine texture.
+ owner.repinUvToLightmap();
+ owner.setTexture(buffers[0]);
+ }
+ }
+
+ /**
+ * True when this lightmap still runs at a coarser resolution than
+ * {@link #fineUnitsPerTexel} implies (i.e. {@link #refine()} would
+ * reallocate). Used by the GI catch-up watcher: a coarse-baked
+ * lightmap whose triangle enters the stage-4 radius gets refined
+ * and re-baked at the final density.
+ *
+ * @return true when a refine would change the dimensions
+ */
+ public boolean needsRefine() {
+ final double len1 = Math.sqrt(edge1X * edge1X + edge1Y * edge1Y + edge1Z * edge1Z);
+ final double len2 = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
+ final int[] dims = dimsFor(len1, len2, fineUnitsPerTexel);
+ return dims[0] != width || dims[1] != height;
+ }
+
+ /** Bilinear upscale of a composite texture into a new w x h texture. */
+ private static Texture upscale(final int[] sp, final int sw, final int sh,
+ final int w, final int h) {
+ final Texture out = new Texture(w, h, 0);
+ final int[] dp = out.primaryBitmap.pixels;
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++) {
+ final double sx = Math.min(sw - 1.0, Math.max(0.0, (i + 0.5) * sw / w - 0.5));
+ final double sy = Math.min(sh - 1.0, Math.max(0.0, (j + 0.5) * sh / h - 0.5));
+ final int x0 = (int) sx, y0 = (int) sy;
+ final int x1 = Math.min(sw - 1, x0 + 1), y1 = Math.min(sh - 1, y0 + 1);
+ final double fx = sx - x0, fy = sy - y0;
+ dp[j * w + i] = bilinear(sp[y0 * sw + x0], sp[y0 * sw + x1],
+ sp[y1 * sw + x0], sp[y1 * sw + x1], fx, fy);
+ }
+ return out;
+ }
+
+ /** Bilinear mix of four ARGB pixels, per channel. */
+ private static int bilinear(final int p00, final int p10, final int p01, final int p11,
+ final double fx, final double fy) {
+ final double w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy);
+ final double w01 = (1 - fx) * fy, w11 = fx * fy;
+ final int r = Math.min(255, (int) (w00 * ((p00 >> 16) & 255) + w10 * ((p10 >> 16) & 255)
+ + w01 * ((p01 >> 16) & 255) + w11 * ((p11 >> 16) & 255)));
+ final int g = Math.min(255, (int) (w00 * ((p00 >> 8) & 255) + w10 * ((p10 >> 8) & 255)
+ + w01 * ((p01 >> 8) & 255) + w11 * ((p11 >> 8) & 255)));
+ final int b = Math.min(255, (int) (w00 * (p00 & 255) + w10 * (p10 & 255)
+ + w01 * (p01 & 255) + w11 * (p11 & 255)));
+ return 0xFF000000 | (r << 16) | (g << 8) | b;
+ }
+
private Texture createTexture() {
final Texture texture = new Texture(width, height, 0);
final int r = Math.min(255, (int) (INITIAL_IRRADIANCE * baseColor.r / 255));
* @return texel index, clamped into the texture
*/
public int texelAt(final double px, final double py, final double pz) {
+ final double[] uv = new double[2];
+ uvAt(px, py, pz, uv);
+ int i = (int) (uv[0] * width);
+ int j = (int) (uv[1] * height);
+ if (i < 0) i = 0;
+ if (i >= width) i = width - 1;
+ if (j < 0) j = 0;
+ if (j >= height) j = height - 1;
+ return j * width + i;
+ }
+
+ /**
+ * Parametric (u, v) of a world-space point on this lightmap's quad.
+ * Resolution-independent: callers sampling a texture whose size can
+ * change under them (GI catch-up reading a composite while another
+ * worker {@link #refine()}s this lightmap) scale (u, v) by the
+ * texture's own dimensions and stay in bounds. Values may fall
+ * slightly outside 0..1 for edge hits; callers clamp after scaling.
+ *
+ * @param px world x
+ * @param py world y
+ * @param pz world z
+ * @param out receives {u, v}
+ */
+ public void uvAt(final double px, final double py, final double pz, final double[] out) {
final double dx = px - originX;
final double dy = py - originY;
final double dz = pz - originZ;
final double dp1 = dx * edge1X + dy * edge1Y + dz * edge1Z;
final double dp2 = dx * edge2X + dy * edge2Y + dz * edge2Z;
final double denom = d11 * d22 - d12 * d12;
- if (denom < 1e-12)
- return 0;
- final double u = (dp1 * d22 - dp2 * d12) / denom;
- final double v = (dp2 * d11 - dp1 * d12) / denom;
- int i = (int) (u * width);
- int j = (int) (v * height);
- if (i < 0) i = 0;
- if (i >= width) i = width - 1;
- if (j < 0) j = 0;
- if (j >= height) j = height - 1;
- return j * width + i;
+ if (denom < 1e-12) {
+ out[0] = 0;
+ out[1] = 0;
+ return;
+ }
+ out[0] = (dp1 * d22 - dp2 * d12) / denom;
+ out[1] = (dp2 * d11 - dp1 * d12) / denom;
}
/**
}
generation = 0;
baked = false;
+ // Visibility bytes were just (re)allocated blank: the direct
+ // pass that follows re-traces them. Until it completes, the
+ // catch-up watcher must treat this lightmap as never-baked.
+ directBaked = false;
}
/**
--- /dev/null
+/*
+ * Aukio 3D engine. Author: Svjatoslav Agejenko.
+ * This project is released under Creative Commons Zero (CC0) license.
+ */
+package eu.svjatoslav.aukio.e3d.renderer.raster.gi;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * RAM cache of baked lightmap composite textures, keyed by a 64-bit
+ * hash of the triangle's three world-space vertices. Streaming worlds
+ * (FO4 cells) discard and rebuild their mesh blocks as the camera
+ * travels; a cache hit rebuilds the lightmap's display textures
+ * instantly, without re-running the bake. RAM-only, per GI instance —
+ * nothing is persisted to disk.
+ *
+ * <p>Only the final COMPOSITE pixels are cached (plus dimensions);
+ * bake-state texel arrays are transient by design. A dimension mismatch
+ * (different texel density configuration) is a miss.</p>
+ *
+ * <p>Capacity is capped ({@code e3d.giLightmapCacheEntries}); eviction
+ * is least-recently-used. Thread-safe.</p>
+ */
+final class LightmapCache {
+
+ /** One cached composite. */
+ static final class Entry {
+ final int width;
+ final int height;
+ final int[] pixels;
+ /** Lighting signature under which the composite was baked; a
+ * light change invalidates the entry (restore compares). */
+ final double lightSignature;
+
+ Entry(final int width, final int height, final int[] pixels,
+ final double lightSignature) {
+ this.width = width;
+ this.height = height;
+ this.pixels = pixels;
+ this.lightSignature = lightSignature;
+ }
+ }
+
+ private final LinkedHashMap<Long, Entry> map;
+
+ LightmapCache(final int capacity) {
+ map = new LinkedHashMap<>(256, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(
+ final Map.Entry<Long, LightmapCache.Entry> e) {
+ return size() > capacity;
+ }
+ };
+ }
+
+ /**
+ * Geometry key for a triangle: splitmix64-mixed double bits of the
+ * 9 world-space vertex coordinates. Deterministic across block
+ * rebuilds from identical source data.
+ */
+ static long key(final double[] world9) {
+ long h = 0x9E3779B97F4A7C15L;
+ for (int i = 0; i < 9; i++) {
+ long z = Double.doubleToLongBits(world9[i]) + 0x9E3779B97F4A7C15L
+ + (h << 6) + (h >>> 2);
+ z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
+ z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
+ h ^= z ^ (z >>> 31);
+ }
+ return h;
+ }
+
+ /**
+ * Geometry key over float vertex bits (TriangleBvh.Entry.v).
+ * Deterministic across block rebuilds from identical source data.
+ */
+ static long key(final float[] world9) {
+ long h = 0x9E3779B97F4A7C15L;
+ for (int i = 0; i < 9; i++) {
+ long z = Float.floatToIntBits(world9[i]) + 0x9E3779B97F4A7C15L
+ + (h << 6) + (h >>> 2);
+ z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
+ z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
+ h ^= z ^ (z >>> 31);
+ }
+ return h;
+ }
+
+ /** Looks up a cached composite; marks it recently used. */
+ synchronized Entry get(final long key) {
+ return map.get(key);
+ }
+
+ /** Stores a composite (the pixel array is adopted, not copied). */
+ synchronized void put(final long key, final int width, final int height,
+ final int[] pixels, final double lightSignature) {
+ map.put(key, new Entry(width, height, pixels, lightSignature));
+ }
+
+ synchronized int size() {
+ return map.size();
+ }
+}
new Vertex(b, new Point2D(1, 0)),
new Vertex(c, new Point2D(0, 1)),
null);
- lightmap = new Lightmap(a, b, c, baseColor, unitsPerTexel,
+ lightmap = new Lightmap(a, b, c, baseColor,
+ GlobalIllumination.lightmapUnitsPerTexel(unitsPerTexel),
normalX, normalY, normalZ);
+ // The raw configured resolution is where stage 4 refines to.
+ lightmap.fineUnitsPerTexel = unitsPerTexel;
lightmap.owner = this;
// UVs are in PRIMARY TEXTURE PIXELS in this engine (multiplication
// factor scales them into the selected mip level), so the triangle
// corners map to the lightmap corners directly.
- vertices.get(0).textureCoordinate = new Point2D(0, 0);
- vertices.get(1).textureCoordinate = new Point2D(lightmap.width, 0);
- vertices.get(2).textureCoordinate = new Point2D(0, lightmap.height);
- refreshTextureDistance();
+ repinUvToLightmap();
setTexture(lightmap.shownTexture());
}
+ /**
+ * Pins the corner UVs to the lightmap's CURRENT dimensions and
+ * refreshes the texture-distance estimate. Called at construction
+ * and by {@link Lightmap#refine()} (stage 4 changes the texture
+ * size — without re-pinning, the painter would sample only the
+ * coarse-sized corner of the fine texture). Each vertex gets its
+ * own frame-space corner ({@link Lightmap#cornerU}/{@code cornerV})
+ * — the bounding-rect frame may assign any corner to any vertex.
+ */
+ public void repinUvToLightmap() {
+ for (int k = 0; k < 3; k++)
+ vertices.get(k).textureCoordinate = new Point2D(
+ lightmap.cornerU[k] * lightmap.width,
+ lightmap.cornerV[k] * lightmap.height);
+ refreshTextureDistance();
+ }
+
@Override
public Lightmap getLightmap() {
return lightmap;
/** Squared distance from the camera at snapshot build (near-to-far bake order). */
public float distance;
+ /**
+ * Radius-gating mask, re-evaluated from the live camera position
+ * at every generation barrier: bit 0 = eligible for stage 2
+ * (centroid bounce), bit 1 = stage 3 (coarse per-texel), bit 2 =
+ * stage 4 (fine refinement). All bits set when no radius is
+ * configured (the historical global bake).
+ */
+ public volatile int eligibleStages = 7;
+
public Entry(final AbstractCoordinateShape polygon) {
this.polygon = polygon;
this.block = null;
--- /dev/null
+/*
+ * Aukio 3D engine. Author: Svjatoslav Agejenko.
+ * This project is released under Creative Commons Zero (CC0) license.
+ */
+package eu.svjatoslav.aukio.e3d.renderer.raster.lighting;
+
+import eu.svjatoslav.aukio.e3d.diag.EngineConfig;
+import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
+
+/**
+ * Optional distance haze ("atmospheric perspective"): geometry fades
+ * toward the sky color as camera-space depth grows, factor
+ * {@code f = 1 - exp(-depth / scale)}. Disabled by default; enable per
+ * scene ({@link #setEnabled}, the Fallout 4 environment does) or
+ * globally with {@code -De3d.atmosphere=true} /
+ * {@code e3d.atmosphere: true} in the config file
+ * (bugreport-20261006-000922).
+ *
+ * <p>Cost model: the factor is evaluated once per polygon per frame and
+ * folded into the same per-polygon light multiplier the span loops
+ * already apply — {@code texel * (light*(1-f)) + sky*f} — so the
+ * per-pixel price on textured triangles is one ADD per channel and no
+ * additional multiplication. Solid polygons precompute one shaded color
+ * per polygon, so their per-pixel cost is exactly zero. Lightmapped
+ * triangles sit inside the stage-3 bubble a few hundred units from the
+ * camera, where the factor rounds to zero for any practical scale; that
+ * path is deliberately left untouched.</p>
+ *
+ * <p>The haze target color is the configured {@code e3d.atmosphereColor}
+ * when set, otherwise the scene's sky color
+ * ({@link LightingManager#getSkyColor()}), so the horizon blends into
+ * the backdrop seamlessly. With neither, haze is inert.</p>
+ */
+public final class Atmosphere {
+
+ /** Runtime enable override from environment modules; null = config. */
+ private static volatile Boolean enabledOverride;
+ /** Runtime scale override; NaN = config. */
+ private static volatile double scaleOverride = Double.NaN;
+ /** Runtime haze color override; null = config or scene sky color. */
+ private static volatile Color colorOverride;
+
+ /**
+ * Resolved file/property configuration, read once per JVM: the
+ * getters below run per TRIANGLE per frame, so they must never
+ * re-navigate the config file (bugreport-20261006-000922: a
+ * per-call AukioConfig lookup made a 649k-shape frame render 15x
+ * slower).
+ */
+ private static volatile Resolved config;
+
+ /** Immutable resolved configuration triple. */
+ private record Resolved(boolean enabled, double scale, Color color) {
+ }
+
+ private static Resolved config() {
+ Resolved r = config;
+ if (r == null) {
+ synchronized (Atmosphere.class) {
+ r = config;
+ if (r == null) {
+ final String hex = EngineConfig.getAtmosphereColor();
+ r = new Resolved(EngineConfig.isAtmosphereEnabled(),
+ EngineConfig.getAtmosphereScale(),
+ hex == null || hex.isEmpty()
+ ? null : Color.hex(hex));
+ config = r;
+ }
+ }
+ }
+ return r;
+ }
+
+ private Atmosphere() {
+ }
+
+ /**
+ * Enables or disables the haze at runtime (environment modules).
+ * Wins over {@code e3d.atmosphere}; see {@link #resetOverrides()}.
+ *
+ * @param enabled true to haze distant geometry toward the sky color
+ */
+ public static void setEnabled(final boolean enabled) {
+ enabledOverride = enabled;
+ }
+
+ /**
+ * Sets the haze scale at runtime: the camera depth at which the haze
+ * factor reaches ~63% (1 - 1/e). Wins over
+ * {@code e3d.atmosphereScale}.
+ *
+ * @param scale world units
+ */
+ public static void setScale(final double scale) {
+ scaleOverride = scale;
+ }
+
+ /**
+ * Sets the haze target color at runtime. Wins over
+ * {@code e3d.atmosphereColor} and the scene sky color.
+ *
+ * @param color haze color, or null to fall back to configuration
+ */
+ public static void setColor(final Color color) {
+ colorOverride = color;
+ }
+
+ /** Drops all runtime overrides; configuration applies again. */
+ public static void resetOverrides() {
+ enabledOverride = null;
+ scaleOverride = Double.NaN;
+ colorOverride = null;
+ }
+
+ /** Returns whether distance haze is active. */
+ public static boolean enabled() {
+ final Boolean o = enabledOverride;
+ return o != null ? o : config().enabled();
+ }
+
+ /** Returns the haze scale in world units. */
+ public static double scale() {
+ final double o = scaleOverride;
+ return Double.isNaN(o) ? config().scale() : o;
+ }
+
+ /**
+ * The haze factor for a camera-space depth: 0 at the camera,
+ * approaching 1 at infinity. Returns 0 when the haze is disabled or
+ * the depth is behind the near plane.
+ *
+ * @param cameraDepth camera-space Z of the polygon
+ * @return haze blend factor in [0, 1)
+ */
+ public static float factor(final double cameraDepth) {
+ if (cameraDepth <= 0 || !enabled())
+ return 0f;
+ final double s = scale();
+ if (s <= 0)
+ return 0f;
+ final float f = (float) (1.0 - Math.exp(-cameraDepth / s));
+ // Sub-perceptible factors round to zero so near geometry keeps
+ // the bit-identical haze-free span path.
+ return f < 1.0e-4f ? 0f : Math.min(f, 1f);
+ }
+
+ /**
+ * Resolves the haze target color: runtime override, then the
+ * configured {@code e3d.atmosphereColor}, then the scene's sky color.
+ *
+ * @param lighting the scene lighting manager, or null
+ * @return the color to fade toward, or null when none is known
+ * (haze stays inert)
+ */
+ public static Color targetColor(final LightingManager lighting) {
+ final Color o = colorOverride;
+ if (o != null)
+ return o;
+ final Color configured = config().color();
+ if (configured != null)
+ return configured;
+ return lighting == null ? null : lighting.getSkyColor();
+ }
+
+ /**
+ * Blends a per-polygon shaded color toward the haze target in place:
+ * {@code c = c*(1-f) + target*f}. Called once per polygon per frame
+ * — the span loops keep painting the constant result, so solid
+ * polygons pay zero per-pixel cost for the haze.
+ *
+ * @param shaded the polygon's lit color, mutated
+ * @param f haze factor from {@link #factor(double)}
+ * @param target haze target color from {@link #targetColor}
+ */
+ public static void applyHaze(final Color shaded, final float f,
+ final Color target) {
+ final float keep = 1f - f;
+ shaded.r = Color.clamp((int) (shaded.r * keep + target.r * f + 0.5f));
+ shaded.g = Color.clamp((int) (shaded.g * keep + target.g * f + 0.5f));
+ shaded.b = Color.clamp((int) (shaded.b * keep + target.b * f + 0.5f));
+ }
+}
*/
private volatile GiLightProvider giProvider;
+ /**
+ * Sky dome color for GI bounce rays that escape the scene; see
+ * {@link #setSkyColor(Color)}. Volatile: the GI workers read it at
+ * snapshot (re)build time on their own threads.
+ */
+ private volatile Color skyColor;
+
/**
* Creates a new lighting manager with no light sources.
*/
this.ambientLight = ambientLight;
}
+ /**
+ * Sky dome color sampled by global-illumination bounce rays that
+ * escape the scene (hit nothing). Null (default) = no sky
+ * contribution: misses contribute zero, the historical behavior.
+ * Set this to the same color the app clears its background with, so
+ * shadowed surfaces pick up a sky-tinted first bounce instead of
+ * going black.
+ *
+ * @return the sky dome color, or null when sky sampling is off
+ */
+ public Color getSkyColor() {
+ return skyColor;
+ }
+
+ /**
+ * Sets the sky dome color for GI bounce rays that escape the scene.
+ *
+ * @param skyColor the sky color, or null to disable sky sampling
+ */
+ public void setSkyColor(final Color skyColor) {
+ this.skyColor = skyColor;
+ }
+
/**
* Returns all light sources in the scene.
*
import eu.svjatoslav.aukio.e3d.renderer.raster.Vertex;
import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderAggregator;
+import eu.svjatoslav.aukio.e3d.renderer.raster.lighting.Atmosphere;
import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.AbstractCoordinateShape;
import java.util.ArrayList;
renderingContext.lightingManager.computeLighting(
this, cachedCenter, cachedBackNormal, color, backShadedColor);
}
+ // Atmospheric haze (optional, bugreport-20261006-000922):
+ // folded into the per-polygon shaded color itself, so the
+ // span loops keep painting one constant color — zero
+ // per-pixel cost.
+ if (Atmosphere.enabled()) {
+ final float f = Atmosphere.factor(getZ(renderingContext));
+ final Color hazeTarget = f > 0f
+ ? Atmosphere.targetColor(
+ renderingContext.lightingManager) : null;
+ if (hazeTarget != null) {
+ Atmosphere.applyHaze(shadedColor, f, hazeTarget);
+ if (!backfaceCulling)
+ Atmosphere.applyHaze(backShadedColor, f, hazeTarget);
+ }
+ }
}
}
}
\ No newline at end of file
import eu.svjatoslav.aukio.e3d.geometry.Point2D;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderingContext;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderAggregator;
+import eu.svjatoslav.aukio.e3d.renderer.raster.lighting.Atmosphere;
import eu.svjatoslav.aukio.e3d.math.TransformStack;
/**
final Point2D[] screen = SCREEN_SCRATCH.get();
final Point2D[] uvs = UV_SCRATCH.get();
+ // Per-texel GI lightmap (attached when this triangle sits inside
+ // the stage-3 radius bubble): once a real composite has landed,
+ // the composite texture IS the paint source — base texture and
+ // lighting premultiplied — so the per-triangle shade multiply
+ // must go away. Before the first composite the triangle keeps
+ // the base texture + per-triangle shade (progressive, never a
+ // flat-color regression).
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap lightmap =
+ block.lightmapAt(index);
+ final int clip = block.clipOffset(slot, index);
+ // Near-plane straddlers keep base texture + shade this frame:
+ // the clip store carries base-texture UVs, not lightmap UVs.
+ final boolean useLightmap = lightmap != null && lightmap.everComposited
+ && clip < 0;
+
// Per-triangle GI light (null while no GI system traces this
// block): the span loops multiply texels by it. Values are read
// racily from the GI threads — fine for converging estimates.
- final float[] giLight = block.giLight();
- if (giLight != null) {
- final int i = index * 3;
- giShadeR = giLight[i];
- giShadeG = giLight[i + 1];
- giShadeB = giLight[i + 2];
- giShaded = true;
+ if (!useLightmap) {
+ final float[] giLight = block.giLight();
+ if (giLight != null) {
+ final int i = index * 3;
+ giShadeR = giLight[i];
+ giShadeG = giLight[i + 1];
+ giShadeB = giLight[i + 2];
+ giShaded = true;
+ }
+ } else {
+ // Composite carries all light; no shade multiply.
+ giShaded = false;
+ }
+
+ // Atmospheric haze (optional, bugreport-20261006-000922):
+ // evaluated once per triangle and folded into the same
+ // per-triangle multiplier the span loops already apply —
+ // texel * (shade*(1-f)) + sky*f — so the per-pixel price is one
+ // add per channel, no extra multiplication. Lightmapped
+ // triangles sit inside the stage-3 bubble, a few hundred units
+ // from the camera: the factor rounds to zero there for any
+ // practical atmosphere scale, so the composite path is left
+ // untouched.
+ if (!useLightmap && Atmosphere.enabled()) {
+ final float f = Atmosphere.factor(getZ(renderBuffer));
+ final eu.svjatoslav.aukio.e3d.renderer.raster.Color sky =
+ f > 0f ? Atmosphere.targetColor(
+ renderBuffer.lightingManager) : null;
+ if (sky == null) {
+ hazed = false;
+ } else {
+ final float att = 1f - f;
+ if (giShaded)
+ setHaze(giShadeR * att, giShadeG * att, giShadeB * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ else
+ setHaze(255f * att, 255f * att, 255f * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ }
+ } else {
+ hazed = false;
}
- final int clip = block.clipOffset(slot, index);
if (clip >= 0) {
// Near-plane straddler: the block clipped to a loop of 3-4
// vertices, stored as (x, y, z, u, v, sx, sy) tuples. Paint
block.loadScreenVertex(screen[0], uvs[0], slot, index, 0, renderBuffer);
block.loadScreenVertex(screen[1], uvs[1], slot, index, 1, renderBuffer);
block.loadScreenVertex(screen[2], uvs[2], slot, index, 2, renderBuffer);
+ if (useLightmap) {
+ // Pin UVs to the lightmap corners (texture pixels), exactly
+ // like LightmappedTriangle. The lightmap's own UV perimeter
+ // drives mipmap selection (texel density differs from the
+ // base texture's). UVs come from the lightmap's frame
+ // corners: the bounding-rect frame may assign any corner
+ // of the rect to any vertex of the triangle.
+ final int w = lightmap.width, h = lightmap.height;
+ for (int k = 0; k < 3; k++) {
+ uvs[k].x = lightmap.cornerU[k] * w;
+ uvs[k].y = lightmap.cornerV[k] * h;
+ }
+ paintFlat(renderBuffer, lightmap.shownTexture(),
+ block.backfaceCull(),
+ screen[0], screen[1], screen[2],
+ uvs[0], uvs[1], uvs[2],
+ block.camZ(slot, index, 0),
+ block.camZ(slot, index, 1),
+ block.camZ(slot, index, 2),
+ block.screenPerim(slot, index),
+ lightmap.uvPerimeter());
+ return;
+ }
paintFlat(renderBuffer, block.texture(index), block.backfaceCull(),
screen[0], screen[1], screen[2],
uvs[0], uvs[1], uvs[2],
import eu.svjatoslav.aukio.e3d.geometry.Point2D;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderingContext;
import eu.svjatoslav.aukio.e3d.renderer.raster.Vertex;
+import eu.svjatoslav.aukio.e3d.renderer.raster.lighting.Atmosphere;
import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.AbstractCoordinateShape;
import eu.svjatoslav.aukio.e3d.renderer.raster.texture.Texture;
import eu.svjatoslav.aukio.e3d.renderer.raster.texture.TextureBitmap;
private boolean backfaceCulling = Boolean.getBoolean("e3d.backface");
- // ---- per-triangle GI shading (mesh-block path only) ----
+ // ---- per-triangle GI shading ----
/**
* Per-triangle light total in light units (255 = full texture
- * brightness), written by {@code MeshTriangle.paint} from the owning
- * block's GI arrays before the paint core runs. Object-backed
- * triangles never touch these: {@link #giShaded} stays false and the
- * span loops render bit-identically to the unlit path.
+ * brightness). Two writers: {@code MeshTriangle.paint} copies it
+ * from the owning block's GI arrays before the paint core runs, and
+ * the GI system stamps it on a {@code LightmappedTriangle} for the
+ * stage-1 uniform preview (cleared when the first real composite
+ * lands). While {@link #giShaded} is false the span loops render
+ * bit-identically to the unlit path.
*/
float giShadeR, giShadeG, giShadeB;
- /** True while {@link #giShadeR/G/B} carry a GI light total. */
- boolean giShaded;
+ /**
+ * True while {@link #giShadeR/G/B} carry a GI light total. Volatile:
+ * the GI worker threads stamp/clear it on lightmapped triangles
+ * while render threads read it in the span loops; the float triplet
+ * piggybacks on this flag's happens-before edge.
+ */
+ volatile boolean giShaded;
+
+ /**
+ * Stamps a uniform GI light triplet on this triangle (stage-1
+ * preview): the span loops multiply every sampled texel by
+ * triplet / 255 until {@link #clearGiShade()} is called.
+ *
+ * @param r red light units (255 = full)
+ * @param g green light units
+ * @param b blue light units
+ */
+ public void setGiShade(final float r, final float g, final float b) {
+ giShadeR = r;
+ giShadeG = g;
+ giShadeB = b;
+ giShaded = true; // last: volatile release publishes the triplet
+ }
+
+ /** Returns to painting the bare texture (stage-1 preview over). */
+ public void clearGiShade() {
+ giShaded = false;
+ }
/**
* Multiplies a sampled texel by the per-triangle GI light, clamped.
return (texel & 0xFF000000) | (r << 16) | (g << 8) | b;
}
+ // ---- per-triangle atmospheric haze ----
+
+ /**
+ * Per-triangle atmospheric haze in light units: {@code hazeMul*}
+ * is the shade multiplier with the (1-f) attenuation ALREADY folded
+ * in (GI shade × (1-f), or 255×(1-f) when no GI shades this
+ * triangle), {@code hazeAdd*} is the additive sky term sky×f.
+ * Stamped once per triangle per frame from the paint path when the
+ * atmosphere is enabled (bugreport-20261006-000922). While
+ * {@link #hazed} is false the span loops render bit-identically to
+ * the haze-free path.
+ */
+ float hazeMulR, hazeMulG, hazeMulB, hazeAddR, hazeAddG, hazeAddB;
+ /** True while the haze sextet carries an active haze blend. */
+ boolean hazed;
+
+ /**
+ * Stamps this triangle's haze blend: the span loops compute
+ * {@code texel * mul / 255 + add} per channel — the attenuation half
+ * of the haze rides the light multiply that already exists, so the
+ * per-pixel price is one add per channel, no extra multiplication.
+ *
+ * @param mulR red shade multiplier including (1-f) (255 = full)
+ * @param mulG green multiplier
+ * @param mulB blue multiplier
+ * @param addR red additive sky term (sky × f)
+ * @param addG green additive term
+ * @param addB blue additive term
+ */
+ public void setHaze(final float mulR, final float mulG,
+ final float mulB, final float addR,
+ final float addG, final float addB) {
+ hazeMulR = mulR;
+ hazeMulG = mulG;
+ hazeMulB = mulB;
+ hazeAddR = addR;
+ hazeAddG = addG;
+ hazeAddB = addB;
+ hazed = true;
+ }
+
+ /** Returns to the haze-free span path (atmosphere off or too near). */
+ public void clearHaze() {
+ hazed = false;
+ }
+
+ /**
+ * Applies the haze blend to a sampled texel, clamped. Called only on
+ * the {@link #hazed} path.
+ */
+ private int shadeHaze(final int texel) {
+ final int r = Math.min(255,
+ (int) (((texel >> 16) & 0xff) * hazeMulR / 255f
+ + hazeAddR));
+ final int g = Math.min(255,
+ (int) (((texel >> 8) & 0xff) * hazeMulG / 255f
+ + hazeAddG));
+ final int b = Math.min(255,
+ (int) ((texel & 0xff) * hazeMulB / 255f + hazeAddB));
+ return (texel & 0xFF000000) | (r << 16) | (g << 8) | b;
+ }
+
// --- ad-hoc frame profiling (-De3d.prof=true; dead code when off)
/** Master switch, constant-folded when false. */
private static final boolean PROF =
}
final int sampledPixel = texPixels[ity * texW + itx];
- final int srcPixel = giShaded ? shadeGi(sampledPixel) : sampledPixel;
+ final int srcPixel = hazed ? shadeHaze(sampledPixel)
+ : giShaded ? shadeGi(sampledPixel) : sampledPixel;
final int srcAlpha = (srcPixel >> 24) & 0xff;
if (srcAlpha == 255) {
@Override
public void paint(final RenderingContext renderBuffer) {
+ // Atmospheric haze (optional, bugreport-20261006-000922):
+ // stamped once per triangle per frame, folded into the same
+ // multiplier the span loops already apply — see MeshTriangle.
+ // LightmappedTriangle flows through here too: it lives inside
+ // the stage-3 bubble a few hundred units out, where the factor
+ // rounds to zero for any practical scale, so composites stay
+ // untouched in practice.
+ if (Atmosphere.enabled()) {
+ final float f = Atmosphere.factor(getZ(renderBuffer));
+ // java.awt.* is wildcard-imported in this file — qualify
+ final eu.svjatoslav.aukio.e3d.renderer.raster.Color sky =
+ f > 0f ? Atmosphere.targetColor(
+ renderBuffer.lightingManager) : null;
+ if (sky == null) {
+ hazed = false;
+ } else {
+ final float att = 1f - f;
+ if (giShaded)
+ setHaze(giShadeR * att, giShadeG * att, giShadeB * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ else
+ setHaze(255f * att, 255f * att, 255f * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ }
+ } else {
+ hazed = false;
+ }
// Near-plane clip output takes precedence: a straddling triangle
// clips to a triangle or a quad (one corner cut off). The quad is
// painted as a 2-triangle fan — the clip of a convex polygon stays
}
final int sampledPixel = texPixels[ity * texW + itx];
- final int srcPixel = giShaded ? shadeGi(sampledPixel) : sampledPixel;
+ final int srcPixel = hazed ? shadeHaze(sampledPixel)
+ : giShaded ? shadeGi(sampledPixel) : sampledPixel;
final int srcAlpha = (srcPixel >> 24) & 0xff;
if (srcAlpha == 255) {
* dedicated GI threads.</p>
*
* <p>Limitations vs object-backed triangles: no mouse picking, no SDF
- * textures (rejected at build), no per-texel lightmaps (GI lands per
- * triangle — the right granularity for game meshes).</p>
+ * textures (rejected at build). Per-texel lightmaps exist only inside
+ * the GI stage-3 radius bubble (see {@link #lightmapAt}); outside it GI
+ * lands per triangle — the right granularity for far game meshes.</p>
*/
public final class TriangleMeshBlock extends AbstractShape {
*/
private volatile float[] giLight;
+ /**
+ * Per-triangle lightmaps, attached lazily by the GI system for
+ * triangles inside the stage-3 radius bubble ({@code
+ * e3d.giStage3Radius}); null slots keep the per-triangle
+ * {@link #giLight} shade as their terminal display. The paint path
+ * switches to the lightmap's composite texture once a real
+ * composite has landed ({@code Lightmap.everComposited}). Null until
+ * the first attach.
+ */
+ private volatile eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap[] lightmaps;
+
/**
* Lazy per-texture average color (albedo source for GI bounce rays),
* keyed by texture because a block's triangles share few textures.
out[i] = (float) world[w + i];
}
+ /**
+ * Copies the triangle's 9 world-space vertex coordinates at full
+ * double precision (GI lightmap construction and cache keys).
+ *
+ * @param tri triangle index
+ * @param out destination array of at least 9 doubles
+ */
+ public void triangleWorld(final int tri, final double[] out) {
+ final int w = tri * 9;
+ System.arraycopy(world, w, out, 0, 9);
+ }
+
+ /**
+ * Copies the triangle's 6 UV coordinates (primary-texture pixels).
+ * Used by the GI system when attaching a lightmap.
+ *
+ * @param tri triangle index
+ * @param out destination array of at least 6 doubles
+ */
+ public void triangleUv(final int tri, final double[] out) {
+ final int u = tri * 6;
+ System.arraycopy(uv, u, out, 0, 6);
+ }
+
+ // ---- per-triangle lightmaps (GI stage 3/4, radius-gated) ----
+
+ /**
+ * The lightmap attached to a triangle, or null when the triangle is
+ * outside the stage-3 bubble (or GI has not reached it yet).
+ *
+ * @param tri triangle index
+ * @return the lightmap or null
+ */
+ public eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap lightmapAt(
+ final int tri) {
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap[] maps =
+ lightmaps;
+ return maps == null ? null : maps[tri];
+ }
+
+ /**
+ * Attaches a lightmap to a triangle unless one is already attached.
+ * Called from GI threads; idempotent and thread-safe.
+ *
+ * @param tri triangle index
+ * @param lightmap the candidate lightmap
+ * @return the lightmap actually attached to the slot (the argument,
+ * or the pre-existing one on a lost race)
+ */
+ public eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap attachLightmapIfAbsent(
+ final int tri,
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap lightmap) {
+ eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap[] maps = lightmaps;
+ if (maps == null) {
+ synchronized (this) {
+ if (lightmaps == null)
+ lightmaps = new eu.svjatoslav.aukio.e3d.renderer.raster
+ .gi.Lightmap[triCount];
+ maps = lightmaps;
+ }
+ }
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap existing =
+ maps[tri];
+ if (existing != null)
+ return existing;
+ synchronized (this) {
+ if (maps[tri] == null)
+ maps[tri] = lightmap;
+ return maps[tri];
+ }
+ }
+
@Override
public Box getBoundingBox() {
return boundingBox;
return camZ[slot][tri * 3 + vertex];
}
- Texture texture(final int tri) {
+ /**
+ * The triangle's base texture (also read by the GI system when it
+ * attaches a lightmap: the composite resamples this texture into
+ * lightmap space).
+ */
+ public Texture texture(final int tri) {
return textures[tri];
}
/**
* Emits one lightmapped triangle for the front side. When the source
- * polygon is two-sided (backface culling off), also emits a plain
- * solid triangle with reversed winding for the back side, and turns
- * culling on for both halves: a lightmap only knows its front side,
- * so without a real back surface the camera would see the front
- * side's light through the polygon (undersides glowing with the
- * top's light). The reversed solid renders with ordinary one-sided
- * direct lighting — correctly dark where the front is lit — and each
- * side's pixels are owned by exactly one surface, so nothing
- * z-fights.
+ * polygon is two-sided (backface culling off), also emits a SECOND
+ * lightmapped triangle with reversed winding for the back side —
+ * its own lightmap with the negated normal — and turns culling on
+ * for both halves: each side's pixels are owned by exactly one
+ * surface, so nothing z-fights, and both sides bake their own
+ * lighting (exteriors catch street lamps and moonlight instead of
+ * showing the interior's light through the wall or staying plain
+ * per-polygon).
*/
private void emitWrapped(final SolidPolygon triangle, final List<AbstractShape> out) {
final LightmappedTriangle front = wrapTriangle(triangle);
return;
}
front.setBackfaceCulling(true);
- final SolidPolygon back = new SolidPolygon(
- triangle.vertices.get(0).coordinate,
- triangle.vertices.get(2).coordinate,
- triangle.vertices.get(1).coordinate,
- triangle.getColor());
- back.setShadingEnabled(triangle.isShadingEnabled());
- back.setBackfaceCulling(true);
- back.setMouseInteractionController(triangle.mouseInteractionController);
out.add(front);
- out.add(back);
+ out.add(wrapReversedTriangle(triangle));
+ }
+
+ /**
+ * Wraps the reversed-winding back side of a two-sided source into
+ * its own lightmapped triangle: the reversed winding makes
+ * {@link #wrapTriangle} compute the negated normal and build the
+ * back side's own lightmap parameterization.
+ */
+ private LightmappedTriangle wrapReversedTriangle(final SolidPolygon polygon) {
+ final SolidPolygon reversed = new SolidPolygon(
+ polygon.vertices.get(0).coordinate,
+ polygon.vertices.get(2).coordinate,
+ polygon.vertices.get(1).coordinate,
+ polygon.getColor());
+ reversed.setBackfaceCulling(true);
+ reversed.setMouseInteractionController(polygon.mouseInteractionController);
+ return wrapTriangle(reversed);
}
/**
--- /dev/null
+package eu.svjatoslav.aukio.e3d.renderer.raster.lighting;
+
+import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
+
+import org.junit.After;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Verifies the atmospheric haze factor math and the in-place color
+ * blend (bugreport-20261006-000922).
+ */
+public class AtmosphereTest {
+
+ @After
+ public void resetOverrides() {
+ Atmosphere.resetOverrides();
+ }
+
+ @Test
+ public void disabledByDefaultOverrideOff() {
+ Atmosphere.setEnabled(false);
+ assertEquals(0f, Atmosphere.factor(1_000_000), 0f);
+ }
+
+ @Test
+ public void factorCurve() {
+ Atmosphere.setEnabled(true);
+ Atmosphere.setScale(100_000);
+ // At the camera and behind it: no haze.
+ assertEquals(0f, Atmosphere.factor(0), 0f);
+ assertEquals(0f, Atmosphere.factor(-50), 0f);
+ // At one scale depth: 1 - 1/e ≈ 0.6321.
+ assertEquals(0.6321f, Atmosphere.factor(100_000), 1e-3f);
+ // At five scale depths: nearly fully hazed.
+ assertEquals(0.9933f, Atmosphere.factor(500_000), 1e-3f);
+ // Monotonic increase.
+ assertTrue(Atmosphere.factor(10_000) < Atmosphere.factor(50_000));
+ assertTrue(Atmosphere.factor(50_000) < Atmosphere.factor(200_000));
+ // Sub-perceptible factors round to zero (bit-identical near path).
+ assertEquals(0f, Atmosphere.factor(1), 0f);
+ }
+
+ @Test
+ public void targetColorPrefersOverrideThenSky() {
+ final LightingManager lighting = new LightingManager();
+ lighting.setSkyColor(Color.hex("7AA3D8"));
+ // No override and no configured color: the scene sky wins.
+ final Color resolved = Atmosphere.targetColor(lighting);
+ assertEquals(0x7A, resolved.r);
+ assertEquals(0xA3, resolved.g);
+ assertEquals(0xD8, resolved.b);
+ // An explicit override wins over the sky.
+ Atmosphere.setColor(Color.hex("C0C0C0"));
+ assertEquals(0xC0, Atmosphere.targetColor(lighting).r);
+ }
+
+ @Test
+ public void applyHazeBlends() {
+ final Color target = new Color(200, 100, 50);
+ // f = 0: unchanged.
+ final Color c0 = new Color(40, 80, 120);
+ Atmosphere.applyHaze(c0, 0f, target);
+ assertEquals(40, c0.r);
+ assertEquals(80, c0.g);
+ assertEquals(120, c0.b);
+ // f = 1: fully the target.
+ final Color c1 = new Color(40, 80, 120);
+ Atmosphere.applyHaze(c1, 1f, target);
+ assertEquals(200, c1.r);
+ assertEquals(100, c1.g);
+ assertEquals(50, c1.b);
+ // f = 0.5: midpoint (rounded).
+ final Color c5 = new Color(40, 80, 120);
+ Atmosphere.applyHaze(c5, 0.5f, target);
+ assertEquals(120, c5.r);
+ assertEquals(90, c5.g);
+ assertEquals(85, c5.b);
+ }
+
+ @Test
+ public void enabledReadsOverride() {
+ Atmosphere.setEnabled(true);
+ assertTrue(Atmosphere.enabled());
+ Atmosphere.setEnabled(false);
+ assertFalse(Atmosphere.enabled());
+ }
+}