From 1ec378aa7935eb3b12eb69374500e91e62b9eeef Mon Sep 17 00:00:00 2001 From: Toni Seas <83423392+ToniSeas@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:23:56 -0600 Subject: [PATCH] Remove the Core documentation Signed-off-by: Antony Seas <83423392+ToniSeas@users.noreply.github.com> Signed-off-by: Toni Seas <83423392+ToniSeas@users.noreply.github.com> --- AGENTS.md | 5 +- CONTRIBUTING.md | 8 +- README.md | 3 +- docs/core/add-to-your-project.md | 43 --- .../config/group-tree-and-inspectors.md | 83 ------ docs/core/codegen/config/linked-scene.md | 53 ---- .../core/codegen/config/translation-config.md | 35 --- docs/core/codegen/config/ts-config.md | 80 ----- .../codegen/config/ts-pending-config-edit.md | 71 ----- docs/core/codegen/config/ts-window.md | 89 ------ .../internals/adding-a-codegen-module.md | 97 ------- .../codegen/internals/supporting-utilities.md | 74 ----- docs/core/codegen/internals/ts-generator.md | 90 ------ docs/core/codegen/internals/ts-module.md | 103 ------- .../internals/ts-translation-window.md | 45 --- docs/core/codegen/modules/construct-module.md | 68 ----- docs/core/codegen/modules/factory-module.md | 73 ----- docs/core/codegen/modules/global-module.md | 62 ---- docs/core/codegen/modules/instance-module.md | 59 ---- docs/core/codegen/modules/log-module.md | 38 --- docs/core/codegen/modules/memory-module.md | 17 -- docs/core/codegen/modules/pool-module.md | 88 ------ docs/core/codegen/modules/scaffold-module.md | 53 ---- .../codegen/modules/translation-module.md | 72 ----- .../modules/ts-single-component-module.md | 48 --- docs/core/core-concepts/attributes.md | 129 --------- .../core-concepts/how-it-fits-together.md | 75 ----- docs/core/core-concepts/instance.md | 67 ----- docs/core/core-concepts/process.md | 132 --------- docs/core/core-concepts/ts-root.md | 61 ---- docs/core/core-concepts/tsvrc-behaviour.md | 172 ----------- .../explanations/builtin-registrations.md | 67 ----- .../explanations/codegen-vs-reflection.md | 61 ---- docs/core/explanations/pooling-pattern.md | 48 --- docs/core/explanations/sync-model.md | 60 ---- docs/core/first-behaviour.md | 93 ------ docs/core/game-flow/ranked-game-session.md | 200 ------------- docs/core/game-flow/state-manager.md | 93 ------ docs/core/how-to/adding-a-language.md | 80 ----- .../how-to/adding-a-screen-state-machine.md | 77 ----- docs/core/how-to/assigning-player-colors.md | 51 ---- docs/core/how-to/building-a-list-ui.md | 72 ----- docs/core/how-to/combining-meshes.md | 49 ---- .../how-to/guarding-against-head-clipping.md | 54 ---- docs/core/how-to/persisting-a-value.md | 95 ------ docs/core/how-to/pooling-a-prefab.md | 81 ------ docs/core/how-to/reaching-a-scene-object.md | 79 ----- docs/core/how-to/running-a-countdown.md | 79 ----- docs/core/how-to/running-a-timed-round.md | 108 ------- docs/core/how-to/set-up-automated-testing.md | 39 --- docs/core/how-to/showing-player-positions.md | 86 ------ docs/core/how-to/spawning-a-local-object.md | 58 ---- .../how-to/tracking-a-group-of-players.md | 67 ----- .../transferring-data-between-clients.md | 115 -------- docs/core/how-to/wiring-a-ready-check.md | 95 ------ docs/core/how-to/writing-your-first-test.md | 90 ------ docs/core/intro.md | 44 --- .../data-transfer/chunked-transfer-session.md | 77 ----- .../data-transfer/data-chunk-receiver.md | 91 ------ .../data-transfer/data-chunker.md | 45 --- .../data-transfer/data-sender-receiver.md | 53 ---- .../data-transfer/data-sender.md | 49 ---- .../data-transfer/data-transferer.md | 60 ---- docs/core/networking-data/overview.md | 55 ---- docs/core/networking-data/tsvrc-memory.md | 153 ---------- docs/core/networking-data/tsvrc-timer.md | 116 -------- .../players-tracking/auto-player-tracker.md | 74 ----- docs/core/players-tracking/head-clip-guard.md | 84 ------ .../players-tracking/player-color-assigner.md | 54 ---- docs/core/players-tracking/player-tracker.md | 106 ------- .../players-tracking/ready-check-process.md | 105 ------- docs/core/players-tracking/ts-player.md | 64 ---- docs/core/testing/testing-your-world.md | 43 --- docs/core/ui-components/list/list-item.md | 49 ---- docs/core/ui-components/list/tsvrc-list.md | 60 ---- .../overlay/player-marker-renderer.md | 45 --- .../overlay/player-position-overlay.md | 69 ----- .../overlay/raster-player-marker-renderer.md | 61 ---- .../core/ui-components/texture-graphics-2d.md | 117 -------- docs/core/utilities/mesh-combiner.md | 110 ------- docs/core/utilities/read-only-attribute.md | 25 -- docs/core/utilities/ts-array.md | 71 ----- docs/core/utilities/ts-json.md | 78 ----- docs/core/utilities/tsvrc-logger.md | 91 ------ i18n/es/code.json | 135 --------- .../current/core/intro.md | 46 --- sidebars.ts | 107 +------ src/components/TsWindowMock/EntriesPanel.tsx | 236 --------------- .../TsWindowMock/GeneratedPreview.tsx | 49 ---- src/components/TsWindowMock/GroupsPanel.tsx | 170 ----------- src/components/TsWindowMock/Icons.tsx | 47 --- src/components/TsWindowMock/SettingsPanel.tsx | 103 ------- src/components/TsWindowMock/data.ts | 179 ------------ src/components/TsWindowMock/index.tsx | 274 ------------------ src/components/TsWindowMock/styles.ts | 50 ---- .../TsWindowMock/useConfigureState.ts | 208 ------------- .../core/AnnotatedCode/AnnotationList.tsx | 37 --- src/components/core/AnnotatedCode/Badge.tsx | 10 - .../core/AnnotatedCode/CodePanel.tsx | 118 -------- .../core/AnnotatedCode/annotations.ts | 104 ------- src/components/core/AnnotatedCode/index.tsx | 13 - src/components/core/Features.tsx | 127 -------- src/components/core/GetStarted.tsx | 52 ---- src/components/core/Hero.tsx | 57 ---- src/components/core/ProblemSolution.tsx | 36 --- src/components/core/ScrollCue.tsx | 16 - src/components/homepage/Projects.tsx | 12 - src/pages/core.tsx | 24 -- 108 files changed, 8 insertions(+), 8341 deletions(-) delete mode 100644 docs/core/add-to-your-project.md delete mode 100644 docs/core/codegen/config/group-tree-and-inspectors.md delete mode 100644 docs/core/codegen/config/linked-scene.md delete mode 100644 docs/core/codegen/config/translation-config.md delete mode 100644 docs/core/codegen/config/ts-config.md delete mode 100644 docs/core/codegen/config/ts-pending-config-edit.md delete mode 100644 docs/core/codegen/config/ts-window.md delete mode 100644 docs/core/codegen/internals/adding-a-codegen-module.md delete mode 100644 docs/core/codegen/internals/supporting-utilities.md delete mode 100644 docs/core/codegen/internals/ts-generator.md delete mode 100644 docs/core/codegen/internals/ts-module.md delete mode 100644 docs/core/codegen/internals/ts-translation-window.md delete mode 100644 docs/core/codegen/modules/construct-module.md delete mode 100644 docs/core/codegen/modules/factory-module.md delete mode 100644 docs/core/codegen/modules/global-module.md delete mode 100644 docs/core/codegen/modules/instance-module.md delete mode 100644 docs/core/codegen/modules/log-module.md delete mode 100644 docs/core/codegen/modules/memory-module.md delete mode 100644 docs/core/codegen/modules/pool-module.md delete mode 100644 docs/core/codegen/modules/scaffold-module.md delete mode 100644 docs/core/codegen/modules/translation-module.md delete mode 100644 docs/core/codegen/modules/ts-single-component-module.md delete mode 100644 docs/core/core-concepts/attributes.md delete mode 100644 docs/core/core-concepts/how-it-fits-together.md delete mode 100644 docs/core/core-concepts/instance.md delete mode 100644 docs/core/core-concepts/process.md delete mode 100644 docs/core/core-concepts/ts-root.md delete mode 100644 docs/core/core-concepts/tsvrc-behaviour.md delete mode 100644 docs/core/explanations/builtin-registrations.md delete mode 100644 docs/core/explanations/codegen-vs-reflection.md delete mode 100644 docs/core/explanations/pooling-pattern.md delete mode 100644 docs/core/explanations/sync-model.md delete mode 100644 docs/core/first-behaviour.md delete mode 100644 docs/core/game-flow/ranked-game-session.md delete mode 100644 docs/core/game-flow/state-manager.md delete mode 100644 docs/core/how-to/adding-a-language.md delete mode 100644 docs/core/how-to/adding-a-screen-state-machine.md delete mode 100644 docs/core/how-to/assigning-player-colors.md delete mode 100644 docs/core/how-to/building-a-list-ui.md delete mode 100644 docs/core/how-to/combining-meshes.md delete mode 100644 docs/core/how-to/guarding-against-head-clipping.md delete mode 100644 docs/core/how-to/persisting-a-value.md delete mode 100644 docs/core/how-to/pooling-a-prefab.md delete mode 100644 docs/core/how-to/reaching-a-scene-object.md delete mode 100644 docs/core/how-to/running-a-countdown.md delete mode 100644 docs/core/how-to/running-a-timed-round.md delete mode 100644 docs/core/how-to/set-up-automated-testing.md delete mode 100644 docs/core/how-to/showing-player-positions.md delete mode 100644 docs/core/how-to/spawning-a-local-object.md delete mode 100644 docs/core/how-to/tracking-a-group-of-players.md delete mode 100644 docs/core/how-to/transferring-data-between-clients.md delete mode 100644 docs/core/how-to/wiring-a-ready-check.md delete mode 100644 docs/core/how-to/writing-your-first-test.md delete mode 100644 docs/core/intro.md delete mode 100644 docs/core/networking-data/data-transfer/chunked-transfer-session.md delete mode 100644 docs/core/networking-data/data-transfer/data-chunk-receiver.md delete mode 100644 docs/core/networking-data/data-transfer/data-chunker.md delete mode 100644 docs/core/networking-data/data-transfer/data-sender-receiver.md delete mode 100644 docs/core/networking-data/data-transfer/data-sender.md delete mode 100644 docs/core/networking-data/data-transfer/data-transferer.md delete mode 100644 docs/core/networking-data/overview.md delete mode 100644 docs/core/networking-data/tsvrc-memory.md delete mode 100644 docs/core/networking-data/tsvrc-timer.md delete mode 100644 docs/core/players-tracking/auto-player-tracker.md delete mode 100644 docs/core/players-tracking/head-clip-guard.md delete mode 100644 docs/core/players-tracking/player-color-assigner.md delete mode 100644 docs/core/players-tracking/player-tracker.md delete mode 100644 docs/core/players-tracking/ready-check-process.md delete mode 100644 docs/core/players-tracking/ts-player.md delete mode 100644 docs/core/testing/testing-your-world.md delete mode 100644 docs/core/ui-components/list/list-item.md delete mode 100644 docs/core/ui-components/list/tsvrc-list.md delete mode 100644 docs/core/ui-components/overlay/player-marker-renderer.md delete mode 100644 docs/core/ui-components/overlay/player-position-overlay.md delete mode 100644 docs/core/ui-components/overlay/raster-player-marker-renderer.md delete mode 100644 docs/core/ui-components/texture-graphics-2d.md delete mode 100644 docs/core/utilities/mesh-combiner.md delete mode 100644 docs/core/utilities/read-only-attribute.md delete mode 100644 docs/core/utilities/ts-array.md delete mode 100644 docs/core/utilities/ts-json.md delete mode 100644 docs/core/utilities/tsvrc-logger.md delete mode 100644 i18n/es/docusaurus-plugin-content-docs/current/core/intro.md delete mode 100644 src/components/TsWindowMock/EntriesPanel.tsx delete mode 100644 src/components/TsWindowMock/GeneratedPreview.tsx delete mode 100644 src/components/TsWindowMock/GroupsPanel.tsx delete mode 100644 src/components/TsWindowMock/Icons.tsx delete mode 100644 src/components/TsWindowMock/SettingsPanel.tsx delete mode 100644 src/components/TsWindowMock/data.ts delete mode 100644 src/components/TsWindowMock/index.tsx delete mode 100644 src/components/TsWindowMock/styles.ts delete mode 100644 src/components/TsWindowMock/useConfigureState.ts delete mode 100644 src/components/core/AnnotatedCode/AnnotationList.tsx delete mode 100644 src/components/core/AnnotatedCode/Badge.tsx delete mode 100644 src/components/core/AnnotatedCode/CodePanel.tsx delete mode 100644 src/components/core/AnnotatedCode/annotations.ts delete mode 100644 src/components/core/AnnotatedCode/index.tsx delete mode 100644 src/components/core/Features.tsx delete mode 100644 src/components/core/GetStarted.tsx delete mode 100644 src/components/core/Hero.tsx delete mode 100644 src/components/core/ProblemSolution.tsx delete mode 100644 src/components/core/ScrollCue.tsx delete mode 100644 src/pages/core.tsx diff --git a/AGENTS.md b/AGENTS.md index 0e64939..45c279b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,5 @@ link, which `npm start` doesn't catch. - `sidebars.ts` is written by hand. A `dirName` pointed at a leaf folder returns an unlabeled flat list, so the `label` of a category comes from its wrapping `{type: 'category', ...}` node, not a `_category_.json`. -- The code of each project lives in its own repo (`tsvrc-core`, `udon-test-kit`), and nothing - keeps it in sync with this one. When the public behavior of a project changes, check its pages - here, and the Core testing pages too when Udon Test Kit changes. +- The code of each project lives in its own repo (such as `udon-test-kit`), and nothing keeps it in + sync with this one. When the public behavior of a project changes, check its pages here. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 92cc83e..e66b532 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,15 +35,15 @@ A page every project shares, such as [Install a TsVRC package](docs/install-a-pa the root of `docs/`. Each project install page links to it and adds only what's specific to that project: the package name, requirements, and how to check that it worked. -The docs of a project stand on their own. When one project depends on another, as Core does on Udon -Test Kit, the dependent project links to the other where a reader needs it, and the project -depended on never mentions its consumers. +The docs of a project stand on their own. When one project depends on another, the dependent +project links to the other where a reader needs it, and the project depended on never mentions its +consumers. ## Adding a translation English pages live in `docs//`. A translation mirrors the same paths and file names under `i18n//docusaurus-plugin-content-docs/current//`, so adding a language never -touches the English files. `docs/core/intro.md` and its Spanish counterpart are a worked example. +touches the English files. Pages in `src/pages/` translate through `@docusaurus/Translate` instead, with their strings in `i18n//code.json`. diff --git a/README.md b/README.md index 9a62443..829a3c0 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,7 @@ The [Docusaurus](https://docusaurus.io/) site behind [tsvrc.com](https://tsvrc.com), with the docs for every TsVRC project. The code of each project lives in its own repository, such as -[tsvrc/udon-test-kit](https://github.com/tsvrc/udon-test-kit) for Udon Test Kit and -[tsvrc/tsvrc-core](https://github.com/tsvrc/tsvrc-core) for Core. +[tsvrc/udon-test-kit](https://github.com/tsvrc/udon-test-kit) for Udon Test Kit. ## Contributing diff --git a/docs/core/add-to-your-project.md b/docs/core/add-to-your-project.md deleted file mode 100644 index 029b76f..0000000 --- a/docs/core/add-to-your-project.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -id: add-to-your-project -title: Add TsVRC Core to your project -sidebar_position: 1 ---- - -# Add TsVRC Core to your project - -Install TsVRC Core in a VRChat world project. - -## Requirements - -- **Unity 2022.3.** The Core package manifest targets this version. -- **The [VRChat Worlds SDK](https://creators.vrchat.com/worlds/) `3.10.x`.** - -## Install the package - -Install **TsVRC Core** (`com.tsvrc.core`) as described in -[Install a TsVRC package](/docs/install-a-package). Its `.unitypackage` is on -[the Core GitHub releases](https://github.com/tsvrc/tsvrc-core/releases). - -Core depends on [Udon Test Kit](/docs/udon-test-kit/intro) (`com.tsvrc.udon-test-kit`): its -codegen uses the kit to [hold back while tests run](./testing/testing-your-world#codegen-during-a-test-run). -The Creator Companion installs it along with Core. With the `.unitypackage`, import the -[Udon Test Kit](/docs/udon-test-kit/add-to-your-project) one too, unless your project already has -the kit. - -You'll know it worked when the Unity menu bar gains a **Tsvrc** menu. Everything Core does -from here runs from there. - -## What you just added - -The Core manifest description sums it up: structured initialization, dependency wiring, -and editor codegen tooling for building VRChat worlds with UdonSharp. The package compiles as -one runtime assembly (`Tsvrc.Runtime`), the base classes your world -scripts extend and call into, and one editor-only assembly (`Tsvrc.Editor`) holding all -the codegen and Configure-window tooling. See [How Core fits -together](./core-concepts/how-it-fits-together) for how those two halves relate. - -## Next - -Continue to [Build your first behaviour](./first-behaviour) to initialize Core in a -scene and get a script running. diff --git a/docs/core/codegen/config/group-tree-and-inspectors.md b/docs/core/codegen/config/group-tree-and-inspectors.md deleted file mode 100644 index 6228c28..0000000 --- a/docs/core/codegen/config/group-tree-and-inspectors.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -id: group-tree-and-inspectors -title: Group tree, inspectors, and shared UI helpers -sidebar_position: 4 ---- - -# Group tree, inspectors, and shared UI helpers - -The rest of the `Editor/Configure` folder: the master-detail widget every grouped tab -(Globals, Pool, Constructs, Factories) is actually built from, the custom inspectors that -redirect a curious Hierarchy click back to [Tsvrc > Configure](./ts-window), and the small -shared drawing helpers used across every Tsvrc editor window. - -## TsGroupTreeGUI - -`Tsvrc.Editor.TsGroupTreeGUI` renders one `TsGroup[]`/`TsGroupedEntry[]` pair as a -master-detail view: a searchable `TreeView` of nested groups on the left, the selected -group's direct entries on the right (row rendering delegated to -[`ObjectListGUI`](#objectlistgui) below). Every grouped module's tab is this same widget -with different parameters. `memberPrefix`/`memberSuffix` control whether a live member-name -preview is shown at all (`"_ts."` for Globals, `"Create"`/`"(parent)"` for Factories, -neither for Pool or Constructs, since neither generates a name at all). `prefixRespectsToggle` -mirrors the `respectToggle` parameter of -[`BuildGroupPrefix`](../internals/ts-module): Factory always prefixes regardless of a group's `IncludeInName`, Global respects -it per-group. - -Its `State` class holds purely UI-local state (tree expansion, selection, search text, -pagination), never written back to any config asset, persisted across a domain reload via -`SessionState`. It's keyed by a combination of the target object's type name and the -property name being drawn, specifically so the `TsConfig`-backed trees in `TsWindow` and the -`TsBuiltinConfig`-backed trees in `TsBuiltinConfigInspector` (which share property names like -`"GlobalGroups"`) never collide on the same session key. - -`Draw` returns whether a drag-and-drop reparent action already flushed its own nested -`ApplyModifiedProperties()` call during this draw. Callers must fold that into their own -"did anything change" tracking, since a raw `SerializedProperty` write never sets -`GUI.changed` on its own, so it would otherwise go undetected by the caller's own -`EditorGUI.EndChangeCheck()`. - -## ObjectListGUI - -`Tsvrc.Editor.ObjectListGUI` supplies the actual per-row rendering `TsGroupTreeGUI` calls -into: a delete button, and per-row hint text covering three cases a bare `PropertyField` -can't communicate on its own. An empty slot means something used to be assigned here and -was probably deleted; a scene-instance reference where only a persisted prefab asset is -valid (the Pool and Factory tabs, both drawn with `assetsOnly: true`) gets its own hint too; -and a type resolved only via the compile-broken fallback in `TsModule.TryResolveObjectType` is -shown with a note that the compile is currently broken, since the Unity `PropertyField` -can't display a component's real type while nothing compiles. - -## The three "managed by Configure" inspectors - -`TsRootInspector`, `TsConfigInspector`, and `TsBuiltinConfigInspector` all exist for the -same reason: someone can select the generated root, the `TsConfig` object, or the shared -builtin config asset directly in the Hierarchy or Project window without knowing -**Tsvrc > Configure** exists at all, and a bare default inspector would give no hint that a -friendlier, purpose-built UI is what they actually want. - -- **`TsRootInspector`** shows a banner, then falls through to `DrawDefaultInspector()`. The - generated root's fields are meant to be *read*, occasionally, not edited by hand. -- **`TsConfigInspector`** shows a banner and draws **nothing else at all**: every field on - `TsConfig` is only ever meant to be edited through the Configure window's Apply/Discard - batching, so exposing raw field editing here would bypass that guarantee entirely. -- **`TsBuiltinConfigInspector`** is the one real exception. `TsBuiltinConfig` has no - dedicated window of its own, so this inspector *is* its actual editing surface, drawing - the same `TsGroupTreeGUI` widget Configure uses, with its own - [`TsPendingConfigEdit`](./ts-pending-config-edit) instance for the same Apply/Discard - consistency, even though nothing watches this particular asset for automatic regeneration - the way `TsConfig` is watched. - -## Shared helpers: TsEditorGUI and TsAbout - -`TsEditorGUI` is a small set of drawing helpers shared by every Tsvrc editor window -(Configure, the Translation window, the Mesh Combiner window) so they present one consistent -look: `DrawStatusBox` (a `HelpBox` plus consistent spacing), `PrimaryButton` (a button that -can be disabled with an explanatory tooltip instead of silently doing nothing when clicked), -and `DrawManagedByConfigureBanner` (the banner the three inspectors above all share, with a -button that opens Configure directly via `EditorApplication.ExecuteMenuItem`). - -`TsAbout` backs the **Tsvrc > Documentation** and **Tsvrc > About** menu items. The latter -reads `package.json` directly off disk and shows its name, version, and description, so -someone reporting a bug doesn't have to dig through the Package Manager UI or open the raw -file themselves to find the version they're running. diff --git a/docs/core/codegen/config/linked-scene.md b/docs/core/codegen/config/linked-scene.md deleted file mode 100644 index 256385a..0000000 --- a/docs/core/codegen/config/linked-scene.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -id: linked-scene -title: TsLinkedScene -sidebar_position: 5 ---- - -# TsLinkedScene - -`Tsvrc.Editor.TsLinkedScene` is the single scene the code generator is allowed to read -scene-sourced configuration from: `TsConfig`, `[WirePool]` field scans, the compiled -scaffold root. It exists to close a real correctness gap. Without it, every codegen lookup -searched "whatever scene happens to be loaded," which meant switching to look at an -unrelated scene, or a play-mode test's own temporary scene, could silently regenerate a -project's real generated output with an almost-empty result. A scene with no `TsConfig` -compiles clean, and per the snapshot-fallback logic in `TsModule`, a clean compile with fewer -entries than before is treated as a deliberate deletion, not an error. - -## How it's set - -Set from **Tsvrc > Configure**, persisted in a small per-project asset -(`TsLinkedSceneConfig`, holding just a scene GUID) under the project's generated-output -folder. Until a project links a scene, every lookup falls back to the legacy "search -whatever scene is loaded" behavior, so an unconfigured project keeps working exactly as it -always did. Linking is opt-in, not a breaking requirement. - -The stored value is a GUID, not a path: Unity keeps a GUID's `.meta` mapping correct -automatically across a rename or move, so resolving the current path from the GUID at read -time makes renaming or relocating the linked scene a non-issue rather than a silent, -permanent break. A GUID that no longer resolves to *any* path means the scene asset itself -was deleted outright, distinguished from "linked but not currently open" via -`IsConfiguredButMissing`, so the Configure window can show the right message for each case. - -## What it changes about lookups - -Once a scene is linked, every scene-scoped lookup (`Find`, `FindType`, `FindAll`, -`FindAllType`) is scoped strictly to that scene's root objects, rather than searching -whatever's currently loaded. `Find`/`FindType` additionally refuse to guess: if more than -one match exists within the linked scene, they return `null` rather than picking whichever -one the Unity iteration order happens to return first, the same "don't guess" stance -`InstanceModule` takes for resolving a project's single scaffold instance. - -`IsConfiguredButNotLoaded` is true whenever a scene has been linked but isn't currently -among the loaded scenes, for any reason, including having been deleted (a strict superset of -`IsConfiguredButMissing`). The generator's own run logic treats this as a hard "do nothing": -once a scene has been explicitly linked, no other loaded scene is ever treated as a -legitimate substitute for it. - -## Test-only override - -`SetOverride`/`ClearOverride` exist purely as a test seam, mirroring a pattern used -elsewhere in the codegen tooling (`TsPaths`): a test can point lookups at its own synthetic -scene for the scope of that test, so the codegen test suite keeps resolving its own test -fixtures regardless of what a real consuming project happens to have linked. diff --git a/docs/core/codegen/config/translation-config.md b/docs/core/codegen/config/translation-config.md deleted file mode 100644 index abbbafd..0000000 --- a/docs/core/codegen/config/translation-config.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -id: translation-config -title: TsTranslationConfig -sidebar_position: 6 ---- - -# TsTranslationConfig - -`Tsvrc.Editor.TsTranslationConfig` is a small `ScriptableObject` holding the list of -language files (`LanguageFiles`, a `TextAsset[]`) that `TranslationModule` and the -Translation editor window read from. Each referenced file is expected to be a JSON document -containing a `"key"`, a `"label"`, and an `"entries"` field: one file per language. See -[`TranslationModule`](../modules/translation-module) for how the generator actually turns -these into generated lookup code, and the -[Translation window](../internals/ts-translation-window) for the authoring tool -built around this same file format. - -## Usage - -A language file for French, referenced from a `TsTranslationConfig` asset's `LanguageFiles` -array: - -```json -{ - "key": "fr", - "label": "Français", - "entries": { - "menu.play": "Jouer", - "menu.settings": "Paramètres" - } -} -``` - -An entry's value can also be an object with its own `"label"` field instead of a plain -string, for entries that need extra per-language metadata later. diff --git a/docs/core/codegen/config/ts-config.md b/docs/core/codegen/config/ts-config.md deleted file mode 100644 index 7dcf2ef..0000000 --- a/docs/core/codegen/config/ts-config.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -id: ts-config -title: TsConfig and TsBuiltinConfig -sidebar_position: 1 ---- - -# TsConfig and TsBuiltinConfig - -`Tsvrc.Config.TsConfig`, `TsGroup`, `TsGroupedEntry`, and `Tsvrc.Editor.TsBuiltinConfig` -together form the data model the [codegen modules](../modules/global-module) (Global, Pool, -Construct, Factory) read at generate time. **Tsvrc > Configure** is the intended way to -change these fields; you don't normally hand-edit them directly, but they're what the -window actually writes to, and what a codegen module's own reference page describes reading -from. - -## TsConfig: one scene component holds everything - -`TsConfig` is a plain `MonoBehaviour`, never compiled to Udon since it's compile-time-only -configuration. It's auto-created and self-healed as a child of the generated scaffold -object, and holds four parallel entry/group/next-id triples, one per registration kind: - -| Entries | Groups | What they register | -|---|---|---| -| `GlobalEntries` | `GlobalGroups` | Scene objects exposed as named fields on the generated root (`_ts.Name`) | -| `PoolEntries` | `PoolGroups` | `UdonSharpBehaviour` prefabs to pool (must be prefab assets, not scene objects) | -| `ConstructEntries` | `ConstructGroups` | `TsvrcBehaviour`s always active in the scene, constructed at startup. The reference stays private, never exposed as `_ts.Name` | -| `FactoryEntries` | `FactoryGroups` | Prefabs registered for non-networked runtime instantiation via a generated `Create{Name}(Transform parent)` method | - -Globals and Constructs hold scene-object references specifically because only a scene -object can hold one: a `ScriptableObject` asset has no stable way to reference a scene -object, since a scene object's `fileID` is only meaningful within its own scene file. Pool -and Factory entries are asset/prefab references instead, which a scene object can hold just -as well. The constraint only runs one direction, which is why everything ends up on this -one scene component rather than split between an asset and a scene behaviour. - -It's deliberately *not* placed under an `Editor/` folder, despite being editor-only -configuration: a script under a folder literally named `Editor` is excluded from the -runtime assembly, and `AddComponent` silently fails for such a type: the component could -never actually attach to a scene object. What strips it from the actual VRChat build -instead is an `EditorOnly` tag on its `GameObject`, set by the scaffold module. - -`TreeShakeUnused` (off by default) and `ForceIncludeNames` control whether Global/Factory -entries not referenced anywhere in your project's own code get excluded from generated -output. See the relevant codegen module's reference page for the exact mechanics and the -two-pass grace period involved. - -## TsGroup and TsGroupedEntry - -`TsGroup` is one node in an entry group tree, flat, with a `ParentId` reference rather than -a nested/recursive structure, so it maps directly onto a tree-view's row model and avoids -the Unity serialization depth limit for nested types. `Id` is assigned once and never reused, -even after deletion. Groups are purely organizational by default; setting `IncludeInName` -turns nesting into namespacing, prefixing an opted-in group's own name (and its -opted-in ancestors) onto the generated member name of everything inside it. `_ts.Spawner` -under a plain group stays `_ts.Spawner`, but under a group named "Enemies" with -`IncludeInName` set it becomes `_ts.EnemiesSpawner`. Factory groups always prefix -regardless of this toggle; Global groups respect it per-group. Construct groups have no -member name to namespace at all, so the toggle has no effect there. Grouping a construct is -purely organizational. - -```csharp -// A scene object registered as a Global entry named "Spawner", inside a group -// named "Enemies" with IncludeInName set, shows up on the generated root as: -_ts.EnemiesSpawner.SetActive(true); -``` - -`TsGroupedEntry` pairs one registration (`Value`, an arbitrary `UnityEngine.Object`: a -scene object, component, or prefab) with its owning group (`GroupId`, `0` if ungrouped) and -an optional explicit `Name`. A blank `Name` derives a default from the component's type -name, a plain GameObject's own name, or a prefab's name, sanitized into a valid C# -identifier. - -## TsBuiltinConfig: the same shape, library-wide - -`TsBuiltinConfig` is a `ScriptableObject`, not a scene component but a package asset, -holding the same Global/Pool/Factory entry-and-group shape as `TsConfig`, but for -registrations Core itself ships and wants present regardless of what any individual -project configures. It's merged with each project's own `TsConfig` at generate time, so a -library-provided global or pooled prefab shows up in the generated output the same way a -project's own entry would, without every project needing to register it by hand. diff --git a/docs/core/codegen/config/ts-pending-config-edit.md b/docs/core/codegen/config/ts-pending-config-edit.md deleted file mode 100644 index aa1e6b2..0000000 --- a/docs/core/codegen/config/ts-pending-config-edit.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -id: ts-pending-config-edit -title: TsPendingConfigEdit -sidebar_position: 3 ---- - -# TsPendingConfigEdit - -`Tsvrc.Editor.TsPendingConfigEdit` is the batching primitive behind every Apply/Discard -button in the Core editor UI. [`TsWindow`](./ts-window) owns one per `TsConfig` it edits -(plus a second one for the Settings tab's `TsvrcLogger` fields), and -`TsBuiltinConfigInspector` owns one for whichever `TsBuiltinConfig` asset is selected. One -instance tracks edits to exactly one target object. - -## Why edits need batching at all - -Without this, every `SerializedObject.ApplyModifiedProperties()` call, meaning every single -field edit including one keystroke into a name field, would immediately trigger a real -regenerate pass through the `Undo.postprocessModifications` watch in `TsGenerator`. Typing a -ten-character name would fire ten regenerate passes. `TsPendingConfigEdit` suppresses -the `TsGenerator` automatic triggers for the duration of an in-progress edit and only lets the -accumulated changes trigger one real regenerate when you explicitly click Apply. - -## The baseline - -`BeginTracking(target)` rebaselines only when the tracked object's identity actually -changes (a different `TsConfig` found, a different `TsBuiltinConfig` selected), not on every -`OnGUI` call. It snapshots the target twice, for two different purposes: a JSON snapshot -(`EditorJsonUtility.ToJson`) used purely to cheaply detect *whether* anything changed, and a -full object clone (via `EditorUtility.CopySerialized` onto a hidden, same-type instance) -used to actually *restore* the target on Discard. The JSON snapshot alone isn't enough to -discard from: `EditorJsonUtility.FromJsonOverwrite` doesn't reliably round-trip -`UnityEngine.Object` references, a real bug this design was built around fixing. The hidden -clone lives on a `HideAndDontSave` GameObject for a `Component` target (which needs a -GameObject to live on at all) or as a bare `ScriptableObject` instance otherwise. - -## The per-frame contract - -Three calls, in order, once per `OnGUI` pass: - -1. **`BeginFrame()`** — arms suppression proactively, before any edit could happen this - frame. This matters because some UI code (the drag-and-drop reparenting in `TsGroupTreeGUI`) - calls `ApplyModifiedProperties()` itself, mid-draw, ahead of the caller's own outer call, - so suppression has to already be active by then. -2. *(the tab draws its fields, and the caller calls `SerializedObject.ApplyModifiedProperties()` - plus checks `EditorGUI.EndChangeCheck()`)* -3. **`NotifyAppliedToSerializedObject(anyChangesApplied)`** — only re-diffs the target - against the baseline JSON when `anyChangesApplied` is true. Running a full JSON diff on - every single `OnGUI` event, including pure navigation events like scrolling where nothing - changed, measurably degraded scroll smoothness on a config with a non-trivial entry - count, hence the gate. Releasing suppression isn't gated the same way, though: it's keyed - directly off whether pending changes still exist, so a window that's simply open with no - edits ever made doesn't hold suppression forever after its first draw. - -## Apply and Discard - -`Apply()` ends suppression, explicitly schedules exactly one regenerate -(`TsGenerator.ScheduleRerun()`), then rebaselines against the now-applied state, both the -JSON snapshot and the hidden clone. `Discard(so)` does the opposite: it copies the hidden -baseline clone back onto the live target (never touching the network/generator at all), then -calls `so.Update()` so the `SerializedObject` the UI is drawing from reflects the reverted -state immediately. A discarded edit never reaches `ScheduleRerun()`. - -## Cleanup timing - -`Cleanup()` (called from `OnDestroy`, deliberately not `OnDisable`) only releases the hidden -baseline clone and any held suppression scope. It never has data to lose by the time it -runs, since `OnDisable` also fires around an ordinary domain reload, where cleaning up a -pending edit would be wrong because the user hasn't decided anything yet, while `OnDestroy` -only fires once the window or inspector is actually closing for good, by which point the Unity -save-changes dialog has already forced a real Apply or Discard decision. diff --git a/docs/core/codegen/config/ts-window.md b/docs/core/codegen/config/ts-window.md deleted file mode 100644 index 7373308..0000000 --- a/docs/core/codegen/config/ts-window.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -id: ts-window -title: TsWindow -sidebar_position: 2 ---- - -import TsWindowMock from '@site/src/components/TsWindowMock'; - -# TsWindow - -`Tsvrc.Editor.TsWindow` is **Tsvrc > Configure**: the tabbed editor window every -[module](../modules/ts-single-component-module) with a non-null `TabLabel` renders itself -into, plus an always-last "Settings" pseudo-tab. This page covers the window's own behavior: -tab management, the linked-scene picker, status reporting, and the edit-batching contract -every tab's edits go through. See [`TsPendingConfigEdit`](./ts-pending-config-edit) for how -that batching actually works, and each module's own reference page for what a specific -tab's fields mean. - -## Try it - -The window below is live, not a screenshot: every button does what it really does. Mock -data only, nothing here reads from or writes to a real Unity project. - - - -## Tabs - -Tabs come from `TsGenerator.CreateModules()`, filtered to modules with a `TabLabel`, in the -order the generator creates them. The tab list is built once in `OnEnable` and deliberately -not rebuilt every time the underlying config changes: a module instance can hold tab-only UI -state (a group tree's expand/select/search state, a foldout), and rebuilding on every -regenerate would silently reset all of that. Only the tracked `TsConfig` itself is reloaded -on a regenerate; the tab objects persist for the window's lifetime. The selected tab index -survives a domain reload via a `[SerializeField]` field: `EditorWindow` instances are -re-deserialized across a reload, but only serialized fields keep their value across it. - -The Settings tab isn't a real module: it's a pseudo-module (`SettingsTabModule`) appended -last, because its content spans two different data sources (the `LogModule` logging fields, -which live on the scene's `TsvrcLogger`, and the `TsConfig` tree-shaking fields) that don't -belong to any single registered module. - -## Apply / Discard - -Every tab's edits are batched behind an explicit Apply/Discard step rather than triggering a -real regenerate on every single property change. That batching is the entire reason -[`TsPendingConfigEdit`](./ts-pending-config-edit) exists. `TsWindow` participates in the Unity -"unsaved changes" contract (`hasUnsavedChanges`, `SaveChanges`, `DiscardChanges`): it -decorates the window's title/tab and blocks it from closing, including on an editor quit, -until you explicitly apply or discard. `TsWindow` tracks two independent pending-edit sets -at once, the active tab's `TsConfig` edits and the Settings tab's separate `TsvrcLogger` -edits, both folded into one shared "you have unapplied changes" footer and one shared -`hasUnsavedChanges` flag. - -Beyond the window-close path, switching the linked scene (or picking a different scene to -link) also risks discarding an in-progress edit silently. `ResolvePendingChangesBeforeSwitch` -guards that specific action with its own Apply/Cancel/Discard dialog, since -the built-in protection of `hasUnsavedChanges` only covers the window actually closing. - -## Status reporting - -Five independent status boxes render above the tabs on every `OnGUI` pass, each answering a -different question, all backed by a pure, directly-unit-testable `Determine*` method so the -exact wording and triggering condition can be tested without driving real `OnGUI`: - -- **Linked scene** — whether a scene is linked at all, and if so, whether it's currently - open, was deleted outright, or the link itself was lost (real generated content exists on - disk with nothing linked to it, a strong hint `TsLinkedSceneConfig.asset` was deleted). -- **Setup status** — not yet set up, waiting on a pending bootstrap's recompile, in play - mode (regeneration is disabled there), or set up but unlinked. -- **Missing builtin config** — `TsBuiltinConfig.asset` itself is gone (a bad merge or - submodule update can lose this for a whole team at once). -- **Field name collisions** — names dropped from the last regenerate due to a cross-module - naming conflict, naming exactly which ones. -- **Run warnings** — a short summary (capped, with a "see Console" pointer past the cap) of - anything else the last regenerate pass logged. - -A sixth box, the **tree-shaking summary** (what got excluded as unused, and what's in its -one-pass grace period), isn't part of this always-visible group. It only renders inside the -Settings tab's own content, next to the tree-shaking toggle it reports on, drawn as its own -`Info`-level box per condition (this is the feature working as intended, not a problem), so -"gone, bring it back" and "still here for now" read as distinct signals. - -## Initialize Tsvrc / Force Regenerate - -The same button, `TsGenerator.ManualGenerate()`, appears under two labels depending on -state: "Initialize Tsvrc" the first time, "Force Regenerate" after a `TsConfig` already -exists. A first-time setup and a maintenance regenerate are different mental models for the -person clicking it, even though the underlying action is identical. See -[`TsGenerator`](../internals/ts-generator) for what that action actually does. diff --git a/docs/core/codegen/internals/adding-a-codegen-module.md b/docs/core/codegen/internals/adding-a-codegen-module.md deleted file mode 100644 index 93a1690..0000000 --- a/docs/core/codegen/internals/adding-a-codegen-module.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -id: adding-a-codegen-module -title: Adding a new codegen module -sidebar_position: 1 ---- - -# Adding a new codegen module - -A how-to guide for contributors extending the Core generator, not for end users -configuring a world. It assumes you've read [`TsModule`](./ts-module) and -[`TsGenerator`](./ts-generator), and at least a couple of the existing modules under -Codegen > Modules, for example [`LogModule`](../modules/log-module). The pattern below is -drawn directly from how those already work, not a hypothetical design. - -## Decide what your module contributes - -Every module answers three questions independently, and most modules only need to answer -some of them: - -- **Does it generate a file?** Set `FileName` to a non-null string and implement - `GenerateCode()`. A module that only wires data into another module's already-generated - class (rare) leaves `FileName` at its default `null`. -- **Does it need its own Configure tab?** Set `TabLabel`/`TabDescription` and implement - `DrawTab(SerializedObject)`. If your data lives on `TsConfig` as a group tree (like - Globals, Pool, Constructs, Factories), you almost certainly want - [`TsGroupTreeGUI.Draw`](../config/group-tree-and-inspectors) rather than writing - your own tree UI from scratch. -- **Does it need to wire scene references after compile?** Implement `Wire()`. This is - where you resolve the compiled type via `FindRoot()`, find or create whatever scene object - your module owns, and assign serialized fields on it. - -## Read config, generate code, wire the scene, in that order, every pass - -`LoadConfig()` is where you read your config source (a `TsConfig` field, an asset, a scene -scan) and resolve it into whatever in-memory shape `GenerateCode()`/`Wire()` will read from. -Do this work once, in `LoadConfig()`, not lazily inside `GenerateCode()` or `Wire()`. -`TsGenerator` calls every module's `LoadConfig()` before any module's `GenerateCode()`, -specifically so cross-module concerns (field-name collision detection, most importantly) -can look at every module's resolved state before any file gets written. - -`GenerateCode()` should be a pure function of what `LoadConfig()` already resolved: no -further config reads, no scene queries. If you have nothing to generate (an empty entry -list), return `BuildStub(usings, emptyMethodSignatures)` rather than `null`, so the -generated file still declares whatever empty methods other code expects to be able to call -unconditionally. - -`Wire()` runs last, and only once nothing needed writing this pass (see -[`TsGenerator`](./ts-generator) for why). Resolve the compiled root via -`FindRoot()`, look up your field with `TryFindField`, and assign it, then call -`ApplyAndMarkDirty(so, root)` once you're done, not after every individual assignment. - -## Handle a broken compile without wiping real content - -If your module resolves entries from live scene state (rather than, say, a static list), -protect it with [`ApplySnapshotFallback`](./ts-module) exactly the way Global, -Factory, Construct, and Pool do. The scenario this protects against is real: a broken -compile anywhere in the project can null out every scene reference to a component declared -in the broken assembly, making your live resolution pass look like the user deleted -everything. Without the fallback, your next `GenerateCode()` call would silently regenerate -an empty stub and wipe out real, working configuration on the very next domain reload. - -## Support tree-shaking if it's a reasonable fit - -If your entries have a real, checkable "is this actually used" signal in project source -(a member access, a method call), wire it into [`ApplyTreeShaking`](./ts-module) -the way Global and Factory do, rather than hand-rolling your own grace-period bookkeeping. -If your subsystem is a single on/off concern rather than a list of named entries (like Log or -Memory), extend [`TsSingleComponentModule`](../modules/ts-single-component-module) -instead of `TsModule` directly and get the whole thing for free. - -## Report exposed names, and pick a real precedence - -If your module generates a member accessible via `_ts.Name`, report it through -`ExposedFieldNames()` so cross-module collisions get caught before they become duplicate- -member compile errors, and implement `ExcludeFieldNames(names)` to drop the losing side of a -collision cleanly (with a warning explaining the fix, not just silently disappearing). Only -reach for `ReservedFieldNamePrecedence` if your module declares a name unconditionally, -regardless of any user config (`Instance` from `InstanceModule`, `Log`/`Memory` from -`TsSingleComponentModule`). An ordinary config-driven module should use the default precedence (`0`) -and let a real naming conflict resolve the normal way. - -## Watch the right things - -Populate `WatchedAssets()` with any asset path that should trigger a rerun when it changes -(most modules at least watch `BuiltinConfigPath`), and `WatchedComponentTypeNames()` with -any component type name whose *field-level* modifications (not just add/remove) should -trigger a rerun. `PoolModule` is the clearest example, since a `[WirePool]` field being -added to some unrelated behaviour changes the pool's own slot-count math without any pool -config itself changing. - -## Write it up - -Once your module works, give it its own page under Codegen > Modules, following the shape -[`LogModule`](../modules/log-module) and the other pages there already use: what it -generates and why, what's specific to it versus inherited from -`TsModule`/`TsSingleComponentModule`, and any real edge case a careful reviewer would ask -about, not just the happy path. diff --git a/docs/core/codegen/internals/supporting-utilities.md b/docs/core/codegen/internals/supporting-utilities.md deleted file mode 100644 index 6260909..0000000 --- a/docs/core/codegen/internals/supporting-utilities.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -id: supporting-utilities -title: Generator support utilities -sidebar_position: 4 ---- - -# Generator support utilities - -A handful of small internal classes back [`TsGenerator`](./ts-generator) and the codegen -modules. None of these are things you call directly as an end user of Core; they're -documented here for anyone extending the generator itself. - -## ScriptIndex - -Answers "does class X derive from class Y" and "does any script in the project contain this -text" by scanning the raw source text of every `MonoScript`, rather than by reflecting over -compiled types. This matters specifically because it has to keep working **while the -project doesn't currently compile**. Reflection over `Assembly-CSharp` is useless exactly -when a not-yet-generated member breaks the build, which is one of the more common moments a -codegen pass needs to run. It's deliberately a simple regex scan rather than a real parser -(good enough to find a class declaration's immediate base class by simple name), and -namespace-aware so two unrelated classes sharing a short name in different namespaces don't -get confused for each other: an ambiguous match reports "cannot prove derivation" rather -than guessing. Rebuilt fresh at the start of every generation pass, never cached across -passes. - -## TsUsageScanner - -Layered on top of the `ScriptIndex` source scan to answer tree-shaking's real question: "is -this generated member actually used anywhere?" A Global/Log/Memory read has no attribute to -reflect over the way `[WirePool]` does. It's just `_ts.Name`, a bare member access in -arbitrary source text (`IsMemberReferenced`), so this has to pattern-match source rather -than inspect live objects. The generated `CreateName(parent)` call site of a Factory is matched -the same way, via a separate method-call pattern (`IsMethodCallReferenced`). The matching is -deliberately conservative: a false positive (treating something as used when it isn't) only -wastes a few bytes of generated code, but a false negative would silently drop real content, -which is far worse. When genuinely in doubt, it reports "used." - -## ModuleEntrySnapshot - -Persists each module's last successfully resolved entries (name, type, and namespace, -never a live object reference) to a per-module JSON cache. `PoolModule` also stores its last -known-good `TotalSlots` per pool type alongside the entry, since that count comes from the -same kind of live, scene-wide reflection scan as the entry list itself; every other module -leaves it unused. This cache is what -[`TsModule.ApplySnapshotFallback`](./ts-module) reads from when a broken compile makes live -resolution untrustworthy. The scenario this protects against is real and has actually -happened: a world script referencing a not-yet-generated member breaks the whole compile, -which nulls out *every* scene reference to a component declared in that same assembly, -including every genuine Global or Factory entry, making a live resolution pass see zero -entries and, without this fallback, silently regenerate an empty result that wipes out real -configuration on the next domain reload. - -## PackagePaths / TsPaths - -`PackagePaths.Root` resolves the installed package's own root folder -(`Assets/Tsvrc` or `Packages/com.tsvrc.core`, depending on how it was added) using -`[CallerFilePath]`, so nothing else in the generator has to hardcode that path. `TsPaths` is -the single source of truth for everything else path- and identity-related: the generated -output folder, the compiled scaffold class's name and namespace. These are mutable fields -rather than constants specifically so tests can redirect them to scratch locations for the -duration of a test. Production code never changes them itself. - -## TsAssetWatcher / TsDomainReloadHandler - -`TsAssetWatcher` is a Unity `AssetPostprocessor` that schedules a rerun whenever an asset a -module declared via `WatchedAssets()` is imported, deleted, or moved (excluding the case -where that happened as part of a domain reload; `TsDomainReloadHandler` already owns that -path, so the two don't double-trigger). `TsDomainReloadHandler` is what actually calls -`TsGenerator.AfterDomainReload()` after every recompile; it also checks, eagerly and before -anything else, whether a scene is linked but the scaffold file is missing entirely. A -project that lost its generated folder outright (a bad `.gitignore`, an accidental delete) -otherwise just sees a wall of unrelated compile errors with no hint that **Force -Regenerate** is the fix. diff --git a/docs/core/codegen/internals/ts-generator.md b/docs/core/codegen/internals/ts-generator.md deleted file mode 100644 index df421f9..0000000 --- a/docs/core/codegen/internals/ts-generator.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -id: ts-generator -title: TsGenerator -sidebar_position: 3 ---- - -# TsGenerator - -`Tsvrc.Editor.TsGenerator` is the orchestrator that drives every [`TsModule`](./ts-module) -through a full generation pass. It's what actually runs when you click **Force -Regenerate**, when a watched asset changes, or automatically after every recompile. - -## When it runs - -- **Force Regenerate / Initialize Tsvrc** (`ManualGenerate`) — a deliberate click, always - treated as a real developer opportunity for tree-shaking's grace-period accounting. -- **After every domain reload** (`TsDomainReloadHandler`, via `AfterDomainReload`) — the - main automatic trigger; a real recompile is unambiguous developer opportunity too. -- **A watched asset changes** (`TsAssetWatcher`) — any asset path a module declared via - `WatchedAssets()` being imported, deleted, or moved schedules a rerun. A scene hierarchy - change a module cares about, or a property edit on a watched component type, schedules one - too, through the hierarchy-changed and Undo-postprocess hooks in `TsGenerator` rather than - through `TsAssetWatcher` itself. -- **Before a VRChat world build** (`TsBuildCompile`) — see below. - -Every *automatic* trigger is gated by `AutomaticTriggersSuppressed`, which is true while -Unity Test Framework runs tests, whether from the Test Runner window or a `-runTests` -command-line run, while the Editor is entering or in Play Mode, and inside an explicit -`SuppressAutomaticTriggers()` scope. This exists because an -automatic pass reacting to whatever scene happens to be open, a test's own temporary scene -in particular, could otherwise silently regenerate a real project's output down to almost -nothing (see [`TsLinkedScene`](../config/linked-scene) for the deeper reason this is -dangerous). Deliberate, explicit calls a test makes on purpose -(`Run()`/`AfterDomainReload()` directly) are never gated; only the reactive paths that would -otherwise fire unattended are. - -## The bootstrap signal - -A pass with `allowBootstrap: false` (every automatic trigger's default) won't create a -project's scaffold from nothing. It waits until `HasBootstrapSignal()` finds a real reason -this project uses Core (an existing `TsConfig` in the linked scene, an existing compiled -scaffold instance, or *any* non-abstract `Instance` subclass anywhere in the project, unless -marked [`[TsCodegenIgnore]`](../../core-concepts/attributes.md)). Until that signal appears, the -generator just re-arms a hierarchy-changed watch and returns. This is what makes an -unrelated, freshly-opened project safe to have Core installed in without it immediately -scaffolding files nobody asked for. A deliberate **Force Regenerate**/**Initialize Tsvrc** -click passes `allowBootstrap: true` and *is* the signal. - -## One pass, in order - -`RunCore` runs, per pass: rebuild the whole-project [`ScriptIndex`](./supporting-utilities) -fresh (never cached across passes, since a script may have just changed) → check the -bootstrap signal → `LoadConfig()` on every module → collect tree-shaking results → detect -and resolve field-name collisions across modules → collect every module's watched paths → -delete any file a module no longer produces (would otherwise leave a stale partial-class -member behind, a guaranteed compile break, not just clutter) → write every module's -`GenerateCode()` output. - -If any file changed on this pass, the generator stops there: the compiled type on disk is -now stale relative to what was just written, so wiring against it would target the wrong -field set. It schedules the pending-bootstrap/pending-regenerate flags, refreshes the asset -database (triggering a recompile), and lets the *next* pass, driven by that recompile's own -domain-reload trigger, pick up from `AfterFilesStable()` with the now-current compiled type. -Only once nothing needs writing does `Wire()` actually run, scoped to the linked scene's own -compiled scaffold instance so an unrelated instance in some other, additively-loaded scene -never gates it. - -A module whose `AfterFilesStable()` isn't itself idempotent can trigger a bounded self-retry -(`RunCore` recursing on itself, capped at three passes) purely as a safety net against -runaway recursion. Real, well-behaved modules converge in one extra pass, since -`AfterFilesStable()` becomes a no-op once whatever it created already exists. - -## Before a build - -`TsBuildCompile` (a VRChat SDK build callback, ordered to run before the UdonSharp build -pass) forces a generation pass before every scene build, so generated files and scene wiring -can't go stale relative to what's about to ship. It checks `TsLinkedScene.IsConfiguredButNotLoaded` -*before* `HasBootstrapSignal()` specifically because the bootstrap signal's own -any-Instance-subclass-anywhere fallback can't distinguish "the correct scene is open" from -"some unrelated scene is open"; only the linked-scene check can catch that. If nothing has -ever been set up at all, it offers to cancel the build rather than silently shipping a world -where the `_ts` reference of every `TsvrcBehaviour` would be `null` at runtime. - -## Why this exists, briefly - -`TsGenerator` is the concrete mechanism behind the codegen-vs-runtime-reflection split -described in [How Core fits together](../../core-concepts/how-it-fits-together): every module's config is -read once, at edit time, and baked into real generated C#. Nothing about this pipeline runs -in the built world. See that page for the reasoning; this page only covers how the pipeline -itself is sequenced and triggered. diff --git a/docs/core/codegen/internals/ts-module.md b/docs/core/codegen/internals/ts-module.md deleted file mode 100644 index 322a29a..0000000 --- a/docs/core/codegen/internals/ts-module.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -id: ts-module -title: TsModule -sidebar_position: 2 ---- - -# TsModule - -`Tsvrc.Editor.TsModule` is the abstract base contract every codegen module implements. -[`LogModule`](../modules/log-module), [`MemoryModule`](../modules/memory-module), -[`PoolModule`](../modules/pool-module), and the other six modules documented under -Codegen > Modules all extend it. This page is for understanding how the generator pipeline -works and, eventually, for writing a new module yourself; if you're only *using* Core -rather than extending its generator, you can skip it. -See [Adding a codegen module](./adding-a-codegen-module) for a worked example -of implementing one. - -## The call sequence - -`TsGenerator` calls every active module through a fixed sequence each run: `LoadConfig`, -then optionally `ExposedFieldNames`/`ExcludeFieldNames` (conflict detection), then -`GenerateCode`, then `AfterFilesStable`, then `Wire`. Modules must not depend on each -other's in-memory state. The only state safe to share across modules is scene state, read -through `FindRoot`/`TsLinkedScene`, never a module instance's own fields. - -- **`LoadConfig()`** *(abstract)* — reads whatever config source this module cares about. -- **`GenerateCode()`** *(virtual, default `null`)* — returns the C# source fragment this - module contributes to the generated partial class. `FileName` (also virtual, default - `null`) names the file it writes; `null` means the module contributes no file of its own - (for example, a module that only wires data into another module's already-generated - class). -- **`AfterFilesStable()`** *(virtual, default `false`)* — runs once generated files have - settled and compiled. -- **`Wire()`** *(virtual, no-op by default)* — resolves serialized fields on scene objects - against the now-compiled generated type. -- **`WatchedAssets()`** / **`WatchedComponentTypeNames()`** — which asset paths or component - type names, when modified, should trigger a regenerate pass. - -## Field name collision handling - -`ExposedFieldNames()` reports which member names a module's `GenerateCode()` output will -declare; `TsGenerator` cross-checks every module's list after `LoadConfig()` to catch two -modules that would otherwise generate the same member name. `ExcludeFieldNames(names)` is -then called with the actual conflicting set so the module can drop them (and log an error) -before generating real code. `FieldNamePrecedence` (default `0`) is the tie-breaker when two -modules want the same name: the higher-precedence module keeps it, others drop it, and an -exact tie strips the name from every claimant, since a tie at the same precedence is a -genuine, unresolvable collision. `ReservedFieldNamePrecedence` (`int.MaxValue`) marks a name -that's unconditionally present in generated code regardless of any user config, for example -the `Instance` property of `InstanceModule`, so a config entry that happens to auto-derive -the same name is caught as an exclusion instead of silently producing a duplicate-member -compile error. - -## Tree-shaking - -`ApplyTreeShaking` is the shared filter behind `TsConfig.TreeShakeUnused`, used by every -module that supports it (Global, Factory, and Log/Memory via a single-element list) instead -of each reimplementing the same logic. An entry survives if it's referenced anywhere in the -project's own source, or explicitly named in `ForceIncludeNames`. An entry that's neither -isn't excluded immediately: it has to be observed unreferenced across **two separate -counting passes** first (a one-pass grace period), since nothing can reference a -`_ts.Something` member in code before that member has been generated at least once. A -brand-new entry would otherwise look indistinguishable from genuinely dead code. A pass -"counts" only when it represents a real developer opportunity to have added a reference (an -actual recompile or an explicit Force Regenerate/Initialize click); a pass triggered only -by a reactive watcher doesn't advance or reset that grace tracking. - -## Snapshot fallback for a broken compile - -`ApplySnapshotFallback` protects generated output across a transient broken compile: if the -project currently has compile errors and live resolution finds fewer entries than the last -known-good snapshot, the module uses the cached snapshot instead of overwriting real -generated content with a reduced or empty result. A restored, snapshot-sourced entry has no -way to recover an actual scene/prefab object reference from a name alone, so its `Wire()` -step just leaves that field `null` until the next clean compile refreshes the snapshot with -real objects. This protects the generated *code*, not the scene wiring, across the outage. -A separate, always-rising "last known good" count (tracked independently of the -compile-broken snapshot) also warns, without blocking the pass, when a *clean* compile -resolves fewer entries than before, since that's usually a sign of an accidental deletion (a -`TsConfig` object removed from the Hierarchy) rather than a deliberate one. A drop fully -accounted for by this same pass's own tree-shaking exclusions never triggers this warning; -only the remainder of a drop that tree-shaking doesn't explain counts as suspicious. - -## Shared helpers for module authors - -A handful of `protected`/`internal` static helpers exist purely to avoid every module -reimplementing the same logic: `Sanitize`/`SanitizeIdentifier` (arbitrary text → valid C# -identifier, PascalCased per word), `Deduplicate` (append a numeric suffix starting at `2` on -a name collision, matching the convention of OS file-copy dialogs), `BuildGroupPrefix` -(walks a `TsGroup` chain to build a namespacing prefix), `BreakGroupCycles` (defensively -resets a corrupted group hierarchy to root-level rather than looping forever), `ResolveEntries` -(the shared Global/Construct resolution loop: validates each `TsGroupedEntry`, resolves its -type even under a broken compile via `TryResolveObjectType`, and deduplicates the final -name), and `TryFindField`/`ApplyAndMarkDirty` for the `Wire()` step. - -## Tab UI integration - -A module with `TabLabel` non-`null` gets its own tab in **Tsvrc > Configure**, described by -`TabDescription` and drawn by `DrawTab(SerializedObject)`. `DrawTab` returns whether it -committed a change through its own nested `SerializedObject` (for example, drag-and-drop -group reparenting) rather than the caller's. The caller has to fold that into its own -"did anything change" tracking, since a raw `SerializedProperty` assignment never sets -`GUI.changed` on its own. diff --git a/docs/core/codegen/internals/ts-translation-window.md b/docs/core/codegen/internals/ts-translation-window.md deleted file mode 100644 index 3efebd6..0000000 --- a/docs/core/codegen/internals/ts-translation-window.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -id: ts-translation-window -title: Translation window -sidebar_position: 5 ---- - -# Translation window - -**Tsvrc > Translation** (`TsTranslationWindow`) is the authoring surface for the language -files [`TranslationModule`](../modules/translation-module) turns into generated -lookup code. It edits the same [`TsTranslationConfig`](../config/translation-config) -asset the module reads, and offers a one-click **Create Translation Config** if that asset -doesn't exist yet at its expected path. - -## Usage - -Open **Tsvrc > Translation**, click **Create Translation Config** if none exists yet, then -assign one `TextAsset` per language and name any translatable `TextMeshProUGUI` object in the -linked scene `_key_` to match an entry's key across every language file. - -## Editing language files - -Each row is a `TextAsset` slot plus a live preview of that file's `"key"` and `"label"` -fields (parsed once per asset and cached by instance ID, so repainting the window doesn't -re-run the same two regex matches on every frame; the cache is cleared when a file is -swapped out or the project changes). The window's own help text spells out the expected -shape directly: `"key"` (a stable identifier, e.g. `"en"`), `"label"` (the display name, -e.g. `"English"`), and `"entries"`, each entry either a plain string or an object with a -`"label"` (the actual translated text) and an optional `"description"` (translator notes, -never included in the generated build). - -## Scene preview - -Below the language list, the window shows every `TextMeshProUGUI` object in the linked scene -whose name matches the same `_key_` naming pattern and the same linked scene (see -[`TsLinkedScene`](../config/linked-scene)) `TranslationModule` scans at generate -time. Unlike the module's own scan, the count here isn't also filtered down to names that -already have a matching key in a loaded language file. It deliberately counts every -name-pattern match first, then separately flags any of them whose key doesn't appear in -*any* loaded language file. That mismatch would otherwise only surface as a name silently -failing to translate at runtime, with nothing in the console to point at why. - -This target count is invalidated (not eagerly recomputed) on every scene hierarchy change, -so it stays current as you rename or add TMP objects without re-scanning the whole scene on -every single repaint. diff --git a/docs/core/codegen/modules/construct-module.md b/docs/core/codegen/modules/construct-module.md deleted file mode 100644 index e3775f0..0000000 --- a/docs/core/codegen/modules/construct-module.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -id: construct-module -title: ConstructModule -sidebar_position: 7 ---- - -# ConstructModule - -`Tsvrc.Editor.ConstructModule` is the generator behind the [tutorial](../../first-behaviour)'s -onboarding step. Registering a `TsvrcBehaviour` on the Configure window's **Constructs** tab -is what this module turns into a private field and a startup `TsConstruct` call. It's the -module directly responsible for a registered behaviour's `TsStart()` override running at -all. See [Reach a scene object from anywhere, or guarantee it -initializes](../../how-to/reaching-a-scene-object) for a task-oriented walkthrough. - -## Usage - -Register a `TsvrcBehaviour` on the Configure window's Constructs tab. That's the whole -configuration step: there's no name to set, since a construct never becomes a member on -`_ts`. - -```csharp -public class HelloWorld : TsBehaviour -{ - protected override void TsStart() - { - LogInfo("HelloWorld constructed."); - } -} -``` - -Registering `HelloWorld` here is what makes `TsStart` run at all. If another behaviour -needs a direct reference to it afterward, wire it the ordinary Unity way (a -`[SerializeField]` field assigned in the Inspector), or register the object as a -[Global](./global-module) instead if you also want it reachable as `_ts.Name`. - -## What it generates - -Each construct entry becomes a private backing field -(`[HideInInspector][SerializeField] private {Type} _construct{Name};`, `{Name}` derived from -the entry's type and never user-facing) plus, inside `_TsConstructStart()`, a -`{FieldName}.TsConstruct(this);` call. Nothing else: no public accessor, no member name to -configure, no group-based namespacing. Registering a construct under a group in the -Configure window's tree view is purely organizational. - -## Naming and requirements - -A construct must be a component and must be a `TsvrcBehaviour`. `EntryPolicy` enforces both -(`RequireComponent`/`RequireTsvrcBehaviour`), unlike Global, which accepts any scene object. -Because the field is never exposed, its name is always derived from the component's type -(disambiguated by `ResolveEntries`' own suffix dedup on a collision), never from an explicit -entry name. There isn't one to set. - -## Construct vs. Global - -Both modules can initialize a `TsvrcBehaviour`: `GlobalModule` also calls `TsConstruct` when -a Global entry's type happens to be one. The difference is what each is actually for. - -- **Construct** guarantees initialization, a defined build order and a `TsStart` call, and - stops there. The reference stays private, so it never participates in `_ts.Name` collision - detection with Global, Instance, or any other module. -- **Global** guarantees a name, `_ts.Name`, reachable from anywhere, for any scene object - whether or not it's a `TsvrcBehaviour`. Construction only happens as a side effect, when - the registered type needs it so the reference isn't left uninitialized. - -Register something as a Construct when you only need it initialized. Register it as a -Global when you need to reach it by name from other behaviours. Register it as both if you -need both: the two no longer collide, since only Global ever claims a name. diff --git a/docs/core/codegen/modules/factory-module.md b/docs/core/codegen/modules/factory-module.md deleted file mode 100644 index 525d26b..0000000 --- a/docs/core/codegen/modules/factory-module.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -id: factory-module -title: FactoryModule -sidebar_position: 8 ---- - -# FactoryModule - -`Tsvrc.Editor.FactoryModule` generates a `Create{Name}(Transform parent)` method per -registered prefab, for on-demand, **non-networked** runtime instantiation. -`TsConfig.FactoryEntries`/`TsBuiltinConfig.FactoryEntries` register the prefabs; builtin -entries are resolved first so a name collision between a builtin and a project's own factory -always suffixes the project's, never the builtin's. See [Spawn a local, non-networked -object on demand](../../how-to/spawning-a-local-object) for a task-oriented walkthrough. - -## Usage - -Register a prefab on the Configure window's Factory tab, then spawn instances by calling the -generated method from any behaviour: - -```csharp -var vfx = _ts.CreateHitSpark(transform); -``` - -Reach for this only for local, non-networked objects (see below): a projectile or one-off -UI popup, not anything other players need to see. - -## Naming always includes the full group chain - -Unlike Global, where `IncludeInName` makes group-based namespacing an opt-in per group (and -Construct, which has no generated name to namespace at all), a Factory entry's generated -method name is **always** prefixed by its full group ancestor chain. A prefab named "Bolt" -inside a group "Enemies" nested inside "Boss" becomes `CreateEnemiesBossBolt(parent)`, -unconditionally. There's no toggle to opt out, since the -whole point of Factory grouping is organizing what would otherwise be a large flat method -namespace. - -The same prefab registered under two differently-named groups (for example, both an -"Enemies" group and a "Traps" group spawning the same projectile prefab) is a legitimate, -common case, not a mistake. Unlike the Pool duplicate-reference detection, `FactoryModule` -deliberately does *not* flag a prefab appearing more than once across different -registrations. - -## Generated method shape - -```csharp -public {Type} Create{Name}(Transform parent) -{ - var go = (GameObject)Instantiate(_factory{Name}, parent); - if (go == null) return null; - go.SetActive(true); - // for a TsvrcBehaviour prefab: - var instance = go.GetComponent<{Type}>(); - if (instance != null) instance.TsConstruct(this); - return instance; - // for a plain GameObject prefab, returns go directly instead - // for any other component type, returns go.GetComponent<{Type}>() directly, uncostructed -} -``` - -The instantiation source (`_factory{Name}`) is itself a **pre-instantiated, inactive** -instance under a `"Factories"` scene child, not the original prefab asset. `Wire()` creates -one inactive instance per registered factory once, at wire time, and `Create{Name}` clones -*that* instance at call time via `Instantiate`, rather than instantiating the original -prefab asset directly on every call. - -## No networking, by design - -The Configure window's own tab description states this plainly: an object created through a -Factory method never receives a VRChat network ID and can't send or receive network events. -Use [`PoolModule`](./pool-module) instead for anything that needs to participate in -networked gameplay. Factory exists specifically for cheap, purely local, on-demand -instantiation (VFX, local UI popups) where networking would be unnecessary overhead. diff --git a/docs/core/codegen/modules/global-module.md b/docs/core/codegen/modules/global-module.md deleted file mode 100644 index 3840dab..0000000 --- a/docs/core/codegen/modules/global-module.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -id: global-module -title: GlobalModule -sidebar_position: 4 ---- - -# GlobalModule - -`Tsvrc.Editor.GlobalModule` generates one named field per `_ts`-exposed scene object. -`TsConfig.GlobalEntries` and `TsBuiltinConfig.GlobalEntries` are merged into a single set, -scene entries resolved first so they keep an unsuffixed name on a collision with a builtin. -Naming is the point of a Global: it accepts any scene object, not only a `TsvrcBehaviour`, -which is what sets it apart from [Construct](./construct-module) (initialization only, no -name at all). See that page's "Construct vs. Global" section for the full comparison, and -[Reach a scene object from anywhere, or guarantee it -initializes](../../how-to/reaching-a-scene-object) for a task-oriented walkthrough of both. - -## Usage - -Register a scene object as a Global on the Configure window's Globals tab, then reach it -from any behaviour by the generated field name: - -```csharp -_ts.ScoreboardAnimator.SetTrigger("Refresh"); -``` - -## Naming - -An entry's generated member name is its explicit `Name` if set, otherwise derived by -`DeriveName`: a plain `GameObject` reference is named after the GameObject itself (the -literal type name `"GameObject"` would be useless and collide across every ungrouped plain -GameObject entry), an `Animator` reference is named `{GameObjectName}Animator`, and anything -else uses its component type name directly. A group with `IncludeInName` set prefixes the -final name with its (and its opted-in ancestors) own name, exactly as described on -[`TsConfig`](../config/ts-config). - -## Generated shape - -Each entry becomes a `[HideInInspector][SerializeField] public {Type} {Name};` field plus, -inside `_TsGlobalStart()`, a `{Name}.TsConstruct(this);` call, but only for entries whose -type is actually a `TsvrcBehaviour`. A plain `GameObject` or arbitrary `Component` reference -is exposed without ever being constructed, since construction only makes sense for -`TsvrcBehaviour`s. - -## Tree-shaking and the snapshot fallback - -Globals participate fully in `TreeShakeUnused` (via `TsUsageScanner.IsMemberReferenced`, -checking for `_ts.Name` in project source) and in `ApplySnapshotFallback`. See -[`TsModule`](../internals/ts-module) for the shared mechanics behind both. This -module is the primary example the snapshot fallback exists for: a broken compile nulls out -live scene references to any component declared in the broken assembly, which is exactly -what a real Global entry usually is. - -## Collision handling - -`ExcludeFieldNames` drops any Global entry whose name lost a cross-module collision, most -commonly two Global entries independently deriving the same name (two plain GameObjects -both named "Manager", say), or a Global entry that happens to auto-derive a reserved name -like `Instance` (see the reserved-name precedence in [`InstanceModule`](./instance-module)). It -logs a warning naming the fix: give one of the conflicting entries a distinct explicit -`Name`. A Construct entry never causes this, since a construct's field is always private and -never claims a name at all. diff --git a/docs/core/codegen/modules/instance-module.md b/docs/core/codegen/modules/instance-module.md deleted file mode 100644 index 1496f45..0000000 --- a/docs/core/codegen/modules/instance-module.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -id: instance-module -title: InstanceModule -sidebar_position: 5 ---- - -# InstanceModule - -`Tsvrc.Editor.InstanceModule` is what finds, creates, and heals a project's single -[`Instance`](../../core-concepts/instance) subclass, the type you'd otherwise need to -hand-wire onto the generated root yourself. There's no manual configuration for this one: -the module scans every loaded assembly for a non-abstract `Instance` subclass and fully owns -a child object named `"Instance"` under the scaffold root, self-recovering without any user -action needed. - -## Detecting the one real subclass - -`DetectInstanceType` reflects across every loaded assembly, filters out anything marked -[`[TsCodegenIgnore]`](../../core-concepts/attributes.md) (test doubles, most commonly), and -deduplicates by full type name. The Unity `AppDomain` can carry stale duplicate copies of the -same assembly across successive recompiles, which would otherwise make one real subclass -look ambiguous just because it was seen twice. Zero candidates or exactly one are both -unambiguous outcomes; more than one logs an error and makes `Wire()` leave whatever's -currently wired untouched entirely, since destroying a working setup because a second, -possibly-transient subclass momentarily appeared would be worse than doing nothing. - -## Surviving a broken compile - -The generated field and property (`_instance` / `public override Instance Instance => -_instance;`) are always declared as the plain `Instance` base type. The output of `GenerateCode()` -never depends on which concrete subclass was detected, so a broken compile can't corrupt the -generated *code*. What a broken compile *can* corrupt is the live-reflection -detection in `Wire()`: if the AppDomain scan finds zero candidates, but the independent, -source-text-based `ScriptIndex` scan confirms exactly one real `Instance` subclass genuinely exists in -project source, that almost always means the subclass itself just failed to compile along -with everything else. In that case (`_knownViaScriptIndexOnly`), `Wire()` deliberately does -nothing rather than destroying the real, working `"Instance"` child object and nulling the -scene field. There's no live type to re-wire it with anyway, so leaving the existing scene -state alone is the only safe option. - -## Self-healing the scene object - -On a clean detection, `Wire()` creates the `"Instance"` child if it doesn't exist, or -recreates its component if the existing one is the wrong type (renamed/retyped) or its -UdonSharp program asset was deleted. `UdonSharpUndo.DestroyImmediate` is required for that -teardown rather than a plain destroy, since an UdonSharp component carries a hidden backing -`UdonBehaviour` a plain destroy would orphan. This destruction is narrowly scoped: it only -ever removes a component that's either exactly the currently-detected type or some other -stale `Instance` subclass, never every `UdonSharpBehaviour` on that child indiscriminately, -so a developer's own unrelated script hand-attached to the same GameObject survives an -`Instance` retype untouched. - -## Reserved name - -`Instance` is reported via `ExposedFieldNames()` at `ReservedFieldNamePrecedence` -unconditionally, so a Global entry that happens to auto-derive the exact name `"Instance"` -(for example, referencing a plain GameObject literally named that) is caught by collision -detection and excluded, rather than silently producing a duplicate-member compile -error. diff --git a/docs/core/codegen/modules/log-module.md b/docs/core/codegen/modules/log-module.md deleted file mode 100644 index 76e46aa..0000000 --- a/docs/core/codegen/modules/log-module.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -id: log-module -title: LogModule -sidebar_position: 2 ---- - -# LogModule - -`Tsvrc.Editor.LogModule` generates the `_log` field, the `Log` property override, and the -`_TsLogStart()` startup call that wire a scene [`TsvrcLogger`](../../utilities/tsvrc-logger) -into the generated root. It's a thin subclass of -[`TsSingleComponentModule`](./ts-single-component-module), which does essentially all the -real work. See that page for the shared mechanics (usage detection, self-healing scene -object, tree-shaking). - -## Usage - -A script never touches the generated `_log` field directly: call the wrapper methods -`TsvrcBehaviour` already gives every behaviour: - -```csharp -LogInfo("Round started"); -LogWarning("Slot already occupied, skipping"); -``` - -## What's specific to LogModule - -- **Extra usage detection.** A script rarely writes `_ts.Log` directly: it calls - `TsvrcBehaviour.LogInfo`/`LogWarning`/`LogError`, which reach the logger indirectly. Those - wrapper calls never textually mention `_ts.Log`, so the base member-access check in - `TsSingleComponentModule` alone would miss the single most common way logging actually gets - used. `LogModule` reports those three method names as additional usage signatures so - tree-shaking doesn't wrongly conclude an actively-used logger is dead. -- **No standalone Configure tab.** Logging settings are rendered as a section inside the - Settings tab rather than getting their own top-level tab. `FindLogger`, - `DetermineNotFoundMessage`, and `DrawFields` exist specifically to let that host tab own - the `TsvrcLogger` component's `SerializedObject` lifecycle and batch its edits through the - same Apply/Discard flow every other tab uses, rather than `LogModule` managing its own. diff --git a/docs/core/codegen/modules/memory-module.md b/docs/core/codegen/modules/memory-module.md deleted file mode 100644 index 2284aa8..0000000 --- a/docs/core/codegen/modules/memory-module.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -id: memory-module -title: MemoryModule -sidebar_position: 3 ---- - -# MemoryModule - -`Tsvrc.Editor.MemoryModule` generates the `_memory` field, the `Memory` property override, -and the `_TsMemoryStart()` startup call that wire a scene -[`TsvrcMemory`](../../networking-data/tsvrc-memory) into the generated root. It's a direct -subclass of [`TsSingleComponentModule`](./ts-single-component-module) with no additional -behavior of its own: every mechanic (self-healing scene object, tree-shaking, usage -detection via plain `_ts.Memory` member access) is exactly what that shared base implements. -Unlike [`LogModule`](./log-module), there's no indirect-access wrapper equivalent to -`LogInfo`/`LogWarning`/`LogError` to account for, so `MemoryModule` doesn't override -`AdditionalUsageMethodNames`. diff --git a/docs/core/codegen/modules/pool-module.md b/docs/core/codegen/modules/pool-module.md deleted file mode 100644 index 8ec2574..0000000 --- a/docs/core/codegen/modules/pool-module.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -id: pool-module -title: PoolModule -sidebar_position: 6 ---- - -# PoolModule - -`Tsvrc.Editor.PoolModule` is the generator behind -[`WirePoolAttribute`](../../core-concepts/attributes.md): it decides how many instances of -each pooled prefab a project actually needs, generates one serialized slot field per -instance, and instantiates and wires them all under a `"Pool"` child at wire time. This is -the densest of the nine modules `TsGenerator.CreateModules()` registers: the slot-count math -is a real dependency graph, not a flat per-type count. - -## Usage - -Register the prefab's type as a pool entry (Configure window, Pools tab), then declare a -field for it wherever an instance is needed: - -```csharp -[WirePool][SerializeField] private RoundTimer _roundTimer; -``` - -`Wire()` fills `_roundTimer` in with one of the generated slot instances, nothing else to -call. A pooled type that itself needs another pooled type follows the same pattern one level -down: put a `[WirePool]` field on the pooled behaviour itself, and the dependency-graph math -above accounts for it automatically. - -## Registering a pool type - -`TsConfig.PoolEntries`/`TsBuiltinConfig.PoolEntries` register which `UdonSharpBehaviour` -prefabs are poolable at all. Registration alone creates zero slots: a type with no -`[WirePool]` field anywhere referencing it resolves to `TotalSlots == 0` and is silently -skipped in generated output. Slots exist only because something asked for them. - -## How many slots: a dependency graph, not a flat count - -A `[WirePool]` field can appear two places: on an ordinary scene behaviour (an **external** -reference, "give me one instance of this pooled type"), or on *another pooled type itself* -(an **internal** dependency, "each instance of pool type P needs its own instance of pool -type Q"). The total slot count for type `T` is: - -``` -totalSlots(T) = externalCount(T) + Σ_P (fields-in-P-referencing-T) × totalSlots(P) -``` - -computed via a topological walk (`ComputeForType`, memoized, cycle-detected) so a parent -pool type's own slot count is always resolved before a child dependency's count that depends -on it. A genuine circular dependency between pool types (P needs Q, Q needs P) is detected -and logs an error, excluding the offending type from generation rather than recursing -forever. - -Every `[WirePool]` field whose type was never registered as a pool entry logs a warning -(deduplicated per declaring-type-plus-field, so a scene with many instances of the same -behaviour only logs once). Without it, that field would just stay `null` forever at runtime -with no indication why, disconnecting the symptom from a forgotten registration. - -## Generated shape and wiring - -Each slot becomes `[HideInInspector][SerializeField] private {Type} _pool_{Type}_{index};`, -and `_TsPoolStart()` calls `TsConstruct(this)` on every slot whose type is a -`TsvrcBehaviour`. At wire time, `Wire()` instantiates every slot under a `"Pool"` child -(created lazily, only once a slot actually needs it), assigns each instance to its own -scaffold field, then makes a second pass to assign every `[WirePool]` field across the -scene, including internal dependencies inside other pool instances themselves, to its -matching freshly-created slot. A slot/target-count mismatch (more or fewer `[WirePool]` -targets than generated slots) is a warning, not a hard failure, since either mismatch -usually self-heals on the very next pass once the scene or field declarations catch up. - -## Wiring is skipped, not partially applied, on a broken compile - -Unlike Global, Factory, and Construct, none of which destroy existing scene state on empty -input, `PoolModule.Wire()` has real destructive potential: an empty-looking `_poolEntries` -would otherwise tear down a genuinely populated `"Pool"` container. Because `TotalSlots` -itself comes from a live, scene-wide reflection scan (`ScanExternalRefs`/`ScanInternalDeps`) -that's just as fragile to a broken compile as any other live scan, a pass that had to fall -back to the cached snapshot (`_usedSnapshotFallback`) makes `Wire()` do nothing at all, -leaving whatever is already wired in the scene completely alone until a clean compile -restores a trustworthy live count. - -## Already-wired detection - -Before tearing anything down, `Wire()` checks `IsPoolAlreadyWired`: matching slot count, -matching prefab source per slot (via `PrefabUtility.GetCorrespondingObjectFromSource`), and -matching field assignments, and skips the whole rebuild if everything already matches. This -avoids destroying and recreating every pool instance (losing any in-scene state on them) on -a pass where nothing about the pool configuration actually changed. diff --git a/docs/core/codegen/modules/scaffold-module.md b/docs/core/codegen/modules/scaffold-module.md deleted file mode 100644 index 3bb23cc..0000000 --- a/docs/core/codegen/modules/scaffold-module.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -id: scaffold-module -title: ScaffoldModule -sidebar_position: 9 ---- - -# ScaffoldModule - -`Tsvrc.Editor.ScaffoldModule` generates and owns `TsGenerated.cs`, the project-specific -concrete subclass of [`TsRoot`](../../core-concepts/ts-root) every other module's generated -fragment extends via the `partial class` mechanism. It always writes first and must compile -before any other module's `Wire()` pass can locate the root object, since every other module -finds the scene root through `ScaffoldModule.FindCompiledType()`. - -## What it generates - -The scaffold file declares `public partial class TsGenerated : TsRoot`, a `Start()` method -that calls every subsystem's generated `_Ts*Start()` method in a fixed order -(`_TsLogStart`, `_TsMemoryStart`, `_TsGlobalStart`, `_TsPoolStart`, `_TsConstructStart`, -`_TsInstanceStart`), and one generated shadow class per framework type carrying -[`[TsWorldExtensionPoint]`](../../core-concepts/attributes.md). This is the mechanism that -produces `TsBehaviour`, `TsInstance`, and every other shadow class your own scripts actually -extend, discovered entirely by reflecting over that attribute rather than a hardcoded list. - -## The self-healing scene object - -`AfterFilesStable()` ensures the compiled scaffold type's own `UdonSharpProgramAsset` -exists, creates or repairs the scene root object carrying it -(`EnsureRootSceneObject`), and creates the child [`TsConfig`](../config/ts-config) -object (tagged `EditorOnly` so it's stripped from the actual VRChat build) if it's missing. -Finding more than one instance of the compiled type logs a warning naming exactly which one -survives and which are destroyed, so a puzzled "where did my duplicate's settings go" -moment (say, after a Ctrl+D) has a trail to follow in the console, rather than silently -picking one. - -## Auto-linking the scene - -The very first successful bootstrap in a project auto-links -[`TsLinkedScene`](../config/linked-scene) to the scene it just scaffolded, rather than -leaving that corruption-safety net an indefinitely manual opt-in. It's a no-op once anything -is already linked, including a second bootstrap attempt within the same pass, since once a -scene is linked, the generator's own "linked scene not loaded" guard refuses to touch any -other scene at all, so a second scene can never silently grow a competing scaffold of its -own. - -## Deterministic program asset field order - -`NormalizeProgramAsset` sorts the internal field-definition dictionary of an -`UdonSharpProgramAsset` into a stable order after every pass. The Unity/UdonSharp serialization of that -dictionary isn't guaranteed to stay in the same order across compilations, which without -this normalization would produce a spurious file diff on every single domain reload even -when nothing about the actual fields changed. That's noisy for version control and confusing -for anyone trying to tell whether a regenerate actually changed anything. diff --git a/docs/core/codegen/modules/translation-module.md b/docs/core/codegen/modules/translation-module.md deleted file mode 100644 index 83da748..0000000 --- a/docs/core/codegen/modules/translation-module.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -id: translation-module -title: TranslationModule -sidebar_position: 10 ---- - -# TranslationModule - -`Tsvrc.Editor.TranslationModule` turns the JSON language files registered in -[`TsTranslationConfig`](../config/translation-config) into generated `Language` -enum values, a `SetLanguage`/`Translate` API, and the batched text-application logic that -actually updates `TextMeshProUGUI` targets in the scene. See [Add another language and -switch at runtime](../../how-to/adding-a-language) for a task-oriented walkthrough. - -## Usage - -Name a `TextMeshProUGUI` object `_greeting_`, give a language file a matching `"_greeting_"` -entry, and it updates automatically on every language switch, nothing to wire by hand. From -code, switch languages and pull a translation directly: - -```csharp -_ts.SetLanguage(Language.French); -_ts.LobbyStatusText.text = _ts.Translate("_players_remaining_", remaining.ToString()); -``` - -## Language file format - -Each language file is a JSON object with `"key"` (a stable identifier for the language, -independent of its display label), `"label"` (the human-readable name used to derive the -generated `Language` enum member), and `"entries"` (a flat map of translation key → either a -plain string or an object with its own `"label"` field). A file missing any of the three -top-level fields is rejected with a logged error naming which field is missing, and -contributes nothing to that pass's generated output rather than partially generating with -missing data. - -## How translation targets are discovered - -A `TextMeshProUGUI` component becomes a translation target purely by its **GameObject's -name** matching a specific pattern, a single underscore on each side, such as `_greeting_`, -*and* that exact name (underscores included) appearing as a key in at least one loaded -language file's `entries`. There's no component-level marker or attribute: name -the text object `_greeting_`, give a language file an `"_greeting_"` entry, and it's picked -up automatically. Re-scanned whenever the scene hierarchy changes or generated files settle, -so renaming a text object in or out of the naming pattern picks up or drops it as a target -on the next pass with no manual re-registration needed. - -## Generated API - -- **`SetLanguage(Language lang)`** — switches the active key/value arrays and immediately - starts a batched re-application pass over every translation target, then notifies every - listener registered via `SubscribeLanguageChanged`. -- **`SubscribeLanguageChanged(UdonSharpBehaviour listener, string callback)`** — registers - `listener` to receive `SendCustomEvent(callback)` on every future `SetLanguage` call, its - own small generated pub/sub separate from `TsSubscribe`/ - `TsEmit` in the base `TsvrcBehaviour`. Subscribing the same listener/callback pair twice is a no-op rather than a - duplicate delivery. -- **`Translate(string key)`** / **`Translate(string key, string param)`** — linear-scans the - active language's keys for an exact match, returning the untranslated key itself as a - fallback when nothing matches (so a missing translation degrades to showing the raw key - rather than an empty string or an exception) The `param` overload additionally substitutes - a `{value}` placeholder in the matched string. -- **`_TsApplyTranslationBatch()`** — applies translated text to scene targets in fixed-size - batches (20 per frame) via `SendCustomEventDelayedFrames`, rather than all at once, so - switching languages with many on-screen text elements doesn't spike a single frame. - -## Generated code changes when targets do, not just when language files do - -`AfterFilesStable`/`OnSceneHierarchyChanged` both re-scan for matching `TextMeshProUGUI` -targets and compare against the last known set (`SyncEffectiveKeys`). A scene edit that adds -or renames a matching text object triggers a regenerate on its own, independent of whether -any language file itself changed, since the `_translationTargets` array in `Wire()` needs to -include it. diff --git a/docs/core/codegen/modules/ts-single-component-module.md b/docs/core/codegen/modules/ts-single-component-module.md deleted file mode 100644 index db01455..0000000 --- a/docs/core/codegen/modules/ts-single-component-module.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -id: ts-single-component-module -title: TsSingleComponentModule -sidebar_position: 1 ---- - -# TsSingleComponentModule - -`Tsvrc.Editor.TsSingleComponentModule` is the shared abstract base behind -[`LogModule`](./log-module) and [`MemoryModule`](./memory-module). Both generate exactly -one `[ReadOnly][SerializeField]` field, backed by exactly one library-internal singleton -component that the module itself creates and heals in the scene. Rather than duplicating -identical `GenerateCode`/`AfterFilesStable`/`Wire`/`OnSceneHierarchyChanged` logic twice, -this class implements all of it once, parameterized by seven abstract members a subclass -supplies: `ComponentType`, `FieldName`, `PublicPropertyName`, `StartMethodName`, -`ChildGameObjectName`, `ScriptPath`, `AssetPath`, and `ModuleTag`. - -## Usage-gated, not existence-gated - -`TsRoot.Log`/`TsRoot.Memory` are declared `virtual ... => null`, not `abstract`, so a -project that never uses logging or memory compiles perfectly fine without either field ever -being generated at all. Usage (tracked via the shared `ApplyTreeShaking` mechanism, treating -this single subsystem as a one-element list) gates exactly two things: whether -`GenerateCode()` emits the real field/property/start-method or a stub, and whether the -backing scene child object exists at all. A caller reading `_ts.Log` or `_ts.Memory` while -genuinely unused simply gets the `null` default from `TsRoot`. There's no special-casing needed -elsewhere in the framework for "this subsystem happens to be turned off." - -`IsUsed` is exposed as a `protected` property specifically so the `LogModule` Settings-tab -integration can tell "never generated yet, click Force Regenerate" apart from "deliberately -tree-shaken away, won't reappear until referenced or force-included." Without it, the tab's -guidance would be actively misleading once tree-shaking legitimately turns this subsystem -off. - -## Self-healing, but never destructive to the shared package asset - -`AfterFilesStable()` always calls `ScaffoldModule.EnsureUdonSharpProgramAsset` for -the script/asset pair of `ComponentType`, regardless of current usage. Those are permanent -package resources (`TsvrcLogger.cs`/`.asset`, `TsvrcMemory.cs`/`.asset`), never created or -deleted by this module, only healed if something about their linkage drifted. What usage -*does* control is the scene-local child object: when unused, an existing child under the -scaffold root is torn down (mirroring how `FactoryModule` empties its own container); when -used, `ScaffoldModule.EnsureChildSceneObject` creates or repairs it. - -`Wire()` skips entirely while unused. There's no field on the compiled type to wire in that -state (`GenerateCode()` omitted it), and attempting to find it would trigger the shared -"force compile to regenerate" warning every single pass for a field that's deliberately, -permanently absent rather than merely stale. diff --git a/docs/core/core-concepts/attributes.md b/docs/core/core-concepts/attributes.md deleted file mode 100644 index 21dacdc..0000000 --- a/docs/core/core-concepts/attributes.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -id: core-attributes -title: Framework attributes -sidebar_position: 6 ---- - -# Framework attributes - -Reference for the three plain marker attributes the Core codegen reads by reflection at -edit time. None of them do anything at runtime themselves. They exist so the generator -can find and validate things without hardcoding a list of types. - -These attributes tag things across the whole framework, not just Core concepts, so a -few names below (a codegen module, a table of runtime classes) won't be familiar yet if -you're reading this section in order. That's expected: treat this page as one you come -back to once you've reached those pages, not one that assumes you already have. - -## WirePoolAttribute - -Put `[WirePool]` on a field to declare that it should be filled from a pool rather than -assigned by hand: - -```csharp -[WirePool] -public MyPooledBehaviour slot; - -[WirePool("used for enemy spawns")] -public MyPooledBehaviour describedSlot; -``` - -The optional constructor argument is a free-text description of what the pool is for. -Nothing currently reads it back: not the Configure window, not codegen. Today it's -documentation for whoever reads the field declaration, not something surfaced anywhere -in the UI. [`PoolModule`](../codegen/modules/pool-module) (one of the codegen -modules covered later, under Codegen > Modules) checks every `[WirePool]` field's -type against its own configuration and -validates the pairing at generation time, not compile time, so a mismatched or -unregistered pool type surfaces as a codegen warning, not a C# compiler error. See that -module's own reference page for exactly what gets checked. If the pooled type is a -`TsvrcBehaviour` subclass, Core calls `TsConstruct` on each pool slot at scene start; -for any other type, the field is just wired to a reference with no construction step. - -A `[WirePool]` field is read-only in the inspector: `WirePoolAttributeDrawer` disables -the GUI control while drawing it, the same technique -[`ReadOnlyAttribute`](../utilities/read-only-attribute) uses elsewhere. This is a -display-only restriction. It stops accidental edits in the Inspector, not a runtime -enforcement: the generator is what actually owns the field's value. - -## TsCodegenIgnoreAttribute - -Put `[TsCodegenIgnore]` on a class to exclude it from the generator's automatic type -scans, even though it would otherwise match one. The generator uses reflection to find -candidate types (for example, `Instance` subclasses when looking for your project's -scaffold), and those scans can't distinguish "this happens to be an `Instance` subclass" -from "this is the one real scaffold type." A test double that subclasses a framework -type for its own purposes is the common case that needs excluding. Tagging it means the -type is never mistaken for a genuine scaffold candidate and never gets an unwanted, -failing wiring attempt. - -It carries no members and does nothing at runtime. It exists purely as a marker codegen -checks for. - -```csharp -// A test double the generator would otherwise mistake for a real scaffold. -[TsCodegenIgnore] -public class FakeInstanceForTests : Instance -{ -} -``` - -## TsWorldExtensionPointAttribute - -Put `[TsWorldExtensionPoint("GeneratedName")]` on a framework base class to mark it as -one world scripts are meant to subclass directly, and to name the generated shadow class -that [`ScaffoldModule`](../codegen/modules/scaffold-module) (the codegen module you -already met in [How Core fits together](./how-it-fits-together)) writes for it. See -that page again for why the shadow class exists at all. In short, it -retypes the inherited `_ts` reference to your project's own concrete generated root, so -your code gets it fully typed with no cast. - -You don't write this attribute yourself day to day: it's already on the framework -classes in the table below. What you actually write is a subclass of the generated -shadow it produces: - -```csharp -public class GameManager : TsBehaviour // generated shadow of TsvrcBehaviour -{ -} -``` - -`Inherited` is `false` on this attribute deliberately: tagging a base class must not -implicitly tag its own subclasses within the framework. -[`TsvrcMemory`](../networking-data/tsvrc-memory) and -[`TsvrcLogger`](../utilities/tsvrc-logger) both extend `TsvrcBehaviour` (which carries -this attribute) without inheriting the tag themselves. Each extension point opts in on -its own class, individually. - -As of this writing, these are the framework classes tagged with this attribute and the -shadow name each one generates. Each links to its own reference page; follow one if the -name isn't familiar yet: - -| Framework class | Generated shadow | -|---|---| -| [`TsvrcBehaviour`](./tsvrc-behaviour) | `TsBehaviour` | -| [`Instance`](./instance) | `TsInstance` | -| [`Process`](./process) | `TsProcess` | -| [`TsvrcTimer`](../networking-data/tsvrc-timer) | `TsTimer` | -| [`TsvrcLogger`](../utilities/tsvrc-logger) | `TsLogger` | -| [`TsvrcMemory`](../networking-data/tsvrc-memory) | `TsMemory` | -| [`PlayerTracker`](../players-tracking/player-tracker) | `TsPlayerTracker` | -| [`AutoPlayerTracker`](../players-tracking/auto-player-tracker) | `TsAutoPlayerTracker` | -| [`ReadyCheckProcess`](../players-tracking/ready-check-process) | `TsReadyCheckProcess` | -| [`DataTransferer`](../networking-data/data-transfer/data-transferer) | `TsDataTransferer` | -| [`HeadClipGuard`](../players-tracking/head-clip-guard) | `TsHeadClipGuard` | -| [`StateManager`](../game-flow/state-manager) | `TsStateManager` | -| [`TsvrcList`](../ui-components/list/tsvrc-list) | `TsList` | -| [`ListItem`](../ui-components/list/list-item) | `TsListItem` | -| [`PlayerPositionOverlay`](../ui-components/overlay/player-position-overlay) | `TsPlayerPositionOverlay` | -| [`RankedGameSession`](../game-flow/ranked-game-session) | `TsRankedGameSession` | - -A class not on this list is internal plumbing you're not meant to subclass directly. -Tagging it would just generate an unused shadow class. - -The internal class name and its generated shadow name deliberately differ in most -cases: `TsvrcBehaviour` keeps its distinguishing `Tsvrc` prefix internally because a bare -`Behaviour` would collide with -[`UnityEngine.Behaviour`](https://docs.unity3d.com/ScriptReference/Behaviour.html), -while the shadow gets the clean name (`TsBehaviour`) that your own code actually -extends. diff --git a/docs/core/core-concepts/how-it-fits-together.md b/docs/core/core-concepts/how-it-fits-together.md deleted file mode 100644 index 4190da6..0000000 --- a/docs/core/core-concepts/how-it-fits-together.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -id: how-it-fits-together -title: How Core fits together -sidebar_position: 1 ---- - -# How Core fits together - -Core splits into two halves: one lives in the Unity editor while you build, the other -runs at runtime for players. This page explains how they relate, and how the pieces from -[the first-behaviour tutorial](../first-behaviour) fit together. Read it once: every -module's reference page assumes you already have this picture instead of re-explaining -it. - -## Two halves: codegen-time and run-time - -The **codegen half** lives entirely in the Unity editor, under `Editor/CodeGen`. It reads -what you've configured through **Tsvrc > Configure**: which behaviours you've registered -as constructs, which pools exist, which globals are exposed. Then it writes plain C# -files into your project. That configuration always comes from exactly one linked scene -per project, never whatever scene happens to be open (see -[TsLinkedScene](../codegen/config/linked-scene)). Nothing in this half ships in the -built world; it only ever runs while you're editing. - -The **runtime half** lives under `Runtime/` and is ordinary UdonSharp. Some of its types, -like `TsvrcBehaviour` and `Instance`, are base classes your world's scripts extend, always -through a generated shadow rather than directly (the next section covers why). Others, -like `TsvrcMemory`, are services your scripts call into through `_ts` without ever -subclassing them. This is the part that runs for players. - -The generated files are the bridge between the two: they're real, checked-in-looking C# -that extends the runtime half and gets compiled by Unity like any other script. You never -hand-write them, and re-running codegen regenerates them from your configuration each -time. - -## Why a generation step exists at all - -Most frameworks like this solve two problems at runtime: finding whichever object of a -given type is currently registered, and giving you a typed reference to your project's -own subclass instead of a generic base type. The usual tools for that are runtime -reflection or a dependency injection container. - -Core solves both while you're still in the editor instead. The codegen pass reads your -project's types and configuration once, at edit time, and writes plain code with direct -references already baked in. Nothing gets looked up while the world is actually running. - -Whether UdonSharp specifically requires this approach is a separate question this page -doesn't try to answer. What's certain: Core generates every extension point instead of -resolving it at runtime. That's why your own scripts extend a generated shadow class -(`TsBehaviour`, `TsInstance`, and so on) instead of the framework class directly: the -shadow is what carries your project's own concrete types. - -## What the root object bootstraps - -`TsRoot` is the framework's own root type: an abstract class exposing `Instance`, -`Memory`, and `Log`. It's not something you extend yourself. -[`ScaffoldModule`](../codegen/modules/scaffold-module), one of the codegen modules, -generates a concrete subclass for your project and creates the scene object that carries -it. Every `TsvrcBehaviour` in your world holds a reference to that one object -(`_ts`), assigned once when the behaviour is constructed, and reaches the rest of the -framework through it: `_ts.Memory` for shared state, `_ts.Log` for logging, `_ts.Instance` -for instance-level concerns like master detection. - -That's also why construction is a distinct step from `Awake`/`Start`: a `TsvrcBehaviour` -doesn't have a working `_ts` reference until something explicitly calls `TsConstruct` on -it, which is what registering a behaviour as a construct (or a pool member, or a factory -product) in **Tsvrc > Configure** arranges for the generated code to do. A behaviour -that's sitting in the scene but never registered anywhere never gets constructed, and any -of its `TsStart` logic never runs. - -## Where to go from here - -Module reference pages assume you've read this page. If you're looking for how a specific -runtime type behaves in detail, or how a specific codegen module decides what to generate, -start from that module's own reference page rather than this one. diff --git a/docs/core/core-concepts/instance.md b/docs/core/core-concepts/instance.md deleted file mode 100644 index 8e37dd7..0000000 --- a/docs/core/core-concepts/instance.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -id: instance -title: Instance -sidebar_position: 3 ---- - -# Instance - -`Tsvrc.Core.Instance` is the `TsvrcBehaviour` subclass representing the running world -instance itself. It's what you'd reach for to ask "am I the [instance -master](https://creators.vrchat.com/worlds/udon/networking/ownership/#the-instance-master)?" or to hook -startup logic that should run once for the instance as a whole. Its generated -shadow class is `TsInstance`. Your project's actual instance type is a subclass of that -shadow, discovered and wired automatically by `InstanceModule`. There's exactly one per -project; see that module's own reference page for how it's found. - -## Usage - -Override `OnInstanceStart` for setup that should run once the instance itself is ready, -and `IsTsMaster` only if the project needs a notion of "host" that differs from the VRChat -instance master: - -```csharp -public class GameInstance : TsInstance -{ - protected override void OnInstanceStart() - { - LogInfo("Instance started."); - } -} -``` - -## Public surface - -- **`IsTsMaster`** — a `virtual bool`, currently a thin wrapper over the VRChat - [`Networking.IsMaster`](https://udonsharp.docs.vrchat.com/vrchat-api/#networking). It's - a real, working default today, not a stub that throws, so a project with no special - master logic doesn't need to touch it. Treat the name and the logic behind it as a - placeholder, though: the plan for Core is real master management of its own, independent - of the VRChat instance master, and this property will change to reflect that before 1.0. - Override it now if your world needs different master logic in the meantime, but expect - to revisit that override later. Before gating any world feature on master status at - all, note that [VRChat itself recommends against - it](https://creators.vrchat.com/worlds/udon/networking/ownership/#best-practices): prefer an ownership - check where one is available. -- **`OnInstanceStart()`** — a `virtual void`, empty by default. This is where - instance-level startup logic goes. - -## How OnInstanceStart differs from TsStart - -`Instance` deliberately doesn't override `TsvrcBehaviour.TsStart()`. Here's why that -matters: `TsConstruct` only ever calls `TsStart`, so if `Instance` reused it for its own -startup hook, every `TsConstruct` call anywhere would accidentally trigger instance -startup too, with no way to tell the two apart. Generated code calls `OnInstanceStart()` -as a separate, explicit step instead, right after construction. They're two different -events on purpose, not two names for the same thing. - -That also means calling `OnInstanceStart()` yourself, outside the generated call path, -does nothing useful. It's a plain method like any other, not something wired to fire on -its own. - -## Edge cases worth knowing - -The default `IsTsMaster` implementation reads live VRChat networking state. Call it outside -a real running instance, say directly in an editor test with no network context, and it -won't throw. It also won't mean anything: the property is safe to call in a non-runtime -environment, just not meaningful there. diff --git a/docs/core/core-concepts/process.md b/docs/core/core-concepts/process.md deleted file mode 100644 index 5d8eab1..0000000 --- a/docs/core/core-concepts/process.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -id: process -title: Process -sidebar_position: 4 ---- - -# Process - -`Tsvrc.Core.Process` is the base class for networked work that one player runs at a time: it -starts, runs, then stops or completes. That player is the owner, and another player takes over if -the owner leaves or is suspended. Its generated shadow is `TsProcess`. - -## Usage - -Subclass the generated shadow and override the hooks you need: - -```csharp -public class GameRound : TsProcess -{ - protected override void OnProcessStarted() - { - LogInfo("Round started."); - } - - protected override void OnProcessCompleted() - { - LogInfo("Round complete."); - } -} -``` - -Any player can call the lifecycle methods. The owner runs the call, and any other player sends it to -the owner over the network: - -```csharp -gameRound.StartProcess(); -// ...later, from any player: -gameRound.CompleteProcess(); -``` - -## Lifecycle - -`StartProcess(useProcessUpdate)` starts a run on the owner. It marks the process running, calls -`OnProcessStarted`, sends the synced state and starts the [tick loop](#the-tick-loop). On any other -player it sends `RequestStartProcess` to the owner and changes nothing locally. It never changes who -owns the object. A subclass that should run on the player who starts it calls `SetProcessOwner` -before `StartProcess`. If two players start such a subclass at the same time, both can take -ownership and start a run before either sees the other, and only one stays the owner, so start it -from one player when that can happen. - -`StopProcess()` ends a run early and `CompleteProcess()` ends it successfully. The owner acts on -them directly, and any other player sends `RequestStopProcess` or `RequestCompleteProcess` to the -owner. `IsProcessRunning()` reports whether a run is active. Starting a process that's already -running, or stopping or completing one that isn't, logs a warning and does nothing. - -The hooks are all `protected virtual` and empty by default: - -| Hook | Runs on | When | -|---|---|---| -| `OnProcessStarted` | Owner | A run starts, before its first packet goes out, so synced fields set here are in that packet | -| `OnProcessStopped` | Owner | `StopProcess` ends the run | -| `OnProcessCompleted` | Owner | `CompleteProcess` ends the run | -| `OnProcessCleanup(bool isCompleted)` | Owner | After either of the two above, before the cleanup packet goes out. Clear the synced state of your subclass here | -| `OnProcessUpdate` | Owner | About every 0.5 seconds while running, if the run started with `useProcessUpdate: true` | -| `OnBecameProcessOwner` | New owner | The local player becomes the owner while a run is going, see [Taking over a run](#taking-over-a-run) | - -`OnProcessCleanup` is skipped when a new run starts from inside `OnProcessStopped` or -`OnProcessCompleted`, because it would clear the state the new run just set. That happens when a -subclass broadcasts its stop with `SendCustomNetworkEvent(All, ...)`, which [runs on the sender -right away](https://creators.vrchat.com/worlds/udon/networking/events/#event-targeting), and a -listener starts the process again. - -## Ownership - -The owner of a process is the [VRChat owner](https://creators.vrchat.com/worlds/udon/networking/ownership/) -of its GameObject. Subclasses read and change it with three `protected` methods: - -- `IsProcessOwner()` checks whether the local player is the owner. -- `IsProcessOwnedBy(player)` checks whether `player` is the owner. -- `SetProcessOwner(newOwner)` calls `Networking.SetOwner` and sends nothing itself. Don't write - synced fields right after it: the old owner [has to acknowledge the - transfer](https://udonsharp.docs.vrchat.com/networking-tips-&-tricks/#known-issues) first, which - can take a few seconds. - -## Taking over a run - -A run keeps going when its owner can no longer drive it: - -- When the owner leaves, [VRChat assigns a new - owner](https://creators.vrchat.com/worlds/udon/networking/ownership/#how-ownership-works). That - player takes over from `OnPlayerLeft` or `OnOwnershipTransferred`. -- When the owner is [suspended](https://creators.vrchat.com/worlds/udon/players/#get-issuspended), - their client stops running Udon and answering network events, so nothing would drive the run. - Every client that sees the suspension in `OnPlayerSuspendChanged` calls `SetProcessOwner` for its - own player, and the one that ends up owning the object takes over. - -Taking over calls `OnBecameProcessOwner`, then restarts the tick loop. It happens once per handoff, -even when both callbacks see it. It also happens for a handoff made on purpose, such as a subclass -calling `SetProcessOwner` during a run. Only synced fields reach the new owner, so override -`OnBecameProcessOwner` to rebuild anything the previous owner kept in unsynced fields. - -## The tick loop - -While a process runs, its owner runs a loop scheduled with -[`SendCustomEventDelayedSeconds`](https://udonsharp.docs.vrchat.com/vrchat-api/#methods-5) every 0.5 -seconds. Each tick calls `OnProcessUpdate` if the run asked for it. Every 5 seconds it also calls -`RequestSerialization`, which sends every synced field again, those of subclasses included, so a -client that missed a network event still gets the current synced state within a few seconds. - -The loop stops when the run ends or the local player stops being the owner, including when -`OnProcessUpdate` ends the run. If the owner receives a packet while the -process runs and the loop isn't running, `OnDeserialization` starts it again. - -## The request methods - -`RequestStartProcess(bool useProcessUpdate)`, `RequestStopProcess(int requestedGeneration)` and -`RequestCompleteProcess(int requestedGeneration)` are the -[`[NetworkCallable]`](https://creators.vrchat.com/worlds/udon/networking/events/#legacy-events-and-security) -methods a non-owner call sends to the owner. They're public, so any player in the instance can call -them directly, and the owner checks each one: - -- The local player must be the owner, and the process must be stopped for a start or running for a - stop or complete. -- Stop and complete carry the run number the caller saw. Each start increases the synced run - number, and the owner rejects a request whose number doesn't match the current run. -- Each method is rate-limited to one call per second. VRChat [queues calls over that - rate](https://creators.vrchat.com/worlds/udon/networking/events/#rate-limiting) instead of - dropping them, so a stop sent during one run can arrive after the next one started. The run number - is what rejects it. - -A rejected request logs a warning on the owner and does nothing else. Who may start or stop a -process beyond that is up to the subclass. diff --git a/docs/core/core-concepts/ts-root.md b/docs/core/core-concepts/ts-root.md deleted file mode 100644 index dfa483f..0000000 --- a/docs/core/core-concepts/ts-root.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -id: ts-root -title: TsRoot -sidebar_position: 5 ---- - -# TsRoot - -`Tsvrc.Core.Generated.TsRoot` is the abstract root every `TsvrcBehaviour` reaches through -its `_ts` field. See [How Core fits together](./how-it-fits-together) for the overall -picture. This page is its full reference. - -## Usage - -You reach `TsRoot` through `_ts` (see [TsvrcBehaviour](./tsvrc-behaviour) for the base -class it's assigned on). You never construct or subclass it yourself. Because each -property can independently be `null` if its codegen module never ran, guard before using -one rather than assuming all three are populated: - -```csharp -if (_ts.Memory != null) -{ - _ts.Memory.Set("score", new DataToken(0)); -} -``` - -## Public surface - -`TsRoot` declares three independent `virtual` properties, each defaulting to `null` -until a codegen module fills it in: - -- **`Instance`** — your project's [`Instance`](./instance) subclass. -- **`Memory`** — your project's [`TsvrcMemory`](../networking-data/tsvrc-memory) - component. -- **`Log`** — your project's [`TsvrcLogger`](../utilities/tsvrc-logger) component. - -`TsRoot` stays abstract on purpose. Every `TsvrcBehaviour` reaches it only through -`_ts`, and `_ts` is always typed as this abstract base, not as your project's actual -generated class. That's what lets the runtime assembly compile on its own, before your -project's generated code exists yet: `TsvrcBehaviour` only ever depends on `TsRoot`, so -it never needs to know about a generated class that hasn't been written. - -A generator module called `ScaffoldModule` writes that real, concrete subclass for your -project. It's the type your `TsBehaviour`-extending scripts actually get back once -Core retypes `_ts` for them (see [How Core fits -together](./how-it-fits-together#why-a-generation-step-exists-at-all) for how that -retyping works). - -`ScaffoldModule` itself doesn't fill in `Instance`, `Memory`, or `Log`, though. Three -other modules each contribute one override to that same generated class, and only if -they actually ran for your project: `InstanceModule` writes `Instance`, and -`LogModule`/`MemoryModule` write `Log`/`Memory` through a shared base they both extend, -`TsSingleComponentModule`. - -## A missing property isn't the only way this can go wrong - -`_ts` itself is `null` until [`TsConstruct`](./tsvrc-behaviour#construction) has run on -a behaviour. Calling `_ts.Memory` before that point throws a `NullReferenceException` on -`_ts`, not a graceful `null`. Once construction has happened, `_ts` is always a real -object, so from that point on, a property that's unpopulated because its codegen module -never ran returns `null` cleanly instead, exactly like the check in Usage above expects. diff --git a/docs/core/core-concepts/tsvrc-behaviour.md b/docs/core/core-concepts/tsvrc-behaviour.md deleted file mode 100644 index d7b3c83..0000000 --- a/docs/core/core-concepts/tsvrc-behaviour.md +++ /dev/null @@ -1,172 +0,0 @@ ---- -id: tsvrc-behaviour -title: TsvrcBehaviour -sidebar_position: 2 ---- - -# TsvrcBehaviour - -`Tsvrc.Core.TsvrcBehaviour` is the base class every other Core runtime type extends, -directly or indirectly. It's an -[`UdonSharpBehaviour`](https://udonsharp.docs.vrchat.com/) with structured, one-time -initialization and a small publish/subscribe event system built in. Its generated shadow -class is `TsBehaviour`. See [How Core fits together](./how-it-fits-together) for why -your own scripts extend the shadow rather than this class directly. - -## Usage - -In practice, you only write one method yourself: `TsStart`. That's where your setup code -goes. Logging and the event system (`LogInfo`, `LogWarning`, `LogError`, `TsSubscribe`, -`TsEmit`) are already built for you, so you just call them. - -```csharp -public class RoundTimer : TsBehaviour -{ - protected override void TsStart() - { - LogInfo("Round timer ready."); - } - - public void OnRoundEnded() - { - TsEmit("RoundEnded"); - } -} -``` - -Another behaviour reacts to that event by subscribing to it, once, during its own -`TsStart`: - -```csharp -public class ScoreTracker : TsBehaviour -{ - public RoundTimer roundTimer; - - protected override void TsStart() - { - roundTimer.TsSubscribe(this, "RoundEnded", nameof(OnRoundEnded)); - } - - public void OnRoundEnded() - { - LogInfo("Recording final scores."); - } -} -``` - -## Construction - -A `TsvrcBehaviour` doesn't do anything until something calls `TsConstruct` on it. That -call assigns `_ts` and runs `TsStart()`, and it only ever does this once: calling -`TsConstruct` again on an already-constructed behaviour is a silent no-op, no matter which -overload you use. `_ts` is never reassigned, and `TsStart` never runs a second time. - -That one-time guarantee is the whole point. It's what lets `TsStart` safely do things -that would break if run twice, like subscribing to an event or starting a timer, without -needing to guard against being re-entered. `_ts` is set before `TsStart` runs, so -`TsStart` can rely on it being there immediately. - -There are two ways to construct a behaviour: - -- **`TsConstruct(TsRoot tsvrc)`** is the root form. Registering something on the - Configure window's Constructs, Pools, or Factories tab ultimately generates a call to - this, wiring the behaviour directly to the project's root object. -- **`TsConstruct(TsvrcBehaviour parent)`** is the propagating form, for a behaviour that - should share an already-constructed behaviour's `_ts` reference instead of being wired - to the root itself. It reads `parent._ts` and forwards to the root overload. - -A few edge cases fall out of how that guard works: - -- Passing a `null` root to `TsConstruct(TsRoot)` is allowed. `_ts` becomes `null`, and - `TsStart` still runs once. A second call, even with a real root this time, still - changes nothing: the first call already used up the one construction. -- Passing a `null` parent to `TsConstruct(TsvrcBehaviour)` throws a - `NullReferenceException`, but only on a behaviour's *first* construction. The no-op - guard only checks for a second call, so the first call dereferences `parent._ts` - without checking it first. Once a behaviour has already been constructed, a later - `TsConstruct(null)` call is safe: the guard catches it before `parent` is ever touched. -- Passing a real, non-null parent that was itself never constructed doesn't throw. - `parent._ts` is just `null` in that case, and propagating a null root is fine. It's - only a null *parent reference* that throws. -- Propagation chains through any number of hops. Construct `C` against `B`, which was - constructed against `A`, which was constructed against the real root, and `C` ends up - holding that same original root reference. - -## Events: TsSubscribe and TsEmit - -A `TsvrcBehaviour` can broadcast events that other behaviours react to: one side -subscribes to a named event, the other side emits it, and every subscriber gets called. - -Call `TsSubscribe(listener, eventName, callbackName)` to register a listener. From then -on, whenever this behaviour calls `TsEmit(eventName)`, `listener` gets a -[`SendCustomEvent(callbackName)`](https://udonsharp.docs.vrchat.com/vrchat-api/#methods-5) -call. There's no way to unsubscribe: once a listener -signs up, it stays subscribed for the rest of the world's lifetime. Pass both -`eventName` and `callbackName` through `nameof()` instead of a plain string, so renaming -either one later doesn't silently break the wiring. - -A few things worth knowing about how subscriptions behave: - -- Subscribing the same listener to the same event twice registers two separate - deliveries, not one. `TsSubscribe` doesn't check for duplicates. -- Listeners are called in the order they subscribed. -- Subscribing to an event from inside that same event's own callback (a reentrant - subscribe) doesn't take effect until the *next* time it's emitted. `TsEmit` works off - a snapshot taken before it starts calling listeners, so a subscription added mid-emit - can't affect the emit already in progress. - -Two failure modes matter here, and they're handled differently on purpose: - -- A listener that was already `null` when it subscribed throws a - `NullReferenceException`, but not until `TsEmit` actually reaches it. Subscribing - `null` itself doesn't fail; emitting to it does. Any listener earlier in the list - still gets called normally before that throw happens. -- A listener whose GameObject got destroyed *after* subscribing is treated differently: - `TsEmit` just skips it, and every other listener still fires. This works because - the Unity [`==` operator](https://docs.unity3d.com/ScriptReference/Object-operator_eq.html) - treats a destroyed object as equal to `null`, but `TsEmit` casts to `object` first to - check whether the reference is genuinely null (never assigned) versus just destroyed, - and only throws for the first case. - -One more detail, about performance rather than behavior: the storage backing -subscriptions grows by doubling instead of by one slot per subscription, so repeated -`TsSubscribe` calls stay cheap on average instead of reallocating every time. - -## Logging - -Use `LogInfo`, `LogWarning`, and `LogError` to log from a `TsvrcBehaviour` subclass, -rather than calling `TsvrcLogger` or `Debug.Log` directly. See -[TsvrcLogger](../utilities/tsvrc-logger) for the full message format and how the toggles -work. Two things specific to calling it from here: - -- Every message is tagged with this instance's own runtime class name, via - `GetUdonTypeName()`. You never pass the tag yourself. -- `IsTsvrcInternal` (`false` by default) decides which of a message's paired toggles - applies: the "Tsvrc Internal" one or the "Your World" one. Only override it to `true` - if you're writing a framework base class that should be classified as part of Core - itself. Every subclass of a class that overrides it inherits that classification - automatically. Leave it alone in ordinary world scripts. - -If you call `LogInfo`, `LogWarning`, or `LogError` before `TsConstruct` has run, or after -it ran against a root whose `Log` is `null`, these methods fall back to -`Debug.Log`/`LogWarning`/`LogError` directly. The tag and message format stay the same, -but there's no project prefix (there's no `TsvrcLogger` instance to read one from) and no -toggle filtering at all. A message logged this early always prints, no matter how -logging is configured elsewhere. - -## Destruction - -`TsDestroy()` is `virtual` and defaults to calling the Unity -[`Destroy(gameObject)`](https://docs.unity3d.com/ScriptReference/Object.Destroy.html). In -play mode, that defers the actual removal to the end of the current frame rather than -happening instantly. Outside play mode, in the editor, Unity refuses to run it -synchronously at all. Override `TsDestroy()` if a behaviour needs to do something other -than remove its whole GameObject. An override replaces the default entirely: there's no -"your override runs, then the base behavior also runs" chaining, so call -`Destroy(gameObject)` yourself if you still need it. - -## What subclasses actually override - -In practice, a subclass overrides `TsStart()` (a no-op by default) and, rarely, -`IsTsvrcInternal` or `TsDestroy()`. Everything else on this page is inherited behavior -you call, not something you override. diff --git a/docs/core/explanations/builtin-registrations.md b/docs/core/explanations/builtin-registrations.md deleted file mode 100644 index f64d81d..0000000 --- a/docs/core/explanations/builtin-registrations.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -id: builtin-registrations -title: "Decision note: builtin pool and factory entries" -sidebar_position: 4 ---- - -# Decision note: builtin pool and factory entries - -Eight of the Core runtime types ship pre-registered in `TsBuiltinConfig`, the -library-wide counterpart to a project's own [`TsConfig`](../codegen/config/ts-config): -[`DataTransferer`](../networking-data/data-transfer/data-transferer), -[`TsvrcTimer`](../networking-data/tsvrc-timer), -[`PlayerTracker`](../players-tracking/player-tracker), -[`ReadyCheckProcess`](../players-tracking/ready-check-process), and -[`AutoPlayerTracker`](../players-tracking/auto-player-tracker) as pool entries; -[`HeadClipGuard`](../players-tracking/head-clip-guard) and -[`StateManager`](../game-flow/state-manager) as factory entries; and -[`RankedGameSession`](../game-flow/ranked-game-session) as a pool entry too, not just the -sub-behaviours it composes. A `[WirePool]` field or `_ts.CreateX()` call for any of these -eight works the moment you write it, with nothing to add on the Configure window's Pools -or Factories tab first. This note explains why Core ships them pre-registered, and why -each one landed on Pool or Factory specifically. - -## What shipping them pre-registered actually buys - -The doc comment on `TsBuiltinConfig` describes it plainly: "library-wide Globals/Pool/Factory -registrations shipped with tsvrc itself, merged with each world's own `TsConfig` at generate -time." The observable effect of that merge is what matters here: without it, using -`PlayerTracker` in your own code would need the same round trip registering one of your own -project's types does, open Configure, add it to the Pools tab, then come back to write the -`[WirePool]` field, even though every project that uses `PlayerTracker` needs it registered -the exact same way, with no project-specific choice to make. Merging the Core -registrations in ahead of a project's own removes that step for these eight types -specifically, without changing anything about how a project registers its *own* types. - -## Why Pool for six of them, Factory for two - -The split isn't arbitrary, and it isn't about which types happen to be networked either: -`RankedGameSession` carries `[UdonBehaviourSyncMode(BehaviourSyncMode.None)]`, the same -annotation as the two factory entries, so "does this type sync" doesn't actually separate -the two groups. The real split comes from how each generator produces an instance: - -- **A pool slot is instantiated once, at edit time**, and never again. `PoolModule.Wire()` - creates every slot the project needs and wires it directly into the matching - `[WirePool]` field, all before the world is ever uploaded. Nothing about getting a - pooled reference involves a runtime `Instantiate()` call. -- **A factory method clones its prefab at the moment you call it**, via an actual - `Instantiate()` inside the generated `CreateX(parent)` method. See [the pooling - pattern](./pooling-pattern) for why that specific operation, a runtime `Instantiate` - call, is exactly what the VRChat networking model can't synchronize. That's a hard - constraint on every factory-created object, not a convention: no factory-created - instance could correctly participate in networked gameplay regardless of what it is, - which is exactly why [`FactoryModule`](../codegen/modules/factory-module) documents that - restriction as a fact about the mechanism rather than a rule you're expected to - self-enforce. `HeadClipGuard` and `StateManager` both happen to be local-only already - (their own `BehaviourSyncMode.None`), which is what makes Factory a safe fit for them. - -That difference also explains why `PlayerTracker`, `ReadyCheckProcess`, -`AutoPlayerTracker`, `TsvrcTimer`, `DataTransferer`, and `RankedGameSession` couldn't have -been factory entries instead, independent of whether they sync. `RankedGameSession` and -several of the others declare their own `[WirePool]` fields (in `RankedGameSession`, -`_lobbyTracker`, `_readyCheck`, and so on), and `PoolModule.Wire()` only ever wires -`[WirePool]` fields on objects that already exist in the scene when it runs, at edit time. -A factory-cloned instance is created later, during actual gameplay, long after that pass -ran. Its own `[WirePool]` fields would stay `null` forever: nothing re-wires them after the -fact. Pooling is the only one of the two mechanisms compatible with a type that itself -depends on further pooled types. diff --git a/docs/core/explanations/codegen-vs-reflection.md b/docs/core/explanations/codegen-vs-reflection.md deleted file mode 100644 index d99c8e2..0000000 --- a/docs/core/explanations/codegen-vs-reflection.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -id: codegen-vs-reflection -title: "Decision note: codegen instead of runtime reflection" -sidebar_position: 1 ---- - -# Decision note: codegen instead of runtime reflection - -Core resolves a project's own concrete types (which class is your `Instance` subclass, -which behaviours are registered as Constructs, which prefabs are pooled) once, at edit -time, and bakes the result into generated C# with direct field references and typed -accessors. A framework built the same way in ordinary C# would more commonly reach for -runtime reflection or a dependency-injection container to do this lookup dynamically, -lazily, whenever it's actually needed. Core doesn't have that option, for a concrete, -checkable reason: the runtime environment it targets doesn't support it. - -## What Udon-compiled code can't do - -UdonSharp compiles against a fixed set of APIs the Udon VM exposes ("externs"), determined -by walking the .NET type system at compile time, not at the compiled program's own runtime. -[The VRChat documentation of the Udon VM](https://creators.vrchat.com/worlds/udon/vm-and-assembly/#overview-of-the-udon-vm) -states this directly: "reflection is not used to access functions," though the VM is -"'styled' like it is," meaning a function call compiles down to a fixed extern name resolved -ahead of time, not a live, `System.Reflection`-style lookup by member name at runtime. (The -reflection calls you'll find inside the UdonSharp tooling, for example [the Editor-side -"proxy" object every `UdonSharpBehaviour` -has](https://udonsharp.docs.vrchat.com/editor-scripting/#overview), run in the C# context of the -Unity Editor while compiling or inspecting a script; they never execute as part -of the compiled Udon bytecode itself.) - -Generics compound the problem: [the UdonSharp -FAQ](https://udonsharp.docs.vrchat.com/frequently-asked-questions/#im-starting-from-scratch-and-need-to-use-c-tutorials-what-common-aspects-of-c-dont-work-in-udonsharp) -lists generic classes and generic methods among the C# features that don't work in Udon. A -typical reflection-or-DI-based framework leans on both together: reflect over a type, then -resolve or construct it generically. With neither tool available in compiled Udon code, -that whole approach is closed off, not just inconvenient. - -Object creation is restricted the same way: the only instantiation method [the VRChat API -reference](https://udonsharp.docs.vrchat.com/vrchat-api/#vrcinstantiate) lists is -`GameObject VRCInstantiate(GameObject original)`, a single, non-generic overload. Since -generic methods don't work in Udon at all (the same restriction cited above), there's no -way a generic `Instantiate()` returning an arbitrary, runtime-determined component type -could exist here either, and reading a component back off a freshly instantiated object has -the same limitation. That's part of why generated factory code (see -[`FactoryModule`](../codegen/modules/factory-module)) resolves its type at generation time -and emits a concrete, non-generic `GetComponent()` call rather than anything -parameterized. - -## What Core does instead - -None of that machinery exists in compiled Udon, but all of it is perfectly ordinary, -supported C# in the Unity Editor, where Core does its own reflection. Scanning loaded -assemblies for an `Instance` subclass, or a class tagged -[`[TsWorldExtensionPoint]`](../core-concepts/attributes.md), runs entirely in the editor's -own C# runtime, at generate time, never inside a compiled UdonSharpBehaviour. The generator -does the type resolution once, while it still has full reflection and generics available to -it, and writes the *result* (a concrete field, a concrete property, a concrete method -signature) as plain generated code that the Udon compiler then compiles like any other -UdonSharp script. By the time a world is actually running, there's no lookup left to do at -all: `_ts.Name` is a real, direct field access, not a dictionary lookup or a reflected member -access, because the framework already did that resolution before the world was ever built. diff --git a/docs/core/explanations/pooling-pattern.md b/docs/core/explanations/pooling-pattern.md deleted file mode 100644 index b97d276..0000000 --- a/docs/core/explanations/pooling-pattern.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -id: pooling-pattern -title: "Decision note: the pooling pattern" -sidebar_position: 2 ---- - -# Decision note: the pooling pattern - -[`WirePoolAttribute`](../core-concepts/attributes.md) and [`PoolModule`](../codegen/modules/pool-module) -compute how many instances of each poolable prefab a project needs, and instantiate exactly -that many into the scene as generated content: at edit time, wired and saved as part of the -scene, rather than instantiated on demand while the world is running. This mirrors a -constraint documented directly in the VRChat creator documentation, not an arbitrary design -preference. - -## The documented constraint - -[The UdonSharp networking -guidance](https://udonsharp.docs.vrchat.com/networking-tips-&-tricks/) states plainly, under -its "Instantiation" heading, that "instantiated objects cannot be correctly synchronized," -and that "the only workaround is to use object-pooling": pre-placing a fixed set of objects -in the scene ahead of time and toggling their active state at runtime instead of creating -new ones. [The VRChat `VRCObjectPool` -component](https://udonsharp.docs.vrchat.com/vrchat-api/#vrcobjectpool) documents doing -exactly that: it "manage[s] and synchronize[s] the active state of each object it holds," -handing one out via a spawn call and returning it later rather than ever instantiating or -destroying anything at runtime. That's the same model `PoolModule` follows for `[WirePool]` -fields. - -## What this means for the design of Core - -Because a networked, poolable object has to already exist in the scene before the world -starts, "how many instances do we need" has to be answered before runtime, not lazily as -demand appears. There's no safe way to spin up a new synced instance of a type on demand -once players are already in the instance. The `PoolModule` slot-count computation (see its own -reference page for the dependency-graph math) exists to answer that question as accurately -as possible at edit time, from real usage found in the project: how many places actually -declare a `[WirePool]` field for a given type, including other pooled types that themselves -depend on further pooled types. - -This page deliberately doesn't go further and explain the lower-level mechanism, for -example exactly why the VRChat networking model ties an object's ability to be owned and -synced to it having existed since before the scene loaded. That's a real, documented rule -(the constraint above is directly stated in the VRChat docs), but the deeper "why" at the -level of how network IDs get allocated isn't something either the public UdonSharp -documentation or its compiler source spells out in enough detail to state as fact here. -Treat the rule itself as solid; treat any explanation of the underlying networking mechanics -beyond it as unverified. diff --git a/docs/core/explanations/sync-model.md b/docs/core/explanations/sync-model.md deleted file mode 100644 index 1e7a3cc..0000000 --- a/docs/core/explanations/sync-model.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -id: sync-model -title: "Decision note: the shared-memory and sync model" -sidebar_position: 3 ---- - -# Decision note: the shared-memory and sync model - -Every Core type that replicates state, such as [`TsvrcMemory`](../networking-data/tsvrc-memory) -and [`Process`](../core-concepts/process), uses the same two pieces: the VRChat manual sync mode -(`BehaviourSyncMode.Manual`) and an explicit `RequestSerialization()` call after each change. This -note explains why. - -## Manual sync, sent on demand - -[VRChat describes the two sync -modes](https://creators.vrchat.com/worlds/udon/networking/variables/#2-manual-sync) this way: manual -sync "requires calling `RequestSerialization()` to send data updates" and suits values that don't -change often, while continuous sync "updates automatically" and suits "frequently updated values." -State in the Core types changes in discrete steps, such as a process starting, a timer pausing or a -player joining a tracked set, not continuously like a transform position. Each change has a clear -moment to send it, so there's no reason to pay for automatic periodic replication. - -## The resync heartbeat - -`Process` adds a second mechanism: while a process runs, its owner sends its full synced state -again every 5 seconds, whether or not anything changed. The lifecycle broadcasts of the Core process -types are discrete `[NetworkCallable]` events with no delivery confirmation, and a client that misses -one has no other way to catch up. The VRChat docs document one case where events are lost: when -players in one instance run different world versions, [the server "may silently drop events and not -deliver -them"](https://creators.vrchat.com/worlds/udon/networking/events/#mismatched-world-versions-in-the-same-instance). -The heartbeat doesn't depend on knowing which case happened: a client that missed a broadcast gets -the current synced state within a few seconds, with no acknowledgement or retry logic. See -[`Process`](../core-concepts/process#the-tick-loop) for the loop that sends it. - -## Working around what can't be synced directly - -The synced tier of `TsvrcMemory` exists because `DataDictionary`, the natural shape for a key-value -store, isn't a syncable type. [The types synced variables -support](https://udonsharp.docs.vrchat.com/vrchat-api/#synced-variables) are primitives, the small -Unity value types (`Vector2`, `Vector3`, `Vector4`, `Quaternion`, `Color`), strings and `VRCUrl`. -`TsvrcMemory` serializes the dictionary to a string with [`TsJson`](../utilities/ts-json) before -each synced write and parses it back in `OnDeserialization`, and that string field follows the same -manual sync pattern as any other synced value. See [`TsvrcMemory`](../networking-data/tsvrc-memory) -for what the synced tier guarantees about ordering and delivery. - -## Ownership - -Core uses the [VRChat ownership -model](https://creators.vrchat.com/worlds/udon/networking/ownership/#how-ownership-works) as it is: -only "the owner of a networked object can modify its synchronized Udon variables," so only the -owner sends state to other players. There's no second ownership concept on top of it. - -The types differ in how a write from another player reaches the owner: - -- `TsvrcMemory` takes ownership for the local player before it writes a synced key. -- `Process` never takes ownership by itself. A lifecycle call from another player is sent to the - owner over the network, and the owner applies it. A subclass that should run on the player who - starts it [takes ownership first](../core-concepts/process#lifecycle). diff --git a/docs/core/first-behaviour.md b/docs/core/first-behaviour.md deleted file mode 100644 index ef2d8f5..0000000 --- a/docs/core/first-behaviour.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -id: first-behaviour -title: Build your first behaviour -sidebar_position: 2 ---- - -# Build your first behaviour - -This walks you through initializing Core in a scene and getting one script running in -play mode. By the end you'll have a world-specific behaviour that Core constructs at -startup and that logs through the framework's own logger. - -This assumes Core is already installed. See [Add TsVRC Core to your -project](./add-to-your-project) first if your project doesn't have a **Tsvrc** menu in -the menu bar yet. - -## Initialize Core in your scene - -Save your scene first. Open **Tsvrc > Configure**: on a scene that hasn't used Core -before, the window tells you it isn't set up yet and offers a single button: -**Initialize Tsvrc**. Click it. - -That button runs the same code generation pass you'll trigger again every time you add -something new later (its label switches to **Force Regenerate** afterward). It writes a -generated root script for your project and compiles it. Wait for Unity to finish -recompiling before continuing: the Configure window shows a "waiting for scripts to -compile" message while that's in progress. - -This first run also links this scene to Core, since only a saved scene has a file path -to link to. Core reads its configuration from exactly that one linked scene from now on, -no matter what else is open. If your project uses more than one scene, see -[TsLinkedScene](./codegen/config/linked-scene) before you go further. - -## Write your behaviour - -Core generates a project-specific subclass of its internal root types so your code gets a -typed `_ts` reference back to your own project instead of a generic one. That means your -script extends the generated shadow class, not the framework class it shadows. For an -ordinary behaviour, that shadow class is called `TsBehaviour`: - -```csharp -using Tsvrc.Core.Generated; - -public class HelloWorld : TsBehaviour -{ - protected override void TsStart() - { - LogInfo("HelloWorld constructed."); - } -} -``` - -`TsStart` is the framework's initialization hook, called once per instance. `LogInfo` -routes through the Core logger instead of `Debug.Log`, so the message respects whatever -log levels you've configured in **Tsvrc > Configure > Logging**. - -Attach `HelloWorld` to a GameObject in your scene. - -## Register it as a construct - -Adding the component to the scene isn't enough by itself: Core only calls `TsStart` on -behaviours it's been told about. Back in **Tsvrc > Configure**, open the **Constructs** -tab and click **+ Add**. With the `HelloWorld` GameObject selected, drag its `HelloWorld` -component (from the Inspector, not the GameObject from the Hierarchy) into the new slot. -Core needs the actual component reference here and silently rejects anything else, a -GameObject included, with a console warning, so dropping the GameObject by mistake looks -like nothing happened. - -Registering it here is what makes Core call `TsStart` on it once at world startup. The -reference itself stays private: if another behaviour needs to reach `HelloWorld` directly, -wire it in the Inspector like any other field, or register it as a -[Global](./codegen/modules/global-module) instead if you want it reachable as -`_ts.HelloWorld`. - -A footer appears at the bottom of the window once you've made this change: "You have -unapplied changes." Click **Apply** there. That single click both saves the entry and -runs codegen, so you don't need **Force Regenerate** afterward too, and can't: it's -disabled while a change is still unapplied. [Try this flow on a live mockup of the -window](./codegen/config/ts-window#try-it). - -## Run it - -Enter play mode. You should see `HelloWorld constructed.` in the console, tagged with the -`HelloWorld` class name. If you don't see it, reopen **Tsvrc > Configure** and check for a -warning banner — the window surfaces the generator's own warnings and errors there instead -of leaving you to search the console for them. - -## Where to go next - -Read [How Core fits together](./core-concepts/how-it-fits-together) for the bigger picture behind what -just happened: why there's a generation step at all, and how the pieces you touched here -(the root object, the construct registration, the generated shadow class) relate to each -other. diff --git a/docs/core/game-flow/ranked-game-session.md b/docs/core/game-flow/ranked-game-session.md deleted file mode 100644 index f50b571..0000000 --- a/docs/core/game-flow/ranked-game-session.md +++ /dev/null @@ -1,200 +0,0 @@ ---- -id: ranked-game-session -title: RankedGameSession -sidebar_position: 2 ---- - -# RankedGameSession - -`Tsvrc.Session.RankedGameSession` composes the rest of the tracking and timing stack into a -full round-based game session: a lobby, a synchronized ready-check-gated start, an active -game phase with completion tracking, and a configurable end condition. Its generated shadow -is `TsRankedGameSession`. It's built from [`PlayerTracker`](../players-tracking/player-tracker), -[`ReadyCheckProcess`](../players-tracking/ready-check-process) and -[`TsvrcTimer`](../networking-data/tsvrc-timer) instances, listed under [What it's built -from](#what-its-built-from). See [Run a full timed round with a lobby](../how-to/running-a-timed-round) -for a task-oriented walkthrough. - -## Getting an instance - -`RankedGameSession` itself, not just the sub-behaviours it composes, ships as one of -[the Core default pool entries](../explanations/builtin-registrations) -(`TsBuiltinConfig`). - -- **Default:** `[WirePool][SerializeField] private RankedGameSession _session;` just - resolves, nothing to register in Configure first, and codegen calls `TsConstruct` for - you at wire time. -- **Manual:** skip pooling entirely. Drag the shipped `RankedGameSession` prefab into your - scene and call `TsConstruct` on it yourself, since nothing does that for an instance - nobody registered anywhere. - -## What it's built from - -Five pooled ([`WirePoolAttribute`](../core-concepts/core-attributes)) sub-behaviours, wired -up by codegen rather than assigned by hand: - -- `_lobbyTracker` (`PlayerTracker`) — who's in the lobby, before a round starts. -- `_readyCheck` (`ReadyCheckProcess`) — gates the transition from lobby to active game. -- `_gameTracker` (`PlayerTracker`) — who's actively playing the current round. -- `_completedTracker` (`PlayerTracker`) — who has finished the current round. -- `_timer` (`TsvrcTimer`) — an optional round duration. - -`RankedGameSession` itself carries no state about *why* a game is won or lost. It only -manages phase transitions and player-set bookkeeping; your own subclass or event subscribers -decide what "completed" or "should end" actually means for your game. - -## The state machine - -`CurrentState` is one of `RankedGameSessionState.Idle`, `Loading`, or `InGame`. It's a plain -local field, not re-derived from the sub-trackers own synced state on every read: `TsStart` -seeds it once from that live state (safe only there, since a late-joining client's -sub-trackers are already fully synced by the time its own scripts start running), and from -then on the `RankedGameSession` code sets it directly at each transition, whether that -code is running in response to a subscribed sub-behaviour event or, for `StopSession` -specifically, directly inside the call itself. Re-deriving it live on every read instead -would go stale on any client that doesn't own that particular sub-process. - -```mermaid -stateDiagram-v2 - [*] --> Idle - Idle --> Loading: StartSession - Loading --> InGame: ready check completes - Loading --> Idle: StopSession - Loading --> Idle: empty lobby - InGame --> Idle: StopSession - InGame --> Idle: natural end -``` - -## Running a session - -```csharp -session.StartLobbyTracking(); -session.AddLobbyPlayer(somePlayerId); -// ... later ... -session.StartSession(); -// each client, once ready: -session.SetReady(); -// ... a round is now InGame; your game logic calls: -session.AddCompletedPlayer(somePlayerId); -``` - -`StartLobbyTracking`/`StopLobbyTracking` are thin forwards that start and stop tracking -on `_lobbyTracker`. `AddLobbyPlayer`/`RemoveLobbyPlayer` add or remove one player from the lobby, and -both require `StartLobbyTracking` to have run first: calling either before that logs an -error and does nothing, rather than silently queuing the player for later. - -`StartSession` snapshots the current lobby roster and starts the ready check over it; it -logs an error and does nothing if a session is already running (`CurrentState` isn't -`Idle`). It takes an optional `additionalKnownPresentPlayerIds`: extra IDs unioned into that -initial snapshot even if the synced state of `_lobbyTracker` hasn't caught up to them yet, -since a caller's own local knowledge (say, a trigger volume's roster) can be ahead of what's -propagated over the network. Starting with an empty roster logs an error and does nothing: -[a ready check with no players never -completes](../players-tracking/ready-check-process#edge-cases), so the session would otherwise -stay in `Loading` until a `StopSession` call. - -`AddLoadingParticipant` lets a player join an *already-running* ready check that they -weren't part of the original snapshot: useful for a game that becomes eligible to more -players over time without waiting for the next round. It does nothing outside `Loading` or -for a player already tracked. - -Once `InGame`, `RemoveGamePlayer` drops a player from `_gameTracker` directly, for a player -leaving the round early without leaving the instance (a respawn, an exit trigger); it's a -no-op outside `InGame`. `SetTimerDuration(ms)` overrides the inspector-configured round -length at runtime; it only takes effect the next time the ready check completes and -`_timer.StartTimer` actually runs, so call it any time before that moment, including while a -session is already `Loading`, not while a round is already `InGame`. -`GetRemainingMilliseconds()` forwards to the round timer directly, for a HUD that doesn't -want to hold its own reference to `_timer`. - -## Ending a session - -Four independent, individually toggleable natural end conditions -(`_endOnTimerComplete`, `_endOnAllGamePlayersLeft`, `_endOnAllPlayersCompleted`, -`_stopOnEmptyLobbyDuringLoading`) plus an explicit `StopSession()` call. Each maps to its own -`RankedGameSessionEndReason` value, readable via `LastEndReason` once the corresponding event -fires. `_stopOnEmptyLobbyDuringLoading` exists for the same reason as the empty-roster start -guard: a ready check whose players all left never completes, so without it the session would stay -in `Loading`. It's the `Loading` counterpart of `_endOnAllGamePlayersLeft`. - -**`StopSession` reaches every client during `Loading`, but not during `InGame`.** The two -branches behave differently, and the difference matters if you're building a networked -"force stop" button. - -During `Loading`, `StopSession` calls `_readyCheck.StopReadyCheck()`. `RankedGameSession` -subscribes to `OnReadyCheckStoppedEvent`, which fires on every client when the ready check stops, -so every client updates its own state when that event arrives. - -During `InGame`, `StopSession` calls `_EndSession` directly instead: `CurrentState`, -`LastEndReason` and `OnSessionStoppedEvent` are set and fired right away, on the calling client -only, before `_StopSubProcesses()` asks `_gameTracker`, `_completedTracker` and `_timer` to stop. -`RankedGameSession` doesn't subscribe to the stop events of those three, only to their -players-added, players-removed and timer-completed events, so nothing updates its state on other -clients when they stop. **A client that didn't call `StopSession` itself -during `InGame` never sees its own `CurrentState` return to `Idle`.** - -`RankedGameSession` carries no authorization or broadcast policy of its own (who's allowed -to stop a session, and how that reaches every client): that's entirely the caller's -responsibility. A networked "force stop" button needs to broadcast the `StopSession` call to -itself across clients to cover the `InGame` case; the `Loading` case already gets there -through the ready check's own networking. - -## Reading player state safely from inside an end event - -`GamePlayerIds`/`CompletedPlayerIds` read live off the sub-trackers, which are already being -torn down by the time `OnSessionEndedEvent`/`OnSessionStoppedEvent` actually fire: reading -them from inside those events handlers sees either an already-emptied result (on whichever -client owns the sub-tracker being stopped) or a stale one that hasn't caught up yet (on -every other client), never reliably the picture at the moment the round actually ended. Use -`LastEndedGamePlayerIds`/`LastEndedCompletedPlayerIds` instead: both are snapshotted -immediately before the sub-trackers are torn down, on every client, specifically so a -subscriber to the end events has accurate data to work with regardless of ownership. -`LoadingPlayerIds` has a related but distinct subtlety: it reads the ready check's own -roster (which can be broader than `LobbyPlayerIds`, thanks to -`additionalKnownPresentPlayerIds`), so use it rather than `LobbyPlayerIds` to check whether a -player is part of the round currently loading. - -```csharp -session.TsSubscribe(this, RankedGameSession.OnSessionEndedEvent, nameof(_OnRoundOver)); -session.TsSubscribe(this, RankedGameSession.OnSessionStoppedEvent, nameof(_OnRoundOver)); - -public void _OnRoundOver() -{ - // GamePlayerIds is unreliable here - the sub-trackers are already being torn - // down by the time this fires. Use the snapshot instead. - if (TsArray.Contains(session.LastEndedGamePlayerIds, localPlayerId)) - AwardCompletionBonus(); -} -``` - -## Events - -Eight of nine events pair a `protected virtual` hook with a public string constant for -`TsSubscribe`, firing the hook first, matching the convention used throughout the tracking -chain; `OnTimerUpdatedEvent` is a plain forward of the round timer's own tick, with no -matching hook of its own. - -| Hook | Event constant | Fires when | Read | -|---|---|---|---| -| `OnSessionLoading` | `OnSessionLoadingEvent` | `StartSession` begins the ready check | `LobbyPlayerIds` | -| `OnSessionStarted` | `OnSessionStartedEvent` | The ready check completes and the round goes `InGame` | `LobbyPlayerIds` | -| `OnSessionStopped` | `OnSessionStoppedEvent` | `StopSession` (either phase), or (with `_stopOnEmptyLobbyDuringLoading`) the lobby emptying while `Loading` | `LastEndedGamePlayerIds`/`LastEndedCompletedPlayerIds`, `LastEndReason` | -| `OnSessionEnded` | `OnSessionEndedEvent` | A natural end condition fires (timer expired, all active players left, all players completed) | same as above | -| `OnLobbyPlayerAdded` | `OnLobbyPlayerAddedEvent` | A player is added to the lobby | `LastAddedLobbyPlayerIds` | -| `OnLobbyPlayerRemoved` | `OnLobbyPlayerRemovedEvent` | A player is removed from the lobby, including [automatically on leaving or suspending](../players-tracking/player-tracker#automatic-removal) | `LastRemovedLobbyPlayerIds` | -| `OnGamePlayerRemoved` | `OnGamePlayerRemovedEvent` | A player leaves `_gameTracker` during `InGame` | `LastRemovedGamePlayerIds` | -| `OnPlayerCompleted` | `OnPlayerCompletedEvent` | `AddCompletedPlayer` succeeds | `LastCompletedPlayerIds` | -| (none) | `OnTimerUpdatedEvent` | Forwarded from the round timer's own `OnTimerUpdatedEvent` | — | - -`LobbyPlayerIds` is what both `OnSessionLoadingEvent` and `OnSessionStartedEvent` document -reading, even though the round is already using the ready check's broader roster -(`LoadingPlayerIds`) by the time it starts; read `LoadingPlayerIds` instead if a player was -added via `AddLoadingParticipant`. - -## GetPlayerStatus - -`GetPlayerStatus(playerId)` derives a single `RankedGamePlayerStatus` value -(`NotInSession`/`InLobby`/`Loading`/`Playing`/`Completed`) from the tracker arrays already -available on any client at any moment. It introduces no new synced state, just a -consumer-friendly read over state that already exists, replacing what would otherwise be -manual cross-referencing of three or four separate ID arrays. diff --git a/docs/core/game-flow/state-manager.md b/docs/core/game-flow/state-manager.md deleted file mode 100644 index df2a9b3..0000000 --- a/docs/core/game-flow/state-manager.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -id: state-manager -title: StateManager -sidebar_position: 1 ---- - -# StateManager - -`Tsvrc.StateMachine.StateManager` is a generic, local-only (unsynced) finite state machine: -states are plain integers, each with optional enter/exit method dispatch on a chosen target -behaviour. Its generated shadow is `TsStateManager`. It has no dependency on any other -Core module beyond `TsvrcBehaviour`. See [Give a screen or flow its own state -machine](../how-to/adding-a-screen-state-machine) for a task-oriented walkthrough. - -## Getting an instance - -`StateManager` ships as one of [the Core default factory -entries](../explanations/builtin-registrations) (`TsBuiltinConfig`). - -- **Default:** `_ts.CreateStateManager(parent)` just works, nothing to register in - Configure first. -- **Manual:** skip the factory entirely. `AddComponent` it (or drag the shipped - `StateManager` prefab into your scene) and start calling `RegisterState`/`SetState` - directly. Unlike most other Core runtime types, `StateManager` never overrides - `TsStart` and never touches `_ts`, so it doesn't need `TsConstruct` to have run at all: - first-class support for the fully manual path. - -## Usage - -```csharp -manager.RegisterState(StateIdle, this, exitMethod: nameof(OnExitIdle)); -manager.RegisterState(StateActive, this, enterMethod: nameof(OnEnterActive)); -manager.SetState(StateActive); -``` - -`RegisterState(state, target, enterMethod, exitMethod)` associates a state integer with a -target `UdonSharpBehaviour` and up to two method names, dispatched via `SendCustomEvent`. -Use `nameof()` for the method names so a rename doesn't silently break the wiring. Pass -`this` as the target for a `StateManager` subclass that hosts its own enter/exit methods. -Either method name is optional; a state can register only an exit, only an enter, or -neither (useful if you only need to react through `OnStateChanged` instead). -`UnregisterState` removes an entry entirely: a later transition into or out of an -unregistered state simply skips dispatch for it, without throwing. - -`SetState(newState)` runs the transition: calls the current state's registered exit method -(skipped if no state has been entered yet, the initial state is `-1`), calls the virtual -`OnStateChanged(oldState, newState)` hook and emits an -[`"OnStateChanged"`](../core-concepts/tsvrc-behaviour#events-tssubscribe-and-tsemit) event -via `TsEmit`, then calls the new state's registered enter method. Calling `SetState` with the -state already current is a no-op: no dispatch happens at all, not even a redundant -exit/enter of the same state. `CurrentState`/`PreviousState` are also exposed as -`GetCurrentState()`/`GetPreviousState()` method calls returning the same values, useful -anywhere only a method, not a property getter, can be wired up, such as a `UnityEvent` bound -in the inspector. - -## Reentrant SetState calls are queued, not interleaved - -Calling `SetState` again from inside `OnStateChanged`, from an external subscriber to the -`OnStateChanged` event, or from an enter/exit method itself doesn't run that new transition -immediately: it's queued (only the most recently queued state survives if several arrive -before the current transition finishes) and runs only after the in-progress transition -completes in full. This guarantees a transition's exit → `OnStateChanged` → enter sequence -is never interrupted partway through by a reentrant call jumping the queue. - -That queue drains in a loop inside the original `SetState` call, not in a separate future -tick: if a queued transition's own `OnStateChanged` (or dispatched method) immediately -queues yet another *different* state every time it runs, the loop keeps draining and never -returns control to whoever made the original call. It won't overflow the call stack the way -naive recursion would, but it will hang that calling frame indefinitely. Redirecting to a -state and stopping there is fine (already the pattern a reentrant redirect exists for); an -enter/exit chain that never settles is not. - -## Failure mode worth knowing - -`SetState` sets `_isTransitioning = true`, runs the transition, then sets it back to -`false`. UdonSharp can't compile `try`/`catch`/`finally`, so that reset can't be wrapped in a -`finally` block. If `OnStateChanged`, a dispatched enter/exit method, or an external -subscriber to the `"OnStateChanged"` event throws mid-transition, the exception unwinds -straight past the reset and `_isTransitioning` is left stuck `true`. Every subsequent -`SetState` call is then permanently treated as reentrant: it queues its state instead of -running it, and nothing ever processes the queue again, since nothing completes the -transition that's stuck "in progress." A `StateManager` instance that hits this is stuck for -good, silently swallowing every later `SetState` call rather than throwing again or -recovering. If your enter/exit methods or `OnStateChanged` override can throw, catch inside -them rather than letting an exception escape into `SetState`. - -## Dispatch target lifetime - -A registered target whose `GameObject` was destroyed after `RegisterState` is treated the -same as a `null` target: its dispatch is skipped silently rather than throwing, using the -same "compare to `null` through the overridden Unity equality" check used elsewhere in the -framework. A destroyed target for one state doesn't affect dispatch for any other -registered state. diff --git a/docs/core/how-to/adding-a-language.md b/docs/core/how-to/adding-a-language.md deleted file mode 100644 index 78ca617..0000000 --- a/docs/core/how-to/adding-a-language.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -id: adding-a-language -title: Add another language and switch at runtime -sidebar_position: 16 ---- - -# Add another language and switch at runtime - -How to localize your world's UI text and let players switch languages while it's -running, using **Tsvrc > Translation** and the generated -[`TranslationModule`](../codegen/modules/translation-module) API. - -## Steps - -1. Open **Tsvrc > Translation** and click **Create Translation Config** if none exists - yet. Assign one `TextAsset` per language, each a JSON file shaped like: - - ```json - { - "key": "fr", - "label": "French", - "entries": { - "menu_play": "Jouer", - "players_remaining": "{value} joueurs restants" - } - } - ``` - - The generated `Language` enum member's name is derived from `"label"`, sanitized into - a valid identifier, so `"French"` becomes `Language.French`. A label with characters - outside `A-Za-z0-9` (an accented name, a language's own native script) sanitizes into - whatever identifier those characters actually produce; pick a plain ASCII label if you - want a predictable enum member name to reference from code. - -2. Name every translatable `TextMeshProUGUI` object with a single underscore on each - side, matching an entry key exactly (`_menu_play_`, `_players_remaining_`). No - component or attribute marks it as translatable, just the name. -3. Regenerate. Switch languages and read a translation directly from code: - - ```csharp - public class LanguageSelector : TsBehaviour - { - [SerializeField] private TextMeshProUGUI _remainingText; - - public void SwitchToFrench() => _ts.SetLanguage(Language.French); - - public void ShowRemaining(int count) => - _remainingText.text = _ts.Translate("players_remaining", count.ToString()); - } - ``` - - Every `_menu_play_`/`_players_remaining_`-named text object updates automatically the - moment `SetLanguage` runs. Nothing else to wire for text that's just named correctly. - -4. If a script needs to react to a language switch itself, not just have its own text - objects update, subscribe to it: - - ```csharp - protected override void TsStart() - { - _ts.SubscribeLanguageChanged(this, nameof(_OnLanguageChanged)); - } - - public void _OnLanguageChanged() => RefreshCustomWidgets(); - ``` - -## Checking for missing translations - -Open **Tsvrc > Translation** and look at the scene preview list below the language -files. It flags any `_key_`-named text object whose key doesn't appear in a loaded -language file, so a missing entry surfaces there instead of only failing silently at -runtime (a missing key just falls back to showing the raw key itself, never an empty -string or an exception). - -## Why this shape - -See the [`TranslationModule` reference page](../codegen/modules/translation-module) for -exactly how a text object is discovered as a translation target, why the batch -application spreads across multiple frames instead of updating everything at once, and -the required `"key"`/`"label"`/`"entries"` shape a language file must have. diff --git a/docs/core/how-to/adding-a-screen-state-machine.md b/docs/core/how-to/adding-a-screen-state-machine.md deleted file mode 100644 index 49e8d38..0000000 --- a/docs/core/how-to/adding-a-screen-state-machine.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -id: adding-a-screen-state-machine -title: Give a screen or flow its own state machine -sidebar_position: 12 ---- - -# Give a screen or flow its own state machine - -How to drive a UI screen or a local flow (idle → loading → active → done) through named -states with enter/exit callbacks, using [`StateManager`](../game-flow/state-manager) -instead of a pile of booleans. - -## Steps - -1. Spawn one for the screen or flow that needs it. `StateManager` ships as [one of - the Core default factory entries](../explanations/builtin-registrations), so - there's nothing to register on the Configure window first. Give each screen its own - instance rather than sharing one across unrelated screens: - - ```csharp - public class SettingsScreen : TsBehaviour - { - private const int StateIdle = 0; - private const int StateLoading = 1; - private const int StateReady = 2; - - [SerializeField] private GameObject _panel; - [SerializeField] private GameObject _spinner; - private StateManager _state; - - protected override void TsStart() - { - _state = _ts.CreateStateManager(transform); - _state.RegisterState(StateIdle, this, enterMethod: nameof(OnEnterIdle)); - _state.RegisterState(StateLoading, this, enterMethod: nameof(OnEnterLoading), exitMethod: nameof(OnExitLoading)); - _state.RegisterState(StateReady, this, enterMethod: nameof(OnEnterReady)); - _state.SetState(StateIdle); - } - - public void OnEnterIdle() => _panel.SetActive(false); - public void OnEnterLoading() => _spinner.SetActive(true); - public void OnExitLoading() => _spinner.SetActive(false); - public void OnEnterReady() => _panel.SetActive(true); - } - ``` - -2. Trigger transitions from wherever your own logic decides, not from inside another - state's own enter/exit method chain: - - ```csharp - public void StartLoadingSettings() => _state.SetState(StateLoading); - ``` - -3. If something outside this screen needs to react to every transition generically - (analytics, a shared loading spinner), subscribe to the state manager's own event - instead of duplicating calls at every `SetState` call site: - - ```csharp - _state.TsSubscribe(this, "OnStateChanged", nameof(_OnAnyStateChanged)); - ``` - -## Why one instance per screen - -A `StateManager` instance only knows the states you've registered on it. Sharing one -across unrelated screens means their state numbers collide (`StateLoading = 1` on one -screen is a different concept than `StateLoading = 1` on another) unless you're careful -to give every screen's states globally unique numbers. A fresh instance per screen avoids -that entirely, and costs nothing extra: `_ts.CreateStateManager` is a cheap, local, -non-networked spawn. - -## Why this shape - -See the [`StateManager` reference page](../game-flow/state-manager) for what happens if an -enter/exit method or a subscriber throws mid-transition, how a reentrant `SetState` call -from inside an enter/exit method is queued rather than interleaved, and why `StateManager` -needs no `TsConstruct` at all if you want to skip the factory and use one completely -manually. diff --git a/docs/core/how-to/assigning-player-colors.md b/docs/core/how-to/assigning-player-colors.md deleted file mode 100644 index c5eba50..0000000 --- a/docs/core/how-to/assigning-player-colors.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -id: assigning-player-colors -title: Give each player a unique color -sidebar_position: 10 ---- - -# Give each player a unique color - -How to give every player in the instance a distinct, stable color every client agrees on -(for markers, name tags, team indicators), using -[`PlayerColorAssigner`](../players-tracking/player-color-assigner). - -## Steps - -1. Add one `PlayerColorAssigner` to your scene. It never overrides `TsStart` and doesn't - touch `_ts`, so there's no Configure registration step at all, just drop it in. - Since it syncs a shuffled color order (`[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]`), - it needs to be a real object present when the world starts rather than something you - spawn later: manual placement, not Factory. -2. Call `Initialize()` once, from wherever your world does one-time setup, before the - first `GetColor` call: - - ```csharp - public class TeamMarkers : TsBehaviour - { - [SerializeField] private PlayerColorAssigner _colors; - - protected override void TsStart() - { - _colors.Initialize(); - } - } - ``` - -3. Look up a player's color wherever you need it, keyed by their `TsPlayer`-format ID: - - ```csharp - public Color GetMarkerColor(VRCPlayerApi player) => - _colors.GetColor(TsPlayer.GetPlayerID(player)); - ``` - -If more than one behaviour needs matching colors, share this one instance (a Global or a -plain serialized reference) rather than adding a second `PlayerColorAssigner`. A second -instance would shuffle its own, independent order and disagree with the first about which -color belongs to which player. - -## Why this shape - -See the [`PlayerColorAssigner` reference page](../players-tracking/player-color-assigner) -for why the palette is shuffled per instance instead of used in raw ID order, and why -`GetColor` is always safe to call even before `Initialize` has run anywhere. diff --git a/docs/core/how-to/building-a-list-ui.md b/docs/core/how-to/building-a-list-ui.md deleted file mode 100644 index 0dff0df..0000000 --- a/docs/core/how-to/building-a-list-ui.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -id: building-a-list-ui -title: Build a paginated list UI -sidebar_position: 15 ---- - -# Build a paginated list UI - -How to show a scrollable, paginated list of rows (a leaderboard, a settings list, a -roster) that reuses a fixed pool of row instances instead of instantiating one per -entry, using [`TsvrcList`](../ui-components/list/tsvrc-list) and -[`ListItem`](../ui-components/list/list-item). - -## Steps - -1. In the scene, add a `TsvrcList` next to a `ScrollRect`. Assign the `ScrollRect` - `Content` transform as its item container, a prefab carrying your `ListItem` - subclass as its item prefab, and a page size (or `-1` to show every row without - pagination) in the Inspector. -2. Subclass `ListItem` to populate one row from its bound data: - - ```csharp - public class LeaderboardRow : ListItem - { - [SerializeField] private TextMeshProUGUI _nameText; - [SerializeField] private TextMeshProUGUI _scoreText; - - protected override void _OnBind() - { - _nameText.text = _itemData.GetValue("name").String; - _scoreText.text = _itemData.GetValue("score").Int.ToString(); - } - } - ``` - - Wire the row prefab's own button, if it has one, to call `_OnItemPressed()` from its - `OnClick`. That's what tells the owning list which row was selected. - -3. Feed it data and react to a selection: - - ```csharp - public class LeaderboardController : TsBehaviour - { - [SerializeField] private TsvrcList _list; - - protected override void TsStart() - { - _list.TsSubscribe(this, TsvrcList.OnItemSelectedEvent, nameof(_OnRowSelected)); - } - - public void ShowLeaderboard(DataList entries) => _list.SetData(entries); - - public void _OnRowSelected() => LogInfo("Selected index " + _list.SelectedIndex); - } - ``` - -4. Move between pages with `_list.NextPage()`/`PreviousPage()`, and check - `_list.HasNextPage`/`HasPreviousPage` to enable or disable your own page buttons. - -## Showing a loading state - -Call `_list.SetLoadingState()` before you have data ready (while waiting on a -[`DataTransferer`](./transferring-data-between-clients) or similar), then `SetData` once -it arrives. Passing `null` or an empty list to `SetData` shows the empty state instead, -if one's assigned in the Inspector. - -## Why this shape - -See the [`TsvrcList`](../ui-components/list/tsvrc-list) and -[`ListItem`](../ui-components/list/list-item) reference pages for exactly how row -instances get reused across pages instead of destroyed and recreated, and what -`Bind`/`Unbind` guarantee about the lifetime of `_itemData` inside `_OnUnbind`. diff --git a/docs/core/how-to/combining-meshes.md b/docs/core/how-to/combining-meshes.md deleted file mode 100644 index e65ff1b..0000000 --- a/docs/core/how-to/combining-meshes.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -id: combining-meshes -title: Combine meshes and colliders before uploading -sidebar_position: 17 ---- - -# Combine meshes and colliders before uploading - -How to merge a group of static scene objects into one multi-material mesh, and their -colliders where possible, to cut down draw calls before you upload, using -**Tsvrc > Tools > Mesh Combiner**. - -## Steps - -1. Select the scene objects you want combined (a wall of individual rocks, a set of - static props), then open **Tsvrc > Tools > Mesh Combiner**. -2. Click **Load from Selection**. This also picks up any GameObject with a collider but - no `MeshFilter` (a collider-only source) and any GameObject with a `ParticleSystem` - but no `MeshFilter`, without needing its own slot. -3. Choose a save path for the combined mesh asset, leave **Exclude EditorOnly** and - **Combine Colliders** on unless you have a reason not to, and click **Combine**. - -The tool creates one new GameObject with the combined `MeshFilter`/`MeshRenderer` (and a -`MeshCollider` if any solid colliders were merged), one child per recreated primitive or -trigger collider, and deactivates the sources (or, for a source carrying an -`UdonSharpBehaviour`, only disables its `MeshRenderer` so the script and its own collider -keep working). - -## Deciding whether to recalculate normals - -Leave **Recalculate Normals** off (the default) to preserve baked or hand-authored -normals from the source meshes. Turn it on only if the sources own normals don't look -right once merged, since recalculating from the combined geometry can smooth over -intentional hard edges. - -## If you change your mind - -Undo reverses the new GameObject, the recreated collider children, and the source -deactivation as one step. It doesn't remove the saved mesh asset file (and the -`_Collider` asset alongside it, if one was created): the Unity Undo system doesn't -track saving an asset to disk. Delete those files by hand if you undo a combine you -don't want to keep. - -## Why this shape - -See [the Mesh Combiner reference page](../utilities/mesh-combiner) for exactly which -colliders merge versus get recreated as children, how a source carrying an -`UdonSharpBehaviour` is handled differently throughout, and the two conditions that -disable the Combine button outright rather than letting it produce a broken result. diff --git a/docs/core/how-to/guarding-against-head-clipping.md b/docs/core/how-to/guarding-against-head-clipping.md deleted file mode 100644 index 8b01e1c..0000000 --- a/docs/core/how-to/guarding-against-head-clipping.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -id: guarding-against-head-clipping -title: Stop VR players clipping through walls -sidebar_position: 11 ---- - -# Stop VR players clipping through walls - -How to push a VR player's head back out when it clips through solid geometry, using -[`HeadClipGuard`](../players-tracking/head-clip-guard), and how to make it an optional -comfort setting rather than something every world forces on. - -## Steps - -1. Spawn one with the generated factory method. `HeadClipGuard` ships as [one of the Core - default factory entries](../explanations/builtin-registrations), so there's - nothing to register on the Configure window first: - - ```csharp - public class ComfortSettings : TsBehaviour - { - [SerializeField] private BoxCollider[] _wallColliders; - private HeadClipGuard _guard; - - public void EnableHeadClipGuard() - { - if (_guard == null) - { - _guard = _ts.CreateHeadClipGuard(transform); - } - _guard.Begin(_wallColliders, _wallColliders.Length); - } - - public void DisableHeadClipGuard() => _guard?.End(); - } - ``` - -2. Call `EnableHeadClipGuard`/`DisableHeadClipGuard` from wherever your world's own - comfort settings toggle lives. `Begin`/`End` are cheap to call repeatedly: `End` - fully resets the guard's state, so the same instance can be reused across multiple - guarded sessions instead of spawning a fresh one each time. - -## Only guard the geometry that needs it - -Pass just the colliders around the specific area a player could clip through (a wall -ring, a doorway frame), not every collider in the world: `Begin` bakes each one's world -transform once and the guard re-evaluates all of them every frame it's active. - -## Why this shape - -See the [`HeadClipGuard` reference page](../players-tracking/head-clip-guard) for how it -decides which direction to push, the three-tier movement gate/batch-scan/full-test -pipeline that keeps per-frame cost down with many colliders, and the two tunable -invariants (`_margin`, `_batchScanExpansion`) worth understanding before changing them. diff --git a/docs/core/how-to/persisting-a-value.md b/docs/core/how-to/persisting-a-value.md deleted file mode 100644 index c323f50..0000000 --- a/docs/core/how-to/persisting-a-value.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -id: persisting-a-value -title: Persist a value across visits -sidebar_position: 6 ---- - -# Persist a value across visits - -How to save a value for the local player that's still there the next time they load your -world, using the persistent tier of [`TsvrcMemory`](../networking-data/tsvrc-memory). No -registration or pooling is needed to reach it at all: it's always available as `_ts.Memory`. - -## Steps - -1. Pick a key and register it as persistent, once, before you ever read or write it: - - ```csharp - public class AudioSettings : TsBehaviour - { - private const string VolumeKey = "musicVolume"; - - protected override void TsStart() - { - _ts.Memory.Register(VolumeKey, persist: true, synced: false); - _ts.Memory.Add(VolumeKey, new DataToken(1f)); - } - } - ``` - - `Add` seeds a default without overwriting a value VRChat may have already restored by - the time `TsStart` runs. - -2. Read and write it like any other value: - - ```csharp - public float GetVolume() => _ts.Memory.GetFloat(VolumeKey); - - public void SetVolume(float value) => _ts.Memory.Set(VolumeKey, new DataToken(value)); - ``` - -3. If your UI needs to reflect the restored value the moment it becomes available, react to - [`OnPlayerRestored`](https://creators.vrchat.com/worlds/udon/persistence/player-data/#events) - rather than assuming `TsStart` already has it: VRChat restores `PlayerData` - asynchronously, and `TsvrcMemory` only has a real value to read once that fires. - - ```csharp - [SerializeField] private Slider _volumeSlider; // add this field to AudioSettings too - - public override void OnPlayerRestored(VRCPlayerApi player) - { - if (!player.isLocal) return; - _volumeSlider.value = _ts.Memory.GetFloat(VolumeKey); - } - ``` - -Call `Add` or `Set` on the key before this point too (step 1 already does), since -`TsvrcMemory` only knows which typed accessor to restore with once a value has been -written at least once. - -## Letting a feature own its own keys - -A key doesn't have to be registered from your world root. Give each feature module a -static method that registers and seeds its own keys, and call it once from wherever your -world already does one-time setup: - -```csharp -public static class DifficultySettings -{ - public const string DifficultyKey = "difficulty"; - - public static void Register(TsvrcMemory memory) - { - memory.Register(DifficultyKey, persist: true, synced: false); - memory.Add(DifficultyKey, new DataToken(1)); - } -} -``` - -```csharp -protected override void TsStart() -{ - DifficultySettings.Register(_ts.Memory); - // ...one line per feature module that owns its own persisted keys. -} -``` - -This keeps a feature's own persisted keys next to the feature that owns them instead of -piling every key into one root class as the world grows. - -## Why this shape - -See the [`TsvrcMemory` reference page](../networking-data/tsvrc-memory) for the full -contract: the three isolated tiers (ephemeral/persistent/synced), why `Add` and `Set` -behave differently, the VRChat PlayerData size and timing limits, and what happens if -you register the same key twice or write to it before it's restored. diff --git a/docs/core/how-to/pooling-a-prefab.md b/docs/core/how-to/pooling-a-prefab.md deleted file mode 100644 index b228919..0000000 --- a/docs/core/how-to/pooling-a-prefab.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -id: pooling-a-prefab -title: Pool a prefab instead of instantiating it -sidebar_position: 2 ---- - -# Pool a prefab instead of instantiating it - -How to get a networked-safe instance of a behaviour at runtime, using -[`[WirePool]`](../core-concepts/attributes.md#wirepoolattribute) and -[`PoolModule`](../codegen/modules/pool-module) instead of `Instantiate`. See -[the pooling pattern](../explanations/pooling-pattern) for why `Instantiate` isn't an option -here at all. - -## Steps - -1. Register the prefab's type as a pool entry on the Configure window's **Pools** tab (backed - by `TsConfig.PoolEntries`), then click **Apply** in the window's pending-changes - footer. That's a direct edit to `TsConfig` made through the window, so it's batched - behind Apply/Discard like any other Configure tab edit: see - [`TsWindow`](../codegen/config/ts-window#apply--discard) for why, or - [try it on a live mockup of the window](../codegen/config/ts-window#try-it). - Registration alone - creates no slots yet, since nothing references the type as `[WirePool]` yet. -2. Declare a `[WirePool]` field for it on whatever behaviour needs an instance: - - ```csharp - public class EnemySpawner : TsBehaviour - { - [WirePool("used when a wave spawns an enemy")] - public EnemyController slot; - - [SerializeField] private Transform spawnPoint; - } - ``` - - This is a code change, not a Configure window edit, so it needs no Apply click at all: - once Unity finishes compiling, the Core generator runs automatically and discovers the - field by reflection. `PoolModule` computes how many total slots the project needs - across every `[WirePool]` field referencing this type, generates one serialized field - per slot, and instantiates and wires them all under a `"Pool"` container at wire time. -3. Use the field like any other reference once the scene has regenerated. It's already a - real, scene-resident instance by the time your code runs, not something you create: - - ```csharp - protected override void TsStart() - { - slot.BeginPatrol(spawnPoint); - } - ``` - -## Pooling a type that itself needs a pooled dependency - -A pooled type can declare its own `[WirePool]` field for a second pooled type. -`PoolModule` resolves the dependency graph so the second type's slot count accounts for -every instance of the first: - -```csharp -public class EnemyController : TsvrcBehaviour -{ - [WirePool] - public HitEffect impactEffectSlot; // one HitEffect instance per EnemyController instance -} -``` - -## If the slot stays null - -Check the Console for a `PoolModule` warning first: a `[WirePool]` field whose type was -never registered on the Pools tab logs a warning and leaves the field `null` forever, -rather than failing generation outright. Registering the type and regenerating resolves -it. - -If the field's type is one of the Core runtime types (`PlayerTracker`, `TsvrcTimer`, -and four others), skip step 1 entirely: it's already registered for you. See [Decision -note: builtin pool and factory entries](../explanations/builtin-registrations). - -## Why this shape - -See [the pooling pattern](../explanations/pooling-pattern) for the underlying VRChat -networking constraint this works around, and the [`PoolModule` reference page](../codegen/modules/pool-module) -for the exact slot-count formula and what happens on a broken compile mid-generation. diff --git a/docs/core/how-to/reaching-a-scene-object.md b/docs/core/how-to/reaching-a-scene-object.md deleted file mode 100644 index c5a802f..0000000 --- a/docs/core/how-to/reaching-a-scene-object.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -id: reaching-a-scene-object -title: Reach a scene object from anywhere, or guarantee it initializes -sidebar_position: 13 ---- - -# Reach a scene object from anywhere, or guarantee it initializes - -How to register a scene object on the Configure window so codegen wires it up for you, -using either a **Global** (to name it and reach it from any script) or a **Construct** -(to guarantee it initializes, with no name at all). - -## Choosing between them - -Register something as a **Construct** when you only need it initialized (its `TsStart` -to actually run) and nothing else needs to reference it by name. Register it as a -**Global** when another behaviour needs to reach it as `_ts.Name` from anywhere in the -project. Register it as both if you need both: a Global entry that happens to be a -`TsvrcBehaviour` gets constructed too, so there's no conflict. - -## Steps: registering a Global - -1. Open **Tsvrc > Configure**, select the **Globals** tab, and drag the scene object in. - Give it an explicit name, or leave it blank to derive one from the object/component - name. -2. Click **Apply** in the window's pending-changes footer. That's what turns this - registration into generated code: dragging the object in only stages the edit, - **Force Regenerate** stays disabled while it's unapplied, and the automatic trigger - that normally regenerates for you is suppressed for the same reason. See - [`TsWindow`](../codegen/config/ts-window#apply--discard) for why edits made in this - window are batched behind Apply/Discard instead of regenerating on every keystroke, or - [try the flow on a live mockup of the window](../codegen/config/ts-window#try-it). -3. Reach it from any script by the generated field name: - - ```csharp - public class ScoreboardController : TsBehaviour - { - protected override void TsStart() - { - _ts.ScoreboardAnimator.SetTrigger("Refresh"); - } - } - ``` - -Any scene object works as a Global, not just a `TsvrcBehaviour`, since the whole point -of a Global is naming, not initialization. A plain `GameObject` or an arbitrary `Component` -reference is exposed the same way, just never constructed. - -## Steps: registering a Construct - -1. Open **Tsvrc > Configure**, select the **Constructs** tab, and drag the behaviour in. - There's nothing to name. -2. Click **Apply** in the window's pending-changes footer, same as for a Global above. - `TsStart` on that behaviour now runs at world start, whether or not anything else in - the project ever references it: - - ```csharp - public class HelloWorld : TsBehaviour - { - protected override void TsStart() - { - LogInfo("HelloWorld constructed."); - } - } - ``` - -3. If something else later needs a direct reference to it, wire it the ordinary Unity - way (a serialized field assigned in the Inspector), or register it as a Global too if - you need it reachable by name. - -A Construct must be a component and must be a `TsvrcBehaviour`; unlike a Global, an -arbitrary `GameObject` reference doesn't qualify. - -## Why this shape - -See the [`GlobalModule`](../codegen/modules/global-module) and -[`ConstructModule`](../codegen/modules/construct-module) reference pages for how each -derives a default name, what happens on a name collision, and how tree-shaking can -exclude an unused Global if your project has `TreeShakeUnused` turned on. diff --git a/docs/core/how-to/running-a-countdown.md b/docs/core/how-to/running-a-countdown.md deleted file mode 100644 index e6cfd67..0000000 --- a/docs/core/how-to/running-a-countdown.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -id: running-a-countdown -title: Run a synced countdown -sidebar_position: 7 ---- - -# Run a synced countdown - -How to run a countdown every client sees identically, using -[`TsvrcTimer`](../networking-data/tsvrc-timer). - -## Steps - -1. Declare a `[WirePool]` field. `TsvrcTimer` ships as [one of the Core default pool - entries](../explanations/builtin-registrations), so there's nothing to register on the - Configure window first: - - ```csharp - public class RoundClock : TsBehaviour - { - [WirePool][SerializeField] private TsvrcTimer _timer; - [SerializeField] private TextMeshProUGUI _countdownText; - - protected override void TsStart() - { - _timer.TsSubscribe(this, TsvrcTimer.OnTimerCompletedEvent, nameof(_OnRoundEnded)); - } - - public void StartRound() => _timer.StartTimer(60_000); // 60 seconds - - public void _OnRoundEnded() => LogInfo("Round timer finished."); - } - ``` - -2. Read the remaining time from your own per-frame update, not from - `OnTimerUpdatedEvent`: that event exists for reacting to a state change (started, - paused, completed), not for driving a UI redraw every frame. - - ```csharp - private void Update() - { - if (!_timer.IsProcessRunning()) return; - int seconds = (int)_timer.GetRemainingSeconds(); - _countdownText.text = $"{seconds / 60:00}:{seconds % 60:00}"; - } - ``` - -3. Pause and resume it from anywhere, owner or not; both forward to the real owner over - the network if the caller isn't it: - - ```csharp - public void PauseRound() => _timer.PauseTimer(); - public void ResumeRound() => _timer.ResumeTimer(); - ``` - -## Reacting to a late joiner mid-round - -A client that joins while the timer is already running still needs its `_countdownText` -to catch up. Read the current state once in `TsStart` instead of assuming `StartTimer` -already ran on this client: - -```csharp -protected override void TsStart() -{ - _timer.TsSubscribe(this, TsvrcTimer.OnTimerCompletedEvent, nameof(_OnRoundEnded)); - - if (_timer.IsProcessRunning()) - { - _countdownText.gameObject.SetActive(true); - } -} -``` - -## Why this shape - -See the [`TsvrcTimer` reference page](../networking-data/tsvrc-timer) for the full event -table, how pausing interacts with the timer's own auto-complete check, and the two sharp -edges around detecting a late joiner or a stop-then-restart landing in the same network -packet. diff --git a/docs/core/how-to/running-a-timed-round.md b/docs/core/how-to/running-a-timed-round.md deleted file mode 100644 index ee071e4..0000000 --- a/docs/core/how-to/running-a-timed-round.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -id: running-a-timed-round -title: Run a full timed round with a lobby -sidebar_position: 9 ---- - -# Run a full timed round with a lobby - -How to drive a complete round, players gather in a lobby, a ready check gates the start, -a timed round runs with completion tracking, then the round ends, using -[`RankedGameSession`](../game-flow/ranked-game-session) instead of hand-rolling the lobby, -ready check, and timer yourself. - -## Steps - -1. Declare a `[WirePool]` field. `RankedGameSession` ships as [one of the Core default - pool entries](../explanations/builtin-registrations), so there's nothing to register on - the Configure window first: - - ```csharp - public class MatchController : TsBehaviour - { - [WirePool][SerializeField] private RankedGameSession _match; - - protected override void TsStart() - { - _match.TsSubscribe(this, RankedGameSession.OnSessionStartedEvent, nameof(_OnMatchStarted)); - _match.TsSubscribe(this, RankedGameSession.OnSessionEndedEvent, nameof(_OnMatchOver)); - _match.TsSubscribe(this, RankedGameSession.OnSessionStoppedEvent, nameof(_OnMatchOver)); - } - } - ``` - -2. Build the lobby before you ever start a round, and let players join and leave it - freely: - - ```csharp - protected override void TsStart() - { - // ...continued from above - _match.StartLobbyTracking(); - } - - public void OnPlayerRequestsToJoin(string playerId) => _match.AddLobbyPlayer(playerId); - ``` - -3. Start the round from the lobby roster once you're ready to begin. This snapshots who's - in the lobby and starts a ready check over them: - - ```csharp - public void BeginMatch() => _match.StartSession(); - ``` - - Each client marks itself ready from wherever your own UI exposes that: - - ```csharp - public void PlayerIsReady() => _match.SetReady(); - ``` - -4. React to the round actually starting (the ready check completed) and to it ending: - - ```csharp - public void _OnMatchStarted() => LogInfo("Match started with " + _match.LobbyPlayerIds.Length + " players."); - - public void _OnMatchOver() - { - // GamePlayerIds/CompletedPlayerIds are unreliable here, the sub-trackers are - // already being torn down. Use the snapshot instead. - foreach (string playerId in _match.LastEndedCompletedPlayerIds) - { - AwardCompletionReward(playerId); - } - } - ``` - -5. Mark a player finished as your own game logic decides: - - ```csharp - public void OnPlayerFinishedTheRound(string playerId) => _match.AddCompletedPlayer(playerId); - ``` - -## Choosing what ends a round - -`RankedGameSession` never invents its own win condition. Toggle whichever combination of -its Inspector-exposed end conditions your game actually needs (a countdown running out, -every active player having left, or every active player having completed) instead of -polling for them yourself, and call `StopSession()` for anything else (a host command, a -vote to end early). See [the reference page](../game-flow/ranked-game-session#ending-a-session) -for exactly what each condition maps to on `LastEndReason`. - -## Reading a specific player's status - -`GetPlayerStatus(playerId)` answers "where is this player right now" (not in the -session, in the lobby, loading, playing, or completed) from state that's already -available, so you don't have to cross-reference `LobbyPlayerIds`/`GamePlayerIds`/ -`CompletedPlayerIds` by hand: - -```csharp -public bool IsPlayerStillPlaying(string playerId) => - _match.GetPlayerStatus(playerId) == RankedGamePlayerStatus.Playing; -``` - -## Why this shape - -See the [`RankedGameSession` reference page](../game-flow/ranked-game-session) for the full -state machine, the nine lifecycle events, and a real asymmetry worth knowing before you -build a networked "force stop" button: `StopSession` reaches every client automatically -during the lobby's ready check, but not once a round is already in progress. diff --git a/docs/core/how-to/set-up-automated-testing.md b/docs/core/how-to/set-up-automated-testing.md deleted file mode 100644 index bc9b894..0000000 --- a/docs/core/how-to/set-up-automated-testing.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -id: set-up-automated-testing -title: Set up automated testing -sidebar_position: 5 ---- - -# Set up automated testing - -Set up your project for Play Mode and Edit Mode tests against your own `UdonSharpBehaviour`s, -written with [Udon Test Kit](/docs/udon-test-kit/intro). - -## 1. Put your scripts and generated code in one assembly - -The code Core generates declares the base types your world scripts extend (`TsBehaviour`, -`TsInstance`, and so on), and in turn references concrete types from your own scripts: a -Construct or Factory entry generates a field typed as whatever class you registered. That's -a two-way dependency, and Unity doesn't allow two assembly definitions to reference each -other. Give your project's own scripts folder a single `asmdef` placed high enough in the -folder tree to cover both your hand-written scripts and wherever the generated-folder -setting in your `TsConfig` points (they don't need to be nested inside each other, just both -under that one asmdef's root), referencing `Tsvrc.Runtime` plus whatever VRChat SDK/ -UdonSharp assemblies your scripts use. - -## 2. Create your test assemblies - -Core depends on Udon Test Kit, so the kit is already in your project. Create your test -assemblies with its menu item, as described in -[Create your test assemblies](/docs/udon-test-kit/add-to-your-project#create-your-test-assemblies). -They already reference the kit, the VRChat SDK, ClientSim and your project's assembly from -step 1. - -## 3. Reference Tsvrc.Runtime - -Add `Tsvrc.Runtime` to the references of the `EditMode` and `PlayMode` test assemblies if it isn't -listed already, and to the `Doubles` assembly if your test doubles extend Core types. - -That's all. The Core codegen holds back on its own while tests run, so nothing else needs -arming. [Testing your world](../testing/testing-your-world) covers how a test builds your -behaviours. diff --git a/docs/core/how-to/showing-player-positions.md b/docs/core/how-to/showing-player-positions.md deleted file mode 100644 index c12fec1..0000000 --- a/docs/core/how-to/showing-player-positions.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -id: showing-player-positions -title: Show player positions on an overlay -sidebar_position: 4 ---- - -# Show player positions on an overlay - -How to render a live minimap-style overlay of tracked players, using -[`PlayerPositionOverlay`](../ui-components/overlay/player-position-overlay) (itself a -[`PlayerTracker`](../players-tracking/player-tracker), no separate tracker component needed) and -[`RasterPlayerMarkerRenderer`](../ui-components/overlay/raster-player-marker-renderer). - -## Steps - -1. Add a `PlayerPositionOverlay` to your scene and register it as a construct, so codegen calls - `TsConstruct` on it at startup. The renderer needs no registration: neither - `PlayerMarkerRenderer` nor `RasterPlayerMarkerRenderer` uses `TsStart` or `_ts`, so drop one - into the scene and assign it. -2. Subclass `RasterPlayerMarkerRenderer` to decide what a marker looks like: - - ```csharp - public class DotMarkerRenderer : RasterPlayerMarkerRenderer - { - public override void DrawMarker(Color32[] pixelBuffer, int textureWidth, int textureHeight, - int pixelX, int pixelY, bool isLocalPlayer, float headingDegrees, string playerId) - { - Color32 color = isLocalPlayer ? Color.green : Color.red; - TextureGraphics2D.DrawCircleToBuffer(pixelBuffer, textureWidth, textureHeight, pixelX, pixelY, 4, color); - } - } - ``` - -3. Wire the output texture of the renderer to a `RawImage` in your UI, then configure and start - the overlay: - - ```csharp - public class MinimapController : TsBehaviour - { - [SerializeField] private PlayerPositionOverlay _overlay; - [SerializeField] private DotMarkerRenderer _renderer; - [SerializeField] private Transform _mapOrigin; - - protected override void TsStart() - { - _renderer.Setup(width: 256, height: 256, worldOrigin: _mapOrigin.position, unitsPerGridX: 4f, unitsPerGridZ: 4f); - _overlay.Renderer = _renderer; - _overlay.StartOverlay(new string[0]); - } - } - ``` - -4. Add or remove players while it runs with the tracking methods the overlay inherits, - `_overlay.AddTrackedPlayers(playerIds)` and `RemoveTrackedPlayers(playerIds)`. The renderer - picks up the change on its next tick with no extra wiring. - -If only a subset of players should ever appear (not everyone in the instance), start the -overlay with that explicit ID list instead of an empty one. - -## Swapping the drawing style - -`RasterPlayerMarkerRenderer` handles the texture, pixel buffer, and flush timing; only -`DrawMarker` decides the visuals, so a different look (a triangle that rotates with heading, -say) is a different `DrawMarker` body, not a different setup: - -```csharp -public override void DrawMarker(Color32[] pixelBuffer, int textureWidth, int textureHeight, - int pixelX, int pixelY, bool isLocalPlayer, float headingDegrees, string playerId) -{ - TextureGraphics2D.DrawTriangleToBuffer(pixelBuffer, textureWidth, textureHeight, pixelX, pixelY, 5, 5, headingDegrees, someColor); -} -``` - -## Skipping the raster renderer - -If you're not drawing to a texture at all (driving 3D world-space marker objects instead, -for example), implement [`PlayerMarkerRenderer`](../ui-components/overlay/player-marker-renderer) -directly instead of its raster subclass. `PlayerPositionOverlay` only calls the two methods of the -base class. - -## Why this shape - -`PlayerPositionOverlay` is a pure backend that never draws anything itself. See its -[reference page](../ui-components/overlay/player-position-overlay) for why presentation is split -out into a pluggable renderer, and what the two independent tick loops (position resolution -vs. blink) cost on their own. diff --git a/docs/core/how-to/spawning-a-local-object.md b/docs/core/how-to/spawning-a-local-object.md deleted file mode 100644 index c1173eb..0000000 --- a/docs/core/how-to/spawning-a-local-object.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -id: spawning-a-local-object -title: Spawn a local, non-networked object on demand -sidebar_position: 14 ---- - -# Spawn a local, non-networked object on demand - -How to instantiate your own prefab at runtime for something purely local (a hit-spark -VFX, a one-off UI popup), using [`FactoryModule`](../codegen/modules/factory-module) -instead of `Instantiate`. - -Reach for this only when the object doesn't need to be seen by other players. For -anything a networked, [pool a prefab](./pooling-a-prefab) instead: a factory-created -object never receives a VRChat network ID and can't send or receive network events. - -## Steps - -1. Register the prefab on the Configure window's **Factories** tab, inside a group if - you want its generated method name namespaced. -2. Click **Apply** in the Configure window's pending-changes footer. **Force Regenerate** - and the automatic trigger both stay disabled while this edit is unapplied, so Apply is - what actually runs codegen here; see [`TsWindow`](../codegen/config/ts-window#apply--discard) - for why, or [try it on a live mockup of the window](../codegen/config/ts-window#try-it). - `FactoryModule` then generates one `Create{Group}{Name}(Transform parent)` - method per registered prefab. -3. Call it wherever you need a fresh instance: - - ```csharp - public class HitEffectSpawner : TsBehaviour - { - public void PlayHitEffect(Vector3 position) - { - var vfx = _ts.CreateHitSpark(transform); - vfx.transform.position = position; - } - } - ``` - - The returned instance is already active and, if the prefab's root is a - `TsvrcBehaviour`, already `TsConstruct`ed. A plain `GameObject` prefab with no - `TsvrcBehaviour` root returns the `GameObject` itself instead of a typed component. - -## Registering the same prefab under more than one group - -Spawning the same prefab from two different named groups (an "Enemies" group and a -"Traps" group both spawning the same projectile, say) is a legitimate, supported case, -not flagged as a conflict: each group gets its own, separately-named `Create` method for -the same prefab. - -## Why this shape - -See the [`FactoryModule` reference page](../codegen/modules/factory-module) for how the -instantiation source is a pre-instantiated, inactive template rather than the raw prefab -asset, and why that specific detail is what makes factory-created objects fast to spawn -repeatedly. See [Decision note: builtin pool and factory entries](../explanations/builtin-registrations) -for the deeper reason a factory-created object can never be synced, not just a rule to -follow but a consequence of how `Instantiate` itself works in Udon. diff --git a/docs/core/how-to/tracking-a-group-of-players.md b/docs/core/how-to/tracking-a-group-of-players.md deleted file mode 100644 index 25c4f61..0000000 --- a/docs/core/how-to/tracking-a-group-of-players.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -id: tracking-a-group-of-players -title: Track a custom group of players -sidebar_position: 8 ---- - -# Track a custom group of players - -How to maintain a synced roster of players for something narrower than "everyone in the -instance", using [`PlayerTracker`](../players-tracking/player-tracker) directly instead of -[`AutoPlayerTracker`](../players-tracking/auto-player-tracker). - -## When to use which - -Use `AutoPlayerTracker` when the roster is every player in the instance: it needs no add or remove -calls of your own. Use a plain `PlayerTracker` when the roster is a subset you decide, such as -players in an area, in a queue or on a team, since `AutoPlayerTracker` always tracks everyone. - -## Steps - -1. Declare a `[WirePool]` field. `PlayerTracker` ships as [one of the Core default pool - entries](../explanations/builtin-registrations), so there's nothing to register on the - Configure window first: - - ```csharp - public class SpectatorRoster : TsBehaviour - { - [WirePool][SerializeField] private PlayerTracker _spectators; - - protected override void TsStart() - { - _spectators.TsSubscribe(this, PlayerTracker.OnTrackingPlayersAddedEvent, nameof(_OnRosterChanged)); - _spectators.TsSubscribe(this, PlayerTracker.OnTrackingPlayersRemovedEvent, nameof(_OnRosterChanged)); - _spectators.StartPlayerTracking(new string[0]); - } - - public void _OnRosterChanged() => LogInfo(_spectators.LastPlayerIds.Length + " spectators."); - } - ``` - -2. Add or remove players as your own logic decides, for example when a player enters or - leaves a trigger volume: - - ```csharp - public override void OnPlayerTriggerEnter(VRCPlayerApi player) - { - _spectators.AddTrackedPlayers(new[] { TsPlayer.GetPlayerID(player) }); - } - - public override void OnPlayerTriggerExit(VRCPlayerApi player) - { - _spectators.RemoveTrackedPlayers(new[] { TsPlayer.GetPlayerID(player) }); - } - ``` - - A player who leaves the instance or gets suspended is removed automatically; you never - need to handle that yourself. - -3. Read the roster from `LastPlayerIds` inside any `OnTracking*` callback. The owner manages the - set: `AddTrackedPlayers` and `RemoveTrackedPlayers` called by another player go to the owner - over the network. - -## Why this shape - -See the [`PlayerTracker` reference page](../players-tracking/player-tracker) for the events, when a -`Notify*` broadcast fires compared to when `LastPlayerIds` updates, and the three cases that remove -a player automatically: leaving, being suspended, or a new owner taking over the tracker. diff --git a/docs/core/how-to/transferring-data-between-clients.md b/docs/core/how-to/transferring-data-between-clients.md deleted file mode 100644 index da61728..0000000 --- a/docs/core/how-to/transferring-data-between-clients.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -id: transferring-data-between-clients -title: Send a string payload to other players -sidebar_position: 3 ---- - -# Send a string payload to other players - -How to move an arbitrary string from one client to a set of others, using -[`DataTransferer`](../networking-data/data-transfer/data-transferer) to handle chunking, sequencing, and -reassembly for you. See [the chain overview](../networking-data/overview.md) if you want to -understand what's happening underneath this API. - -## Steps - -1. Declare a `[WirePool]` field for it. `DataTransferer` ships as [one of the Core - default pool entries](../explanations/builtin-registrations), so there's nothing to - register on the Configure window first. -2. Subscribe to completion before you ever call `TransferData`, so you don't miss a transfer - that finishes on the same frame it starts: - - ```csharp - public class ScoreSync : TsBehaviour - { - [WirePool][SerializeField] private DataTransferer _transferer; - - protected override void TsStart() - { - _transferer.TsSubscribe(this, DataTransferer.OnTransferCompletedEvent, nameof(_OnScoresReceived)); - } - - public void _OnScoresReceived() - { - string payload = _transferer.LastData; - // parse and apply payload - } - } - ``` - -3. Send it from whichever client has the data, to whichever players should receive it: - - ```csharp - public void BroadcastScores(string serializedScores, string[] targetPlayerIds) - { - _transferer.TransferData(serializedScores, targetPlayerIds); - } - ``` - -That's the whole public surface. `DataTransferer` is the type you interact with regardless -of how large the payload is or how many chunks it takes to arrive. - -## Serializing structured data - -`TransferData` takes a string, so send structured data through [`TsJson`](../utilities/ts-json) -first: - -```csharp -public void BroadcastScores(DataDictionary scores, string[] targetPlayerIds) -{ - _transferer.TransferData(TsJson.Serialize(scores), targetPlayerIds); -} -``` - -```csharp -public void _OnScoresReceived() -{ - DataDictionary scores = TsJson.Deserialize(_transferer.LastData); - if (scores != null) - { - // use scores - } -} -``` - -## Showing transfer progress - -Subscribe to `OnTransferChunkEvent` to drive a progress bar while a large payload arrives. -`LastChunkIndex`/`LastTotalChunks` are set before this event fires, so both are safe to -read from inside the handler: - -```csharp -public class ScoreSyncProgress : TsBehaviour -{ - [WirePool][SerializeField] private DataTransferer _transferer; - [SerializeField] private Slider _progressBar; - - protected override void TsStart() - { - _transferer.TsSubscribe(this, DataTransferer.OnTransferChunkEvent, nameof(_OnChunkReceived)); - _transferer.TsSubscribe(this, DataTransferer.OnTransferCompletedEvent, nameof(_OnTransferDone)); - } - - public void _OnChunkReceived() - { - // LastChunkIndex is 1-based (it's "how many chunks have arrived so far"). - _progressBar.value = (float)_transferer.LastChunkIndex / _transferer.LastTotalChunks; - } - - public void _OnTransferDone() => _progressBar.value = 1f; -} -``` - -## Handling a target player leaving mid-transfer - -You don't need to: `DataTransferer` already handles a target player leaving, getting -suspended, or the sending object changing owners mid-transfer. See -[the chain overview](../networking-data/overview.md) and the individual layer pages if you need -the exact guarantees (what "completed" means when the recipient list shrank, for instance). - -## Why this shape - -VRChat caps individual network event payloads well below what most real payloads need, so a -single call has to become a sequenced chunk transfer underneath. The -[chain overview](../networking-data/overview.md) explains why that's split across several small -layers instead of one large class. diff --git a/docs/core/how-to/wiring-a-ready-check.md b/docs/core/how-to/wiring-a-ready-check.md deleted file mode 100644 index f49601a..0000000 --- a/docs/core/how-to/wiring-a-ready-check.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -id: wiring-a-ready-check -title: Gate something on all players being ready -sidebar_position: 1 ---- - -# Gate something on all players being ready - -How to block an action until every present player has confirmed they're ready, using -[`AutoPlayerTracker`](../players-tracking/auto-player-tracker) to know who's present and -[`ReadyCheckProcess`](../players-tracking/ready-check-process) to track their ready state. - -## Steps - -1. Declare a `[WirePool]` field for each. Both ship as [the Core default pool - entries](../explanations/builtin-registrations), so there's nothing to register on the - Configure window first, and codegen calls `TsConstruct` for you at wire time: - - ```csharp - public class MatchStarter : TsBehaviour - { - [WirePool][SerializeField] private AutoPlayerTracker _roster; - [WirePool][SerializeField] private ReadyCheckProcess _readyCheck; - - protected override void TsStart() - { - _roster.StartAutoTracking(); - _roster.TsSubscribe(this, AutoPlayerTracker.OnAutoTrackingPlayersAddedEvent, nameof(_OnRosterChanged)); - } - - public void _OnRosterChanged() - { - if (!_readyCheck.IsProcessRunning()) - { - _readyCheck.StartReadyCheck(_roster.LastPlayerIds); - } - } - } - ``` - -2. Subscribe to completion and act on it: - - ```csharp - protected override void TsStart() - { - // ...continued from above - _readyCheck.TsSubscribe(this, ReadyCheckProcess.OnReadyCheckCompletedEvent, nameof(_OnEveryoneReady)); - } - - public void _OnEveryoneReady() => StartMatch(); - ``` - -3. Wherever your own UI lets a player mark themselves ready, call - `_readyCheck.SetReady()` (or `SetReady(false)` to take it back). It only changes the status of - the calling player, see [the reference - page](../players-tracking/ready-check-process#ownership-and-changes-to-the-ready-set) for why. - -## Handling the roster changing mid-check - -A player who leaves or is suspended is [removed from the check -automatically](../players-tracking/player-tracker#automatic-removal). To include a player who -joins while the check runs, add them to it. They start out not ready: - -```csharp -public void _OnRosterChanged() -{ - if (_readyCheck.IsProcessRunning()) - { - _readyCheck.AddTrackedPlayers(_roster.LastAddedPlayerIds); - return; - } - - _readyCheck.StartReadyCheck(_roster.LastPlayerIds); -} -``` - -Restarting the check with the current roster also works, but clears every ready mark. - -For a fixed, known set of players instead of everyone in the instance, start the ready check with -that ID list and skip `AutoPlayerTracker`. - -Declare each `[WirePool]` field exactly once in the whole project if you want one shared -roster and ready check. [Pool slot counts are computed per -type](../codegen/modules/pool-module#how-many-slots-a-dependency-graph-not-a-flat-count): -a second `[WirePool] private ReadyCheckProcess` field somewhere else allocates a second, -independent instance rather than sharing this one. Reach the same instance from another -behaviour with an ordinary serialized reference or a Global, not a second `[WirePool]` -field of the same type. - -## Why this shape - -See the [`ReadyCheckProcess` reference page](../players-tracking/ready-check-process) for the -ordering of `SetReady` and what happens when the tracked set changes during a check. For the "why -generated code, why not just call these directly at compile time" background, see -[How Core fits together](../core-concepts/how-it-fits-together). diff --git a/docs/core/how-to/writing-your-first-test.md b/docs/core/how-to/writing-your-first-test.md deleted file mode 100644 index 291a32b..0000000 --- a/docs/core/how-to/writing-your-first-test.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -id: writing-your-first-test -title: Write your first automated test for your own behaviour -sidebar_position: 18 ---- - -# Write your first automated test for your own behaviour - -How to write a real Play Mode test against your own `TsvrcBehaviour` subclass with -[Udon Test Kit](/docs/udon-test-kit/intro), once [your test assemblies are set -up](./set-up-automated-testing). - -## Steps - -1. Extend the kit's [`ClientSimTestBase`](/docs/udon-test-kit/reference/clientsim-test-base), give - the class a scene of its own, and start ClientSim in a `[UnityTest]`: - - ```csharp - public class RoundRefereeTests : ClientSimTestBase - { - public RoundRefereeTests() : base(TestScene.Empty("RoundRefereeTests")) - { - } - - [UnityTest] - public IEnumerator BeginRound_Owner_StartsTheRound() - { - yield return Session.Start(); - ``` - - Every test gets a fresh empty scene, and everything it creates goes when the scene unloads. - -2. Add the behaviour under test to a GameObject and construct it, as your generated root does at - world startup: - - ```csharp - var referee = new GameObject("RoundReferee").AddComponent(); - referee.TsConstruct((TsRoot)null); - ``` - - Pass `null` when the behaviour doesn't reach `_ts` during the test. - -3. Drive the behaviour and assert on it: - - ```csharp - referee.BeginRound(); - - Assert.IsTrue(referee.IsProcessRunning()); - } - } - ``` - -## Reaching a private field or method - -Use [`PrivateFieldAccess`](/docs/udon-test-kit/reference/private-field-access) from -Udon Test Kit instead of making something `public` just so a test can see it: - -```csharp -int remaining = PrivateFieldAccess.GetField(referee, "_remainingMilliseconds"); -``` - -## Asserting an event actually fired - -Subscribe a spy from the Udon Test Kit -[`CallLog`](/docs/udon-test-kit/reference/callback-spy-and-call-log) instead of writing a -one-off listener class for every test: - -```csharp -using var calls = new CallLog(); -CallbackSpy listener = calls.CreateSpy("Listener"); -referee.TsSubscribe(listener, RoundReferee.OnRoundEndedEvent, nameof(CallbackSpy.CallbackA)); - -// ...drive the round to completion... - -Assert.That(calls, Is.EqualTo(new[] { "Listener.CallbackA" })); -``` - -The log records each call in order, so the same assertion also fails if the event fired -twice. - -## Testing as a player who isn't the owner - -A `Process` such as `RoundReferee` acts only for its owner and forwards everything else. Hand it to -a remote player with the kit's `Session.SetOwner` to test the other side, as in -[Test what happens for a player who isn't the owner](/docs/udon-test-kit/how-to/testing-a-player-who-isnt-the-owner). - -## Why this shape - -See [Testing your world](../testing/testing-your-world) for how a test builds your behaviours -and what the Core codegen does during a test run. diff --git a/docs/core/intro.md b/docs/core/intro.md deleted file mode 100644 index 82f8142..0000000 --- a/docs/core/intro.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -id: intro -title: TsVRC Core -sidebar_position: 1 ---- - -# TsVRC Core - -TsVRC Core is an open-source framework for building VRChat worlds with -UdonSharp: structured initialization, dependency wiring, and an editor tool that generates -the code for both automatically (codegen), on top of the VRChat Worlds SDK. - -:::warning[Experimental and pre-1.0] -Core is an experiment, and AI coding tools generated part of its features. It isn't fully vibe -coded, but AI had a large share in writing it. It's also still pre-1.0: everything documented -here, including edge-case behavior on reference pages, describes what the code does today, not a -locked API contract. - -Test the behavior your world relies on before you publish it. For projects that are ready to use, -see [Udon Test Kit](/docs/udon-test-kit/intro) and -[Udon Tools Kit](https://github.com/tsvrc/udon-tools-kit). -::: - -## New to Core? - -Start with [Add TsVRC Core to your project](./add-to-your-project), then -[Build your first behaviour](./first-behaviour): by the end you'll have a script running -in play mode. - -## Already using it? - -Jump straight to what you need: - -- **Doing a specific task** — [pooling a prefab](./how-to/pooling-a-prefab), - [showing player positions](./how-to/showing-player-positions), - [transferring data between clients](./how-to/transferring-data-between-clients), or - [wiring a ready check](./how-to/wiring-a-ready-check). -- **Looking up a type's behavior** — search for its name, start from - [How Core fits together](./core-concepts/how-it-fits-together) and follow its links, or - browse Reference in the sidebar, grouped by area: players, networking, UI, codegen, and - so on. -- **Understanding why Core works the way it does** — - [Codegen instead of reflection](./explanations/codegen-vs-reflection) and the other pages - under Explanations. diff --git a/docs/core/networking-data/data-transfer/chunked-transfer-session.md b/docs/core/networking-data/data-transfer/chunked-transfer-session.md deleted file mode 100644 index d94888d..0000000 --- a/docs/core/networking-data/data-transfer/chunked-transfer-session.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -id: chunked-transfer-session -title: ChunkedTransferSession -sidebar_position: 2 ---- - -# ChunkedTransferSession - -`Tsvrc.DataTransfer.ChunkedTransferSession` sends a message split by [DataChunker](./data-chunker) -one chunk at a time: each chunk runs its own [ready -check](../../players-tracking/ready-check-process), in which every target player acknowledges it, -before the next chunk starts. It only owns the chunk sequence and sends nothing over the network -itself. It's one layer of [the data transfer chain](../data-transfer-overview), which names the type -to use. - -## The sequence - -`TransferData(data, playerIds)` stores the data and starts a ready check over the target players. -Each completed ready check (`OnProcessCompleted`) starts the ready check of the next chunk, or, after -the last chunk, fires `OnChunkSequenceCompleted`. A subclass overrides four `protected virtual` hooks -to broadcast the transitions: - -- `OnChunkSequenceStarted`: chunk 1 is about to go out. -- `OnChunkSequenceStopped`: the transfer was cancelled, or every target left. -- `OnChunkSequenceCompleted`: the ready check of the last chunk completed. -- `OnDataChunkSendRequested(dataChunk, chunkIndex, totalChunks, playerIds)`: fires for every chunk, - and is where a subclass sends it over the network. - -If every tracked player leaves or is suspended during a ready check, [the check can't -complete](../../players-tracking/ready-check-process#edge-cases). `ChunkedTransferSession` -overrides `OnProcessUpdate` to find a running process with no tracked players and calls -`CancelDataTransfer()`, so the transfer doesn't wait forever. - -## Between chunks - -Between two chunks, the underlying `Process` isn't running, and a stopped `ReadyCheckProcess` looks -the same whether the transfer ended or the next chunk hasn't started yet. `ChunkedTransferSession` -marks that gap with the synced `_pendingNextChunk` flag, and starts the next ready check one frame -later (`SendCustomEventDelayedSeconds(..., 0f)`) so the tick loop of the previous chunk ends first. -The flag is synced so a new owner can tell it took over in the gap. - -When the next ready check starts, the list of targets is filtered down to players who are present -and not suspended. `OnPlayerLeft` and `OnPlayerSuspendChanged` don't remove anyone during the gap, -since both check `IsProcessRunning()`. - -## A new owner during a transfer - -Transfer state (`_dataChunks` and the chunk indices) isn't synced. Only the owner needs it, and -keeping it off the network means the [periodic resync](../../core-concepts/process#the-tick-loop) -never sends the rest of the message again. A new owner therefore starts with no chunk state. - -`OnBecameProcessOwner` handles that. If a ready check is running, it stops it, since a check on -zeroed indices could otherwise read as a completed transfer. If the handover happened in the gap -between chunks, it broadcasts the stopped event so receivers clean up instead of waiting for a chunk -that won't come. - -`OnDeserialization` handles two late packets from the previous owner. A packet that says the -transfer is between chunks, arriving after the new owner already handled the gap, is turned into a -stop. A packet that marks the process running again with no chunk data behind it stops the ready -check. The comments in the source describe both orderings. - -## Cancellation - -`CancelDataTransfer()` can be called at any point, including between chunks, and does nothing when -no transfer is active. Between chunks it resets the state and fires the stopped hook right away. -After a ready check completed but before its cleanup ran, `StopReadyCheck` would do nothing, so it -sets an internal flag that the next `OnProcessCleanup` reads to stop instead of starting the next -chunk. After the ready check of the last chunk, cancelling does nothing, since the transfer is -already completing. - -## Adding players during a transfer - -`CanAcceptTrackedPlayerAdditions` rejects new tracked players with a warning once -`_currentChunkIndex > 0`, which covers chunks in flight and the gaps between them. A player added -after the first chunk would fail the player-list check of every later chunk, could never call -`SetReady`, and would block the ready check forever. Removing a tracked player during a transfer is -allowed, since that's how departures are handled. diff --git a/docs/core/networking-data/data-transfer/data-chunk-receiver.md b/docs/core/networking-data/data-transfer/data-chunk-receiver.md deleted file mode 100644 index 0f77d48..0000000 --- a/docs/core/networking-data/data-transfer/data-chunk-receiver.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -id: data-chunk-receiver -title: DataChunkReceiver -sidebar_position: 4 ---- - -# DataChunkReceiver - -`Tsvrc.DataTransfer.DataChunkReceiver` is where an incoming chunk actually gets validated, -stored, and acknowledged. It overrides -`OnDataChunkSendRequested` from [DataSender](./data-sender) to broadcast each chunk via its own `[NetworkCallable]` method, -`BroadcastDataChunkReceived`, which every instance player receives and which validates the -chunk before storing it. It's one layer of [the data transfer chain](../data-transfer-overview), -which names the type to use. - -## Validation, layer by layer - -`BroadcastDataChunkReceived` is reachable directly by any player, since [VRChat can't -restrict callers of a -`[NetworkCallable]` method](https://creators.vrchat.com/worlds/udon/networking/events/#legacy-events-and-security). -So every check inside it is defending against a chunk that didn't come from the legitimate -flow, not just handling malformed input: - -- **Transfer must actually be active** — checked via an internal `_transferActive` flag - rather than `IsProcessRunning()`, because the synced `_isRunning` field and network events - aren't delivery-ordered relative to each other; a chunk could otherwise arrive and be - dropped before `_isRunning` catches up. `_transferActive` is instead set from the - `OnTransferStarted` hook, which is guaranteed to have already run by the time a chunk - event can arrive, since network events from the same sender *are* ordered. -- **Sender must match the expected process owner** — an internal `_expectedSenderPlayerId`, - captured in `OnTransferStarted` from `Networking.LocalPlayer` (if the local instance is - the process owner) or from `NetworkCalling.CallingPlayer` (if not), rejects a chunk from - anyone else. The owner skips this check during its own broadcast, tracked by the - `_isSendingChunk` flag. -- **`playerIds` must be non-null and include the local player** — otherwise the chunk isn't - meant for this client and is ignored. -- **`dataChunk` must be non-null** — `StringBuilder.Append(null)` is a silent no-op, so a - null chunk stored without this check would leave that slot looking filled while actually - corrupting the reassembled message. -- **`totalChunks` is bounds-checked** against a computed maximum - (`⌈MAX_MESSAGE_SIZE / CHUNK_SIZE⌉`) before it's ever used to size an array — an unbounded - value from a malicious direct call could otherwise trigger an out-of-memory allocation on - every client that receives it. -- **`chunkIndex` must fall within `1..totalChunks`** — otherwise it's rejected before it's - ever used to index into `_receivedChunks`, which a malicious out-of-range value would - crash on. -- **`totalChunks` is locked to the first chunk's value** for the rest of the transfer; a - later chunk claiming a different total is rejected outright, since accepting it would - silently reallocate the receive buffer and discard everything already assembled. -- **A chunk index already filled is ignored** — the VRChat documentation [describes its - internal splitting of large events as "almost - transparent"](https://creators.vrchat.com/worlds/udon/networking/events/#parameter-size-limits-and-event-splitting), - which leaves room for a duplicate delivery under some conditions (network anomalies, an - ownership-transfer race). Without de-duplication a repeat would re-fire `OnChunkStored` - and send a redundant acknowledgment. - -## Why the rate limit is 100 per second - -`BroadcastDataChunkReceived` uses `maxEventsPerSecond: 100`, the same limit as the [broadcasts it -must stay in order with](./data-sender#why-the-rate-limit-is-100-per-second). It has a second reason -of its own: VRChat [splits any event payload over 1 KB into internal 1 KB -packets](https://creators.vrchat.com/worlds/udon/networking/events/#parameter-size-limits-and-event-splitting), -and each of those counts separately against the rate limit. A 2,500-character ASCII -chunk is already close to 2,500 bytes (roughly three internal packets); a CJK chunk near the -worst case discussed on the [`DataChunker`](./data-chunker) page is closer to 7,500 bytes -(roughly eight). At the SDK default of 5 events per second, even the ASCII case would take -over half a second to clear the rate limiter per chunk, and the CJK case over a second. A -100/second budget clears either in well under a tenth of a second, comfortably inside -the VRChat [global throughput cap](https://creators.vrchat.com/worlds/udon/networking/network-details/#bandwidth-limits) -of about 11 KB/s, which ends up being the real limit on how fast a transfer can go. - -## Storing and acknowledging - -A validated chunk is stored at `_receivedChunks[chunkIndex - 1]`, `OnChunkStored` fires -(subclass hook for updating public properties), and only then does `NotifyChunkReceived()` -acknowledge the chunk by calling the inherited -[`SetReady()`](../../players-tracking/ready-check-process#usage). `OnChunkStored` firing *before* the -acknowledgment matters on the owner specifically: `SetReady` can synchronously cascade into -completing the whole ready check, so emitting the chunk-received signal first guarantees a -chunk event is never observed to arrive after the completion event it made possible. - -## Reassembly, and a player tracked only partway through - -`OnTransferCompleted` reassembles the message only if every chunk slot was actually filled -(`HasAllChunks`); if any slot is still `null`, the result is an empty string, the same -result an untracked bystander's never-touched array already produces. This is what a player -who was tracked for only part of the transfer sees: someone removed mid-transfer, or -filtered out during an inter-chunk gap because they left or suspended. Chunks sent -after their removal are addressed to a `playerIds` list that no longer includes them and are -silently ignored by the `playerIds`-membership check above. Reassembly deliberately doesn't -attempt a partial result in that case. diff --git a/docs/core/networking-data/data-transfer/data-chunker.md b/docs/core/networking-data/data-transfer/data-chunker.md deleted file mode 100644 index 0b19a4b..0000000 --- a/docs/core/networking-data/data-transfer/data-chunker.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -id: data-chunker -title: DataChunker -sidebar_position: 1 ---- - -# DataChunker - -`Tsvrc.DataTransfer.DataChunker` is a [ReadyCheckProcess](../../players-tracking/ready-check-process) -that adds no network or process state: it splits and validates string data through `protected` -methods for subclasses, which keeps the chunking math apart from the code that sends chunks. It's -one layer of [the data transfer chain](../data-transfer-overview), which names the type to use. - -## Public surface (all `protected`, for subclasses) - -- **`ValidateMessage(message)`** — rejects a `null`/empty message (logs a warning) or one - longer than `MAX_MESSAGE_SIZE` (500,000 characters; logs an error). Returns whether the - message is safe to transfer. -- **`CreateDataChunks(data)`** — splits a string into an ordered array of chunks, each at - most `CHUNK_SIZE` characters. -- **`CalculateTotalChunks(dataLength)`** / **`ExtractChunk(data, chunkIndex)`** — the - underlying math, exposed separately so a subclass can compute chunk count without - materializing every chunk, or extract one chunk on demand. - -## Why CHUNK_SIZE is 2500 - -VRChat caps the [total parameter size of a single network -event](https://creators.vrchat.com/worlds/udon/networking/events/#parameter-size-limits-and-event-splitting) -at 16 KB (16,384 bytes), and the event that delivers a chunk carries four parameters: the chunk -string, its index, the total count, and the target player ID array. The chunk string dominates that budget, encoded as UTF-8, -which means the true worst case isn't emoji (2 UTF-16 chars but only 4 UTF-8 bytes, i.e. 2 -bytes/char) but CJK text in the U+0800-U+FFFF range, which costs 3 bytes per character. The -player ID array adds its own cost: IDs are `displayName#playerId` strings, and a busy -session with player turnover can produce 3-digit numeric IDs well past the concurrent -player cap (IDs are assigned in increasing order and never reused). The worst-case -calculation also assumes a 32-character CJK display name as a deliberately generous bound -(VRChat doesn't publish an official display name length limit), putting one player ID -entry's cost at 104 bytes. Worked out for a worst-case -80-player, all-CJK-name, all-CJK-data transfer, 2500 characters per chunk lands at roughly -15,828 of the 16,384 available bytes: close to the ceiling but safely under it. The same -math at `CHUNK_SIZE = 3000` already breaks the limit at 71 CJK-named players (16,392 bytes, -over the cap). An oversized event doesn't throw or degrade. VRChat silently drops it, the -receiver never acknowledges it, and the transfer stalls with no error anywhere. If you ever -need to change `CHUNK_SIZE`, redo this calculation against your own worst-case name length -and player count rather than picking a new number by feel. diff --git a/docs/core/networking-data/data-transfer/data-sender-receiver.md b/docs/core/networking-data/data-transfer/data-sender-receiver.md deleted file mode 100644 index 4655f69..0000000 --- a/docs/core/networking-data/data-transfer/data-sender-receiver.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -id: data-sender-receiver -title: DataSenderReceiver -sidebar_position: 5 ---- - -# DataSenderReceiver - -`Tsvrc.DataTransfer.DataSenderReceiver` builds on [DataChunkReceiver](./data-chunk-receiver) and -only changes how reception is exposed. It turns the raw hooks of the receiver (`OnTransferStarted`, -`OnChunksAssembled`, `OnChunkStored` and others) into `LastData`, `LastChunkIndex`, -`LastTotalChunks` and four events, `OnDataReceptionStartedEvent`, `...StoppedEvent`, -`...CompletedEvent` and `OnDataChunkReceivedEvent`, each with a matching `protected virtual` hook. A -subclass overrides those hooks without touching the chunk arrays. It's one layer of [the data -transfer chain](../data-transfer-overview), which names the type to use. - -The started and stopped events don't update a `Last*` property. `LastChunkIndex` and -`LastTotalChunks` are set before `OnDataChunkReceivedEvent` fires, and `LastData` before -`OnDataReceptionCompletedEvent`, so a subscriber can read them inside its handler. - -## Deferred stop and complete events - -`DataSenderReceiver` emits `OnDataReceptionStopped` and `Completed` one frame late, [like the -transfer events of DataSender](./data-sender#deferred-stop-and-complete-events) and for the same -reason: they fire inside the stop or complete call, before [the cleanup of the -process](../../core-concepts/process#lifecycle), and a new transfer started from the event right -away would lose its state to that cleanup. - -The assembled data waits in the private `_pendingCompletionData` field instead of going straight to -`LastData`. A new transfer that starts within that frame resets the receiver state, and this keeps -it from clearing the data before the deferred event reads it. `LastData` is set in the same step -that fires the completion event. - -`ResetReceiverState`, which runs when a new transfer starts, clears both pending flags -(`_pendingCompletion` and `_pendingStop`). A deferred call for an older transfer still fires, finds -its flag cleared, and emits nothing. - -## Validation - -This layer adds no checks. Sender verification, duplicate suppression and the chunk-count bounds -are [done by DataChunkReceiver](./data-chunk-receiver#validation-layer-by-layer). - -## Usage - -To build your own type on this layer, override `OnDataReceptionCompleted` and read `LastData`: - -```csharp -protected override void OnDataReceptionCompleted() -{ - string received = LastData; - // ... -} -``` diff --git a/docs/core/networking-data/data-transfer/data-sender.md b/docs/core/networking-data/data-transfer/data-sender.md deleted file mode 100644 index 1e076d1..0000000 --- a/docs/core/networking-data/data-transfer/data-sender.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -id: data-sender -title: DataSender -sidebar_position: 3 ---- - -# DataSender - -`Tsvrc.DataTransfer.DataSender` adds networking to the sequence hooks of -[ChunkedTransferSession](./chunked-transfer-session): it turns `OnChunkSequenceStarted`, `Stopped` -and `Completed` into `[NetworkCallable]` broadcasts to every player in the instance. It exposes them -as three events (`OnDataTransferStartedEvent`, `...StoppedEvent` and `...CompletedEvent`) with -matching `protected virtual` hooks (`OnTransferStarted`, `OnTransferStopped` and -`OnTransferCompleted`). None of the three updates a `Last*` property. It's one layer of [the data -transfer chain](../data-transfer-overview), which names the type to use. - -## Owner-only broadcasts, checked per call - -Each `Notify*` broadcast method checks that the caller is the owner of the object before acting. -Any player can call a -[`[NetworkCallable]`](https://creators.vrchat.com/worlds/udon/networking/events/#legacy-events-and-security) -method directly, so without the check a forged call could fire the start, stop or complete events -on every client and stall a running transfer for everyone. The owner skips the check during its own -broadcast, tracked by the inherited `_isBroadcasting` flag, because `CallingPlayer` isn't reliable -there. - -## Why the rate limit is 100 per second - -The three broadcasts use `maxEventsPerSecond: 100`, the [maximum VRChat -allows](https://creators.vrchat.com/worlds/udon/networking/events/#rate-limiting). VRChat keeps the -order of events from one sender only while none of them hits its own rate limit. At the default -rate, a quick cancel and restart could let a later event of the transfer, such as a chunk, overtake -the start notification on another client. That client would drop the chunk and the transfer would -stall with nothing to recover it. A subclass that adds events to the transfer needs the same limit -to keep that order. - -## Deferred stop and complete events - -The broadcast handlers `NotifyTrackedPlayersDataTransferStopped` and `...Completed` call the -`OnTransferStopped` and `OnTransferCompleted` hooks right away, but emit the public events one frame -later: they set a pending flag and schedule `_EmitDataTransferStopped` or -`_EmitDataTransferCompleted` with `SendCustomEventDelayedSeconds`. On the owner, the handler runs -inside the stop or complete call, before [the cleanup of the process](../../core-concepts/process#lifecycle). -A subscriber that started a new transfer from the event right away would have the new state cleared -by that cleanup. Waiting a frame lets the cleanup finish first. - -`NotifyTrackedPlayersDataTransferStarted` clears both pending flags, so when a subscriber starts a -new transfer within that frame, the deferred stop or complete event of the old transfer doesn't fire -after the new one began. diff --git a/docs/core/networking-data/data-transfer/data-transferer.md b/docs/core/networking-data/data-transfer/data-transferer.md deleted file mode 100644 index 52e49a7..0000000 --- a/docs/core/networking-data/data-transfer/data-transferer.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -id: data-transferer -title: DataTransferer -sidebar_position: 6 ---- - -# DataTransferer - -`Tsvrc.DataTransfer.DataTransferer` is the last link of the chain and the type you use. Its -generated shadow is `TsDataTransferer`. Everything it does comes from [DataChunker](./data-chunker) -through [DataSenderReceiver](./data-sender-receiver), and this page covers only what -`DataTransferer` adds. See [Send a string payload to other -players](../../how-to/transferring-data-between-clients) for a task-oriented walkthrough. - -## What it adds - -Four public event constants that emit the reception events of `DataSenderReceiver` under transfer -names: `OnTransferStartedEvent`, `OnTransferStoppedEvent`, `OnTransferCompletedEvent` and -`OnTransferChunkEvent`. - -## Getting an instance - -`DataTransferer` is one of the [builtin pool entries](../../explanations/builtin-registrations), so a -`[WirePool]` field of this type resolves with nothing to register, and codegen calls `TsConstruct` -on it: - -```csharp -[WirePool][SerializeField] private DataTransferer _transferer; -``` - -If you place the shipped `DataTransferer` prefab in your scene yourself instead, call -[`TsConstruct`](../../core-concepts/tsvrc-behaviour#construction) on it before using it. Its -`TsStart` stores the ID of the local player, and without it a receiver never finds itself among the -targets of a chunk, so it never acknowledges one and the transfer stalls. - -## Usage - -```csharp -transferer.TransferData(payload, targetPlayerIds); -transferer.TsSubscribe(this, TsDataTransferer.OnTransferCompletedEvent, nameof(OnTransferDone)); -``` - -```csharp -public void OnTransferDone() -{ - string received = transferer.LastData; - // ... -} -``` - -`LastPlayerIds`, inherited from `PlayerTracker`, holds the targets of the transfer when -`OnTransferStarted`, `Stopped` and `Completed` fire, carried over from the `OnTracking*` broadcast -before each one. `LastData`, `LastChunkIndex` and `LastTotalChunks` hold the reception details. - -## Where the behavior is documented - -Each failure case is documented on the layer that handles it: a target player leaving during a -transfer, a new owner taking over, how chunks are validated, and why events are deferred by a frame. -Start from [the chain overview](../data-transfer-overview) when a transfer doesn't behave the way -this page describes. diff --git a/docs/core/networking-data/overview.md b/docs/core/networking-data/overview.md deleted file mode 100644 index 16f58af..0000000 --- a/docs/core/networking-data/overview.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -id: data-transfer-overview -title: The data transfer chain -sidebar_position: 3 ---- - -# The data transfer chain - -`DataTransferer`, the type you use, is the last link in an inheritance chain built on -[Process](../core-concepts/process): -`Process → PlayerTracker → ReadyCheckProcess → DataChunker → ChunkedTransferSession → -DataSender → DataChunkReceiver → DataSenderReceiver → DataTransferer`. Each layer adds one -concern on top of the one below it, so this section documents them bottom-up in that same -order. Reading the `DataTransferer` page without the ones before it skips the reasoning -behind most of what it does. - -## The problem being solved - -VRChat caps the [total parameter size of a single network -event](https://creators.vrchat.com/worlds/udon/networking/events/#parameter-size-limits-and-event-splitting) -at 16 KB and [the overall outgoing Udon -bandwidth](https://creators.vrchat.com/worlds/udon/networking/network-details/#bandwidth-limits) -to about 11 KB/s, so sending an arbitrary string to a set of players means splitting it -into chunks, sending them one at a time, and confirming each one arrived before -sending the next, all while players can join, leave, get suspended, or have ownership of -the sending object change mid-transfer. Each layer in the chain exists to handle one slice -of that: chunking the data, sequencing the chunks through a ready check, broadcasting -lifecycle events, validating and reassembling what arrives, and exposing a clean public API -on top. - -## Reading order - -Read these in order; each page assumes the ones before it: - -1. [DataChunker](./data-transfer/data-chunker): splits and validates the raw string, no - networking or process state of its own. -2. [ChunkedTransferSession](./data-transfer/chunked-transfer-session): runs the ready check of - each chunk in turn. -3. [DataSender](./data-transfer/data-sender): broadcasts the sequencing transitions as - networked lifecycle events. -4. [DataChunkReceiver](./data-transfer/data-chunk-receiver): validates, stores, and - acknowledges each incoming chunk. -5. [DataSenderReceiver](./data-transfer/data-sender-receiver): turns the raw hooks of the - receiver into `Last*` properties and events. -6. [DataTransferer](./data-transfer/data-transferer): the type you use, adding only - transfer-focused event names on top. - -## What you use - -Unless you're extending the chain, you only use `DataTransferer`: call -`TransferData(data, playerIds)`, subscribe to its events, read `LastData` when a transfer -completes. The intermediate pages explain *why* `DataTransferer` -behaves the way it does under failure conditions (a player leaving mid-transfer, an -ownership handover between chunks, a malicious direct call to one of the network-callable -methods), not to hand you a separate API surface at each layer. diff --git a/docs/core/networking-data/tsvrc-memory.md b/docs/core/networking-data/tsvrc-memory.md deleted file mode 100644 index 5dc806a..0000000 --- a/docs/core/networking-data/tsvrc-memory.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -id: tsvrc-memory -title: TsvrcMemory -sidebar_position: 1 ---- - -# TsvrcMemory - -`Tsvrc.Utils.TsvrcMemory` is the shared key-value store in Core, reached through `_ts.Memory`. -Its generated shadow class is `TsMemory`. It holds every key in exactly one of three -isolated tiers, ephemeral, persistent, or synced, and the tier is a per-key decision you -make once, before you ever write a value. See [Persist a value across -visits](../how-to/persisting-a-value) for a task-oriented walkthrough. - -## The three tiers - -- **Ephemeral** (the default). Local to this client only, and gone when the player leaves - the world. Any key you never call `Register` on lives here. -- **Persistent.** Backed by VRChat `PlayerData`, so it survives across sessions for the - local player. Declared with `Register(key, persist: true, synced: false)`. -- **Synced.** Replicated to every player over the network. Declared with - `Register(key, persist: false, synced: true)`. - -A key can be exactly one of these, never a combination: `Register("k", true, true)` logs -an error and registers nothing. Registration only declares intent. It doesn't move or -migrate any value a key might already hold from before you registered it (see edge cases -below). - -## Reading and writing - -`Set` writes a value unconditionally, overwriting whatever was there. `Add` only writes if -the key has no value yet. For an already-populated ephemeral or persistent key it logs an -error and leaves the existing value alone, per its own doc comment ("use Set to overwrite"). -For an already-populated **synced** key it silently does nothing instead of erroring, since -a synced key being pre-populated usually just means the network already delivered a value -before your own `Add` call ran. `Has`, `Get`, and the typed accessors (`GetString`, `GetInt`, -`GetFloat`, `GetBool`, `GetDict`, `GetList`) all read from whichever store the key's -registered tier maps to; an unregistered key reads from the ephemeral store, matching -where `Set`/`Add` would have written it. - -`Add` on a synced key with no prior value writes into the local synced store immediately but -never calls `RequestSerialization`. The value doesn't reach other clients until some later -`Set` call on any synced key serializes the whole store. Use `Set`, not `Add`, for a synced -value that needs to go out right away. - -`Remove` clears a key from its store but **keeps its registration**, so you can `Add` the -same key again later without re-registering it. `Clear` empties every store's values but -likewise preserves all registrations. - -## The synced tier's mechanics - -A `DataDictionary` isn't a type UdonSync can replicate directly, so the synced store is -serialized to a plain synced string (`_syncedJson`) via `TsJson` whenever `Set`, `Remove`, or -`Clear` changes a synced key (see the `Add` caveat above: that one path doesn't serialize), -and `RequestSerialization()` is called to send it. `TsvrcMemory` declares -`[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]`, meaning that request, not an automatic -per-frame sync, is what triggers a network send. On the receiving end, `OnDeserialization` -parses `_syncedJson` back into the synced store and emits `OnSyncedChangedEvent` to every -subscriber. Subscribe to it via [`TsSubscribe`](../core-concepts/tsvrc-behaviour#events-tssubscribe-and-tsemit)`(this, -TsvrcMemory.OnSyncedChangedEvent, nameof(YourCallback))`. That event fires only from -network-driven deserialization, never for your own local `Set` calls. - -Writing to a synced key you don't currently own transfers ownership to the local player -first (`Networking.SetOwner`), matching the VRChat networking model where only the owner of an -object can push synced-variable updates for it. - -If `_syncedJson` ever fails to parse as a JSON object, whether from malformed data or a JSON -array instead of a dictionary, `OnDeserialization` returns early without updating the store -or emitting the event, leaving the previous synced contents in place rather than clearing -them. - -## PlayerData constraints (persistent tier) - -These come from the VRChat [persistence system](https://creators.vrchat.com/worlds/udon/persistence/player-data), -not from Core: - -- VRChat allows [100 KB of PlayerData per player per - world](https://creators.vrchat.com/worlds/udon/persistence/#limitations). VRChat - compresses data before storing it, so easily compressible data can exceed 100 KB - uncompressed and still fit. Keep persistent values small regardless. Exceeding the limit - fails the write silently: VRChat logs its own error, and no exception reaches your code. -- [VRChat cannot commit a PlayerData write made from inside - `OnPlayerLeft`](https://creators.vrchat.com/worlds/udon/persistence/#limitations). Avoid - calling `Set` on a persistent key there. -- [Persistent data is scoped to this - world](https://creators.vrchat.com/worlds/udon/persistence/#limitations); it isn't shared - with any other world. -- A persistent key can't actually be deleted from PlayerData: [the VRChat API reference - says the same](https://creators.vrchat.com/worlds/udon/persistence/player-data/#mutators) - ("Keys cannot be deleted after being written."). `Remove` only clears the local - in-memory cache, and logs a warning saying so. - -Restoring persisted values happens in -[`OnPlayerRestored`](https://creators.vrchat.com/worlds/udon/persistence/player-data/#events), -which VRChat calls once the local player's saved data has been loaded (`IsPlayerRestored` -reflects whether that's happened yet). Restoration is type-directed: `TsvrcMemory` records -each persistent key's value type the first time you `Add` or `Set` it, and uses that -recorded type to read the right PlayerData accessor back (`GetString`, `GetInt`, and so -on). A key registered as persistent but never given a value before `OnPlayerRestored` runs -has no recorded type yet, so restoration logs a warning and skips it. Call `Add` or `Set` -on a persistent key before you expect it to be restored, not after. - -## Usage - -Register each key once, before you ever read or write it, commonly in `TsStart`: - -```csharp -public class GameManager : TsBehaviour -{ - private const string DifficultyKey = "difficulty"; - private const string HighScoreKey = "highScore"; - - protected override void TsStart() - { - _ts.Memory.Register(DifficultyKey, persist: false, synced: true); - _ts.Memory.Register(HighScoreKey, persist: true, synced: false); - - _ts.Memory.Add(DifficultyKey, new DataToken(1)); - _ts.Memory.Add(HighScoreKey, new DataToken(0)); - - _ts.Memory.TsSubscribe(this, TsvrcMemory.OnSyncedChangedEvent, nameof(_OnMemorySynced)); - } - - public void _OnMemorySynced() - { - int difficulty = _ts.Memory.GetInt(DifficultyKey); - } - - public void IncreaseDifficulty() - { - _ts.Memory.Set(DifficultyKey, new DataToken(_ts.Memory.GetInt(DifficultyKey) + 1)); - } -} -``` - -`Add` seeds the default once without erroring on a value the network may have already -delivered. `Set` is what actually pushes a change, to `PlayerData` for the persistent key, -or to every client for the synced one; see "Reading and writing" above for exactly when -each method serializes. - -## Edge cases worth knowing - -- **Registering after data already exists doesn't migrate it.** If you `Set` a key while it's - still unregistered (ephemeral), then `Register` it as persistent, the ephemeral value is - orphaned in the ephemeral store; the persistent store still has nothing at that key. - `Register` before your first `Add`/`Set`, per the class's own contract. -- **Registering the same key twice** logs an error and keeps the original tier; the second - call's flags are discarded. -- **`Set` on a persistent key before `OnPlayerRestored`** still updates the local in-memory - cache and the recorded value type (neither is rejected), but the PlayerData write itself - is unconditionally skipped, with a warning logged, purely because `OnPlayerRestored` - hasn't run yet for this instance, regardless of whether a type is already recorded for - that key. diff --git a/docs/core/networking-data/tsvrc-timer.md b/docs/core/networking-data/tsvrc-timer.md deleted file mode 100644 index 0824333..0000000 --- a/docs/core/networking-data/tsvrc-timer.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -id: tsvrc-timer -title: TsvrcTimer -sidebar_position: 2 ---- - -# TsvrcTimer - -`Tsvrc.Timing.TsvrcTimer` is a networked, pausable timer built on [Process](../core-concepts/process). -Its generated shadow is `TsTimer`. All clients share [server -time](https://udonsharp.docs.vrchat.com/vrchat-api/#methods-4) anchors and compute elapsed time -locally, so a running timer sends nothing per tick beyond the periodic [resync of -`Process`](../core-concepts/process#the-tick-loop). See [Run a synced -countdown](../how-to/running-a-countdown) for a task-oriented walkthrough. - -## Getting an instance - -`TsvrcTimer` is one of the [builtin pool entries](../explanations/builtin-registrations), so a -`[WirePool]` field of this type resolves with nothing to register, and codegen calls `TsConstruct` -on it. If you place the shipped `TsTimer` prefab in your scene yourself instead, call -[`TsConstruct`](../core-concepts/tsvrc-behaviour#construction) on it before using it. - -## Usage - -```csharp -public class RoundClock : TsBehaviour -{ - [WirePool][SerializeField] private TsvrcTimer _timer; - - protected override void TsStart() - { - _timer.TsSubscribe(this, TsvrcTimer.OnTimerCompletedEvent, nameof(_OnRoundEnded)); - _timer.StartTimer(60_000); // 60-second round - } - - public void _OnRoundEnded() => LogInfo("Round timer finished."); -} -``` - -To show the countdown, read `_timer.GetRemainingSeconds()` from your own update loop. -`OnTimerUpdatedEvent` is for reacting to state changes, not for redrawing a UI every frame. - -## Starting, stopping, pausing - -- **`StartTimer()`** counts up with no end. `DurationMs` stays `0`. -- **`StartTimer(int durationMilliseconds)`** completes once elapsed time reaches the duration. A - negative value counts as `0`, a timer with no end. - -Either overload makes the calling player the owner first, so the timer runs on the player who -starts it. Calling either one while the timer runs does nothing: it doesn't restart the timer or -change its duration. - -- **`StopTimer()`** and the inherited `CompleteProcess()` end the timer early or complete it. Both - [send the call to the owner](../core-concepts/process#lifecycle) when another player makes it. -- **`PauseTimer()`** and **`ResumeTimer()`** freeze and unfreeze elapsed time. A pause extends the - run: the completion check in `OnProcessUpdate` uses `GetElapsedMilliseconds()`, which stays frozen - while paused, so the full duration always runs. Another player calling either one sends it to the - owner through `RequestPauseTimer` or `RequestResumeTimer`, both - [`[NetworkCallable]`](https://creators.vrchat.com/worlds/udon/networking/events/#rate-limiting) - and limited to two calls per second. - -## Reading elapsed and remaining time - -`GetElapsedMilliseconds()` and `GetElapsedSeconds()` compute from the synced server-time anchor -while running, and return the frozen offset while stopped or paused. `GetRemainingMilliseconds()` -and `GetRemainingSeconds()` return `DurationMs - GetElapsedMilliseconds()`, and `0` for a timer -with no end, one past its duration, or a completed one. - -`LastElapsedMilliseconds` holds the last value the timer computed. Read it when you need what the -timer last reported: it updates on every start, stop, pause, resume and deserialization, and every -0.25 seconds while running and not paused, from the same local loop that drives -`OnTimerUpdatedEvent`. - -## Events - -Each transition has a `protected virtual` hook to override in a subclass and a string constant to -pass to `TsSubscribe`. Both fire on every client, the hook first: - -| Hook | Event constant | Fires when | -|---|---|---| -| `OnTimerStarted` | `OnTimerStartedEvent` | The timer starts, including when a late joiner finds it running | -| `OnTimerStopped` | `OnTimerStoppedEvent` | The timer stops before completion | -| `OnTimerCompleted` | `OnTimerCompletedEvent` | The timer completes: duration reached, or `CompleteProcess` called | -| `OnTimerPaused` | `OnTimerPausedEvent` | The timer pauses, including when a late joiner finds it paused | -| `OnTimerResumed` | `OnTimerResumedEvent` | The timer resumes | -| `OnTimerUpdated` | `OnTimerUpdatedEvent` | The elapsed time, running state or paused state seen locally changed | -| `OnTimerDeserialization` | `OnTimerDeserializationEvent` | Every `OnDeserialization` call, whether or not anything changed | - -## How other players detect transitions - -On the owner, the `OnProcessStarted`, `Stopped` and `Completed` hooks of `Process` call the timer -hooks directly. Other players compare the running and paused flags in each packet against what they -saw last, inside `OnDeserialization`. Two cases matter if you rely on the exact order of events: - -- **A late joiner arriving mid-run** sees the timer go from never seen to running in one packet. - That counts as a start: `OnTimerStarted` fires, and `OnTimerPaused` right after it if the timer - is paused. -- **A stop and a restart in one packet.** Manual sync doesn't send on `RequestSerialization` right - away. It [waits for its rate limit and sends whatever the synced fields hold at that - moment](https://creators.vrchat.com/worlds/udon/networking/network-details/#manual-synchronization). - A listener that starts a new run from `OnTimerStopped` or `OnTimerCompleted` (possible because - [`SendCustomNetworkEvent(All, ...)` runs on the sender right - away](https://creators.vrchat.com/worlds/udon/networking/events/#event-targeting)) can produce one - packet in which the timer never stopped. `TsvrcTimer` counts runs in `_runId`, increased in every - `OnProcessStarted`. When the timer stays running across a packet but `_runId` changed, the timer - treats it as a new start. Whether the old run stopped or completed is lost by then, so only the - start of the new run (and its pause, if any) fires. - -## Edge cases - -- The read methods return `0` on a timer that never started, and none of them throw. -- Elapsed time never goes negative. If `_elapsedOffsetMs + delta` overflows `int`, it becomes `0` - instead of wrapping to a negative value. -- `OnProcessCleanup` keeps the server-time anchors of the last run, so other players can still - show the final elapsed time after the timer stops. `OnProcessStarted` resets them at the start of - the next run. diff --git a/docs/core/players-tracking/auto-player-tracker.md b/docs/core/players-tracking/auto-player-tracker.md deleted file mode 100644 index 105ff33..0000000 --- a/docs/core/players-tracking/auto-player-tracker.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -id: auto-player-tracker -title: AutoPlayerTracker -sidebar_position: 3 ---- - -# AutoPlayerTracker - -`Tsvrc.Tracking.AutoPlayerTracker` is a [PlayerTracker](./player-tracker) that tracks every player in -the instance, with no player list to manage. Its generated shadow is `TsAutoPlayerTracker`. See -[Track a custom group of players](../how-to/tracking-a-group-of-players) for when to use it instead -of a plain `PlayerTracker`. - -## Getting an instance - -`AutoPlayerTracker` is one of the [builtin pool entries](../explanations/builtin-registrations), so a -`[WirePool]` field of this type resolves with nothing to register, and codegen calls `TsConstruct` -on it. If you place the shipped `AutoPlayerTracker` prefab in your scene yourself instead, call -[`TsConstruct`](../core-concepts/tsvrc-behaviour#construction) on it before using it. - -## Usage - -Call `StartAutoTracking()`. It makes the calling player the owner first, so tracking runs on the -player who starts it. `StartPlayerTracking` is overridden to do the same as `StartAutoTracking` and -ignores both of its parameters, since `AutoPlayerTracker` never uses the process update. -`StopAutoTracking()` and `CompleteAutoTracking()` call `StopPlayerTracking` and -`CompletePlayerTracking`. - -While tracking runs, the owner adds each player who joins in `OnPlayerJoined`. A join is skipped -when the player reference [isn't valid](https://creators.vrchat.com/worlds/udon/players/#isvalid), -which VRChat says to check before using a player. Players who leave or -are suspended are [removed by the base class](./player-tracker#automatic-removal). Other players -ignore `OnPlayerJoined`, -because only the owner changes the tracked set. - -```csharp -public class InstanceRoster : TsBehaviour -{ - [WirePool][SerializeField] private AutoPlayerTracker _tracker; - - protected override void TsStart() - { - _tracker.TsSubscribe(this, AutoPlayerTracker.OnAutoTrackingPlayersAddedEvent, nameof(_OnRosterChanged)); - _tracker.TsSubscribe(this, AutoPlayerTracker.OnAutoTrackingPlayersRemovedEvent, nameof(_OnRosterChanged)); - _tracker.StartAutoTracking(); - } - - public void _OnRosterChanged() => LogInfo(_tracker.LastPlayerIds.Length + " players in the instance."); -} -``` - -## When the first list is read - -`StartAutoTracking` reads the player list when it's called, not in `OnPlayerJoined`. [Joining an -instance fires `OnPlayerJoined` for every player already -present](https://creators.vrchat.com/worlds/udon/graph/event-nodes/#onplayerjoined), the local -player included, and that wave fires before any of your code runs. The tracker isn't running yet, -so it drops all of those events, and the list read at start is what covers those players. - -A player still joining at that moment fires `OnPlayerJoined` later, once tracking runs, and is added -then. UdonSharp runs on the Unity main thread only, so no `OnPlayerJoined` can run between reading -the list and the start of tracking, and no joining player is missed. - -The first list leaves out players who are already suspended. The base class [removes a -player](./player-tracker#automatic-removal) when they become suspended, so a player who is suspended -before tracking starts would never be removed. - -## Events - -The same six events as `PlayerTracker`, with an `Auto` prefix: `OnAutoTrackingStarted`, `Stopped`, -`Completed`, `Deserialization`, `PlayersAdded` and `PlayersRemoved`, each with an -`OnAutoTracking*Event` constant. Each one overrides the matching `OnTracking*` hook to emit the -renamed event. Read `LastPlayerIds`, `LastAddedPlayerIds` and `LastRemovedPlayerIds` as on -`PlayerTracker`. diff --git a/docs/core/players-tracking/head-clip-guard.md b/docs/core/players-tracking/head-clip-guard.md deleted file mode 100644 index 6f0b7b3..0000000 --- a/docs/core/players-tracking/head-clip-guard.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -id: head-clip-guard -title: HeadClipGuard -sidebar_position: 6 ---- - -# HeadClipGuard - -`Tsvrc.Player.HeadClipGuard` stops a VR player's head from clipping through solid geometry -by teleporting them back out along the axis their body most likely entered from. Its -generated shadow is `TsHeadClipGuard`. It's a local-only, per-client behaviour (no network -sync) that runs every frame in -[`PostLateUpdate`](https://udonsharp.docs.vrchat.com/events/#udon-update-events), fired -"near the end of the frame after IK has been calculated," so tracking and IK have -already settled by the time it runs. See [Stop VR players clipping through -walls](../how-to/guarding-against-head-clipping) for a task-oriented walkthrough. - -## Getting an instance - -`HeadClipGuard` ships as one of [the Core default factory -entries](../explanations/builtin-registrations) (`TsBuiltinConfig`). - -- **Default:** `_ts.CreateHeadClipGuard(parent)` just works, nothing to register in - Configure first. -- **Manual:** skip the factory entirely. `AddComponent` it (or drag the shipped - `HeadClipGuard` prefab into your scene) and call `Begin` directly, no `TsConstruct` call - needed first. `Begin` itself re-caches the local `VRCPlayerApi` reference if it's still - unset, the same reference `TsStart` would otherwise cache, so a never-constructed - instance still guards correctly. - -## Usage - -```csharp -guard.Begin(solidColliders, count); -// ... later, when the guarded region no longer applies: -guard.End(); -``` - -`Begin` bakes the world-space center, rotation, and half-extents of each `BoxCollider` once -(a one-time cost, not repeated per frame) and starts the guard. Null entries in the -array are skipped rather than rejected. `End` fully resets all runtime state and is safe to -call before a later `Begin` on the same instance, so one `HeadClipGuard` can be reused -across multiple guarded sessions rather than requiring a fresh instance each time. - -## How it decides which way to push - -Detection happens in world space against oriented bounding boxes (not axis-aligned: each -collider's own rotation is respected), each expanded by a configurable `_margin` so the head -stays a small distance from the wall surface instead of resting exactly on it. When the head -is inside a violated box, the push direction is chosen by which axis the player's *body* -(the VRChat capsule position, not the head) most exceeds the box's raw extents on. The -assumption is that whichever direction the body is pushing from is the direction the -head entered through, and the correct way to eject it. If the body is also fully inside the -same box (both head and body clipped, a rarer case), it falls back to pushing the head -toward its own single nearest face instead, since there's no body-direction signal to use. -Multiple simultaneous violations (a corner, where two OBBs overlap) accumulate their push -vectors. If two pushes happen to cancel out exactly (the head trapped symmetrically -between two opposing walls), the guard falls back to the last known safe capsule -position instead of teleporting to a net-zero displacement. - -## Performance design - -Every frame potentially scanning every collider in a scene as a full OBB test would be -wasteful, so the guard layers three progressively cheaper checks: - -1. **Movement gate** — if the head hasn't moved more than a small threshold (default 5mm, - comfortably above VR tracking jitter) on any axis since the last processed frame, and no - violation was active, the entire frame's work is skipped. -2. **Rolling batch scan** — instead of testing every collider's AABB against the head every - frame, only a rotating slice (`1/_batchFrames` of the full list) is re-evaluated each - frame, added to or removed from a compact candidate list in O(1) via swap-with-last. A - collider only needs re-checking on the cadence set by `_batchFrames`, expanded by - `_batchScanExpansion` to cover how far the head could plausibly move between two scans - of the same collider. -3. **Tight AABB pre-reject, then full OBB test** — only candidates surviving the batch scan - get a cheap axis-aligned bounds check, and only those get the full oriented-box test. - -## Configuration invariants - -- `_batchScanExpansion` must cover the maximum realistic head speed times the batch period: - the field's own tooltip states the relationship as - `batchScanExpansion >= maxSpeed * batchFrames / minFPS`. Set too small, a fast-moving head - could pass a collider's stale batch AABB and get a false negative between scans. -- `_batchFrames < 1` is silently clamped to `1` rather than causing a division error. diff --git a/docs/core/players-tracking/player-color-assigner.md b/docs/core/players-tracking/player-color-assigner.md deleted file mode 100644 index cf10b3a..0000000 --- a/docs/core/players-tracking/player-color-assigner.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -id: player-color-assigner -title: PlayerColorAssigner -sidebar_position: 5 ---- - -# PlayerColorAssigner - -`Tsvrc.Player.PlayerColorAssigner` assigns every player a stable, visually distinct -color from an 82-entry palette, one slot per player up to [the absolute maximum VRChat -instance size](https://wiki.vrchat.com/wiki/Special:MyLanguage/Instances) (80 is the -configurable hard cap; the world author and instance creator can each still join on top -of that, for 82 in the worst case), keyed off their numeric player ID so every client -independently resolves the same color for the same player with no per-lookup network -traffic. See [Give each player a unique color](../how-to/assigning-player-colors) for a -task-oriented walkthrough. - -## Usage - -Call `Initialize()` once per instance start, before any `GetColor` call. Multiple -consumers that need matching colors should share one `PlayerColorAssigner` instance -rather than each deriving their own: the whole point of the synced shuffle order is that -everyone agrees. - -```csharp -assigner.Initialize(); -Color c = assigner.GetColor(TsPlayer.GetPlayerID(somePlayer)); -``` - -## Why the palette is shuffled, and how - -A player's raw color slot is just their numeric player ID modulo the palette size, cheap -and deterministic, but it means the *n*th player to ever join any instance always gets -the same slot, so two friends who happen to join in the same relative order across -sessions always see the same two colors paired together. `Initialize` fixes that by -generating a random permutation of palette indices (a synced `byte[] _order`) once per -instance, so the same raw slot maps to a different actual color each session. Only the -owner actually shuffles and broadcasts it: a non-owner's own `Initialize` call just -ensures a sane identity-order default (`_order[i] = i`) is in place locally until the -owner's real order arrives, so `GetColor` is never called against an uninitialized -array. - -## Edge cases worth knowing - -- `GetColor` never throws: an empty or missing palette returns `Color.white`, and a - numeric ID that doesn't parse (see [`TsPlayer.GetNumericPlayerId`](./ts-player)) - simply resolves to slot `0`. -- Calling `GetColor` before `Initialize` (or before the owner's synced order has - arrived) is safe. The palette-index modulo alone still produces a color, just not yet - the session-shuffled one. -- The palette itself is a fixed, hand-tuned hue sweep (two passes around the color - wheel at alternating saturation/value) chosen for maximum distinctness between - adjacent slots, not a generated gradient. Changing its length changes the modulo - divisor for every ID. diff --git a/docs/core/players-tracking/player-tracker.md b/docs/core/players-tracking/player-tracker.md deleted file mode 100644 index 57ea13f..0000000 --- a/docs/core/players-tracking/player-tracker.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -id: player-tracker -title: PlayerTracker -sidebar_position: 2 ---- - -# PlayerTracker - -`Tsvrc.Tracking.PlayerTracker` is a [Process](../core-concepts/process) that keeps a networked set -of tracked players, managed by its owner and identified by [`TsPlayer`](./ts-player) ID strings -instead of live `VRCPlayerApi` references. Its generated shadow is `TsPlayerTracker`. See [Track a -custom group of players](../how-to/tracking-a-group-of-players) for a task-oriented walkthrough. - -## Getting an instance - -`PlayerTracker` is one of the [builtin pool entries](../explanations/builtin-registrations), so a -`[WirePool]` field of this type resolves with nothing to register, and codegen calls `TsConstruct` -on it. If you place the shipped `PlayerTracker` prefab in your scene yourself instead, call -[`TsConstruct`](../core-concepts/tsvrc-behaviour#construction) on it before using it. - -## Usage - -```csharp -public class SpectatorRoster : TsBehaviour -{ - [WirePool][SerializeField] private PlayerTracker _spectators; - - protected override void TsStart() - { - _spectators.TsSubscribe(this, PlayerTracker.OnTrackingPlayersAddedEvent, nameof(_OnRosterChanged)); - _spectators.TsSubscribe(this, PlayerTracker.OnTrackingPlayersRemovedEvent, nameof(_OnRosterChanged)); - _spectators.StartPlayerTracking(new string[0]); - } - - public void AddSpectator(string playerId) => _spectators.AddTrackedPlayers(new[] { playerId }); - - public void _OnRosterChanged() => LogInfo(_spectators.LastPlayerIds.Length + " spectators."); -} -``` - -## Starting and reading the tracked set - -`StartPlayerTracking(playerIds, useProcessUpdate)` starts the process with an initial set. A player -who isn't the owner takes ownership first, so the tracker runs on the player who starts it. The list -is cleaned before use: `null` entries are removed and duplicates collapsed, so no ID appears twice -from the first broadcast on. Calling it while the tracker runs logs a warning and leaves both the -run and the pending initial list alone, so a rejected start can't change the set of the next one. - -`LastPlayerIds` is the tracked set as of the last received broadcast or deserialization. Read it -inside an `OnTracking*` callback. `IsTrackedPlayer`, a `protected` helper for subclasses, reads the -synced field instead, which on a non-owner can lag behind a `Notify*` callback that just fired. - -## Adding and removing players while running - -`AddTrackedPlayers` and `RemoveTrackedPlayers` apply directly on the owner and send the call to the -owner from any other player. The change itself happens in `BroadcastAddTrackedPlayers` and -`BroadcastRemoveTrackedPlayers`. Both are `[NetworkCallable]`, so any player in the instance can -call them directly, and both check `IsProcessRunning() && IsProcessOwner()` themselves. - -`BroadcastAddTrackedPlayers` also asks the `CanAcceptTrackedPlayerAdditions()` hook, `true` by -default. Override it to reject additions. It's the one place that sees both the local call on the -owner and a call from another player, since a -[`[NetworkCallable]`](https://creators.vrchat.com/worlds/udon/networking/events/#defining-an-event) -method can't be `virtual`. - -Both broadcast methods skip IDs that don't apply (already tracked for an add, not tracked for a -remove) without an error, and remove duplicates from their own input, so passing the same ID twice -in one call never tracks or broadcasts it twice. - -## Automatic removal - -The owner removes a tracked player without a `RemoveTrackedPlayers` call in three cases: - -- **`OnPlayerLeft`**: the player left while the tracker runs. -- **`OnPlayerSuspendChanged`**: the player was suspended. A suspended player can't run Udon or - answer network events, so subclass logic that waits for every tracked player would block - forever. Waking up needs nothing, since the player was already removed. -- **`OnBecameProcessOwner`**: the tracker changed owner during a run, for example because the - previous owner left or was suspended. Only the owner removes players, so a tracked player who - left or was suspended while the previous owner couldn't act is still in the set. The new owner - checks the whole set against the players who are present and not suspended, and removes the - rest. - -## Events - -Six `OnTracking*` hooks, `protected virtual` and empty by default, each paired with an -`OnTracking*Event` constant for `TsSubscribe`: `Started`, `Stopped`, `Completed`, `Deserialization`, -`PlayersAdded` and `PlayersRemoved`. The doc comment of each hook says which `Last*Ids` property to -read inside it. - -The `Notify*` methods behind these events all allow 100 calls per second. VRChat keeps the order of -events from one sender [only while none of them hits its rate -limit](https://creators.vrchat.com/worlds/udon/networking/events/#rate-limiting), so a run of adds -and removes can't overtake a start, stop or complete broadcast on another client. - -## Edge cases - -- Each `Notify*` method cleans its own input again (removes `null` entries, then duplicates) and - checks that the caller is the current owner, since any player can call a `[NetworkCallable]` - method directly. The owner skips that caller check during its own broadcast, tracked by the - internal `_isBroadcasting` flag. -- Synced fields and network events travel separately: [manual sync sends only when its own rate - limit - allows](https://creators.vrchat.com/worlds/udon/networking/network-details/#manual-synchronization), - however often `RequestSerialization` is called, so either can arrive first. - `NotifyTrackedPlayersAdded` adds to `LastPlayerIds` only the IDs it doesn't already hold. diff --git a/docs/core/players-tracking/ready-check-process.md b/docs/core/players-tracking/ready-check-process.md deleted file mode 100644 index 47613b1..0000000 --- a/docs/core/players-tracking/ready-check-process.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -id: ready-check-process -title: ReadyCheckProcess -sidebar_position: 4 ---- - -# ReadyCheckProcess - -`Tsvrc.Tracking.ReadyCheckProcess` is a [PlayerTracker](./player-tracker) that runs a ready check: -it tracks a fixed set of players and completes once every one of them has marked themselves ready. -Its generated shadow is `TsReadyCheckProcess`. See [Gate something on all players being -ready](../how-to/wiring-a-ready-check) for a task-oriented walkthrough. - -## Getting an instance - -`ReadyCheckProcess` is one of the [builtin pool entries](../explanations/builtin-registrations), so a -`[WirePool]` field of this type resolves with nothing to register, and codegen calls `TsConstruct` -on it. If you place the shipped `ReadyCheckProcess` prefab in your scene yourself instead, call -[`TsConstruct`](../core-concepts/tsvrc-behaviour#construction) on it before using it. Its `TsStart` -stores the ID of the local player, and without it `SetReady` can't mark the local player ready. - -## Usage - -`StartReadyCheck(playerIds)` starts tracking the given players through -`StartPlayerTracking(playerIds, useProcessUpdate: true)`, so the calling player becomes the owner -and the process update polls readiness. Each player calls `SetReady()` to mark themselves ready, or -`SetReady(false)` to take it back. The owner checks whether everyone is ready after each change and -on every 0.5-second tick, and calls `CompleteReadyCheck()` as soon as all tracked players are. -`StopReadyCheck()` ends the check early. - -There are three events, following the `PlayerTracker` pattern: the `OnReadyCheckStarted`, -`OnReadyCheckStopped` and `OnReadyCheckCompleted` hooks, with matching `OnReadyCheck*Event` -constants for `TsSubscribe`. `IsPlayerReady(playerId)` checks the ready set, and the inherited -`LastPlayerIds` is the tracked set. - -```csharp -public class LoadingGate : TsBehaviour -{ - [WirePool][SerializeField] private ReadyCheckProcess _readyCheck; - - protected override void TsStart() - { - _readyCheck.TsSubscribe(this, ReadyCheckProcess.OnReadyCheckCompletedEvent, nameof(_OnEveryoneReady)); - } - - public void BeginLoadGate(string[] participantIds) => _readyCheck.StartReadyCheck(participantIds); - - // Call once this client has finished whatever it was waiting on. - public void FinishedLoading() => _readyCheck.SetReady(); - - public void _OnEveryoneReady() => LogInfo("Everyone is ready, continuing."); -} -``` - -## Why SetReady doesn't check IsProcessRunning - -`SetReady` checks an internal `_readyCheckActive` flag instead of `IsProcessRunning()`. Manual sync -sends synced fields [when its own rate limit -allows](https://creators.vrchat.com/worlds/udon/networking/network-details/#manual-synchronization), -independently of network events, so `SetReady` called from a network event handler can run before -the synced running state arrives, even though the start event already has. `_readyCheckActive` -follows the ordered `Notify*` events (`OnTrackingStarted`, `Stopped` and `Completed`) and is set in -two more places those events don't reach: - -- **`OnTrackingDeserialization`**: [network events aren't replayed to players who join - later](https://creators.vrchat.com/worlds/udon/networking/late-joiners/), so a late joiner never - gets the start event. The flag follows the synced running state on every deserialization instead. -- **`OnBecameProcessOwner`**: a player who becomes the owner before receiving the start event or a - packet would keep the flag `false`, and an owner never deserializes its own packets. The flag - follows the running state here too, so the new owner can still mark itself ready. - -A `SetReady` call while `_readyCheckActive` is `false` logs a warning locally and sends nothing, so -a flag stuck by a missed broadcast leaves no trace on any other client. - -## Ownership and changes to the ready set - -Only the copy of the ready set on the owner counts. Unlike the tracked set, it has no `Notify*` -broadcast, so `IsPlayerReady` on another player reflects only the last packet received. - -`SetReady` changes the set directly on the owner. Any other player sends the change to the owner -through `BroadcastAddReadyPlayer` or `BroadcastRemoveReadyPlayer`. Both are `[NetworkCallable]` and -limited to two calls per second, since VRChat [recommends keeping that limit as low as the use case -allows](https://creators.vrchat.com/worlds/udon/networking/events/#rate-limiting). Both reject a -call that marks anyone other than the caller: -[`NetworkCalling.CallingPlayer`](https://creators.vrchat.com/worlds/udon/networking/events/#accessing-the-sender-of-an-event) -must match the `playerId` argument. It's `null` for a direct local call, which skips the check. - -An internal `RemoveReadyPlayerInternal` changes the set without going through the network for a -player who leaves or is removed, and for the owner calling `SetReady(false)`. VRChat keeps -`CallingPlayer` set to the sender of the outermost network call for the whole call chain, so calling -`BroadcastRemoveReadyPlayer` from the handler of a network event sent by another player would carry -that player as the caller and fail the check above. - -## Edge cases - -- A check with no tracked players never completes on its own: completion needs at least one - tracked player, and every one of them ready. That holds for a check started with an empty list - and for one whose tracked players all left. Stop it with `StopReadyCheck()`. -- A ready mark from a player who isn't tracked is rejected with a warning. `CheckAllPlayersReady` - only looks at tracked players, so that mark could never affect completion. -- `OnTrackingPlayersRemoved` can remove up to 79 players at once when a new owner takes over, one - below the [80-player instance cap](https://wiki.vrchat.com/wiki/Special:MyLanguage/Instances). It - removes them from the ready set in one pass with one array allocation. -- Removing a player who isn't ready can complete the check: if everyone left is ready, - `OnTrackingPlayersRemoved` completes it right after the removal. diff --git a/docs/core/players-tracking/ts-player.md b/docs/core/players-tracking/ts-player.md deleted file mode 100644 index 7fbd50a..0000000 --- a/docs/core/players-tracking/ts-player.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -id: ts-player -title: TsPlayer -sidebar_position: 1 ---- - -# TsPlayer - -`Tsvrc.Player.TsPlayer` is a static helper class for identifying and looking up players. -It depends on no other Core type. - -## Why a custom player ID exists - -The VRChat `VRCPlayerApi.playerId` only identifies a player while they're present in -the current instance: -[`GetPlayerById`](https://creators.vrchat.com/worlds/udon/players/getting-players/#getplayerbyid) -only resolves someone who's still around, and playerId numbering isn't guaranteed to -line up the same way for every client watching the instance. Neither is safe to store -and compare later. The Core ID format, `displayName#playerId` (built by -`GetPlayerID`), is what gets stored and compared across clients throughout the -framework instead. - -## Usage - -Store the result of `GetPlayerID` anywhere you need to refer to a player later, and resolve it -back to a live `VRCPlayerApi` with `FindPlayerByID` (which returns `null` once that player -has left): - -```csharp -string winnerId = TsPlayer.GetPlayerID(Networking.LocalPlayer); -// ...sent over the network, stored, or compared later... -VRCPlayerApi winner = TsPlayer.FindPlayerByID(winnerId); -if (winner != null) -{ - LogInfo(winner.displayName + " is still here."); -} -``` - -## Methods - -- **`GetPlayerID(VRCPlayerApi)`** — builds the `displayName#playerId` string for a player. -- **`GetNumericPlayerId(string)`** — extracts the numeric ID from a `GetPlayerID` string, by - scanning backward from the end for digits until a `#` or a non-digit. It parses by hand - instead of calling `int.Parse`, since Core avoids standard-library calls that the Udon - runtime isn't guaranteed to support. A malformed string (no `#` at all, a `#` with nothing - after it, or a non-digit character right after the last `#`) returns `0` instead of - throwing. A display name that contains `#` works too: parsing from the end finds the last - `#`, which is the one `GetPlayerID` appended. -- **`FindPlayerByID(string)`** — finds the live `VRCPlayerApi` matching a `GetPlayerID` - string among players currently in the instance, or `null` if none match (for example, the - player already left). -- **`GetAllPlayers()`** / **`GetAllPlayerIDs()`** — the current player list, as - `VRCPlayerApi[]` or as ID strings. -- **`ToPlayerIDs(VRCPlayerApi[])`** / **`ToPlayerApis(string[])`** — convert between the two - representations. `ToPlayerApis` fetches the player list once for all lookups instead of - calling `GetAllPlayers()` per ID, and its result holds only the IDs that resolved to a live - player: an ID for someone who left the instance is dropped, not returned as a `null` entry. -- **`ToArray(string)`** — wraps a single player ID in a one-element array, for APIs that - expect an array. - -## Edge cases - -`GetNumericPlayerId("First#0")` returns `0`, the same value it returns for a string with no numeric -ID, so a caller can't tell the two apart from the result alone. diff --git a/docs/core/testing/testing-your-world.md b/docs/core/testing/testing-your-world.md deleted file mode 100644 index a7376f4..0000000 --- a/docs/core/testing/testing-your-world.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -id: testing-your-world -title: Testing your world -sidebar_position: 1 ---- - -# Testing your world - -Test a world built on Core with [Udon Test Kit](/docs/udon-test-kit/intro), which runs Play Mode -tests in a real ClientSim session and works around the VRChat SDK problems that break them. Core -depends on the kit, so it's already in your project, and Core has no testing helpers of its own: -players, ownership, saved data, spies and reaching private fields all come from the kit. - -This page covers what's particular to a world built on Core: how a test builds your behaviours, -and what the Core codegen does while tests run. See [Set up automated -testing](../how-to/set-up-automated-testing) to add the assemblies to your project, and [Write your -first automated test](../how-to/writing-your-first-test) for a worked example. - -## Your behaviours in a test - -A test adds your behaviour to a GameObject with `AddComponent` and constructs it with -`TsConstruct`, the call your generated root makes at world startup. A behaviour that doesn't reach -`_ts` during the test can take `null`: - -```csharp -var referee = new GameObject("RoundReferee").AddComponent(); -referee.TsConstruct((TsRoot)null); -``` - -`TsConstruct` runs the behaviour's `TsStart` once, as at startup. An `AddComponent`-created -behaviour is plain C#, never compiled to Udon, so Unity doesn't call its `Start()` and the generated -startup sequence never runs for it; the test calls what it needs directly. - -Give the test class a [scene of its own](/docs/udon-test-kit/how-to/running-tests-in-their-own-scene), -and everything a test created is destroyed when it ends. - -## Codegen during a test run - -A test that creates or changes scene objects would otherwise trigger the reactive Core codegen, -which could regenerate your project's real output against the test's temporary scene. -[`TsGenerator`](../codegen/internals/ts-generator) skips every automatic trigger while tests run, -from the Test Runner window or the command line, and while the Editor enters Play Mode, so there's -nothing to set up for it. diff --git a/docs/core/ui-components/list/list-item.md b/docs/core/ui-components/list/list-item.md deleted file mode 100644 index 64d8fe2..0000000 --- a/docs/core/ui-components/list/list-item.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -id: list-item -title: ListItem -sidebar_position: 2 ---- - -# ListItem - -`Tsvrc.UI.ListItem` is the base class for a single row in a [`TsvrcList`](./tsvrc-list). -Its generated shadow is `TsListItem`. You don't create or destroy instances yourself: -`TsvrcList` instantiates, binds, unbinds, and destroys them as its pool and pagination -require. - -## Usage - -Subclass it and override the two lifecycle hooks: - -```csharp -public class MyRow : TsListItem -{ - protected override void _OnBind() - { - // _itemData, _dataIndex are populated here; populate your UI children from them. - } - - protected override void _OnUnbind() - { - // _itemData and _dataIndex are STILL valid here — clear UI state before they're cleared. - } -} -``` - -`_OnBind` runs when `TsvrcList` assigns this instance a row of data (`_itemData`, a -`DataDictionary`, and `_dataIndex`, its position in the full data list, not necessarily its -position on the current page). `_OnUnbind` runs when the list is done with this instance, -before `_dataIndex`/`_itemData` are actually cleared, so your override can still read them -one last time if cleanup needs to reference which row it was. - -`IsBound` reports whether the item currently holds live data: `false` between -`Unbind()` and the next `Bind()` call, useful for guarding UI logic that shouldn't run on a -pooled-but-currently-unbound instance. - -## Wiring selection - -Wire `_OnItemPressed` to the `onClick` of a `Button`. It's a no-op if the item isn't currently -bound (guards against a stray press on a pooled item mid-transition). Otherwise it calls -back into the owning list's `OnItemSelected(dataIndex)`, which is what actually records the -selection and emits `TsvrcList.OnItemSelectedEvent`. `ListItem` itself never emits that event -directly; it only triggers the list's own handling of it. diff --git a/docs/core/ui-components/list/tsvrc-list.md b/docs/core/ui-components/list/tsvrc-list.md deleted file mode 100644 index a1e170e..0000000 --- a/docs/core/ui-components/list/tsvrc-list.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -id: tsvrc-list -title: TsvrcList -sidebar_position: 1 ---- - -# TsvrcList - -`Tsvrc.UI.TsvrcList` is a pooled, paginated list view: it instantiates one -[`ListItem`](./list-item) per visible row rather than one per data entry, so a list backed -by thousands of rows only ever pays for however many are on screen at once. Its generated -shadow is `TsList`. Local-only and unsynced: each client's own list state is independent. -See [Build a paginated list UI](../../how-to/building-a-list-ui) for a task-oriented -walkthrough. - -## Setup - -Wire up in the inspector: `_itemContainer` (typically the `Content` transform of a `ScrollRect`) -and `_itemPrefab` (a prefab carrying a `ListItem` component). Set `_pageSize` to a positive -number to paginate, or `-1` to load every item on one page with no pagination at all. - -## Usage - -```csharp -list.SetData(dataList); // a VRC.SDK3.Data.DataList of DataDictionary entries -``` - -The list is always in one of three states, read via `ListState`: `STATE_LOADING`, -`STATE_EMPTY`, or `STATE_POPULATED`. `SetData` resets to the first page and picks between the -latter two based on what it's given: `STATE_EMPTY` if called with `null` or a zero-length -list (shows the empty indicator), `STATE_POPULATED` otherwise (rebuilds the item pool for the -current page). `SetData` never enters `STATE_LOADING`; only `SetLoadingState()` does that, -destroying all live items and showing the loading indicator if one is wired up. -`SelectedIndex`, `CurrentPage`, and -`PageCount` are all readable, along with `HasNextPage`/`HasPreviousPage` for wiring up -pagination controls (`NextPage()`/`PreviousPage()` call `SetPage` for you, and are no-ops at -either end of the range). - -Each list entry is expected to be a `DataDictionary` token; a non-dictionary entry at a given -index is silently treated as an empty dictionary rather than causing an error, so the -`_OnBind` override in a `ListItem` should be written defensively against missing keys either -way. - -## Selection - -A [`ListItem`](./list-item) calls back into `OnItemSelected(dataIndex)` when pressed. -`TsvrcList` records the index and emits `OnItemSelectedEvent` via `TsEmit`, so anything -elsewhere in your world can subscribe via `TsSubscribe` rather than needing a direct -reference to the specific pressed item. `ClearSelection()` resets `SelectedIndex` to `-1` -without touching anything else. - -## Pool rebuild behavior - -`SetPage`, `SetData`, and `SetLoadingState` all destroy every currently-live `ListItem` -(calling `Unbind()` on each first) before creating whatever the new state needs. There's no -attempt to diff and reuse items across a page change or state transition. This keeps the -pooling logic simple at the cost of a full rebuild on every page turn; if a prefab's -`_OnBind`/`_OnUnbind` are expensive, that cost is paid on every page change, not just once. -A prefab instance that comes back from `Instantiate` without a `ListItem` component attached -is destroyed immediately and skipped, rather than left in the pool in a broken state. diff --git a/docs/core/ui-components/overlay/player-marker-renderer.md b/docs/core/ui-components/overlay/player-marker-renderer.md deleted file mode 100644 index ed90090..0000000 --- a/docs/core/ui-components/overlay/player-marker-renderer.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -id: player-marker-renderer -title: PlayerMarkerRenderer -sidebar_position: 2 ---- - -# PlayerMarkerRenderer - -`Tsvrc.UI.PlayerMarkerRenderer` is the pluggable presentation strategy a -[`PlayerPositionOverlay`](./player-position-overlay) reports positions to. The overlay only -ever decides *when* and *where*; this class (or a subclass of it) decides what a marker -actually looks like and how it's drawn. It's a plain, non-`abstract` base with empty-bodied -virtual methods, deliberately, so a subclass that only overrides one of the two methods -still works: the other simply does nothing. A `PlayerPositionOverlay` with no `Renderer` -assigned is a separate, explicit case: `StartOverlay` and the tracking hooks all check for -`Renderer == null` themselves and refuse to run rather than relying on this class's own -safety for that. - -## Overriding it - -```csharp -public class MyRenderer : PlayerMarkerRenderer -{ - public override bool UsesHeading => false; // skip the overlay's rotation read if unneeded - - public override void OnMarkerVisible(Vector3 worldPosition, bool isLocalPlayer, float headingDegrees, string playerId) - { - // Called once per visible tracked player, every blink-show cycle. - } - - public override void OnPresent() - { - // Called once per blink tick, after this cycle's OnMarkerVisible calls (none, on a hide cycle). - // Batch-present anything accumulated in OnMarkerVisible here. - } -} -``` - -`UsesHeading` defaults to `true`; override it to `false` if your presentation doesn't care -about facing direction, so the overlay skips the extra `GetRotation()` call for every -tracked player, every remote tick. `OnMarkerVisible` fires per visible player; `OnPresent` -fires once per cycle regardless of how many (or how few) markers were visible that cycle: -it's the natural place to do a single batched flush rather than committing per-marker work -immediately in `OnMarkerVisible`. See [`RasterPlayerMarkerRenderer`](./raster-player-marker-renderer) -for a ready-made base that does exactly that. diff --git a/docs/core/ui-components/overlay/player-position-overlay.md b/docs/core/ui-components/overlay/player-position-overlay.md deleted file mode 100644 index 579cdf6..0000000 --- a/docs/core/ui-components/overlay/player-position-overlay.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: player-position-overlay -title: PlayerPositionOverlay -sidebar_position: 1 ---- - -# PlayerPositionOverlay - -`Tsvrc.UI.PlayerPositionOverlay` is a [PlayerTracker](../../players-tracking/player-tracker) that -periodically reports the world position of each tracked player on a blinking show/hide cycle: -think a radar sweep or a minimap that pulses rather than staying static. Its generated -shadow is `TsPlayerPositionOverlay`. It's a pure backend: it never draws anything itself, -only reports positions to a pluggable [`PlayerMarkerRenderer`](./player-marker-renderer). -Everything about rendering is local and unsynced: each client runs its own independent tick -loop and decides its own presentation. - -## Usage - -```csharp -overlay.Renderer = someRendererInstance; -overlay.StartOverlay(playerIds); -// ... AddTrackedPlayers/RemoveTrackedPlayers to change the set while running ... -overlay.StopOverlay(); -``` - -Subscribe to `OnOverlayUpdatedEvent` to react after every cycle (both a show and a hide -count as a cycle, so this fires roughly twice per blink period). It also fires once more -when the overlay stops or completes, after the final clear, so a subscriber doesn't need a -separate hook just to know when markers are gone for good. - -## Two independent tick loops - -- **The remote tick** (`RemoteUpdateInterval`, default 0.3s) resolves every tracked player - ID to a live `VRCPlayerApi` and caches its position, heading, and identity. It never - touches the renderer directly. -- **The blink tick** (`MarkerOnDuration`/`MarkerOffDuration`) alternates between presenting - every cached position through `Renderer.OnMarkerVisible` and presenting nothing, always - finishing with exactly one `Renderer.OnPresent()` call per cycle regardless of how many - markers were shown. - -Splitting these two matters for cost: resolving player IDs to live references and reading -positions happens only once per `RemoteUpdateInterval`, not once per blink transition, and -`Renderer.UsesHeading` gates a `GetRotation()` call (a comparatively expensive -quaternion-to-Euler conversion) so a renderer that never uses heading never pays for it. - -The local player is the one exception to "everything comes from the cache": it's re-read -fresh at blink-show time from `Networking.LocalPlayer`, rather than through the cached -remote-tick snapshot, since the position of the local player costs almost nothing to read and -benefits from being as current as possible. - -## Stale-tick discarding - -Both tick loops use `SendCustomEventDelayedSeconds`, which can't be canceled once scheduled. Each maintains its own counter, incremented on every -schedule and decremented on every fire; a tick only actually runs its body if its counter has -returned to zero, meaning no newer tick of the same kind is already queued behind it. This is -what makes `StartOverlay`/`StopOverlay`/`OnTrackingDeserialization` restarting the loop -mid-flight safe: an old, now-superseded tick fires, sees a nonzero counter, and does -nothing. - -## Buffers are pre-sized to the VRChat cap - -Every internal buffer (cached positions, headings, player IDs, live player references) is -sized to 82, the [worst-case absolute maximum instance -size](https://wiki.vrchat.com/wiki/Special:MyLanguage/Instances) (80 is the VRChat -configurable hard cap; the world author and instance creator can each still join on top of -that), allocated once, lazily, on first use, and reused every tick rather than reallocated. -`_ResolveTrackedPlayers` allocates nothing: it compares the number after the last `#` of each -tracked ID with `VRCPlayerApi.playerId`, without building an ID string per player. A malformed -tracked ID, with no number after a `#`, is skipped without an error. diff --git a/docs/core/ui-components/overlay/raster-player-marker-renderer.md b/docs/core/ui-components/overlay/raster-player-marker-renderer.md deleted file mode 100644 index e5822d3..0000000 --- a/docs/core/ui-components/overlay/raster-player-marker-renderer.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -id: raster-player-marker-renderer -title: RasterPlayerMarkerRenderer -sidebar_position: 3 ---- - -# RasterPlayerMarkerRenderer - -`Tsvrc.UI.RasterPlayerMarkerRenderer` is an optional -[`PlayerMarkerRenderer`](./player-marker-renderer) base that paints markers into a raster -texture displayed on a `RawImage`: a minimap-style overlay. It owns all the texture and -pixel-buffer plumbing, the world-to-pixel coordinate mapping, and a flush-only-when-dirty -optimization; you only override `DrawMarker` to decide what gets painted at each player's -projected pixel position, typically using the [`TextureGraphics2D`](../texture-graphics-2d) -drawing primitives. A separate public `MarkerShape` enum (`Circle`/`Triangle`) ships -alongside this class for a subclass's own use when labeling marker styles; the class itself -never reads it. - -## Setup - -```csharp -renderer.Setup(width: 256, height: 256, worldOrigin: someWorldPoint, unitsPerGridX: 4f, unitsPerGridZ: 4f); -``` - -`Setup` allocates the texture and pixel buffer and configures the world-to-pixel mapping: -`worldOrigin` is the world-space point that maps to pixel `(0, 0)` (the bottom-left corner -on the XZ plane), and `unitsPerGridX`/`Z` are pixels per world unit along each axis. It's -safe to call again to reconfigure (the old texture is destroyed first). Three things make it -reject the call with a logged error instead of producing a broken texture: no `OverlayImage` -assigned, non-positive `width`/`height`, or non-positive `unitsPerGridX`/`Z`. `OverlayFilterMode` -(default `Point`) controls whether the result looks crisp (good for pixel-art-style -minimaps) or smooth when the `RawImage` is scaled up, but it's only read at `Setup()` time: -changing it afterward has no effect until `Setup` runs again. Until `Setup` succeeds at -least once, `DrawMarker` is never called and `OnPresent` never flushes; both silently no-op -rather than throwing on an unconfigured renderer. - -## Overriding DrawMarker - -```csharp -public override void DrawMarker(Color32[] pixelBuffer, int textureWidth, int textureHeight, - int pixelX, int pixelY, bool isLocalPlayer, float headingDegrees, string playerId) -{ - TextureGraphics2D.DrawCircleToBuffer(pixelBuffer, textureWidth, textureHeight, pixelX, pixelY, 4, someColor); -} -``` - -`OnMarkerVisible` (inherited, already implemented) projects the given world position into a -pixel coordinate, clamped to stay within the texture bounds rather than wrapping or -throwing for a player outside the mapped world region, and calls `DrawMarker` with that -projected position. You draw directly into the shared pixel buffer using whichever -`TextureGraphics2D` buffer-based primitives fit your marker shape. - -## Flush-only-when-dirty - -`OnPresent` (also inherited) only actually re-uploads the texture to the GPU when something -changed. A cycle where `DrawMarker` was called at least once flushes the drawn buffer and -marks it dirty; the *next* cycle, if nothing was drawn (a hide cycle, or every tracked player -left), clears the buffer once, flushes that single clear, and then stops flushing entirely -until something is drawn again. This means an idle overlay with no visible markers costs -nothing per cycle beyond a single flag check. The GPU only ever sees a new frame of texture -data when the picture has actually changed. diff --git a/docs/core/ui-components/texture-graphics-2d.md b/docs/core/ui-components/texture-graphics-2d.md deleted file mode 100644 index 631aed5..0000000 --- a/docs/core/ui-components/texture-graphics-2d.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -id: texture-graphics-2d -title: TextureGraphics2D -sidebar_position: 3 ---- - -# TextureGraphics2D - -`Tsvrc.UI.Utils.TextureGraphics2D` is a static utility for pixel-level 2D drawing onto -Unity textures: whole-texture fills, lines (including horizontal/vertical spans), circles, -and headed triangles. It's a software rasterizer, no GPU shader involved, built for -UdonSharp contexts where drawing a handful of shapes onto a small texture (an overlay HUD, -a minimap marker) is simpler than setting up a render pipeline for it. - -## Two families of method, and when to use each - -Every drawing operation comes in two forms, and neither one reaches the GPU by itself: - -- **Texture methods** (`DrawLine`, `DrawCircle`, `FillTexture`, ...) write straight into the - `Texture2D` you pass in, but only into its CPU-side pixel data. [The Unity `SetPixel` - docs say so - directly](https://docs.unity3d.com/ScriptReference/Texture2D.SetPixel.html): "you must - call `Apply` after `SetPixel`" for a change to actually reach the GPU. None of these - methods call `Apply` for you, so nothing you draw with them is visible until you call - `texture.Apply()` yourself once you're done. `DrawLine`, `DrawHorizontalLine`, - `DrawVerticalLine`, and `DrawCircle` write pixel by pixel via `Texture2D.SetPixel`, each - with its own bounds check. `FillTexture` and `ClearTexture` are the exception within this - family: they build a full-size array and write it in one shot via `Texture2D.SetPixels32` - rather than looping over `SetPixel`, but they still don't call `Apply` either. -- **Buffer methods** (`DrawLineToBuffer`, `DrawCircleToBuffer`, ...) write into a - pre-allocated `Color32[]` buffer you own instead of a `Texture2D`, and pre-clamp their - drawing bounds once up front rather than checking per pixel. Nothing reaches even the - texture's CPU-side data, let alone the GPU, until you call `FlushBuffer`. - -Use the buffer form whenever you're drawing more than one or two shapes before the result -needs to be visible: skipping repeated `SetPixel` calls in favor of plain array writes, and -paying for [the genuinely expensive -`Apply()`](https://docs.unity3d.com/ScriptReference/Texture2D.Apply.html) exactly once no -matter how many shapes you drew, is the entire reason the buffer family exists. The Unity -docs for `Apply` say why: it "copies all the pixels in the texture even if you've only -changed some of the pixels," so the fewer times you call it, the better. - -## Coordinate and bounds conventions - -Every method that takes explicit coordinates uses pixel coordinates with `(0, 0)` at the -[bottom-left corner](https://docs.unity3d.com/ScriptReference/Texture2D.GetPixel.html) -("the lower left corner is (0, 0)," as the Unity docs put it), and clips silently at the -texture's or buffer's edges: a shape drawn partially or entirely out of bounds never throws, -it just doesn't draw the out-of-bounds part. `FillTexture` and `ClearTexture` take no -coordinates at all; they always cover the whole texture. - -Buffer methods clip against `bufferWidth`/`bufferHeight`, the two parameters you pass -alongside the array, not against `buffer.Length` itself. Passing a buffer shorter than -`bufferWidth * bufferHeight` throws `IndexOutOfRangeException` once a clipped-in-bounds -pixel lands past the buffer's real length; a zero-length buffer with matching zero -dimensions is fine and simply draws nothing. In other words: coordinates are always safe to -pass, but the buffer size and the width/height you pass alongside it must actually agree. - -None of the methods null-check their `texture` or `buffer` argument, but the two families -fail differently on `null`. A texture-based method always touches `texture` on its very -first pixel regardless of the coordinates given, so a `null` texture throws -`NullReferenceException` unconditionally. A buffer-based method pre-clamps its drawing -bounds before writing anything, so a `null` buffer paired with a shape whose bounds end up -empty (a negative radius, a zero-length span, a triangle entirely off the buffer) never -actually indexes into the buffer, and doesn't throw at all: it just draws nothing, same as -it would with a real buffer in that situation. - -## Shape-specific behavior - -- **`DrawLine` / `DrawLineToBuffer`** use Bresenham's algorithm with a square brush of the - given `thickness` centered on each point. Thickness `0` still draws a single-pixel-wide - line (the brush half-width is `thickness / 2` with integer division, so it degenerates to - one row/column rather than disappearing). A zero-length line (equal start and end points) - draws a single point. -- **`DrawHorizontalLine` / `DrawVerticalLine`** (and their buffer equivalents) draw a solid - span. Zero thickness or zero length draws nothing, unlike `DrawLine`: there's no - brush-degenerates-to-one-pixel behavior here. -- **`DrawCircle` / `DrawCircleToBuffer`** fill a disc using the `dx² + dy² ≤ r²` test. - Radius `0` draws a single center pixel. Radius `1` draws a plus shape, not a 3×3 square: - the four diagonal pixels are at distance `√2` from the center, which fails the `≤ 1` test. - A negative radius draws nothing (the iteration range is empty rather than throwing). -- **`DrawTriangleToBuffer`** draws a filled, direction-aware triangle inscribed in a - `(2×halfWidth) × (2×halfHeight)` box. `headingDegrees` follows the Unity Y-axis rotation - convention: `0°` points the tip toward `+Y` (up), and increasing degrees rotate the tip - clockwise (`90°` toward `+X`). Headings outside `[0, 360)`, including negative values, are - accepted directly: trigonometric functions handle the wraparound, so `-90°` points the - same direction as `270°`. Degenerate or negative half-extents don't throw. - -## Usage - -Drawing several shapes and uploading once, the pattern the buffer methods exist for: - -```csharp -var buffer = new Color32[texture.width * texture.height]; -TextureGraphics2D.ClearBuffer(buffer); - -TextureGraphics2D.DrawCircleToBuffer(buffer, texture.width, texture.height, - centerX, centerY, radius: 6, color: Color.red); -TextureGraphics2D.DrawLineToBuffer(buffer, texture.width, texture.height, - x0, y0, x1, y1, thickness: 2, color: Color.white); - -TextureGraphics2D.FlushBuffer(texture, buffer); -``` - -Calling the non-buffer `DrawCircle`/`DrawLine` methods instead works too, but remember to -call `texture.Apply()` yourself afterward: nothing is visible until you do. Reach for those -only when you're drawing a single shape and don't need the buffer; drawing several shapes -this way still means writing them all before that one `Apply()` call, or you pay its full -cost per shape instead of once. - -## Buffer-only helpers - -`ClearBuffer` and `FillBuffer` write to every element of a buffer (transparent or a solid -color respectively) without touching the GPU. `FlushBuffer` is what actually uploads a -buffer via `SetPixels32` followed by `Texture2D.Apply(false)`. The `false` skips mipmap -recalculation, which only matters if the texture was created with a mip chain in the first -place. diff --git a/docs/core/utilities/mesh-combiner.md b/docs/core/utilities/mesh-combiner.md deleted file mode 100644 index 415bd35..0000000 --- a/docs/core/utilities/mesh-combiner.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -id: mesh-combiner -title: Mesh Combiner -sidebar_position: 5 ---- - -# Mesh Combiner - -**Tsvrc > Tools > Mesh Combiner** (`MeshCombinerWindow`, backed by the pure -`MeshCombinerTool.Combine`) merges multiple `MeshFilter` sources into a single -multi-material mesh asset, along with their colliders. It's independent of the rest of the -codegen system: no dependency on `TsConfig`, `TsGenerator`, or any other module. See -[Combine meshes and colliders before uploading](../how-to/combining-meshes) for a -task-oriented walkthrough. - -## Usage - -Select scene objects, click **Load from Selection** (or add `MeshFilter` slots manually), -choose a save path, and click **Combine**. Loading from selection also picks up two kinds of -object that don't need their own slot: GameObjects with colliders but no `MeshFilter` -(collider-only sources), and GameObjects with a `ParticleSystem` but no `MeshFilter`, unless -that GameObject also carries an `UdonSharpBehaviour`, in which case it's skipped entirely -rather than picked up as either kind. - -## Settings - -- **Recalculate Normals** (off by default) — recomputes normals from the combined geometry. - Leave it off to preserve baked or hand-authored normals from the source meshes. -- **Exclude EditorOnly** (on by default) — skips source GameObjects tagged `EditorOnly`. -- **Combine Colliders** (on by default) — merges solid `MeshCollider`s and collects - primitive/trigger colliders for recreation; see the next section for exactly how. -- **Reparent Particle Systems** (on by default) — moves each collected `ParticleSystem` - GameObject to be a child of the combined output instead of merging it, preserving its - settings and simulation state. Turning it off leaves those GameObjects exactly where they - started, still active, not reparented and not deactivated. -- **Deactivate Sources** (on by default) — see "What a combine actually creates" below. - -## What gets merged, and what doesn't - -The visual mesh is built in two passes: sources are first merged per-material into flat -meshes, then those per-material meshes are combined again as separate submeshes. This is -what keeps material boundaries intact in the final multi-material result rather than losing -per-source materials. A submesh index past the end of its source's material array reuses -that array's last material, matching how the Unity `MeshRenderer` handles the same -mismatch. Colliders follow their own rules: - -- A **solid `MeshCollider`** merges into one combined collision mesh. -- A **trigger `MeshCollider`**, or any **primitive collider** (Box/Sphere/Capsule), can't be - merged that way: a trigger flag or a primitive shape would be lost in a merge, so these are - returned separately for the caller to recreate as individual child GameObjects instead. A - trigger `MeshCollider` with no mesh assigned has no physics shape to recreate either way, - so it's skipped entirely rather than merged or recreated. -- A **disabled collider** is skipped entirely rather than recreated enabled, since silently - re-enabling it would be a real behavior change, not a mesh optimization. -- A source carrying an `UdonSharpBehaviour` has its colliders **excluded from collection - entirely**, so its physics callbacks (`OnTriggerEnter`, etc.) keep firing against the - original object rather than a combined mesh that can't dispatch Udon events the same way. - -Reparenting a `ParticleSystem` out of a prefab instance runs into a Unity restriction: you -can't reparent a transform that's inside one. The tool works around this by unpacking the -enclosing prefab instance, layer by layer, until the GameObject is free to move, before -setting its new parent. - -## Two known trap conditions, checked before combining - -Two situations disable the Combine button outright with an explanatory message, rather than -letting a combine "succeed" and produce a broken or invisible result: - -- **Running in Play Mode** — a combine creates real scene objects and assets; anything - created in Play Mode vanishes on exit, so combining there would look like it worked and - then silently lose everything. -- **The chosen root Transform is itself one of the sources being combined, or a descendant - of one.** The window's default behavior deactivates source objects after a successful - combine (`_deactivateSources`), and `Transform.activeInHierarchy` cascades to children. - If the combined result was just reparented under a Transform that then gets deactivated as - a "source," the newly-created mesh vanishes from the Scene view with no error at all. - Reordering the deactivate and reparent steps wouldn't fix this case (the root itself is - the thing being deactivated), so it's caught and blocked before `Combine` ever runs - instead. - -Every combine groups its GameObject-level changes (the new GameObject, recreated collider -children, source deactivation) under one Undo name, so a single Ctrl+Z reverses all of them -at once rather than requiring several undo steps. The saved mesh asset(s) on disk aren't -part of that: the Unity `Undo` system doesn't track `AssetDatabase.CreateAsset`, so undoing a -combine leaves the `.asset` file (and the `_Collider.asset` file, if one was created) in -place. Delete those manually if you undo a combine you don't want to keep. - -## What a combine actually creates - -A successful combine saves the visual mesh to the chosen path, and, only when merged -colliders exist, a second collision-mesh asset saved alongside it at the same path with -`_Collider` inserted before the extension. It then creates one new GameObject holding the -combined `MeshFilter`/`MeshRenderer` (and a `MeshCollider` referencing the collision mesh, if -any), reparented under the chosen root, plus one child GameObject per recreated primitive or -trigger collider, positioned and scaled to match the original, plus (with **Reparent -Particle Systems** on) each collected `ParticleSystem` GameObject moved under the same root. - -Deactivating sources afterward (the default, toggled by **Deactivate Sources**) treats a -source with an `UdonSharpBehaviour` differently from an ordinary one: instead of deactivating -the whole GameObject, it only disables that source's `MeshRenderer`, leaving the GameObject -itself, and so the Udon script and its collider, active. A collider-only source only gets -deactivated when its collider was actually folded into the combined result (**Combine -Colliders** on); deactivating one whose collider was never combined would remove its physics -with nothing left to replace it. A collider-only source that was also just reparented as a -particle system is never deactivated either, regardless of that setting: it moved, it wasn't -left behind as a source to retire. - -`Combine` never checks a source's own active state: an inactive `MeshFilter` still -contributes geometry, unlike `Exclude EditorOnly`, which is an explicit opt-in filter rather -than an implicit one. diff --git a/docs/core/utilities/read-only-attribute.md b/docs/core/utilities/read-only-attribute.md deleted file mode 100644 index 236f041..0000000 --- a/docs/core/utilities/read-only-attribute.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -id: read-only-attribute -title: ReadOnlyAttribute -sidebar_position: 1 ---- - -# ReadOnlyAttribute - -`Tsvrc.Utils.ReadOnlyAttribute` marks a serialized field as read-only in the Unity -Inspector. - -```csharp -[ReadOnly] -public int computedAtRuntime; -``` - -It's a plain `PropertyAttribute` with no members and no behavior on its own: the actual -effect comes from its paired `ReadOnlyDrawer` (in the Editor assembly), which disables the -GUI control while drawing the field so it renders grayed out. This only stops accidental -edits in the Inspector; it doesn't make the field read-only from code, and doesn't affect -serialization. Use it to signal "this value is managed elsewhere," most commonly a field -the codegen generator itself writes, where hand-editing it in the Inspector would just be -overwritten on the next regeneration. -[`WirePoolAttribute`](../core-concepts/core-attributes#wirepoolattribute) uses the same -disable-while-drawing technique for the same reason. diff --git a/docs/core/utilities/ts-array.md b/docs/core/utilities/ts-array.md deleted file mode 100644 index e5955ac..0000000 --- a/docs/core/utilities/ts-array.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -id: ts-array -title: TsArray -sidebar_position: 2 ---- - -# TsArray - -`Tsvrc.Utils.TsArray` is a static helper class for array operations that Udon can't express -generically. UdonSharp doesn't support generic methods, so there's no single `Add`. -Instead `TsArray` overloads each operation for `string[]` and `UdonSharpBehaviour[]`, the -two element types Core itself needs this for. - -## What it's for - -Every method allocates and returns a new array; none of them mutate their inputs. That -makes them safe to call on an array you're still holding a reference to elsewhere, at the -cost of an allocation per call. Don't reach for these in a tight per-frame loop over large -arrays. - -## Methods - -- **`Add(original, items)`** — returns a new array with every element of `original` - followed by every element of `items`. -- **`Remove(original, items)`** — returns a new array with every occurrence of any element - in `items` removed from `original`. All matches are removed, not just the first, and - order is preserved. -- **`Contains(array, value)`** — returns whether `value` is present in `array`, compared by - `==` (reference equality for `UdonSharpBehaviour[]`, value equality for `string[]`). For - `UdonSharpBehaviour[]`, that's [the overridden Unity equality - operator](https://docs.unity3d.com/ScriptReference/Object-operator_eq.html), so a - destroyed-but-not-yet-garbage-collected behaviour still correctly reports as equal to - `null`, not as a dangling non-null reference. -- **`Dedupe(original)`** *(strings only)* — returns a new array with repeated values - collapsed to their first occurrence, order preserved. - -## Usage - -```csharp -private string[] _activeTags = new string[0]; - -public void AddTag(string tag) -{ - if (!TsArray.Contains(_activeTags, tag)) - { - _activeTags = TsArray.Add(_activeTags, new[] { tag }); - } -} - -public void RemoveTag(string tag) -{ - _activeTags = TsArray.Remove(_activeTags, new[] { tag }); -} -``` - -Each call reassigns `_activeTags` to the returned array rather than mutating it in place: -skipping the reassignment silently keeps the old array, since nothing here mutates it. - -## Edge cases worth knowing - -- **No null guards.** Passing `null` for any array parameter throws - `NullReferenceException`: these methods trust the caller, they don't validate input. -- **Always allocates, even when nothing changes.** `Remove` with no matches and `Dedupe` - with no duplicates still return a new array instance, never the original reference. Code - that relies on reference equality to detect "nothing changed" will not see it that way. -- **`null` is a comparable value, not a special case.** `Contains(array, null)` matches a - literal `null` element in the array, and `Dedupe` treats `null` as a value it can - deduplicate like any other. -- **Zero-length inputs produce the same outcome as any other size.** `Dedupe` does take a - separate code path for arrays shorter than 2 elements, but purely as an allocation - shortcut; the result is identical to what the general path would have produced. diff --git a/docs/core/utilities/ts-json.md b/docs/core/utilities/ts-json.md deleted file mode 100644 index eaa3496..0000000 --- a/docs/core/utilities/ts-json.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -id: ts-json -title: TsJson -sidebar_position: 3 ---- - -# TsJson - -`Tsvrc.Utils.TsJson` is a static helper class for converting the VRChat `DataDictionary` and -`DataToken` types to and from JSON, built on top of `VRCJson`. It exists to give the rest of -Core a smaller, consistent surface than calling the `VRCJson` `Try...` methods directly -everywhere a serialization step is needed. - -## Methods - -- **`Serialize(DataDictionary)`** / **`Deserialize(string)`** — convert a dictionary to and - from a minified JSON string. -- **`SerializeToken(DataToken)`** / **`DeserializeToken(string)`** — the same, but for a raw - `DataToken`, which can hold a dictionary, a list, or (on serialize) any other token type. -- **`Clone(DataDictionary)`** — deep-clones a dictionary by serializing it and immediately - deserializing the result. Nested dictionaries and lists inside it are copied too, not - shared by reference, exactly as if you'd round-tripped through JSON yourself. - -## Usage - -```csharp -var payload = new DataDictionary(); -payload.SetValue("round", new DataToken(3)); -payload.SetValue("mapName", new DataToken("Arena")); - -string json = TsJson.Serialize(payload); // send this over the network or into TsvrcMemory -DataDictionary restored = TsJson.Deserialize(json); -if (restored != null) -{ - int round = restored.GetValue("round").Int; -} -``` - -Always check the result of `Deserialize` for `null` before reading from it: see the failure -table below for why a bad string never throws instead. - -## Failure handling - -None of these methods throw on bad input. Every failure path logs through -[`TsvrcLogger.Format`](./tsvrc-logger) (tagged `[TsJson]`) and returns a safe empty value -instead. These calls go straight to `Debug.LogError`, not through a `TsvrcLogger` instance, -so unlike a normal `LogError` call they bypass the six Info/Warning/Error toggles entirely: -a `TsJson` failure always prints, regardless of how logging is configured. - -| Method | On failure, returns | -|---|---| -| `Serialize` | `string.Empty` | -| `Deserialize` | `null` | -| `SerializeToken` | `string.Empty` | -| `DeserializeToken` | `default(DataToken)` | -| `Clone` | `null` | - -This means a caller that doesn't check the return value silently gets an empty string or a -null dictionary rather than an exception. If you're persisting the result (for example into -`TsvrcMemory`), check for `null`/empty before storing it. - -## Edge cases worth knowing - -- **`null` and empty string are rejected before ever reaching `VRCJson`**, both logging - `"Cannot deserialize null or empty JSON string."` But a **whitespace-only** string is not - caught by that same guard (`string.IsNullOrEmpty(" ")` is `false`), so it falls through to - `VRCJson`, fails to parse there instead, and logs a different message - (`"Failed to deserialize JSON string..."`). Both end in `null`/default, but if you're - matching on the exact log message, the two cases aren't interchangeable. -- **A bare scalar is not valid top-level JSON.** `VRCJson` requires an object or array at - the top level, so deserializing `"5"` fails to parse entirely: it does not succeed with a - non-dictionary/non-list token. -- **`Deserialize` additionally rejects anything that isn't a `DataDictionary`.** Valid JSON - that parses to an array (`"[1,2,3]"`) still fails `Deserialize` (wrong shape) even though - the same string succeeds through `DeserializeToken`. -- **`Clone(null)` logs twice.** It's implemented as `Deserialize(Serialize(original))`, so a - `null` input fails `Serialize` (logs once, returns `""`) and then fails `Deserialize` on - that empty string (logs again, returns `null`): one call, two distinct error log lines. diff --git a/docs/core/utilities/tsvrc-logger.md b/docs/core/utilities/tsvrc-logger.md deleted file mode 100644 index 83be820..0000000 --- a/docs/core/utilities/tsvrc-logger.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -id: tsvrc-logger -title: TsvrcLogger -sidebar_position: 4 ---- - -# TsvrcLogger - -`Tsvrc.Utils.TsvrcLogger` is the centralized logging sink in Core: a `TsvrcBehaviour` you reach -through `_ts.Log`, wrapping `Debug.Log`/`LogWarning`/`LogError` with a consistent message -format and independent on/off toggles per severity. Its generated shadow class is -`TsLogger`. Most code never calls it directly: prefer the `TsvrcBehaviour` methods `LogInfo`, -`LogWarning`, and `LogError`, which supply the tag and context automatically. - -## Message format - -Every message follows `[TsVRC] [prefix] [tag] message`, where: - -- `TsVRC` is a fixed framework tag, always present, never configurable. -- `prefix` is your project's own optional tag (`Prefix`, empty by default). Set it once - (for example to your world's name) to distinguish your logs from another package's in a - shared console. Omitted entirely (no empty `[]`) when left blank. -- `tag` is the name of the class that logged the message. - -Configure `Prefix` and the six enable toggles below either directly on the component or -through **Tsvrc > Configure > Logging**. - -## The six toggles - -Info, Warning, and Error are each independently gated by whether the call came from inside -the framework itself or from your world's own code: six toggles in total, all defaulting -to `true`: - -| | Tsvrc internal | Your world | -|---|---|---| -| Info | `InternalInfoEnabled` | `WorldInfoEnabled` | -| Warning | `InternalWarningEnabled` | `WorldWarningEnabled` | -| Error | `InternalErrorEnabled` | `WorldErrorEnabled` | - -Which column a message falls into is decided by the caller, not the message content: a -`TsvrcBehaviour` subclass reports itself as internal via `IsTsvrcInternal` (`true` for -framework classes like `Process` or `TsvrcMemory`, `false` by default, meaning every one of -your own scripts is "Your world" unless it deliberately opts in). Calling `Info`/`Warning`/ -`Error` directly on the logger without going through a `TsvrcBehaviour` defaults -`isInternal` to `false`. - -The two columns are independent: disabling `WorldInfoEnabled` doesn't touch -`InternalInfoEnabled`, and vice versa. Severity levels are independent of each other too: -turning off Info logging entirely still lets Warning and Error through. - -## What happens before construction - -`TsvrcBehaviour.LogInfo`/`LogWarning`/`LogError` read `_ts.Log`, which is `null` until -`TsConstruct` has run. Called before that point, they fall back to calling -`Debug.Log`/`LogWarning`/`LogError` directly, using the same message format with an empty -prefix, but that fallback path bypasses every one of the six toggles above, since there's -no `TsvrcLogger` instance yet to check them against. A message logged before construction -always prints, regardless of how logging is configured. - -[`TsJson`](./ts-json) hits the same kind of bypass for a different reason: its own failure -logs call `Debug.LogError` directly rather than going through a `TsvrcLogger` instance at -all, so they always print too, construction timing aside. - -## Usage - -From inside any `TsvrcBehaviour` subclass, log through the inherited wrappers rather than -touching `_ts.Log` directly: - -```csharp -public class GameManager : TsBehaviour -{ - private void StartRound() - { - LogInfo("Round started"); - if (_players.Length == 0) - { - LogWarning("Starting a round with no players registered"); - } - } -} -``` - -`LogInfo`/`LogWarning`/`LogError` fill in the `[GameManager]` tag and the "Your world" -column automatically. See the toggle table above for what controls whether this message -actually prints. - -## Edge case worth knowing - -Calling `Info`/`Warning`/`Error` on the logger directly, rather than through the -wrappers on a `TsvrcBehaviour`, means you supply your own `tag` string and `isInternal` value -by hand: there's no automatic class-name tag or `IsTsvrcInternal` lookup at that layer. diff --git a/i18n/es/code.json b/i18n/es/code.json index 20eca4d..596b12a 100644 --- a/i18n/es/code.json +++ b/i18n/es/code.json @@ -1,13 +1,4 @@ { - "core.notice.title": { - "message": "Antes de construir con esto" - }, - "core.notice.vrchat": { - "message": "TsVRC no está afiliado a VRChat Inc. ni cuenta con su respaldo." - }, - "core.notice.body": { - "message": "Además, sigue siendo un trabajo en curso. Cada parte tiene sus propios tests, y los ejecutamos antes de cada versión, pero no podemos prometer haber cubierto todos los casos. Guarda una copia de seguridad de tu proyecto antes de añadir Core o de actualizarlo, solo por si acaso. Si algo se rompe de tu lado, no podemos arreglarlo por ti, pero nos gustaría mucho saberlo. Abre un issue en GitHub y le echaremos un vistazo." - }, "homepage.hero.greeting": { "message": "Hola, soy {name}" }, @@ -17,9 +8,6 @@ "homepage.hero.intro": { "message": "Creo herramientas para crear mundos de VRChat. TsVRC es el nombre con el que las publico, y la mayoría son de código abierto." }, - "homepage.projects.core.description": { - "message": "Una forma estructurada de crear mundos de VRChat con UdonSharp: inicio consistente, dependencias ya conectadas y código generado en vez de conectarlo todo a mano." - }, "homepage.projects.udonTestKit.description": { "message": "Tests de Unity Test Framework para mundos de VRChat, con tus behaviours de UdonSharp ejecutándose en una sesión real de ClientSim." }, @@ -53,129 +41,6 @@ "homepage.meta.description": { "message": "Herramientas de código abierto de Toni para crear mundos de VRChat, publicadas como TsVRC." }, - "core.hero.title": { - "message": "Un framework para mundos de VRChat construido sobre UdonSharp" - }, - "core.hero.subtitle": { - "message": "Inicialización estructurada, conexión de dependencias y generación de código en el editor, para que tus scripts de mundo hereden de una clase base tipada en vez de conectar referencias a mano cada vez que agregas un behaviour." - }, - "core.hero.cta.docs": { - "message": "Leer la documentación" - }, - "core.hero.cta.github": { - "message": "Ver en GitHub" - }, - "core.hero.jumpToLabel": { - "message": "Ir a:" - }, - "core.hero.jump.why": { - "message": "Por qué existe" - }, - "core.hero.jump.blocks": { - "message": "Las piezas fundamentales" - }, - "core.hero.jump.start": { - "message": "Empezar" - }, - "core.hero.scrollCue": { - "message": "Desplázate para saber más" - }, - "core.hero.annotation.behaviour.title": { - "message": "TsBehaviour" - }, - "core.hero.annotation.behaviour.description": { - "message": "La clase generada de la que hereda cada script. Es lo que le da a este behaviour su referencia _ts." - }, - "core.hero.annotation.globals.title": { - "message": "Globals" - }, - "core.hero.annotation.globals.description": { - "message": "Cualquier objeto de la escena con nombre, accesible como _ts.Name desde cualquier behaviour, sin arrastrar referencias a mano." - }, - "core.hero.annotation.memory.title": { - "message": "Memory" - }, - "core.hero.annotation.memory.description": { - "message": "El almacén de clave-valor compartido, accesible como _ts.Memory desde cualquier parte." - }, - "core.hero.annotation.more.title": { - "message": "Y eso no es todo" - }, - "core.hero.annotation.more.description": { - "message": "Y hay más de donde vino eso. Mira el resto de las piezas fundamentales de Core más abajo." - }, - "core.why.title": { - "message": "Por qué existe" - }, - "core.why.paragraph1": { - "message": "Cada script de UdonSharp se inicia por su cuenta, sin garantía de en qué orden pasan las cosas y sin una forma fácil de llegar a otro script en tu mundo. La mayoría de los creadores lo resuelve a mano: arrastrando referencias entre objetos en el Inspector, y con la esperanza de que todo siga conectado cuando el mundo carga." - }, - "core.why.paragraph2": { - "message": "Core le da a cada script una única referencia compartida, {code}, para llegar a cualquier otra cosa de tu proyecto. La configuración ocurre en un orden que tú controlas, y Core descubre de antemano cuál de tus propias clases usar, en el editor de Unity. Consulta {link} para ver el panorama completo." - }, - "core.why.linkText": { - "message": "cómo encaja Core" - }, - "core.features.constructs.title": { - "message": "Constructs" - }, - "core.features.constructs.description": { - "message": "Registra un TsvrcBehaviour una vez y Core lo inicializa por ti, en un orden fijo, mediante TsStart, en vez de que tengas que encargarte tú de iniciarlo a mano." - }, - "core.features.globals.title": { - "message": "Globals" - }, - "core.features.globals.description": { - "message": "Señala un objeto de la escena una vez y cualquier behaviour puede leerlo de vuelta por su nombre, en vez de arrastrar la misma referencia a una docena de campos del Inspector." - }, - "core.features.memory.title": { - "message": "Memory" - }, - "core.features.memory.description": { - "message": "Un almacén de clave-valor compartido con niveles efímero, persistente y sincronizado, para que llevar un valor a todos los jugadores no signifique escribir tu propia capa de red." - }, - "core.features.factories.title": { - "message": "Factories" - }, - "core.features.factories.description": { - "message": "Instancia un prefab bajo demanda con una llamada _ts.Create... generada, para cualquier cosa que no necesite mantenerse sincronizada entre jugadores." - }, - "core.features.pools.title": { - "message": "Pools" - }, - "core.features.pools.description": { - "message": "Pre-instancia y conecta exactamente las instancias que un prefab en red necesita, en tiempo de edición, porque VRChat no puede sincronizar un objeto creado mientras el mundo está en ejecución." - }, - "core.features.instance.title": { - "message": "Instance" - }, - "core.features.instance.description": { - "message": "Un behaviour por proyecto que representa la instancia de mundo en ejecución, encontrado y conectado automáticamente, para que comprobaciones como \"¿soy el master?\" tengan un único lugar obvio." - }, - "core.features.title": { - "message": "Las piezas fundamentales" - }, - "core.features.subtitle": { - "message": "Seis piezas generadas cubren la mayor parte de lo que necesita un mundo. Registra o señala algo una vez, y luego alcánzalo de la misma forma desde cualquier behaviour." - }, - "core.features.detailsLink": { - "message": "Detalles →" - }, - "core.cta.title": { - "message": "Empieza a construir" - }, - "core.cta.subtitle": { - "message": "Agrega Core mediante VCC y luego sigue la guía de introducción para tener un behaviour funcionando en Play Mode." - }, - "core.cta.button": { - "message": "Empezar" - }, - "core.meta.title": { - "message": "TsVRC Core" - }, - "core.meta.description": { - "message": "TsVRC Core es un framework para crear mundos de VRChat con UdonSharp: inicialización estructurada, conexión de dependencias y generación de código en el editor." - }, "support.meta.title": { "message": "Apoya a TsVRC" }, diff --git a/i18n/es/docusaurus-plugin-content-docs/current/core/intro.md b/i18n/es/docusaurus-plugin-content-docs/current/core/intro.md deleted file mode 100644 index 28983dd..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/core/intro.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -id: intro -title: TsVRC Core -sidebar_position: 1 ---- - -# TsVRC Core - -TsVRC Core es un framework de código abierto para crear mundos de -VRChat con UdonSharp: inicialización estructurada, conexión de dependencias y -generación de código en el editor (codegen) que escribe ese código de conexión por ti, -sobre el VRChat Worlds SDK. - -:::warning[Experimental y pre-1.0] -Core es un experimento, y herramientas de programación con IA generaron parte de sus funciones. No -está hecho por completo con vibe coding, pero la IA tuvo una gran participación al escribirlo. -Además, todavía es pre-1.0: todo lo documentado aquí, incluyendo el comportamiento de casos límite -en las páginas de referencia, describe lo que el código hace hoy, no un contrato de API cerrado. - -Prueba el comportamiento del que depende tu mundo antes de publicarlo. Si buscas proyectos listos -para usar, mira [Udon Test Kit](/docs/udon-test-kit/intro) y -[Udon Tools Kit](https://github.com/tsvrc/udon-tools-kit). -::: - -## ¿Eres nuevo en Core? - -Empieza por [Añade TsVRC Core a tu proyecto](./add-to-your-project) y luego -[Construye tu primer behaviour](./first-behaviour): al final tendrás un script -funcionando en modo Play. - -## ¿Ya lo usas? - -Ve directo a lo que necesitas: - -- **Resolver una tarea concreta** — - [agrupar un prefab en un pool](./how-to/pooling-a-prefab), - [mostrar las posiciones de los jugadores](./how-to/showing-player-positions), - [transferir datos entre clientes](./how-to/transferring-data-between-clients) o - [conectar un ready check](./how-to/wiring-a-ready-check). -- **Buscar el comportamiento de un tipo concreto** — busca su nombre, empieza por - [Cómo encaja Core](./core-concepts/how-it-fits-together) y sigue sus enlaces, o - explora Reference en la barra lateral, agrupado por área: jugadores, red, UI, codegen, - etc. -- **Entender por qué Core funciona como funciona** — - [Codegen en vez de reflexión](./explanations/codegen-vs-reflection) y el resto de - páginas en Explanations. diff --git a/sidebars.ts b/sidebars.ts index cd639c0..b0a4c30 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -6,7 +6,7 @@ import type {SidebarsConfig} from '@docusaurus/plugin-content-docs'; * Each project under docs// gets one top-level category here, built from * autogenerated subtrees so individual pages never need a sidebar entry of their own. * Adding another project means adding its own top-level category the same way - * udon-test-kit's and core's are built below, not relying on blanket autogeneration (see + * udon-test-kit's is built below, not relying on blanket autogeneration (see * AGENTS.md's Gotchas section for why). * * Each labeled category below wraps a single-folder `autogenerated` subtree: pointing @@ -47,111 +47,6 @@ const sidebars: SidebarsConfig = { }, ], }, - { - type: 'category', - label: 'Core', - link: {type: 'doc', id: 'core/intro'}, - items: [ - { - type: 'category', - label: 'Getting started', - items: ['core/add-to-your-project', 'core/first-behaviour'], - }, - { - type: 'category', - label: 'How-to guides', - items: [{type: 'autogenerated', dirName: 'core/how-to'}], - }, - { - type: 'category', - label: 'Reference', - items: [ - { - type: 'category', - label: 'Core concepts', - items: [{type: 'autogenerated', dirName: 'core/core-concepts'}], - }, - { - type: 'category', - label: 'Players & tracking', - items: [{type: 'autogenerated', dirName: 'core/players-tracking'}], - }, - { - type: 'category', - label: 'Networking & data', - items: [ - 'core/networking-data/tsvrc-memory', - 'core/networking-data/tsvrc-timer', - { - type: 'category', - label: 'Data transfer chain', - link: {type: 'doc', id: 'core/networking-data/data-transfer-overview'}, - items: [{type: 'autogenerated', dirName: 'core/networking-data/data-transfer'}], - }, - ], - }, - { - type: 'category', - label: 'UI components', - items: [ - { - type: 'category', - label: 'List', - items: [{type: 'autogenerated', dirName: 'core/ui-components/list'}], - }, - 'core/ui-components/texture-graphics-2d', - { - type: 'category', - label: 'Player position overlay', - items: [{type: 'autogenerated', dirName: 'core/ui-components/overlay'}], - }, - ], - }, - { - type: 'category', - label: 'Game flow', - items: [{type: 'autogenerated', dirName: 'core/game-flow'}], - }, - { - type: 'category', - label: 'Utilities', - items: [{type: 'autogenerated', dirName: 'core/utilities'}], - }, - { - type: 'category', - label: 'Codegen', - items: [ - { - type: 'category', - label: 'Config', - items: [{type: 'autogenerated', dirName: 'core/codegen/config'}], - }, - { - type: 'category', - label: 'Modules', - items: [{type: 'autogenerated', dirName: 'core/codegen/modules'}], - }, - { - type: 'category', - label: 'Internals', - items: [{type: 'autogenerated', dirName: 'core/codegen/internals'}], - }, - ], - }, - { - type: 'category', - label: 'Testing', - items: [{type: 'autogenerated', dirName: 'core/testing'}], - }, - ], - }, - { - type: 'category', - label: 'Explanations', - items: [{type: 'autogenerated', dirName: 'core/explanations'}], - }, - ], - }, // Shared by every project, so it sits at the docs root rather than under one project. 'install-a-package', ], diff --git a/src/components/TsWindowMock/EntriesPanel.tsx b/src/components/TsWindowMock/EntriesPanel.tsx deleted file mode 100644 index fd3d5f9..0000000 --- a/src/components/TsWindowMock/EntriesPanel.tsx +++ /dev/null @@ -1,236 +0,0 @@ -import { useEffect, useRef, useState } from 'react'; -import { COLOR, button, fieldInnerLine } from '@site/src/components/TsWindowMock/styles'; -import { memberPreview, NULL_SLOT_HINT, TAB_CONFIG, type RegistryTabKey } from '@site/src/components/TsWindowMock/data'; -import { PrefabIcon, ScriptIcon } from '@site/src/components/TsWindowMock/Icons'; -import type { ConfigureState } from '@site/src/components/TsWindowMock/useConfigureState'; - -export default function EntriesPanel({ tabKey, state }: { tabKey: RegistryTabKey; state: ConfigureState }) { - const config = TAB_CONFIG[tabKey]; - const tab = state.working.registry[tabKey]; - const group = tab.groups[tab.sel]; - const entries = group ? group.entries : []; - const [pickerIndex, setPickerIndex] = useState(null); - const openEntryRef = useRef(null); - useEffect(() => { - if (pickerIndex === null) return; - function handlePointerDown(e: MouseEvent) { - if (openEntryRef.current && !openEntryRef.current.contains(e.target as Node)) { - setPickerIndex(null); - } - } - document.addEventListener('mousedown', handlePointerDown); - return () => document.removeEventListener('mousedown', handlePointerDown); - }, [pickerIndex]); - - return ( -
-
-
- {group ? group.name : ''} -
-
group && state.addEntry(tabKey)}> - + Add -
-
- - {entries.length === 0 && ( -
- {config.emptyHint} -
- )} - - {entries.length > 0 && ( -
- {entries.map((entry, index) => { - const sub = entry.icon === 'none' ? NULL_SLOT_HINT : memberPreview(tabKey, entry, group.name); - return ( -
-
-
setPickerIndex(pickerIndex === index ? null : index)} - style={{ - flex: 1, - minWidth: 0, - height: 18, - boxSizing: 'border-box', - background: '#282828', - border: `1px solid ${COLOR.borderField}`, - display: 'flex', - alignItems: 'center', - gap: 4, - padding: '0 3px', - cursor: 'default', - ...fieldInnerLine, - }}> -
- {entry.icon === 'prefab' && } - {entry.icon === 'script' && } -
-
- {entry.label} -
-
-
-
-
- {config.showNames && ( -
- state.renameEntry(tabKey, index, e.target.value)} - style={{ - flex: 1, - minWidth: 0, - background: 'transparent', - border: 0, - outline: 'none', - color: COLOR.text, - fontSize: 12, - padding: 0, - }} - /> -
- )} -
state.removeEntry(tabKey, index)} - style={{ - width: 18, - height: 18, - flex: 'none', - background: COLOR.btnBg, - borderRadius: 2, - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - fontSize: 10, - color: COLOR.textBright, - cursor: 'default', - }}> - {'✕'} -
-
- {pickerIndex === index && ( -
-
- {config.entryIcon === 'prefab' ? 'Assign mock prefab' : 'Assign mock object'} -
- {config.catalog.map((name) => ( -
{ - state.assignEntry(tabKey, index, config.entryIcon, name); - setPickerIndex(null); - }} - style={{ height: 16, display: 'flex', alignItems: 'center', gap: 4, padding: '0 6px', cursor: 'default' }}> -
- {config.entryIcon === 'prefab' ? : } -
-
- {name} -
-
- {config.entryIcon === 'prefab' ? 'Prefab' : 'Scene'} -
-
- ))} -
{ - state.assignEntry(tabKey, index, 'none', 'None (Object)'); - setPickerIndex(null); - }} - style={{ height: 16, display: 'flex', alignItems: 'center', padding: '0 6px', color: COLOR.textDim, fontSize: 12, cursor: 'default' }}> - None -
-
- )} - {sub && ( -
-
{'↳'}
-
{sub}
-
- )} -
- ); - })} -
- )} -
- ); -} diff --git a/src/components/TsWindowMock/GeneratedPreview.tsx b/src/components/TsWindowMock/GeneratedPreview.tsx deleted file mode 100644 index 0b61bc1..0000000 --- a/src/components/TsWindowMock/GeneratedPreview.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { memberPreview, sanitizeIdentifier, type RegistryTabData, type RegistryTabKey } from '@site/src/components/TsWindowMock/data'; - -function typeNameOf(label: string): string { - return label.split(' (')[0]; -} - -export default function GeneratedPreview({ registry }: { registry: Record }) { - const lines: string[] = []; - - for (const g of registry.globals.groups) { - for (const entry of g.entries) { - if (entry.icon === 'none') continue; - const preview = memberPreview('globals', entry, g.name); - if (preview) lines.push(preview.replace('', sanitizeIdentifier(typeNameOf(entry.label)))); - } - } - for (const g of registry.constructs.groups) { - for (const entry of g.entries) { - if (entry.icon === 'none') continue; - lines.push(`// ${typeNameOf(entry.label)}.TsStart() runs automatically at world start`); - } - } - const poolTypes = new Set(); - for (const g of registry.pool.groups) - for (const entry of g.entries) if (entry.icon !== 'none') poolTypes.add(typeNameOf(entry.label)); - for (const name of poolTypes) { - lines.push(`// ${name} is registered as poolable - declare [WirePool] on a field of this type to get an instance`); - } - for (const g of registry.factories.groups) { - for (const entry of g.entries) { - if (entry.icon === 'none') continue; - const preview = memberPreview('factories', entry, g.name); - if (preview) lines.push(preview.replace('', sanitizeIdentifier(entry.label))); - } - } - - return ( -
-
- What's actually generated right now -
- {lines.length === 0 ? ( -
Nothing yet. Add an entry and click Apply.
- ) : ( -
{lines.join('\n')}
- )} -
- ); -} diff --git a/src/components/TsWindowMock/GroupsPanel.tsx b/src/components/TsWindowMock/GroupsPanel.tsx deleted file mode 100644 index 86dc24c..0000000 --- a/src/components/TsWindowMock/GroupsPanel.tsx +++ /dev/null @@ -1,170 +0,0 @@ -import { COLOR, button } from '@site/src/components/TsWindowMock/styles'; -import type { RegistryTabKey } from '@site/src/components/TsWindowMock/data'; -import type { ConfigureState } from '@site/src/components/TsWindowMock/useConfigureState'; - -interface Row { - index: number; - name: string; - depth: number; - count: number; - hasKids: boolean; - expanded: boolean; -} - -function buildVisibleRows(groups: { name: string; depth: number; expanded: boolean; entries: unknown[] }[]): Row[] { - const rows: Row[] = []; - let hideBelowDepth: number | null = null; - for (let i = 0; i < groups.length; i++) { - const g = groups[i]; - if (hideBelowDepth !== null) { - if (g.depth > hideBelowDepth) continue; - hideBelowDepth = null; - } - const next = groups[i + 1]; - const hasKids = !!next && next.depth > g.depth; - rows.push({ index: i, name: g.name, depth: g.depth, count: g.entries.length, hasKids, expanded: g.expanded }); - if (hasKids && !g.expanded) hideBelowDepth = g.depth; - } - return rows; -} - -export default function GroupsPanel({ tabKey, state }: { tabKey: RegistryTabKey; state: ConfigureState }) { - const tab = state.working.registry[tabKey]; - const selectedGroup = tab.groups[tab.sel]; - const canActOnSelection = !!selectedGroup && selectedGroup.name !== '(ungrouped)'; - - const query = state.search.trim().toLowerCase(); - const rows = query - ? tab.groups - .map((g, index) => ({ - index, - name: g.name, - depth: g.depth, - count: g.entries.length, - hasKids: false, - expanded: g.expanded, - })) - .filter((r) => r.name.toLowerCase().includes(query)) - : buildVisibleRows(tab.groups); - - return ( -
-
- Groups -
-
-
state.addGroup(tabKey)}> - + Group -
-
canActOnSelection && state.addSubGroup(tabKey)}> - + Sub-group -
-
canActOnSelection && state.deleteGroup(tabKey)}> - Delete -
-
- {canActOnSelection && ( -
- state.renameGroup(tabKey, e.target.value)} - onFocus={() => state.setRenameFocused(true)} - onBlur={() => state.setRenameFocused(false)} - style={{ - flex: 1, - minWidth: 0, - background: 'transparent', - border: 0, - outline: 'none', - color: COLOR.text, - fontSize: 12, - padding: 0, - }} - /> -
- )} -
-
- {rows.map((row) => { - const selected = row.index === tab.sel; - const highlighted = selected && tab.focused; - return ( -
state.selectGroup(tabKey, row.index)} - style={{ - height: 16, - display: 'flex', - alignItems: 'center', - cursor: 'default', - fontSize: 12, - background: highlighted ? COLOR.selection : 'transparent', - paddingLeft: 3 + row.depth * 13, - }}> -
{ - e.stopPropagation(); - if (row.hasKids) state.toggleExpand(tabKey, row.index); - }} - style={{ - width: 12, - flex: 'none', - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - fontSize: 8, - color: COLOR.text, - visibility: row.hasKids ? 'visible' : 'hidden', - }}> - {row.expanded ? '▼' : '▶'} -
-
- {row.name} - {row.count > 0 ? ` (${row.count})` : ''} -
-
- ); - })} -
-
- ); -} diff --git a/src/components/TsWindowMock/Icons.tsx b/src/components/TsWindowMock/Icons.tsx deleted file mode 100644 index 362f2d4..0000000 --- a/src/components/TsWindowMock/Icons.tsx +++ /dev/null @@ -1,47 +0,0 @@ -export function SceneIcon({ size = 12 }: { size?: number }) { - return ( - - - - - - ); -} - -export function ScriptIcon({ size = 12 }: { size?: number }) { - return ( - - - - - C# - - - ); -} - -export function PrefabIcon({ size = 12 }: { size?: number }) { - return ( - - - - - - ); -} - -export function SparkleIcon({ size = 11, className }: { size?: number; className?: string }) { - return ( - - - - - ); -} diff --git a/src/components/TsWindowMock/SettingsPanel.tsx b/src/components/TsWindowMock/SettingsPanel.tsx deleted file mode 100644 index dad9ecb..0000000 --- a/src/components/TsWindowMock/SettingsPanel.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import type { ReactNode } from 'react'; -import { COLOR, fieldInnerLine, LABEL_COLUMN_WIDTH } from '@site/src/components/TsWindowMock/styles'; -import type { SettingsData } from '@site/src/components/TsWindowMock/data'; -import type { ConfigureState } from '@site/src/components/TsWindowMock/useConfigureState'; - -function SectionHeader({ children }: { children: ReactNode }) { - return
{children}
; -} - -function Toggle({ label, checked, onClick }: { label: string; checked: boolean; onClick: () => void }) { - return ( -
-
{label}
-
- {checked ? '✔' : ''} -
-
- ); -} - -export default function SettingsPanel({ state }: { state: ConfigureState }) { - const s = state.working.settings; - const set = (fn: (settings: SettingsData) => void) => state.mutateSettings(fn); - - return ( -
- Logging -
-
World Prefix
-
- set((prev) => { prev.worldPrefix = e.target.value; })} - style={{ flex: 1, minWidth: 0, background: 'transparent', border: 0, outline: 'none', color: COLOR.text, fontSize: 12, padding: 0 }} - /> -
-
- -
- Tsvrc Internal - set((p) => { p.internalInfo = !p.internalInfo; })} /> - set((p) => { p.internalWarning = !p.internalWarning; })} /> - set((p) => { p.internalError = !p.internalError; })} /> - -
- Your World - set((p) => { p.worldInfo = !p.worldInfo; })} /> - set((p) => { p.worldWarning = !p.worldWarning; })} /> - set((p) => { p.worldError = !p.worldError; })} /> - -
- Tree-Shaking (generate only what's used) -
set((p) => { p.treeShakeUnused = !p.treeShakeUnused; })}> -
- Tree-Shake Unused Globa -
-
- {s.treeShakeUnused ? '✔' : ''} -
-
-
- ); -} diff --git a/src/components/TsWindowMock/data.ts b/src/components/TsWindowMock/data.ts deleted file mode 100644 index f9401bf..0000000 --- a/src/components/TsWindowMock/data.ts +++ /dev/null @@ -1,179 +0,0 @@ -export type TabKey = 'pool' | 'globals' | 'constructs' | 'factories' | 'settings'; -export type RegistryTabKey = Exclude; -export const TABS: TabKey[] = ['pool', 'globals', 'constructs', 'factories', 'settings']; - -export const TAB_LABELS: Record = { - pool: 'Pool', - globals: 'Globals', - constructs: 'Constructs', - factories: 'Factories', - settings: 'Settings', -}; - -export type EntryIcon = 'script' | 'prefab' | 'none'; - -export interface MockEntry { - icon: EntryIcon; - label: string; - name: string; -} - -export interface MockGroup { - name: string; - depth: number; - expanded: boolean; - entries: MockEntry[]; -} - -export interface RegistryTabData { - sel: number; - focused: boolean; - groups: MockGroup[]; -} - -export interface SettingsData { - worldPrefix: string; - internalInfo: boolean; - internalWarning: boolean; - internalError: boolean; - worldInfo: boolean; - worldWarning: boolean; - worldError: boolean; - treeShakeUnused: boolean; -} - -export interface RegistryTabConfig { - key: RegistryTabKey; - description: string; - emptyHint: string; - showNames: boolean; - entryIcon: 'script' | 'prefab'; - catalog: string[]; -} - -export const TAB_CONFIG: Record = { - pool: { - key: 'pool', - description: - 'Register UdonSharpBehaviour prefabs to pool. The system automatically instantiates all slots, ' + - 'initializes them, and wires every [WirePool] field across your behaviours at compile time. ' + - 'No manual scene placement, no cross-behaviour drag-and-drop, and no broken references when you refactor.', - emptyHint: 'No pooled prefabs registered yet. Add a prefab here to make it available for network-synced spawning.', - showNames: false, - entryIcon: 'script', - catalog: ['PickupOrb (Pickup Orb)', 'RoundTimer (Round Timer)', 'BossController (Boss Controller)'], - }, - globals: { - key: 'globals', - description: - "Register any scene object or component as a named field on _ts. After compiling, access it from any " + - "TsvrcBehaviour via _ts.FieldName. Example: drag your GameManager here, then use _ts.GameManager from any " + - "behaviour. Groups are organizational by default; toggle 'Namespace with group name' on a group to prefix " + - "its entries member names (e.g. _ts.EnemiesSpawner).", - emptyHint: 'No globals registered yet. Add a scene object here to expose it as a field on TsGenerated.', - showNames: true, - entryIcon: 'script', - catalog: ['GameManager (Game Manager)', 'MusicManager (Music Manager)', 'SpawnPoint (Spawn Point)'], - }, - constructs: { - key: 'constructs', - description: - 'Register TsvrcBehaviours that are always active in the scene, not pooled, to initialize them at startup ' + - "(TsConstruct). The reference stays private, never reachable as _ts.Name, so there's no member name to configure.", - emptyHint: 'No constructs registered yet. Add a TsvrcBehaviour here to initialize it at startup without exposing it on _ts.', - showNames: false, - entryIcon: 'script', - catalog: ['MatchStarter (Match Starter)', 'LobbyController (Lobby Controller)', 'AudioSettings (Audio Settings)'], - }, - factories: { - key: 'factories', - description: - 'Register prefabs organized into nested groups. Generates a Create{Group}{SubGroup}...{Name}(Transform parent) ' + - 'method for each entry, prefixed by its full group ancestor chain. WARNING: instantiated objects do not receive ' + - 'a VRChat network ID and cannot send or receive network events. Use Pool for networked objects.', - emptyHint: 'No factory prefabs registered yet. Add a group on the left, then add prefabs inside it for on-demand instantiation.', - showNames: true, - entryIcon: 'prefab', - catalog: ['ConfettiBurst', 'BulletTrail', 'TrailFX'], - }, -}; - -export const SETTINGS_DESCRIPTION = - "Project-wide Tsvrc configuration: logging levels and tags, and tree-shaking (generate only what's used)."; - -export const NULL_SLOT_HINT = - 'empty - nothing assigned here (if this used to point at something, it may have been deleted)'; - -function script(label: string): MockEntry { - return { icon: 'script', label, name: '' }; -} -function prefab(label: string): MockEntry { - return { icon: 'prefab', label, name: '' }; -} -function group(name: string, depth: number, entries: MockEntry[] = []): MockGroup { - return { name, depth, expanded: true, entries }; -} - -export function createInitialRegistryData(): Record { - return { - pool: { - sel: 0, - focused: true, - groups: [group('(ungrouped)', 0, [script('EnemyController (Enemy Controller)'), script('HitEffect (Hit Effect)')])], - }, - globals: { - sel: 0, - focused: true, - groups: [ - group('(ungrouped)', 0, [script('ScoreboardAnimator (Scoreboard Animator)'), script('AudioSettings (Audio Settings)')]), - group('UI', 0, [script('SettingsMenu (Settings Menu)')]), - group('Overlay', 1, [script('PlayerListOverlay (Player List Overlay)')]), - ], - }, - constructs: { - sel: 1, - focused: true, - groups: [ - group('(ungrouped)', 0, [script('HelloWorld (Bootstrap)')]), - group('Core', 0, [script('EventRouter (Event Router)')]), - ], - }, - factories: { - sel: 1, - focused: true, - groups: [group('(ungrouped)', 0), group('Effects', 0, [prefab('HitSparkVFX'), prefab('ScorePopup')])], - }, - }; -} - -export function createInitialSettings(): SettingsData { - return { - worldPrefix: '', - internalInfo: true, - internalWarning: true, - internalError: true, - worldInfo: true, - worldWarning: true, - worldError: true, - treeShakeUnused: false, - }; -} - -export function sanitizeIdentifier(name: string): string { - const cleaned = name.replace(/[^A-Za-z0-9_]/g, ''); - return cleaned.length > 0 ? cleaned : ''; -} - -export function memberPreview(tabKey: RegistryTabKey, entry: MockEntry, groupName: string): string | null { - if (entry.icon === 'none') return null; - if (tabKey === 'globals') { - const leaf = sanitizeIdentifier(entry.name); - return `_ts.${leaf.length > 0 ? leaf : ''}`; - } - if (tabKey === 'factories') { - const chain = groupName === '(ungrouped)' ? '' : sanitizeIdentifier(groupName); - const leaf = sanitizeIdentifier(entry.name); - return `Create${chain}${leaf.length > 0 ? leaf : ''}(parent)`; - } - return null; -} diff --git a/src/components/TsWindowMock/index.tsx b/src/components/TsWindowMock/index.tsx deleted file mode 100644 index 86ab16e..0000000 --- a/src/components/TsWindowMock/index.tsx +++ /dev/null @@ -1,274 +0,0 @@ -import GroupsPanel from '@site/src/components/TsWindowMock/GroupsPanel'; -import EntriesPanel from '@site/src/components/TsWindowMock/EntriesPanel'; -import SettingsPanel from '@site/src/components/TsWindowMock/SettingsPanel'; -import GeneratedPreview from '@site/src/components/TsWindowMock/GeneratedPreview'; -import { SceneIcon } from '@site/src/components/TsWindowMock/Icons'; -import { COLOR, FONT_FAMILY, fieldInnerLine } from '@site/src/components/TsWindowMock/styles'; -import { SETTINGS_DESCRIPTION, TAB_CONFIG, TAB_LABELS, TABS, type RegistryTabKey } from '@site/src/components/TsWindowMock/data'; -import { useConfigureState } from '@site/src/components/TsWindowMock/useConfigureState'; - -function WarningTriangle({ gutterWidth }: { gutterWidth: number }) { - return ( -
-
-
- ! -
-
-
- ); -} - -export default function TsWindowMock() { - const state = useConfigureState(); - const isSettings = state.activeTab === 'settings'; - const registryTabKey = isSettings ? null : (state.activeTab as RegistryTabKey); - const description = registryTabKey ? TAB_CONFIG[registryTabKey].description : SETTINGS_DESCRIPTION; - - return ( -
-
-
-
-
- {`Configure${state.dirty ? '*' : ''}`} -
-
-
-
- {'⋮'} -
-
-
-
-
- {'✕'} -
-
-
- -
-
-
Linked Scene
-
-
- -
-
MyWorld
-
-
-
-
-
- -
- Tsvrc is set up. -
- -
- {TABS.map((key) => { - const active = key === state.activeTab; - return ( -
state.selectTab(key)} - style={{ - flex: 1, - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - fontSize: 12, - cursor: 'default', - boxSizing: 'border-box', - borderRight: key === 'settings' ? 0 : `1px solid ${COLOR.tabDivider}`, - background: active ? COLOR.tabActive : COLOR.btnBg, - color: active ? COLOR.textBright : '#d2d2d2', - }}> - {TAB_LABELS[key]} -
- ); - })} -
- -
- {description} -
- -
-
-
-
- state.setSearch(e.target.value)} - style={{ flex: 1, minWidth: 0, background: 'transparent', border: 0, outline: 'none', color: COLOR.text, fontSize: 11.5, padding: 0 }} - /> -
- - {isSettings && } - {registryTabKey && ( -
- - -
- )} - - {state.dirty && ( - <> -
- -
- You have unapplied changes. Apply them to regenerate, or discard them to revert. -
-
-
-
- Apply -
-
- Discard -
-
- - )} - -
- Force Regenerate -
-
-
-
- - -
- ); -} diff --git a/src/components/TsWindowMock/styles.ts b/src/components/TsWindowMock/styles.ts deleted file mode 100644 index d9a6228..0000000 --- a/src/components/TsWindowMock/styles.ts +++ /dev/null @@ -1,50 +0,0 @@ -import type { CSSProperties } from 'react'; - -export const COLOR = { - chromeBg: '#282828', - chromeTab: '#3c3c3c', - panelBg: '#383838', - borderDark: '#232323', - borderField: '#202020', - boxBg: '#404040', - fieldBg: '#2a2a2a', - fieldBorderTop: '#0d0d0d', - btnBg: '#585858', - btnDisabled: '#484848', - tabActive: '#46607c', - tabDivider: '#242424', - tabStripTop: '#303030', - rowZebraA: '#3f3f3f', - rowZebraB: '#383838', - selection: '#2c5d87', - dividerLight: '#5e5e5e', - text: '#c4c4c4', - textBright: '#e8e8e8', - textSelected: '#eaeaea', - textDisabled: '#8b8b8b', - textDim: '#9a9a9a', - warning: '#e0b32c', - prefabIcon: '#4c9fd4', - focusRing: '#4a7fb5', -} as const; - -export const FONT_FAMILY = "Inter, 'Segoe UI', system-ui, sans-serif"; - -export const fieldInnerLine: CSSProperties = { boxShadow: `inset 0 1px 0 ${COLOR.fieldBorderTop}` }; - -export function button(enabled: boolean, extra?: CSSProperties): CSSProperties { - return { - boxSizing: 'border-box', - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - fontSize: 12, - borderRadius: 2, - cursor: 'default', - background: enabled ? COLOR.btnBg : COLOR.btnDisabled, - color: enabled ? COLOR.textBright : COLOR.textDisabled, - ...extra, - }; -} - -export const LABEL_COLUMN_WIDTH = 150; diff --git a/src/components/TsWindowMock/useConfigureState.ts b/src/components/TsWindowMock/useConfigureState.ts deleted file mode 100644 index 532af92..0000000 --- a/src/components/TsWindowMock/useConfigureState.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { useCallback, useState } from 'react'; -import { - createInitialRegistryData, - createInitialSettings, - type RegistryTabData, - type RegistryTabKey, - type SettingsData, - type TabKey, -} from '@site/src/components/TsWindowMock/data'; - -interface DataTree { - registry: Record; - settings: SettingsData; -} - -function createInitialTree(): DataTree { - return { registry: createInitialRegistryData(), settings: createInitialSettings() }; -} - -function deepClone(value: T): T { - return JSON.parse(JSON.stringify(value)); -} - -export function useConfigureState() { - const [committed, setCommitted] = useState(() => createInitialTree()); - const [working, setWorking] = useState(committed); - const [dirty, setDirty] = useState(false); - const [activeTab, setActiveTab] = useState('pool'); - const [search, setSearch] = useState(''); - const [renameFocused, setRenameFocused] = useState(false); - - const mutateTab = useCallback( - (key: RegistryTabKey, fn: (tab: RegistryTabData) => void, markDirty = true) => { - setWorking((prev) => { - const next = deepClone(prev); - fn(next.registry[key]); - return next; - }); - if (markDirty) setDirty(true); - }, - [], - ); - - const mutateSettings = useCallback((fn: (s: SettingsData) => void) => { - setWorking((prev) => { - const next = deepClone(prev); - fn(next.settings); - return next; - }); - setDirty(true); - }, []); - - const selectTab = useCallback((tab: TabKey) => { - setActiveTab(tab); - setRenameFocused(false); - }, []); - - const selectGroup = useCallback( - (key: RegistryTabKey, index: number) => { - mutateTab( - key, - (tab) => { - tab.sel = index; - tab.focused = true; - }, - false, - ); - }, - [mutateTab], - ); - - const toggleExpand = useCallback( - (key: RegistryTabKey, index: number) => { - mutateTab(key, (tab) => (tab.groups[index].expanded = !tab.groups[index].expanded), false); - }, - [mutateTab], - ); - - const addGroup = useCallback( - (key: RegistryTabKey) => { - mutateTab(key, (tab) => { - tab.groups.push({ name: 'New Group', depth: 0, expanded: true, entries: [] }); - tab.sel = tab.groups.length - 1; - tab.focused = true; - }); - setRenameFocused(true); - }, - [mutateTab], - ); - - const addSubGroup = useCallback( - (key: RegistryTabKey) => { - mutateTab(key, (tab) => { - const at = tab.sel; - const parent = tab.groups[at]; - if (!parent || parent.name === '(ungrouped)') return; - tab.groups.splice(at + 1, 0, { name: 'New Sub-group', depth: parent.depth + 1, expanded: true, entries: [] }); - tab.sel = at + 1; - }); - setRenameFocused(true); - }, - [mutateTab], - ); - - const deleteGroup = useCallback( - (key: RegistryTabKey) => { - mutateTab(key, (tab) => { - const group = tab.groups[tab.sel]; - if (!group || group.name === '(ungrouped)') return; - tab.groups.splice(tab.sel, 1); - tab.sel = Math.max(0, tab.sel - 1); - }); - setRenameFocused(false); - }, - [mutateTab], - ); - - const renameGroup = useCallback( - (key: RegistryTabKey, name: string) => { - mutateTab(key, (tab) => { - tab.groups[tab.sel].name = name; - }); - }, - [mutateTab], - ); - - const addEntry = useCallback( - (key: RegistryTabKey) => { - mutateTab(key, (tab) => { - const group = tab.groups[tab.sel]; - if (!group) return; - group.entries.push({ icon: 'none', label: 'None (Object)', name: '' }); - }); - }, - [mutateTab], - ); - - const assignEntry = useCallback( - (key: RegistryTabKey, entryIndex: number, icon: 'script' | 'prefab' | 'none', label: string) => { - mutateTab(key, (tab) => { - const entry = tab.groups[tab.sel].entries[entryIndex]; - entry.icon = icon; - entry.label = label; - }); - }, - [mutateTab], - ); - - const removeEntry = useCallback( - (key: RegistryTabKey, entryIndex: number) => { - mutateTab(key, (tab) => { - tab.groups[tab.sel].entries.splice(entryIndex, 1); - }); - }, - [mutateTab], - ); - - const renameEntry = useCallback( - (key: RegistryTabKey, entryIndex: number, name: string) => { - mutateTab(key, (tab) => { - tab.groups[tab.sel].entries[entryIndex].name = name; - }); - }, - [mutateTab], - ); - - const apply = useCallback(() => { - setCommitted(working); - setDirty(false); - setRenameFocused(false); - }, [working]); - - const discard = useCallback(() => { - setWorking(committed); - setDirty(false); - setRenameFocused(false); - }, [committed]); - - const forceRegenerate = useCallback(() => { }, []); - - return { - committed, - working, - dirty, - activeTab, - search, - renameFocused, - setSearch, - setRenameFocused, - selectTab, - selectGroup, - toggleExpand, - addGroup, - addSubGroup, - deleteGroup, - renameGroup, - addEntry, - assignEntry, - removeEntry, - renameEntry, - mutateSettings, - apply, - discard, - forceRegenerate, - }; -} - -export type ConfigureState = ReturnType; diff --git a/src/components/core/AnnotatedCode/AnnotationList.tsx b/src/components/core/AnnotatedCode/AnnotationList.tsx deleted file mode 100644 index 6aeb6b5..0000000 --- a/src/components/core/AnnotatedCode/AnnotationList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { usePrismTheme } from '@docusaurus/theme-common'; -import useIsBrowser from '@docusaurus/useIsBrowser'; -import { colorClasses, type Annotation } from '@site/src/components/core/AnnotatedCode/annotations'; - -export default function AnnotationList({ annotations }: { annotations: Annotation[] }) { - const prismTheme = usePrismTheme(); - const isBrowser = useIsBrowser(); - return ( -
- {annotations.map((a) => { - const body = ( - <> -
{a.title}
-
{a.description}
- - ); - return ( -
- - {a.mark} - - {a.href ? ( - - {body} - - ) : ( -
{body}
- )} -
- ); - })} -
- ); -} diff --git a/src/components/core/AnnotatedCode/Badge.tsx b/src/components/core/AnnotatedCode/Badge.tsx deleted file mode 100644 index 1f248c9..0000000 --- a/src/components/core/AnnotatedCode/Badge.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { colorClasses, type AnnotationColor } from '@site/src/components/core/AnnotatedCode/annotations'; - -export default function Badge({ mark, color }: { mark: number; color: AnnotationColor }) { - return ( - - {mark} - - ); -} diff --git a/src/components/core/AnnotatedCode/CodePanel.tsx b/src/components/core/AnnotatedCode/CodePanel.tsx deleted file mode 100644 index c70360f..0000000 --- a/src/components/core/AnnotatedCode/CodePanel.tsx +++ /dev/null @@ -1,118 +0,0 @@ -import { Fragment } from 'react'; -import { Highlight } from 'prism-react-renderer'; -import { usePrismTheme } from '@docusaurus/theme-common'; -import useIsBrowser from '@docusaurus/useIsBrowser'; -import Badge from '@site/src/components/core/AnnotatedCode/Badge'; -import { - colorClasses, - exampleCode, - findTokenRun, - type Annotation, -} from '@site/src/components/core/AnnotatedCode/annotations'; - -export default function CodePanel({ annotations }: { annotations: Annotation[] }) { - const prismTheme = usePrismTheme(); - const isBrowser = useIsBrowser(); - const byLine = new Map( - annotations.filter((a): a is Annotation & { line: number } => a.line !== undefined).map((a) => [a.line, a]), - ); - return ( -
-
- - - HelloWorld.cs - - C# -
- {!isBrowser ? ( - // Avoid flashing the light Prism theme: colorMode (and so usePrismTheme) is - // intentionally lagged on the first client render to prevent hydration mismatches - // (see Docusaurus's own colorMode.tsx). Render plain, uncolored text until then. -
-          {exampleCode.split('\n').map((line, i) => (
-            
- {i + 1} - {line} -
- ))} -
- ) : ( - - {({ className, style, tokens, getLineProps, getTokenProps }) => ( -
-              {tokens.map((line, i) => {
-                const annotation = byLine.get(i);
-                const run = annotation?.match ? findTokenRun(line, annotation.match) : null;
-                const lineProps = getLineProps({ line });
-                return (
-                  
- {i + 1} - - {line.map((token, key) => { - const tokenProps = getTokenProps({ token }); - const inRun = !!run && key >= run[0] && key <= run[1]; - if (!inRun) { - return ; - } - - const isRunStart = key === run![0]; - const isRunEnd = key === run![1]; - let boxClass = `border-y ${colorClasses[annotation!.color].border}`; - boxClass += isRunStart ? ' rounded-l-sm border-l pl-0.5' : ''; - boxClass += isRunEnd ? ' rounded-r-sm border-r pr-0.5' : ''; - - // The run's own leading indentation, if any, must stay outside the box - // (Prism merges a line's indentation into its first token's content). - let leadingWs = ''; - let text = tokenProps.children as string; - if (isRunStart) { - const m = /^\s+/.exec(text); - if (m) { - leadingWs = m[0]; - text = text.slice(leadingWs.length); - } - } - - const boxed = ( - - {text} - - ); - const rendered = leadingWs ? ( - - - {leadingWs} - - {boxed} - - ) : ( - boxed - ); - - if (isRunEnd) { - return ( - - {rendered} - - - ); - } - return rendered; - })} - -
- ); - })} -
- )} -
- )} -
- ); -} diff --git a/src/components/core/AnnotatedCode/annotations.ts b/src/components/core/AnnotatedCode/annotations.ts deleted file mode 100644 index 26bf8aa..0000000 --- a/src/components/core/AnnotatedCode/annotations.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { translate } from '@docusaurus/Translate'; - -export const exampleCode = `using Tsvrc.Core.Generated; - -public class HelloWorld : TsBehaviour -{ - protected override void TsStart() - { - LogInfo("HelloWorld constructed."); - _ts.Scoreboard.SetTrigger("Refresh"); - _ts.Memory.SetInt("greetings", 1); - } -}`; - -export type AnnotationColor = 'accent' | 'success' | 'attention' | 'purple'; - -export const colorClasses: Record = { - accent: { badge: 'bg-accent-emphasis', border: 'border-accent', text: 'text-accent' }, - success: { badge: 'bg-success', border: 'border-success', text: 'text-success' }, - attention: { badge: 'bg-attention', border: 'border-attention', text: 'text-attention' }, - purple: { - badge: 'bg-purple-500 dark:bg-purple-400', - border: 'border-purple-500 dark:border-purple-400', - text: 'text-purple-600 dark:text-purple-400', - }, -}; - -export type Annotation = { - mark: number; - line?: number; - match?: string; - color: AnnotationColor; - title: string; - description: string; - href?: string; -}; - -export function useAnnotations(): Annotation[] { - return [ - { - mark: 1, - line: 2, - match: 'TsBehaviour', - color: 'accent', - title: translate({ id: 'core.hero.annotation.behaviour.title', message: 'TsBehaviour' }), - description: translate({ - id: 'core.hero.annotation.behaviour.description', - message: "The generated shadow class every script extends. It's what gives this behaviour its _ts reference.", - }), - href: '#building-blocks', - }, - { - mark: 2, - line: 7, - match: '_ts.Scoreboard', - color: 'attention', - title: translate({ id: 'core.hero.annotation.globals.title', message: 'Globals' }), - description: translate({ - id: 'core.hero.annotation.globals.description', - message: 'Any named scene object, reachable as _ts.Name from every behaviour, no dragging references by hand.', - }), - href: '#building-blocks', - }, - { - mark: 3, - line: 8, - match: '_ts.Memory', - color: 'purple', - title: translate({ id: 'core.hero.annotation.memory.title', message: 'Memory' }), - description: translate({ - id: 'core.hero.annotation.memory.description', - message: 'The shared key-value store, reachable as _ts.Memory from anywhere.', - }), - href: '#building-blocks', - }, - { - mark: 4, - color: 'success', - title: translate({ id: 'core.hero.annotation.more.title', message: "That's not all" }), - description: translate({ - id: 'core.hero.annotation.more.description', - message: "There's more where that came from. See the rest of the Core building blocks below.", - }), - href: '#building-blocks', - }, - ]; -} - -// Finds the contiguous run of Prism tokens whose concatenated content equals `target`, -// regardless of exactly how the grammar split it (e.g. "_ts", ".", "Scoreboard"). -export function findTokenRun(line: { content: string }[], target: string): [number, number] | null { - for (let start = 0; start < line.length; start++) { - let acc = ''; - for (let end = start; end < line.length; end++) { - // Prism merges a line's leading indentation into its first token's content, so the - // start of a candidate run needs that whitespace stripped before comparing. - const piece = end === start ? line[end].content.replace(/^\s+/, '') : line[end].content; - acc += piece; - if (acc === target) return [start, end]; - if (!target.startsWith(acc)) break; - } - } - return null; -} diff --git a/src/components/core/AnnotatedCode/index.tsx b/src/components/core/AnnotatedCode/index.tsx deleted file mode 100644 index c9a5592..0000000 --- a/src/components/core/AnnotatedCode/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import CodePanel from '@site/src/components/core/AnnotatedCode/CodePanel'; -import AnnotationList from '@site/src/components/core/AnnotatedCode/AnnotationList'; -import { useAnnotations } from '@site/src/components/core/AnnotatedCode/annotations'; - -export default function AnnotatedCode() { - const annotations = useAnnotations(); - return ( -
- - -
- ); -} diff --git a/src/components/core/Features.tsx b/src/components/core/Features.tsx deleted file mode 100644 index 36eb657..0000000 --- a/src/components/core/Features.tsx +++ /dev/null @@ -1,127 +0,0 @@ -import Link from '@docusaurus/Link'; -import Translate, { translate } from '@docusaurus/Translate'; - -type Feature = { - id: string; - title: string; - description: string; - href: string; -}; - -function useFeatures(): Feature[] { - return [ - { - id: 'constructs', - title: translate({ - id: 'core.features.constructs.title', - message: 'Constructs', - }), - description: translate({ - id: 'core.features.constructs.description', - message: - 'Register a TsvrcBehaviour once and Core initializes it for you, in a fixed order, through TsStart, instead of you wiring startup by hand.', - }), - href: '/docs/core/codegen/modules/construct-module', - }, - { - id: 'globals', - title: translate({ - id: 'core.features.globals.title', - message: 'Globals', - }), - description: translate({ - id: 'core.features.globals.description', - message: - 'Point at a scene object once and every behaviour can read it back by name, instead of dragging the same reference into a dozen inspector slots.', - }), - href: '/docs/core/codegen/modules/global-module', - }, - { - id: 'memory', - title: translate({ - id: 'core.features.memory.title', - message: 'Memory', - }), - description: translate({ - id: 'core.features.memory.description', - message: - "A shared key-value store with ephemeral, persistent, and synced tiers, so getting a value to every player doesn't mean writing your own networking.", - }), - href: '/docs/core/networking-data/tsvrc-memory', - }, - { - id: 'factories', - title: translate({ - id: 'core.features.factories.title', - message: 'Factories', - }), - description: translate({ - id: 'core.features.factories.description', - message: - "Spawn a prefab on demand with a generated _ts.Create... call, for anything that doesn't need to stay in sync across players.", - }), - href: '/docs/core/codegen/modules/factory-module', - }, - { - id: 'pools', - title: translate({ - id: 'core.features.pools.title', - message: 'Pools', - }), - description: translate({ - id: 'core.features.pools.description', - message: - "Pre-instantiate and wire exactly the instances a networked prefab needs, at edit time, because VRChat can't sync an object created while the world is running.", - }), - href: '/docs/core/codegen/modules/pool-module', - }, - { - id: 'instance', - title: translate({ - id: 'core.features.instance.title', - message: 'Instance', - }), - description: translate({ - id: 'core.features.instance.description', - message: - "One behaviour per project standing in for the running world instance itself, found and wired automatically, so instance-level checks like \"am I the master\" have one obvious home.", - }), - href: '/docs/core/core-concepts/instance', - }, - ]; -} - -export default function Features() { - const features = useFeatures(); - return ( -
-
-

- The building blocks -

-

- - Six generated pieces cover most of what a world needs. Register or point at - something once, then reach it the same way from every behaviour. - -

-
- {features.map((item) => ( -
-

{item.title}

-

{item.description}

- - Details → - -
- ))} -
-
-
- ); -} diff --git a/src/components/core/GetStarted.tsx b/src/components/core/GetStarted.tsx deleted file mode 100644 index dd79fdd..0000000 --- a/src/components/core/GetStarted.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import Link from '@docusaurus/Link'; -import Admonition from '@theme/Admonition'; -import Translate, { translate } from '@docusaurus/Translate'; - -export default function GetStarted() { - return ( -
-
- -

- - TsVRC is not affiliated with or endorsed by VRChat Inc. - -

-

- - It's also still a work in progress. Every part of it has its own tests, - and we run them before every release, but we can't promise - we've caught every case. Keep a backup of your project before adding - Core to it or updating it, just to be safe. If something breaks on your end, we - can't fix it for you, but we'd really like to know about it. - Open an issue on GitHub and we'll take a look. - -

-
-
-

- Start building -

-

- - Add Core through VCC, then follow the getting-started guide to have a behaviour - running in play mode. - -

-
- - Get started - -
-
-
-
- ); -} diff --git a/src/components/core/Hero.tsx b/src/components/core/Hero.tsx deleted file mode 100644 index 99e3b54..0000000 --- a/src/components/core/Hero.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import Link from '@docusaurus/Link'; -import Translate from '@docusaurus/Translate'; -import AnnotatedCode from '@site/src/components/core/AnnotatedCode'; -import ScrollCue from '@site/src/components/core/ScrollCue'; - -export default function Hero() { - return ( -
-
-
-

TsVRC Core

-

- - A framework for VRChat worlds built on UdonSharp - -

-

- - Structured initialization, dependency wiring, and editor codegen, so your world - scripts extend a typed base class instead of hand-wiring references every time - you add a behaviour. - -

-

com.tsvrc.core

-
- - Read the docs - - - View on GitHub - -
- -
- -
- -
- ); -} diff --git a/src/components/core/ProblemSolution.tsx b/src/components/core/ProblemSolution.tsx deleted file mode 100644 index 756ebde..0000000 --- a/src/components/core/ProblemSolution.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import Link from '@docusaurus/Link'; -import Translate from '@docusaurus/Translate'; - -export default function ProblemSolution() { - return ( -
-

- Why it exists -

-

- - Every UdonSharp script starts on its own, with no guarantee of what order things - happen in and no easy way to reach another script elsewhere in your world. Most - creators solve this by hand: dragging references between objects in the Inspector, - then hoping everything is still connected when the world loads. - -

-

- - how Core fits together - - ), - code: _ts, - }}> - {"Core gives every script one shared reference, {code}, to reach anything else in your project. Setup happens in an order you control, and Core works out which of your own classes to use ahead of time, in the Unity editor. See {link} for the full shape."} - -

-
- ); -} diff --git a/src/components/core/ScrollCue.tsx b/src/components/core/ScrollCue.tsx deleted file mode 100644 index 5c44457..0000000 --- a/src/components/core/ScrollCue.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { translate } from '@docusaurus/Translate'; - -export default function ScrollCue() { - return ( - - ); -} diff --git a/src/components/homepage/Projects.tsx b/src/components/homepage/Projects.tsx index bc01379..85ce677 100644 --- a/src/components/homepage/Projects.tsx +++ b/src/components/homepage/Projects.tsx @@ -15,18 +15,6 @@ function useProjects(): Project[] { docsHref: '/docs/udon-test-kit/intro', repo: 'tsvrc/udon-test-kit', }, - { - name: 'Core', - status: 'available', - description: translate({ - id: 'homepage.projects.core.description', - message: - 'A structured way to build VRChat worlds with UdonSharp: consistent startup, ' + - 'wired-up dependencies, and generated code instead of hand-wiring everything yourself.', - }), - docsHref: '/docs/core/intro', - repo: 'tsvrc/tsvrc-core', - }, ]; } diff --git a/src/pages/core.tsx b/src/pages/core.tsx deleted file mode 100644 index b5186b0..0000000 --- a/src/pages/core.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import type { ReactNode } from 'react'; -import Layout from '@theme/Layout'; -import { translate } from '@docusaurus/Translate'; -import Hero from '@site/src/components/core/Hero'; -import ProblemSolution from '@site/src/components/core/ProblemSolution'; -import Features from '@site/src/components/core/Features'; -import GetStarted from '@site/src/components/core/GetStarted'; - -export default function Core(): ReactNode { - return ( - - - - - - - ); -}