All files / web/src/components/toys/euclid/engine/recipe evaluate.ts

84.96% Statements 260/306
51.78% Branches 29/56
100% Functions 5/5
84.96% Lines 260/306

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 3071x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 309x 309x 309x 309x 309x 309x 309x 309x 309x 309x 309x 309x 309x 647x 647x 309x 309x 309x 309x 309x 309x 309x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 1x 1x 26x 26x 26x 309x 309x 309x 1864x 1864x 1864x 1864x 309x 309x 309x 309x 309x 309x 309x 309x 309x 309x 309x 1x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 894x 894x 894x 894x 894x 894x 1864x 1864x 614x 614x 614x 614x 614x 614x 614x 614x 614x 614x 614x 614x 614x 614x 1864x 1864x 286x 286x 286x 286x 286x 1864x 1864x 45x 45x 45x 45x 45x 45x 45x 45x 1x 45x 44x 44x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 1864x 1864x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 1864x 1864x 1x 1x 1x 1x 1x 572x 572x 572x 572x 572x 572x 572x 569x 569x 3x 3x 3x 572x 3x 3x 1x 1144x 1144x 1144x 1x 1x 1x 1x 1x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 286x 283x 283x 283x 283x 283x 283x 283x 283x                                 283x 283x                                                   283x 3x 286x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x        
/**
 * Pure evaluator for ConstructionRecipe.
 *
 * Given a recipe and concrete input positions, produces a ConstructionTrace
 * containing every resolved point, circle, segment, and per-op geometry.
 * No side effects, no construction state mutation.
 */
 
import type {
  ConstructionRecipe,
  ConstructionTrace,
  IntersectionSource,
  OpTrace,
  Pt,
  RecipeOp,
  Ref,
  ResolvedCircle,
  ResolvedSegment,
  RecipeRegistry,
} from './types'
import {
  computeEquilateralApex,
  computeDirectionVector,
  intersectionBeyond,
} from '../geometryHelpers'
import { circleCircleIntersections, circleLineIntersections } from '../intersections'
 
/**
 * Evaluate a recipe with concrete input positions.
 * Returns null if the construction is impossible (missing points, degenerate geometry).
 */
export function evaluateRecipe(
  recipe: ConstructionRecipe,
  inputPositions: Pt[],
  registry: RecipeRegistry
): ConstructionTrace | null {
  if (inputPositions.length < recipe.inputSlots.length) return null
 
  const pointMap = new Map<Ref, Pt>()
  const circleMap = new Map<string, ResolvedCircle>()
  const segmentMap = new Map<string, ResolvedSegment>()
  const opTraces: OpTrace[] = []
 
  // Bind input refs to positions
  for (let i = 0; i < recipe.inputSlots.length; i++) {
    pointMap.set(recipe.inputSlots[i].ref, inputPositions[i])
  }
 
  // Check degenerate conditions
  let activeOps = recipe.ops
  let degenerate = false
  let activeCeremony = recipe.ceremony
 
  if (recipe.degenerateCases) {
    for (const dc of recipe.degenerateCases) {
      const [refA, refB] = dc.condition.coincident
      const pA = pointMap.get(refA)
      const pB = pointMap.get(refB)
      if (pA && pB) {
        const dx = pA.x - pB.x
        const dy = pA.y - pB.y
        if (Math.sqrt(dx * dx + dy * dy) < 1e-9) {
          activeOps = dc.ops
          degenerate = true
          if (dc.ceremony) activeCeremony = dc.ceremony
          break
        }
      }
    }
  }
 
  // Walk ops in order
  for (const op of activeOps) {
    const trace = evaluateOp(op, pointMap, circleMap, segmentMap, registry)
    if (!trace) return null
    opTraces.push(trace)
  }
 
  return {
    recipe,
    inputPositions,
    pointMap,
    circleMap,
    segmentMap,
    opTraces,
    degenerate,
  }
}
 
function evaluateOp(
  op: RecipeOp,
  pointMap: Map<Ref, Pt>,
  circleMap: Map<string, ResolvedCircle>,
  segmentMap: Map<string, ResolvedSegment>,
  registry: RecipeRegistry
): OpTrace | null {
  switch (op.kind) {
    case 'segment': {
      const from = pointMap.get(op.from)
      const to = pointMap.get(op.to)
      if (!from || !to) return null
      segmentMap.set(op.id, { opId: op.id, from, to })
      return { kind: 'segment', opId: op.id, from, to, fromRef: op.from, toRef: op.to }
    }
 
    case 'circle': {
      const center = pointMap.get(op.center)
      const radiusPt = pointMap.get(op.radiusPoint)
      if (!center || !radiusPt) return null
      const radius = Math.sqrt((center.x - radiusPt.x) ** 2 + (center.y - radiusPt.y) ** 2)
      circleMap.set(op.id, { opId: op.id, center, radius })
      return {
        kind: 'circle',
        opId: op.id,
        center,
        radius,
        centerRef: op.center,
        radiusPointRef: op.radiusPoint,
      }
    }
 
    case 'intersection': {
      const point = resolveIntersection(op.of, op.prefer, circleMap, segmentMap, pointMap)
      if (!point) return null
      pointMap.set(op.output, point)
      return { kind: 'intersection', opId: op.id, point, outputRef: op.output }
    }
 
    case 'produce': {
      const from = pointMap.get(op.from)
      const through = pointMap.get(op.through)
      const circle = circleMap.get(op.until)
      if (!from || !through || !circle) return null
 
      // Zero-radius circle: the only "intersection" is the center point
      let point: Pt | null
      if (circle.radius < 1e-9) {
        point = { x: circle.center.x, y: circle.center.y }
      } else {
        point = intersectionBeyond(from, through, circle.center.x, circle.center.y, circle.radius)
      }
      if (!point) return null
      pointMap.set(op.output, point)
      return {
        kind: 'produce',
        opId: op.id,
        point,
        outputRef: op.output,
        fromRef: op.from,
        throughRef: op.through,
      }
    }
 
    case 'apply': {
      const subRecipe = registry[op.recipeId]
      if (!subRecipe) return null
 
      const subInputs: Pt[] = op.inputs.map((ref) => pointMap.get(ref)!).filter(Boolean)
      if (subInputs.length < op.inputs.length) return null
 
      const subTrace = evaluateRecipe(subRecipe, subInputs, registry)
      if (!subTrace) return null
 
      // Map sub-recipe exports back to local refs
      const outputMappings: Record<Ref, Ref> = {}
      for (const [subRef, localRef] of Object.entries(op.outputs)) {
        const pt = subTrace.pointMap.get(subRef)
        if (pt) {
          pointMap.set(localRef, pt)
          outputMappings[subRef] = localRef
        }
      }
 
      return { kind: 'apply', opId: op.id, subTrace, outputMappings }
    }
  }
}
 
/**
 * Resolve an IntersectionSource to either a circle or segment.
 * Handles string op IDs (looked up in circleMap/segmentMap) and inline segment refs.
 */
function resolveSource(
  source: IntersectionSource,
  circleMap: Map<string, ResolvedCircle>,
  segmentMap: Map<string, ResolvedSegment>,
  pointMap: Map<Ref, Pt>
): ResolvedCircle | ResolvedSegment | null {
  if (typeof source === 'string') {
    return circleMap.get(source) ?? segmentMap.get(source) ?? null
  }
  // Inline segment refs — create a virtual segment from the pointMap
  const from = pointMap.get(source.segmentRefs[0])
  const to = pointMap.get(source.segmentRefs[1])
  if (!from || !to) return null
  return { opId: `inline-${source.segmentRefs[0]}-${source.segmentRefs[1]}`, from, to }
}
 
function isCircle(el: ResolvedCircle | ResolvedSegment): el is ResolvedCircle {
  return 'radius' in el
}
 
/**
 * Resolve an intersection between two elements.
 * Handles circle-circle and circle-segment/line intersections.
 */
function resolveIntersection(
  sources: [IntersectionSource, IntersectionSource],
  prefer: 'upper' | 'lower',
  circleMap: Map<string, ResolvedCircle>,
  segmentMap: Map<string, ResolvedSegment>,
  pointMap: Map<Ref, Pt>
): Pt | null {
  const elA = resolveSource(sources[0], circleMap, segmentMap, pointMap)
  const elB = resolveSource(sources[1], circleMap, segmentMap, pointMap)
  if (!elA || !elB) return null
 
  const cirA = isCircle(elA) ? elA : null
  const cirB = isCircle(elB) ? elB : null
  const segA = !isCircle(elA) ? elA : null
  const segB = !isCircle(elB) ? elB : null
 
  if (cirA && cirB) {
    // Circle-circle intersection
    // Use computeEquilateralApex if the radii are equal (common case for I.1)
    if (Math.abs(cirA.radius - cirB.radius) < 1e-9) {
      const apex = computeEquilateralApex(cirA.center, cirB.center)
      if (!apex) return null
 
      // computeEquilateralApex already prefers upper/left, which matches 'upper'
      if (prefer === 'lower') {
        // Get the other intersection
        const pts = circleCircleIntersections(
          cirA.center.x,
          cirA.center.y,
          cirA.radius,
          cirB.center.x,
          cirB.center.y,
          cirB.radius
        )
        if (pts.length < 2) return apex
        // Return the one that's NOT the apex
        const other = pts.find(
          (p) => Math.abs(p.x - apex.x) > 0.01 || Math.abs(p.y - apex.y) > 0.01
        )
        return other ?? pts[1]
      }
      return apex
    }

    // Different radii — general circle-circle
    const pts = circleCircleIntersections(
      cirA.center.x,
      cirA.center.y,
      cirA.radius,
      cirB.center.x,
      cirB.center.y,
      cirB.radius
    )
    if (pts.length === 0) return null
    if (pts.length === 1) return pts[0]

    // Use A→B direction for chirality preference
    const abx = cirB.center.x - cirA.center.x
    const aby = cirB.center.y - cirA.center.y
    const upper = pts.filter((p) => abx * (p.y - cirA.center.y) - aby * (p.x - cirA.center.x) > 0)
    if (prefer === 'upper') {
      return upper.length > 0 ? upper[0] : pts[0]
    } else {
      const lower = pts.filter(
        (p) => abx * (p.y - cirA.center.y) - aby * (p.x - cirA.center.x) <= 0
      )
      return lower.length > 0 ? lower[0] : pts[0]
    }
  }
 
  if ((cirA && segB) || (segA && cirB)) {
    const circle = cirA ?? cirB!
    const segment = (segA ?? segB)!
    const pts = circleLineIntersections(
      circle.center.x,
      circle.center.y,
      circle.radius,
      segment.from.x,
      segment.from.y,
      segment.to.x,
      segment.to.y
    )
    if (pts.length === 0) return null
    if (pts.length === 1) return pts[0]
 
    // Pick based on parametric position along the segment direction (from→to).
    // 'upper' = further in the from→to direction (higher t), 'lower' = earlier.
    const dx = segment.to.x - segment.from.x
    const dy = segment.to.y - segment.from.y
    const t0 = (pts[0].x - segment.from.x) * dx + (pts[0].y - segment.from.y) * dy
    const t1 = (pts[1].x - segment.from.x) * dx + (pts[1].y - segment.from.y) * dy
    if (prefer === 'upper') {
      return t0 >= t1 ? pts[0] : pts[1]
    } else {
      return t0 <= t1 ? pts[0] : pts[1]
    }
  }

  return null
}