ad92dbaae3b02bf915eaa2609614649f5d9877be
[aukio-3d.git] /
1 package eu.svjatoslav.aukio.e3d.renderer.raster.shapes.basic.texturedpolygon;
2
3 import eu.svjatoslav.aukio.e3d.geometry.Box;
4 import eu.svjatoslav.aukio.e3d.geometry.Point2D;
5 import eu.svjatoslav.aukio.e3d.geometry.Point3D;
6 import eu.svjatoslav.aukio.e3d.renderer.raster.HiZPyramid;
7 import eu.svjatoslav.aukio.e3d.renderer.raster.RenderingContext;
8 import eu.svjatoslav.aukio.e3d.renderer.raster.StereoEye;
9 import eu.svjatoslav.aukio.e3d.renderer.raster.RenderAggregator;
10 import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.AbstractShape;
11 import eu.svjatoslav.aukio.e3d.renderer.raster.texture.Texture;
12 import eu.svjatoslav.aukio.e3d.math.TransformStack;
13
14 /**
15  * A block of textured triangles stored as flat primitive arrays
16  * (struct-of-arrays) instead of one object graph per triangle. Built once
17  * (off the render thread), then every frame a single tight loop applies
18  * the composed camera transform to all vertices — sequential memory
19  * access instead of pointer chasing through {@code Vertex}/{@code Point3D}
20  * soup, which is what made the transform phase memory-latency-bound.
21  *
22  * <p>Interaction with the rest of the pipeline is unchanged: each visible
23  * triangle is queued as a thin preallocated {@link MeshTriangle} handle
24  * into the same {@link RenderAggregator}, sorted by the same comparator,
25  * binned into the same tile grid, and painted by the same
26  * {@link TexturedTriangle#paintFlat} core — bit-exact with the
27  * object-backed path.</p>
28  *
29  * <p>Subpixel-cull verdicts are cached per triangle ({@link #cullEpoch}):
30  * while the verdict epoch holds, a culled triangle costs one integer
31  * compare per frame — no vertex math at all.</p>
32  *
33  * <p>Global illumination: the GI system traces block triangles like any
34  * other scene triangle and writes per-triangle light totals (ambient +
35  * direct with shadows + indirect bounce) into {@link #giLight}. The
36  * paint path multiplies texture texels by that per-triangle light; while
37  * no GI system has stamped the block the array is null and painting is
38  * bit-identical to the unlit path. Render-side cost: one array read and
39  * three multiplies per triangle — ray casting happens only on the
40  * dedicated GI threads.</p>
41  *
42  * <p>Limitations vs object-backed triangles: no mouse picking, no SDF
43  * textures (rejected at build), no per-texel lightmaps (GI lands per
44  * triangle — the right granularity for game meshes).</p>
45  */
46 public final class TriangleMeshBlock extends AbstractShape {
47
48     // Build-time geometry: 9 world doubles and 6 UV doubles per triangle.
49     private final double[] world;
50     private final double[] uv;
51     private final Texture[] textures;
52     private final boolean backfaceCull;
53     private final int triCount;
54     private final MeshTriangle[] handles;
55     private final Box boundingBox;
56
57     /**
58      * Per-triangle GI light totals in light units (3 floats per triangle:
59      * r, g, b of ambient + direct-with-shadows + indirect), written by
60      * the global illumination system on its worker threads. Null while no
61      * GI system has taken this block into a snapshot: the paint path then
62      * renders the plain texture, bit-identical to the unlit path. The
63      * array starts filled with 255 (the historical full-texture look), so
64      * enabling GI shows no dark age — estimates glide to the traced
65      * solution near-to-far. Elements are plain floats: painters read them
66      * racily, which is fine for progressively converging values.
67      */
68     private volatile float[] giLight;
69
70     /**
71      * Lazy per-texture average color (albedo source for GI bounce rays),
72      * keyed by texture because a block's triangles share few textures.
73      * Block-lifetime cache; textures are immutable once decoded.
74      */
75     private volatile java.util.IdentityHashMap<Texture,
76             eu.svjatoslav.aukio.e3d.renderer.raster.Color> giAlbedos;
77
78     // Per-slot projected state: 3 screen/camera doubles per triangle per
79     // slot. (Sort Z and binning bounds are published into the handles'
80     // per-slot fields at transform time, not kept here.)
81     private final double[][] projX = new double[3][];
82     private final double[][] projY = new double[3][];
83     private final double[][] camZ = new double[3][];
84
85     // Subpixel-cull verdicts: epoch in which the triangle was found tiny.
86     private final int[] cullEpoch;
87
88     // Near-plane clip output per slot: packed (offset << 3) | count into
89     // clipStore, -1 = not clipped. Clip data is 7 doubles per loop vertex
90     // (camera x, y, z, u, v + screen x, y), at most 4 vertices per
91     // straddler. Sort Z and binning bounds for straddlers are derived
92     // from the store, exactly like the object path derives them from the
93     // clipped loop. clipTtd keeps the ORIGINAL triangle's UV perimeter
94     // per straddler (index = clip offset / 28): mipmap selection must
95     // use the unclipped texel density, exactly like the object path.
96     private static final int CLIP_STRIDE = 7;
97     private static final int CLIP_ENTRY = 4 * CLIP_STRIDE;
98     private final int[][] clipRef = new int[3][];
99     private final double[][] clipStore = new double[3][];
100     private final double[][] clipTtd = new double[3][];
101
102     /** Per-triangle UV perimeter (mipmap metric), computed once at build:
103      * the uv array never changes afterwards. Same expression and
104      * accumulation order as {@code TexturedTriangle}'s
105      * computeTotalTextureDistance: d(0,1) + d(0,2) + d(1,2). */
106     private final double[] uvPerimeter;
107
108     /** Per-triangle screen-edge perimeter (mipmap metric's visible side),
109      * computed once per slot in the transform loop — identical expression
110      * to what the paint core used to recompute per tile. */
111     private final double[][] screenPerim = new double[3][];
112     private final int[] clipUsed = new int[3];
113
114     // Scratch for the composed top transform of the current transform call.
115     private final double[] top = new double[12];
116
117     /**
118      * Builds a block from baked world-space triangle soup.
119      *
120      * @param world         9 doubles per triangle (x0,y0,z0,x1,...), world
121      *                      space; the array is adopted, not copied
122      * @param uv            6 doubles per triangle (u0,v0,...) in primary
123      *                      texture pixels; adopted
124      * @param textures      one texture per triangle
125      * @param backfaceCull  cull clockwise triangles on screen
126      */
127     public TriangleMeshBlock(final double[] world, final double[] uv,
128                              final Texture[] textures,
129                              final boolean backfaceCull) {
130         this.triCount = textures.length;
131         if (world.length != triCount * 9 || uv.length != triCount * 6)
132             throw new IllegalArgumentException("array length mismatch");
133         this.world = world;
134         this.uv = uv;
135         this.textures = textures;
136         this.backfaceCull = backfaceCull;
137         for (final Texture texture : textures)
138             if (texture != null && texture.isSdf())
139                 throw new IllegalArgumentException(
140                         "SDF textures are not supported in mesh blocks");
141
142         this.handles = new MeshTriangle[triCount];
143         for (int t = 0; t < triCount; t++)
144             handles[t] = new MeshTriangle(this, t, textures[t]);
145
146         this.cullEpoch = new int[triCount];
147         java.util.Arrays.fill(cullEpoch, -1);
148
149         for (int s = 0; s < 3; s++) {
150             projX[s] = new double[triCount * 3];
151             projY[s] = new double[triCount * 3];
152             camZ[s] = new double[triCount * 3];
153             clipRef[s] = new int[triCount];
154             java.util.Arrays.fill(clipRef[s], -1);
155             clipStore[s] = new double[256];
156             clipTtd[s] = new double[16];
157             screenPerim[s] = new double[triCount];
158         }
159
160         uvPerimeter = new double[triCount];
161         for (int t = 0; t < triCount; t++) {
162             final int u = t * 6;
163             final double d1 = Math.sqrt(
164                     ((uv[u] - uv[u + 2]) * (uv[u] - uv[u + 2]))
165                             + ((uv[u + 1] - uv[u + 3]) * (uv[u + 1] - uv[u + 3])));
166             final double d2 = Math.sqrt(
167                     ((uv[u] - uv[u + 4]) * (uv[u] - uv[u + 4]))
168                             + ((uv[u + 1] - uv[u + 5]) * (uv[u + 1] - uv[u + 5])));
169             final double d3 = Math.sqrt(
170                     ((uv[u + 2] - uv[u + 4]) * (uv[u + 2] - uv[u + 4]))
171                             + ((uv[u + 3] - uv[u + 5]) * (uv[u + 3] - uv[u + 5])));
172             uvPerimeter[t] = d1 + d2 + d3;
173         }
174
175         double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE,
176                 minZ = Double.MAX_VALUE;
177         double maxX = -Double.MAX_VALUE, maxY = -Double.MAX_VALUE,
178                 maxZ = -Double.MAX_VALUE;
179         for (int i = 0; i < world.length; i += 3) {
180             if (world[i] < minX) minX = world[i];
181             if (world[i] > maxX) maxX = world[i];
182             if (world[i + 1] < minY) minY = world[i + 1];
183             if (world[i + 1] > maxY) maxY = world[i + 1];
184             if (world[i + 2] < minZ) minZ = world[i + 2];
185             if (world[i + 2] > maxZ) maxZ = world[i + 2];
186         }
187         boundingBox = new Box(new Point3D(minX, minY, minZ),
188                 new Point3D(maxX, maxY, maxZ));
189     }
190
191     public int triCount() {
192         return triCount;
193     }
194
195     // ---- global illumination integration (engine-internal) ----
196
197     /**
198      * Allocates and publishes the per-triangle GI light array if absent
199      * (called by the GI system when this block enters a scene snapshot).
200      * Fresh arrays start at 255 per channel — the historical full-texture
201      * look — so enabling GI shows no dark age before the first estimates
202      * land. Idempotent and thread-safe.
203      */
204     public void ensureGiLight() {
205         if (giLight == null) {
206             synchronized (this) {
207                 if (giLight == null) {
208                     final float[] array = new float[triCount * 3];
209                     java.util.Arrays.fill(array, 255f);
210                     giLight = array;
211                 }
212             }
213         }
214     }
215
216     /**
217      * Writes one triangle's GI light total (light units, may exceed 255 —
218      * the paint path clamps). Called from GI worker threads only, and only
219      * after {@link #ensureGiLight()}.
220      */
221     public void setGiLight(final int tri, final float r, final float g,
222                            final float b) {
223         final float[] array = giLight;
224         if (array == null)
225             return;
226         final int i = tri * 3;
227         array[i] = r;
228         array[i + 1] = g;
229         array[i + 2] = b;
230     }
231
232     /**
233      * The per-triangle GI light array (3 floats per triangle), or null
234      * when no GI system has stamped this block — the paint path then
235      * renders the plain texture.
236      *
237      * @return the light array or null
238      */
239     public float[] giLight() {
240         return giLight;
241     }
242
243     /**
244      * Average color of the triangle's texture (albedo for GI bounce
245      * rays), sampled from the primary bitmap on a coarse stride and
246      * cached per texture. Cost is paid once per distinct texture, not
247      * per triangle.
248      *
249      * @param tri triangle index
250      * @return the average texture color
251      */
252     public eu.svjatoslav.aukio.e3d.renderer.raster.Color albedo(final int tri) {
253         final Texture texture = textures[tri];
254         if (texture == null)
255             return new eu.svjatoslav.aukio.e3d.renderer.raster.Color(128, 128, 128);
256         java.util.IdentityHashMap<Texture,
257                 eu.svjatoslav.aukio.e3d.renderer.raster.Color> cache = giAlbedos;
258         if (cache == null) {
259             synchronized (this) {
260                 if (giAlbedos == null)
261                     giAlbedos = new java.util.IdentityHashMap<>();
262                 cache = giAlbedos;
263             }
264         }
265         synchronized (cache) {
266             final eu.svjatoslav.aukio.e3d.renderer.raster.Color cached =
267                     cache.get(texture);
268             if (cached != null)
269                 return cached;
270             final int[] pixels = texture.primaryBitmap.pixels;
271             // Coarse stride: ~2000 samples are plenty for an average.
272             final int stride = Math.max(1, pixels.length / 2048);
273             long r = 0, g = 0, b = 0;
274             int n = 0;
275             for (int i = 0; i < pixels.length; i += stride) {
276                 final int px = pixels[i];
277                 r += (px >> 16) & 0xff;
278                 g += (px >> 8) & 0xff;
279                 b += px & 0xff;
280                 n++;
281             }
282             final eu.svjatoslav.aukio.e3d.renderer.raster.Color average =
283                     new eu.svjatoslav.aukio.e3d.renderer.raster.Color(
284                             (int) (r / n), (int) (g / n), (int) (b / n));
285             cache.put(texture, average);
286             return average;
287         }
288     }
289
290     /**
291      * Copies the triangle's 9 world-space vertex coordinates into
292      * {@code out} (x0,y0,z0, x1,y1,z1, x2,y2,z2). Used by the GI system
293      * at snapshot build.
294      *
295      * @param tri triangle index
296      * @param out destination array of at least 9 floats
297      */
298     public void triangleVertices(final int tri, final float[] out) {
299         final int w = tri * 9;
300         for (int i = 0; i < 9; i++)
301             out[i] = (float) world[w + i];
302     }
303
304     @Override
305     public Box getBoundingBox() {
306         return boundingBox;
307     }
308
309     @Override
310     public int getTransformWeight(final RenderingContext renderingContext) {
311         return Math.max(1, triCount);
312     }
313
314     /**
315      * Transforms every triangle of the block with the composed top
316      * transform of the stack (hoisted out of the loop), culls (near
317      * plane, subpixel with verdict cache, viewport) and queues a thin
318      * handle per surviving triangle. All expressions replicate
319      * {@code TransformStack.transform} /
320      * {@code Vertex.calculateLocationRelativeToViewer} exactly, so output
321      * is bit-identical with the object-backed path.
322      */
323     @Override
324     public void transform(final TransformStack transforms,
325                           final RenderAggregator aggregator,
326                           final RenderingContext renderingContext) {
327         final int slot = renderingContext.vertexSlot;
328         final double[] px = projX[slot];
329         final double[] py = projY[slot];
330         final double[] cz = camZ[slot];
331         final int[] cref = clipRef[slot];
332         clipUsed[slot] = 0;
333
334         transforms.getTopTransform(top);
335         final double r0 = top[0], r1 = top[1], r2 = top[2];
336         final double r3 = top[3], r4 = top[4], r5 = top[5];
337         final double r6 = top[6], r7 = top[7], r8 = top[8];
338         final double t0 = top[9], t1 = top[10], t2 = top[11];
339
340         final double near = renderingContext.nearPlaneDistance;
341         final double scale = renderingContext.projectionScale;
342         final double centerX = renderingContext.centerCoordinate.x;
343         final double centerY = renderingContext.centerCoordinate.y;
344         final double stereo = renderingContext.stereoViewportOffsetX;
345
346         // Hi-Z whole-block occlusion: test the world AABB against last
347         // frame's depth pyramid before touching a single triangle.
348         // Skipped in stereo (the pyramid is mono-view) and whenever a
349         // corner crosses the near plane (its projection is unreliable).
350         final HiZPyramid hiz = renderingContext.occlusionPyramid;
351         if (hiz != null
352                 && renderingContext.stereoEye == StereoEye.NONE) {
353             hiz.blocksTested.incrementAndGet();
354             final Point3D lo = boundingBox.p1, hi = boundingBox.p2;
355             double ax1 = Double.MAX_VALUE, ay1 = Double.MAX_VALUE;
356             double ax2 = -Double.MAX_VALUE, ay2 = -Double.MAX_VALUE;
357             double nearestW = -Double.MAX_VALUE;
358             boolean usable = true;
359             for (int c = 0; c < 8; c++) {
360                 final double wx = (c & 1) != 0 ? hi.x : lo.x;
361                 final double wy = (c & 2) != 0 ? hi.y : lo.y;
362                 final double wz = (c & 4) != 0 ? hi.z : lo.z;
363                 final double ccz = r6 * wx + r7 * wy + r8 * wz + t2;
364                 if (ccz <= near) {
365                     usable = false;
366                     break;
367                 }
368                 final double ccx = r0 * wx + r1 * wy + r2 * wz + t0;
369                 final double ccy = r3 * wx + r4 * wy + r5 * wz + t1;
370                 final double sx = ((ccx / ccz) * scale) + centerX + stereo;
371                 final double sy = ((ccy / ccz) * scale) + centerY;
372                 if (sx < ax1) ax1 = sx;
373                 if (sx > ax2) ax2 = sx;
374                 if (sy < ay1) ay1 = sy;
375                 if (sy > ay2) ay2 = sy;
376                 final double w = 1d / ccz;
377                 if (w > nearestW) nearestW = w;
378             }
379             if (usable && ax1 <= ax2 && ay1 <= ay2
380                     && hiz.occluded(ax1, ay1, ax2, ay2, nearestW)) {
381                 hiz.blocksCulled.incrementAndGet();
382                 return;
383             }
384         }
385         final double cullThreshold = renderingContext.subpixelCullingThreshold;
386         final int epoch = renderingContext.subpixelCullingEpoch;
387         final double rMinX = renderingContext.renderMinX;
388         final double rMaxX = renderingContext.renderMaxX;
389         final double rMinY = renderingContext.renderMinY;
390         final double rMaxY = renderingContext.renderMaxY;
391
392         for (int t = 0; t < triCount; t++) {
393             if (cullThreshold > 0 && cullEpoch[t] == epoch)
394                 continue;
395
396             final int w = t * 9;
397             // Same expression order as TransformStack.transform.
398             final double x0 = world[w], y0 = world[w + 1], z0 = world[w + 2];
399             final double cx0 = r0 * x0 + r1 * y0 + r2 * z0 + t0;
400             final double cy0 = r3 * x0 + r4 * y0 + r5 * z0 + t1;
401             final double cz0 = r6 * x0 + r7 * y0 + r8 * z0 + t2;
402             final double x1 = world[w + 3], y1 = world[w + 4], z1 = world[w + 5];
403             final double cx1 = r0 * x1 + r1 * y1 + r2 * z1 + t0;
404             final double cy1 = r3 * x1 + r4 * y1 + r5 * z1 + t1;
405             final double cz1 = r6 * x1 + r7 * y1 + r8 * z1 + t2;
406             final double x2 = world[w + 6], y2 = world[w + 7], z2 = world[w + 8];
407             final double cx2 = r0 * x2 + r1 * y2 + r2 * z2 + t0;
408             final double cy2 = r3 * x2 + r4 * y2 + r5 * z2 + t1;
409             final double cz2 = r6 * x2 + r7 * y2 + r8 * z2 + t2;
410
411             final boolean in0 = cz0 > near;
412             final boolean in1 = cz1 > near;
413             final boolean in2 = cz2 > near;
414
415             if (!in0 && !in1 && !in2) {
416                 cref[t] = -1;
417                 continue;
418             }
419
420             final int v = t * 3;
421             if (!(in0 && in1 && in2)) {
422                 clipAndQueue(t, v, slot, cx0, cy0, cz0, cx1, cy1, cz1,
423                         cx2, cy2, cz2, in0, in1, in2, near, cref,
424                         aggregator, renderingContext);
425                 continue;
426             }
427
428             cref[t] = -1;
429             cz[v] = cz0;
430             cz[v + 1] = cz1;
431             cz[v + 2] = cz2;
432             // Same expression order as
433             // Vertex.calculateLocationRelativeToViewer (divide, scale,
434             // add center, add stereo offset).
435             final double sx0 = ((cx0 / cz0) * scale) + centerX + stereo;
436             final double sy0 = ((cy0 / cz0) * scale) + centerY;
437             final double sx1 = ((cx1 / cz1) * scale) + centerX + stereo;
438             final double sy1 = ((cy1 / cz1) * scale) + centerY;
439             final double sx2 = ((cx2 / cz2) * scale) + centerX + stereo;
440             final double sy2 = ((cy2 / cz2) * scale) + centerY;
441             px[v] = sx0;
442             py[v] = sy0;
443             px[v + 1] = sx1;
444             py[v + 1] = sy1;
445             px[v + 2] = sx2;
446             py[v + 2] = sy2;
447             final double triZ = (cz0 + cz1 + cz2) / 3;
448
449             final double minX = Math.min(sx0, Math.min(sx1, sx2));
450             final double maxX = Math.max(sx0, Math.max(sx1, sx2));
451             final double minY = Math.min(sy0, Math.min(sy1, sy2));
452             final double maxY = Math.max(sy0, Math.max(sy1, sy2));
453
454             // Publish the same per-slot state an object-backed triangle
455             // would have written (paint margins are 0 for mesh tris):
456             // comparator and tile binning then read plain fields.
457             handles[t].publishSlotState(slot, triZ, minY, maxY, minX, maxX);
458
459             // Subpixel verdict with per-triangle cache (same raw-span
460             // semantics as AbstractCoordinateShape).
461             if (cullThreshold > 0
462                     && maxX - minX < cullThreshold
463                     && maxY - minY < cullThreshold) {
464                 cullEpoch[t] = epoch;
465                 continue;
466             }
467
468             // Viewport cull (paint margins are 0 for mesh triangles).
469             if (maxX < rMinX || minX >= rMaxX || maxY < rMinY || minY >= rMaxY)
470                 continue;
471
472             // Mipmap metric's visible side, once per slot instead of per
473             // tile: edge12 + edge13 + edge23, the same expression the
474             // paint core ran per tile (getDistanceTo sequence).
475             final double dx01 = sx0 - sx1, dy01 = sy0 - sy1;
476             final double dx02 = sx0 - sx2, dy02 = sy0 - sy2;
477             final double dx12 = sx1 - sx2, dy12 = sy1 - sy2;
478             screenPerim[slot][t] = Math.sqrt(dx01 * dx01 + dy01 * dy01)
479                     + Math.sqrt(dx02 * dx02 + dy02 * dy02)
480                     + Math.sqrt(dx12 * dx12 + dy12 * dy12);
481
482             aggregator.queueShapeForRendering(handles[t]);
483         }
484     }
485
486     /**
487      * Near-plane clip for one straddling triangle, Sutherland-Hodgman
488      * over the three edges with the exact interpolation expressions of
489      * {@code AbstractCoordinateShape.interpolateAtPlane}. Output goes to
490      * the slot's grow-only clip store; the handle is queued with a packed
491      * reference.
492      */
493     private void clipAndQueue(final int t, final int v, final int slot,
494                               final double cx0, final double cy0, final double cz0,
495                               final double cx1, final double cy1, final double cz1,
496                               final double cx2, final double cy2, final double cz2,
497                               final boolean in0, final boolean in1, final boolean in2,
498                               final double near, final int[] cref,
499                               final RenderAggregator aggregator,
500                               final RenderingContext renderingContext) {
501         double[] store = clipStore[slot];
502         int used = clipUsed[slot];
503         if (used + CLIP_ENTRY > store.length) {
504             final double[] grown = new double[store.length * 2];
505             System.arraycopy(store, 0, grown, 0, used);
506             store = grown;
507             clipStore[slot] = grown;
508             final double[] grownTtd = new double[grown.length / CLIP_ENTRY];
509             System.arraycopy(clipTtd[slot], 0, grownTtd, 0, clipTtd[slot].length);
510             clipTtd[slot] = grownTtd;
511         }
512         final int base = used;
513         clipTtd[slot][base / CLIP_ENTRY] = uvPerimeter[t];
514
515         final double scale = renderingContext.projectionScale;
516         final double centerX = renderingContext.centerCoordinate.x;
517         final double centerY = renderingContext.centerCoordinate.y;
518         final double stereo = renderingContext.stereoViewportOffsetX;
519
520         final double[] cx = {cx0, cx1, cx2};
521         final double[] cy = {cy0, cy1, cy2};
522         final double[] czz = {cz0, cz1, cz2};
523         final boolean[] in = {in0, in1, in2};
524         final int uvi = t * 6;
525
526         int n = 0;
527         double sumZ = 0;
528         for (int i = 0; i < 3; i++) {
529             final int j = (i + 1) % 3;
530             final boolean currentIn = in[i];
531             final boolean nextIn = in[j];
532             if (currentIn) {
533                 store[used++] = cx[i];
534                 store[used++] = cy[i];
535                 store[used++] = czz[i];
536                 store[used++] = uv[uvi + i * 2];
537                 store[used++] = uv[uvi + i * 2 + 1];
538                 // setCameraSpaceCoordinate expression, same order
539                 store[used++] = ((cx[i] / czz[i]) * scale) + centerX + stereo;
540                 store[used++] = ((cy[i] / czz[i]) * scale) + centerY;
541                 n++;
542                 sumZ += czz[i];
543             }
544             if (currentIn != nextIn) {
545                 final double tt = (near - czz[i]) / (czz[j] - czz[i]);
546                 final double ix = cx[i] + (cx[j] - cx[i]) * tt;
547                 final double iy = cy[i] + (cy[j] - cy[i]) * tt;
548                 final double iz = czz[i] + (czz[j] - czz[i]) * tt;
549                 store[used++] = ix;
550                 store[used++] = iy;
551                 store[used++] = iz;
552                 store[used++] = uv[uvi + i * 2]
553                         + (uv[uvi + j * 2] - uv[uvi + i * 2]) * tt;
554                 store[used++] = uv[uvi + i * 2 + 1]
555                         + (uv[uvi + j * 2 + 1] - uv[uvi + i * 2 + 1]) * tt;
556                 store[used++] = ((ix / iz) * scale) + centerX + stereo;
557                 store[used++] = ((iy / iz) * scale) + centerY;
558                 n++;
559                 sumZ += iz;
560             }
561         }
562
563         // Degenerate sliver: fewer loop points than a renderable triangle.
564         if (n < 3) {
565             cref[t] = -1;
566             return;
567         }
568         clipUsed[slot] = used;
569         cref[t] = (base << 3) | n;
570         // Object path averages Z and derives bounds over the clipped loop
571         double cMinX = Double.MAX_VALUE, cMaxX = -Double.MAX_VALUE;
572         double cMinY = Double.MAX_VALUE, cMaxY = -Double.MAX_VALUE;
573         for (int i = 0; i < n; i++) {
574             final double sx = store[base + i * CLIP_STRIDE + 5];
575             final double sy = store[base + i * CLIP_STRIDE + 6];
576             if (sx < cMinX) cMinX = sx;
577             if (sx > cMaxX) cMaxX = sx;
578             if (sy < cMinY) cMinY = sy;
579             if (sy > cMaxY) cMaxY = sy;
580         }
581         handles[t].publishSlotState(slot, sumZ / n, cMinY, cMaxY, cMinX, cMaxX);
582         aggregator.queueShapeForRendering(handles[t]);
583     }
584
585     // ---- handle-facing accessors (package-private) ----
586
587     double camZ(final int slot, final int tri, final int vertex) {
588         return camZ[slot][tri * 3 + vertex];
589     }
590
591     Texture texture(final int tri) {
592         return textures[tri];
593     }
594
595     boolean backfaceCull() {
596         return backfaceCull;
597     }
598
599     int clipOffset(final int slot, final int tri) {
600         final int ref = clipRef[slot][tri];
601         return ref < 0 ? -1 : ref >> 3;
602     }
603
604     int clipCount(final int slot, final int tri) {
605         return clipRef[slot][tri] & 7;
606     }
607
608     double[] clipStore(final int slot) {
609         return clipStore[slot];
610     }
611
612     double clipTtd(final int slot, final int clipOffset) {
613         return clipTtd[slot][clipOffset / CLIP_ENTRY];
614     }
615
616     /** The triangle's UV perimeter, precomputed at build (see field). */
617     double uvPerimeter(final int tri) {
618         return uvPerimeter[tri];
619     }
620
621     /**
622      * The triangle's screen-edge perimeter for this slot, precomputed in
623      * the transform loop (only valid for triangles queued unclipped).
624      */
625     double screenPerim(final int slot, final int tri) {
626         return screenPerim[slot][tri];
627     }
628
629     /**
630      * Loads one unclipped triangle vertex (screen + UV) into the scratch
631      * carriers, values exactly as computed at transform time.
632      */
633     void loadScreenVertex(final Point2D screen, final Point2D uvOut,
634                           final int slot, final int tri, final int vertex,
635                           final RenderingContext ctx) {
636         final int v = tri * 3 + vertex;
637         screen.x = projX[slot][v];
638         screen.y = projY[slot][v];
639         uvOut.x = uv[tri * 6 + vertex * 2];
640         uvOut.y = uv[tri * 6 + vertex * 2 + 1];
641     }
642 }