# Engine reference: Unity

The package `com.360sona.renderer`, namespace `Sona.Unity`. Components are added from the 360sona menu; their fields are in the Inspector.

## SonaContext

A component. One 360sona context per scene.

| Field | Type | Default | What it does |
|---|---|---|---|
| `licence` | `TextAsset` | `null` | sona-licence.json from your download. |
| `appId` | `string` | `""` | Empty: the app id stamped into the library. |
| `dumpFolder` | `string` | `""` | An asset folder the user owns. Relative paths are under Application.persistentDataPath. Empty: none. |
| `consoleFolder` | `string` | `""` | An Xbox 360 Content root, or a PC copy of one. Empty: none. |
| `useGate` | `bool` | `true` | Read from 360sona over the network after the local sources. |
| `gateUrl` | `string` | `""` | Empty: https://360sona.com/g. |
| `workerThreads` | `int` | `-1` | -1: cores - 1 (default); 0: none, work runs inside sona_update. |
| `seed` | `uint` | `0` | 0: from the clock. |
| `faceSize` | `uint` | `0` | 0: auto (512, 256 or 128 by avatar count). |
| `maxAvatars` | `uint` | `256` | Default 256, at most 16384. |
| `buildBudgetMs` | `float` | `6` | Owner-thread loading work per sona_update (steps, commits; builds run on the workers); default 6. Avatars shown per update are also paced by the draw work they add. |
| `stillFaces` | `bool` | `false` | One face per avatar instead of faces that follow each clip's expressions. |
| `crowdLod` | `bool` | `false` | Pose far avatars less often (the core's crowd LOD steps). Sprites stay off: Unity draws the meshes itself. |
| `catalogue` | `TextAsset` | `null` | sona-catalogue.bin, renamed to .bytes so Unity imports it. Empty: no catalogue. |
| `viewCamera` | `Camera` | `null` | Empty: Camera.main. |
| `avatarShader` | `Shader` | `null` | Sona/Avatar. Reference it here so builds include it. |
| `logInfo` | `bool` | `false` | Write the core's information messages to the Unity log, not only its warnings and errors. |

| Member | What it does |
|---|---|
| `static SonaContext Current` | The SonaContext in the loaded scenes, or null. |
| `Core.SonaContext Native` | The C# binding's context, for a call the component does not wrap; null until it opens. |
| `Core.SonaCatalogue Catalogue` | The offline catalogue from the catalogue field; null when there is none. |
| `Core.SonaMaker Maker` | Random looks and outfit rules over the catalogue (SonaAvatar.randomSeed); null without a catalogue. |
| `void SetCatalogue(Core.SonaCatalogue cat)` | Uses a catalogue loaded elsewhere (a file the game downloads, or a test). |
| `float FirstReadyTime` | Time.realtimeSinceStartup when the first avatar became ready; negative before. |
| `event Action<Core.SonaResult, string> Error` | Event. Fires on an error of the context, with its result code and message. |
| `Core.SonaAvatar AddItemPreview(string itemId, Core.SonaPreviewOptions options = null)` | One item worn alone on a grey stand-in body, for wardrobes and pickers. This package does not draw previews: draw one with a Core.SonaRenderer (DrawPreview, SnapshotPreview), or read its pose. |
| `Core.Native.sona_lod_stats LodStats()` | The level-of-detail statistics: avatars in view at each step, those fading, the baked looks and the bakes of the last draw. |
| `static Core.SonaView ViewOf(Camera cam)` | A Unity camera as the core's view: eye, target, field of view, near, far and size. |

## SonaAvatar

A component. One avatar.

| Field | Type | Default | What it does |
|---|---|---|---|
| `manifestBase64` | `string` | `""` | An AvatarDescription (1000 bytes) as base64. |
| `manifestAsset` | `TextAsset` | `null` | The same as a file: 1000 raw bytes, or base64 text. Used when the field above is empty. |
| `clip` | `string` | `"idle"` | A clip key, a raw clip id, "prop", "idle" or "still". |
| `loop` | `bool` | `true` | Loop the clip. Used when the avatar is added and at each change of clip. |
| `speed` | `float` | `1` | Playback speed; 1 is the clip's own. |
| `startAt` | `float` | `0` | Seconds into the clip; negative: random, to desynchronise a crowd. |
| `priority` | `int` | `0` | Higher builds sooner. |
| `crossfadeSeconds` | `float` | `0` | Seconds to blend into the new clip when the clip field changes while it plays. 0: a cut. |
| `applyRootMotion` | `bool` | `false` | Move this Transform by the clip's travel; the hips stay where the clip starts. |
| `expressionMouth` | `int` | `-1` | A mouth shape held over the clip: 0-6 moods, 7-13 speech. -1: as the clip has it. |
| `expressionEyebrows` | `int` | `-1` | An eyebrow shape for both eyebrows. -1: as the clip has it. |
| `expressionEyes` | `int` | `-1` | An eye shape for both eyes. -1: as the clip has it. |
| `jointOverrides` | `JointOverride[]` | `new JointOverride[0]` | Joints turned after the clip: a joint name (Head, LeftUpperArm, ...) and Euler degrees. |
| `overrideWeight` | `float` | `1`, 0 to 1 | How much of each joint override to use, 0 to 1. |
| `overridesAdd` | `bool` | `false` | Turn on top of the clip's rotation instead of replacing it. |
| `marks` | `float[]` | `new float[0]` | Seconds into the clip that raise a Mark clip event (ids 1, 2, ...). |
| `randomSeed` | `uint` | `0` | No manifest: a random look from this seed (needs the catalogue on the SonaContext). 0: none. |
| `proceduralIdle` | `bool` | `false` | Breathing, blinks, glances and weight shifts on top of the clip. |
| `footIk` | `bool` | `false` | Plant the feet on the colliders under them (a ray down), else on this Transform's height. |
| `lookTarget` | `Transform` | `null` | The head and eyes turn to look at this. |
| `sway` | `bool` | `false` | Hair and loose clothes sway as the avatar moves. |
| `upperBodyClip` | `string` | `""` | A clip played on the upper body over the main clip (a wave while walking). Empty: none. |

| Member | What it does |
|---|---|
| `Core.SonaAvatar Native` | The C# binding's avatar under this component, for a call the component does not wrap; null until it is added. |
| `byte[] Manifest` | The manifest the avatar was added with (the random look when randomSeed made it). |
| `Core.SonaAvatarState State` | The avatar's state. |
| `event Action<SonaAvatar> Ready` | Event. Fires once when the avatar is built and on screen. |
| `event Action<SonaAvatar, Core.SonaResult, string> Failed` | Event. Fires when the avatar cannot be built, with the result code and the message. |
| `event Action<SonaAvatar, Core.SonaClipEvent> ClipEvent` | Event. Clip events (started, looped, ended, footfalls, marks), once a frame while the avatar is ready. |
| `void SetManifest(byte[] manifest)` | Wears another manifest: the avatar is added again with it, keeping its clip and settings. |
| `static Core.SonaPlacement PlacementOf(Transform t)` | A Transform's position, yaw and uniform scale as a core placement. |
| `void Play(string clipName, bool loopClip = true, float clipSpeed = 1, float from = 0)` | Plays a clip. Called before the avatar is ready, it is applied when the avatar appears. |
| `void Stop()` | Holds the current pose. |
| `void Crossfade(string clipName, float seconds, bool loopClip = true, float clipSpeed = 1, float from = 0)` | Play, blending from the current pose over seconds. |
| `void Queue(string clipName, float fadeSeconds = 0, bool loopClip = true, float clipSpeed = 1, float from = 0)` | Plays clipName when the current clip ends (queue after a clip that does not loop). |
| `int QueuedCount` | How many clips are waiting in the queue. |
| `void SetOverride(int joint, Quaternion rotation, float weight = 1, Core.SonaOverrideMode mode = Core.SonaOverrideMode.Replace)` | A rotation after the clip, in the core's joint space. joint: a number or SonaJoints.Find("Head"). |
| `void SetOverride(string joint, Quaternion rotation, float weight = 1, Core.SonaOverrideMode mode = Core.SonaOverrideMode.Replace)` | A unit quaternion applied after the clip. |
| `void ClearOverride(int joint)` | A rotation applied after the clip each frame, for look-at and aiming. |
| `void ClearOverrides()` | Clears every override of the avatar. |
| `void SetExpression(byte mouth, byte leftEyebrow = Core.SonaMouth.Clip, byte rightEyebrow = Core.SonaMouth.Clip, byte leftEye = Core.SonaMouth.Clip, byte rightEye = Core.SonaMouth.Clip)` | Shape indexes, or Core.SonaMouth.Clip to leave a part as the clip has it. Speech mouths are 7-13. |
| `void ClearExpression()` | Hands the whole face back to the clip. |
| `void Mark(float seconds, uint id)` | A Mark event with this id each time the current clip passes seconds; marks go when another clip starts. |
| `void ClearMarks()` | Removes the avatar's marks. |
| `bool TryGetJointPosition(int joint, out Vector3 position)` | A joint's world position at the last update, by number or by name ("Head"); false before the avatar is ready and posed. |
| `bool TryGetJointPosition(string joint, out Vector3 position)` | A joint's world position at the last update, by number or by name ("Head"); false before the avatar is ready and posed. |
| `bool TryGetJointWorld(int joint, float[] out16)` | The row-vector world matrix, 16 floats. |
| `bool TryGetCapsule(out Vector3 bottom, out Vector3 top, out float radius)` | A vertical capsule around the posed body, for collisions. |
| `Core.SonaLodStep LodStep` | The level of detail it was drawn at last (sona_avatar_lod). |
| `void RefreshFeatures()` | Applies the 1.2 fields again (call after changing them from code). |

## SonaAvatar.JointOverride

A struct. One entry of jointOverrides.

| Field | Type | Default | What it does |
|---|---|---|---|
| `joint` | `string` | `""` | A joint name: Head, Neck, LeftUpperArm, ... |
| `rotation` | `Vector3` | `Vector3.zero` | Euler degrees, turned after the clip. |

## SonaCredit

A component. The small "Powered by 360sona" badge from sona_credit_get as a screen-space overlay, on by default.

| Field | Type | Default | What it does |
|---|---|---|---|
| `Text` | `string` | `"Powered by 360sona"` | The badge's words. |
| `Opacity` | `float` | `0.75` | The badge's opacity once an avatar is ready. |
| `Margin` | `int` | `6` | Pixels between the badge and the screen's edges. |
| `showBadge` | `bool` | `true` | Off: credit 360sona in your credits screen, about page or store page instead (the SDK Licence). |
| `corner` | `Core.SonaCorner` | `Core.SonaCorner.BottomRight` | Where the badge sits. |

| Member | What it does |
|---|---|
| `static float AlphaAt(float secondsSinceFirstReady)` | The badge's opacity a given number of seconds after the first avatar was ready; a negative time (no avatar ready) gives 0. |
| `static Rect Place(Core.SonaCorner c, float screenW, float screenH, float w, float h)` | The badge rectangle in GUI coordinates (top-left origin) for a screen of the given size. |

## SonaAnimatorBridge

A component. The Mecanim bridge.

| Field | Type | Default | What it does |
|---|---|---|---|
| `mode` | `BridgeMode` | `BridgeMode.Drive` | Drive: the Animator poses the avatar. Follow: the rig follows the avatar's clip. |
| `controller` | `RuntimeAnimatorController` | `null` | The Animator Controller with your humanoid clips (Drive). |

| Member | What it does |
|---|---|
| `Transform Rig` | The Humanoid rig's root Transform, built under the avatar once it is ready. |
| `Animator Animator` | The Animator on the rig, holding the controller. |
| `Avatar HumanAvatar` | The Humanoid Avatar built for the rig. |
| `bool IsBuilt` | True once the rig, its Avatar and the Animator are built. |
| `event Action<SonaAnimatorBridge> Built` | Event. Fires once the rig and its Avatar are built (the avatar is ready and posed). |
| `Transform Bone(string humanBodyBone)` | The rig's Transform for a HumanBodyBones name ("LeftHand"), or null before the rig is built. |
| `void Step()` | One step now: build once the avatar is ready, then follow or drive. LateUpdate calls it. |

## SonaAnimatorBridge.BridgeMode

An enum. Which way the pose goes between the Animator and the avatar.

Values: `Follow`, `Drive`.

## SonaAvatarEditor

A component. The drop-in avatar editor (the sona_editor module) as a component: the full creator, the quick creator or the wardrobe picker.

| Field | Type | Default | What it does |
|---|---|---|---|
| `mode` | `EditorMode` | `EditorMode.Full` | Full: Body, Appearance and Wardrobe, as 360sona.com's editor. Quick creator: eight looks, one change. Wardrobe picker: clothes only. |
| `target` | `SonaAvatar` | `null` | The avatar it edits, which wears the result. Empty: start from a blank figure (the wardrobe picker needs one). |
| `garmentColours` | `bool` | `true` | A worn garment's colourways over its Wardrobe category. |
| `lightTheme` | `bool` | `true` | The editor's light colours; off, the dark ones. |
| `thumbnails` | `bool` | `true` | Rendered pictures in the look and item cells (a headless Vulkan device of the core). Off: names only. |
| `noCancel` | `bool` | `false` | The player must finish: no Cancel. |
| `openOnStart` | `bool` | `false` | Open the editor when the scene starts. |
| `seed` | `uint` | `1` | The eight generated looks. |
| `title` | `string` | `""` | The heading. Empty: "Create your avatar" or "Choose an outfit". |
| `stageLayer` | `int` | `31` | The layer the editor's avatar and camera use; keep it out of your cameras' culling masks. |
| `stage` | `Vector3` | `new Vector3(0, -1000, 0)` | Where the editor's avatar stands, away from the game. |

| Member | What it does |
|---|---|
| `event Action<byte[]> Finished` | Event. Fires with the finished manifest (1,000 bytes) when the player is done; the target wears it. |
| `event Action Cancelled` | Event. Fires when the player cancels; nothing changes. |
| `event Action<string> Announced` | Event. What a screen reader should say (pass it to your accessibility layer). |
| `event Action<uint> Sound` | Event. A sound to play: SONA_EDITOR_SOUND_* (move 1, select 2, back 3, tab 4, page 5, done 6, cancel 7, error 8, random 9). |
| `bool IsOpen` | True while the editor is open. |
| `Core.SonaEditorStatus Status` | SONA_EDITOR_RUNNING, _DONE or _CANCELLED, as the last sona_editor_update returned. |
| `bool Busy` | True while an avatar is still building (the shown one or a change on its way); thumbnails do not count. |
| `Core.SonaEditorScreen Screen` | The screen shown now. |
| `SonaAvatar ShownAvatar` | The avatar on the editor's stage, or null while none is shown. |
| `Camera StageCamera` | The camera that draws the editor's stage. |
| `Texture2D UiTexture` | The editor's UI as a texture, drawn over the screen. |
| `byte[] UiPixels` | The UI layer as last drawn: straight RGBA8, UiWidth x UiHeight, row 0 at the top. |
| `int UiWidth` | The UI texture's width in pixels. |
| `int UiHeight` | The UI texture's height in pixels. |
| `bool HasThumbnails` | True while open with cell pictures (a headless device opened, or will once the shading data is in). |
| `bool Open()` | Opens the editor; false (with the reason in the log) when the context or its catalogue is missing. |
| `void Close()` | Closes the editor without an event and removes its avatars. |
| `void Button(Pad b, bool down)` | A gamepad button pressed or let go (sona_editor_input). |
| `void Press(Pad b)` | A button pressed and let go, with an update between. |
| `void Key(Core.SonaEditorKey k, bool shift = false, bool ctrl = false)` | A key pressed, with shift and ctrl (sona_editor_input). |
| `void Axis(Core.SonaEditorAxis a, float v)` | A gamepad axis moved, -1 to 1 (sona_editor_input). |
| `void Pointer(Vector2 at, bool? down, uint id = 0)` | A pointer in editor pixels (top-left origin). down: true pressed, false released, null moved. |
| `bool SetScreen(Core.SonaEditorScreen s)` | Moves to a screen of the mode (a deprecated id to the screen that took its place). |
| `byte[] Result()` | The avatar as it stands (at any time): SONA_MANIFEST_BYTES. |
| `List<Core.SonaEditorControl> Controls()` | Every control on screen for a screen reader: label, role, value and whether it has focus. |
| `Core.SonaEditorStatus Step(float dt)` | One frame of the editor: dt seconds, then the avatar, the camera and the UI layer. |

## SonaAvatarEditor.EditorMode

An enum. The editor's three screens.

Values: `Full`, `QuickCreator`, `WardrobePicker`.

## SonaAvatarEditor.Pad

An enum. The gamepad buttons Button and Press take.

Values: `A`, `B`, `X`, `Y`, `LB`, `RB`, `LT`, `RT`, `Up`, `Down`, `Left`, `Right`, `Start`, `Back`.

## SonaHumanoid

A class. The avatar rig under Unity Humanoid names, and the maths SonaAnimatorBridge uses.

| Member | What it does |
|---|---|
| `static int JointParent(int joint)` | The rig's parent of a joint (from sona_mask_branch), -1 for the hips. |
| `static string HumanName(string bone)` | "Left Thumb Proximal" for "LeftThumbProximal"; the body bones keep their names. |
| `static IReadOnlyList<Bone> Bones` | Every joint with a Unity Humanoid bone, parents first. |
| `static Quaternion RotationOf(float[] m)` | The rotation of a row-vector matrix (the core's, 16 floats), scale taken off. |
| `static Vector3 PositionOf(float[] m)` | The position of a row-vector matrix (16 floats). |
| `static Quaternion Normalize(Quaternion q)` | The quaternion at length 1. |
| `static Quaternion ToRig(Quaternion q)` | A rotation or position from the avatar's axes to the Humanoid rig's (turned 180 degrees about Y). |
| `static Quaternion FromRig(Quaternion q)` | A rotation or position from the Humanoid rig's axes to the avatar's. |
| `static Vector3 ToRig(Vector3 p)` | A rotation or position from the avatar's axes to the Humanoid rig's (turned 180 degrees about Y). |
| `static Vector3 FromRig(Vector3 p)` | A rotation or position from the Humanoid rig's axes to the avatar's. |

## SonaHumanoid.Bone

A class. One joint of the rig with its Humanoid bone.

| Field | Type | Default | What it does |
|---|---|---|---|
| `Joint` | `int` | `0` | The core's joint number. |
| `Parent` | `int` | `0` | index into Bones, -1 for the hips. |
| `Name` | `string` | `""` | HumanBodyBones name: "LeftUpperArm", "LeftThumbProximal". |
| `HumanName` | `string` | `""` | HumanTrait name: "LeftUpperArm", "Left Thumb Proximal". |

## SonaMeshBuilder

A class. The data API's meshes, textures and materials as Unity objects.

| Field | Type | Default | What it does |
|---|---|---|---|
| `Stride` | `int` | `76` | Bytes in one runtime vertex. |
| `ColorTexId` | `int` | `Shader.PropertyToID("_ColorTex")` | The shader property id of the colour texture. |
| `IntensityTexId` | `int` | `Shader.PropertyToID("_IntensityTex")` | The shader property id of the intensity texture. |
| `DecalTexId` | `int` | `Shader.PropertyToID("_DecalTex")` | The shader property id of the decal texture (the matcap of a reflective material). |
| `RimId` | `int` | `Shader.PropertyToID("_SonaRim")` | The shader property id of the rim colour and power. |
| `TransparencyId` | `int` | `Shader.PropertyToID("_SonaTransparency")` | The shader property id of the transparency. |
| `SkinId` | `int` | `Shader.PropertyToID("_SonaSkin")` | The shader property id of the skin flag. |
| `ReflectiveId` | `int` | `Shader.PropertyToID("_SonaReflective")` | The shader property id of the reflective flag. |
| `PaletteId` | `int` | `Shader.PropertyToID("_SonaPalette")` | The shader property id of the joint palette buffer. |
| `IrradianceId` | `int` | `Shader.PropertyToID("_SonaIrradiance")` | The shader property id of the environment's irradiance. |
| `IrradianceGainId` | `int` | `Shader.PropertyToID("_SonaIrradianceGain")` | The shader property id of the irradiance gain. |

| Member | What it does |
|---|---|
| `static VertexAttributeDescriptor[] Layout` | The Unity vertex layout (a copy). |
| `static unsafe void Repack(byte* src, byte* dst, int count)` | Copies count vertices from the runtime layout into Unity's attribute order. |
| `static unsafe void Repack(ReadOnlySpan<byte> src, Span<byte> dst, int count)` | Copies count vertices from the runtime layout into Unity's attribute order. |
| `static Bounds SkinnedBounds` | Avatar-space bounds wide enough for any clip: the shader moves vertices away from the bind pose. |
| `static unsafe Mesh BuildMesh(in SonaMeshData m, ref byte[] scratch)` | A Unity Mesh from a mesh of the data API; scratch is reused between calls. |
| `static Texture2D BuildTexture(in SonaTextureData t, int addr)` | RGBA32 sRGB. Row 0 of the data lands at v = 0, as on the web. |
| `static void UpdateTexture(Texture2D tex, in SonaTextureData t)` | Uploads a texture's pixels from the data API again. |
| `static Texture2D Solid(byte r, byte g, byte b, byte a)` | A 1 x 1 texture of one colour, for a material that has no texture. |
| `static Cubemap BuildIrradiance(SonaShadingData s)` | The 16x16 RGBA16F irradiance cube, faces +X -X +Y -Y +Z -Z (Unity's CubemapFace order). |
| `static Texture2D BuildBadge(SonaCreditImage c)` | Our credit badge (straight RGBA, row 0 at the top) flipped into Unity's bottom-up rows. |
| `static Material BuildMaterial(Shader shader, in SonaMaterialData m, Texture color, Texture intensity, Texture decal, int order)` | One material per draw: the program (skin, reflective), RimLightColorAndReflectivity (params 36..39), transparency and the web's two pass states. order keeps the web's list order inside a pass. |
| `static void UploadPalette(GraphicsBuffer buffer, IntPtr palette, float[] staging)` | Copies 864 palette floats from the core into a staging array, then into the GPU buffer. |
| `static GraphicsBuffer NewPaletteBuffer()` | A GraphicsBuffer for one avatar's joint palette (216 float4: 72 joints, three rows each). |
