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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions desktop/src/__tests__/hologram-display-correction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ function fixture(reducedMotion: boolean) {
}

describe('display collision correction in the production frame',()=>{
it('keeps the accepted correction camera fixed after a subthreshold camera settle',()=>{
const f=fixture(false),{h,camera}=f;
try {
h.desiredCamera.z+=.0005;h.desiredLookAt.x+=.0003;
const prepare=h.prepareDisplayCorrection.bind(h);let accepted:number[]|null=null;
h.prepareDisplayCorrection=()=>{accepted=camera.matrixWorld.toArray();prepare();};
h.displayRelaxationPending=true;h.render(1/60);
expect(accepted).not.toBeNull();
for(let i=0;i<180;i++){h.render(1/60);if(!h.displayTransition.moving)break;}
expect(h.displayTransition.moving).toBe(false);
expect(camera.matrixWorld.toArray()).toEqual(accepted);
}finally{f.dispose();}
});

it('keeps emergency state latched and returns to idle after a visible redraw',()=>{
const f=fixture(false),{h}=f;
const callbacks=new Map<number,FrameRequestCallback>();let serial=0,now=0;
Expand Down
34 changes: 34 additions & 0 deletions desktop/src/__tests__/projected-relaxation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,37 @@ describe('dense viewports keep core separation ahead of optional whitespace',()=
expect(diagnostics.pairTests).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.pairTests);
});
});

describe('candidate admission and fixed geometry work',()=>{
const points=()=>Array.from({length:2048},()=>({x:320,y:240,radius:1.6}));
class CountedPins extends Set<number>{
calls=0;
override has(value:number){this.calls++;return super.has(value);}
}
it('retains all fixed offsets without quadratically querying fixed memberships',()=>{
const input=points(),fixed=new CountedPins(input.map((_,i)=>i)),prior=new Float64Array(input.length*2);
prior[14]=4;prior[15]=-2;
const r=relaxProjectedCircles(input,viewport,fixed,prior);
expect([...r.offsets]).toEqual([...prior]);
expect(fixed.calls).toBeLessThanOrEqual(input.length);
expect(r.diagnostics.pairTests).toBe(0);
expect(r.diagnostics.candidateVisits).toBe(0);
});
it('bounds traversal with only two movable points and preserves immutable pins',()=>{
const input=points(),fixed=new CountedPins(Array.from({length:2046},(_,i)=>i));
const r=relaxProjectedCircles(input,viewport,fixed);
expect(fixed.calls).toBeLessThanOrEqual(input.length);
expect([...r.offsets.slice(0,4092)].every(value=>value===0)).toBe(true);
expect([...r.offsets].every(Number.isFinite)).toBe(true);
expect(r.diagnostics.candidateVisits).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.candidateVisits);
expect(r.diagnostics.pairTests).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.pairTests);
});
it('reports bounded partial work instead of treating skipped traversal as free',()=>{
const r=relaxProjectedCircles(points(),viewport);
expect(r.diagnostics.candidateVisits).toBeGreaterThan(0);
expect(r.diagnostics.candidateVisits).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.candidateVisits);
expect(r.diagnostics.pairTests).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.pairTests);
expect(r.diagnostics.budgetExhausted).toBe(true);
expect([...r.offsets].every(Number.isFinite)).toBe(true);
});
});
10 changes: 9 additions & 1 deletion desktop/src/knowledge/hologram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1142,6 +1142,14 @@ export class KnowledgeHologram {
||this.lookAt.distanceToSquared(this.desiredLookAt)>0||this.orbitActive;
const alpha=this.reducedMotionEnabled||this.paused?1:1-Math.exp(-12*elapsed);
this.camera.position.lerp(this.desiredCamera,alpha);this.lookAt.lerp(this.desiredLookAt,alpha);
const cameraRestDistanceSquared=0.000001;
// A correction accepted as stationary must keep the same camera while its
// offsets animate. Otherwise subthreshold interpolation moves the cores
// away from the screen-space constraints that were just solved.
if(!this.orbitActive){
if(this.camera.position.distanceToSquared(this.desiredCamera)<=cameraRestDistanceSquared)this.camera.position.copy(this.desiredCamera);
if(this.lookAt.distanceToSquared(this.desiredLookAt)<=cameraRestDistanceSquared)this.lookAt.copy(this.desiredLookAt);
}
this.camera.lookAt(this.lookAt);this.orbit.target.copy(this.lookAt);this.orbit.update();
this.camera.updateMatrixWorld(true);

Expand All @@ -1154,7 +1162,7 @@ export class KnowledgeHologram {
// Include perspective motion from depth changes at the viewport corners.
const perspectiveBound = Math.hypot(1, halfFovTangent * Math.hypot(1, this.camera.aspect));
const denseOverview=this.view.hops===0&&this.view.nodes.length>120;
const cameraMoving=this.camera.position.distanceToSquared(this.desiredCamera)>0.000001||this.lookAt.distanceToSquared(this.desiredLookAt)>0.000001;
const cameraMoving=this.camera.position.distanceToSquared(this.desiredCamera)>cameraRestDistanceSquared||this.lookAt.distanceToSquared(this.desiredLookAt)>cameraRestDistanceSquared;
this.plasticity.setDisplayScale(2 * nearestDepth * halfFovTangent / (Math.max(1, this.viewport.height) * perspectiveBound
* (denseOverview?OVERVIEW_DISPLAY_GAIN:1)));
const pointsMoving = this.plasticity.moving || this.positionTransition.moving;
Expand Down
68 changes: 45 additions & 23 deletions desktop/src/knowledge/projected-relaxation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { ProjectedCircle, ProjectionViewport } from './projected-layout-metrics';

export const PROJECTED_RELAXATION_LIMITS = Object.freeze({ nodes: 2048, passes: 16, pairTests: 131072, shiftCssPx: 10, gapCssPx: 4.5 });
export const PROJECTED_RELAXATION_LIMITS = Object.freeze({ nodes: 2048, passes: 32, gapPasses: 8, pairTests: 131072, candidateVisits: 524288, shiftCssPx: 10, gapCssPx: 4.5 });
export interface RelaxationResult {
offsets: Float64Array;
diagnostics: { nodes: number; passes: number; effectiveGapCssPx:number; pairTests: number; corePairTests:number; gapPairTests:number; coreContacts:number; moved: number; maxShift: number; budgetExhausted: boolean; inputTruncated: boolean };
diagnostics: { nodes: number; passes: number; effectiveGapCssPx:number; candidateVisits:number; candidateBudgetExhausted:boolean; pairTests: number; corePairTests:number; gapPairTests:number; coreContacts:number; moved: number; maxShift: number; budgetExhausted: boolean; inputTruncated: boolean };
}

/** Bounded display-only offsets. No identities, edges, source coordinates or
Expand All @@ -12,25 +12,27 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor
pinned: ReadonlySet<number> = new Set(), initialOffsets?: Float64Array): RelaxationResult {
const limits = PROJECTED_RELAXATION_LIMITS, count = Math.min(input.length, limits.nodes);
const offsets = new Float64Array(count * 2), x = new Float64Array(count), y = new Float64Array(count);
const active = new Uint8Array(count), dx = new Float64Array(count), dy = new Float64Array(count);
const diagnostics = { nodes: count, passes: 0, effectiveGapCssPx:0, pairTests: 0, corePairTests:0, gapPairTests:0, coreContacts:0, moved: 0, maxShift: 0,
const active = new Uint8Array(count), fixed = new Uint8Array(count), dx = new Float64Array(count), dy = new Float64Array(count);
const diagnostics = { nodes: count, passes: 0, effectiveGapCssPx:0, candidateVisits:0, candidateBudgetExhausted:false, pairTests: 0, corePairTests:0, gapPairTests:0, coreContacts:0, moved: 0, maxShift: 0,
budgetExhausted: false, inputTruncated: input.length > count };
const { left, top, width, height } = viewport;
if (![left,top,width,height].every(Number.isFinite) || width <= 0 || height <= 0) return { offsets, diagnostics };
let maxRadius = 0, retainedCorrection = false;
let maxRadius = 0, movableCount = 0, retainedCorrection = false;
for (let i = 0; i < count; i++) {
const p = input[i]; x[i] = p.x; y[i] = p.y;
if (![p.x,p.y,p.radius].every(Number.isFinite) || p.radius <= 0 || p.inClipVolume === false
|| p.x < left || p.x > left + width || p.y < top || p.y > top + height
|| p.radius * 2 > width || p.radius * 2 > height) continue;
active[i] = 1; maxRadius = Math.max(maxRadius, p.radius);
active[i] = 1; fixed[i] = Number(pinned.has(i));
if (!fixed[i]) movableCount++;
maxRadius = Math.max(maxRadius, p.radius);
if (initialOffsets?.length === count * 2) {
const ox = initialOffsets[i*2], oy = initialOffsets[i*2+1], size = Math.hypot(ox,oy);
if (Number.isFinite(size)) {
if (size > 0) retainedCorrection = true;
const gain = size > limits.shiftCssPx ? limits.shiftCssPx / size : 1;
x[i] = pinned.has(i) ? p.x + ox * gain : Math.max(left + p.radius,Math.min(left + width - p.radius,p.x + ox * gain));
y[i] = pinned.has(i) ? p.y + oy * gain : Math.max(top + p.radius,Math.min(top + height - p.radius,p.y + oy * gain));
x[i] = fixed[i] ? p.x + ox * gain : Math.max(left + p.radius,Math.min(left + width - p.radius,p.x + ox * gain));
y[i] = fixed[i] ? p.y + oy * gain : Math.max(top + p.radius,Math.min(top + height - p.radius,p.y + oy * gain));
}
}
}
Expand All @@ -39,10 +41,12 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor
// source/semantic distance or a guarantee that every packing is feasible.
const gap = Math.min(limits.gapCssPx,Math.sqrt(width*height/Math.max(1,visibleCount))*.1);
diagnostics.effectiveGapCssPx = gap;
for (let pass = 0; pass < limits.passes; pass++) {
for (let pass = 0; movableCount > 0 && pass < limits.passes; pass++) {
if (diagnostics.pairTests >= limits.pairTests || diagnostics.candidateVisits >= limits.candidateVisits) break;
dx.fill(0); dy.fill(0);
const budget = Math.floor((limits.pairTests - diagnostics.pairTests) / (limits.passes - pass));
let tested = 0, contacts = 0, coreContacts = 0;
const visitBudget = Math.floor((limits.candidateVisits - diagnostics.candidateVisits) / (limits.passes - pass));
let tested = 0, visited = 0, contacts = 0, coreContacts = 0, passCutoff = false;
const accumulate = (gap:number, core:boolean) => {
const cellSize = Math.max(1, maxRadius * 2 + gap);
const columns = Math.ceil(width / cellSize) + 3;
Expand All @@ -54,12 +58,23 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor
}
outer: for (let slot = 0; slot < count; slot++) {
const a = (slot + pass * 257) % count;
if (!active[a]) continue;
// A fixed point never needs its own query. Its contacts are visited by
// movable neighbors, including neighbors with a larger original index.
if (!active[a] || fixed[a]) continue;
const cx = Math.floor((x[a] - left) / cellSize), cy = Math.floor((y[a] - top) / cellSize);
for (let gx = cx - 1; gx <= cx + 1; gx++) for (let gy = cy - 1; gy <= cy + 1; gy++)
for (const b of grid.get(gy * columns + gx) ?? []) {
if (b <= a || pinned.has(a) && pinned.has(b)) continue;
if (tested >= budget) { diagnostics.budgetExhausted = true; break outer; }
for (let gx = cx - 1; gx <= cx + 1; gx++) for (let gy = cy - 1; gy <= cy + 1; gy++) {
const cell = grid.get(gy * columns + gx);
if (!cell) continue;
for (let k = 0; k < cell.length; k++) {
// Admit a cell entry before reading it, including duplicate/self
// entries that will not cause a distance calculation.
if (visited >= visitBudget) {
diagnostics.budgetExhausted = diagnostics.candidateBudgetExhausted = passCutoff = true;
break outer;
}
const b = cell[k]; visited++; diagnostics.candidateVisits++;
if (b === a || b < a && !fixed[b]) continue;
if (tested >= budget) { diagnostics.budgetExhausted = passCutoff = true; break outer; }
tested++; diagnostics.pairTests++;
if(core)diagnostics.corePairTests++;else diagnostics.gapPairTests++;
let vx = x[a] - x[b], vy = y[a] - y[b], distance = Math.hypot(vx, vy);
Expand All @@ -68,25 +83,32 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor
if (distance >= (core ? radii : separation)) continue;
contacts++;if(core){coreContacts++;diagnostics.coreContacts++;}
if (distance < 1e-9) {
const angle = ((Math.imul(a + 1, 2654435761) ^ Math.imul(b + 1, 1597334677)) >>> 0) / 4294967296 * Math.PI * 2;
vx = Math.cos(angle); vy = Math.sin(angle); distance = 1;
const first=Math.min(a,b),second=Math.max(a,b),sign=a<b?1:-1;
const angle = ((Math.imul(first + 1, 2654435761) ^ Math.imul(second + 1, 1597334677)) >>> 0) / 4294967296 * Math.PI * 2;
vx = Math.cos(angle)*sign; vy = Math.sin(angle)*sign;
} else { vx /= distance; vy /= distance; }
const amount = Math.max(.1, separation - Math.hypot(x[a]-x[b],y[a]-y[b])) * .55;
const share = pinned.has(a) || pinned.has(b) ? 1 : .5;
if (!pinned.has(a)) { dx[a] += vx * amount * share; dy[a] += vy * amount * share; }
if (!pinned.has(b)) { dx[b] -= vx * amount * share; dy[b] -= vy * amount * share; }
const share = fixed[b] ? 1 : .5;
dx[a] += vx * amount * share; dy[a] += vy * amount * share;
if (!fixed[b]) { dx[b] -= vx * amount * share; dy[b] -= vy * amount * share; }
}
}
}
};
// Spend each pass on actual overlapping cores before optional whitespace.
accumulate(0,true);
// A retained correction is already a settled display choice. Reprojection
// repairs new core contacts without repeatedly spending optional whitespace.
// Extra convergence rounds are for cores only, not repeated whitespace.
if (!retainedCorrection && !coreContacts && tested < budget && pass < Math.floor(limits.passes/2)) accumulate(gap,false);
if (!retainedCorrection && !passCutoff && !coreContacts && tested < budget && pass < limits.gapPasses) accumulate(gap,false);
diagnostics.passes++;
if (!contacts) break;
for (let i = 0; i < count; i++) if (active[i] && !pinned.has(i)) {
if (!contacts) {
// An exhausted prefix is not evidence that the unvisited suffix is free
// of contacts. Use the next bounded, rotated round when capacity remains.
if (passCutoff) continue;
break;
}
for (let i = 0; i < count; i++) if (active[i] && !fixed[i]) {
const step = Math.hypot(dx[i],dy[i]), gain = step > 2 ? 2 / step : 1;
let ox = x[i] + dx[i] * gain - input[i].x, oy = y[i] + dy[i] * gain - input[i].y;
const total = Math.hypot(ox,oy);
Expand Down
Loading