@vielzeug/ink 0.0.0-stage → 26.11.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/_validate.cjs +2 -0
  4. package/dist/_validate.cjs.map +1 -0
  5. package/dist/_validate.d.ts +11 -0
  6. package/dist/_validate.d.ts.map +1 -0
  7. package/dist/_validate.js +32 -0
  8. package/dist/_validate.js.map +1 -0
  9. package/dist/errors.cjs +2 -0
  10. package/dist/errors.cjs.map +1 -0
  11. package/dist/errors.d.ts +8 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +9 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/index.cjs +1 -0
  16. package/dist/index.d.ts +14 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +8 -0
  19. package/dist/ink.cjs +2 -0
  20. package/dist/ink.cjs.map +1 -0
  21. package/dist/ink.iife.js +2 -0
  22. package/dist/ink.iife.js.map +1 -0
  23. package/dist/ink.js +191 -0
  24. package/dist/ink.js.map +1 -0
  25. package/dist/outline.cjs +2 -0
  26. package/dist/outline.cjs.map +1 -0
  27. package/dist/outline.d.ts +14 -0
  28. package/dist/outline.d.ts.map +1 -0
  29. package/dist/outline.js +48 -0
  30. package/dist/outline.js.map +1 -0
  31. package/dist/simplify.cjs +2 -0
  32. package/dist/simplify.cjs.map +1 -0
  33. package/dist/simplify.d.ts +12 -0
  34. package/dist/simplify.d.ts.map +1 -0
  35. package/dist/simplify.js +29 -0
  36. package/dist/simplify.js.map +1 -0
  37. package/dist/smoothing.cjs +2 -0
  38. package/dist/smoothing.cjs.map +1 -0
  39. package/dist/smoothing.d.ts +20 -0
  40. package/dist/smoothing.d.ts.map +1 -0
  41. package/dist/smoothing.js +39 -0
  42. package/dist/smoothing.js.map +1 -0
  43. package/dist/stabilize.cjs +2 -0
  44. package/dist/stabilize.cjs.map +1 -0
  45. package/dist/stabilize.d.ts +24 -0
  46. package/dist/stabilize.d.ts.map +1 -0
  47. package/dist/stabilize.js +25 -0
  48. package/dist/stabilize.js.map +1 -0
  49. package/dist/svg.cjs +2 -0
  50. package/dist/svg.cjs.map +1 -0
  51. package/dist/svg.d.ts +27 -0
  52. package/dist/svg.d.ts.map +1 -0
  53. package/dist/svg.js +14 -0
  54. package/dist/svg.js.map +1 -0
  55. package/dist/types.d.ts +20 -0
  56. package/dist/types.d.ts.map +1 -0
  57. package/dist/widths.cjs +2 -0
  58. package/dist/widths.cjs.map +1 -0
  59. package/dist/widths.d.ts +26 -0
  60. package/dist/widths.d.ts.map +1 -0
  61. package/dist/widths.js +28 -0
  62. package/dist/widths.js.map +1 -0
  63. package/package.json +48 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ink.js","names":["message","opts","value","name","min","max","resolved","minPoints","dx","bx","ax","dy","by","ay","last","points","prev","i","next","tx","ty","other","len","s","angle","startAngle","center","radius","input","perPoint","widths","index","w","left","right","point","half","normal","first","firstNormal","lastNormal","outline","b","a","lenSq","p","tolerance","keep","stack","farthest","maxDistance","d","result","linear","p1","p2","t","t2","t3","alpha","p0","p3","pressure","time","steps","tension","options","strength","deadZone","source","sx","sy","rounded","precision","close","parts","MIN_SCALE","MAX_SCALE","width","thinning","referenceSpeed","timed","lastScale","from","to","dt"],"sources":["../src/errors.ts","../src/_validate.ts","../src/outline.ts","../src/simplify.ts","../src/smoothing.ts","../src/stabilize.ts","../src/svg.ts","../src/widths.ts"],"sourcesContent":["/** Base class for all ink errors. Use `instanceof InkError` to catch any ink-originated error. */\nexport class InkError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when ink options are invalid, such as a negative `tolerance`, a `tension` outside `[0, 1]`, or a non-positive `width`. */\nexport class InkConfigError extends InkError {}\n","/** Internal validation helpers. Shared by every public entry point; never exported.\n *\n * Stroke points arrive typed and are produced by capture loops, not by untrusted\n * input, so they are not validated per point (matching atlas and wire). Only\n * option ranges and algorithm preconditions are checked.\n */\nimport { InkConfigError } from './errors.js';\nimport type { StrokePoint } from './types.js';\n\nexport function requireFiniteNumber(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new InkConfigError(`Expected ${name} to be a finite number, received ${String(value)}.`);\n }\n return value;\n}\n\nexport function requireRange(value: number, name: string, min: number, max: number): number {\n if (value < min || value > max) {\n throw new InkConfigError(`Expected ${name} to be within [${min}, ${max}], received ${value}.`);\n }\n return value;\n}\n\nexport function requirePositive(value: unknown, name: string): number {\n return requireRange(requireFiniteNumber(value, name), name, Number.MIN_VALUE, Number.POSITIVE_INFINITY);\n}\n\nexport function requireInteger(value: unknown, name: string, min: number, max: number): number {\n const resolved = requireFiniteNumber(value, name);\n if (!Number.isInteger(resolved)) {\n throw new InkConfigError(`Expected ${name} to be an integer, received ${String(value)}.`);\n }\n return requireRange(resolved, name, min, max);\n}\n\n/** Checks the array shape and minimum length of a stroke; the points themselves are trusted as typed. */\nexport function requireStrokePoints(value: readonly StrokePoint[], minPoints = 0): readonly StrokePoint[] {\n if (value.length < minPoints) {\n throw new InkConfigError(`Expected at least ${minPoints} stroke point(s), received ${value.length}.`);\n }\n return value;\n}\n\nexport function clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\n/** Distance between two points. */\nexport function distance(ax: number, ay: number, bx: number, by: number): number {\n const dx = bx - ax;\n const dy = by - ay;\n return Math.hypot(dx, dy);\n}\n","/** Closed variable-width polygon approximating a stroked path. */\n\nimport { clamp, requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { Point, StrokePoint } from './types.js';\n\n/** Unit normal at sample `i` of a polyline, derived from the central tangent; falls back to adjacent segments. */\nfunction normalAt(points: readonly Point[], i: number): Point {\n const last = points.length - 1;\n const prev = points[clamp(i - 1, 0, last)];\n const next = points[clamp(i + 1, 0, last)];\n let tx = next.x - prev.x;\n let ty = next.y - prev.y;\n if (tx === 0 && ty === 0) {\n // Degenerate central tangent (e.g. a spike back on itself): use the outgoing segment.\n const other = points[clamp(i + 1, 0, last)];\n tx = other.x - points[i].x;\n ty = other.y - points[i].y;\n }\n const len = Math.hypot(tx, ty);\n if (len === 0) return { x: 0, y: -1 };\n return { x: ty / len, y: -tx / len };\n}\n\n/** Append the interior points of a half-circle cap: samples from `startAngle` to `startAngle + PI`, endpoints excluded. */\nfunction appendCap(outline: Point[], center: Point, startAngle: number, radius: number): void {\n const steps = 8;\n for (let s = 1; s < steps; s++) {\n const angle = startAngle + Math.PI * (s / steps);\n outline.push({ x: center.x + Math.cos(angle) * radius, y: center.y + Math.sin(angle) * radius });\n }\n}\n\n/**\n * Build a closed polygon approximating the variable-width stroke through `points`.\n *\n * Each sample is offset by half its width along the local normal; the ring runs the start cap,\n * the left side forward, the end cap, and the right side backward, so it is closed without a\n * repeated final point. Pass a constant `width` for a uniform stroke, or one width per point\n * (from `strokeWidths`) for a variable one. Deterministic: identical input produces an identical ring.\n *\n * @throws {import('./errors.js').InkConfigError} When `widths` is a mismatched array or holds non-positive values.\n */\nexport function strokeOutline(points: readonly StrokePoint[], widths: number | readonly number[]): Point[] {\n const input = requireStrokePoints(points, 1);\n const perPoint: readonly number[] = typeof widths === 'number' ? input.map(() => widths) : widths;\n if (perPoint.length !== input.length) {\n throw new InkConfigError(`Expected widths to hold ${input.length} number(s), received ${perPoint.length}.`);\n }\n for (const [index, w] of perPoint.entries()) {\n requireFiniteNumber(w, `widths[${index}]`);\n if (w <= 0) {\n throw new InkConfigError(`Expected widths[${index}] to be a positive finite number, received ${w}.`);\n }\n }\n\n const left: Point[] = [];\n const right: Point[] = [];\n for (let i = 0; i < input.length; i++) {\n const point = input[i];\n const half = perPoint[i] / 2;\n const normal = normalAt(input, i);\n left.push({ x: point.x + normal.x * half, y: point.y + normal.y * half });\n right.push({ x: point.x - normal.x * half, y: point.y - normal.y * half });\n }\n\n const first = input[0];\n const last = input[input.length - 1];\n const firstNormal = normalAt(input, 0);\n const lastNormal = normalAt(input, input.length - 1);\n\n const outline: Point[] = [];\n // Start cap: half-circle from the right offset of the first sample, around its back, to the left offset.\n appendCap(outline, first, Math.atan2(firstNormal.y, firstNormal.x) + Math.PI, perPoint[0] / 2);\n outline.push(...left);\n // End cap: half-circle from the left offset of the last sample, around its front, to the right offset.\n appendCap(outline, last, Math.atan2(lastNormal.y, lastNormal.x), perPoint[perPoint.length - 1] / 2);\n outline.push(...right.reverse());\n return outline;\n}\n","/** Ramer-Douglas-Peucker stroke decimation. */\n\nimport { requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { StrokePoint } from './types.js';\n\n/** Perpendicular distance from `p` to the infinite line through `a`-`b`; point distance when degenerate. */\nfunction perpendicularDistance(p: StrokePoint, a: StrokePoint, b: StrokePoint): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lenSq = dx * dx + dy * dy;\n if (lenSq === 0) return Math.hypot(p.x - a.x, p.y - a.y);\n const cross = Math.abs(dy * p.x - dx * p.y + b.x * a.y - b.y * a.x);\n return cross / Math.sqrt(lenSq);\n}\n\n/**\n * Decimate a stroke with Ramer-Douglas-Peucker: iteratively drop the point farthest from the\n * chord when its distance is under `tolerance`, keeping the first and last points. The result is\n * always a subsequence of the input (same object references), so metadata like `pressure` survives.\n *\n * @throws {import('./errors.js').InkConfigError} When `points` is invalid or `tolerance` is not a\n * non-negative finite number.\n */\nexport function simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[] {\n const input = requireStrokePoints(points);\n requireFiniteNumber(tolerance, 'tolerance');\n if (tolerance < 0) {\n throw new InkConfigError(`Expected tolerance to be >= 0, received ${tolerance}.`);\n }\n if (input.length < 3) return input.map((point) => ({ ...point }));\n\n // Iterative RDP with an explicit stack: no recursion depth limit on long strokes.\n const keep = new Uint8Array(input.length);\n keep[0] = 1;\n keep[input.length - 1] = 1;\n const stack: [number, number][] = [[0, input.length - 1]];\n while (stack.length > 0) {\n const [first, last] = stack.pop() as [number, number];\n let farthest = -1;\n let maxDistance = -1;\n for (let i = first + 1; i < last; i++) {\n const d = perpendicularDistance(input[i], input[first], input[last]);\n if (d > maxDistance) {\n maxDistance = d;\n farthest = i;\n }\n }\n if (farthest !== -1 && maxDistance > tolerance) {\n keep[farthest] = 1;\n stack.push([first, farthest], [farthest, last]);\n }\n }\n\n const result: StrokePoint[] = [];\n for (let i = 0; i < input.length; i++) {\n if (keep[i]) result.push(input[i]);\n }\n return result;\n}\n","/** Stroke smoothing: deterministic Catmull-Rom resampling. */\n\nimport { clamp, requireInteger, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface SmoothStrokeOptions {\n /** Samples emitted per input segment (minimum 2). Default 8. */\n steps?: number;\n /** Interpolation tension. `0` is linear, `1` is the standard uniform spline. Default `1`. */\n tension?: number;\n}\n\n/**\n * Interpolation basis for one axis; `t` in `[0, 1]`. `alpha` blends linear\n * interpolation (`alpha = 0`) with the standard uniform Catmull-Rom spline\n * (`alpha = 1`), so `tension: 0` is genuinely linear.\n */\nfunction catmullRomAxis(p0: number, p1: number, p2: number, p3: number, t: number, alpha: number): number {\n const linear = p1 + (p2 - p1) * t;\n const t2 = t * t;\n const t3 = t2 * t;\n const spline =\n 0.5 * (2 * p1 + t * (p2 - p0) + t2 * (2 * p0 - 5 * p1 + 4 * p2 - p3) + t3 * (3 * p1 - 3 * p2 - p0 + p3));\n return linear + alpha * (spline - linear);\n}\n\n/** Linear interpolation of optional metadata; keeps the field absent when neither side has it. */\nfunction lerpField(a: number | undefined, b: number | undefined, t: number): number | undefined {\n if (a !== undefined && b !== undefined) return a + (b - a) * t;\n return a ?? b;\n}\n\nfunction emitPoint(x: number, y: number, pressure?: number, time?: number): StrokePoint {\n const point: { x: number; y: number; pressure?: number; time?: number } = { x, y };\n if (pressure !== undefined) point.pressure = pressure;\n if (time !== undefined) point.time = time;\n return point;\n}\n\nfunction catmullRomResample(points: readonly StrokePoint[], tension: number, steps: number): StrokePoint[] {\n const result: StrokePoint[] = [];\n const last = points.length - 1;\n // Duplicated end controls keep the spline interpolating the true endpoints.\n const at = (index: number): StrokePoint => points[clamp(index, 0, last)];\n for (let i = 0; i < last; i++) {\n const [p0, p1, p2, p3] = [at(i - 1), at(i), at(i + 1), at(i + 2)];\n for (let s = 0; s < steps; s++) {\n const t = s / steps;\n result.push(\n emitPoint(\n catmullRomAxis(p0.x, p1.x, p2.x, p3.x, t, tension),\n catmullRomAxis(p0.y, p1.y, p2.y, p3.y, t, tension),\n lerpField(p1.pressure, p2.pressure, t),\n lerpField(p1.time, p2.time, t),\n ),\n );\n }\n }\n result.push(emitPoint(points[last].x, points[last].y, points[last].pressure, points[last].time));\n return result;\n}\n\n/**\n * Resample a freehand stroke through a uniform Catmull-Rom spline: `steps` samples per input\n * segment, with the first and last input points preserved exactly. `pressure` and `time` are\n * interpolated linearly, so widths computed from the output match widths computed from the input.\n *\n * For jitter removal *while drawing*, use `stabilizeStroke` instead: this function adds points and\n * looks ahead, so it is the post-capture step.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range.\n */\nexport function smoothStroke(points: readonly StrokePoint[], options: SmoothStrokeOptions = {}): StrokePoint[] {\n const input = requireStrokePoints(points);\n const tension = requireRange(options.tension ?? 1, 'tension', 0, 1);\n const steps = requireInteger(options.steps ?? 8, 'steps', 2, 1000);\n if (input.length < 3) return input.map((point) => ({ ...point }));\n return catmullRomResample(input, tension, steps);\n}\n","/** Causal stroke stabilization: Streamline-style low-pass for use while drawing. */\n\nimport { distance, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StabilizeStrokeOptions {\n /**\n * How strongly the filter pulls toward each incoming sample. `0` keeps the raw input,\n * `1` is maximum smoothing. Default `0.5`.\n */\n strength?: number;\n}\n\n/**\n * Remove hand jitter from a stroke *while it is being drawn*: a causal exponential\n * average toward each incoming sample, with a jitter dead zone so straight lines stay crisp.\n *\n * Output length always equals input length, so per-point widths and metadata stay aligned with\n * the source samples. The last output point is always the last input point — the stroke ends\n * exactly where the pen lifted, never short of it. Inside the dead zone the previous smoothed\n * position repeats, but the incoming sample's `pressure` and `time` are carried through.\n *\n * Deterministic and pure: the same input always returns the same output.\n *\n * @throws {import('./errors.js').InkConfigError} When `strength` is out of range.\n */\nexport function stabilizeStroke(points: readonly StrokePoint[], options: StabilizeStrokeOptions = {}): StrokePoint[] {\n const input = requireStrokePoints(points);\n const strength = requireRange(options.strength ?? 0.5, 'strength', 0, 1);\n if (input.length < 2) return input.map((point) => ({ ...point }));\n // strength 0 -> alpha 1 (no smoothing); strength 1 -> alpha 0.1 (heavy smoothing).\n const alpha = 1 - strength * 0.9;\n const deadZone = (1 - alpha) * 2;\n const emit = (x: number, y: number, source: StrokePoint): StrokePoint => {\n const point: { x: number; y: number; pressure?: number; time?: number } = { x, y };\n if (source.pressure !== undefined) point.pressure = source.pressure;\n if (source.time !== undefined) point.time = source.time;\n return point;\n };\n\n const result: StrokePoint[] = [emit(input[0].x, input[0].y, input[0])];\n let sx = input[0].x;\n let sy = input[0].y;\n for (let i = 1; i < input.length; i++) {\n const point = input[i];\n if (i === input.length - 1) {\n // Snap to the final sample so the stroke never trails past where the pen lifted.\n result.push(emit(point.x, point.y, point));\n break;\n }\n if (distance(sx, sy, point.x, point.y) < deadZone) {\n result.push(emit(sx, sy, point));\n continue;\n }\n sx += (point.x - sx) * alpha;\n sy += (point.y - sy) * alpha;\n result.push(emit(sx, sy, point));\n }\n return result;\n}\n","/** SVG path `d` string output for polylines and outline polygons. */\n\nimport { requireInteger, requireStrokePoints } from './_validate.js';\nimport type { Point } from './types.js';\n\nexport interface PolylineToSvgPathOptions {\n /** Append `Z` to close the path. Use for outline rings from `strokeOutline`. Default `false`. */\n close?: boolean;\n /** Decimal places for emitted coordinates (`0`-`12`). Default `2`. */\n precision?: number;\n}\n\nfunction format(value: number, precision: number): string {\n // `+ 0` normalizes -0 to 0 so output is stable across platforms.\n const rounded = Number(value.toFixed(precision)) + 0;\n return String(rounded);\n}\n\n/**\n * Serialize a polyline as an SVG path `d` string: `M x y` followed by one `L x y` per remaining\n * point. Coordinates are rounded to `precision` decimal places.\n *\n * Works for both open strokes and closed rings: pass `close: true` for the outline polygon\n * returned by `strokeOutline`.\n *\n * @example\n * ```ts\n * polylineToSvgPath([{ x: 0, y: 0 }, { x: 10, y: 5 }]);\n * // 'M 0 0 L 10 5'\n * polylineToSvgPath(strokeOutline(points, 4), { close: true });\n * // 'M ... L ... Z'\n * ```\n *\n * @throws {import('./errors.js').InkConfigError} When `points` is empty or `precision` is out of range.\n */\nexport function polylineToSvgPath(points: readonly Point[], options: PolylineToSvgPathOptions = {}): string {\n const input = requireStrokePoints(points, 1);\n const close = options.close ?? false;\n const precision = requireInteger(options.precision ?? 2, 'precision', 0, 12);\n const parts: string[] = [`M ${format(input[0].x, precision)} ${format(input[0].y, precision)}`];\n for (let i = 1; i < input.length; i++) {\n parts.push(`L ${format(input[i].x, precision)} ${format(input[i].y, precision)}`);\n }\n if (close) parts.push('Z');\n return parts.join(' ');\n}\n","/** Velocity- and pressure-modulated stroke widths. */\n\nimport { clamp, distance, requirePositive, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StrokeWidthOptions {\n /** Pen speed treated as \"neutral\", in pixels per millisecond. Default `0.5`. */\n referenceSpeed?: number;\n /** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */\n thinning?: number;\n /** Width at reference speed with neutral pressure. Must be positive. */\n width: number;\n}\n\n/** Fixed velocity-scale range; slow strokes at most double, fast strokes at most quarter. */\nconst MIN_SCALE = 0.25;\nconst MAX_SCALE = 2;\n\n/**\n * Pressure response curve, clamped to `[0, 1]`:\n * `0.5` (the neutral value a mouse reports) maps to exactly `1`, so a stroke with\n * neutral pressure is as wide as one without pressure data. Range: `[0.5, 1.25]`.\n */\nfunction pressureScale(pressure: number): number {\n const p = clamp(pressure, 0, 1);\n return p <= 0.5 ? 0.5 + p : 1 + (p - 0.5) * 0.5;\n}\n\n/**\n * Compute one width per stroke point from pen speed and optional pressure.\n *\n * Speed is `distance / Δtime` between consecutive points, which stays correct after any\n * smoothing, stabilization, or simplification — the pipeline order no longer matters. When any\n * point lacks `time`, or a Δtime is zero, velocity modulation is disabled for the whole stroke\n * (width becomes `width × pressure`) instead of falling back to a spacing proxy that resampling\n * would distort. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n *\n * The first point uses the forward segment; degenerate (zero-length) segments keep the previous\n * scale so stationary samples do not spike.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.\n */\nexport function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[] {\n const input = requireStrokePoints(points, 1);\n const width = requirePositive(options.width, 'width');\n const thinning = requireRange(options.thinning ?? 0.5, 'thinning', 0, 1);\n const referenceSpeed = requirePositive(options.referenceSpeed ?? 0.5, 'referenceSpeed');\n\n // Velocity needs a timestamp on every point; otherwise it is off for the whole stroke.\n const timed = input.every((point) => point.time !== undefined);\n\n const widths: number[] = [];\n let lastScale = 1;\n for (let i = 0; i < input.length; i++) {\n if (timed && thinning > 0) {\n const point = input[i];\n const next = input[i + 1];\n // First point looks forward; the rest look at the segment they arrived on.\n const from = i > 0 ? input[i - 1] : point;\n const to = i > 0 ? point : next;\n if (to) {\n const dt = Math.abs((to.time as number) - (from.time as number));\n if (dt > 0) {\n const speed = distance(from.x, from.y, to.x, to.y) / dt;\n // Slow (speed < reference) widens: scale = (referenceSpeed / speed) ^ thinning.\n lastScale = clamp((referenceSpeed / speed) ** thinning, MIN_SCALE, MAX_SCALE);\n }\n }\n }\n const pressure = input[i].pressure;\n widths.push(width * lastScale * (pressure === undefined ? 1 : pressureScale(pressure)));\n }\n return widths;\n}\n"],"mappings":";AACA,IAAa,WAAb,cA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x,s=i.y-t[n].y}let c=Math.hypot(o,s);return c===0?{x:0,y:-1}:{x:s/c,y:-o/c}}function appendCap(e,t,n,r){for(let i=1;i<8;i++){let a=n+i/8*Math.PI;e.push({x:t.x+Math.cos(a)*r,y:t.y+Math.sin(a)*r})}}function strokeOutline(n,r){let i=e.requireStrokePoints(n,1),a=typeof r==`number`?i.map(()=>r):r;if(a.length!==i.length)throw new t.InkConfigError(`Expected widths to hold ${i.length} number(s), received ${a.length}.`);for(let[n,r]of a.entries())if(e.requireFiniteNumber(r,`widths[${n}]`),r<=0)throw new t.InkConfigError(`Expected widths[${n}] to be a positive finite number, received ${r}.`);let o=[],s=[];for(let e=0;e<i.length;e++){let t=i[e],n=a[e]/2,r=normalAt(i,e);o.push({x:t.x+r.x*n,y:t.y+r.y*n}),s.push({x:t.x-r.x*n,y:t.y-r.y*n})}let c=i[0],l=i[i.length-1],u=normalAt(i,0),d=normalAt(i,i.length-1),f=[];return appendCap(f,c,Math.atan2(u.y,u.x)+Math.PI,a[0]/2),f.push(...o),appendCap(f,l,Math.atan2(d.y,d.x),a[a.length-1]/2),f.push(...s.reverse()),f}exports.strokeOutline=strokeOutline;
2
+ //# sourceMappingURL=outline.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outline.cjs","names":["clamp","requireStrokePoints","InkConfigError","require__validate","require_errors","last","points","prev","i","next","tx","ty","other","len","s","angle","startAngle","outline","center","radius","input","perPoint","widths","index","w","left","right","point","half","normal","first","firstNormal","lastNormal"],"sources":["../src/outline.ts"],"sourcesContent":["/** Closed variable-width polygon approximating a stroked path. */\n\nimport { clamp, requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { Point, StrokePoint } from './types.js';\n\n/** Unit normal at sample `i` of a polyline, derived from the central tangent; falls back to adjacent segments. */\nfunction normalAt(points: readonly Point[], i: number): Point {\n const last = points.length - 1;\n const prev = points[clamp(i - 1, 0, last)];\n const next = points[clamp(i + 1, 0, last)];\n let tx = next.x - prev.x;\n let ty = next.y - prev.y;\n if (tx === 0 && ty === 0) {\n // Degenerate central tangent (e.g. a spike back on itself): use the outgoing segment.\n const other = points[clamp(i + 1, 0, last)];\n tx = other.x - points[i].x;\n ty = other.y - points[i].y;\n }\n const len = Math.hypot(tx, ty);\n if (len === 0) return { x: 0, y: -1 };\n return { x: ty / len, y: -tx / len };\n}\n\n/** Append the interior points of a half-circle cap: samples from `startAngle` to `startAngle + PI`, endpoints excluded. */\nfunction appendCap(outline: Point[], center: Point, startAngle: number, radius: number): void {\n const steps = 8;\n for (let s = 1; s < steps; s++) {\n const angle = startAngle + Math.PI * (s / steps);\n outline.push({ x: center.x + Math.cos(angle) * radius, y: center.y + Math.sin(angle) * radius });\n }\n}\n\n/**\n * Build a closed polygon approximating the variable-width stroke through `points`.\n *\n * Each sample is offset by half its width along the local normal; the ring runs the start cap,\n * the left side forward, the end cap, and the right side backward, so it is closed without a\n * repeated final point. Pass a constant `width` for a uniform stroke, or one width per point\n * (from `strokeWidths`) for a variable one. Deterministic: identical input produces an identical ring.\n *\n * @throws {import('./errors.js').InkConfigError} When `widths` is a mismatched array or holds non-positive values.\n */\nexport function strokeOutline(points: readonly StrokePoint[], widths: number | readonly number[]): Point[] {\n const input = requireStrokePoints(points, 1);\n const perPoint: readonly number[] = typeof widths === 'number' ? input.map(() => widths) : widths;\n if (perPoint.length !== input.length) {\n throw new InkConfigError(`Expected widths to hold ${input.length} number(s), received ${perPoint.length}.`);\n }\n for (const [index, w] of perPoint.entries()) {\n requireFiniteNumber(w, `widths[${index}]`);\n if (w <= 0) {\n throw new InkConfigError(`Expected widths[${index}] to be a positive finite number, received ${w}.`);\n }\n }\n\n const left: Point[] = [];\n const right: Point[] = [];\n for (let i = 0; i < input.length; i++) {\n const point = input[i];\n const half = perPoint[i] / 2;\n const normal = normalAt(input, i);\n left.push({ x: point.x + normal.x * half, y: point.y + normal.y * half });\n right.push({ x: point.x - normal.x * half, y: point.y - normal.y * half });\n }\n\n const first = input[0];\n const last = input[input.length - 1];\n const firstNormal = normalAt(input, 0);\n const lastNormal = normalAt(input, input.length - 1);\n\n const outline: Point[] = [];\n // Start cap: half-circle from the right offset of the first sample, around its back, to the left offset.\n appendCap(outline, first, Math.atan2(firstNormal.y, firstNormal.x) + Math.PI, perPoint[0] / 2);\n outline.push(...left);\n // End cap: half-circle from the left offset of the last sample, around its front, to the right offset.\n appendCap(outline, last, Math.atan2(lastNormal.y, lastNormal.x), perPoint[perPoint.length - 1] / 2);\n outline.push(...right.reverse());\n return outline;\n}\n"],"mappings":"A,6DAOA,SAAS,SAAS,EAA0B,EAAkB,CAC5D,IAAMK,EAAOC,EAAO,OAAS,EACvBC,EAAOD,EAAON,EAAAA,MAAMQ,EAAI,EAAG,EAAGH,CAAI,GAClCI,EAAOH,EAAON,EAAAA,MAAMQ,EAAI,EAAG,EAAGH,CAAI,GACpCK,EAAKD,EAAK,EAAIF,EAAK,EACnBI,EAAKF,EAAK,EAAIF,EAAK,EACvB,GAAIG,IAAO,GAAKC,IAAO,EAAG,CAExB,IAAMC,EAAQN,EAAON,EAAAA,MAAMQ,EAAI,EAAG,EAAGH,CAAI,GACzC,EAAKO,EAAM,EAAIN,EAAOE,EAAE,CAAC,EACzB,EAAKI,EAAM,EAAIN,EAAOE,EAAE,CAAC,CAC3B,CACA,IAAMK,EAAM,KAAK,MAAMH,EAAIC,CAAE,EAE7B,OADIE,IAAQ,EAAU,CAAE,EAAG,EAAG,EAAG,EAAG,EAC7B,CAAE,EAAGF,EAAKE,EAAK,EAAG,CAACH,EAAKG,CAAI,CACrC,CAGA,SAAS,UAAU,EAAkB,EAAe,EAAoB,EAAsB,CAE5F,IAAK,IAAIC,EAAI,EAAGA,EAAI,EAAO,IAAK,CAC9B,IAAMC,EAAQC,EAAwBF,EAAI,EAAf,KAAK,GAChCG,EAAQ,KAAK,CAAE,EAAGC,EAAO,EAAI,KAAK,IAAIH,CAAK,EAAII,EAAQ,EAAGD,EAAO,EAAI,KAA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B,UAAUR,EAASZ,EAAM,KAAK,MAAM2B,EAAW,EAAGA,EAAW,CAAC,EAAGX,EAASA,EAAS,OAAS,GAAK,CAAC,EAClGJ,EAAQ,KAAK,GAAGS,EAAM,QAAQ,CAAC,EACxBT,CACT,C"}
@@ -0,0 +1,14 @@
1
+ /** Closed variable-width polygon approximating a stroked path. */
2
+ import type { Point, StrokePoint } from './types.js';
3
+ /**
4
+ * Build a closed polygon approximating the variable-width stroke through `points`.
5
+ *
6
+ * Each sample is offset by half its width along the local normal; the ring runs the start cap,
7
+ * the left side forward, the end cap, and the right side backward, so it is closed without a
8
+ * repeated final point. Pass a constant `width` for a uniform stroke, or one width per point
9
+ * (from `strokeWidths`) for a variable one. Deterministic: identical input produces an identical ring.
10
+ *
11
+ * @throws {import('./errors.js').InkConfigError} When `widths` is a mismatched array or holds non-positive values.
12
+ */
13
+ export declare function strokeOutline(points: readonly StrokePoint[], widths: number | readonly number[]): Point[];
14
+ //# sourceMappingURL=outline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outline.d.ts","sourceRoot":"","sources":["../src/outline.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAIlE,OAAO,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AA6BrD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,KAAK,EAAE,CAoCzG"}
@@ -0,0 +1,48 @@
1
+ import { clamp as e, requireFiniteNumber as t, requireStrokePoints as n } from "./_validate.js";
2
+ import { InkConfigError as r } from "./errors.js";
3
+ // src/outline.ts
4
+ function normalAt(t, n) {
5
+ let r = t.length - 1, i = t[e(n - 1, 0, r)], a = t[e(n + 1, 0, r)], o = a.x - i.x, s = a.y - i.y;
6
+ if (o === 0 && s === 0) {
7
+ let i = t[e(n + 1, 0, r)];
8
+ o = i.x - t[n].x, s = i.y - t[n].y;
9
+ }
10
+ let c = Math.hypot(o, s);
11
+ return c === 0 ? {
12
+ x: 0,
13
+ y: -1
14
+ } : {
15
+ x: s / c,
16
+ y: -o / c
17
+ };
18
+ }
19
+ function appendCap(e, t, n, r) {
20
+ for (let i = 1; i < 8; i++) {
21
+ let a = n + i / 8 * Math.PI;
22
+ e.push({
23
+ x: t.x + Math.cos(a) * r,
24
+ y: t.y + Math.sin(a) * r
25
+ });
26
+ }
27
+ }
28
+ function strokeOutline(e, i) {
29
+ let a = n(e, 1), o = typeof i == "number" ? a.map(() => i) : i;
30
+ if (o.length !== a.length) throw new r(`Expected widths to hold ${a.length} number(s), received ${o.length}.`);
31
+ for (let [e, n] of o.entries()) if (t(n, `widths[${e}]`), n <= 0) throw new r(`Expected widths[${e}] to be a positive finite number, received ${n}.`);
32
+ let s = [], c = [];
33
+ for (let e = 0; e < a.length; e++) {
34
+ let t = a[e], n = o[e] / 2, r = normalAt(a, e);
35
+ s.push({
36
+ x: t.x + r.x * n,
37
+ y: t.y + r.y * n
38
+ }), c.push({
39
+ x: t.x - r.x * n,
40
+ y: t.y - r.y * n
41
+ });
42
+ }
43
+ let l = a[0], u = a[a.length - 1], d = normalAt(a, 0), f = normalAt(a, a.length - 1), p = [];
44
+ return appendCap(p, l, Math.atan2(d.y, d.x) + Math.PI, o[0] / 2), p.push(...s), appendCap(p, u, Math.atan2(f.y, f.x), o[o.length - 1] / 2), p.push(...c.reverse()), p;
45
+ }
46
+ export { strokeOutline };
47
+
48
+ //# sourceMappingURL=outline.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outline.js","names":["last","points","prev","clamp","i","next","tx","ty","other","len","s","angle","startAngle","center","radius","input","requireStrokePoints","perPoint","widths","InkConfigError","index","w","requireFiniteNumber","left","right","point","half","normal","first","firstNormal","lastNormal","outline"],"sources":["../src/outline.ts"],"sourcesContent":["/** Closed variable-width polygon approximating a stroked path. */\n\nimport { clamp, requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { Point, StrokePoint } from './types.js';\n\n/** Unit normal at sample `i` of a polyline, derived from the central tangent; falls back to adjacent segments. */\nfunction normalAt(points: readonly Point[], i: number): Point {\n const last = points.length - 1;\n const prev = points[clamp(i - 1, 0, last)];\n const next = points[clamp(i + 1, 0, last)];\n let tx = next.x - prev.x;\n let ty = next.y - prev.y;\n if (tx === 0 && ty === 0) {\n // Degenerate central tangent (e.g. a spike back on itself): use the outgoing segment.\n const other = points[clamp(i + 1, 0, last)];\n tx = other.x - points[i].x;\n ty = other.y - points[i].y;\n }\n const len = Math.hypot(tx, ty);\n if (len === 0) return { x: 0, y: -1 };\n return { x: ty / len, y: -tx / len };\n}\n\n/** Append the interior points of a half-circle cap: samples from `startAngle` to `startAngle + PI`, endpoints excluded. */\nfunction appendCap(outline: Point[], center: Point, startAngle: number, radius: number): void {\n const steps = 8;\n for (let s = 1; s < steps; s++) {\n const angle = startAngle + Math.PI * (s / steps);\n outline.push({ x: center.x + Math.cos(angle) * radius, y: center.y + Math.sin(angle) * radius });\n }\n}\n\n/**\n * Build a closed polygon approximating the variable-width stroke through `points`.\n *\n * Each sample is offset by half its width along the local normal; the ring runs the start cap,\n * the left side forward, the end cap, and the right side backward, so it is closed without a\n * repeated final point. Pass a constant `width` for a uniform stroke, or one width per point\n * (from `strokeWidths`) for a variable one. Deterministic: identical input produces an identical ring.\n *\n * @throws {import('./errors.js').InkConfigError} When `widths` is a mismatched array or holds non-positive values.\n */\nexport function strokeOutline(points: readonly StrokePoint[], widths: number | readonly number[]): Point[] {\n const input = requireStrokePoints(points, 1);\n const perPoint: readonly number[] = typeof widths === 'number' ? input.map(() => widths) : widths;\n if (perPoint.length !== input.length) {\n throw new InkConfigError(`Expected widths to hold ${input.length} number(s), received ${perPoint.length}.`);\n }\n for (const [index, w] of perPoint.entries()) {\n requireFiniteNumber(w, `widths[${index}]`);\n if (w <= 0) {\n throw new InkConfigError(`Expected widths[${index}] to be a positive finite number, received ${w}.`);\n }\n }\n\n const left: Point[] = [];\n const right: Point[] = [];\n for (let i = 0; i < input.length; i++) {\n const point = input[i];\n const half = perPoint[i] / 2;\n const normal = normalAt(input, i);\n left.push({ x: point.x + normal.x * half, y: point.y + normal.y * half });\n right.push({ x: point.x - normal.x * half, y: point.y - normal.y * half });\n }\n\n const first = input[0];\n const last = input[input.length - 1];\n const firstNormal = normalAt(input, 0);\n const lastNormal = normalAt(input, input.length - 1);\n\n const outline: Point[] = [];\n // Start cap: half-circle from the right offset of the first sample, around its back, to the left offset.\n appendCap(outline, first, Math.atan2(firstNormal.y, firstNormal.x) + Math.PI, perPoint[0] / 2);\n outline.push(...left);\n // End cap: half-circle from the left offset of the last sample, around its front, to the right offset.\n appendCap(outline, last, Math.atan2(lastNormal.y, lastNormal.x), perPoint[perPoint.length - 1] / 2);\n outline.push(...right.reverse());\n return outline;\n}\n"],"mappings":";;;AAOA,SAAS,SAAS,GAA0B,GAAkB;CAC5D,IAAMA,IAAOC,EAAO,SAAS,GACvBC,IAAOD,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI,IAClCK,IAAOJ,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI,IACpCM,IAAKD,EAAK,IAAIH,EAAK,GACnBK,IAAKF,EAAK,IAAIH,EAAK;CACvB,IAAII,MAAO,KAAKC,MAAO,GAAG;EAExB,IAAMC,IAAQP,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI;EAEzC,AADA,IAAKQ,EAAM,IAAIP,EAAOG,EAAE,CAAC,GACzB,IAAKI,EAAM,IAAIP,EAAOG,EAAE,CAAC;CAC3B;CACA,IAAMK,IAAM,KAAK,MAAMH,GAAIC,CAAE;CAE7B,OADIE,MAAQ,IAAU;EAAE,GAAG;EAAG,GAAG;CAAG,IAC7B;EAAE,GAAGF,IAAKE;EAAK,GAAG,CAACH,IAAKG;CAAI;AACrC;AAGA,SAAS,UAAU,GAAkB,GAAe,GAAoB,GAAsB;CAE5F,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B,IAAmB,CAAC;CAO1B,OALA,UAAUA,GAASH,GAAO,KAAK,MAAMC,EAAY,GAAGA,EAAY,CAAC,IAAI,KAAK,IAAIZ,EAAS,KAAK,CAAC,GAC7Fc,EAAQ,KAAK,GAAGR,CAAI,GAEpB,UAAUQ,GAAS/B,GAAM,KAAK,MAAM8B,EAAW,GAAGA,EAAW,CAAC,GAAGb,EAASA,EAAS,SAAS,KAAK,CAAC,GAClGc,EAAQ,KAAK,GAAGP,EAAM,QAAQ,CAAC,GACxBO;AACT"}
@@ -0,0 +1,2 @@
1
+ const e=require("./_validate.cjs"),t=require("./errors.cjs");function perpendicularDistance(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=r*r+i*i;return a===0?Math.hypot(e.x-t.x,e.y-t.y):Math.abs(i*e.x-r*e.y+n.x*t.y-n.y*t.x)/Math.sqrt(a)}function simplifyStroke(n,r){let i=e.requireStrokePoints(n);if(e.requireFiniteNumber(r,`tolerance`),r<0)throw new t.InkConfigError(`Expected tolerance to be >= 0, received ${r}.`);if(i.length<3)return i.map(e=>({...e}));let a=new Uint8Array(i.length);a[0]=1,a[i.length-1]=1;let o=[[0,i.length-1]];for(;o.length>0;){let[e,t]=o.pop(),n=-1,s=-1;for(let r=e+1;r<t;r++){let a=perpendicularDistance(i[r],i[e],i[t]);a>s&&(s=a,n=r)}n!==-1&&s>r&&(a[n]=1,o.push([e,n],[n,t]))}let s=[];for(let e=0;e<i.length;e++)a[e]&&s.push(i[e]);return s}exports.simplifyStroke=simplifyStroke;
2
+ //# sourceMappingURL=simplify.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simplify.cjs","names":["requireStrokePoints","InkConfigError","require__validate","require_errors","dx","b","a","dy","lenSq","p","input","points","tolerance","point","keep","stack","first","last","farthest","maxDistance","i","d","result"],"sources":["../src/simplify.ts"],"sourcesContent":["/** Ramer-Douglas-Peucker stroke decimation. */\n\nimport { requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { StrokePoint } from './types.js';\n\n/** Perpendicular distance from `p` to the infinite line through `a`-`b`; point distance when degenerate. */\nfunction perpendicularDistance(p: StrokePoint, a: StrokePoint, b: StrokePoint): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lenSq = dx * dx + dy * dy;\n if (lenSq === 0) return Math.hypot(p.x - a.x, p.y - a.y);\n const cross = Math.abs(dy * p.x - dx * p.y + b.x * a.y - b.y * a.x);\n return cross / Math.sqrt(lenSq);\n}\n\n/**\n * Decimate a stroke with Ramer-Douglas-Peucker: iteratively drop the point farthest from the\n * chord when its distance is under `tolerance`, keeping the first and last points. The result is\n * always a subsequence of the input (same object references), so metadata like `pressure` survives.\n *\n * @throws {import('./errors.js').InkConfigError} When `points` is invalid or `tolerance` is not a\n * non-negative finite number.\n */\nexport function simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[] {\n const input = requireStrokePoints(points);\n requireFiniteNumber(tolerance, 'tolerance');\n if (tolerance < 0) {\n throw new InkConfigError(`Expected tolerance to be >= 0, received ${tolerance}.`);\n }\n if (input.length < 3) return input.map((point) => ({ ...point }));\n\n // Iterative RDP with an explicit stack: no recursion depth limit on long strokes.\n const keep = new Uint8Array(input.length);\n keep[0] = 1;\n keep[input.length - 1] = 1;\n const stack: [number, number][] = [[0, input.length - 1]];\n while (stack.length > 0) {\n const [first, last] = stack.pop() as [number, number];\n let farthest = -1;\n let maxDistance = -1;\n for (let i = first + 1; i < last; i++) {\n const d = perpendicularDistance(input[i], input[first], input[last]);\n if (d > maxDistance) {\n maxDistance = d;\n farthest = i;\n }\n }\n if (farthest !== -1 && maxDistance > tolerance) {\n keep[farthest] = 1;\n stack.push([first, farthest], [farthest, last]);\n }\n }\n\n const result: StrokePoint[] = [];\n for (let i = 0; i < input.length; i++) {\n if (keep[i]) result.push(input[i]);\n }\n return result;\n}\n"],"mappings":"A,6DAOA,SAAS,sBAAsB,EAAgB,EAAgB,EAAwB,CACrF,IAAMI,EAA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Q,IAC5BI,EAAKM,IAAIE,EAAO,KAAKZ,EAAMU,EAAE,EAEnC,OAAOE,CACT,C"}
@@ -0,0 +1,12 @@
1
+ /** Ramer-Douglas-Peucker stroke decimation. */
2
+ import type { StrokePoint } from './types.js';
3
+ /**
4
+ * Decimate a stroke with Ramer-Douglas-Peucker: iteratively drop the point farthest from the
5
+ * chord when its distance is under `tolerance`, keeping the first and last points. The result is
6
+ * always a subsequence of the input (same object references), so metadata like `pressure` survives.
7
+ *
8
+ * @throws {import('./errors.js').InkConfigError} When `points` is invalid or `tolerance` is not a
9
+ * non-negative finite number.
10
+ */
11
+ export declare function simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[];
12
+ //# sourceMappingURL=simplify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simplify.d.ts","sourceRoot":"","sources":["../src/simplify.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAI/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAY9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,WAAW,EAAE,CAmC/F"}
@@ -0,0 +1,29 @@
1
+ import { requireFiniteNumber as e, requireStrokePoints as t } from "./_validate.js";
2
+ import { InkConfigError as n } from "./errors.js";
3
+ // src/simplify.ts
4
+ function perpendicularDistance(e, t, n) {
5
+ let r = n.x - t.x, i = n.y - t.y, a = r * r + i * i;
6
+ return a === 0 ? Math.hypot(e.x - t.x, e.y - t.y) : Math.abs(i * e.x - r * e.y + n.x * t.y - n.y * t.x) / Math.sqrt(a);
7
+ }
8
+ function simplifyStroke(r, i) {
9
+ let a = t(r);
10
+ if (e(i, "tolerance"), i < 0) throw new n(`Expected tolerance to be >= 0, received ${i}.`);
11
+ if (a.length < 3) return a.map((e) => ({ ...e }));
12
+ let o = new Uint8Array(a.length);
13
+ o[0] = 1, o[a.length - 1] = 1;
14
+ let s = [[0, a.length - 1]];
15
+ for (; s.length > 0;) {
16
+ let [e, t] = s.pop(), n = -1, r = -1;
17
+ for (let i = e + 1; i < t; i++) {
18
+ let o = perpendicularDistance(a[i], a[e], a[t]);
19
+ o > r && (r = o, n = i);
20
+ }
21
+ n !== -1 && r > i && (o[n] = 1, s.push([e, n], [n, t]));
22
+ }
23
+ let c = [];
24
+ for (let e = 0; e < a.length; e++) o[e] && c.push(a[e]);
25
+ return c;
26
+ }
27
+ export { simplifyStroke };
28
+
29
+ //# sourceMappingURL=simplify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simplify.js","names":["dx","b","a","dy","lenSq","p","input","requireStrokePoints","points","requireFiniteNumber","tolerance","InkConfigError","point","keep","stack","first","last","farthest","maxDistance","d","result","i"],"sources":["../src/simplify.ts"],"sourcesContent":["/** Ramer-Douglas-Peucker stroke decimation. */\n\nimport { requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { StrokePoint } from './types.js';\n\n/** Perpendicular distance from `p` to the infinite line through `a`-`b`; point distance when degenerate. */\nfunction perpendicularDistance(p: StrokePoint, a: StrokePoint, b: StrokePoint): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lenSq = dx * dx + dy * dy;\n if (lenSq === 0) return Math.hypot(p.x - a.x, p.y - a.y);\n const cross = Math.abs(dy * p.x - dx * p.y + b.x * a.y - b.y * a.x);\n return cross / Math.sqrt(lenSq);\n}\n\n/**\n * Decimate a stroke with Ramer-Douglas-Peucker: iteratively drop the point farthest from the\n * chord when its distance is under `tolerance`, keeping the first and last points. The result is\n * always a subsequence of the input (same object references), so metadata like `pressure` survives.\n *\n * @throws {import('./errors.js').InkConfigError} When `points` is invalid or `tolerance` is not a\n * non-negative finite number.\n */\nexport function simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[] {\n const input = requireStrokePoints(points);\n requireFiniteNumber(tolerance, 'tolerance');\n if (tolerance < 0) {\n throw new InkConfigError(`Expected tolerance to be >= 0, received ${tolerance}.`);\n }\n if (input.length < 3) return input.map((point) => ({ ...point }));\n\n // Iterative RDP with an explicit stack: no recursion depth limit on long strokes.\n const keep = new Uint8Array(input.length);\n keep[0] = 1;\n keep[input.length - 1] = 1;\n const stack: [number, number][] = [[0, input.length - 1]];\n while (stack.length > 0) {\n const [first, last] = stack.pop() as [number, number];\n let farthest = -1;\n let maxDistance = -1;\n for (let i = first + 1; i < last; i++) {\n const d = perpendicularDistance(input[i], input[first], input[last]);\n if (d > maxDistance) {\n maxDistance = d;\n farthest = i;\n }\n }\n if (farthest !== -1 && maxDistance > tolerance) {\n keep[farthest] = 1;\n stack.push([first, farthest], [farthest, last]);\n }\n }\n\n const result: StrokePoint[] = [];\n for (let i = 0; i < input.length; i++) {\n if (keep[i]) result.push(input[i]);\n }\n return result;\n}\n"],"mappings":";;;AAOA,SAAS,sBAAsB,GAAgB,GAAgB,GAAwB;CACrF,IAAMA,IAAKC,EAAE,IAAIC,EAAE,GACbC,IAAKF,EAAE,IAAIC,EAAE,GACbE,IAAQJ,IAAKA,IAAKG,IAAKA;CAG7B,OAFIC,MAAU,IAAU,KAAK,MAAMC,EAAE,IAAIH,EAAE,GAAGG,EAAE,IAAIH,EAAE,CAAC,IACzC,KAAK,IAAIC,IAAKE,EAAE,IAAIL,IAAKK,EAAE,IAAIJ,EAAE,IAAIC,EAAE,IAAID,EAAE,IAAIC,EAAE,CAC1D,IAAQ,KAAK,KAAKE,CAAK;AAChC;AAUA,SAAgB,eAAe,GAAgC,GAAkC;CAC/F,IAAME,IAAQC,EAAoBC,CAAM;CAExC,IADAC,EAAoBC,GAAW,WAAW,GACtCA,IAAY,GACd,MAAM,IAAIC,EAAe,2CAA2CD,EAAU,EAAE;CAElF,IAAIJ,EAAM,SAAS,GAAG,OAAOA,EAAM,KAAK,OAAW,EAAE,GAAGM,EAAM,EAAE;CAGhE,IAAMC,IAAO,IAAI,WAAWP,EAAM,MAAM;CAExC,AADA,EAAK,KAAK,GACV,EAAKA,EAAM,SAAS,KAAK;CACzB,IAAMQ,IAA4B,CAAC,CAAC,GAAGR,EAAM,SAAS,CAAC,CAAC;CACxD,OAAOQ,EAAM,SAAS,IAAG;EACvB,IAAM,CAACC,GAAOC,KAAQF,EAAM,IAAI,GAC5BG,IAAW,IACXC,IAAc;EAClB,KAAK,IAAI,IAAIH,IAAQ,GAAG,IAAIC,GAAM,KAAK;GACrC,IAAMG,IAAI,sBAAsBb,EAAM,IAAIA,EAAMS,IAAQT,EAAMU,EAAK;GACnE,AAAIG,IAAID,MACN,IAAcC,GACd,IAAW;EAEf;EACA,AAAIF,MAAa,MAAMC,IAAcR,MACnC,EAAKO,KAAY,GACjBH,EAAM,KAAK,CAACC,GAAOE,CAAQ,GAAG,CAACA,GAAUD,CAAI,CAAC;CAElD;CAEA,IAAMI,IAAwB,CAAC;CAC/B,KAAK,IAAIC,IAAI,GAAGA,IAAIf,EAAM,QAAQ,KAChC,AAAIO,EAAKQ,MAAID,EAAO,KAAKd,EAAMe,EAAE;CAEnC,OAAOD;AACT"}
@@ -0,0 +1,2 @@
1
+ const e=require("./_validate.cjs");function catmullRomAxis(e,t,n,r,i,a){let o=t+(n-t)*i,s=i*i,c=s*i;return o+a*(.5*(2*t+i*(n-e)+s*(2*e-5*t+4*n-r)+c*(3*t-3*n-e+r))-o)}function lerpField(e,t,n){return e!==void 0&&t!==void 0?e+(t-e)*n:e??t}function emitPoint(e,t,n,r){let i={x:e,y:t};return n!==void 0&&(i.pressure=n),r!==void 0&&(i.time=r),i}function catmullRomResample(t,n,r){let i=[],a=t.length-1,at=n=>t[e.clamp(n,0,a)];for(let e=0;e<a;e++){let[t,a,o,s]=[at(e-1),at(e),at(e+1),at(e+2)];for(let e=0;e<r;e++){let c=e/r;i.push(emitPoint(catmullRomAxis(t.x,a.x,o.x,s.x,c,n),catmullRomAxis(t.y,a.y,o.y,s.y,c,n),lerpField(a.pressure,o.pressure,c),lerpField(a.time,o.time,c)))}}return i.push(emitPoint(t[a].x,t[a].y,t[a].pressure,t[a].time)),i}function smoothStroke(t,n={}){let r=e.requireStrokePoints(t),i=e.requireRange(n.tension??1,`tension`,0,1),a=e.requireInteger(n.steps??8,`steps`,2,1e3);return r.length<3?r.map(e=>({...e})):catmullRomResample(r,i,a)}exports.smoothStroke=smoothStroke;
2
+ //# sourceMappingURL=smoothing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smoothing.cjs","names":["clamp","requireStrokePoints","requireRange","requireInteger","require__validate","linear","p1","p2","t","t2","t3","alpha","p0","p3","a","b","point","pressure","time","result","last","points","index","i","s","steps","tension","input","options"],"sources":["../src/smoothing.ts"],"sourcesContent":["/** Stroke smoothing: deterministic Catmull-Rom resampling. */\n\nimport { clamp, requireInteger, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface SmoothStrokeOptions {\n /** Samples emitted per input segment (minimum 2). Default 8. */\n steps?: number;\n /** Interpolation tension. `0` is linear, `1` is the standard uniform spline. Default `1`. */\n tension?: number;\n}\n\n/**\n * Interpolation basis for one axis; `t` in `[0, 1]`. `alpha` blends linear\n * interpolation (`alpha = 0`) with the standard uniform Catmull-Rom spline\n * (`alpha = 1`), so `tension: 0` is genuinely linear.\n */\nfunction catmullRomAxis(p0: number, p1: number, p2: number, p3: number, t: number, alpha: number): number {\n const linear = p1 + (p2 - p1) * t;\n const t2 = t * t;\n const t3 = t2 * t;\n const spline =\n 0.5 * (2 * p1 + t * (p2 - p0) + t2 * (2 * p0 - 5 * p1 + 4 * p2 - p3) + t3 * (3 * p1 - 3 * p2 - p0 + p3));\n return linear + alpha * (spline - linear);\n}\n\n/** Linear interpolation of optional metadata; keeps the field absent when neither side has it. */\nfunction lerpField(a: number | undefined, b: number | undefined, t: number): number | undefined {\n if (a !== undefined && b !== undefined) return a + (b - a) * t;\n return a ?? b;\n}\n\nfunction emitPoint(x: number, y: number, pressure?: number, time?: number): StrokePoint {\n const point: { x: number; y: number; pressure?: number; time?: number } = { x, y };\n if (pressure !== undefined) point.pressure = pressure;\n if (time !== undefined) point.time = time;\n return point;\n}\n\nfunction catmullRomResample(points: readonly StrokePoint[], tension: number, steps: number): StrokePoint[] {\n const result: StrokePoint[] = [];\n const last = points.length - 1;\n // Duplicated end controls keep the spline interpolating the true endpoints.\n const at = (index: number): StrokePoint => points[clamp(index, 0, last)];\n for (let i = 0; i < last; i++) {\n const [p0, p1, p2, p3] = [at(i - 1), at(i), at(i + 1), at(i + 2)];\n for (let s = 0; s < steps; s++) {\n const t = s / steps;\n result.push(\n emitPoint(\n catmullRomAxis(p0.x, p1.x, p2.x, p3.x, t, tension),\n catmullRomAxis(p0.y, p1.y, p2.y, p3.y, t, tension),\n lerpField(p1.pressure, p2.pressure, t),\n lerpField(p1.time, p2.time, t),\n ),\n );\n }\n }\n result.push(emitPoint(points[last].x, points[last].y, points[last].pressure, points[last].time));\n return result;\n}\n\n/**\n * Resample a freehand stroke through a uniform Catmull-Rom spline: `steps` samples per input\n * segment, with the first and last input points preserved exactly. `pressure` and `time` are\n * interpolated linearly, so widths computed from the output match widths computed from the input.\n *\n * For jitter removal *while drawing*, use `stabilizeStroke` instead: this function adds points and\n * looks ahead, so it is the post-capture step.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range.\n */\nexport function smoothStroke(points: readonly StrokePoint[], options: SmoothStrokeOptions = {}): StrokePoint[] {\n const input = requireStrokePoints(points);\n const tension = requireRange(options.tension ?? 1, 'tension', 0, 1);\n const steps = requireInteger(options.steps ?? 8, 'steps', 2, 1000);\n if (input.length < 3) return input.map((point) => ({ ...point }));\n return catmullRomResample(input, tension, steps);\n}\n"],"mappings":"A,mCAiBA,SAAS,eAAe,EAAY,EAAY,EAAY,EAAY,EAAW,EAAuB,CACxG,IAAMK,EAASC,GAAMC,EAAKD,GAAME,EAC1BC,EAAKD,EAAIA,EACTE,EAAKD,EAAKD,EAGhB,OAAOH,EAASM,GADd,IAAO,EAAIL,EAAKE,GAAK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OD,EAAK,CAAC,EAAGC,EAAOD,EAAK,CAAC,SAAUC,EAAOD,EAAK,CAAC,IAAI,CAAC,EACxFD,CACT,CAYA,SAAgB,aAAa,EAAgC,EAA+B,CAAC,EAAkB,CAC7G,IAAMQ,EAAQ1B,EAAAA,oBAAoBoB,CAAM,EAClCK,EAAUxB,EAAAA,aAAa0B,EAAQ,SAAW,EAAG,UAAW,EAAG,CAAC,EAC5DH,EAAQtB,EAAAA,eAAeyB,EAAQ,OAAS,EAAG,QAAS,EAAG,GAAI,EAEjE,OADID,EAAM,OAAS,EAAUA,EAAM,IAAK,IAAW,CAAE,GAAGX,CAAM,EAAE,EACzD,mBAAmBW,EAAOD,EAASD,CAAK,CACjD,C"}
@@ -0,0 +1,20 @@
1
+ /** Stroke smoothing: deterministic Catmull-Rom resampling. */
2
+ import type { StrokePoint } from './types.js';
3
+ export interface SmoothStrokeOptions {
4
+ /** Samples emitted per input segment (minimum 2). Default 8. */
5
+ steps?: number;
6
+ /** Interpolation tension. `0` is linear, `1` is the standard uniform spline. Default `1`. */
7
+ tension?: number;
8
+ }
9
+ /**
10
+ * Resample a freehand stroke through a uniform Catmull-Rom spline: `steps` samples per input
11
+ * segment, with the first and last input points preserved exactly. `pressure` and `time` are
12
+ * interpolated linearly, so widths computed from the output match widths computed from the input.
13
+ *
14
+ * For jitter removal *while drawing*, use `stabilizeStroke` instead: this function adds points and
15
+ * looks ahead, so it is the post-capture step.
16
+ *
17
+ * @throws {import('./errors.js').InkConfigError} When options are out of range.
18
+ */
19
+ export declare function smoothStroke(points: readonly StrokePoint[], options?: SmoothStrokeOptions): StrokePoint[];
20
+ //# sourceMappingURL=smoothing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smoothing.d.ts","sourceRoot":"","sources":["../src/smoothing.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAG9D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,WAAW,mBAAmB;IAClC,gEAAgE;IAChE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6FAA6F;IAC7F,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAoDD;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,GAAE,mBAAwB,GAAG,WAAW,EAAE,CAM7G"}
@@ -0,0 +1,39 @@
1
+ import { clamp as e, requireInteger as t, requireRange as n, requireStrokePoints as r } from "./_validate.js";
2
+ // src/smoothing.ts
3
+ function catmullRomAxis(e, t, n, r, i, a) {
4
+ let o = t + (n - t) * i, s = i * i, c = s * i;
5
+ return o + a * (.5 * (2 * t + i * (n - e) + s * (2 * e - 5 * t + 4 * n - r) + c * (3 * t - 3 * n - e + r)) - o);
6
+ }
7
+ function lerpField(e, t, n) {
8
+ return e !== void 0 && t !== void 0 ? e + (t - e) * n : e ?? t;
9
+ }
10
+ function emitPoint(e, t, n, r) {
11
+ let i = {
12
+ x: e,
13
+ y: t
14
+ };
15
+ return n !== void 0 && (i.pressure = n), r !== void 0 && (i.time = r), i;
16
+ }
17
+ function catmullRomResample(t, n, r) {
18
+ let i = [], a = t.length - 1, at = (n) => t[e(n, 0, a)];
19
+ for (let e = 0; e < a; e++) {
20
+ let [t, a, o, s] = [
21
+ at(e - 1),
22
+ at(e),
23
+ at(e + 1),
24
+ at(e + 2)
25
+ ];
26
+ for (let e = 0; e < r; e++) {
27
+ let c = e / r;
28
+ i.push(emitPoint(catmullRomAxis(t.x, a.x, o.x, s.x, c, n), catmullRomAxis(t.y, a.y, o.y, s.y, c, n), lerpField(a.pressure, o.pressure, c), lerpField(a.time, o.time, c)));
29
+ }
30
+ }
31
+ return i.push(emitPoint(t[a].x, t[a].y, t[a].pressure, t[a].time)), i;
32
+ }
33
+ function smoothStroke(e, i = {}) {
34
+ let a = r(e), o = n(i.tension ?? 1, "tension", 0, 1), s = t(i.steps ?? 8, "steps", 2, 1e3);
35
+ return a.length < 3 ? a.map((e) => ({ ...e })) : catmullRomResample(a, o, s);
36
+ }
37
+ export { smoothStroke };
38
+
39
+ //# sourceMappingURL=smoothing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smoothing.js","names":["linear","p1","p2","t","t2","t3","alpha","p0","p3","a","b","point","pressure","time","result","last","points","clamp","index","i","s","steps","tension","input","requireStrokePoints","requireRange","options","requireInteger"],"sources":["../src/smoothing.ts"],"sourcesContent":["/** Stroke smoothing: deterministic Catmull-Rom resampling. */\n\nimport { clamp, requireInteger, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface SmoothStrokeOptions {\n /** Samples emitted per input segment (minimum 2). Default 8. */\n steps?: number;\n /** Interpolation tension. `0` is linear, `1` is the standard uniform spline. Default `1`. */\n tension?: number;\n}\n\n/**\n * Interpolation basis for one axis; `t` in `[0, 1]`. `alpha` blends linear\n * interpolation (`alpha = 0`) with the standard uniform Catmull-Rom spline\n * (`alpha = 1`), so `tension: 0` is genuinely linear.\n */\nfunction catmullRomAxis(p0: number, p1: number, p2: number, p3: number, t: number, alpha: number): number {\n const linear = p1 + (p2 - p1) * t;\n const t2 = t * t;\n const t3 = t2 * t;\n const spline =\n 0.5 * (2 * p1 + t * (p2 - p0) + t2 * (2 * p0 - 5 * p1 + 4 * p2 - p3) + t3 * (3 * p1 - 3 * p2 - p0 + p3));\n return linear + alpha * (spline - linear);\n}\n\n/** Linear interpolation of optional metadata; keeps the field absent when neither side has it. */\nfunction lerpField(a: number | undefined, b: number | undefined, t: number): number | undefined {\n if (a !== undefined && b !== undefined) return a + (b - a) * t;\n return a ?? b;\n}\n\nfunction emitPoint(x: number, y: number, pressure?: number, time?: number): StrokePoint {\n const point: { x: number; y: number; pressure?: number; time?: number } = { x, y };\n if (pressure !== undefined) point.pressure = pressure;\n if (time !== undefined) point.time = time;\n return point;\n}\n\nfunction catmullRomResample(points: readonly StrokePoint[], tension: number, steps: number): StrokePoint[] {\n const result: StrokePoint[] = [];\n const last = points.length - 1;\n // Duplicated end controls keep the spline interpolating the true endpoints.\n const at = (index: number): StrokePoint => points[clamp(index, 0, last)];\n for (let i = 0; i < last; i++) {\n const [p0, p1, p2, p3] = [at(i - 1), at(i), at(i + 1), at(i + 2)];\n for (let s = 0; s < steps; s++) {\n const t = s / steps;\n result.push(\n emitPoint(\n catmullRomAxis(p0.x, p1.x, p2.x, p3.x, t, tension),\n catmullRomAxis(p0.y, p1.y, p2.y, p3.y, t, tension),\n lerpField(p1.pressure, p2.pressure, t),\n lerpField(p1.time, p2.time, t),\n ),\n );\n }\n }\n result.push(emitPoint(points[last].x, points[last].y, points[last].pressure, points[last].time));\n return result;\n}\n\n/**\n * Resample a freehand stroke through a uniform Catmull-Rom spline: `steps` samples per input\n * segment, with the first and last input points preserved exactly. `pressure` and `time` are\n * interpolated linearly, so widths computed from the output match widths computed from the input.\n *\n * For jitter removal *while drawing*, use `stabilizeStroke` instead: this function adds points and\n * looks ahead, so it is the post-capture step.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range.\n */\nexport function smoothStroke(points: readonly StrokePoint[], options: SmoothStrokeOptions = {}): StrokePoint[] {\n const input = requireStrokePoints(points);\n const tension = requireRange(options.tension ?? 1, 'tension', 0, 1);\n const steps = requireInteger(options.steps ?? 8, 'steps', 2, 1000);\n if (input.length < 3) return input.map((point) => ({ ...point }));\n return catmullRomResample(input, tension, steps);\n}\n"],"mappings":";;AAiBA,SAAS,eAAe,GAAY,GAAY,GAAY,GAAY,GAAW,GAAuB;CACxG,IAAMA,IAASC,KAAMC,IAAKD,KAAME,GAC1BC,IAAKD,IAAIA,GACTE,IAAKD,IAAKD;CAGhB,OAAOH,IAASM,KADd,MAAO,IAAIL,IAAKE,KAAKD,IAAKK,KAAMH,KAAM,IAAIG,IAAK,IAAIN,IAAK,IAAIC,IAAKM,KAAMH,KAAM,IAAIJ,IAAK,IAAIC,IAAKK,IAAKC,MACpER;AACpC;AAGA,SAAS,UAAU,GAAuB,GAAuB,G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AAM,GAClCM,IAAUG,EAAaC,EAAQ,WAAW,GAAG,WAAW,GAAG,CAAC,GAC5DL,IAAQM,EAAeD,EAAQ,SAAS,GAAG,SAAS,GAAG,GAAI;CAEjE,OADIH,EAAM,SAAS,IAAUA,EAAM,KAAK,OAAW,EAAE,GAAGZ,EAAM,EAAE,IACzD,mBAAmBY,GAAOD,GAASD,CAAK;AACjD"}
@@ -0,0 +1,2 @@
1
+ const e=require("./_validate.cjs");function stabilizeStroke(t,n={}){let r=e.requireStrokePoints(t),i=e.requireRange(n.strength??.5,`strength`,0,1);if(r.length<2)return r.map(e=>({...e}));let a=1-i*.9,o=(1-a)*2,emit=(e,t,n)=>{let r={x:e,y:t};return n.pressure!==void 0&&(r.pressure=n.pressure),n.time!==void 0&&(r.time=n.time),r},s=[emit(r[0].x,r[0].y,r[0])],c=r[0].x,l=r[0].y;for(let t=1;t<r.length;t++){let n=r[t];if(t===r.length-1){s.push(emit(n.x,n.y,n));break}e.distance(c,l,n.x,n.y)<o||(c+=(n.x-c)*a,l+=(n.y-l)*a),s.push(emit(c,l,n))}return s}exports.stabilizeStroke=stabilizeStroke;
2
+ //# sourceMappingURL=stabilize.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stabilize.cjs","names":["requireStrokePoints","requireRange","distance","require__validate","input","points","strength","options","point","alpha","deadZone","source","result","sx","sy","i"],"sources":["../src/stabilize.ts"],"sourcesContent":["/** Causal stroke stabilization: Streamline-style low-pass for use while drawing. */\n\nimport { distance, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StabilizeStrokeOptions {\n /**\n * How strongly the filter pulls toward each incoming sample. `0` keeps the raw input,\n * `1` is maximum smoothing. Default `0.5`.\n */\n strength?: number;\n}\n\n/**\n * Remove hand jitter from a stroke *while it is being drawn*: a causal exponential\n * average toward each incoming sample, with a jitter dead zone so straight lines stay crisp.\n *\n * Output length always equals input length, so per-point widths and metadata stay aligned with\n * the source samples. The last output point is always the last input point — the stroke ends\n * exactly where the pen lifted, never short of it. Inside the dead zone the previous smoothed\n * position repeats, but the incoming sample's `pressure` and `time` are carried through.\n *\n * Deterministic and pure: the same input always returns the same output.\n *\n * @throws {import('./errors.js').InkConfigError} When `strength` is out of range.\n */\nexport function stabilizeStroke(points: readonly StrokePoint[], options: StabilizeStrokeOptions = {}): StrokePoint[] {\n const input = requireStrokePoints(points);\n const strength = requireRange(options.strength ?? 0.5, 'strength', 0, 1);\n if (input.length < 2) return input.map((point) => ({ ...point }));\n // strength 0 -> alpha 1 (no smoothing); strength 1 -> alpha 0.1 (heavy smoothing).\n const alpha = 1 - strength * 0.9;\n const deadZone = (1 - alpha) * 2;\n const emit = (x: number, y: number, source: StrokePoint): StrokePoint => {\n const point: { x: number; y: number; pressure?: number; time?: number } = { x, y };\n if (source.pressure !== undefined) point.pressure = source.pressure;\n if (source.time !== undefined) point.time = source.time;\n return point;\n };\n\n const result: StrokePoint[] = [emit(input[0].x, input[0].y, input[0])];\n let sx = input[0].x;\n let sy = input[0].y;\n for (let i = 1; i < input.length; i++) {\n const point = input[i];\n if (i === input.length - 1) {\n // Snap to the final sample so the stroke never trails past where the pen lifted.\n result.push(emit(point.x, point.y, point));\n break;\n }\n if (distance(sx, sy, point.x, point.y) < deadZone) {\n result.push(emit(sx, sy, point));\n continue;\n }\n sx += (point.x - sx) * alpha;\n sy += (point.y - sy) * alpha;\n result.push(emit(sx, sy, point));\n }\n return result;\n}\n"],"mappings":"A,mCA0BA,SAAgB,gBAAgB,EAAgC,EAAkC,CAAC,EAAkB,CACnH,IAAMI,EAAQJ,EAAAA,oBAAoBK,CAAM,EAClCC,EAAWL,EAAAA,aAAaM,EAAQ,UAAY,GAAK,WAAY,EAAG,CAAC,EACvE,GAAIH,EAAM,OAAS,EAAG,OAAOA,EAAM,IAAK,IAAW,CAAE,GAAGI,CAAM,EAAE,EAEhE,IAAMC,EAAQ,EAAIH,EAAW,GACvBI,GAAY,EAAID,GAAS,EACzB,MAAQ,EAAW,EAAW,IAAqC,CACvE,IAAMD,EAAoE,CAAE,IAAG,GAAE,EAGjF,OAFIG,EAAO,WAAa,IAAA,KAAW,EAAM,SAAWA,EAAO,UACvDA,EAAO,OAAS,IAAA,KAAW,EAAM,KAAOA,EAAO,MAC5CH,CACT,EAEMI,EAAwB,CAAC,KAAKR,EAAM,EAAE,CAAC,EAAGA,EAAM,EAAE,CAAC,EAAGA,EAAM,EAAE,CAAC,EACjES,EAAKT,EAAM,EAAE,CAAC,EACdU,EAAKV,EAAM,EAAE,CAAC,EAClB,IAAK,IAAIW,EAAI,EAAGA,EAAIX,EAAM,OAAQ,IAAK,CACrC,IAAMI,EAAQJ,EAAMW,GACpB,GAAIA,IAAMX,EAAM,OAAS,EAAG,CAE1BQ,EAAO,KAAK,KAAKJ,EAAM,EAAGA,EAAM,EAAGA,CAAK,CAAC,EACzC,KACF,CACIN,EAAAA,SAASW,EAAIC,EAAIN,EAAM,EAAGA,EAAM,CAAC,EAAIE,IAIzC,IAAOF,EAAM,EAAIK,GAAMJ,EACvB,IAAOD,EAAM,EAAIM,GAAML,GACvBG,EAAO,KAAK,KAAKC,EAAIC,EAAIN,CAAK,CAAC,CACjC,CACA,OAAOI,CACT,C"}
@@ -0,0 +1,24 @@
1
+ /** Causal stroke stabilization: Streamline-style low-pass for use while drawing. */
2
+ import type { StrokePoint } from './types.js';
3
+ export interface StabilizeStrokeOptions {
4
+ /**
5
+ * How strongly the filter pulls toward each incoming sample. `0` keeps the raw input,
6
+ * `1` is maximum smoothing. Default `0.5`.
7
+ */
8
+ strength?: number;
9
+ }
10
+ /**
11
+ * Remove hand jitter from a stroke *while it is being drawn*: a causal exponential
12
+ * average toward each incoming sample, with a jitter dead zone so straight lines stay crisp.
13
+ *
14
+ * Output length always equals input length, so per-point widths and metadata stay aligned with
15
+ * the source samples. The last output point is always the last input point — the stroke ends
16
+ * exactly where the pen lifted, never short of it. Inside the dead zone the previous smoothed
17
+ * position repeats, but the incoming sample's `pressure` and `time` are carried through.
18
+ *
19
+ * Deterministic and pure: the same input always returns the same output.
20
+ *
21
+ * @throws {import('./errors.js').InkConfigError} When `strength` is out of range.
22
+ */
23
+ export declare function stabilizeStroke(points: readonly StrokePoint[], options?: StabilizeStrokeOptions): StrokePoint[];
24
+ //# sourceMappingURL=stabilize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stabilize.d.ts","sourceRoot":"","sources":["../src/stabilize.ts"],"names":[],"mappings":"AAAA,oFAAoF;AAGpF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,WAAW,sBAAsB;IACrC;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,GAAE,sBAA2B,GAAG,WAAW,EAAE,CAiCnH"}
@@ -0,0 +1,25 @@
1
+ import { distance as e, requireRange as t, requireStrokePoints as n } from "./_validate.js";
2
+ // src/stabilize.ts
3
+ function stabilizeStroke(r, i = {}) {
4
+ let a = n(r), o = t(i.strength ?? .5, "strength", 0, 1);
5
+ if (a.length < 2) return a.map((e) => ({ ...e }));
6
+ let s = 1 - o * .9, c = (1 - s) * 2, emit = (e, t, n) => {
7
+ let r = {
8
+ x: e,
9
+ y: t
10
+ };
11
+ return n.pressure !== void 0 && (r.pressure = n.pressure), n.time !== void 0 && (r.time = n.time), r;
12
+ }, l = [emit(a[0].x, a[0].y, a[0])], u = a[0].x, d = a[0].y;
13
+ for (let t = 1; t < a.length; t++) {
14
+ let n = a[t];
15
+ if (t === a.length - 1) {
16
+ l.push(emit(n.x, n.y, n));
17
+ break;
18
+ }
19
+ e(u, d, n.x, n.y) < c || (u += (n.x - u) * s, d += (n.y - d) * s), l.push(emit(u, d, n));
20
+ }
21
+ return l;
22
+ }
23
+ export { stabilizeStroke };
24
+
25
+ //# sourceMappingURL=stabilize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stabilize.js","names":["input","requireStrokePoints","points","strength","requireRange","options","point","alpha","deadZone","source","result","sx","sy","i","distance"],"sources":["../src/stabilize.ts"],"sourcesContent":["/** Causal stroke stabilization: Streamline-style low-pass for use while drawing. */\n\nimport { distance, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StabilizeStrokeOptions {\n /**\n * How strongly the filter pulls toward each incoming sample. `0` keeps the raw input,\n * `1` is maximum smoothing. Default `0.5`.\n */\n strength?: number;\n}\n\n/**\n * Remove hand jitter from a stroke *while it is being drawn*: a causal exponential\n * average toward each incoming sample, with a jitter dead zone so straight lines stay crisp.\n *\n * Output length always equals input length, so per-point widths and metadata stay aligned with\n * the source samples. The last output point is always the last input point — the stroke ends\n * exactly where the pen lifted, never short of it. Inside the dead zone the previous smoothed\n * position repeats, but the incoming sample's `pressure` and `time` are carried through.\n *\n * Deterministic and pure: the same input always returns the same output.\n *\n * @throws {import('./errors.js').InkConfigError} When `strength` is out of range.\n */\nexport function stabilizeStroke(points: readonly StrokePoint[], options: StabilizeStrokeOptions = {}): StrokePoint[] {\n const input = requireStrokePoints(points);\n const strength = requireRange(options.strength ?? 0.5, 'strength', 0, 1);\n if (input.length < 2) return input.map((point) => ({ ...point }));\n // strength 0 -> alpha 1 (no smoothing); strength 1 -> alpha 0.1 (heavy smoothing).\n const alpha = 1 - strength * 0.9;\n const deadZone = (1 - alpha) * 2;\n const emit = (x: number, y: number, source: StrokePoint): StrokePoint => {\n const point: { x: number; y: number; pressure?: number; time?: number } = { x, y };\n if (source.pressure !== undefined) point.pressure = source.pressure;\n if (source.time !== undefined) point.time = source.time;\n return point;\n };\n\n const result: StrokePoint[] = [emit(input[0].x, input[0].y, input[0])];\n let sx = input[0].x;\n let sy = input[0].y;\n for (let i = 1; i < input.length; i++) {\n const point = input[i];\n if (i === input.length - 1) {\n // Snap to the final sample so the stroke never trails past where the pen lifted.\n result.push(emit(point.x, point.y, point));\n break;\n }\n if (distance(sx, sy, point.x, point.y) < deadZone) {\n result.push(emit(sx, sy, point));\n continue;\n }\n sx += (point.x - sx) * alpha;\n sy += (point.y - sy) * alpha;\n result.push(emit(sx, sy, point));\n }\n return result;\n}\n"],"mappings":";;AA0BA,SAAgB,gBAAgB,GAAgC,IAAkC,CAAC,GAAkB;CACnH,IAAMA,IAAQC,EAAoBC,CAAM,GAClCC,IAAWC,EAAaC,EAAQ,YAAY,IAAK,YAAY,GAAG,CAAC;CACvE,IAAIL,EAAM,SAAS,GAAG,OAAOA,EAAM,KAAK,OAAW,EAAE,GAAGM,EAAM,EAAE;CAEhE,IAAMC,IAAQ,IAAIJ,IAAW,IACvBK,KAAY,IAAID,KAAS,GACzB,QAAQ,GAAW,GAAW,MAAqC;EACvE,IAAMD,IAAoE;GAAE;GAAG;EAAE;EAGjF,OAFIG,EAAO,aAAa,KAAA,MAAW,EAAM,WAAWA,EAAO,WACvDA,EAAO,SAAS,KAAA,MAAW,EAAM,OAAOA,EAAO,OAC5CH;CACT,GAEMI,IAAwB,CAAC,KAAKV,EAAM,EAAE,CAAC,GAAGA,EAAM,EAAE,CAAC,GAAGA,EAAM,EAAE,CAAC,GACjEW,IAAKX,EAAM,EAAE,CAAC,GACdY,IAAKZ,EAAM,EAAE,CAAC;CAClB,KAAK,IAAIa,IAAI,GAAGA,IAAIb,EAAM,QAAQ,KAAK;EACrC,IAAMM,IAAQN,EAAMa;EACpB,IAAIA,MAAMb,EAAM,SAAS,GAAG;GAE1B,EAAO,KAAK,KAAKM,EAAM,GAAGA,EAAM,GAAGA,CAAK,CAAC;GACzC;EACF;EACA,AAAIQ,EAASH,GAAIC,GAAIN,EAAM,GAAGA,EAAM,CAAC,IAAIE,MAIzC,MAAOF,EAAM,IAAIK,KAAMJ,GACvB,MAAOD,EAAM,IAAIM,KAAML,IACvBG,EAAO,KAAK,KAAKC,GAAIC,GAAIN,CAAK,CAAC;CACjC;CACA,OAAOI;AACT"}
package/dist/svg.cjs ADDED
@@ -0,0 +1,2 @@
1
+ const e=require("./_validate.cjs");function format(e,t){let n=Number(e.toFixed(t))+0;return String(n)}function polylineToSvgPath(t,n={}){let r=e.requireStrokePoints(t,1),i=n.close??!1,a=e.requireInteger(n.precision??2,`precision`,0,12),o=[`M ${format(r[0].x,a)} ${format(r[0].y,a)}`];for(let e=1;e<r.length;e++)o.push(`L ${format(r[e].x,a)} ${format(r[e].y,a)}`);return i&&o.push(`Z`),o.join(` `)}exports.polylineToSvgPath=polylineToSvgPath;
2
+ //# sourceMappingURL=svg.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"svg.cjs","names":["requireStrokePoints","requireInteger","require__validate","rounded","value","precision","input","points","close","options","parts","i"],"sources":["../src/svg.ts"],"sourcesContent":["/** SVG path `d` string output for polylines and outline polygons. */\n\nimport { requireInteger, requireStrokePoints } from './_validate.js';\nimport type { Point } from './types.js';\n\nexport interface PolylineToSvgPathOptions {\n /** Append `Z` to close the path. Use for outline rings from `strokeOutline`. Default `false`. */\n close?: boolean;\n /** Decimal places for emitted coordinates (`0`-`12`). Default `2`. */\n precision?: number;\n}\n\nfunction format(value: number, precision: number): string {\n // `+ 0` normalizes -0 to 0 so output is stable across platforms.\n const rounded = Number(value.toFixed(precision)) + 0;\n return String(rounded);\n}\n\n/**\n * Serialize a polyline as an SVG path `d` string: `M x y` followed by one `L x y` per remaining\n * point. Coordinates are rounded to `precision` decimal places.\n *\n * Works for both open strokes and closed rings: pass `close: true` for the outline polygon\n * returned by `strokeOutline`.\n *\n * @example\n * ```ts\n * polylineToSvgPath([{ x: 0, y: 0 }, { x: 10, y: 5 }]);\n * // 'M 0 0 L 10 5'\n * polylineToSvgPath(strokeOutline(points, 4), { close: true });\n * // 'M ... L ... Z'\n * ```\n *\n * @throws {import('./errors.js').InkConfigError} When `points` is empty or `precision` is out of range.\n */\nexport function polylineToSvgPath(points: readonly Point[], options: PolylineToSvgPathOptions = {}): string {\n const input = requireStrokePoints(points, 1);\n const close = options.close ?? false;\n const precision = requireInteger(options.precision ?? 2, 'precision', 0, 12);\n const parts: string[] = [`M ${format(input[0].x, precision)} ${format(input[0].y, precision)}`];\n for (let i = 1; i < input.length; i++) {\n parts.push(`L ${format(input[i].x, precision)} ${format(input[i].y, precision)}`);\n }\n if (close) parts.push('Z');\n return parts.join(' ');\n}\n"],"mappings":"A,mCAYA,SAAS,OAAO,EAAe,EAA2B,CAExD,IAAMG,EAAU,OAAOC,EAAM,QAAQC,CAAS,CAAC,EAAI,EACnD,OAAO,OAAOF,CAAO,CACvB,CAmBA,SAAgB,kBAAkB,EAA0B,EAAoC,CAAC,EAAW,CAC1G,IAAMG,EAAQN,EAAAA,oBAAoBO,EAAQ,CAAC,EACrCC,EAAQC,EAAQ,OAAS,GACzBJ,EAAYJ,EAAAA,eAAeQ,EAAQ,WAAa,EAAG,YAAa,EAAG,EAAE,EACrEC,EAAkB,CAAC,KAAK,OAAOJ,EAAM,EAAE,CAAC,EAAGD,CAAS,EAAE,GAAG,OAAOC,EAAM,EAAE,CAAC,EAAGD,CAAS,GAAG,EAC9F,IAAK,IAAIM,EAAI,EAAGA,EAAIL,EAAM,OAAQ,IAChCI,EAAM,KAAK,KAAK,OAAOJ,EAAMK,EAAE,CAAC,EAAGN,CAAS,EAAE,GAAG,OAAOC,EAAMK,EAAE,CAAC,EAAGN,CAAS,GAAG,EAGlF,OADIG,GAAOE,EAAM,KAAK,GAAG,EAClBA,EAAM,KAAK,GAAG,CACvB,C"}
package/dist/svg.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /** SVG path `d` string output for polylines and outline polygons. */
2
+ import type { Point } from './types.js';
3
+ export interface PolylineToSvgPathOptions {
4
+ /** Append `Z` to close the path. Use for outline rings from `strokeOutline`. Default `false`. */
5
+ close?: boolean;
6
+ /** Decimal places for emitted coordinates (`0`-`12`). Default `2`. */
7
+ precision?: number;
8
+ }
9
+ /**
10
+ * Serialize a polyline as an SVG path `d` string: `M x y` followed by one `L x y` per remaining
11
+ * point. Coordinates are rounded to `precision` decimal places.
12
+ *
13
+ * Works for both open strokes and closed rings: pass `close: true` for the outline polygon
14
+ * returned by `strokeOutline`.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * polylineToSvgPath([{ x: 0, y: 0 }, { x: 10, y: 5 }]);
19
+ * // 'M 0 0 L 10 5'
20
+ * polylineToSvgPath(strokeOutline(points, 4), { close: true });
21
+ * // 'M ... L ... Z'
22
+ * ```
23
+ *
24
+ * @throws {import('./errors.js').InkConfigError} When `points` is empty or `precision` is out of range.
25
+ */
26
+ export declare function polylineToSvgPath(points: readonly Point[], options?: PolylineToSvgPathOptions): string;
27
+ //# sourceMappingURL=svg.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"svg.d.ts","sourceRoot":"","sources":["../src/svg.ts"],"names":[],"mappings":"AAAA,qEAAqE;AAGrE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,MAAM,WAAW,wBAAwB;IACvC,iGAAiG;IACjG,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAQD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,EAAE,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAU1G"}
package/dist/svg.js ADDED
@@ -0,0 +1,14 @@
1
+ import { requireInteger as e, requireStrokePoints as t } from "./_validate.js";
2
+ // src/svg.ts
3
+ function format(e, t) {
4
+ let n = Number(e.toFixed(t)) + 0;
5
+ return String(n);
6
+ }
7
+ function polylineToSvgPath(n, r = {}) {
8
+ let i = t(n, 1), a = r.close ?? !1, o = e(r.precision ?? 2, "precision", 0, 12), s = [`M ${format(i[0].x, o)} ${format(i[0].y, o)}`];
9
+ for (let e = 1; e < i.length; e++) s.push(`L ${format(i[e].x, o)} ${format(i[e].y, o)}`);
10
+ return a && s.push("Z"), s.join(" ");
11
+ }
12
+ export { polylineToSvgPath };
13
+
14
+ //# sourceMappingURL=svg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"svg.js","names":["rounded","value","precision","input","requireStrokePoints","points","close","options","requireInteger","parts","i"],"sources":["../src/svg.ts"],"sourcesContent":["/** SVG path `d` string output for polylines and outline polygons. */\n\nimport { requireInteger, requireStrokePoints } from './_validate.js';\nimport type { Point } from './types.js';\n\nexport interface PolylineToSvgPathOptions {\n /** Append `Z` to close the path. Use for outline rings from `strokeOutline`. Default `false`. */\n close?: boolean;\n /** Decimal places for emitted coordinates (`0`-`12`). Default `2`. */\n precision?: number;\n}\n\nfunction format(value: number, precision: number): string {\n // `+ 0` normalizes -0 to 0 so output is stable across platforms.\n const rounded = Number(value.toFixed(precision)) + 0;\n return String(rounded);\n}\n\n/**\n * Serialize a polyline as an SVG path `d` string: `M x y` followed by one `L x y` per remaining\n * point. Coordinates are rounded to `precision` decimal places.\n *\n * Works for both open strokes and closed rings: pass `close: true` for the outline polygon\n * returned by `strokeOutline`.\n *\n * @example\n * ```ts\n * polylineToSvgPath([{ x: 0, y: 0 }, { x: 10, y: 5 }]);\n * // 'M 0 0 L 10 5'\n * polylineToSvgPath(strokeOutline(points, 4), { close: true });\n * // 'M ... L ... Z'\n * ```\n *\n * @throws {import('./errors.js').InkConfigError} When `points` is empty or `precision` is out of range.\n */\nexport function polylineToSvgPath(points: readonly Point[], options: PolylineToSvgPathOptions = {}): string {\n const input = requireStrokePoints(points, 1);\n const close = options.close ?? false;\n const precision = requireInteger(options.precision ?? 2, 'precision', 0, 12);\n const parts: string[] = [`M ${format(input[0].x, precision)} ${format(input[0].y, precision)}`];\n for (let i = 1; i < input.length; i++) {\n parts.push(`L ${format(input[i].x, precision)} ${format(input[i].y, precision)}`);\n }\n if (close) parts.push('Z');\n return parts.join(' ');\n}\n"],"mappings":";;AAYA,SAAS,OAAO,GAAe,GAA2B;CAExD,IAAMA,IAAU,OAAOC,EAAM,QAAQC,CAAS,CAAC,IAAI;CACnD,OAAO,OAAOF,CAAO;AACvB;AAmBA,SAAgB,kBAAkB,GAA0B,IAAoC,CAAC,GAAW;CAC1G,IAAMG,IAAQC,EAAoBC,GAAQ,CAAC,GACrCC,IAAQC,EAAQ,SAAS,IACzBL,IAAYM,EAAeD,EAAQ,aAAa,GAAG,aAAa,GAAG,EAAE,GACrEE,IAAkB,CAAC,KAAK,OAAON,EAAM,EAAE,CAAC,GAAGD,CAAS,EAAE,GAAG,OAAOC,EAAM,EAAE,CAAC,GAAGD,CAAS,GAAG;CAC9F,KAAK,IAAIQ,IAAI,GAAGA,IAAIP,EAAM,QAAQ,KAChC,EAAM,KAAK,KAAK,OAAOA,EAAMO,EAAE,CAAC,GAAGR,CAAS,EAAE,GAAG,OAAOC,EAAMO,EAAE,CAAC,GAAGR,CAAS,GAAG;CAGlF,OADII,KAAOG,EAAM,KAAK,GAAG,GAClBA,EAAM,KAAK,GAAG;AACvB"}
@@ -0,0 +1,20 @@
1
+ /** @vielzeug/ink: shared public type definitions. */
2
+ /** A two-dimensional point. Structural so canvas-toolkit packages can share it without importing each other. */
3
+ export type Point = Readonly<{
4
+ x: number;
5
+ y: number;
6
+ }>;
7
+ /**
8
+ * A sampled point along a freehand stroke.
9
+ *
10
+ * - `pressure` is normalized to `[0, 1]` when present.
11
+ * - `time` is a millisecond timestamp (`PointerEvent.timeStamp` or `performance.now()`).
12
+ * `strokeWidths` uses it to derive real pen speed, and smoothing interpolates it.
13
+ */
14
+ export type StrokePoint = Readonly<{
15
+ x: number;
16
+ y: number;
17
+ pressure?: number;
18
+ time?: number;
19
+ }>;
20
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,qDAAqD;AAErD,gHAAgH;AAChH,MAAM,MAAM,KAAK,GAAG,QAAQ,CAAC;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAEvD;;;;;;GAMG;AACH,MAAM,MAAM,WAAW,GAAG,QAAQ,CAAC;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC"}
@@ -0,0 +1,2 @@
1
+ const e=require("./_validate.cjs");var t=.25,n=2;function pressureScale(t){let n=e.clamp(t,0,1);return n<=.5?.5+n:1+(n-.5)*.5}function strokeWidths(r,i){let a=e.requireStrokePoints(r,1),o=e.requirePositive(i.width,`width`),s=e.requireRange(i.thinning??.5,`thinning`,0,1),c=e.requirePositive(i.referenceSpeed??.5,`referenceSpeed`),l=a.every(e=>e.time!==void 0),u=[],d=1;for(let r=0;r<a.length;r++){if(l&&s>0){let i=a[r],o=a[r+1],l=r>0?a[r-1]:i,u=r>0?i:o;if(u){let r=Math.abs(u.time-l.time);if(r>0){let i=e.distance(l.x,l.y,u.x,u.y)/r;d=e.clamp((c/i)**s,t,n)}}}let i=a[r].pressure;u.push(o*d*(i===void 0?1:pressureScale(i)))}return u}exports.strokeWidths=strokeWidths;
2
+ //# sourceMappingURL=widths.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widths.cjs","names":["clamp","requireStrokePoints","requirePositive","requireRange","distance","require__validate","MIN_SCALE","MAX_SCALE","p","pressure","input","points","width","options","thinning","referenceSpeed","timed","point","widths","lastScale","i","next","from","to","dt","speed"],"sources":["../src/widths.ts"],"sourcesContent":["/** Velocity- and pressure-modulated stroke widths. */\n\nimport { clamp, distance, requirePositive, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StrokeWidthOptions {\n /** Pen speed treated as \"neutral\", in pixels per millisecond. Default `0.5`. */\n referenceSpeed?: number;\n /** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */\n thinning?: number;\n /** Width at reference speed with neutral pressure. Must be positive. */\n width: number;\n}\n\n/** Fixed velocity-scale range; slow strokes at most double, fast strokes at most quarter. */\nconst MIN_SCALE = 0.25;\nconst MAX_SCALE = 2;\n\n/**\n * Pressure response curve, clamped to `[0, 1]`:\n * `0.5` (the neutral value a mouse reports) maps to exactly `1`, so a stroke with\n * neutral pressure is as wide as one without pressure data. Range: `[0.5, 1.25]`.\n */\nfunction pressureScale(pressure: number): number {\n const p = clamp(pressure, 0, 1);\n return p <= 0.5 ? 0.5 + p : 1 + (p - 0.5) * 0.5;\n}\n\n/**\n * Compute one width per stroke point from pen speed and optional pressure.\n *\n * Speed is `distance / Δtime` between consecutive points, which stays correct after any\n * smoothing, stabilization, or simplification — the pipeline order no longer matters. When any\n * point lacks `time`, or a Δtime is zero, velocity modulation is disabled for the whole stroke\n * (width becomes `width × pressure`) instead of falling back to a spacing proxy that resampling\n * would distort. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n *\n * The first point uses the forward segment; degenerate (zero-length) segments keep the previous\n * scale so stationary samples do not spike.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.\n */\nexport function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[] {\n const input = requireStrokePoints(points, 1);\n const width = requirePositive(options.width, 'width');\n const thinning = requireRange(options.thinning ?? 0.5, 'thinning', 0, 1);\n const referenceSpeed = requirePositive(options.referenceSpeed ?? 0.5, 'referenceSpeed');\n\n // Velocity needs a timestamp on every point; otherwise it is off for the whole stroke.\n const timed = input.every((point) => point.time !== undefined);\n\n const widths: number[] = [];\n let lastScale = 1;\n for (let i = 0; i < input.length; i++) {\n if (timed && thinning > 0) {\n const point = input[i];\n const next = input[i + 1];\n // First point looks forward; the rest look at the segment they arrived on.\n const from = i > 0 ? input[i - 1] : point;\n const to = i > 0 ? point : next;\n if (to) {\n const dt = Math.abs((to.time as number) - (from.time as number));\n if (dt > 0) {\n const speed = distance(from.x, from.y, to.x, to.y) / dt;\n // Slow (speed < reference) widens: scale = (referenceSpeed / speed) ^ thinning.\n lastScale = clamp((referenceSpeed / speed) ** thinning, MIN_SCALE, MAX_SCALE);\n }\n }\n }\n const pressure = input[i].pressure;\n widths.push(width * lastScale * (pressure === undefined ? 1 : pressureScale(pressure)));\n }\n return widths;\n}\n"],"mappings":"A,mCAeA,IAAMM,EAAY,IACZC,EAAY,EAOlB,SAAS,cAAc,EAA0B,CAC/C,IAAMC,EAAIR,EAAAA,MAAMS,EAAU,EAAG,CAAC,EAC9B,OAAOD,GAAK,GAAM,GAAMA,EAAI,GAAKA,EAAI,IAAO,EAC9C,CAgBA,SAAgB,aAAa,EAAgC,EAAuC,CAClG,IAAME,EAAQT,EAAAA,oBAAoBU,EAAQ,CAAC,EACrCC,EAAQV,EAAAA,gBAAgBW,EAAQ,MAAO,OAAO,EAC9CC,EAAWX,EAAAA,aAAaU,EAAQ,UAAY,GAAK,WAAY,EAAG,CAAC,EACjEE,EAAiBb,EAAAA,gBAAgBW,EAAQ,gBAAkB,GAAK,gBAAgB,EAGhFG,EAAQN,EAAM,MAAO,GAAUO,EAAM,OAAS,IAAA,EAAS,EAEvDC,EAAmB,CAAC,EACtBC,EAAY,EAChB,IAAK,IAAIC,EAAI,EAAGA,EAAIV,EAAM,OAAQ,IAAK,CACrC,GAAIM,GAASF,EAAW,EAAG,CACzB,IAAMG,EAAQP,EAAMU,GACdC,EAAOX,EAAMU,EAAI,GAEjBE,EAAOF,EAAI,EAAIV,EAAMU,EAAI,GAAKH,EAC9BM,EAAKH,EAAI,EAAIH,EAAQI,EAC3B,GAAIE,EAAI,CACN,IAAMC,EAAK,KAAK,IAAKD,EAAG,KAAmBD,EAAK,IAAe,EAC/D,GAAIE,EAAK,EAAG,CACV,IAAMC,EAAQrB,EAAAA,SAASkB,EAAK,EAAGA,EAAK,EAAGC,EAAG,EAAGA,EAAG,CAAC,EAAIC,EAErD,EAAYxB,EAAAA,OAAOe,EAAiBU,IAAUX,EAAUR,EAAWC,CAAS,CAC9E,CACF,CACF,CACA,IAAME,EAAWC,EAAMU,EAAE,CAAC,SAC1BF,EAAO,KAAKN,EAAQO,GAAaV,IAAa,IAAA,GAAY,EAAI,cAAcA,CAAQ,EAAE,CACxF,CACA,OAAOS,CACT,C"}
@@ -0,0 +1,26 @@
1
+ /** Velocity- and pressure-modulated stroke widths. */
2
+ import type { StrokePoint } from './types.js';
3
+ export interface StrokeWidthOptions {
4
+ /** Pen speed treated as "neutral", in pixels per millisecond. Default `0.5`. */
5
+ referenceSpeed?: number;
6
+ /** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */
7
+ thinning?: number;
8
+ /** Width at reference speed with neutral pressure. Must be positive. */
9
+ width: number;
10
+ }
11
+ /**
12
+ * Compute one width per stroke point from pen speed and optional pressure.
13
+ *
14
+ * Speed is `distance / Δtime` between consecutive points, which stays correct after any
15
+ * smoothing, stabilization, or simplification — the pipeline order no longer matters. When any
16
+ * point lacks `time`, or a Δtime is zero, velocity modulation is disabled for the whole stroke
17
+ * (width becomes `width × pressure`) instead of falling back to a spacing proxy that resampling
18
+ * would distort. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.
19
+ *
20
+ * The first point uses the forward segment; degenerate (zero-length) segments keep the previous
21
+ * scale so stationary samples do not spike.
22
+ *
23
+ * @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.
24
+ */
25
+ export declare function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];
26
+ //# sourceMappingURL=widths.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widths.d.ts","sourceRoot":"","sources":["../src/widths.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAGtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,WAAW,kBAAkB;IACjC,gFAAgF;IAChF,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,mHAAmH;IACnH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAC;CACf;AAgBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,EAAE,kBAAkB,GAAG,MAAM,EAAE,CA+BlG"}