+ /**
+ * 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);
+ }
+