Skip to content

ByteTerrace/Puck / .claude/skills/maths-usage

maths-usage

Unverified

Picks Puck.Maths primitives and determinism rules: FixedQ4816, FixedVector3, rate accumulators, Pcg32XshRr, AliasTable, Fnv1aHash, rounding, saturation, primes. Law cases: maths-laws.

Puck.Maths: choose, obey, verify

During the refactoring campaign, AGENTS.md suspends this skill's blanket test, coverage and gate requirements. An explicit brief's verification still applies; exact rejection and continuation laws are useful where a running world cannot reliably reach the inputs.

Puck.Maths is the deterministic numerics library for values a simulation advances, compares, hashes, snapshots or replays: the same inputs give the same bits on every machine, backend and run. Presentation-only floats, shaders, renderer or UI math and explicit presentation conversions are outside this contract. Each wing has a README that owns its contracts; when one disagrees with this file, the wing wins.

Choose

Search the library and the relevant wing README before hand-rolling numeric behavior (content-search finds candidates). A second implementation of a lerp, clamp, GCD, floor division, bit mixer or rate carrier can diverge in rounding, overflow or floor and ceiling convention.

The value isUseNot
A signed quantity with an integer part: position, velocity, accumulated advanceFixedQ4816 (Q48.16 on a long)float/double; a bare long scaled by hand
The same, never negativeUFixedQ4816FixedQ4816 plus an assertion
A fraction in [0, 1)UnitFraction16 or UnitFraction32A Q48.16 promised to stay under one
A weight or probability that must reach 1UnitInterval32 (closed [0, 1])UnitFraction32, which has no One
A 2D or 3D displacementFixedVector2 / FixedVector3Three scalars
A rotationFixedComplex (2D), FixedQuaternion (3D), FixedRigidTransform (rotation plus translation)Hand-built matrices
A world position beyond a small sceneFixedPosition (cell indices plus a local offset)A bare FixedVector3, which is a displacement
A rate integrated over ticksFixedRateAccumulator / FixedVector3RateAccumulatorA per-second velocity pre-rounded into one per-tick delta
A target that eases or overshootsSecondOrderDynamicsSecondOrderFollower3 and SecondOrderFollower4, the presentation-only float twins
Lerp or clampFixedQ4816.Lerp / .Clamp, FixedVector3.Lerp, FixedQuaternion.SlerpA hand-rolled a + (b - a) * t
Sequential random drawsPcg32XshRrSystem.Random, Random.Shared
A bounded index over a fallible or budgeted raw-word sourceBoundedRandomSampling.TrySampleRange (or TrySampleWide past 32 bits) over an IRawWordSource, with a caller-set attempt budget; it counts every raw word and refuses on exhaustion. TryMap is the per-word stepA multiply-high map without rejection; a second Lemire implementation
A weighted pickWeightedSampler.Create once at load, then AliasTable<T>.SampleA per-call cumulative scan over floats
A shufflePcg32XshRr.ShuffleOrderBy(_ => random)
Spatial noise, per-cell randomness or a scattered pointPcg3dLatticeNoise (ValueNoise01, ScatterPoint)A per-call RNG; a second copy of the block formula
Fractal (fBm) value noise over a 2D cell index: a noise fill, a patchy placement regionPcg3dLatticeNoise.Fbm01(cellX, cellZ, frequency, octaves, seed): halved edge and amplitude per octave, a HashStreamA seed step, the world seed folded into seed with PackedIntPair.FoldXorA per-caller octave loop over ValueNoise01, which can drift from the other callers'
A one-shot weighted pickWeightedSampler.SampleOnceA cumulative scan; a table built to be thrown away
A 64-bit mix with an inverseInvertibleBitMix.Mix64 (SplitMix64's finalizer)A hand-rolled multiply-xorshift
Two 32-bit words packed into one long or ulong (a pair key, a LUID, a handle's generation over its index, a 64-bit value split into GPU words)PackedIntPair.Pack(high, low), High, Low: ints into a long, uints into a ulong, the low word zero-extended(((long)a) << 32) | ((uint)b) and (int)(x >> 32) written by hand: the signed high half and the zero-extended low half are each a place to differ
A 64-bit seed or hash narrowed to 32 bits (a GetHashCode, a digest, a seed folded with a world seed)PackedIntPair.FoldXor(ulong): low word xor high word, as a uint(uint)x ^ (uint)(x >> 32) written by hand, or (uint)x alone, which drops the high word
A Windows adapter LUID packed into the 64-bit identity IGpuDeviceContext.AdapterLuid reportsGpuAdapterLuid.Pack(highPart, lowPart) in Puck.Abstractions (each CsWin32 binding generates its own LUID, so it takes the two parts)PackedIntPair.Pack re-spelled with the LowPart cast at each DXGI or Direct3D reader
Hashing two 32-bit words packed into a long dictionary or set keyPackedIntPairComparer.Instance beside InvertibleBitMix: full-word equality and a Fibonacci multiply's upper wordLong's default hash folds the halves; a private comparer per caller
Dividing many uint values by one nonzero uint divisorReciprocalDivisor32: ceil(2^64/d), high multiply, exact across both uint ranges; default divides by oneA private reciprocal copy; applying the uncorrected formula to a 64-bit dividend
An angle in degrees entering the simFixedQ4816.FromDegrees (one rounding against PiQ189)FromDouble(degrees * (Math.PI / 180)), a rounded radians-per-degree factor
π, π/2, 2π, or an angle reduced to one turnFixedQ4816.Pi/HalfPi/Tau, FixedQ4816.WrapAngleFromDouble(Math.PI), Pi + Pi (one raw short of Tau), a floor-and-correct wrap
A vector shortened to a length, or rejected from an axisFixedVector3.ClampLength/WithLength (toward zero, never above), RejectFrom/TryRejectNormalized; a one-sided limit (a contact removing approach velocity) is LimitAlong(v / v.Length) * limit, which can land above the limit
A product over a divisor (x·y/z), a projection's segment parameter (clamp(dot(p, s)/dot(s, s), 0, 1)), or the nearer of two offsetsFusedArithmetic.MultiplyDivide; FixedVector2.SegmentParameter / FixedVector3.SegmentParameter (or FusedArithmetic.ClampedUnitQuotient over sums already formed); FixedVector3.CompareLengthTo. Each rounds once or not at all(x * y) / z, Dot(p, s) / Dot(s, s), a.LengthSquared < b.LengthSquared: each rounds a product of lengths to 2⁻¹⁶, which at centimetre sizes keeps a few bits and puts a millimetre of noise in a field
A sphere or cone testFixedVector3.IsWithin (exact |d|² ≤ r²), IsWithinCone (apex inside, normalized forward)LengthSquared > r * r (rounded twice), a cone that rejects its apex
Spread points, or stratification that must be a theoremLowDiscrepancy (R1, R2), DigitalNetSamplerPlain random scatter
A per-tick state hash for a replay probeFnv1aHashstring.GetHashCode or HashCode.Combine (randomly seeded per process)
Hex cells, tile or chunk order, ringsHexagonalCoordinate, HilbertCurve, LayerSequenceHand-rolled axial math
Floor or ceiling division, low masks, alignment, PDEP/PEXT, Morton codesBinaryIntegerFunctions (FloorDivide, CeilingDivide, LowMask, AlignUp, ParallelBitDeposit, BitwisePair)/ on a negative dividend, (1 << n) - 1, a Bmi2 call
Exact GF(2^k), mod p, a primality decisionBinaryField<T>, PrimeField64, PrimeExtensions.IsPrimeFloats; a rounded product
The Nth prime or a prime count within uintPrimeExtensions.NthPrime(uint) / PrimeCountingFunction(uint)A second sieve or counting implementation
A graph, lattice, language or finite structureThe Oracle/ presented algebraA bespoke solver

FixedQ3232, FixedInterval, FixedMassProperties, FixedSymmetricSolve, CurvatureSpline, the transforms (NTT, Walsh-Hadamard, fixed FFT and DCT) and the Research/ wing are in the wing READMEs' "At a glance" tables. references/complete-reference.md maps each question to its wing and README section.

Contracts that bite

  • Rate accumulators carry authoritative state. The sub-unit remainder and TicksPerSecond ride snapshots and state hashes, restored together with FromRemainder / FromRemainders. Call Reset when the integrated quantity is assigned, clamped or teleported outside the accumulator. Both are mutable structs: keep one in a field, an array slot or a ref local. A readonly field, a get-only property or a List<T> element hands Integrate a copy, and every advance is silently lost.
  • RNG state is simulation state. One Pcg32XshRr stream per system, derived from the master seed with a small consecutive id (Create(state: masterSeed, stream: id)); persist State, Increment and Multiplier and restore through FromRawBits. Never share a generator across systems, never reseed to "resume", and keep draw order stable.
  • Alias tables are order-sensitive. Build once at load from deterministically ordered entries; entry order is part of the table's identity. A sample consumes exactly two generator advances.
  • Seeking counts advances, not calls. Advance-based seeking is exact only against fixed-cost draws (NextUInt32(), the fraction draws, the Gaussian pair, an alias sample). A bounded NextUInt32(min, max) and Shuffle can reject and consume extra advances.
  • Wrap is the default. Bare operators are unchecked, checked forms throw after rounding, and AddSaturating / SubtractSaturating (unsigned and unit types) or FixedSaturate (FixedQ4816 and vectors) clamp. Some saturators have no Try... sibling. State the rounding and overflow policy at each narrowing boundary.
  • Ties go to even everywhere except Exp2, Log2 and Atan2, which narrow half up. Do not add a fourth exception or "correct" one of the three.
  • Do not reassociate a rounded product. (a * b) * c and a * (b * c) differ over FixedQ4816; the fused kernels round a whole expression once. Finite-field products are exact and may be reassociated.
  • Projection bounds use the point kernel too. FixedInterval.SegmentParameter encloses a fixed segment's parameter over a 2D or 3D box through its two extreme corners. Dividing carrier-rounded dot-product intervals can turn a tiny squared length into a divisor containing zero, or overflow a large one, and leave an otherwise valid SDF program with no query frame.
  • Float presentation helpers live in VectorFunctions. The angle wraps, easings, shortest arc, −Z-forward attitude readbacks and unorm packers every presentation seam shares are in Puck.Maths.VectorFunctions, outside the determinism contract and in every project's closure; a second float copy in a client or shader-side file is a defect.
  • Floats stay out of state. Authoring in (FromDouble, a document weight) and presentation out (ToVector3, ToQuaternion, FixedPosition.ToRenderRelative) are the two boundaries; presentation seams are one-way, and nothing they return flows back into state.
  • Outbound precision needs an exact oracle. The FixedQ4816 float cast rounds its raw directly to single precision before exact binary scaling; routing it through double can manufacture a tie. The decimal-backed Half conversion is correctly rounded at the current Q16/Q32 scales, pinned at every Half midpoint by scalar.half-midpoints-vs-exact-oracle; do not assume that proof covers a future finer carrier. Generic FixedQ3232/UFixedQ4816 peers round to the target grid before applying checked, saturating or width-truncating policy.
  • Generic peers support both hooks. Verify TryConvertFrom* and TryConvertTo* directly through the derived-interface adapter in the Maths suite. Create* falls back to the other operand's hook and can conceal a missing half of the conversion contract.
  • Gate PDEP/PEXT on BitManipulation.HasFastParallelBits, never Bmi2.IsSupported: AMD before Zen 3 (the Steam Deck's Zen 2 included) and Hygon's licensed Zen 1 run them in microcode at up to hundreds of cycles.
  • Do not infer a contract from a name. Read the member's XML documentation, its wing README section and the tests that pin it.
  • A deliberate correction moves values. A rounding or logic fix is expected to change state hashes: make it, and re-record the persisted replay or baseline it invalidates (AGENTS.md rule 4). Never keep a path that reproduces the old wrong result.

Prime kernels

Work on PrimeExtensions.IsPrime, NthPrime(uint), PrimeKernels and ScaledResidueRing64 follows references/prime-kernels.md. Preserve the fast single-value decision and its SIMD fallbacks. Wide prime counting, selection and interval exploration are out of scope (the owner's ruling, prime exploration); Research/, Algebra/ and Oracle/ are unaffected.

Verify

Build the test project (dotnet build tests/Puck.Maths.Tests/Puck.Maths.Tests.csproj -c Release -nodeReuse:false). Running the suite is optional while the campaign lifts test requirements; where a change needs the evidence, it takes about half a minute:

dotnet test tests/Puck.Maths.Tests/Puck.Maths.Tests.csproj -c Release --no-build

Pass -nodeReuse:false to the build step only (verification). The run is the Default tier. A rounding change or a new value kernel can also use Deep (--explicit on --filter-trait tier=Deep). Exhaustive takes tens of minutes: run it only when the member's waiver or the coverage law declaration names it as the gate of record, and narrow it to one law with --explicit on --filter-display-name '<law-id>*'. No tier measures time; puck bench does. Report the exact commands you ran and where any failure came from.

A new public Maths member carries its classification (a law case or a precise waiver) in the same change; the 100% line-coverage target is suspended for the campaign. Authoring the case and waiver belongs to maths-laws. The owner rules out recorded Maths registers and coverage ratchets; completeness is checked from the current declarations.

Route adjacent work

SkillUse when
maths-lawsAuthoring or changing a Maths law, subject, oracle, leg, waiver or public-member classification.
dotnet-performanceSIMD, allocation and throughput questions on code that is not a simulation value path.
renderingShaders, renderer or UI math and presentation-only floats, which sit outside the determinism contract.
content-searchFinding textual occurrences, candidate hand-rollings, tokens or patterns across the tree.
symbol-analysisSemantic C# questions about references, implementers, dead code, renames or deletion safety.
gaming-bricksVerifying a Maths change that reaches emulator code and its dedicated batteries.
physicsContact, sweep, rigid, gravity and navigation kernels that consume these primitives.
stateThe rule engine's expression arithmetic, draw sites and arena hashing.
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 192kUpdated Claude CodeCodexVerifiedInstall