{"id":"gabrielselvenca/stance","name":"stance","scope":"gabrielselvenca","platform":"roblox","description":"Procedural animation layers for R15 characters, on top of the Animator","version":"0.1.0","latest":"0.1.0","versions":["0.1.0"],"license":"MIT","licenseRating":"safe","licenseCaveats":[],"licenseVerified":true,"dependencies":{},"integrity":"b7e3ffb22c6789421e6b2863e8ea5a0d3db2c18347908ed7eeadc54d1012ddec","likes":0,"downloads":0,"install":"forest install gabrielselvenca/stance","url":"https://forest.dev/p/roblox/gabrielselvenca/stance","files":"https://api.forest.dev/ai/package/roblox/gabrielselvenca/stance/files","readme":"# Stance\n\nProcedural animation layers for R15 characters in Roblox.\n\nThe Animator keeps playing your keyframe animations. Stance runs right after it, every frame, and adds poses, IK and\nsprings on top through `Motor6D.Transform` (or `AnimationConstraint.Transform`). Nothing fights the Animator, and\nthere is no `C0` to restore when a layer turns off.\n\nYou write small modules (\"layers\"). Stance handles the loop, springs, blending, IK, and level of detail for every\ncharacter in the game.\n\n```lua\nlocal Posture = { name = \"Posture\" }\n\nfunction Posture.layer(rig, out, dt, now, api)\n    local speed = rig.hrp.CFrame.LookVector:Dot(rig.velocity)\n    local lean = math.clamp(speed / 20, 0, 1) * math.rad(6) * api.LOD.weight(rig, \"Posture\", \"pose\")\n    out.Waist += Vector3.new(-lean, 0, 0) -- Waist -X bends forward\n    return lean > 0\nend\n\nreturn Posture\n```\n\nThat is a complete layer: every character bends forward a little as it runs, the joint spring smooths it, and it\nfades out with distance. Returning `false` when there's nothing to add lets the rig rest.\n\n## Install\n\nStance is a single ModuleScript with no dependencies. Any of these works:\n\n- **Wally:** add `Stance = \"gabrielselvenca/stance@0.1.0\"` to `[dependencies]` in `wally.toml`.\n- **Model file:** download `Stance.rbxm` from [Releases](https://github.com/GabrielSelvenca/stance/releases) and drop it in\n  `ReplicatedStorage`.\n- **By hand:** create a ModuleScript named `Stance` and paste [`src/init.luau`](src/init.luau) into it.\n\nTag the characters you want animated. From a server Script:\n\n```lua\nlocal CollectionService = game:GetService(\"CollectionService\")\n\ngame.Players.PlayerAdded:Connect(function(player)\n    player.CharacterAdded:Connect(function(character)\n        CollectionService:AddTag(character, \"ProcRig\")\n    end)\nend)\n```\n\nNPCs work the same way: tag the model.\n\nThen start it from one LocalScript:\n\n```lua\nlocal Stance = require(game.ReplicatedStorage.Stance) -- or ReplicatedStorage.Packages.Stance with Wally\n\nStance.add(game.ReplicatedStorage.Layers) -- a Folder of layer ModuleScripts, or a table\nStance.start()\n```\n\nAdd every module before `start()`.\n\n## How a frame works\n\n1. The Animator writes the keyframe pose into each joint's `Transform`.\n2. Stance reads it as the **base** of that joint.\n3. The current **state** pose runs (if a module owns the state), then every **layer**, in `order`.\n4. Both write into `out` (spring targets) and `rig.direct` (no spring).\n5. Joint springs move toward `out`.\n6. The final rotation is `base:Lerp(identity, suppress) * (spring + direct)`.\n\n`suppress` is how much of the keyframe to hide, from 0 to 1. A layer that only adds on top returns nothing for it. A\nlayer that replaces the animation (a custom walk cycle, a climb) returns 1.\n\nA rig that has nothing to do goes to rest: Stance hands the keyframe back once and stops touching it until it moves\nagain.\n\n## Modules\n\nA module is a table. Every key is optional.\n\n| Key | Called | Purpose |\n|---|---|---|\n| `name` | | Used for LOD lookups and warnings |\n| `order` | | Layers run from low to high (default 50) |\n| `lod` | | `{ pose, ik, ray }`, see [LOD](#lod) |\n| `init(rig)` | once per rig | Create the fields your module keeps on the rig |\n| `layer(rig, out, dt, now, api)` | each update | Add to `out` / `rig.direct`. Return `active, suppress` |\n| `states` | | `{ StateName = { duration = s, far = bool } }` |\n| `pose(rig, out, t, state)` | each update, while in one of its states | `t` = seconds in the state. Return `suppress, spin` |\n| `owner(rig, dt, now, api)` | every frame, local player only | Input, physics, choosing states |\n| `onStateChanged(rig, old, new, api)` | any rig, on change | One-shot effects |\n\nStance ignores any other key, so your own systems can read extra fields from the same module (input binds, network\nvalidation).\n\n`spin` from `pose` turns the whole body around `rig.spinAxis` (flips, rolls). It is applied after the springs, so it\nisn't smoothed away.\n\n## Writing poses\n\nJoint keys: `Root`, `RootPos` (studs), `Waist`, `Neck`, `LShoulder`, `LElbow`, `RShoulder`, `RElbow`, `LHip`, `LKnee`,\n`LAnkle`, `RHip`, `RKnee`, `RAnkle`. Values are `Vector3` angles (X, Y, Z) in radians.\n\n```lua\nlocal Pose = Stance.Pose\n\nlocal CROUCH = Pose.define({ -- degrees, converted once\n    RootPos = { 0, -1.2, 0 },\n    LHip = { 60, 0, 0 }, LKnee = { -100, 0, 0 },\n    RHip = { 60, 0, 0 }, RKnee = { -100, 0, 0 },\n})\n\nfunction Module.pose(rig, out, t)\n    local s = Pose.smoothstep(0, 0.2, t) -- ease in over 0.2 s\n    Pose.add(out, CROUCH, s)\n    return s, 0 -- hide the keyframe as the crouch comes in\nend\n```\n\n## IK\n\nTwo-bone IK for arms and legs. Chains: `LArm`, `RArm`, `LLeg`, `RLeg`.\n\n```lua\nlocal rootAngles, midAngles, reached = api.IK.solve(rig, \"RArm\", targetWorldPosition, pole)\n```\n\n`pole` is optional: where the elbow or knee points, in the space of the parent part (`UpperTorso` for arms,\n`LowerTorso` for legs).\n\nThe result is absolute: it is correct when the keyframe is suppressed. To place one limb while the animation keeps\nplaying, convert it:\n\n```lua\nrig.direct.RShoulder += api.IK.relative(rig, \"RShoulder\", rootAngles)\nrig.direct.RElbow += api.IK.relative(rig, \"RElbow\", midAngles)\n```\n\nUse `rig.direct` for IK. The springs lag a few frames, and a planted foot can't.\n\n`IK.relative` works for any absolute rotation, not only IK results. It is how one layer overrides a few joints (aim\nthe arms) while the keyframe keeps playing on the rest: `suppress` hides the keyframe on every joint at once.\n\n## LOD\n\nEvery non-local rig gets a tier, rechecked 5 times per second:\n\n| Tier | When | Update rate |\n|---|---|---|\n| 1 Full | closer than 30 studs and on screen | every frame |\n| 2 Medium | closer than 80 studs and on screen | every 2 frames |\n| 3 Low | closer than 150 studs, or off screen but near | every 5 frames |\n| 4 Off | beyond that | keyframe only |\n\nThe local player is always Full. Only `maxFull` rigs (default 4) can be Full at once; the farthest drop to Medium.\nLower graphics quality shrinks the distances, and zooming the camera in (a smaller `FieldOfView`) counts as closer.\nTier changes blend over a few frames instead of popping. Updates are staggered per rig, so 50 rigs at \"every 5\nframes\" don't all update on the same frame.\n\nUpdates also have a budget, `config.budget` (2 ms by default). Past it, the rigs left wait for the next frame, and the\nnext frame starts from a different rig, so nobody waits twice in a row. The local player never waits.\n\nEach module declares up to which tier each part of it runs:\n\n```lua\nModule.lod = { pose = 3, ik = 2, ray = 1 } -- the default\n```\n\n- `pose`: the pose or layer itself.\n- `ik`: IK and small detail.\n- `ray`: new raycasts. Between `ray` and `ik`, reuse the last hit you stored on the rig. `0` means never.\n\nRead them with `api.LOD.weight(rig, name, \"pose\" | \"ik\")` (a 0 to 1 weight, already blended) and\n`api.LOD.canRaycast(rig, name)`.\n\n## The rig\n\nFields you will read the most:\n\n| Field | |\n|---|---|\n| `model`, `humanoid`, `hrp`, `joints` | The character, and its joints by key |\n| `isLocal` | The local player's character |\n| `velocity`, `accel`, `turnRate` | Measured from the root part, smoothed |\n| `state`, `t0`, `stateParams` | Current state, when it started (`os.clock`), its parameters |\n| `tier`, `weight`, `detail` | LOD tier, base pose weight, IK/detail weight |\n| `params` | `RaycastParams` that exclude the character |\n| `thigh`, `shin` | Leg bone lengths |\n| `seed` | Random per rig, to keep crowds out of sync |\n| `lodTier` | Set it to pin the LOD tier. `nil` = by distance |\n| `disabled` | `disabled.ModuleName = true` turns a module off for this rig |\n\nYour modules can add their own fields in `init`. Prefix them (`rig.climbPhase`) to avoid collisions.\n\n## Customizing\n\nEverything below works without editing the module.\n\n**Tuning.** Any key of `Stance.config` can go in `start()`:\n\n```lua\nStance.start({\n    enter = { 50, 120, 250 }, exit = { 55, 130, 270 }, -- bigger LOD distances\n    period = { 1, 1, 3, 3 },                          -- Medium updates every frame\n    maxFull = 8,\n    springs = { Neck = { stiffness = 300, damping = 30 } }, -- a snappier head, other joints keep the default\n})\n```\n\n**Per character.** Every module's `init` runs when a rig is tracked, in `order`. A small module with a low order is\nthe place to set things up per character:\n\n```lua\nStance.add({\n    name = \"Setup\",\n    order = -math.huge,\n    init = function(rig)\n        if rig.model:HasTag(\"Boss\") then\n            rig.lodTier = 1 -- always Full, at any distance. Pinned rigs don't count toward maxFull\n        end\n        if rig.model:HasTag(\"Horse\") then\n            rig.disabled.FootIK = true -- a module written for humans\n        end\n    end,\n})\n```\n\n`rig.lodTier` and `rig.disabled` can also change at any time later (`Stance.rigOf(model)`).\n\n**Another module's LOD.** `module.lod` is copied when the module is added. To change it without touching the module:\n\n```lua\nStance.add(Layers)\nStance.LOD.ANIMS.FootIK = { pose = 3, ik = 3, ray = 2 } -- foot IK on Low too\n```\n\n**Replacing functions.** Modules call `Pose`, `IK` and `LOD` through those tables, so a replacement applies everywhere:\n\n```lua\n-- LOD distances from the camera instead of the character (spectating, cutscenes)\nStance.LOD.origin = function()\n    return workspace.CurrentCamera.CFrame.Position\nend\n\n-- ignore the player's graphics setting\nStance.LOD.quality = function()\n    return 1\nend\n\n-- your own solver: same arguments, same return values\nStance.IK.solve = function(rig, chain, target, pole)\n    ...\nend\n```\n\n**IK chains.** `Stance.IK.CHAINS` sets the bones, the side the elbow or knee bends to, and the default pole. Edit it\nbefore `start()`:\n\n```lua\nStance.IK.CHAINS.LLeg.pole = Vector3.new(0.3, 0, -1) -- knees point slightly outward\nStance.IK.CHAINS.RLeg.pole = Vector3.new(-0.3, 0, -1)\n```\n\nBone lengths are measured per rig, so scaled characters work without changes. To turn IK off for one limb on one\nrig, set `rig.ik.LLeg = nil` in `init`; `IK.solve` returns `nil` for it.\n\n## Extra joints (beta)\n\nTails, wings, ears, a cape: any `Motor6D` or `AnimationConstraint` past the R15 set can be animated like the others.\n\n```lua\nStance.start({\n    extraJoints = {\n        Tail = { \"Tail\", \"TailJoint\" }, -- part name, joint name inside it\n        Tail2 = { \"TailTip\", \"TailJoint\" },\n    },\n})\n```\n\nThey are optional: a rig without the part is still animated, its `out.Tail` is just `nil`. Check before writing:\n\n```lua\nfunction Wag.layer(rig, out, dt, now)\n    if not out.Tail then\n        return false\n    end\n    out.Tail += Vector3.new(0, math.sin(now * 6) * 0.4, 0)\n    return true\nend\n```\n\n`Pose.add` skips keys the rig doesn't have, so a pose table can include them. The part is searched in the whole\ncharacter, so it can live inside an `Accessory`.\n\nBeta, because:\n\n- Joints are found once, when the rig is tracked. A tail added later needs the tag removed and added again.\n- `IK` chains only use the R15 joints.\n- The API may still change.\n\n## API\n\n```lua\nStance.add(moduleOrFolder)\nStance.start(options?)        -- client only; options: any Stance.config key, plus `api`\nStance.setState(rig, state, params?)\nStance.wake(rig)              -- a resting rig updates again (an event turned a layer on)\nStance.localRig()\nStance.rigOf(model)\nStance.rigs                   -- every tracked rig\nStance.modules                -- every module, sorted by order\nStance.states                 -- state -> { module, duration, far }\nStance.cost()                 -- seconds per frame spent in Stance, smoothed\nStance.config                 -- tunables, see the top of src/init.luau\nStance.Pose, Stance.IK, Stance.LOD -- see Customizing\nStance.LOD.origin()           -- where distances are measured from\nStance.LOD.quality()          -- 0.4 to 1, scales distances and maxFull\n```\n\n`api`, the last argument of `layer`, `owner` and `onStateChanged`, is `Stance.api`: `setState`, `wake`, `localRig`,\n`Pose`, `IK`, `LOD`. Pass `{ api = { ... } }` to `start` to add your own fields or replace one. A common case is a\n`setState` that also tells the server:\n\n```lua\nStance.start({\n    api = {\n        setState = function(rig, state, params)\n            Stance.setState(rig, state, params)\n            StateRemote:FireServer(state, params)\n        end,\n    },\n})\n```\n\n## Networking\n\nStance doesn't replicate anything. Layers driven by physics (lean, foot IK, gait) need nothing, because every client\nalready sees every character move. For states and aim targets, send a small message and call `Stance.setState` on\nthe other clients. Never send poses.\n\n## Performance\n\nMeasured in Studio with 50 R15 characters walking around the camera and the 19 modules of the demo game loaded: 0.9 ms per frame on the\nclient. With just the local player: 0.06 ms.\n\n`debug.profilebegin(\"Stance\")` wraps the loop, so it shows up in the MicroProfiler.\n\n## Limits\n\n- R15 only (extra joints on top of it are in [beta](#extra-joints-beta)).\n- Two-bone IK only (no spine chains).\n- One state at a time per rig.\n- Layers run on the client. The server never sees the procedural pose.\n\nPlanned, not in this version:\n\n- Chain IK (spines, tails) and an aim helper with angle limits.\n- A weight per layer that the game can fade from outside (today it's `rig.disabled`, on or off).\n- R6 and custom rigs.\n- Parallel Luau for the heavy math.\n\n## License\n\nMIT, see `LICENSE`.\n","readmeTruncated":false}