{"id":"nightcycle/imposter-render","name":"imposter-render","scope":"nightcycle","platform":"roblox","description":"Typed shared EditableMesh / PBR atlas runtime for imposter-baker","version":"0.1.1","latest":"0.1.1","versions":["0.1.0","0.1.1"],"license":"Apache-2.0","licenseRating":"safe","licenseCaveats":["Modified files must carry a notice of changes. If the package ships a NOTICE file, its attributions must be preserved."],"licenseVerified":true,"dependencies":{},"integrity":"13fabae2b22d85cad4f3fa49e84245f5a9569f10d8deb729ce892a0d62f3da81","likes":0,"downloads":0,"install":"forest install nightcycle/imposter-render","url":"https://forest.dev/p/roblox/nightcycle/imposter-render","files":"https://api.forest.dev/ai/package/roblox/nightcycle/imposter-render/files","readme":"# imposter-render\n\nStrictly typed Luau runtime for `imposter-baker` layout version 1. One batch owns a single EditableMesh, a single MeshPart, and one shared EditableImage per enabled material layer. Every imposter has its own quad in that mesh, so independent instances can select different shots and still share geometry and textures.\n\nAll Luau methods and record fields use PascalCase, including constructors (`ImposterRender.New`), options (`Limits.MaxInstances`), sources (`Color`, `Normal`), and generated layout fields (`PanShotCount`). This is a breaking change from the earlier camelCase API: update callers and regenerate old `.imposter.luau` files. Lowercase layer IDs in `Layers` and `Images[\"color\"]`, shot keys, PNG paths, and the JSON manifest format are unchanged.\n\n## Install\n\nThis directory is a standalone Wally project:\n\n```sh\nwally package --project-path imposter-render --output imposter-render.zip\nrojo build imposter-render/default.project.json --output imposter-render.rbxm\n```\n\nTo publish the registry package, authenticate with Wally and run `wally publish` inside this directory. GitHub Actions also supports manual or automatic stable-version registry publication using `WALLY_AUTH_TOKEN`; see the [release guide](../.github/RELEASING.md). Once published, consumers add:\n\n```toml\n[dependencies]\nImposterRender = \"nightcycle/imposter-render@0.1.0\"\n```\n\nEnable editable assets in the experience's security settings. Asset ownership/access requirements still apply. Roblox can deny allocations before a configured limit is reached; creation and registration return errors with cleanup. Editable assets are local to each client. Create/update the renderer from a LocalScript.\n\n## Spritesheet example\n\nUpload the baker's PNGs without resizing them. Keep the generated `.imposter.luau` layout alongside your asset IDs; the default layout can be omitted. Use bounds from the same model and coordinate basis used during baking.\n\n```lua\n--!strict\nlocal RunService = game:GetService(\"RunService\")\nlocal ImposterRender = require(game.ReplicatedStorage.Packages.ImposterRender)\n\nlocal options: ImposterRender.Options = {\n    Origin = CFrame.new(100, 0, 100),\n    Limits = {\n        MaxTextureSize = 1024,\n        MaxInstances = 256,\n        MaxEditableMeshes = 1,\n        MaxEditableImages = 6,\n        MaxTexturePixels = 6 * 1024 * 1024,\n        WorldExtent = 512,\n    },\n}\nlocal batch, createError = ImposterRender.New(options)\nassert(batch, createError)\n\nlocal ok, loadError = batch:Register(\"birch-v1\", {\n    Color = \"rbxassetid://COLOR_ATLAS_ID\",\n    Normal = \"rbxassetid://NORMAL_ATLAS_ID\",\n    Roughness = \"rbxassetid://ROUGHNESS_ATLAS_ID\",\n    Metalness = \"rbxassetid://METALNESS_ATLAS_ID\",\n})\nassert(ok, loadError)\n\nlocal model = workspace:WaitForChild(\"Birch\") :: Model\nlocal boxCFrame, boxSize = model:GetBoundingBox()\nlocal first, addError = batch:Add(\"birch-v1\", boxCFrame, boxSize)\nassert(first, addError)\nlocal second, secondError = batch:Add(\"birch-v1\", boxCFrame + Vector3.new(10, 0, 0), boxSize)\nassert(second, secondError)\n\nlocal connection = RunService.RenderStepped:Connect(function()\n    local camera = workspace.CurrentCamera\n    if camera then\n        batch:Update(camera.CFrame, camera.FieldOfView)\n    end\nend)\n\n-- When disposing:\n-- connection:Disconnect()\n-- first:Destroy()\n-- second:Destroy()\n-- batch:Unregister(\"birch-v1\")\n-- batch:Destroy()\n```\n\nUse the camera's **vertical** field of view in degrees. If you use a nonvertical `Camera.FieldOfViewMode`, supply the equivalent vertical FOV. Your application controls LOD switching and hiding/replacing the original model. `Update()` does not modify originals, connect frame events, or allocate editable assets.\n\nSingle BaseParts should use their `CFrame` and `Size`. Models use `GetBoundingBox()`; if changing PrimaryPart or geometry since baking, supply the original bake basis and corresponding size. Uniformly scaled copies work. A billboard cannot reproduce arbitrary nonuniform mesh deformation.\n\n## Sources and layout\n\nEach layer accepts a URL string, a `Content` (including `Content.fromObject(editableImage)`), or a dictionary of individual shot contents:\n\n```lua\nlocal colors: { [string]: ImposterRender.ImageContent } = {}\nfor index = 0, 7 do\n    colors[ImposterRender.Util.ShotKey(index)] = uploadedShotUrls[index + 1]\nend\nlocal ok, err = batch:Register(\"grass-v1\", { Color = colors }, {\n    PanShotCount = 8,\n    TiltShotCount = 1,\n    MaxResolutionPx = 252,\n    PaddingPx = 2,\n    TiltConstraints = NumberRange.new(-180, 180),\n    TiltOffset = 0,\n})\n```\n\nEvery individual image includes the baker's padding. Directory exports group layers by shot, such as `shot_0000/color.png` and `shot_0000/normal.png`; upload these files and keep using `shot_0000` as the runtime map key. A sheet must match `Util.AtlasSize(layout)` exactly. Each provided map dictionary must contain every `shot_####` key; missing maps use neutral defaults. Source images are streamed one at a time into the shared atlas, then destroyed. Registration yields while loading. A model becomes available to `Add()` only after all its maps succeed. Failed registration returns its atlas allocation. Concurrent registrations are rejected with a retryable message.\n\nBy default, the batch enables `color`, `normal`, `roughness`, `metalness`, and `emissive`. For lower memory use, declare `local layers: { ImposterRender.Layer } = { \"color\" }` and pass it as `Options.Layers`. Disabled layers are not loaded. `Emissive` consumes the grayscale emissive mask; the optional constructor `EmissiveStrength` and `EmissiveTint` apply to the entire batch. The manifest records source emission settings. Use separate batches for incompatible emission settings.\n\nThe `id` is a model-version cache key. Register it once, then call `Add` for each copy. Registering an existing ID fails rather than silently changing active resources. Destroy its handles and `Unregister` before replacing it. `Handle:Update(cf, size)` moves/resizes one instance. `Handle:Destroy()` and `Renderer:Destroy()` are idempotent.\n\n## Nearby real models and instance caching\n\nRegister a static `Model` or `BasePart` template under the same cache key as its baked images. Existing and future handles then switch automatically: nearby handles use cached real geometry, and distant ones use their shared imposter quad. Keep templates in `ReplicatedStorage`; the renderer leaves the source instances untouched.\n\n```lua\n-- After batch:Register(\"birch-v1\", sources, layout):\nlocal template = game.ReplicatedStorage.Birch\nlocal ok, message = batch:RegisterTemplate(\"birch-v1\", template, { CanCollide = true, CanQuery = true })\nassert(ok, message)\nlocal count, warmError = batch:Prewarm(\"birch-v1\", 16)\nassert(count >= 16, warmError)\n\nbatch:SetLodOptions({\n    NearDistance = 48,\n    FarDistance = 64,\n    MaxRealInstances = 64,\n    MaxTransitionsPerFrame = 4,\n    MaxCreatesPerFrame = 1,\n    ReplacementMargin = 4,\n    LookAheadSeconds = 0.75,\n    MaxLookAheadDistance = 192,\n    CameraLookAheadDistance = 24,\n    PriorityBudgetFraction = 0.65,\n})\n-- Supply character movement separately from the rendering camera:\nbatch:Update(camera.CFrame, camera.FieldOfView, availableMs, {\n    Position = characterRoot.Position,\n    Velocity = characterRoot.AssemblyLinearVelocity,\n})\nhandle:SetLodEnabled(false) -- Keep a particular instance as an imposter.\nlocal real: Model? = handle:GetRealInstance() -- Borrowed cached wrapper; nil when using an imposter.\n```\n\n`Options.Lod` accepts the same fields; the values above are defaults. `Update` takes an optional fourth argument of type `Motion`, with `Position` and `Velocity` in world space. Use the character's position and velocity when its movement differs from the camera. For immediate response to turns, applications can supply movement intent multiplied by speed. Without these inputs, the renderer estimates camera velocity between updates; while stationary, it looks `CameraLookAheadDistance` studs along the camera's look direction. Large inferred teleports and long pauses reset velocity estimation.\n\nReal-model selection looks `LookAheadSeconds` into the travel direction, capped by `MaxLookAheadDistance`. At **160 studs/second**, the default predicts **120 studs ahead**. Candidates are ranked by distance to the travel segment plus 20% of their distance along it. This favors upcoming geometry while retaining very close objects around the current position. `NearDistance` and `FarDistance` apply to that priority distance; setting both lookahead options to zero restores ordinary distance selection. Rendering and shot selection always use the actual camera.\n\nA separate spatial queue finds candidates along this corridor without waiting for a full pass over distant imposters. It gets up to `PriorityBudgetFraction` of the shared update budget after reserving time for the bulk move. The fraction must be between 0 and 0.9, leaving time for visual updates. Significant movement or a turn discards stale priority work; the background visual pass continues without restarting. Queue construction, promotions, and mesh work all respect the same deadline and clone/transition limits. Prewarm collidable templates before movement; zero available headroom still defers all work.\n\nWhen the real-instance cap is full, a candidate must improve the priority distance by more than `ReplacementMargin` to replace the farthest active instance. Active real models stay real until they cross `FarDistance`. This distance band and replacement margin prevent rapid oscillation. Set `MaxRealInstances = 0` to return all models to imposters over the configured frame budgets. `SetLodOptions` replaces the configuration, defaulting omitted fields.\n\nUse `Options.InstanceCache` to bound pooled geometry separately from editable assets:\n\n| Option | Default | Meaning |\n| --- | --- | --- |\n| `MaxInstances` | 128 | total active and idle cached clones; must cover `MaxRealInstances` |\n| `MaxPartsPerInstance` | 128 | maximum BaseParts in any template |\n| `MaxPartsPerFlush` | 256 | maximum parts submitted to one bulk move; must cover one template |\n| `WorldRoot` | `workspace` | Workspace or WorldModel receiving the bulk move |\n| `Parent` | `WorldRoot` | parent for the cache's active-instance Folder; must be inside that world |\n| `CanCollide` / `CanQuery` | false | opt-in flags for the anchored visual parts |\n\n`TemplateOptions.CanCollide` and `TemplateOptions.CanQuery` override the cache defaults for an individual model key. For example, enable these for trees and pillars while leaving grass and lilypads non-collidable.\n\nPrewarming ensures the requested number of clones for a template, including active clones. It runs synchronously, so call it during loading. Idle clones remain unparented and are reused by model key; if the cache is full, an idle clone of another key can be reclaimed. Active clones are never reclaimed by the cache. Runtime growth is capped by `MaxCreatesPerFrame`; set it to zero after prewarming to prevent cloning during updates. Cache exhaustion keeps the imposter visible. Each template also has one private, sanitized snapshot, separate from the clone count.\n\nAll changed parts, across all promoted or moved models, are submitted through one [`WorldRoot:BulkMoveTo`](https://create.roblox.com/docs/reference/engine/classes/WorldRoot#BulkMoveTo) call per renderer update using `FireCFrameChanged`. Models are placed before their quads are hidden. On demotion, the quad is restored before the clone is unparented. Returning an instance to its pool does not move it to a distant parking coordinate. No texture or mesh reallocation occurs during a swap. The original imposter slot stays reserved for immediate reuse.\n\nThe scheduler shares the existing update deadline with selection and swaps, reserving time for the bulk move. Clone creation, transitions, and moved parts also have separate caps. A replacement counts as two transitions. These engine calls are atomic, so one complex clone or bulk move can overrun a soft deadline; prewarm and lower the part/transition caps for tighter frame times. `GetUsage()` includes `RealInstances`, `CachedInstances`, `BulkMovedParts`, and `LodTransitions`; `UpdateMilliseconds` includes the bulk move and visibility handoff.\n\nTemplate bounds default to `Model:GetBoundingBox()` or `BasePart.CFrame/Size`. For a custom bake basis, pass `{ BoundingBoxCFrame = originalBoundsCf, BoundingBoxSize = originalBoundsSize }` as the third argument to `RegisterTemplate`. Multipart offsets, rotations, attachments, and uniform scale are preserved. `Handle:Update` moves an active real model through the same bulk queue. Nonuniformly scaled handles stay as imposters. Clones are static, anchored visuals with scripts removed and touch disabled; animated rigs and server-authoritative gameplay need a separate system. Inspect borrowed models without modifying or destroying them, since they can be reassigned to other handles.\n\n`UnregisterTemplate(id)` frees its idle pool and snapshot; it refuses while any real instance uses that template. Disable LOD on those handles (or set the real limit to zero) and update until they have demoted first. Destroying a handle returns its clone; unregistering an unused model also removes its template. Destroying the renderer disposes of active clones, idle clones, snapshots, and the cache Folder.\n\nFor custom integrations, `ImposterRender.InstanceCache` exports a typed standalone cache with `New`, `Register`, `Prewarm`, `Acquire`, `Queue`, `Flush`, `Release`, `Unregister`, and `Destroy`. Queueing the same lease repeatedly keeps its latest transform; releasing it cancels pending placement. `Lod.Resolve`, `Lod.GetFocus`, `Lod.PriorityDistance`, `Lod.Distance`, and `Lod.ShouldReplace` expose the selection policy. `Lod.NewQueue`, `Set`, `Remove`, `Clear`, and `RunQueue` expose the bounded spatial queue.\n\n## Frame scheduling\n\nUpdates default to a 240 FPS target with one quarter of the frame interval (about 1.04 ms) available to the renderer. Configure `Options.UpdateBudget`, or change it with `batch:SetUpdateBudget({ TargetFps = 240, MaxMilliseconds = 1 })`. `batch:Update(cameraCFrame, verticalFov, availableMilliseconds, motion)` optionally accepts the remaining CPU headroom for this frame; zero defers all work. The effective budget is the smaller of that headroom and the configured maximum.\n\nThe real-model priority queue runs first within its budget share. The background visual queue then uses the remaining time. Each visual pass snapshots the camera position, builds its queue incrementally, then processes the closest model centers first. Unfinished work resumes next frame. The pass finishes before distances are refreshed, preventing distant instances from starving during continuous camera motion. Each visited instance uses the current camera and latest model bounds to choose its shot, including continuously moving handles. Removed and reused handles invalidate stale queue entries. New instances may remain hidden until their first scheduled update.\n\n`GetUsage()` exposes `PendingInstances` (remaining background queue estimate), `CheckedInstances`, `UpdatedInstances`, and `UpdateMilliseconds` for profiling. The last three describe the most recent update call, including work from both queues. Unchanged shots skip mesh writes. This is a cooperative CPU budget: one in-progress item can finish slightly past the deadline. It cannot guarantee total game FPS or account for GPU time; reserve time for the rest of your game's frame, and share the available budget when updating multiple batches. The demo caps this work at 1 ms and reserves another 1 ms after accounting for earlier render callbacks.\n\n## Allocation limits\n\n`Options.Limits` configures local soft budgets. `GetUsage()` reports actual batch counts and texture pixels; `SetLimits()` can change logical limits within allocated capacity. `ImposterRender.Limits.Resolve()` validates and freezes a budget without allocating anything. Budgets are per","readmeTruncated":true,"readmeFull":"https://api.forest.dev/v1/package/nightcycle/roblox/imposter-render/0.1.1/readme"}