chore: add ai skills

This commit is contained in:
walon
2026-10-18 13:06:37 +08:00
parent 6cadd24d10
commit ea9196e8c3
8 changed files with 361 additions and 0 deletions
@@ -0,0 +1,51 @@
---
name: hybridclr-aot-generic
description: >-
Handle HybridCLR AOT generics: supplementary metadata via LoadMetadataForAOTAssembly, saving stripped AOT dlls per platform, HomologousImageMode, AOTGenericReference, and MissingMethodException for an AOT generic method. Use when an AOT generic fails to instantiate, the user asks about metadata patching, List/Dictionary/async generics, or which supplementary dll to ship.
---
# AOT generics
Docs: `D:/workspace/hybridclr-doc/docs/guide/build/aotgeneric.md` and `start/generic.md`.
Generic types and methods **defined in hot-update assemblies** have no AOT restriction. The restriction is hot-update code using a generic **defined in an AOT assembly** (`List<T>`, `Dictionary<TKey,TValue>`, async state machines, and similar) when that instantiation was not generated in AOT. Typical log:
```text
MissingMethodException: AOT generic method not instantiated in aot module
```
## Default: supplementary metadata
The community edition uses supplementary metadata. Do not send the user to hand-written RefTypes unless they are chasing one instantiation or optimizing a hot path.
Patch the **AOT dll that contains the generic method**, not the dll that contains the generic argument. `List<SomeHotUpdateStruct>` needs `mscorlib.dll`, because the missing IL is `List<T>.Add`, not the struct.
```csharp
// Call once before any hot-update code uses that AOT generic. Order among dlls does not matter.
LoadImageErrorCode err = HybridCLR.RuntimeApi.LoadMetadataForAOTAssembly(dllBytes, HomologousImageMode.SuperSet);
// Do not keep dllBytes. The API copies them.
```
- Call it after player startup, or after hot-update dlls are loaded and before business code runs. The supplementary dlls can ship in the player (for example StreamingAssets) or with a hot update.
- Call it on another thread if it stalls.
- Loaded metadata uses several times the dll size and is not released. Memory-tight projects use the commercial full generic sharing build (no supplementary dlls), or run `AOTAssemblyMetadataStripper.Strip` to drop non-generic method metadata first.
- `HybridCLR/Generate/AOTGenericReference` writes a conservative `PatchedAOTAssemblyList`. Load the whole list when memory is fine. Otherwise start with common dlls such as `mscorlib` and add a dll when a new AOT generic error appears. Supplementary dlls can themselves be hot-updated.
## Which dll
The player build copies stripped AOT dlls to `{project}/HybridCLRData/AssembliesPostIl2CppStrip/{target}`. `Generate/AotDlls` can also produce them by exporting a temp project.
- **Stripped dlls from different BuildTargets are not interchangeable.**
- **Freeze the dlls from the shipped player.** Do not replace them with a newer Generate output on every hot update.
- `HomologousImageMode.SuperSet`: a superset is enough. Stripped or original AOT dlls both work. Use this by default.
- `HomologousImageMode.Consistent`: the bytes must match **that player build's** stripped dll. Original dlls do not work. `Generate/All` output often differs slightly from the real player, so Consistent fails more often.
## Generic sharing (optional)
After metadata is loaded, HybridCLR still prefers an il2cpp shared instantiation when one exists. Class type arguments share as `object`. Non-enum value types share only with themselves. Enums share with enums of the same underlying type. Value types do not share across different types the way classes do, so `List<HotUpdateStruct>` is not covered by an AOT `List<int>`.
Instantiations in `AOTGenericReferences.cs` are comments and are overwritten on regenerate. Copy any you want into another AOT file (for example `new List<object>()`). That is a performance optimization, not a requirement for correctness.
## Full generic sharing
Commercial editions only. It removes the size, memory, and interpreted-call cost of supplementary metadata. Do not switch the workflow to it unless the user has that edition.
@@ -0,0 +1,48 @@
---
name: hybridclr-avoid-code-strip
description: >-
Keep Unity IL2CPP from stripping AOT types and methods that hot-update code calls: Generate/LinkXml, linkPreserveLevel, a hand-written Assets/link.xml, a real reference from the main project, and MissingMetadataChecker. Use for TypeLoadException, MissingMethodException that is not an AOT generic error, code stripping, link.xml, or Generate/LinkXml.
---
# Avoid code stripping
Doc: `D:/workspace/hybridclr-doc/docs/guide/build/codestriping.md`.
If a stripped AOT type or method is called from hot-update code:
```text
TypeLoadException: Could not load type 'Xxx' from assembly 'yyy'
MissingMethodException: ...
```
If the log says `AOT generic method not instantiated`, use `hybridclr-aot-generic`. link.xml does not fix that.
## Before the player build
Run `HybridCLR/Generate/All` before building the player. It includes `Generate/LinkXml`. LinkXml alone scans AOT references from the current hot-update dlls.
- Output is Settings `outputLinkFile`, default `Assets/HybridCLR/Generate/link.xml`.
- **Do not** point `outputLinkFile` at a hand-maintained `Assets/link.xml`. Generation overwrites it.
- `linkPreserveLevel`: default `PreserveAllOfDeclaringType` keeps the whole referenced type. Use `PreserveExactMember` only to shrink the player (referenced fields, methods, properties, and events). A later hot update that touches another member can then miss it.
## When link.xml has no effect
If the main project never references any type or method in an AOT assembly, Unity strips that assembly entirely and preserve entries are ignored. Reference one type or method from that dll in the main project.
`preserve all` on `UnityEngine.Debug` can hit a Unity bug. Since 6.1.0, generated link.xml skips that class. Do not add it back.
## Reserve types for later hot updates
`Generate/LinkXml` only covers references in the **current** hot-update dlls. Put types you will need later in a separate `Assets/link.xml`, or call them from the main project. Do not put them in the generated file.
## Check before publishing a hot update
Use the stripped AOT dll directory saved from the player build. Do not use `AssembliesPostIl2CppStrip` after a later `Generate/All` has refreshed it.
```csharp
var checker = new HybridCLR.HotUpdate.MissingMetadataChecker(
aotDirFromPlayerBuild, SettingsUtil.HotUpdateAssemblyNamesIncludePreserved);
bool ok = checker.Check(hotUpdateDllPath); // false: the dll touches a stripped type or method
```
The second argument is hot-update assembly names without `.dll`. If an Ultimate build also has DHE assemblies, include those names in the list.
+51
View File
@@ -0,0 +1,51 @@
---
name: hybridclr-configure
description: >-
Configure HybridCLR Settings and PlayerSettings: enable, hot-update assembly lists, external dll search paths, link.xml output, linkPreserveLevel, incremental GC, and IL2CPP. Use when the user opens HybridCLR/Settings, edits ProjectSettings/HybridCLRSettings.asset, checks settings before a player build, or asks what a setting does.
---
# Configure HybridCLR
Docs: `D:/workspace/hybridclr-doc/docs/guide/setup/projectsettings.md` and `hybridclr-unity-package.md`. Fields follow `Editor/Settings/HybridCLRSettings.cs` in this repo. The asset is `ProjectSettings/HybridCLRSettings.asset`.
How to split assemblies and create asmdefs is `hybridclr-hotupdate-assembly`. Do not expand that here.
## PlayerSettings
- Scripting Backend is **IL2CPP**. WebGL does not use this option. Since v2.4.0 the build check switches this automatically.
- Api Compatibility Level is **.NET Framework**.
- Incremental GC is allowed since v4.0.0. Older packages must turn it off.
## Hot-update lists
`hotUpdateAssemblyDefinitions` and `hotUpdateAssemblies` merge into the final hot-update dll list. **Do not put the same assembly in both.**
| Source | Where |
|---|---|
| asmdef | `hotUpdateAssemblyDefinitions` |
| External dll, or `Assembly-CSharp` | `hotUpdateAssemblies`, name **without** `.dll` |
An empty list fails the player-build check. `IFilterBuildAssemblies` removes these dlls from the player build so they are not compiled into AOT.
## Settings
- `enable`: default true. Turning it off drops HybridCLR from the player. Also remove the main project's reference to `HybridCLR.Runtime`, or symbols such as `LoadMetadataForAOTAssembly` are missing.
- `useGlobalIl2cpp`: default false. Keep the local `UNITY_IL2CPP_PATH`.
- `hybridclrRepoURL` / `il2cppPlusRepoURL`: clone URLs for the installer. Default is gitee.
- `preserveHotUpdateAssemblies`: names of hot-update dlls that do not exist yet (no `.dll`). The build does not check that the files exist, but it writes the names into `ScriptingAssemblies.json` so scripts can be attached to assets later. Do not list dlls that already exist.
- `externalHotUpdateAssembliyDirs`: search paths for external hot-update dlls. The serialized name is spelled `Assembliy`. Do not rename it. Paths are relative to the **project root** (parent of Assets). Each entry is searched as `{dir}/{platform}` first, then `{dir}`. Earlier entries win. The dll name still goes in `hotUpdateAssemblies`.
- `outputLinkFile`: output of `Generate/LinkXml`. Default `HybridCLR/Generate/link.xml`, relative to Assets. **Do not** point it at `Assets/link.xml`. Generation overwrites the file.
- `linkPreserveLevel`: `PreserveAllOfDeclaringType` (default; keep every member of a referenced type) or `PreserveExactMember` (only referenced fields, methods, properties, and events; smaller).
- `outputAOTGenericReferenceFile`: default `HybridCLR/Generate/AOTGenericReferences.cs`.
- `maxGenericReferenceIteration` / `maxMethodBridgeGenericIteration`: generic scan iteration cap, default 10. Raise them only if the log shows the scan has not converged.
## Fixed output directories
These are not settings:
- Hot-update dlls: `{project}/HybridCLRData/HotUpdateDlls/{target}`
- Stripped AOT dlls: `{project}/HybridCLRData/AssembliesPostIl2CppStrip/{target}`
## What the package does during a player build
Do not hand-edit these: set or clear the process `UNITY_IL2CPP_PATH` from `enable`; strip hot-update assemblies from the build; write hot-update dll names into the assembly list; copy stripped AOT dlls to the directory above.
@@ -0,0 +1,61 @@
---
name: hybridclr-hotupdate-assembly
description: >-
Split, create, compile, and load HybridCLR hot-update assemblies: asmdefs and Assembly-CSharp, forbidding AOT references to hot-update code, CompileDll, Assembly.Load order, and calling hot-update entry points from the main project. Use when the user adds a hot-update module, splits AOT and hot-update code, compiles HotUpdate.dll, loads a dll, hits a duplicate load, or a player build references a hot-update assembly.
---
# Hot-update assemblies
Docs: `D:/workspace/hybridclr-doc/docs/guide/setup/hotupdateassemblysetting.md`, `guide/build/compileassembly.md`, and `guide/build/runhotupdatecodes.md`. Settings fields are in `hybridclr-configure`.
## Split
Keep at least one **AOT** assembly for startup and for downloading hot-update content. Hot-update code must live in its own assembly.
Two common layouts:
- `Assembly-CSharp` stays AOT, and other code is split into AOT and hot-update asmdefs. **Turn off Auto Referenced on hot-update asmdefs.** `Assembly-CSharp` references every other assembly, so Auto Referenced easily creates an AOT reference to a hot-update dll and the player build fails.
- `Assembly-CSharp` itself is hot-update. Put the name in `hotUpdateAssemblies` without `.dll`.
AOT assemblies must not reference hot-update assemblies. Hot-update assemblies may reference each other. Load dependencies first.
## Create
1. Create a folder, for example `Assets/HotUpdate`.
2. Create → Assembly Definition, named like the module.
3. In `HybridCLR/Settings`, put asmdefs in `hotUpdateAssemblyDefinitions`. Put assemblies that have no asmdef in `hotUpdateAssemblies` by name. Do not add the same assembly to both.
4. For a prebuilt dll outside the default output directory, put the name in `hotUpdateAssemblies` and the directory in `externalHotUpdateAssembliyDirs` (relative to the project root).
## Compile
Do not ship dlls from `Library/ScriptAssemblies`. Those are compiled for the Editor target and depend on the debugger setting.
- Use `HybridCLR/Compile/{platform}`, or `HybridCLR.Editor.Commands.CompileDllCommand.CompileDll(BuildTarget)`.
- Output: `{project}/HybridCLRData/HotUpdateDlls/{target}`. Compile once per BuildTarget so defines such as `UNITY_ANDROID` match.
- `HybridCLR/Generate/All` also compiles hot-update dlls. **After the player is shipped**, a normal hot update only recompiles and publishes the dll. Do not run Generate every time.
When copying into assets, add a `.bytes` extension (`HotUpdate.dll.bytes`).
## Load
```csharp
// The runtime copies the bytes. Do not keep assemblyData or pdb after the call returns.
Assembly ass = Assembly.Load(assemblyData);
// Since v6.4.0, symbols can load with the assembly:
Assembly ass2 = Assembly.Load(assemblyData, pdbSymbolData);
```
- `Assembly.Load` multiple dlls in dependency order. Move the call to another thread if it stalls the main thread.
- **Do not Load again in the Editor.** The assemblies are already in the domain. Wrap the load in `#if !UNITY_EDITOR` and, in the Editor, find them with `AppDomain.CurrentDomain.GetAssemblies()`.
- An assembly missing from the hot-update lists is compiled into AOT. Loading it again at runtime is a duplicate load.
## Call hot-update code from AOT
The main project cannot reference hot-update types directly. Typical entry points:
- Reflection: `ass.GetType(...).GetMethod(...).Invoke`
- `Delegate.CreateDelegate`, or `Activator.CreateInstance` cast to an interface defined in AOT
- `go.AddComponent(type)` after the dll is loaded
- Instantiate a prefab or scene packed in an AssetBundle (extra rules for scripts on assets are in `hybridclr-monobehaviour`)
Load the dll **before** loading an AssetBundle that should restore those scripts.
@@ -0,0 +1,28 @@
---
name: hybridclr-monobehaviour
description: >-
Use MonoBehaviour and ScriptableObject from HybridCLR hot-update code: AddComponent, scripts on assets, ScriptingAssemblies.json, AssetBundle load order, Script Missing, and the GetComponent(string) limitation. Use when the user attaches a hot-update script to a prefab or scene, hits Script Missing, or asks about the hot-update MonoBehaviour workflow.
---
# Hot-update MonoBehaviour
Doc: `D:/workspace/hybridclr-doc/docs/guide/features/monobehaviour.md`. Registering the assembly is `hybridclr-hotupdate-assembly`.
`AddComponent<T>()` and `AddComponent(Type)` work after that dll has been `Assembly.Load`ed.
## Scripts and ScriptableObjects on assets
Deserialization needs all of the following:
1. The dll that contains the script is already loaded.
2. The asset is loaded from an AssetBundle (Addressables and other AB-based systems count). A script on a Resources asset or a scene that ships in the player becomes **Script Missing**. Building that asset into an AssetBundle and then placing the bundle in Resources is fine.
3. The dll name is in the generated `ScriptingAssemblies.json`. Hot-update dlls are removed by `IFilterBuildAssemblies`, so they are not listed on their own. `PatchScriptingAssemblyList` writes names from `hotUpdateAssemblyDefinitions`, `hotUpdateAssemblies`, and `preserveHotUpdateAssemblies`. Unlisted assemblies are not restored.
The hot-update dll itself may live in an AssetBundle, as a raw file, or in an encrypted package. `Assembly.Load` it **before** loading assets that contain the scripts.
Do not rename these assemblies after release. The assembly list is baked into the player and cannot be hot-updated.
## Known limits
- `GetComponent(string)` cannot find a hot-update script that was restored from a hot-update asset. Use `GetComponent<T>()` or `GetComponent(typeof(T))`. Components added with `AddComponent` in code are not affected.
- Do not disable TypeTree when building AssetBundles. Script signature checks then fail and a normal load fails. If TypeTree must be off, call `AssetBundleCreateRequest.SetEnableCompatibilityChecks(false)` through reflection and keep code and asset versions matched. A mismatch can crash.
@@ -0,0 +1,39 @@
---
name: hybridclr-monopinvokecallback
description: >-
Reserve MonoPInvokeCallback and ReversePInvokeWrapper slots for HybridCLR hot-update methods: ReversePInvokeWrapperGenerationAttribute, Generate/ReversePInvokeWrapper, and the lack of automatic marshaling for string and other non-blittable arguments. Use for MonoPInvokeCallback, xlua/tolua/puerts callbacks, too few wrappers, or a crash when native code calls hot-update C#.
---
# MonoPInvokeCallback
Doc: `D:/workspace/hybridclr-doc/docs/guide/features/monopinvokecallback.md`. Choosing a Lua, JS, or Python stack is `hybridclr-script-language`.
A static method with `[MonoPInvokeCallback]` needs a C++ wrapper before `Marshal.GetFunctionPointerForDelegate` can return a pointer. Platforms that cannot JIT, including iOS, cannot create that wrapper at runtime. Generate it in the player build with `HybridCLR/Generate/ReversePInvokeWrapper` (`Generate/All` includes it).
## Reserve a count
Generating one wrapper per current callback runs out as soon as a later hot update adds another callback.
Add `[ReversePInvokeWrapperGeneration(preserveCount)]` (`HybridCLR` namespace) on the callback. **Counts are per signature:**
wrappers for a signature = sum of `preserveCount` on that signature + number of callbacks of that signature that do not have the attribute.
```csharp
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int LuaFunction(IntPtr luaState);
[ReversePInvokeWrapperGeneration(10)]
[MonoPInvokeCallback(typeof(LuaFunction))]
public static int LuaCallback(IntPtr luaState) => 0;
```
The reservation is fixed in the player. Hot updates can only consume wrappers that were already generated.
## Argument marshaling
HybridCLR does **not** marshal arguments when calling these callbacks. `int` and `float` work. `string` arrives as `char*` and using it as a string crashes.
Two options:
1. Put the callback in AOT and call into hot-update code from there. The AOT wrapper has il2cpp marshaling.
2. Take `IntPtr` in the hot-update callback and convert with `Marshal.PtrToStringUTF8`. Do the same for other non-primitive types that need marshaling.
@@ -0,0 +1,36 @@
---
name: hybridclr-script-language
description: >-
Run HybridCLR next to Lua, JavaScript/TypeScript, or Python: prefer ZLua and ZenTS; xlua, tolua, slua, and puerts need reserved ReversePInvokeWrappers and generated binding code moved into a hot-update assembly. Use when the user combines HybridCLR with lua, js, ts, python, xlua, tolua, puerts, zlua, or ZenTS, or is moving script hot update to C#.
---
# Script languages
Doc: `D:/workspace/hybridclr-doc/docs/guide/features/workwithscriptlanguage.md`. Wrapper reservation rules are in `hybridclr-monopinvokecallback`. Do not restate them here.
HybridCLR is native C# hot update. It can sit beside an existing script stack while gameplay moves back to C#.
## Prefer ZLua / ZenTS
For a new scripting layer, use the official stacks instead of xlua or puerts.
- [ZLua](https://github.com/focus-creative-games/zlua) for Lua
- [ZenTS](https://github.com/focus-creative-games/zen-ts) for JavaScript / TypeScript
They talk to il2cpp directly. They do not need `[MonoPInvokeCallback]` or a wrapper quota. Use the path below only when the project is already on xlua, tolua, or puerts.
## Other script stacks
xlua, tolua, slua, puerts, and similar binders call C# from native through `[MonoPInvokeCallback]`. Before the player build:
1. Add `[ReversePInvokeWrapperGeneration(n)]` on signatures that will grow. The count must cover later hot updates, not only the callbacks that exist now.
2. Run `HybridCLR/Generate/All` (includes `ReversePInvokeWrapper`).
3. Put generated binding code in a **hot-update** assembly and register that assembly. Do not leave it where it will be compiled as AOT.
### xlua
xlua emits code into global `Assembly-CSharp` and ties it to runtime types with partial classes. The generated output usually has to be edited before it can live in a hot-update assembly. [HybridCLRXlua](https://gitee.com/ldr123/HybridCLRXlua) is a working reference. Follow that project's assembly split. Do not assume the stock xlua generator supports HybridCLR as-is.
### tolua, slua, puerts
Check three things: enough wrappers are reserved, generated code is in the hot-update module, and registration runs after the hot-update dll is loaded.
+47
View File
@@ -0,0 +1,47 @@
---
name: hybridclr-setup
description: >-
Install and initialize com.code-philosophy.hybridclr: pick a matching Unity and package version, add the package from git or a local Packages folder, run HybridCLR/Installer, and recover from git or network failures. Use when the user installs, upgrades, or initializes HybridCLR, or when install fails, git clone fails, or the player still uses stock IL2CPP.
---
# Install HybridCLR
Docs: `D:/workspace/hybridclr-doc/docs/guide/setup/install.md` and `supported-platforms-and-unity-versions.md`. Package and il2cpp branches come from this repo's `Data~/hybridclr_version.json`. Do not change those branches from memory.
## Versions
- **v9.x** supports Unity **2022.3.x** and **6000.x** except 6000.5.x. Use **v8.x** for 2019.4, 2020.3, and 2021.3.
- The package name is `com.code-philosophy.hybridclr`. Before v3.0.0 it was `com.focus-creative-games.hybridclr_unity`.
- Standalone players need the **IL2CPP** module (`Windows Build Support (IL2CPP)` or `Mac Build Support (IL2CPP)`). An editor that only has the iOS or Android module cannot build that Standalone player. Exporting an iOS Xcode project does not require a local signing certificate.
## Install the package
Either:
1. Package Manager → Add package from git URL: `https://gitee.com/focus-creative-games/hybridclr_unity.git` or the GitHub repo with the same name. Pin a tag with `#{tag}`, for example `#v9.0.0`.
2. Place the repo at `Packages/com.code-philosophy.hybridclr`.
## Initialize (required)
Installing the package does not replace libil2cpp.
1. **git** must be installed. Restart the Unity Editor and Hub after installing git. Restart the machine if git is on PATH but the installer still cannot find it.
2. Open `HybridCLR/Installer...` and use the default remote install. Success prints `安装成功` and the status becomes installed.
3. The installer clones the `hybridclr` and `il2cpp_plus` branches listed in `Data~/hybridclr_version.json` for the current Unity major version. Do not edit that file unless the user explicitly wants a non-matching version.
4. If git or the network is unavailable, merge a local libil2cpp that already contains HybridCLR, enable "copy libil2cpp from local" in the installer, and install. Merge `il2cpp_plus/libil2cpp` with `hybridclr/hybridclr` into the final libil2cpp (see the install doc).
Local install lands in `{project}/HybridCLRData/LocalIl2CppData-{platform}/`. The package sets `UNITY_IL2CPP_PATH` only for the **current Editor process**. Leave `useGlobalIl2cpp` off.
## Updates
After updating the package, run `HybridCLR/Installer` again. The installer clears `Library/Il2cppBuildCache`. If libil2cpp was replaced by hand, delete that cache or the player build keeps the old IL2CPP.
## Host tools
- Windows: Visual Studio 2022 or newer with the Unity game development and C++ game development workloads, plus git.
- Mac: macOS 12 or newer, Xcode 13 or newer, plus git and cmake.
## Do not
- Do not replace libil2cpp inside the Editor install unless the user explicitly wants a global install and accepts that other projects are affected and that every `Generate` must be copied back over the Editor libil2cpp.
- WebGL uses the same local install as other platforms.