baxi 2 週間 前
親
コミット
7cdf823ff5
100 ファイル変更、3884 行追加、519 行削除
  1. 10 5
      CHANGELOG.md
  2. 165 0
      Documentation~/HotPatch.md
  3. 17 23
      Documentation~/OriginalUsage.md
  4. 15 0
      Documentation~/S3Upload.md
  5. 1 1
      Editor/AppHelpLinkerProcessor.cs
  6. 2 1
      Editor/AppHelpPackagePaths.cs
  7. 4 4
      Editor/AppHelpProjectSettings.cs
  8. 1 1
      Editor/AppHelpStreamingAssetsProcessor.cs
  9. 20 14
      Editor/AppRuntimes.Editor.asmdef
  10. 107 46
      Editor/AppSettingsWindow.cs
  11. 1 1
      Editor/Config.meta
  12. 7 0
      Editor/Config/S3UploadSettings.json
  13. 1 1
      Editor/Config/S3UploadSettings.json.meta
  14. 104 0
      Editor/CryptoTools.cs
  15. 1 4
      Editor/CryptoTools.cs.meta
  16. 1 0
      Editor/DefaultSettings/AppSettings.asset
  17. 26 26
      Editor/DisableBitcode.cs
  18. 5 0
      Editor/HotPatch.meta
  19. 8 0
      Editor/HotPatch/HotPatch.Editor.asmdef
  20. 4 0
      Editor/HotPatch/HotPatch.Editor.asmdef.meta
  21. 39 0
      Editor/HotPatch/HotPatchAndroidResolverScope.cs
  22. 2 0
      Editor/HotPatch/HotPatchAndroidResolverScope.cs.meta
  23. 503 0
      Editor/HotPatch/HotPatchBuild.cs
  24. 1 4
      Editor/HotPatch/HotPatchBuild.cs.meta
  25. 148 0
      Editor/HotPatch/HotPatchBundleBuild.cs
  26. 2 0
      Editor/HotPatch/HotPatchBundleBuild.cs.meta
  27. 134 0
      Editor/HotPatch/HotPatchGenerationState.cs
  28. 2 0
      Editor/HotPatch/HotPatchGenerationState.cs.meta
  29. 92 0
      Editor/HotPatch/HotPatchLocalTesting.cs
  30. 2 0
      Editor/HotPatch/HotPatchLocalTesting.cs.meta
  31. 195 0
      Editor/HotPatch/HotPatchResourcePackage.cs
  32. 2 0
      Editor/HotPatch/HotPatchResourcePackage.cs.meta
  33. 27 0
      Editor/HotPatch/HotPatchSettingsIntegration.cs
  34. 2 0
      Editor/HotPatch/HotPatchSettingsIntegration.cs.meta
  35. 49 0
      Editor/HotPatch/HotPatchSourcesLinker.cs
  36. 2 0
      Editor/HotPatch/HotPatchSourcesLinker.cs.meta
  37. 132 0
      Editor/HotPatchAssemblySelection.cs
  38. 2 0
      Editor/HotPatchAssemblySelection.cs.meta
  39. 11 0
      Editor/HotPatchResourceActions.cs
  40. 2 0
      Editor/HotPatchResourceActions.cs.meta
  41. 178 0
      Editor/HotPatchSourceSync.cs
  42. 1 4
      Editor/HotPatchSourceSync.cs.meta
  43. 7 7
      Editor/LocalFacebookSdk.cs
  44. 1 1
      Editor/PackageSetup.meta
  45. 8 0
      Editor/PackageSetup/AppRuntimes.PackageSetup.Editor.asmdef
  46. 1 1
      Editor/PackageSetup/AppRuntimes.PackageSetup.Editor.asmdef.meta
  47. 101 0
      Editor/PackageSetup/EditorPackageInstaller.cs
  48. 2 0
      Editor/PackageSetup/EditorPackageInstaller.cs.meta
  49. 16 0
      Editor/PackageSetup/HybridCLRPackageSetup.cs
  50. 2 0
      Editor/PackageSetup/HybridCLRPackageSetup.cs.meta
  51. 60 0
      Editor/PackageSetup/LaunchTemplateSetup.cs
  52. 2 0
      Editor/PackageSetup/LaunchTemplateSetup.cs.meta
  53. 29 0
      Editor/PackageSetup/UnityMcpPackageSetup.cs
  54. 2 0
      Editor/PackageSetup/UnityMcpPackageSetup.cs.meta
  55. 184 0
      Editor/S3ResourceUploader.cs
  56. 2 0
      Editor/S3ResourceUploader.cs.meta
  57. 85 0
      Editor/S3UploadController.cs
  58. 2 0
      Editor/S3UploadController.cs.meta
  59. 73 0
      Editor/S3UploadSettings.cs
  60. 2 0
      Editor/S3UploadSettings.cs.meta
  61. 8 8
      Editor/XcodePluginLayout.cs
  62. 2 2
      Editor/XcodePostprocessor.cs
  63. 10 102
      README.md
  64. 17 18
      Runtime/AppRuntimes.asmdef
  65. 5 0
      Runtime/HotPatch.meta
  66. 7 0
      Runtime/HotPatch/HotPatch.Runtime.asmdef
  67. 4 0
      Runtime/HotPatch/HotPatch.Runtime.asmdef.meta
  68. 47 0
      Runtime/HotPatch/HotPatchBundleLoader.cs
  69. 2 0
      Runtime/HotPatch/HotPatchBundleLoader.cs.meta
  70. 35 0
      Runtime/HotPatch/HotPatchLaunchResources.cs
  71. 2 0
      Runtime/HotPatch/HotPatchLaunchResources.cs.meta
  72. 174 0
      Runtime/HotPatch/HotPatchManifest.cs
  73. 1 4
      Runtime/HotPatch/HotPatchManifest.cs.meta
  74. 299 0
      Runtime/HotPatch/HotPatchResourceStore.cs
  75. 2 0
      Runtime/HotPatch/HotPatchResourceStore.cs.meta
  76. 216 0
      Runtime/HotPatch/HotPatchService.cs
  77. 8 0
      Runtime/HotPatch/HotPatchService.cs.meta
  78. 38 0
      Runtime/HotPatch/HotPatchUnityGenericReferences.cs
  79. 2 0
      Runtime/HotPatch/HotPatchUnityGenericReferences.cs.meta
  80. 37 19
      Runtime/Plugins/iOS/AppRuntimesNative.mm
  81. 8 0
      Runtime/Scripts/AppRuntimes.Base.asmdef
  82. 4 0
      Runtime/Scripts/AppRuntimes.Base.asmdef.meta
  83. 12 0
      Runtime/Scripts/AppRuntimesEvents.cs
  84. 2 0
      Runtime/Scripts/AppRuntimesEvents.cs.meta
  85. 38 2
      Runtime/Scripts/AppSettings.cs
  86. 0 220
      Runtime/Scripts/ClientCrypto.cs
  87. 10 0
      Runtime/Scripts/FacebookNativeBridge.cs
  88. 2 0
      Runtime/Scripts/FacebookNativeBridge.cs.meta
  89. 14 0
      Runtime/Scripts/HotPatchInitializerAttribute.cs
  90. 2 0
      Runtime/Scripts/HotPatchInitializerAttribute.cs.meta
  91. 17 0
      Runtime/Scripts/HotPatchLog.cs
  92. 2 0
      Runtime/Scripts/HotPatchLog.cs.meta
  93. 18 0
      Runtime/Scripts/ILaunchResources.cs
  94. 2 0
      Runtime/Scripts/ILaunchResources.cs.meta
  95. 9 0
      Runtime/Scripts/ILaunchView.cs
  96. 2 0
      Runtime/Scripts/ILaunchView.cs.meta
  97. 150 0
      Runtime/Scripts/LaunchApp.cs
  98. 2 0
      Runtime/Scripts/LaunchApp.cs.meta
  99. 65 0
      Runtime/Scripts/LaunchSceneInput.cs
  100. 2 0
      Runtime/Scripts/LaunchSceneInput.cs.meta

+ 10 - 5
CHANGELOG.md

@@ -1,5 +1,15 @@
 # Changelog
 # Changelog
 
 
+## Unreleased — Hot Patch
+
+- Switch StreamingAssets between the latest complete original/update resource sets in AppSettings; support local-only Launch loading with an isolated cache and disable resource actions until a matching package exists.
+- Automatically install the missing HybridCLR UPM Git package after import, preserve existing installations, and expose installation status and retry in AppSettings.
+- Resolve the current UPM package name when normalizing Xcode Frameworks/Libraries paths, removing the come.runtimes.hot wrapper after export.
+- Keep Sources as Editor-only C# templates; synchronize them into HexaCrazy.Runtime without the marked outer UNITY_EDITOR envelope.
+- Add DownloadUrl, manifest validation, verified cache, AOT metadata loading and automatic patched initialization.
+- Add source synchronization, DLL-only compilation, one-click export and Windows host baseline tools.
+- Separate stable foundation APIs from patchable SDK logic and preserve package-local editor tools.
+
 ## 1.0.0
 ## 1.0.0
 
 
 - Normalize iOS native plugin exports to standard Frameworks/Libraries paths without package wrapper directories, preserving Xcode references, compiler flags and build phases.
 - Normalize iOS native plugin exports to standard Frameworks/Libraries paths without package wrapper directories, preserving Xcode references, compiler flags and build phases.
@@ -18,8 +28,3 @@
 - Fix the Obfuscator settings page's 14 hardcoded GUI resource paths to load textures from the package; include a repeatable DLL/PDB patch tool.
 - Fix the Obfuscator settings page's 14 hardcoded GUI resource paths to load textures from the package; include a repeatable DLL/PDB patch tool.
 - Update Xcode Project Folders
 - Update Xcode Project Folders
 - Explicitly select AppRuntimes for obfuscation after UPM migration; validate renamed types and methods in the assembly consumed by IL2CPP.
 - Explicitly select AppRuntimes for obfuscation after UPM migration; validate renamed types and methods in the assembly consumed by IL2CPP.
-
-## 1.0.3
-
-- Add new api (/api/platform/config)
-- Remove Privacy agreement

+ 165 - 0
Documentation~/HotPatch.md

@@ -0,0 +1,165 @@
+# Hot Patch / 资源构建
+
+Resources are split into three AssetBundles: AOT, hot-update assembly, and game scene. Original resources contain all three bundles. Update resources contain only the assembly and scene bundles. AOT is fixed in the installed application and is never updated from the server.
+
+## Package installation
+
+Install AppRuntimes through Package Manager using its Git URL. Once the Editor finishes importing, an independent Editor assembly checks for `com.code-philosophy.hybridclr`. If missing, it uses Unity Package Manager to add `https://gitee.com/focus-creative-games/hybridclr_unity.git#v9.0.3` to the project's dependencies. It preserves an existing HybridCLR package, including Git, registry, embedded, and local installations.
+
+Unity does not support Git dependencies inside a package's `package.json`; Git URLs must be project dependencies. The installer therefore uses `Client.Add` instead of declaring an invalid package dependency or editing another project's manifest directly. See [Unity Git dependencies](https://docs.unity3d.com/6000.3/Documentation/Manual/upm-git.html).
+
+Installation runs asynchronously after compilation and import finish. A failed attempt does not repeat on every domain reload. Open AppSettings and select **Retry HybridCLR Installation**, or add the URL manually through Package Manager. The official GitHub alternative is `https://github.com/focus-creative-games/hybridclr_unity.git#v9.0.3`. Projects with existing script compilation errors may need this manual installation before Editor initialization can run. Wait for installation and compilation before clicking Save.
+
+Adding the UPM package and running `HybridCLR/Installer` are separate steps. **一键打包资源** still performs Installer setup and Generate/All when needed; the package import step does not build a Player or modify IL2CPP. See [HybridCLR installation](https://www.hybridclr.cn/docs/basic/install).
+
+## Configuration
+
+Select **AppSettings/Install Unity MCP** to install `com.coplaydev.unity-mcp` from `https://github.com/CoplayDev/unity-mcp.git?path=/MCPForUnity#main` when absent. Installation starts only from this menu, which also retries failed installations; startup and status checks do not schedule it. Its installer shares the HybridCLR request queue. Existing installations are not upgraded. Select **AppSettings/Load Launch Templates** to copy the package's `Templates~/Launch` into `Assets/Launch` only if that folder is absent; it preserves the scene/script GUID references and leaves existing project Launch content intact. Launch is not copied automatically at startup. **Open Settings** appears first in the AppSettings menu, followed by a separator, **Load Launch Templates**, and **Install Unity MCP**.
+
+Save automatically adds missing `AppRuntimes.Base` and `Unity.Advertisement.IosSupport` references to the selected runtime asmdef, preserving other settings and supporting both name and GUID references. The build button and menu stay disabled while required references or saved assembly/scene settings are missing. The window also disables building for unsaved assembly/scene selections; Save refreshes its state. Compilation, Play Mode, uploads and ongoing builds temporarily disable building.
+
+In `AppSettings/Open Settings`, select the hot-update asmdef, enter the **Game Scene Name** and **DownloadUrl**, then click Save. The current configuration is `HexaCrazy.Runtime` / `HexaCrazy`. The scene name excludes `.unity` and must be unique under Assets. Selecting an assembly synchronizes the HybridCLR hot-update settings.
+
+DownloadUrl accepts a resource directory (automatically appending `manifest.json`) or a complete manifest URL. When accessing a local IIS server from a phone, use the computer's LAN IP address or domain name instead of `localhost`. HTTP debugging requires HTTP to be enabled in Player Settings; use HTTPS for releases.
+
+The game scene is provided by its bundle and excluded from the Player scene list. Resource builds first normalize the global scene list and any active Build Profile override to a single enabled Launch scene. Other entries are removed from the list; scene assets are retained. Keep the game scene's own MonoBehaviours. Launch loads the configured scene without a separate game-entry call.
+
+`LaunchApp.RunAsync(Action onUpdated = null)` updates resources, then invokes the supplied callback. Without a callback it awaits `OpenSceneAsync()` directly. To defer scene entry, supply a callback to show your ready/start UI, then call `OpenSceneAsync()` when ready. The callback runs after `IsRunning` is cleared and may also call `OpenSceneAsync()` immediately. Prepared resources are reused, and all scene loading, activation, input transfer, Editor initialization and Launch unloading are handled by `OpenSceneAsync()`. `IsResourcesReady` indicates a successful update; `IsCompleted` becomes true only after scene entry and Launch scene unloading finish. Update retries preserve the callback. Failed or canceled updates do not invoke it. Callback exceptions propagate to the caller.
+
+## Local resource testing
+
+AppSettings enables **使用本地资源测试**, **恢复正式资源**, and **上传资源** when `Build/HotUpdate` contains a complete `AllRes_<timestamp>` directory matching the saved assembly, game scene, and active build target. It selects the newest complete matching directory. Both manifests and their referenced files must exist. Build, upload, compilation, and Play Mode temporarily disable resource switching.
+
+**使用本地资源测试** verifies and stages `manifest_hot.json`, its assembly and scene bundles, and the fixed AOT bundle. It replaces all StreamingAssets contents and names the selected manifest `manifest.json`. It saves local testing mode in AppSettings. Launch extracts and verifies those resources using a separate `HotUpdate/LocalTest` cache and makes no remote manifest or resource requests. DownloadUrl is preserved and may be empty in this mode. This also works in iOS and Android Players; Editor execution continues to use its local script assemblies as before.
+
+**恢复正式资源** replaces StreamingAssets with `manifest.json` and only its referenced original resources from the same latest archive. It disables local testing mode, so Launch resumes remote updates. A successful original resource publication during 一键打包资源 also restores normal mode. Source validation and staging finish before replacing StreamingAssets; missing or corrupt inputs leave the previous installation intact.
+
+## Bundle strategy
+
+| Bundle | Input | Update policy |
+| --- | --- | --- |
+| `aot.bundle` | Four `.dll.bytes` files in the project's `Assets/AotDlls` | Shipped only with the original application |
+| `hotupdate.<lowercase-assembly>.bundle` | `<assembly>.dll.bytes` compiled for the current platform | Updated by SHA-256 comparison |
+| `scene.<lowercase-scene>.bundle` | The scene configured in AppSettings and its dependencies collected by Unity | Updated by SHA-256 comparison |
+
+`Assets/AotDlls` contains exactly:
+
+```text
+Assets/AotDlls/
+  mscorlib.dll.bytes
+  Newtonsoft.Json.dll.bytes
+  System.Core.dll.bytes
+  UniTask.dll.bytes
+```
+
+Original builds generate four stripped metadata DLLs from the current platform's Generate/All stripped AOT archive, copy them to the project's `Assets/AotDlls`, and pack those four files into the AOT bundle. Old Windows AOT data is not used for Android/iOS release resources. Update builds neither rebuild the AOT bundle nor modify `Assets/AotDlls`.
+
+DLLs remain `.dll.bytes` TextAssets inside bundles and are loaded by fixed file names. Bundles use LZ4 and retain TypeTree data. Builds do not depend on AssetBundle labels on other project assets. Unity automatically collects scene dependencies, and the build rejects additional bundle dependencies. At runtime, AssetBundle.GetAllScenePaths provides the actual scene path.
+
+Before serializing bundles, both original and update builds run the official TMP build preprocessor to clear Dynamic / Dynamic OS font caches with `Clear Dynamic Data On Build` enabled, then save those fonts and atlases. Characters added while previewing or running UI in the Editor therefore do not change scene bundles unnecessarily. Static fonts and fonts without this setting are preserved, as are OpenType feature data and runtime dynamic glyph generation. Changes to scenes, actual dependencies, or serialized structures still produce new bundle hashes.
+
+## Menus and baselines
+
+The menu contains only **资源构建/一键打包资源**, which performs these stages:
+
+1. Install HybridCLR if necessary, configure .NET Framework/IL2CPP, and run Generate/All if the current platform's record is invalid.
+2. Delete the target assembly's HotPatch directory, wait for compilation, compile the original DLL, validate the AOT baseline, prepare Assets/AotDlls, and stage the three original bundles and manifest.
+3. Synchronize AppRuntimes.Sources into HotPatch, wait for compilation, compile and validate the updated DLL, and build update assembly and scene bundles.
+4. Delete HotPatch, including subdirectories and the folder meta file, and wait for successful compilation. Export both resource versions to `Build/HotUpdate/AllRes_yyyyMMdd_HHmmss_fff`. Replace StreamingAssets with only `manifest.json` and its referenced original resources. Compilation or resource preparation failures preserve the previous StreamingAssets and current baseline pointer. Other files in the assembly directory are preserved.
+
+Separate original/update builds, source synchronization, and DLL compilation remain available as Editor APIs, without separate menu entries.
+
+Generate/All performs the build steps required to obtain stripped AOT assemblies. 一键打包资源 does not additionally create a complete APK/Xcode application package; build that afterward through Unity. The Player requires .NET Framework rather than netstandard; see the [official migration guide](https://www.hybridclr.cn/docs/basic/migratefromnetstandard).
+
+Resource build commands disable `EditorUserBuildSettings.buildScriptsOnly`. Use Build or Clean build for the application package. After changing scenes or resources, do not force reuse of old Player data through `Force skip data build`, which can cause `Cached scene list differs from what is being built` or omit the latest StreamingAssets.
+
+During Android AOT stripping and bundle builds, External Dependency Manager's automatic AAR resolution is temporarily disabled and then restored. Normal APK builds retain their existing dependency resolution settings. Intermediate bundles are stored in `Build/HotUpdate/BundleCache/<platform>`; only bundles declared in the manifest are published to original or update directories.
+
+Original baselines are archived in `Build/HotUpdate/Baselines/<platform>/<build-id>`, including the original stripped AOT assemblies, four stripped metadata DLLs, the fixed AOT bundle, and hashes. Update builds verify Unity/HybridCLR, platform, API compatibility, Development Build, host code, and assembly settings. New host dependencies or incompatible members require rebuilding original resources and the application package.
+
+For iOS, the host explicitly references `ATTrackingStatusBinding`, and the linker preserves `Unity.Advertisement.IosSupport`. The Editor-only Sources assembly cannot reveal calls compiled only for the iOS Player. These preservation changes invalidate the previous Generate/All record and require a fresh baseline. This assembly stays in the AOT host; the four supplemental metadata DLLs in Assets/AotDlls remain unchanged.
+
+## Output and manifests
+
+Original StreamingAssets:
+
+```text
+manifest.json
+aot.bundle
+files/<assembly-bundle-SHA256>.bundle
+files/<scene-bundle-SHA256>.bundle
+```
+
+A server update directory contains only `manifest.json` and two `files/*.bundle` files. Upload files before replacing manifest.json. IIS must allow `.json` and `.bundle` static files.
+
+Both original and update manifests use **schemaVersion 4** with the same field structure: platform, build ID, assembly, and scene name/path. `resources` contains each version's assembly and scene bundles. `aotBundles` identifies the same fixed AOT bundle, and `aotMetadata` records the same four DLL sizes and hashes. Update manifests inherit AOT information from the original baseline without rebuilding or remotely downloading the AOT bundle. Legacy schemaVersion 3 raw DLL resources cannot be mixed with these bundles; rebuild original resources, the application package, and updates.
+
+After 一键打包资源, `Build/HotUpdate/AllRes_<timestamp>` contains every bundle referenced by both manifests. StreamingAssets retains the original layout shown above.
+
+```text
+manifest.json       # Original resource manifest
+manifest_hot.json   # Update resource manifest
+aot.bundle          # Fixed AOT shared by both manifests
+files/*.bundle      # Original and update bundles, deduplicated by content hash
+```
+
+Launch still initializes its original cache from the installed `manifest.json`. When hosting the AllRes output directory directly, set DownloadUrl to the complete `https://server/resource-directory/manifest_hot.json` URL to retrieve updates. Separate update builds through the Editor API output `manifest.json`, which remains the default for directory URLs. Builds do not change AppSettings URLs automatically. DLLs inside bundles retain `.dll.bytes`, while external bundles use `.bundle`. Migrating from `.bundle.bytes` requires rebuilding resources and the application package and updating the server files together.
+
+## Launch flow
+
+1. Read AppSettings.
+2. Extract the AOT bundle from StreamingAssets into `Application.temporaryCachePath/HotUpdate/<build-id-hash>`. If the cache is missing, also extract the original assembly bundle, scene bundle, and manifest. Verify the size and SHA-256 of every bundle.
+3. Download the remote manifest, validate the platform, assembly, scene, and baseline, compare against the cache, and download only changed or corrupt assembly and scene bundles.
+4. Once both bundles are complete, atomically commit the new manifest and remove obsolete files. Any download failure preserves the previous complete version. Unchanged manifests are not rewritten. Corrupt AOT data can only be repaired from the installed application.
+5. Load the cached AOT bundle, read and verify the four DLLs, and call the HybridCLR supplemental metadata API in the Player.
+6. Load the assembly bundle and read the DLL. In the Player, call Assembly.Load and invoke methods marked with HotPatchInitializer. Unload AOT and assembly bundles after reading their bytes.
+7. Load and retain the scene bundle, obtain the configured scene path, then asynchronously load and activate the scene through Launch without calling a game entry function.
+8. Transfer UI input before unloading Launch: prefer an existing game EventSystem, otherwise move Launch's EventSystem and input modules into the game scene. Create an input system if neither exists. Disable duplicate systems, clear selections pointing into Launch, then unload Launch so game buttons retain input.
+
+With DownloadUrl configured, the Editor follows the same download, bundle-reading, and scene-bundle loading flow. It skips native AOT APIs, duplicate Assembly.Load calls, and initialization in the local hot-update assembly. Without a URL, it previews the local scene. After the game scene is loaded and active and input is ready, Launch waits until the next frame and invokes the tagged initializer in `AppRuntimes.Sources.Editor`, then unloads Launch. This Editor-only call is excluded from Player builds and works after generated HotPatch sources have been deleted. Exiting Play Mode releases the previously retained scene bundle. Loaded DLLs are not replaced while running; restart to verify a new version.
+
+## Android / iOS validation
+
+Build resources and application packages separately for Android and iOS; Windows AOT data or bundles cannot be reused. Android APK `jar:file://...!/assets` paths and read-only iOS StreamingAssets are extracted through UnityWebRequest, then bundles are read from the writable cache. iOS application packages still require compilation and signing with macOS/Xcode.
+
+Logs use the `[HotPatch]` prefix and record manifests, cache operations, differences, download progress (at most once per second), verification, and bundle/AOT/DLL/scene loading results. URL query parameters and account credentials are omitted.
+
+```powershell
+adb logcat -v time Unity:I '*:S' | Select-String '\[HotPatch\]'
+```
+
+For the first update, check `version_compare`, `download_complete`, `aot_load_result`, `assembly_load_complete`, `scene_bundle_ready`, `scene_load_complete`, and `scene_input_ready`. Input readiness logs identify the EventSystem source, owning scene, and enabled input modules. With no update, expect `changedFiles=0` and `manifest_unchanged`. Reading bundles in tests is not equivalent to execution on an Android/iOS device.
+
+Launch startup failures use a native Android/iOS alert with the message `There is a problem with the network. Please try again later.` and one `retry` button. The Editor uses a system dialog with the same text. Launch no longer creates an on-screen retry button or exposes exception details in its status text. Confirmation retries on Unity's main thread after the previous attempt finishes. Canceled startup does not display an error. Detailed failures and `retry_dialog_open` / `retry_dialog_confirmed` remain in the logs. The loader still rejects retries after an irreversible assembly/initialization failure; those failures require restarting the application.
+
+The retry-only iOS dialog adds an AOT native entry point. Rebuild resources and the application package before device testing this change.
+
+Launch belongs to the host assembly in the installed application. Changes to scene transitions or input transfer require rebuilding original resources (or using 一键打包资源) and the application package; updating only the hot DLL is insufficient.
+
+## Sources and initialization
+
+`Runtime/Sources` retains `.cs` files in an Editor-only assembly. Each file requires the following outer wrapper. Synchronizing into the target assembly's `HotPatch` directory removes only this wrapper and preserves inner platform directives.
+
+```csharp
+#if UNITY_EDITOR
+public class ExampleRuntime { }
+#endif
+```
+
+Generated file ownership and hashes are recorded in `ProjectSettings/HotPatchSources.json`. Normal synchronization and update builds write only changed templates, remove generated files whose templates were deleted, and reject overwriting manually edited generated files. After checking Generate/All, original builds delete the entire current target HotPatch directory, including manual files, subdirectories, and `.meta` files, without recreating it during that build. The next update build copies Sources again. Other files in the assembly directory are preserved.
+
+In the Player, the loader scans only the selected DLL for `[HotPatch.HotPatchInitializer]` methods and invokes them in Order, type-name, and method-name order. In the Editor, Launch scans only `AppRuntimes.Sources.Editor` after loading the game scene. Entries must be parameterless, non-generic, non-async static void methods. `AppRuntimes.Initialization()` is marked and retains its background CheckVersion behavior; the game does not need to initialize the SDK again. The package Sources assembly and Launch's Editor initialization call are not compiled into the installed Player; the copied Sources still initialize through the downloaded hot-update DLL.
+
+```csharp
+[HotPatch.HotPatchInitializer]
+public static void Initialization() { }
+```
+
+`AppRuntimes.Base/NativeApi.cs` contains only AppInfo, TimeZone, and Dialog. Facebook dynamic configuration uses `FacebookNativeBridge` in the same AOT assembly; IAP and UniWebView use their own native declarations. P/Invoke is not allowed in hot-update DLLs. AOT native interface changes must ship in a new application package.
+
+## Official references
+
+- [HybridCLR quick start](https://www.hybridclr.cn/docs/beginner/quickstart)
+- [HybridCLR GitHub repository](https://github.com/focus-creative-games/hybridclr)
+- [AOT generics and metadata optimization](https://www.hybridclr.cn/docs/basic/aotgeneric)
+- [Build workflow and iOS](https://www.hybridclr.cn/docs/basic/buildpipeline)

+ 17 - 23
Documentation~/OriginalUsage.md

@@ -1,34 +1,28 @@
-## 1. 设置FacebookID
-- 点击 Unity 顶部 AppSettings → Open Settings 菜单。
-- 填写 Facebook AppName
-	Facebook AppID 
-	Client Token
-	AppAddress、
-	AppChannel
-	PrivacyUrl,
-- 点击Save 保存
+## 1. Configure Facebook
 
 
+- Open AppSettings > Open Settings from the Unity menu.
+- Enter Facebook AppName, Facebook AppID, Client Token, AppAddress, AppChannel, and PrivacyUrl.
+- Click Save.
 
 
+## 2. Usage
+
+At startup, CheckVersion determines whether to open the native game or the web view.
 
 
-## 2.使用
-APP启动时根据CheckVersion方法决定打开A面还是B面
-- 初始化
 ```csharp
 ```csharp
-/// 初始化
 AppRuntimes.Initialization();
 AppRuntimes.Initialization();
 
 
-/// 游戏启动脚本 
 if (!await AppRuntimes.CheckVersion()) {
 if (!await AppRuntimes.CheckVersion()) {
-	/// 继续A面流程
-}else{
-	/// 停止A面流程, 关闭BGM!!!!
-	/// 记得要关闭BGM!!!!
+    // Continue the native game flow.
+} else {
+    // Stop the native game flow and turn off background music.
 }
 }
 ```
 ```
 
 
-## 3. 设置测试URL
-在Xcode工程的Info.plist中设置键 `TestUserID`,值为测试 URL。
+## 3. Configure a test URL
+
+Set the `TestUserID` key in the Xcode project's Info.plist to the test URL.
+
+## 4. Review switch
 
 
-## 4.审核开关
-- 开启审核开关:隐私协议[AppRuntimes.PrivacyUrl]包含"Email: [" 字符串
-- 过审后更新隐私协议内容 去掉"Email: ["字符串
+- Enable the review switch by including the string `Email: [` in the privacy policy at `AppRuntimes.PrivacyUrl`.
+- After review, update the privacy policy to remove the `Email: [` string.

+ 15 - 0
Documentation~/S3Upload.md

@@ -0,0 +1,15 @@
+# S3 resource upload
+
+After completing 一键打包资源, open AppSettings and click **上传资源**, then choose a folder. The folder picker starts in the latest complete AllRes directory matching the saved assembly, game scene, and current platform. Without such a directory, the upload button is disabled. DownloadUrl and S3 configuration are validated before opening the picker. The uploader sends the selected folder's contents recursively, preserving relative paths and empty folders. The selected folder's own name is not added to the destination.
+
+The destination prefix is the final directory in the current DownloadUrl field. Both `https://cdn.example.com/hexa_crazy/` and `https://cdn.example.com/hexa_crazy/manifest_hot.json` upload to `s3://ios-games/hexa_crazy/`. A nested URL ending in `/games/hexa_crazy/` also uses only `hexa_crazy/`. A domain root without a directory is rejected.
+
+This company-internal package stores S3 settings in `Editor/Config/S3UploadSettings.json`. Edit its `Bucket`, `Region`, `AccessKey`, `SecretKey` and optional `SessionToken` fields in the package source. The current destination is bucket `ios-games`, Region `us-east-1`. AppSettings no longer exposes a S3 configuration form, and uploads no longer read EditorPrefs or `~/.aws/credentials`. The configuration ships with the internal package under Editor; it is not copied to Assets/Resources, StreamingAssets or Player assemblies.
+
+Uploads use HTTPS directly to the regional S3 endpoint with AWS Signature Version 4 and signed payload hashes. No AWS CLI or SDK installation is required. The uploader streams files, shows progress, supports cancellation and retries temporary network/server failures. Files larger than 5 GiB and symbolic links are rejected during preflight. Existing objects with the same key are replaced; unrelated objects are not deleted. Bucket ACLs and CloudFront settings are not changed.
+
+All resource files are uploaded before `manifest.json` and `manifest_hot.json`. A failed or canceled resource upload stops before publishing the manifests. Uploading an AllRes folder preserves both manifest names. After review, replace the remote `manifest.json` with `manifest_hot.json`, then refresh the S3/CDN cache to publish the update through the existing DownloadUrl. No manifests are renamed automatically. For explicit testing, DownloadUrl may also point directly at `manifest_hot.json`.
+
+Manifests are uploaded with `Cache-Control: no-cache, max-age=0, must-revalidate`. CloudFront policies can override origin cache directives; this feature does not create CloudFront invalidations. Interrupted uploads can be restarted by selecting the same folder again.
+
+References: [AWS shared credentials](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html), [S3 Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sig-v4-header-based-auth.html).

+ 1 - 1
Editor/AppHelpLinkerProcessor.cs

@@ -10,7 +10,7 @@ internal sealed class AppHelpLinkerProcessor : IUnityLinkerProcessor
 
 
     public string GenerateAdditionalLinkXmlFile(BuildReport report, UnityLinkerBuildPipelineData data)
     public string GenerateAdditionalLinkXmlFile(BuildReport report, UnityLinkerBuildPipelineData data)
     {
     {
-        // Unity does not automatically consume link.xml assets inside UPM packages.
+
         var linker = new XElement("linker");
         var linker = new XElement("linker");
         foreach (string relative in new[] { "ThirdParty/FacebookSDK/link.xml", "ThirdParty/UniWebView/link.xml" })
         foreach (string relative in new[] { "ThirdParty/FacebookSDK/link.xml", "ThirdParty/UniWebView/link.xml" })
         {
         {

+ 2 - 1
Editor/AppHelpPackagePaths.cs

@@ -4,9 +4,10 @@ using UnityEditor.PackageManager;
 
 
 internal static class AppHelpPackagePaths
 internal static class AppHelpPackagePaths
 {
 {
-    private static PackageInfo Package => PackageInfo.FindForAssembly(typeof(AppRuntimes).Assembly)
+    private static PackageInfo Package => PackageInfo.FindForAssembly(typeof(AppSettings).Assembly)
         ?? throw new InvalidOperationException("AppRuntimes must be installed through Package Manager.");
         ?? throw new InvalidOperationException("AppRuntimes must be installed through Package Manager.");
 
 
+    internal static string Name => Package.name;
     internal static string FullPath(string relativePath) => Path.Combine(Package.resolvedPath, relativePath);
     internal static string FullPath(string relativePath) => Path.Combine(Package.resolvedPath, relativePath);
     internal static string AssetPath(string relativePath) => Package.assetPath + "/" + relativePath;
     internal static string AssetPath(string relativePath) => Package.assetPath + "/" + relativePath;
 }
 }

+ 4 - 4
Editor/AppHelpProjectSettings.cs

@@ -3,7 +3,7 @@ using System.IO;
 using UnityEditor;
 using UnityEditor;
 using UnityEngine;
 using UnityEngine;
 
 
-// Each consuming project owns its configuration; the package is safe to update.
+
 internal static class AppHelpProjectSettings
 internal static class AppHelpProjectSettings
 {
 {
     private const string DirectoryPath = "Assets/Resources";
     private const string DirectoryPath = "Assets/Resources";
@@ -37,7 +37,7 @@ internal static class AppHelpProjectSettings
     private static T CopyDefault<T>(string fileName) where T : ScriptableObject
     private static T CopyDefault<T>(string fileName) where T : ScriptableObject
     {
     {
         string destination = DirectoryPath + "/" + fileName;
         string destination = DirectoryPath + "/" + fileName;
-        // Never replace an existing file, including one Unity cannot deserialize.
+
         if (File.Exists(destination))
         if (File.Exists(destination))
             throw new InvalidOperationException("AppRuntimes settings exist but could not be loaded: " + destination);
             throw new InvalidOperationException("AppRuntimes settings exist but could not be loaded: " + destination);
 
 
@@ -47,7 +47,7 @@ internal static class AppHelpProjectSettings
 
 
         if (!AssetDatabase.IsValidFolder(DirectoryPath))
         if (!AssetDatabase.IsValidFolder(DirectoryPath))
             AssetDatabase.CreateFolder("Assets", "Resources");
             AssetDatabase.CreateFolder("Assets", "Resources");
-        // CopyAsset assigns a new GUID so the project and package remain independent.
+
         if (!AssetDatabase.CopyAsset(template, destination))
         if (!AssetDatabase.CopyAsset(template, destination))
             throw new IOException("Could not copy AppRuntimes default settings to " + destination);
             throw new IOException("Could not copy AppRuntimes default settings to " + destination);
         return AssetDatabase.LoadAssetAtPath<T>(destination)
         return AssetDatabase.LoadAssetAtPath<T>(destination)
@@ -55,7 +55,7 @@ internal static class AppHelpProjectSettings
     }
     }
 }
 }
 
 
-// Run after startup/domain-reload imports, when loading and copying assets is safe.
+
 internal sealed class AppHelpSettingsInitializer : AssetPostprocessor
 internal sealed class AppHelpSettingsInitializer : AssetPostprocessor
 {
 {
     private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets,
     private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets,

+ 1 - 1
Editor/AppHelpStreamingAssetsProcessor.cs

@@ -3,7 +3,7 @@ using System.IO;
 using UnityEditor.Build;
 using UnityEditor.Build;
 using UnityEngine;
 using UnityEngine;
 
 
-// Register raw package files without copying them into the consuming project's Assets.
+
 public sealed class AppHelpStreamingAssetsProcessor : BuildPlayerProcessor
 public sealed class AppHelpStreamingAssetsProcessor : BuildPlayerProcessor
 {
 {
     public override void PrepareForBuild(BuildPlayerContext buildPlayerContext)
     public override void PrepareForBuild(BuildPlayerContext buildPlayerContext)

+ 20 - 14
Editor/AppRuntimes.Editor.asmdef

@@ -1,16 +1,22 @@
 {
 {
-    "name": "AppRuntimes.Editor",
-    "rootNamespace": "",
-    "references": ["AppRuntimes", "UniWebView-CSharp.Editor"],
-    "includePlatforms": [
-        "Editor"
-    ],
-    "excludePlatforms": [],
-    "allowUnsafeCode": false,
-    "overrideReferences": false,
-    "precompiledReferences": [],
-    "autoReferenced": true,
-    "defineConstraints": [],
-    "versionDefines": [],
-    "noEngineReferences": false
+  "name": "AppRuntimes.Editor",
+  "rootNamespace": "",
+  "references": [
+    "AppRuntimes",
+    "AppRuntimes.PackageSetup.Editor",
+    "UniWebView-CSharp.Editor",
+    "AppRuntimes.Base",
+    "AppRuntimes.Sources.Editor"
+  ],
+  "includePlatforms": [
+    "Editor"
+  ],
+  "excludePlatforms": [],
+  "allowUnsafeCode": false,
+  "overrideReferences": false,
+  "precompiledReferences": [],
+  "autoReferenced": true,
+  "defineConstraints": [],
+  "versionDefines": [],
+  "noEngineReferences": false
 }
 }

+ 107 - 46
Editor/AppSettingsWindow.cs

@@ -1,6 +1,7 @@
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using UnityEditor;
 using UnityEditor;
+using UnityEditorInternal;
 using UnityEngine;
 using UnityEngine;
 
 
 public sealed class AppSettingsWindow : EditorWindow
 public sealed class AppSettingsWindow : EditorWindow
@@ -9,35 +10,17 @@ public sealed class AppSettingsWindow : EditorWindow
     private SerializedObject facebook;
     private SerializedObject facebook;
     private int appIndex;
     private int appIndex;
     private string appName, appId, clientToken;
     private string appName, appId, clientToken;
-    private string appAddress, appChannel, privacyUrl;
+    private string appAddress, appChannel, privacyUrl, downloadUrl, gameSceneName;
+    private AssemblyDefinitionAsset hotPatchAssembly;
     private string addressError;
     private string addressError;
     private Vector2 scrollPosition;
     private Vector2 scrollPosition;
     private bool showTestUrlHelp = false;
     private bool showTestUrlHelp = false;
-    private bool showUsageHelp = false;
+    private bool showUsageHelp = true;
 
 
     private const string TestUrlExample = @"<key>TestUserID</key>
     private const string TestUrlExample = @"<key>TestUserID</key>
 <string>https://example.com/test/</string>";
 <string>https://example.com/test/</string>";
 
 
-    private const string UsageExample = @"using UnityEngine;
-
-public class AppStartup : MonoBehaviour
-{
-    private async void Start()
-    {
-        AppRuntimes.Initialization();
-
-        if (await AppRuntimes.CheckVersion())
-        {
-            // 已打开平台页面,停止游戏背景音乐。
-            // 在这里调用项目的 BGM 停止方法。
-            return;
-        }
-
-        // 未打开平台页面,继续游戏主流程。
-    }
-}";
-
-    [MenuItem("AppSettings/Open Settings")]
+    [MenuItem("AppSettings/Open Settings", false, 0)]
     public static void Open()
     public static void Open()
     {
     {
         var window = GetWindow<AppSettingsWindow>("AppSettings");
         var window = GetWindow<AppSettingsWindow>("AppSettings");
@@ -46,7 +29,11 @@ public class AppStartup : MonoBehaviour
         window.Show();
         window.Show();
     }
     }
 
 
-    private void OnEnable() => LoadSettings();
+    private void OnEnable()
+    {
+        showUsageHelp = true;
+        LoadSettings();
+    }
 
 
     private void LoadSettings()
     private void LoadSettings()
     {
     {
@@ -60,12 +47,15 @@ public class AppStartup : MonoBehaviour
         catch (Exception)
         catch (Exception)
         {
         {
             appAddress = string.Empty;
             appAddress = string.Empty;
-            addressError = "AppAddress 解密失败,请重新填写明文地址后保存。";
+            addressError = "Failed to decrypt AppAddress. Enter the plain-text address again and save.";
         }
         }
         appChannel = settings.AppChannel;
         appChannel = settings.AppChannel;
         privacyUrl = settings.PrivacyUrl;
         privacyUrl = settings.PrivacyUrl;
+        downloadUrl = settings.DownloadUrl;
+        gameSceneName = settings.GameSceneName;
+        hotPatchAssembly = HotPatchAssemblySelection.Find(settings.HotPatchAssemblyName);
 
 
-        // Read the SDK's active application, preserving other configured apps.
+                                                                               
         var facebookAsset = AppHelpProjectSettings.LoadOrCreateFacebookSettings();
         var facebookAsset = AppHelpProjectSettings.LoadOrCreateFacebookSettings();
         facebook = facebookAsset != null ? new SerializedObject(facebookAsset) : null;
         facebook = facebookAsset != null ? new SerializedObject(facebookAsset) : null;
         appName = appId = clientToken = string.Empty;
         appName = appId = clientToken = string.Empty;
@@ -105,6 +95,7 @@ public class AppStartup : MonoBehaviour
     private void DrawWindow()
     private void DrawWindow()
     {
     {
         scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
         scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
+        DrawHybridCLRSetup();
         EditorGUILayout.LabelField("Facebook", EditorStyles.boldLabel);
         EditorGUILayout.LabelField("Facebook", EditorStyles.boldLabel);
         if (facebook == null)
         if (facebook == null)
             EditorGUILayout.HelpBox("FacebookSettings.asset was not found in Resources.", MessageType.Error);
             EditorGUILayout.HelpBox("FacebookSettings.asset was not found in Resources.", MessageType.Error);
@@ -117,23 +108,83 @@ public class AppStartup : MonoBehaviour
         EditorGUILayout.Space();
         EditorGUILayout.Space();
         EditorGUILayout.LabelField("App", EditorStyles.boldLabel);
         EditorGUILayout.LabelField("App", EditorStyles.boldLabel);
         EditorGUI.BeginChangeCheck();
         EditorGUI.BeginChangeCheck();
-        appAddress = EditorGUILayout.TextField(new GUIContent("AppAddress", "填写明文地址,保存时自动加密。"), appAddress);
+        appAddress = EditorGUILayout.TextField(new GUIContent("AppAddress", "Enter a plain-text address. It is encrypted when saved."), appAddress);
         if (EditorGUI.EndChangeCheck()) addressError = null;
         if (EditorGUI.EndChangeCheck()) addressError = null;
         if (!string.IsNullOrEmpty(addressError))
         if (!string.IsNullOrEmpty(addressError))
             EditorGUILayout.HelpBox(addressError, MessageType.Error);
             EditorGUILayout.HelpBox(addressError, MessageType.Error);
         appChannel = EditorGUILayout.TextField("AppChannel", appChannel);
         appChannel = EditorGUILayout.TextField("AppChannel", appChannel);
         privacyUrl = EditorGUILayout.TextField("PrivacyUrl", privacyUrl);
         privacyUrl = EditorGUILayout.TextField("PrivacyUrl", privacyUrl);
+        downloadUrl = EditorGUILayout.TextField(new GUIContent("Hot Patch DownloadUrl", "HTTP(S) resource directory or full manifest.json URL. Use 资源构建/一键打包资源 to export the DLL and manifest."), downloadUrl);
+        hotPatchAssembly = (AssemblyDefinitionAsset)EditorGUILayout.ObjectField(
+            new GUIContent("Hot Patch Assembly", "Select the game runtime asmdef. Save adds the required AppRuntimes.Base and Unity.Advertisement.IosSupport references and synchronizes HybridCLR settings."),
+            hotPatchAssembly, typeof(AssemblyDefinitionAsset), false);
+        EditorGUILayout.LabelField("Saved Assembly", settings.HotPatchAssemblyName);
+        gameSceneName = EditorGUILayout.TextField(new GUIContent("Game Scene Name", "Enter a unique scene name without .unity. It is used to build the scene bundle, which Launch opens at runtime."), gameSceneName);
         EditorGUILayout.Space();
         EditorGUILayout.Space();
         using (new EditorGUILayout.HorizontalScope())
         using (new EditorGUILayout.HorizontalScope())
         {
         {
             if (GUILayout.Button("Reload")) LoadSettings();
             if (GUILayout.Button("Reload")) LoadSettings();
             if (GUILayout.Button("Save")) SaveSettings();
             if (GUILayout.Button("Save")) SaveSettings();
+            using (new EditorGUI.DisabledScope(!CanBuildResources))
+                if (GUILayout.Button("一键打包资源")) EditorApplication.ExecuteMenuItem("资源构建/一键打包资源");
+        }
+        var buildBlockReason = HotPatchAssemblySelection.BuildBlockReason(settings, hotPatchAssembly, gameSceneName);
+        if (buildBlockReason != null) EditorGUILayout.HelpBox(buildBlockReason, MessageType.Info);
+        using (new EditorGUI.DisabledScope(S3UploadController.IsUploading || HotPatchResourceActions.IsBuilding || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
+        {
+            var latest = HotPatchResourceActions.LatestDirectory;
+            using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(latest)))
+            {
+                using (new EditorGUILayout.HorizontalScope())
+                {
+                    if (GUILayout.Button("使用本地资源测试")) ApplyResourceMode(true);
+                    if (GUILayout.Button("恢复正式资源")) ApplyResourceMode(false);
+                }
+                if (GUILayout.Button("上传资源")) S3UploadController.ChooseAndUpload(downloadUrl);
+            }
+            EditorGUILayout.LabelField("启动资源模式", settings.UseLocalHotPatchResources ? "本地资源测试(跳过远程热更新)" : "正式资源(检查远程更新)");
+            if (string.IsNullOrEmpty(latest))
+                EditorGUILayout.HelpBox("没有当前平台、程序集和场景对应的完整打包资源,请先 Save,再执行一键打包资源。", MessageType.Info);
+            else EditorGUILayout.LabelField("最近打包资源", System.IO.Path.GetFileName(latest));
+            try { EditorGUILayout.LabelField("上传目标", "s3://" + S3UploadSettings.Bucket + "/" + S3ResourceUploader.TargetPrefix(downloadUrl) + "/"); }
+            catch (ArgumentException) { EditorGUILayout.LabelField("上传目标", "请设置包含目录的 DownloadUrl"); }
+            catch (Exception exception) { EditorGUILayout.HelpBox(exception.Message, MessageType.Error); }
         }
         }
         DrawUsageHelp();
         DrawUsageHelp();
         EditorGUILayout.EndScrollView();
         EditorGUILayout.EndScrollView();
     }
     }
 
 
-    // Restore shared editor styles after drawing this window.
+    private bool CanBuildResources => HotPatchAssemblySelection.BuildBlockReason(settings, hotPatchAssembly, gameSceneName) == null
+        && !S3UploadController.IsUploading && !HotPatchResourceActions.IsBuilding && !EditorApplication.isCompiling
+        && !EditorApplication.isUpdating && !EditorApplication.isPlayingOrWillChangePlaymode && !BuildPipeline.isBuildingPlayer;
+
+    private void ApplyResourceMode(bool localTesting)
+    {
+        try
+        {
+            HotPatchResourceActions.ApplyResources(localTesting);
+            ShowNotification(new GUIContent(localTesting ? "已切换为本地资源测试" : "已恢复正式资源"));
+        }
+        catch (Exception exception)
+        {
+            Debug.LogException(exception);
+            EditorUtility.DisplayDialog("切换资源失败", exception.Message, "确定");
+        }
+    }
+
+    private void DrawHybridCLRSetup()
+    {
+        if (HybridCLRPackageSetup.IsInstalled) return;
+        var installing = HybridCLRPackageSetup.IsInstalling;
+        var message = installing ? "Installing the HybridCLR package. Wait for installation and compilation to finish." :
+            "The HybridCLR package is required. Retry installation or add the following Git URL in Package Manager:\n" + HybridCLRPackageSetup.PackageUrl;
+        if (!string.IsNullOrEmpty(HybridCLRPackageSetup.LastError)) message += "\n" + HybridCLRPackageSetup.LastError;
+        EditorGUILayout.HelpBox(message, installing ? MessageType.Info : MessageType.Warning);
+        using (new EditorGUI.DisabledScope(installing || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
+            if (GUILayout.Button("Retry HybridCLR Installation")) HybridCLRPackageSetup.RetryInstallation();
+        if (installing) Repaint();
+    }
+
     private sealed class FontSizeScope : IDisposable
     private sealed class FontSizeScope : IDisposable
     {
     {
         private readonly Dictionary<GUIStyle, int> originalSizes = new Dictionary<GUIStyle, int>();
         private readonly Dictionary<GUIStyle, int> originalSizes = new Dictionary<GUIStyle, int>();
@@ -166,34 +217,29 @@ public class AppStartup : MonoBehaviour
     private void DrawUsageHelp()
     private void DrawUsageHelp()
     {
     {
         EditorGUILayout.Space(12);
         EditorGUILayout.Space(12);
-        showTestUrlHelp = EditorGUILayout.Foldout(showTestUrlHelp, "添加测试 URL(iOS)", true);
+        showTestUrlHelp = EditorGUILayout.Foldout(showTestUrlHelp, "Test URL Setup (iOS)", true);
         if (showTestUrlHelp)
         if (showTestUrlHelp)
         {
         {
             EditorGUILayout.HelpBox(
             EditorGUILayout.HelpBox(
-                "导出 iOS 工程后,在 Xcode 的主 App Target → Info 中添加 TestUserID,类型选 String," +
-                "值填写完整测试 URL(例如 https://example.com/test/)。\n" +
-                "也可以直接在 Info.plist 的根 <dict> 内加入以下内容。",
+                "After exporting the iOS project, add TestUserID under the main App Target > Info in Xcode. Set its type to String and" +
+                " its value to the complete test URL (for example, https://example.com/test/).\n" +
+                "Alternatively, add the following entries directly inside the root <dict> in Info.plist.",
                 MessageType.Info);
                 MessageType.Info);
-            DrawExample(TestUrlExample, "复制 Info.plist 示例");
+            DrawExample(TestUrlExample, "Copy Info.plist Example");
             EditorGUILayout.HelpBox(
             EditorGUILayout.HelpBox(
-                "iOS 启动时读取 TestUserID;非空时直接使用该测试地址。修改后需重新构建并启动 App。\n" +
-                "删除该键或清空值可恢复正常流程。Android 和 Unity Editor 的 TestUrl 始终为空。",
+                "iOS reads TestUserID at startup and uses the test URL if it is not empty. Rebuild and launch the app after changing it.\n" +
+                "Remove the key or clear its value to restore the normal flow. TestUrl is always empty on Android and in the Unity Editor.",
                 MessageType.None);
                 MessageType.None);
         }
         }
 
 
         EditorGUILayout.Space(8);
         EditorGUILayout.Space(8);
-        showUsageHelp = EditorGUILayout.Foldout(showUsageHelp, "AppRuntimes 使用方法", true);
+        showUsageHelp = EditorGUILayout.Foldout(showUsageHelp, "使用注意事项", true);
         if (showUsageHelp)
         if (showUsageHelp)
         {
         {
             EditorGUILayout.HelpBox(
             EditorGUILayout.HelpBox(
-                "1. 填写上方配置并点击 Save。AppAddress 填明文,保存时自动加密。\n" +
-                "2. 在App的启动脚本时 先调用 Initialization(),再等待 CheckVersion():返回 true 表示已打开平台页面," +
-                "应停止游戏背景音乐;返回 false 时继续游戏主流程。",
-                MessageType.Info);
-            DrawExample(UsageExample, string.Empty);
-            EditorGUILayout.HelpBox(
-                "AppRuntimes.Log 在编辑器中始终输出。iOS 在 Info.plist 中添加 Boolean 类型的 EnableUnityLog," +
-                "设为 YES 时输出日志;未设置时默认为 NO。其他平台默认关闭。",
+                "1. 订阅 AppRuntimesEvents.OnPlatformOpen 事件,在回调中停止播放单机游戏的背景音乐。打开 WebView 时会触发该事件。\n\n" +
+                "2. 操作步骤:Save >>> 一键打包资源 >>> 上传资源\n\n" +
+                "3. 审核后热更,把 manifest_hot.json 替换成 manifest.json,然后刷新 S3 缓存。",
                 MessageType.Info);
                 MessageType.Info);
         }
         }
     }
     }
@@ -206,13 +252,18 @@ public class AppStartup : MonoBehaviour
         if (!string.IsNullOrEmpty(copyLabel) && GUILayout.Button(copyLabel))
         if (!string.IsNullOrEmpty(copyLabel) && GUILayout.Button(copyLabel))
         {
         {
             EditorGUIUtility.systemCopyBuffer = example;
             EditorGUIUtility.systemCopyBuffer = example;
-            ShowNotification(new GUIContent("示例已复制"));
+            ShowNotification(new GUIContent("Example copied"));
         }
         }
     }
     }
 
 
     private void SaveSettings()
     private void SaveSettings()
     {
     {
-        // Do not overwrite an unreadable address when saving unrelated settings.
+        if (!string.IsNullOrWhiteSpace(downloadUrl) && (!Uri.TryCreate(downloadUrl.Trim(), UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")))
+        {
+            ShowNotification(new GUIContent("The hot patch URL must be an absolute HTTP(S) URL"));
+            return;
+        }
+                                                                                 
         if (!string.IsNullOrEmpty(addressError)) return;
         if (!string.IsNullOrEmpty(addressError)) return;
         string encryptedAddress;
         string encryptedAddress;
         try
         try
@@ -222,13 +273,22 @@ public class AppStartup : MonoBehaviour
         }
         }
         catch (Exception)
         catch (Exception)
         {
         {
-            addressError = "AppAddress 加密失败,配置未保存,请重新填写后重试。";
+            addressError = "Failed to encrypt AppAddress. Settings were not saved. Enter the address again and retry.";
+            return;
+        }
+        try { HotPatchAssemblySelection.Save(settings, hotPatchAssembly); }
+        catch (Exception exception)
+        {
+            ShowNotification(new GUIContent(exception.Message));
+            Debug.LogError("[HotPatch] Settings were not saved: " + exception.Message);
             return;
             return;
         }
         }
         Undo.RecordObject(settings, "Save AppSettings");
         Undo.RecordObject(settings, "Save AppSettings");
         settings.AppAddress = encryptedAddress;
         settings.AppAddress = encryptedAddress;
         settings.AppChannel = appChannel;
         settings.AppChannel = appChannel;
         settings.PrivacyUrl = privacyUrl;
         settings.PrivacyUrl = privacyUrl;
+        settings.DownloadUrl = (downloadUrl ?? string.Empty).Trim();
+        settings.GameSceneName = (gameSceneName ?? string.Empty).Trim();
         EditorUtility.SetDirty(settings);
         EditorUtility.SetDirty(settings);
         if (facebook != null)
         if (facebook != null)
         {
         {
@@ -240,6 +300,7 @@ public class AppStartup : MonoBehaviour
             EditorUtility.SetDirty(facebook.targetObject);
             EditorUtility.SetDirty(facebook.targetObject);
         }
         }
         AssetDatabase.SaveAssets();
         AssetDatabase.SaveAssets();
+        Repaint();
         ShowNotification(new GUIContent("Settings saved"));
         ShowNotification(new GUIContent("Settings saved"));
     }
     }
 }
 }

+ 1 - 1
ThirdParty/GUPS.meta → Editor/Config.meta

@@ -1,5 +1,5 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: a43971d660d815844abc0d72ff8bdb35
+guid: bade89f0ac3443f89b9c10e8f570d1db
 folderAsset: yes
 folderAsset: yes
 DefaultImporter:
 DefaultImporter:
   externalObjects: {}
   externalObjects: {}

+ 7 - 0
Editor/Config/S3UploadSettings.json

@@ -0,0 +1,7 @@
+{
+  "Bucket": "ios-games",
+  "Region": "us-east-1",
+  "AccessKey": "AKIAZCRCMMNMXDQGXI6W",
+  "SecretKey": "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",
+  "SessionToken": ""
+}

+ 1 - 1
ThirdParty/GUPS/Obfuscator/Editor/Plugins/GUPS.Obfuscator.Editor.xml.meta → Editor/Config/S3UploadSettings.json.meta

@@ -1,5 +1,5 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: d61efaa83aac78d43a5a461c6d171ef0
+guid: 877fcfef9fda4774a5b813e0082c8809
 TextScriptImporter:
 TextScriptImporter:
   externalObjects: {}
   externalObjects: {}
   userData: 
   userData: 

+ 104 - 0
Editor/CryptoTools.cs

@@ -0,0 +1,104 @@
+using System;
+using UnityEngine;
+using UnityEditor;
+
+public class CryptoTools : EditorWindow
+{
+    private string input = string.Empty;
+    private string output = string.Empty;
+    private string errorMessage = string.Empty;
+    private Vector2 inputScrollPosition;
+    private Vector2 outputScrollPosition;
+
+    [MenuItem("Tools/Crypto Tools")]
+    private static void OpenWindow()
+    {
+        var window = GetWindow<CryptoTools>("Crypto Tools");
+        window.minSize = new Vector2(520f, 420f);
+        window.Show();
+    }
+
+    private void OnGUI()
+    {
+        EditorGUILayout.Space(8f);
+        EditorGUILayout.LabelField("ClientCrypto String Encryption / Decryption", EditorStyles.boldLabel);
+        EditorGUILayout.Space(4f);
+
+        EditorGUILayout.LabelField("Input");
+        inputScrollPosition = EditorGUILayout.BeginScrollView(
+            inputScrollPosition,
+            GUILayout.MinHeight(120f));
+        input = EditorGUILayout.TextArea(input, GUILayout.ExpandHeight(true));
+        EditorGUILayout.EndScrollView();
+
+        EditorGUILayout.Space(6f);
+        using (new EditorGUILayout.HorizontalScope())
+        {
+            if (GUILayout.Button("Encrypt", GUILayout.Height(30f)))
+            {
+                TransformInput(ClientCrypto.EncryptString);
+            }
+
+            if (GUILayout.Button("Decrypt", GUILayout.Height(30f)))
+            {
+                TransformInput(ClientCrypto.DecryptString);
+            }
+
+            if (GUILayout.Button("Clear", GUILayout.Width(80f), GUILayout.Height(30f)))
+            {
+                input = string.Empty;
+                output = string.Empty;
+                errorMessage = string.Empty;
+                GUI.FocusControl(null);
+            }
+        }
+
+        if (!string.IsNullOrEmpty(errorMessage))
+        {
+            EditorGUILayout.Space(6f);
+            EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
+        }
+
+        EditorGUILayout.Space(8f);
+        EditorGUILayout.LabelField("Output");
+        outputScrollPosition = EditorGUILayout.BeginScrollView(
+            outputScrollPosition,
+            GUILayout.MinHeight(120f));
+        output = EditorGUILayout.TextArea(output, GUILayout.ExpandHeight(true));
+        EditorGUILayout.EndScrollView();
+
+        using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(output)))
+        {
+            using (new EditorGUILayout.HorizontalScope())
+            {
+                if (GUILayout.Button("Copy Output"))
+                {
+                    EditorGUIUtility.systemCopyBuffer = output;
+                    ShowNotification(new GUIContent("Copied"));
+                }
+
+                if (GUILayout.Button("Use Output as Input"))
+                {
+                    input = output;
+                    errorMessage = string.Empty;
+                }
+            }
+        }
+    }
+
+    private void TransformInput(Func<string, string> transform)
+    {
+        try
+        {
+            output = transform(input);
+            errorMessage = string.Empty;
+            GUI.FocusControl(null);
+        }
+        catch (Exception exception)
+        {
+            output = string.Empty;
+            errorMessage = exception.Message;
+        }
+    }
+
+}

+ 1 - 4
Runtime/Scripts/AppRuntimes.cs.meta → Editor/CryptoTools.cs.meta

@@ -1,11 +1,8 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: 1ec37ec645895e742853d78a54dc8817
+guid: d95abae76825439da1db726df136a67c
 MonoImporter:
 MonoImporter:
   externalObjects: {}
   externalObjects: {}
   serializedVersion: 2
   serializedVersion: 2
   defaultReferences: []
   defaultReferences: []
   executionOrder: 0
   executionOrder: 0
   icon: {instanceID: 0}
   icon: {instanceID: 0}
-  userData: 
-  assetBundleName: 
-  assetBundleVariant: 

+ 1 - 0
Editor/DefaultSettings/AppSettings.asset

@@ -15,3 +15,4 @@ MonoBehaviour:
   AppAddress: v2:o4Kxs_mbR8QWdUuPxWmJbHnGzRX4rzVvefI1m6sBcw0-5DgmyWmWcendMvfJY3ec
   AppAddress: v2:o4Kxs_mbR8QWdUuPxWmJbHnGzRX4rzVvefI1m6sBcw0-5DgmyWmWcendMvfJY3ec
   AppChannel: 111
   AppChannel: 111
   PrivacyUrl: https://raw.githubusercontent.com/Bx-Baxy/SUPER_BUFFALO/refs/heads/main/Privacy.md
   PrivacyUrl: https://raw.githubusercontent.com/Bx-Baxy/SUPER_BUFFALO/refs/heads/main/Privacy.md
+  DownloadUrl:

+ 26 - 26
Editor/DisableBitcode.cs

@@ -1,22 +1,22 @@
-/**
- * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
- *
- * You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
- * copy, modify, and distribute this software in source code or binary form for use
- * in connection with the web services and APIs provided by Facebook.
- *
- * As with any software that integrates with the Facebook platform, your use of
- * this software is subject to the Facebook Developer Principles and Policies
- * [http://developers.facebook.com/policy/]. This copyright notice shall be
- * included in all copies or substantial portions of the software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
- * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
+   
+                                                                  
+  
+                                                                                  
+                                                                                   
+                                                                     
+  
+                                                                               
+                                                                             
+                                                                           
+                                                                  
+  
+                                                                             
+                                                                                   
+                                                                                 
+                                                                                 
+                                                                          
+                                                                             
+   
 
 
 using System.IO;
 using System.IO;
 using UnityEngine;
 using UnityEngine;
@@ -30,9 +30,9 @@ using UnityEditor.Callbacks;
 
 
 namespace Facebook.Unity.PostProcess
 namespace Facebook.Unity.PostProcess
 {
 {
-    /// <summary>
-    /// Automatically disables Bitcode on iOS builds
-    /// </summary>
+                 
+                                                    
+                  
     public static class DisableBitcode
     public static class DisableBitcode
     {
     {
         [PostProcessBuildAttribute(999)]
         [PostProcessBuildAttribute(999)]
@@ -44,14 +44,14 @@ namespace Facebook.Unity.PostProcess
             PBXProject pbxProject = new PBXProject();
             PBXProject pbxProject = new PBXProject();
             pbxProject.ReadFromFile(projectPath);
             pbxProject.ReadFromFile(projectPath);
 
 
-            //Disabling Bitcode on all targets
-            //Main
+                                              
+                  
             string target = pbxProject.GetUnityMainTargetGuid();
             string target = pbxProject.GetUnityMainTargetGuid();
             pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
             pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
-            //Unity Tests
+                         
             target = pbxProject.TargetGuidByName(PBXProject.GetUnityTestTargetName());
             target = pbxProject.TargetGuidByName(PBXProject.GetUnityTestTargetName());
             pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
             pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
-            //Unity Framework
+                             
             target = pbxProject.GetUnityFrameworkTargetGuid();
             target = pbxProject.GetUnityFrameworkTargetGuid();
             pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
             pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
 
 

+ 5 - 0
Editor/HotPatch.meta

@@ -0,0 +1,5 @@
+fileFormatVersion: 2
+guid: c23b64a39e2443a9b9678f8e253de4f9
+folderAsset: yes
+DefaultImporter:
+  externalObjects: {}

+ 8 - 0
Editor/HotPatch/HotPatch.Editor.asmdef

@@ -0,0 +1,8 @@
+{
+  "name": "HotPatch.Editor",
+  "references": ["AppRuntimes.Editor", "AppRuntimes.Base", "HotPatch.Runtime", "HybridCLR.Editor", "Unity.TextMeshPro", "Unity.TextMeshPro.Editor"],
+  "includePlatforms": ["Editor"],
+  "autoReferenced": false,
+  "defineConstraints": ["HOT_PATCH_HYBRIDCLR"],
+  "versionDefines": [{"name":"com.code-philosophy.hybridclr","expression":"0.0.0","define":"HOT_PATCH_HYBRIDCLR"}]
+}

+ 4 - 0
Editor/HotPatch/HotPatch.Editor.asmdef.meta

@@ -0,0 +1,4 @@
+fileFormatVersion: 2
+guid: 780d61f6cead4f8aa646bf65dc3dea6b
+AssemblyDefinitionImporter:
+  externalObjects: {}

+ 39 - 0
Editor/HotPatch/HotPatchAndroidResolverScope.cs

@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using UnityEditor;
+
+namespace HotPatch.Editor
+{
+
+    internal sealed class HotPatchAndroidResolverScope : IDisposable
+    {
+        readonly List<(PropertyInfo Property, bool Value)> previous = new List<(PropertyInfo, bool)>();
+
+        public HotPatchAndroidResolverScope()
+        {
+            if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android) return;
+            var type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType("GooglePlayServices.SettingsDialog"))
+                .FirstOrDefault(t => t != null);
+            if (type == null) return;
+            try
+            {
+                foreach (var name in new[] { "AutoResolveOnBuild", "EnableAutoResolution" })
+                {
+                    var property = type.GetProperty(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
+                    if (property == null || !property.CanRead || !property.CanWrite || property.PropertyType != typeof(bool)) continue;
+                    previous.Add((property, (bool)property.GetValue(null)));
+                    property.SetValue(null, false);
+                }
+            }
+            catch { Dispose(); throw; }
+        }
+
+        public void Dispose()
+        {
+            foreach (var item in previous) item.Property.SetValue(null, item.Value);
+            previous.Clear();
+        }
+    }
+}

+ 2 - 0
Editor/HotPatch/HotPatchAndroidResolverScope.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 021e570e3786bb44995d7dd6b6f5354b

+ 503 - 0
Editor/HotPatch/HotPatchBuild.cs

@@ -0,0 +1,503 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using HybridCLR;
+using HybridCLR.Commands;
+using HybridCLR.HotUpdate;
+using HybridCLR.Installer;
+using Newtonsoft.Json.Linq;
+using UnityEditor;
+using UnityEditor.Build;
+using UnityEditor.Build.Player;
+using UnityEditor.Compilation;
+using UnityEngine;
+
+namespace HotPatch.Editor
+{
+    [InitializeOnLoad]
+    public static class HotPatchBuild
+    {
+        const string Pending = "HotPatch.Pending";
+        const string Phase = "HotPatch.Phase";
+        const string Failed = "HotPatch.CompileFailed";
+        const string Combined = "HotPatch.Combined";
+        const string OriginalStaging = "HotPatch.OriginalStaging";
+        const string CombinedStaging = "HotPatch.CombinedStaging";
+        const string PreparedBaseline = "HotPatch.PreparedBaseline";
+        const string OutputRoot = "Build/HotUpdate";
+        const string StagingRoot = "Library/HotPatch/Staging";
+        public static string BaselinePointer => OutputRoot + "/Baselines/" + EditorUserBuildSettings.activeBuildTarget + "/current.json";
+        static bool working;
+        public static bool IsBuilding => working || !string.IsNullOrEmpty(SessionState.GetString(Pending, ""));
+
+        static HotPatchBuild()
+        {
+            CompilationPipeline.assemblyCompilationFinished += (_, messages) =>
+            {
+                if (messages.Any(m => m.type == CompilerMessageType.Error)) SessionState.SetBool(Failed, true);
+            };
+            CompilationPipeline.compilationFinished += _ =>
+            { if (!string.IsNullOrEmpty(SessionState.GetString(Pending, ""))) SessionState.SetString(Phase, "ready"); };
+            EditorApplication.update += ContinueAfterCompile;
+        }
+
+        public static void BuildOriginal() => Begin("original");
+
+        public static void BuildUpdate() => Begin("update");
+
+        [MenuItem("资源构建/一键打包资源", priority = 0)]
+        public static void BuildAll() => Begin("combined");
+
+        [MenuItem("资源构建/一键打包资源", true)]
+        public static bool CanBuildAll() => !IsBuilding && !S3UploadController.IsUploading && !EditorApplication.isCompiling
+            && !EditorApplication.isUpdating && !EditorApplication.isPlayingOrWillChangePlaymode && !BuildPipeline.isBuildingPlayer
+            && HotPatchAssemblySelection.BuildBlockReason(Resources.Load<AppSettings>("AppSettings")) == null;
+
+        public static void CompileOnly() => Begin("compile");
+
+        static void Begin(string operation)
+        {
+            if (working || !string.IsNullOrEmpty(SessionState.GetString(Pending, "")))
+            { Debug.LogWarning("[资源构建] 任务正在执行,请等待完成。"); return; }
+            working = true;
+            try
+            {
+                if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling)
+                    throw new InvalidOperationException("请退出 Play Mode 并等待编译完成。");
+                if (S3UploadController.IsUploading || BuildPipeline.isBuildingPlayer)
+                    throw new InvalidOperationException("请等待资源上传或 Player 构建完成。");
+                var blockReason = HotPatchAssemblySelection.BuildBlockReason(Resources.Load<AppSettings>("AppSettings"));
+                if (blockReason != null) throw new InvalidOperationException(blockReason);
+                if (operation != "compile") HotPatchBundleBuild.ConfigurePlayerScenes();
+                ValidateHybridSettings();
+                PinBuildSettings();
+                SessionState.SetBool(Combined, operation == "combined");
+                SessionState.SetBool(Failed, false);
+                if (operation == "original" || operation == "combined")
+                {
+                    EnsureInstalled();
+                    if (ConfigurePlayerSettings(EditorUserBuildSettings.activeBuildTarget))
+                    {
+                                                                                                               
+                        SessionState.SetString(Pending, "original-generate");
+                        SessionState.SetString(Phase, "compiling");
+                        CompilationPipeline.RequestScriptCompilation();
+                        Debug.Log("[资源构建] 已配置 .NET Framework / IL2CPP,等待编译后继续原始资源构建。");
+                        return;
+                    }
+                    GenerateOriginalBaseline();
+                    return;
+                }
+                ValidatePlayerSettings();
+                if (operation == "update") ReadBaseline();
+                StartSourceCompilation(operation);
+            }
+            catch (Exception e) { FinishOperation(); Debug.LogException(e); }
+            finally { working = false; EditorUtility.ClearProgressBar(); }
+        }
+
+        static void StartSourceCompilation(string operation)
+        {
+            SessionState.SetBool(Failed, false);
+            SessionState.SetString(Pending, operation);
+            SessionState.SetString(Phase, "compiling");
+            AssetDatabase.StartAssetEditing();
+            try { HotPatchSourceSync.Synchronize(refresh: false); }
+            finally { AssetDatabase.StopAssetEditing(); }
+            AssetDatabase.Refresh();
+            CompilationPipeline.RequestScriptCompilation();
+            Debug.Log("[资源构建] 已复制 Sources 到所选程序集的 HotPatch,等待编译: " + operation);
+        }
+
+        static void EnsureInstalled()
+        {
+            var installer = new InstallerController();
+            if (installer.HasInstalledHybridCLR()) return;
+            EditorUtility.DisplayProgressBar("资源构建", "正在安装 HybridCLR", .05f);
+            installer.InstallDefaultHybridCLR();
+            if (!installer.HasInstalledHybridCLR()) throw new BuildFailedException("HybridCLR 安装失败,未修改原始资源。");
+        }
+
+        public static bool ConfigurePlayerSettings(BuildTarget target)
+        {
+            var named = NamedBuildTarget.FromBuildTargetGroup(BuildPipeline.GetBuildTargetGroup(target));
+            bool changed = false;
+            if (PlayerSettings.GetApiCompatibilityLevel(named) != ApiCompatibilityLevel.NET_Unity_4_8)
+            { PlayerSettings.SetApiCompatibilityLevel(named, ApiCompatibilityLevel.NET_Unity_4_8); changed = true; }
+            if (PlayerSettings.GetScriptingBackend(named) != ScriptingImplementation.IL2CPP)
+            { PlayerSettings.SetScriptingBackend(named, ScriptingImplementation.IL2CPP); changed = true; }
+            return changed;
+        }
+
+        public static void RequireFrameworkApi(ApiCompatibilityLevel level)
+        {
+            if (level != ApiCompatibilityLevel.NET_Unity_4_8)
+                throw new InvalidOperationException("HybridCLR 热补丁需要 .NET Framework API Compatibility Level,不能使用 .NET Standard。请执行 资源构建/一键打包资源,自动修正配置并重新生成 AOT 基线。");
+        }
+
+        static void ValidatePlayerSettings()
+        {
+            var named = NamedBuildTarget.FromBuildTargetGroup(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
+            RequireFrameworkApi(PlayerSettings.GetApiCompatibilityLevel(named));
+            if (PlayerSettings.GetScriptingBackend(named) != ScriptingImplementation.IL2CPP)
+                throw new InvalidOperationException("HybridCLR 热补丁需要 IL2CPP,请先执行 资源构建/一键打包资源。");
+        }
+
+        static void PinBuildSettings()
+        {
+            SessionState.SetString("HotPatch.Target", EditorUserBuildSettings.activeBuildTarget.ToString());
+            SessionState.SetString("HotPatch.Assembly", HotPatchSourceSync.AssemblyName);
+            SessionState.SetString("HotPatch.Scene", AppSettings.RequireGameSceneName());
+            SessionState.SetBool("HotPatch.Development", EditorUserBuildSettings.development);
+        }
+
+        static void ClearPending()
+        { SessionState.EraseString(Pending); SessionState.EraseString(Phase); }
+
+        static void FinishOperation()
+        {
+            ClearPending();
+            SessionState.SetBool(Combined, false);
+            SessionState.EraseString(OriginalStaging);
+            SessionState.EraseString(CombinedStaging);
+            SessionState.EraseString(PreparedBaseline);
+        }
+
+        static void ContinueAfterCompile()
+        {
+            if (working || SessionState.GetString(Phase, "") != "ready" || EditorApplication.isCompiling || EditorApplication.isUpdating) return;
+            var operation = SessionState.GetString(Pending, "");
+            ClearPending();
+            if (string.IsNullOrEmpty(operation)) return;
+            working = true;
+            try
+            {
+                if (SessionState.GetBool(Failed, false) || EditorUtility.scriptCompilationFailed)
+                    throw new InvalidOperationException("Unity 编译失败,资源构建已停止。");
+                if (SessionState.GetString("HotPatch.Target", "") != EditorUserBuildSettings.activeBuildTarget.ToString() ||
+                    SessionState.GetString("HotPatch.Assembly", "") != HotPatchSourceSync.AssemblyName ||
+                    SessionState.GetBool("HotPatch.Development", false) != EditorUserBuildSettings.development ||
+                    SessionState.GetString("HotPatch.Scene", "") != AppSettings.RequireGameSceneName())
+                    throw new InvalidOperationException("编译期间构建目标、程序集或 Development Build 改变,任务已停止。");
+                if (operation == "original-generate") GenerateOriginalBaseline();
+                else if (operation == "original-package") BuildOriginalPackage();
+                else if (operation == "combined-update") BuildCombinedUpdate();
+                else if (operation == "combined-publish") PublishCombined();
+                else if (operation == "update") { BuildUpdateNow(); FinishOperation(); }
+                else { CompileNow(); FinishOperation(); }
+            }
+            catch (Exception e) { FinishOperation(); Debug.LogException(e); }
+            finally { working = false; EditorUtility.ClearProgressBar(); }
+        }
+
+        public static string CompileNow(bool requirePatchSources = true)
+        {
+            ValidatePlayerSettings();
+            if (requirePatchSources) HotPatchSourceSync.VerifySynchronized();
+            else if (Directory.Exists(Path.Combine(Path.GetDirectoryName(HotPatchSourceSync.FindAssemblyPath()), "HotPatch")))
+                throw new InvalidOperationException("原始资源构建前必须删除目标程序集下的 HotPatch。");
+            ValidateHybridSettings();
+            var target = EditorUserBuildSettings.activeBuildTarget;
+                                                                                            
+            var directory = Path.GetFullPath("Library/HotPatch/Compile/" + Guid.NewGuid().ToString("N"));
+            Directory.CreateDirectory(directory);
+            var result = PlayerBuildInterface.CompilePlayerScripts(new ScriptCompilationSettings
+            {
+                target = target, group = BuildPipeline.GetBuildTargetGroup(target),
+                options = EditorUserBuildSettings.development ? ScriptCompilationOptions.DevelopmentBuild : ScriptCompilationOptions.None
+            }, directory);
+            if (result.assemblies == null || result.assemblies.Count == 0)
+                throw new BuildFailedException("热补丁 Player 脚本编译失败。");
+            var dll = Path.Combine(directory, HotPatchSourceSync.AssemblyName + ".dll");
+            ValidateDll(dll, requireInitializer: requirePatchSources);
+            File.WriteAllText("Library/HotPatch/last-compile.json", new JObject { ["dll"] = dll, ["platform"] = target.ToString() }.ToString());
+            Debug.Log("[热补丁] DLL 编译及入口检查通过(未构建宿主): " + dll);
+            return dll;
+        }
+
+        public static void ValidateDll(string path, bool requireInitializer = true)
+        {
+                                                                                             
+            using var module = dnlib.DotNet.ModuleDefMD.Load(path);
+            if (module.Assembly.Name != HotPatchSourceSync.AssemblyName)
+                throw new InvalidDataException("DLL 名称与 AppSettings 选择的程序集不一致。");
+            if (module.GetAssemblyRefs().Any(a => a.Name == "netstandard"))
+                throw new InvalidDataException("热更 DLL 仍引用 netstandard。请使用 .NET Framework API Compatibility Level 重新编译,并通过一键打包资源重新生成 AOT 基线;不要将 netstandard.dll 加入补充元数据或忽略兼容性检查。");
+            var methods = module.GetTypes().SelectMany(t => t.Methods).ToArray();
+            var native = methods.FirstOrDefault(m => m.IsPinvokeImpl);
+            if (native != null) throw new InvalidDataException("热更 DLL 不允许 DllImport,请迁入 AOT 程序集(例如 AppRuntimes.Base): " + native.FullName);
+            var initializers = methods.Where(m => m.CustomAttributes.Any(a =>
+                a.AttributeType.FullName == typeof(HotPatchInitializerAttribute).FullName &&
+                a.AttributeType.DefinitionAssembly?.Name == "AppRuntimes.Base")).ToArray();
+            if (requireInitializer && initializers.Length == 0) throw new InvalidDataException("补丁缺少 [HotPatchInitializer] 初始化入口。");
+            foreach (var method in initializers)
+                if (!method.IsStatic || method.IsAbstract || method.HasGenericParameters || HasGenericDeclaringType(method.DeclaringType) ||
+                    method.MethodSig.Params.Count != 0 || method.MethodSig.RetType.FullName != "System.Void" ||
+                    method.CustomAttributes.Any(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.AsyncStateMachineAttribute"))
+                    throw new InvalidDataException("[HotPatchInitializer] 方法签名不正确: " + method.FullName);
+            if (module.GetAssemblyRefs().Any(a => a.Name == "AppRuntimes" || a.Name == "AppRuntimes.Sources.Editor" || a.Name.String.StartsWith("UnityEditor", StringComparison.Ordinal)))
+                throw new InvalidDataException("补丁仍引用旧 AppRuntimes 或 Editor 程序集。");
+        }
+
+        public static void ValidateHybridSettings()
+        {
+            if (!SettingsUtil.Enable || !SettingsUtil.HotUpdateAssemblyNamesExcludePreserved.Contains(HotPatchSourceSync.AssemblyName))
+                throw new InvalidOperationException("请在 AppSettings 选择热补丁程序集并点击 Save,同步 HybridCLR 配置。");
+            if (SettingsUtil.HotUpdateAssemblyNamesExcludePreserved.Any(n => n != HotPatchSourceSync.AssemblyName) ||
+                (SettingsUtil.HybridCLRSettings.preserveHotUpdateAssemblies?.Length ?? 0) != 0)
+                throw new InvalidOperationException("此热补丁流水线只加载 AppSettings 选择的一个程序集。");
+            HotPatchSourceSync.FindAssemblyPath();
+        }
+
+        static bool HasGenericDeclaringType(dnlib.DotNet.TypeDef type)
+            => type != null && (type.HasGenericParameters || HasGenericDeclaringType(type.DeclaringType));
+
+        static void GenerateOriginalBaseline()
+        {
+            ValidateHybridSettings();
+            ValidatePlayerSettings();
+            var target = EditorUserBuildSettings.activeBuildTarget;
+            HotPatchGenerationState.EnsureGenerated();
+            var stripped = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
+                                                                                                                     
+            var names = HotPatchBundleLoader.AotAssemblyNames.ToArray();
+            var id = Guid.NewGuid().ToString("N");
+            var archive = Path.GetFullPath(OutputRoot + "/Baselines/" + target + "/" + id + "/AOT");
+            Directory.CreateDirectory(archive);
+            var hashes = new JObject();
+            foreach (var source in Directory.GetFiles(stripped, "*.dll"))
+            {
+                var name = Path.GetFileName(source);
+                File.Copy(source, Path.Combine(archive, name));
+                hashes[name] = HotPatchHash.OfFile(source);
+            }
+            if (!hashes.Properties().Any() || names.Any(n => hashes[n] == null))
+                throw new BuildFailedException("HybridCLR 未生成完整的裁剪后 AOT 数据。");
+            var metadataDirectory = Path.Combine(Path.GetDirectoryName(archive), "Metadata");
+            var metadataHashes = new JObject();
+            Directory.CreateDirectory(metadataDirectory);
+            foreach (var name in names)
+            {
+                var output = Path.Combine(metadataDirectory, name);
+                HybridCLR.CodeGen.AOT.AOTAssemblyMetadataStripper.Strip(Path.Combine(archive, name), output);
+                metadataHashes[name] = HotPatchHash.OfFile(output);
+            }
+            var baseline = new JObject
+            {
+                ["unityVersion"] = Application.unityVersion, ["platform"] = target.ToString(),
+                ["apiCompatibilityLevel"] = ApiCompatibilityLevel.NET_Unity_4_8.ToString(),
+                ["playerBuildId"] = id, ["developmentBuild"] = EditorUserBuildSettings.development,
+                ["assemblyName"] = HotPatchSourceSync.AssemblyName, ["gameSceneName"] = AppSettings.RequireGameSceneName(),
+                ["resourceSchema"] = 4,
+                ["aotDirectory"] = archive, ["aotHashes"] = hashes, ["metadataNames"] = new JArray(names),
+                ["metadataDirectory"] = metadataDirectory, ["metadataHashes"] = metadataHashes,
+                ["generationContext"] = HotPatchGenerationState.Context()
+            };
+            var baselinePath = Path.Combine(Path.GetDirectoryName(archive), "baseline.json");
+            File.WriteAllText(baselinePath, baseline.ToString());
+            SessionState.SetString(PreparedBaseline, baselinePath);
+                                                                                                                   
+            var assemblyDirectory = Path.GetDirectoryName(HotPatchSourceSync.FindAssemblyPath());
+            HotPatchResourcePackage.DeleteDirectory(Path.Combine(assemblyDirectory, "HotPatch"), assemblyDirectory);
+            Debug.Log("[资源构建] 已删除目标程序集下的 HotPatch,等待编译原始 DLL。");
+                                                                                                                
+            SessionState.SetBool(Failed, false);
+            SessionState.SetString(Pending, "original-package");
+            SessionState.SetString(Phase, "compiling");
+            AssetDatabase.Refresh();
+            CompilationPipeline.RequestScriptCompilation();
+        }
+
+        public static string[] ReadAotNames(string path)
+        {
+            var text = File.ReadAllText(path);
+            var start = text.IndexOf("// {{ AOT assemblies", StringComparison.Ordinal);
+            var end = start >= 0 ? text.IndexOf("// }}", start, StringComparison.Ordinal) : -1;
+            if (end < 0) throw new InvalidDataException("AOTGenericReferences.cs 缺少 AOT 清单区域。");
+            var names = Regex.Matches(text.Substring(start, end - start), "\"([^\"]+\\.dll)\"")
+                .Cast<Match>().Select(m => m.Groups[1].Value).Distinct().OrderBy(n => n, StringComparer.Ordinal).ToArray();
+            if (names.Any(n => !HotPatchResource.IsValidName(n))) throw new InvalidDataException("AOT 清单包含非法名称。");
+            return names;
+        }
+
+        public static string[] SelectAotMetadata(IEnumerable<string> names)
+        {
+            var list = names.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
+            if (list.Any(n => !HotPatchResource.IsValidName(n))) throw new InvalidDataException("AOT 清单包含非法名称。");
+            return list.Where(n => !n.StartsWith("Unity.", StringComparison.OrdinalIgnoreCase) &&
+                !n.StartsWith("UnityEngine.", StringComparison.OrdinalIgnoreCase) &&
+                !n.StartsWith("UnityEditor.", StringComparison.OrdinalIgnoreCase))
+                .OrderBy(n => n, StringComparer.Ordinal).ToArray();
+        }
+
+        static void BuildOriginalPackage()
+        {
+            var baseline = JObject.Parse(File.ReadAllText(SessionState.GetString(PreparedBaseline, "")));
+            ValidateBaseline(baseline);
+            var dll = CompileNow(requirePatchSources: false);
+            CheckCompatibility(baseline, dll);
+            var staging = Path.GetFullPath(StagingRoot + "/" + Guid.NewGuid().ToString("N"));
+            var manifest = WritePackage(staging, dll, baseline, includeAot: true);
+            baseline["aotBundleHash"] = manifest.aotBundle.sha256;
+            var archiveRoot = Path.GetDirectoryName((string)baseline["aotDirectory"]);
+            File.Copy(Path.Combine(staging, manifest.aotBundle.RelativePath), Path.Combine(archiveRoot, "aot.bundle"), true);
+            File.WriteAllText(Path.Combine(archiveRoot, "baseline.json"), baseline.ToString());
+            if (SessionState.GetBool(Combined, false))
+            {
+                SessionState.SetString(OriginalStaging, staging);
+                Debug.Log("[资源构建] 一键打包:原始资源已暂存,继续构建更新资源。");
+                StartSourceCompilation("combined-update");
+                return;
+            }
+            PublishOriginal(staging, baseline);
+            FinishOperation();
+            Debug.Log("[资源构建] 原始资源完成,已替换旧 StreamingAssets: " + Application.streamingAssetsPath);
+        }
+
+        static void PublishOriginal(string staging, JObject baseline)
+        {
+                                                                                                                
+            HotPatchResourcePackage.ReplaceDirectory(staging, Application.streamingAssetsPath,
+                Path.GetFullPath(StagingRoot), Application.dataPath);
+            HotPatchLocalTesting.SetLocalMode(false);
+            Directory.CreateDirectory(Path.GetDirectoryName(BaselinePointer));
+            File.WriteAllText(BaselinePointer, baseline.ToString());
+            AssetDatabase.Refresh();
+        }
+
+        static void BuildCombinedUpdate()
+        {
+            var baseline = JObject.Parse(File.ReadAllText(SessionState.GetString(PreparedBaseline, "")));
+            ValidateBaseline(baseline);
+            var originalDirectory = HotPatchResourcePackage.RequireChild(Path.GetFullPath(StagingRoot), SessionState.GetString(OriginalStaging, ""));
+            var original = ReadOriginal(baseline, originalDirectory);
+            var dll = CompileNow();
+            CheckCompatibility(baseline, dll);
+            var updateDirectory = Path.GetFullPath(StagingRoot + "/" + Guid.NewGuid().ToString("N"));
+            WritePackage(updateDirectory, dll, baseline, includeAot: false, original);
+            var combinedDirectory = Path.GetFullPath(StagingRoot + "/" + Guid.NewGuid().ToString("N"));
+            HotPatchResourcePackage.CopyOriginal(originalDirectory, combinedDirectory);
+            HotPatchResourcePackage.AppendUpdate(combinedDirectory, updateDirectory);
+            SessionState.SetString(CombinedStaging, combinedDirectory);
+            var assemblyDirectory = Path.GetDirectoryName(HotPatchSourceSync.FindAssemblyPath());
+            HotPatchResourcePackage.DeleteDirectory(Path.Combine(assemblyDirectory, "HotPatch"), assemblyDirectory);
+            SessionState.SetBool(Failed, false);
+            SessionState.SetString(Pending, "combined-publish");
+            SessionState.SetString(Phase, "compiling");
+            AssetDatabase.Refresh();
+            CompilationPipeline.RequestScriptCompilation();
+            Debug.Log("[资源构建] 两版资源已暂存,已删除 HotPatch,等待编译完成后发布。");
+        }
+
+        static void PublishCombined()
+        {
+            var baseline = JObject.Parse(File.ReadAllText(SessionState.GetString(PreparedBaseline, "")));
+            ValidateBaseline(baseline);
+            var assemblyDirectory = Path.GetDirectoryName(HotPatchSourceSync.FindAssemblyPath());
+            if (Directory.Exists(Path.Combine(assemblyDirectory, "HotPatch")))
+                throw new InvalidOperationException("HotPatch 目录仍然存在,一键打包未完成。");
+            var originalDirectory = HotPatchResourcePackage.RequireChild(Path.GetFullPath(StagingRoot), SessionState.GetString(OriginalStaging, ""));
+            ReadOriginal(baseline, originalDirectory);
+            var combinedDirectory = HotPatchResourcePackage.RequireChild(Path.GetFullPath(StagingRoot), SessionState.GetString(CombinedStaging, ""));
+            var directory = Path.GetFullPath(OutputRoot + "/AllRes_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"));
+            if (Directory.Exists(directory)) directory += "_" + Guid.NewGuid().ToString("N").Substring(0, 8);
+            HotPatchResourcePackage.ReplaceDirectory(combinedDirectory, directory, Path.GetFullPath(StagingRoot), Path.GetFullPath(OutputRoot));
+            PublishOriginal(originalDirectory, baseline);
+            FinishOperation();
+            Debug.Log("[资源构建] 一键打包完成: " + directory + ";StreamingAssets 只保留原始清单及其资源,HotPatch 已删除。");
+            EditorUtility.RevealInFinder(directory);
+        }
+
+        public static JObject ReadBaseline()
+        {
+            ValidatePlayerSettings();
+            if (!File.Exists(BaselinePointer)) throw new InvalidOperationException("请先执行 资源构建/一键打包资源。");
+            var baseline = JObject.Parse(File.ReadAllText(BaselinePointer));
+            ValidateBaseline(baseline);
+            ReadOriginal(baseline, Application.streamingAssetsPath);
+            return baseline;
+        }
+
+        static HotPatchManifest ReadOriginal(JObject baseline, string directory)
+        {
+            var original = HotPatchResourceStore.Parse(File.ReadAllText(Path.Combine(directory, HotPatchResourceStore.ManifestFileName)));
+            original.Validate(HotPatchSourceSync.AssemblyName, EditorUserBuildSettings.activeBuildTarget.ToString(), AppSettings.RequireGameSceneName());
+            if (original.playerBuildId != (string)baseline["playerBuildId"] || original.developmentBuild != (bool)baseline["developmentBuild"])
+                throw new InvalidOperationException("StreamingAssets 与资源构建基线不匹配,请重新执行一键打包资源。");
+            var metadata = original.aotMetadata ?? Array.Empty<HotPatchResource>();
+            var metadataNames = ((JArray)baseline["metadataNames"]).Values<string>().ToArray();
+            if (metadata.Length != metadataNames.Length || metadata.Any(r => !metadataNames.Contains(r.name) ||
+                !string.Equals(r.sha256, (string)baseline["metadataHashes"][r.name], StringComparison.OrdinalIgnoreCase)))
+                throw new InvalidDataException("安装包 AOT 元数据清单与归档基线不匹配,请重新执行一键打包资源。");
+            if (original.aotBundle == null || original.aotBundle.sha256 != (string)baseline["aotBundleHash"])
+                throw new InvalidDataException("AOT Bundle 与原始基线不匹配,请重新执行一键打包资源。");
+            foreach (var resource in original.resources.Concat(new[] { original.aotBundle }))
+                if (!HotPatchResourceStore.IsVerified(Path.Combine(directory, resource.RelativePath), resource))
+                    throw new InvalidDataException("原始资源缺失或损坏: " + resource.name);
+            return original;
+        }
+
+        static void ValidateBaseline(JObject baseline)
+        {
+            if ((int?)baseline["resourceSchema"] != 4 || (string)baseline["gameSceneName"] != AppSettings.RequireGameSceneName())
+                throw new InvalidDataException("请重新构建包含三个 AssetBundle 的原始资源及安装包。");
+            if ((string)baseline["apiCompatibilityLevel"] != ApiCompatibilityLevel.NET_Unity_4_8.ToString())
+                throw new InvalidDataException("原始资源尚未建立 .NET Framework AOT 基线,请重新执行 资源构建/一键打包资源。");
+            if ((string)baseline["unityVersion"] != Application.unityVersion ||
+                (string)baseline["platform"] != EditorUserBuildSettings.activeBuildTarget.ToString() ||
+                (string)baseline["assemblyName"] != HotPatchSourceSync.AssemblyName ||
+                (bool?)baseline["developmentBuild"] != EditorUserBuildSettings.development ||
+                string.IsNullOrWhiteSpace((string)baseline["playerBuildId"]))
+                throw new InvalidOperationException("Unity 版本、平台、程序集或 Development Build 与原始资源不同。");
+            var aot = (string)baseline["aotDirectory"];
+            if (string.IsNullOrEmpty(aot) || !Directory.Exists(aot) || !(baseline["aotHashes"] is JObject hashes) || !hashes.Properties().Any())
+                throw new InvalidDataException("AOT 基线缺失。");
+            foreach (var file in hashes.Properties())
+                if (!HotPatchResource.IsValidName(file.Name) || !File.Exists(Path.Combine(aot, file.Name)) ||
+                    HotPatchHash.OfFile(Path.Combine(aot, file.Name)) != (string)file.Value)
+                    throw new InvalidDataException("AOT 基线已损坏: " + file.Name);
+            if (!(baseline["metadataNames"] is JArray names) || names.Values<string>().Any(n => n == null || hashes[n] == null))
+                throw new InvalidDataException("AOT 元数据名称清单缺失。");
+            var metadata = (string)baseline["metadataDirectory"];
+            if (string.IsNullOrEmpty(metadata) || !(baseline["metadataHashes"] is JObject metadataHashes) ||
+                names.Values<string>().Any(n => !File.Exists(Path.Combine(metadata, n)) || HotPatchHash.OfFile(Path.Combine(metadata, n)) != (string)metadataHashes[n]) ||
+                (string)baseline["generationContext"] != HotPatchGenerationState.Context())
+                throw new InvalidDataException("AOT 精简元数据缺失或宿主配置已改变,请重新执行一键打包资源。");
+        }
+
+        public static string BuildUpdateNow()
+        {
+            var baseline = ReadBaseline();
+            var original = ReadOriginal(baseline, Application.streamingAssetsPath);
+            var dll = CompileNow();
+            CheckCompatibility(baseline, dll);
+            var directory = Path.GetFullPath(OutputRoot + "/HotRes_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"));
+            if (Directory.Exists(directory)) directory += "_" + Guid.NewGuid().ToString("N").Substring(0, 8);
+            var staging = Path.GetFullPath(StagingRoot + "/" + Guid.NewGuid().ToString("N"));
+            var manifest = WritePackage(staging, dll, baseline, includeAot: false, original);
+            manifest.ValidateAgainst(original);
+            HotPatchResourcePackage.ReplaceDirectory(staging, directory, Path.GetFullPath(StagingRoot), Path.GetFullPath(OutputRoot));
+            Debug.Log("[资源构建] 更新资源完成: " + directory + ";上传 files 后再替换 manifest.json。");
+            EditorUtility.RevealInFinder(directory);
+            return directory;
+        }
+
+        static HotPatchManifest WritePackage(string destination, string dll, JObject baseline, bool includeAot, HotPatchManifest original = null)
+        {
+            var aotDirectory = (string)baseline["metadataDirectory"];
+            var files = includeAot
+                ? ((JArray)baseline["metadataNames"]).Values<string>().ToDictionary(n => n, n => Path.Combine(aotDirectory, n))
+                : new Dictionary<string, string>();
+            return HotPatchBundleBuild.Build(destination, dll, files, (string)baseline["assemblyName"], (string)baseline["gameSceneName"],
+                (string)baseline["platform"], (string)baseline["playerBuildId"], (bool)baseline["developmentBuild"], includeAot, original);
+        }
+
+        static void CheckCompatibility(JObject baseline, string dll)
+        {
+            var checker = new MissingMetadataChecker((string)baseline["aotDirectory"], new[] { HotPatchSourceSync.AssemblyName });
+            if (!checker.Check(dll)) throw new InvalidOperationException("热更 DLL 引用了 AOT 基线缺失的程序集、类型或成员,详见上方 Missing 日志。请检查 API Compatibility Level 和 AOT 保留配置后重新执行一键打包资源,并构建安装包。");
+        }
+    }
+}

+ 1 - 4
Runtime/Scripts/Https.cs.meta → Editor/HotPatch/HotPatchBuild.cs.meta

@@ -1,11 +1,8 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: 1bdffcb648fe9e7429f057a60a81c8e4
+guid: 1065f2086b77411cadee0cc5480022bc
 MonoImporter:
 MonoImporter:
   externalObjects: {}
   externalObjects: {}
   serializedVersion: 2
   serializedVersion: 2
   defaultReferences: []
   defaultReferences: []
   executionOrder: 0
   executionOrder: 0
   icon: {instanceID: 0}
   icon: {instanceID: 0}
-  userData: 
-  assetBundleName: 
-  assetBundleVariant: 

+ 148 - 0
Editor/HotPatch/HotPatchBundleBuild.cs

@@ -0,0 +1,148 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using TMPro;
+using UnityEditor;
+using UnityEditor.Build;
+using UnityEngine;
+
+namespace HotPatch.Editor
+{
+    public static class HotPatchBundleBuild
+    {
+        public static string AotDirectory => Path.Combine(Application.dataPath, "AotDlls");
+        const string AotAssetDirectory = "Assets/AotDlls";
+        const string DllAssetDirectory = "Assets/HotPatch/BundleInputs";
+
+        public static string FindScenePath(string sceneName)
+        {
+            var paths = AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }).Select(AssetDatabase.GUIDToAssetPath)
+                .Where(p => Path.GetFileNameWithoutExtension(p) == sceneName).ToArray();
+            if (paths.Length != 1) throw new InvalidOperationException("场景必须存在且名称唯一: " + sceneName);
+            return paths[0];
+        }
+
+        public static void ConfigurePlayerScenes()
+        {
+            var launchPath = FindScenePath("Launch");
+                                                                                               
+                                                                                                     
+            if (EditorUserBuildSettings.buildScriptsOnly)
+            {
+                EditorUserBuildSettings.buildScriptsOnly = false;
+                Debug.Log("[资源构建] 已关闭 Force skip data build,下一次安装包构建将正常更新场景和资源数据。");
+            }
+                                                                                                  
+            if (!ContainsOnlyLaunch(EditorBuildSettings.scenes, launchPath))
+            {
+                EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(launchPath, true) };
+                Debug.Log("[资源构建] 已调整构建场景列表,仅保留并启用 Launch: " + launchPath);
+            }
+            var profile = UnityEditor.Build.Profile.BuildProfile.GetActiveBuildProfile();
+            if (profile != null && profile.overrideGlobalScenes && !ContainsOnlyLaunch(profile.scenes, launchPath))
+            {
+                profile.scenes = new[] { new EditorBuildSettingsScene(launchPath, true) };
+                EditorUtility.SetDirty(profile);
+                AssetDatabase.SaveAssetIfDirty(profile);
+                Debug.Log("[资源构建] 已调整当前构建配置的场景列表,仅保留并启用 Launch: " + launchPath);
+            }
+        }
+
+        static bool ContainsOnlyLaunch(EditorBuildSettingsScene[] scenes, string launchPath)
+            => scenes != null && scenes.Length == 1 && scenes[0].path == launchPath && scenes[0].enabled;
+
+                                                                                                   
+        public static void PrepareAotFiles(IReadOnlyDictionary<string, string> files)
+        {
+            if (!files.Keys.OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n)))
+                throw new InvalidDataException("Assets/AotDlls 必须包含 mscorlib、Newtonsoft.Json、System.Core 和 UniTask 四个程序集。");
+            foreach (var file in files)
+            {
+                if (!File.Exists(file.Value)) throw new FileNotFoundException("当前平台 AOT 基线缺失。", file.Value);
+                if (System.Reflection.AssemblyName.GetAssemblyName(file.Value).Name + ".dll" != file.Key)
+                    throw new InvalidDataException("AOT 文件与程序集名称不一致: " + file.Key);
+            }
+            Directory.CreateDirectory(AotDirectory);
+            foreach (var file in files) File.Copy(file.Value, Path.Combine(AotDirectory, file.Key + ".bytes"), true);
+            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
+        }
+
+        static void PrepareDynamicFonts()
+        {
+            var fonts = AssetDatabase.FindAssets("t:TMP_FontAsset")
+                .Select(AssetDatabase.GUIDToAssetPath)
+                .Select(AssetDatabase.LoadAssetAtPath<TMP_FontAsset>)
+                .Where(font => font != null && new SerializedObject(font).FindProperty("m_ClearDynamicDataOnBuild").boolValue &&
+                    (font.atlasPopulationMode == AtlasPopulationMode.Dynamic ||
+                     font.atlasPopulationMode == AtlasPopulationMode.DynamicOS)).ToArray();
+            if (fonts.Length == 0) return;
+
+                                                                                           
+                                                                                           
+            new TMP_PreBuildProcessor().OnPreprocessBuild(null);
+            foreach (var font in fonts)
+            {
+                EditorUtility.SetDirty(font);
+                foreach (var texture in font.atlasTextures)
+                    if (texture != null) EditorUtility.SetDirty(texture);
+                                                                                                   
+                AssetDatabase.SaveAssetIfDirty(font);
+            }
+            Debug.Log("[资源构建] 已按 Clear Dynamic Data On Build 设置清理动态字体缓存: " +
+                string.Join(", ", fonts.Select(AssetDatabase.GetAssetPath)));
+        }
+
+        public static HotPatchManifest Build(string destination, string dll, IReadOnlyDictionary<string, string> aotFiles,
+            string assemblyName, string sceneName, string platform, string buildId, bool development, bool includeAot,
+            HotPatchManifest original = null)
+        {
+            if (!includeAot && original?.aotBundle == null)
+                throw new InvalidDataException("构建更新 Bundle 前必须提供原始 AOT 清单。");
+            var target = (BuildTarget)Enum.Parse(typeof(BuildTarget), platform);
+            if (target != EditorUserBuildSettings.activeBuildTarget)
+                throw new InvalidOperationException("请先切换到目标平台再构建 Bundle。");
+            var scenePath = FindScenePath(sceneName);
+            if (includeAot) PrepareAotFiles(aotFiles);
+            Directory.CreateDirectory(DllAssetDirectory);
+            var dllAsset = DllAssetDirectory + "/" + assemblyName + ".dll.bytes";
+            File.Copy(dll, dllAsset, true);
+            AssetDatabase.ImportAsset(dllAsset, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);
+            var assemblyBundleName = HotPatchResource.AssemblyBundleName(assemblyName);
+            var sceneBundleName = HotPatchResource.SceneBundleName(sceneName);
+            var builds = new List<AssetBundleBuild>
+            {
+                new AssetBundleBuild { assetBundleName = assemblyBundleName, assetNames = new[] { dllAsset },
+                    addressableNames = new[] { assemblyName + ".dll.bytes" } },
+                new AssetBundleBuild { assetBundleName = sceneBundleName, assetNames = new[] { scenePath } }
+            };
+            if (includeAot)
+            {
+                var paths = Directory.GetFiles(AotDirectory, "*.bytes", SearchOption.AllDirectories)
+                    .Select(p => AotAssetDirectory + "/" + p.Substring(AotDirectory.Length + 1).Replace('\\', '/')).OrderBy(p => p).ToArray();
+                var expected = HotPatchBundleLoader.AotAssemblyNames.Select(n => n + ".bytes").OrderBy(n => n).ToArray();
+                if (!paths.Select(Path.GetFileName).OrderBy(n => n).SequenceEqual(expected))
+                    throw new InvalidDataException("Assets/AotDlls 目录只能包含指定的四个 .dll.bytes 文件。");
+                builds.Insert(0, new AssetBundleBuild { assetBundleName = "aot.bundle", assetNames = paths,
+                    addressableNames = paths.Select(Path.GetFileName).ToArray() });
+            }
+                                                                                
+                                                                 
+            var output = Path.GetFullPath("Build/HotUpdate/BundleCache/" + platform);
+            Directory.CreateDirectory(output);
+            var options = BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode;
+                                                                                                       
+            PrepareDynamicFonts();
+            AssetBundleManifest result;
+            using (new HotPatchAndroidResolverScope())
+                result = BuildPipeline.BuildAssetBundles(output, builds.ToArray(), options, target);
+            if (result == null) throw new BuildFailedException("AssetBundle 构建失败,未发布资源。");
+            foreach (var build in builds)
+                if (result.GetAllDependencies(build.assetBundleName).Length != 0)
+                    throw new BuildFailedException("Bundle 出现未声明依赖: " + build.assetBundleName);
+            return HotPatchResourcePackage.Write(destination, Path.Combine(output, assemblyBundleName), Path.Combine(output, sceneBundleName),
+                includeAot ? Path.Combine(output, "aot.bundle") : null, includeAot ? aotFiles : new Dictionary<string, string>(),
+                assemblyName, sceneName, scenePath, platform, buildId, development, original);
+        }
+    }
+}

+ 2 - 0
Editor/HotPatch/HotPatchBundleBuild.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8f53a4c8587631b4597766c34445162b

+ 134 - 0
Editor/HotPatch/HotPatchGenerationState.cs

@@ -0,0 +1,134 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Text;
+using HybridCLR;
+using HybridCLR.Commands;
+using HybridCLR.Installer;
+using UnityEditor;
+using UnityEditor.Build;
+using UnityEditor.Build.Reporting;
+using UnityEditor.Compilation;
+using UnityEngine;
+
+namespace HotPatch.Editor
+{
+
+    public static class HotPatchGenerationState
+    {
+        [Serializable] sealed class Record { public string context; public FileStamp[] files; }
+        [Serializable] sealed class FileStamp { public string path; public string hash; }
+        static string RecordPath => "Library/HotPatch/GenerateAll/" + EditorUserBuildSettings.activeBuildTarget + ".json";
+
+        public static string Context()
+        {
+            var target = EditorUserBuildSettings.activeBuildTarget;
+            var named = NamedBuildTarget.FromBuildTargetGroup(BuildPipeline.GetBuildTargetGroup(target));
+            var installer = new InstallerController();
+            var text = new StringBuilder().AppendLine(Application.unityVersion).AppendLine(target.ToString())
+                .AppendLine(EditorUserBuildSettings.development.ToString()).AppendLine(HotPatchSourceSync.AssemblyName)
+                .AppendLine(installer.PackageVersion).AppendLine(installer.InstalledLibil2cppVersion)
+                .AppendLine(PlayerSettings.GetScriptingBackend(named).ToString())
+                .AppendLine(PlayerSettings.GetApiCompatibilityLevel(named).ToString())
+                .AppendLine(PlayerSettings.GetManagedStrippingLevel(named).ToString())
+                .AppendLine(PlayerSettings.GetScriptingDefineSymbols(named))
+                .AppendLine(JsonUtility.ToJson(SettingsUtil.HybridCLRSettings))
+                .AppendLine(HotPatchHash.OfFile(Path.Combine(HotPatchSourceSync.PackageRoot, "Editor/HotPatch/HotPatchSourcesLinker.cs")))
+                .AppendLine(HotPatchHash.OfFile(HotPatchSourcesLinker.Generate()));
+            foreach (var file in AotSourceFiles()) text.AppendLine(file).AppendLine(HotPatchHash.OfFile(file));
+            return HotPatchHash.Of(Encoding.UTF8.GetBytes(text.ToString()));
+        }
+
+        static string[] AotSourceFiles()
+        {
+            var generated = Path.GetFullPath("Assets/" + SettingsUtil.HybridCLRSettings.outputAOTGenericReferenceFile);
+            return CompilationPipeline.GetAssemblies(AssembliesType.Player)
+                .Where(a => !SettingsUtil.HotUpdateAssemblyNamesIncludePreserved.Contains(a.name))
+                .SelectMany(a => a.sourceFiles).Where(File.Exists)
+                .Where(p => !string.Equals(Path.GetFullPath(p), generated, StringComparison.OrdinalIgnoreCase))
+                .Distinct().OrderBy(p => p, StringComparer.Ordinal).ToArray();
+        }
+
+        static string[] Artifacts()
+        {
+            var stripped = SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget);
+            var aot = Directory.Exists(stripped) ? Directory.GetFiles(stripped, "*.dll") : Array.Empty<string>();
+            if (aot.Length == 0) return Array.Empty<string>();
+            return aot.Concat(new[]
+            {
+                "Assets/" + SettingsUtil.HybridCLRSettings.outputLinkFile,
+                "Assets/" + SettingsUtil.HybridCLRSettings.outputAOTGenericReferenceFile,
+                Path.Combine(SettingsUtil.GeneratedCppDir, "UnityVersion.inc"),
+                Path.Combine(SettingsUtil.GeneratedCppDir, "AssemblyManifest.inc"),
+                Path.Combine(SettingsUtil.GeneratedCppDir, "MethodBridge.inc")
+            }).Select(Path.GetFullPath).OrderBy(p => p, StringComparer.Ordinal).ToArray();
+        }
+
+        public static bool IsReusable(string recordPath, string context, string[] artifacts)
+        {
+            if (!File.Exists(recordPath) || artifacts.Length == 0 || artifacts.Any(p => !File.Exists(p))) return false;
+            try
+            {
+                var record = JsonUtility.FromJson<Record>(File.ReadAllText(recordPath));
+                return record != null && record.context == context && record.files != null && record.files.Length == artifacts.Length &&
+                    artifacts.All(p => record.files.Any(f => f != null && f.path == Path.GetFullPath(p) && f.hash == HotPatchHash.OfFile(p)));
+            }
+            catch (Exception e) when (e is ArgumentException || e is IOException) { return false; }
+        }
+
+        public static void RecordSuccess(string recordPath, string context, string[] artifacts)
+        {
+            if (artifacts.Length == 0 || artifacts.Any(p => !File.Exists(p) || new FileInfo(p).Length == 0))
+                throw new InvalidDataException("Generate/All 的生成文件不完整,未记录成功状态。");
+            var record = new Record { context = context, files = artifacts.Select(p => new FileStamp
+                { path = Path.GetFullPath(p), hash = HotPatchHash.OfFile(p) }).ToArray() };
+            Directory.CreateDirectory(Path.GetDirectoryName(recordPath));
+            File.WriteAllText(recordPath, JsonUtility.ToJson(record, true));
+        }
+
+
+
+        static bool CanAdoptManualGeneration(string[] artifacts)
+        {
+            if (artifacts.Length == 0 || artifacts.Any(p => !File.Exists(p) || new FileInfo(p).Length == 0)) return false;
+            var report = BuildReport.GetLatestReport();
+            if (report == null) return false;
+            var summary = report.summary;
+            if (summary.result != BuildResult.Succeeded || summary.platform != EditorUserBuildSettings.activeBuildTarget ||
+                summary.options.HasFlag(BuildOptions.Development) != EditorUserBuildSettings.development ||
+                !summary.outputPath.Replace('\\', '/').Contains("/StrippedAOTDllsTempProj/")) return false;
+            var start = summary.buildStartedAt.ToUniversalTime();
+            var end = summary.buildEndedAt.ToUniversalTime();
+            if (AotSourceFiles().Any(p => File.GetLastWriteTimeUtc(p) > start)) return false;
+            var bridgeTime = File.GetLastWriteTimeUtc(Path.Combine(SettingsUtil.GeneratedCppDir, "MethodBridge.inc"));
+            var referenceTime = File.GetLastWriteTimeUtc("Assets/" + SettingsUtil.HybridCLRSettings.outputAOTGenericReferenceFile);
+            var stripped = SettingsUtil.GetAssembliesPostIl2CppStripDir(summary.platform);
+            if (Directory.GetFiles(stripped, "*.dll").Any(p => File.GetLastWriteTimeUtc(p) < start || File.GetLastWriteTimeUtc(p) > end) ||
+                bridgeTime < end || referenceTime < bridgeTime) return false;
+            var version = Application.unityVersion.Split('.');
+            var patch = new string(version[2].TakeWhile(char.IsDigit).ToArray());
+            var versionNumber = int.Parse(version[0]) * 10000 + int.Parse(version[1]) * 100 + int.Parse(patch);
+            return File.ReadAllText(Path.Combine(SettingsUtil.GeneratedCppDir, "UnityVersion.inc")).Trim() == "#define HYBRIDCLR_UNITY_VERSION " + versionNumber &&
+                File.ReadAllText(Path.Combine(SettingsUtil.GeneratedCppDir, "AssemblyManifest.inc")).Trim().TrimEnd(',').Trim() == "\"" + HotPatchSourceSync.AssemblyName + "\"";
+        }
+
+        public static void EnsureGenerated()
+        {
+            var context = Context();
+            var artifacts = Artifacts();
+            if (IsReusable(RecordPath, context, artifacts))
+            { Debug.Log("[资源构建] 当前平台的 Generate/All 记录和产物有效,跳过生成。"); return; }
+            if (!File.Exists(RecordPath) && CanAdoptManualGeneration(artifacts))
+            {
+                RecordSuccess(RecordPath, context, artifacts);
+                Debug.Log("[资源构建] 已识别此前手动完成的 Generate/All,跳过生成。");
+                return;
+            }
+
+            if (File.Exists(RecordPath)) File.Delete(RecordPath);
+            EditorUtility.DisplayProgressBar("资源构建", "HybridCLR / Generate / All", .2f);
+            using (new HotPatchAndroidResolverScope()) PrebuildCommand.GenerateAll();
+            RecordSuccess(RecordPath, Context(), Artifacts());
+        }
+    }
+}

+ 2 - 0
Editor/HotPatch/HotPatchGenerationState.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d142ca69bb9dddc469fb18111187671a

+ 92 - 0
Editor/HotPatch/HotPatchLocalTesting.cs

@@ -0,0 +1,92 @@
+using System;
+using System.IO;
+using System.Linq;
+using UnityEditor;
+using UnityEngine;
+
+namespace HotPatch.Editor
+{
+    [InitializeOnLoad]
+    public static class HotPatchLocalTesting
+    {
+        static HotPatchLocalTesting()
+        {
+            HotPatchResourceActions.FindLatestResources = FindLatest;
+            HotPatchResourceActions.IsBuildRunning = () => HotPatchBuild.IsBuilding;
+            HotPatchResourceActions.ApplyResources = Apply;
+        }
+
+        public static string FindLatest()
+        {
+            var settings = Resources.Load<AppSettings>("AppSettings");
+            if (settings == null) return null;
+            return FindLatest(Path.GetFullPath("Build/HotUpdate"), settings.HotPatchAssemblyName,
+                EditorUserBuildSettings.activeBuildTarget.ToString(), settings.GameSceneName?.Trim());
+        }
+
+        public static string FindLatest(string root, string assembly, string platform, string scene)
+        {
+            if (!Directory.Exists(root) || string.IsNullOrWhiteSpace(assembly) || string.IsNullOrWhiteSpace(scene)) return null;
+            foreach (var directory in Directory.GetDirectories(root, "AllRes_*", SearchOption.TopDirectoryOnly).OrderByDescending(Path.GetFileName, StringComparer.Ordinal))
+            {
+                try
+                {
+                    HotPatchResourcePackage.RequireChild(root, directory);
+                    var original = ReadManifest(directory, "manifest.json");
+                    original.Validate(assembly, platform, scene);
+                    var hot = ReadManifest(directory, HotPatchResourcePackage.HotManifestFileName);
+                    hot.ValidateAgainst(original);
+                    if (original.aotBundle == null || hot.aotBundle == null || original.aotMetadata == null || hot.aotMetadata == null ||
+                        !original.aotMetadata.Select(r => r.name).OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n)) ||
+                        hot.aotMetadata.Length != original.aotMetadata.Length) continue;
+                    var files = original.resources.Concat(hot.resources).Concat(new[] { original.aotBundle });
+                    if (files.All(resource =>
+                    {
+                        var path = HotPatchResourcePackage.RequireChild(directory, Path.Combine(directory, resource.RelativePath));
+                        return File.Exists(path) && new FileInfo(path).Length == resource.size;
+                    })) return directory;
+                }
+                catch (Exception exception) when (exception is IOException || exception is InvalidDataException || exception is ArgumentException ||
+                    exception is InvalidOperationException || exception is UnauthorizedAccessException) { }
+            }
+            return null;
+        }
+
+        static HotPatchManifest ReadManifest(string directory, string name)
+            => HotPatchResourceStore.Parse(File.ReadAllText(HotPatchResourcePackage.RequireChild(directory, Path.Combine(directory, name))));
+
+        public static void Apply(bool localTesting)
+        {
+            if (HotPatchBuild.IsBuilding || S3UploadController.IsUploading || EditorApplication.isCompiling ||
+                EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer)
+                throw new InvalidOperationException("请等待构建或上传完成,并退出 Play Mode 后再切换资源。");
+            var source = FindLatest() ?? throw new InvalidOperationException("没有可用的最近打包资源,请先执行一键打包资源。");
+            ApplyPackage(source, Application.streamingAssetsPath, Path.GetFullPath("Library/HotPatch/Staging"), Application.dataPath, localTesting);
+            SetLocalMode(localTesting);
+            AssetDatabase.Refresh();
+            Debug.Log("[资源构建] " + (localTesting ? "已使用本地更新资源,Launch 将跳过远程热更新。" : "已恢复正式原始资源,Launch 将正常检查远程更新。") + " 来源: " + source);
+        }
+
+        public static void ApplyPackage(string source, string destination, string stagingParent, string destinationParent, bool localTesting)
+        {
+            var staging = Path.Combine(stagingParent, Guid.NewGuid().ToString("N"));
+            try
+            {
+                HotPatchResourcePackage.CopyOriginal(source, staging, localTesting ? HotPatchResourcePackage.HotManifestFileName : "manifest.json");
+                HotPatchResourcePackage.ReplaceDirectory(staging, destination, stagingParent, destinationParent);
+            }
+            finally
+            {
+                if (Directory.Exists(staging)) HotPatchResourcePackage.DeleteDirectory(staging, stagingParent);
+            }
+        }
+
+        public static void SetLocalMode(bool enabled)
+        {
+            var settings = Resources.Load<AppSettings>("AppSettings") ?? throw new InvalidOperationException("AppSettings 不存在。");
+            settings.UseLocalHotPatchResources = enabled;
+            EditorUtility.SetDirty(settings);
+            AssetDatabase.SaveAssetIfDirty(settings);
+        }
+    }
+}

+ 2 - 0
Editor/HotPatch/HotPatchLocalTesting.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: b49f88c48abea5c4fbabaa85377d289b

+ 195 - 0
Editor/HotPatch/HotPatchResourcePackage.cs

@@ -0,0 +1,195 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using UnityEngine;
+
+namespace HotPatch.Editor
+{
+    public static class HotPatchResourcePackage
+    {
+        public const string HotManifestFileName = "manifest_hot.json";
+
+        public static HotPatchManifest Write(string destination, string assemblyBundle, string sceneBundle, string aotBundle,
+            IReadOnlyDictionary<string, string> aotFiles, string assemblyName, string sceneName, string scenePath,
+            string platform, string buildId, bool development, HotPatchManifest original = null)
+        {
+            if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any())
+                throw new IOException("资源输出目录必须为空: " + destination);
+            var inputs = new List<KeyValuePair<HotPatchResource, string>>
+            {
+                new KeyValuePair<HotPatchResource, string>(Describe(HotPatchResource.AssemblyBundleName(assemblyName), HotPatchResource.AssemblyKind, assemblyBundle), assemblyBundle),
+                new KeyValuePair<HotPatchResource, string>(Describe(HotPatchResource.SceneBundleName(sceneName), HotPatchResource.SceneKind, sceneBundle), sceneBundle)
+            };
+            var manifest = new HotPatchManifest
+            {
+                assemblyName = assemblyName, gameSceneName = sceneName, gameScenePath = scenePath,
+                platform = platform, playerBuildId = buildId, developmentBuild = development,
+                resources = inputs.Select(p => p.Key).ToArray(),
+                aotMetadata = aotFiles.OrderBy(p => p.Key, StringComparer.Ordinal)
+                    .Select(p => Describe(p.Key, HotPatchResource.AotKind, p.Value)).ToArray()
+            };
+            if (aotBundle != null)
+            {
+                manifest.aotBundle = Describe("aot.bundle", HotPatchResource.AotBundleKind, aotBundle);
+                inputs.Add(new KeyValuePair<HotPatchResource, string>(manifest.aotBundle, aotBundle));
+            }
+            else
+            {
+                if (original?.aotBundle == null || (original.aotMetadata?.Length ?? 0) == 0)
+                    throw new InvalidDataException("更新资源必须继承原始资源的完整 AOT 清单。");
+                                                                                                          
+                var copy = HotPatchResourceStore.Parse(JsonUtility.ToJson(original));
+                copy.Validate(assemblyName, platform, sceneName);
+                manifest.aotBundles = copy.aotBundles;
+                manifest.aotMetadata = copy.aotMetadata;
+            }
+            manifest.version = HotPatchHash.Of(Encoding.UTF8.GetBytes(scenePath + "\n" + string.Join("\n",
+                manifest.resources.Select(r => r.kind + ":" + r.name + ":" + r.sha256))));
+            manifest.Validate(assemblyName, platform, sceneName);
+            if (original != null) manifest.ValidateAgainst(original);
+            Directory.CreateDirectory(Path.Combine(destination, "files"));
+            foreach (var input in inputs)
+            {
+                var output = Path.Combine(destination, input.Key.RelativePath);
+                File.Copy(input.Value, output, true);
+                if (!HotPatchResourceStore.IsVerified(output, input.Key)) throw new IOException("资源复制期间发生变化: " + input.Value);
+            }
+            File.WriteAllText(Path.Combine(destination, HotPatchResourceStore.ManifestFileName), JsonUtility.ToJson(manifest, true), new UTF8Encoding(false));
+            return manifest;
+        }
+
+        public static void CopyOriginal(string sourceDirectory, string destination, string manifestFileName = HotPatchResourceStore.ManifestFileName)
+        {
+            if (manifestFileName != HotPatchResourceStore.ManifestFileName && manifestFileName != HotManifestFileName)
+                throw new ArgumentException("资源清单名称不正确。", nameof(manifestFileName));
+            if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any())
+                throw new IOException("资源输出目录必须为空: " + destination);
+            var json = File.ReadAllText(RequireChild(sourceDirectory, Path.Combine(sourceDirectory, manifestFileName)));
+            var original = HotPatchResourceStore.Parse(json);
+            original.Validate(original.assemblyName, original.platform, original.gameSceneName);
+            if (original.aotBundle == null || (original.aotMetadata?.Length ?? 0) == 0)
+                throw new InvalidDataException("原始资源缺少完整 AOT 清单。");
+            var resources = original.resources.Concat(new[] { original.aotBundle }).ToArray();
+            foreach (var resource in resources)
+                if (!HotPatchResourceStore.IsVerified(RequireChild(sourceDirectory, Path.Combine(sourceDirectory, resource.RelativePath)), resource))
+                    throw new InvalidDataException("原始资源缺失或损坏: " + resource.name);
+            foreach (var resource in resources)
+            {
+                var output = RequireChild(destination, Path.Combine(destination, resource.RelativePath));
+                Directory.CreateDirectory(Path.GetDirectoryName(output));
+                File.Copy(Path.Combine(sourceDirectory, resource.RelativePath), output);
+                if (!HotPatchResourceStore.IsVerified(output, resource)) throw new IOException("原始资源复制失败: " + resource.name);
+            }
+            File.WriteAllText(Path.Combine(destination, HotPatchResourceStore.ManifestFileName), json, new UTF8Encoding(false));
+        }
+
+        public static void AppendUpdate(string originalDirectory, string updateDirectory)
+        {
+            var original = HotPatchResourceStore.Parse(File.ReadAllText(Path.Combine(originalDirectory, HotPatchResourceStore.ManifestFileName)));
+            var updateJson = File.ReadAllText(Path.Combine(updateDirectory, HotPatchResourceStore.ManifestFileName));
+            var update = HotPatchResourceStore.Parse(updateJson);
+            original.Validate(original.assemblyName, original.platform, original.gameSceneName);
+            update.ValidateAgainst(original);
+            if (original.aotBundle == null || update.aotBundle == null ||
+                (original.aotMetadata?.Length ?? 0) == 0 || update.aotMetadata?.Length != original.aotMetadata.Length)
+                throw new InvalidDataException("合并资源需要两份完整且一致的 AOT 清单。");
+            var hotManifest = RequireChild(originalDirectory, Path.Combine(originalDirectory, HotManifestFileName));
+            if (File.Exists(hotManifest)) throw new IOException("原始资源暂存目录已包含更新清单。");
+                                                                                                          
+            foreach (var resource in original.resources.Concat(new[] { original.aotBundle }))
+                if (!HotPatchResourceStore.IsVerified(RequireChild(originalDirectory, Path.Combine(originalDirectory, resource.RelativePath)), resource))
+                    throw new InvalidDataException("原始资源缺失或损坏: " + resource.name);
+            foreach (var resource in update.resources)
+                if (!HotPatchResourceStore.IsVerified(RequireChild(updateDirectory, Path.Combine(updateDirectory, resource.RelativePath)), resource))
+                    throw new InvalidDataException("更新资源缺失或损坏: " + resource.name);
+            foreach (var resource in update.resources)
+            {
+                var destination = RequireChild(originalDirectory, Path.Combine(originalDirectory, resource.RelativePath));
+                if (File.Exists(destination))
+                {
+                    if (!HotPatchResourceStore.IsVerified(destination, resource)) throw new InvalidDataException("资源哈希路径冲突: " + resource.name);
+                    continue;
+                }
+                File.Copy(Path.Combine(updateDirectory, resource.RelativePath), destination);
+                if (!HotPatchResourceStore.IsVerified(destination, resource)) throw new IOException("更新资源复制失败: " + resource.name);
+            }
+            File.WriteAllText(hotManifest, updateJson, new UTF8Encoding(false));
+        }
+
+        public static HotPatchResource Describe(string name, string kind, string source)
+        {
+            if (!File.Exists(source)) throw new FileNotFoundException("资源源文件不存在。", source);
+            return new HotPatchResource { name = name, kind = kind, size = new FileInfo(source).Length, sha256 = HotPatchHash.OfFile(source) };
+        }
+
+                                                                                                         
+        public static void ClearDirectory(string directory, string allowedParent)
+        {
+            directory = RequireChild(allowedParent, directory);
+            if (!Directory.Exists(directory)) return;
+            RejectLinks(directory);
+            foreach (var entry in Directory.GetFileSystemEntries(directory))
+            {
+                var path = RequireChild(directory, entry);
+                if (Directory.Exists(path)) Directory.Delete(path, true);
+                else File.Delete(path);
+            }
+        }
+
+                                                                                                           
+        public static void DeleteDirectory(string directory, string allowedParent)
+        {
+            directory = RequireChild(allowedParent, directory);
+            ClearDirectory(directory, allowedParent);
+            if (Directory.Exists(directory)) Directory.Delete(directory);
+            var meta = RequireChild(allowedParent, directory + ".meta");
+            if (File.Exists(meta)) File.Delete(meta);
+        }
+
+                                                                                                           
+        public static void ReplaceDirectory(string staging, string destination, string stagingParent, string destinationParent)
+        {
+            staging = RequireChild(stagingParent, staging);
+            destination = RequireChild(destinationParent, destination);
+            if (!Directory.Exists(staging)) throw new DirectoryNotFoundException(staging);
+            RejectLinks(staging);
+            if (Directory.Exists(destination)) RejectLinks(destination);
+            var backup = RequireChild(stagingParent, Path.Combine(stagingParent, "replaced-" + Guid.NewGuid().ToString("N")));
+            bool hadOld = Directory.Exists(destination);
+            if (hadOld) Directory.Move(destination, backup);
+            try { Directory.Move(staging, destination); }
+            catch
+            {
+                if (hadOld) Directory.Move(backup, destination);
+                throw;
+            }
+            if (hadOld) Directory.Delete(backup, true);
+        }
+
+        public static string RequireChild(string parent, string path)
+        {
+            var root = Path.GetFullPath(parent).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
+            var full = Path.GetFullPath(path);
+            if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new IOException("资源路径超出指定目录: " + full);
+                                                                                    
+            for (var ancestor = new DirectoryInfo(Path.GetDirectoryName(full)); ancestor != null; ancestor = ancestor.Parent)
+                if (ancestor.Exists && (ancestor.Attributes & FileAttributes.ReparsePoint) != 0)
+                    throw new IOException("资源路径包含符号链接目录: " + ancestor.FullName);
+            return full;
+        }
+
+        static void RejectLinks(string directory)
+        {
+            if ((File.GetAttributes(directory) & FileAttributes.ReparsePoint) != 0)
+                throw new IOException("资源构建目录不能是符号链接: " + directory);
+            foreach (var child in Directory.GetFileSystemEntries(directory))
+            {
+                if ((File.GetAttributes(child) & FileAttributes.ReparsePoint) != 0)
+                    throw new IOException("资源构建目录包含符号链接: " + child);
+                if (Directory.Exists(child)) RejectLinks(child);
+            }
+        }
+    }
+}

+ 2 - 0
Editor/HotPatch/HotPatchResourcePackage.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 12ac43d32e31d2e4babea4baa0306012

+ 27 - 0
Editor/HotPatch/HotPatchSettingsIntegration.cs

@@ -0,0 +1,27 @@
+using System;
+using HybridCLR.Settings;
+using UnityEditor;
+using UnityEditorInternal;
+
+namespace HotPatch.Editor
+{
+    [InitializeOnLoad]
+    public static class HotPatchSettingsIntegration
+    {
+        static HotPatchSettingsIntegration() => HotPatchAssemblySelection.ApplyHybridCLRSettings = Apply;
+
+        public static void Apply(AssemblyDefinitionAsset assembly)
+        {
+            if (assembly != null) HotPatchAssemblySelection.Validate(assembly);
+            var settings = HybridCLRSettings.instance;
+            Undo.RecordObject(settings, "Select hot-patch assembly");
+            settings.enable = true;
+            settings.hotUpdateAssemblyDefinitions = assembly != null ? new[] { assembly } : Array.Empty<AssemblyDefinitionAsset>();
+            settings.hotUpdateAssemblies = Array.Empty<string>();
+
+            settings.preserveHotUpdateAssemblies = Array.Empty<string>();
+            EditorUtility.SetDirty(settings);
+            HybridCLRSettings.Save();
+        }
+    }
+}

+ 2 - 0
Editor/HotPatch/HotPatchSettingsIntegration.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: c8ca2a4d2b26740409cdd8764f35affc

+ 49 - 0
Editor/HotPatch/HotPatchSourcesLinker.cs

@@ -0,0 +1,49 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Xml.Linq;
+using HybridCLR.CodeGen.Link;
+using HybridCLR.Mod;
+using UnityEditor;
+using UnityEditor.Build;
+using UnityEditor.Build.Reporting;
+using UnityEditor.UnityLinker;
+
+namespace HotPatch.Editor
+{
+
+
+    public sealed class HotPatchSourcesLinker : IUnityLinkerProcessor
+    {
+        public int callbackOrder => 0;
+        public string GenerateAdditionalLinkXmlFile(BuildReport report, UnityLinkerBuildPipelineData data) => Generate(report.summary.platform);
+
+        public static string Generate() => Generate(EditorUserBuildSettings.activeBuildTarget);
+
+        public static string Generate(BuildTarget target)
+        {
+            const string sourcesAssembly = "AppRuntimes.Sources.Editor";
+            var analyzer = new LinkAnalyzer(new PathAssemblyResolver("Library/ScriptAssemblies"));
+            var types = analyzer.CollectRefs(new List<string> { sourcesAssembly }, LinkPreserveLevel.PreserveAllOfDeclaringType)
+                .Where(t => !t.AssemblyName.StartsWith("UnityEditor", StringComparison.Ordinal) &&
+                    t.AssemblyName != sourcesAssembly).ToList();
+            const string directory = "Library/HotPatch/Linker";
+            Directory.CreateDirectory(directory);
+            var path = Path.GetFullPath(Path.Combine(directory, "Sources.xml"));
+            new LinkXmlWriter().Write(path, types);
+            var document = XDocument.Load(path);
+
+            foreach (var node in document.Root.Elements("assembly").Where(n => (string)n.Attribute("fullname") == "AppRuntimes.Base").ToArray()) node.Remove();
+            document.Root.Add(new XElement("assembly", new XAttribute("fullname", "AppRuntimes.Base"), new XAttribute("preserve", "all")));
+            if (target == BuildTarget.iOS)
+            {
+                const string iosSupport = "Unity.Advertisement.IosSupport";
+                foreach (var node in document.Root.Elements("assembly").Where(n => (string)n.Attribute("fullname") == iosSupport).ToArray()) node.Remove();
+                document.Root.Add(new XElement("assembly", new XAttribute("fullname", iosSupport), new XAttribute("preserve", "all")));
+            }
+            document.Save(path);
+            return path;
+        }
+    }
+}

+ 2 - 0
Editor/HotPatch/HotPatchSourcesLinker.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8c5ad61c63f4a27459e71fd281fd5ddb

+ 132 - 0
Editor/HotPatchAssemblySelection.cs

@@ -0,0 +1,132 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Text;
+using Newtonsoft.Json.Linq;
+using UnityEditor;
+using UnityEditorInternal;
+
+
+public static class HotPatchAssemblySelection
+{
+    public static Action<AssemblyDefinitionAsset> ApplyHybridCLRSettings;
+    static readonly string[] RequiredReferences = { "AppRuntimes.Base", "Unity.Advertisement.IosSupport" };
+
+    public static AssemblyDefinitionAsset Find(string name)
+    {
+        if (string.IsNullOrWhiteSpace(name)) return null;
+        var paths = AssetDatabase.FindAssets("t:AssemblyDefinitionAsset", new[] { "Assets" })
+            .Select(AssetDatabase.GUIDToAssetPath)
+            .Where(p => (string)JObject.Parse(File.ReadAllText(p))["name"] == name).ToArray();
+        return paths.Length == 1 ? AssetDatabase.LoadAssetAtPath<AssemblyDefinitionAsset>(paths[0]) : null;
+    }
+
+    public static string Validate(AssemblyDefinitionAsset assembly)
+    {
+        var path = AssetDatabase.GetAssetPath(assembly);
+        if (assembly == null || !path.StartsWith("Assets/", StringComparison.Ordinal) || !path.EndsWith(".asmdef", StringComparison.Ordinal))
+            throw new InvalidOperationException("请选择 Assets 中的游戏运行时 asmdef。");
+        var definition = JObject.Parse(File.ReadAllText(path));
+        var name = (string)definition["name"];
+        if (string.IsNullOrWhiteSpace(name) || name.IndexOfAny(new[] { '/', '\\', ':', ',' }) >= 0 || name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
+            throw new InvalidOperationException("热补丁程序集名称不正确。");
+        var platforms = definition["includePlatforms"] as JArray;
+        if (platforms != null && platforms.Count > 0 && platforms.All(p => (string)p == "Editor"))
+            throw new InvalidOperationException("不能选择 Editor 专用程序集。");
+        if (name == "AppRuntimes" || name == "AppRuntimes.Base" || name == "HotPatch.Runtime" ||
+            name == "AppRuntimes.Sources.Editor" || ((JArray)definition["references"] ?? new JArray()).Values<string>().Any(IsLoaderReference))
+            throw new InvalidOperationException("宿主或热补丁加载器程序集不能作为热更目标。");
+        return name;
+    }
+
+    static bool IsLoaderReference(string reference)
+    {
+        return ResolveReferenceName(reference) == "HotPatch.Runtime";
+    }
+
+    static string ResolveReferenceName(string reference)
+    {
+        if (reference != null && reference.StartsWith("GUID:", StringComparison.Ordinal))
+        {
+            var path = AssetDatabase.GUIDToAssetPath(reference.Substring(5));
+            if (File.Exists(path)) reference = (string)JObject.Parse(File.ReadAllText(path))["name"];
+        }
+        return reference;
+    }
+
+    public static bool HasRequiredReferences(AssemblyDefinitionAsset assembly)
+    {
+        if (assembly == null) return false;
+        var definition = JObject.Parse(File.ReadAllText(AssetDatabase.GetAssetPath(assembly)));
+        var references = ((JArray)definition["references"] ?? new JArray()).Values<string>().Select(ResolveReferenceName).ToArray();
+        return RequiredReferences.All(references.Contains);
+    }
+
+    public static void EnsureRequiredReferences(AssemblyDefinitionAsset assembly)
+    {
+        Validate(assembly);
+        var path = AssetDatabase.GetAssetPath(assembly);
+        var definition = JObject.Parse(File.ReadAllText(path));
+        var references = (JArray)definition["references"] ?? new JArray();
+        var names = references.Values<string>().Select(ResolveReferenceName).ToArray();
+        var missing = RequiredReferences.Where(name => !names.Contains(name)).ToArray();
+        if (missing.Length == 0) return;
+        bool useGuids = references.Values<string>().Any(reference => reference != null && reference.StartsWith("GUID:", StringComparison.Ordinal));
+        foreach (var name in missing)
+        {
+            var reference = name;
+            if (useGuids)
+            {
+                var dependency = UnityEditor.Compilation.CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(name);
+                var guid = string.IsNullOrEmpty(dependency) ? "" : AssetDatabase.AssetPathToGUID(dependency);
+                if (string.IsNullOrEmpty(guid)) throw new InvalidOperationException("找不到必需程序集:" + name + ",请等待依赖包导入完成。");
+                reference = "GUID:" + guid;
+            }
+            references.Add(reference);
+        }
+        definition["references"] = references;
+        File.WriteAllText(path, definition.ToString() + "\n", new UTF8Encoding(false));
+        AssetDatabase.ImportAsset(path);
+        if (!HasRequiredReferences(assembly)) throw new InvalidOperationException("程序集引用补全失败,请检查 asmdef 后重新 Save。");
+    }
+
+    public static string BuildBlockReason(AppSettings settings, AssemblyDefinitionAsset assembly, string sceneName)
+    {
+        if (settings == null || assembly == null || string.IsNullOrWhiteSpace(sceneName))
+            return "请设置 Hot Patch Assembly、Game Scene Name 并点击 Save。";
+        try
+        {
+            var name = Validate(assembly);
+            if (!HasRequiredReferences(assembly))
+                return "程序集缺少 AppRuntimes.Base 或 Unity.Advertisement.IosSupport 引用,请点击 Save 自动补全。";
+            if (settings.HotPatchAssemblyName != name || string.IsNullOrWhiteSpace(settings.GameSceneName) || settings.GameSceneName.Trim() != sceneName.Trim())
+                return "程序集或场景设置尚未保存,请点击 Save。";
+            if (ApplyHybridCLRSettings == null) return "请等待 HybridCLR 安装和编译完成。";
+            return null;
+        }
+        catch (Exception exception) { return exception.Message; }
+    }
+
+    public static string BuildBlockReason(AppSettings settings)
+    {
+        if (settings == null) return "请先配置 AppSettings 并点击 Save。";
+        try { return BuildBlockReason(settings, Find(settings.HotPatchAssemblyName), settings.GameSceneName); }
+        catch (Exception exception) { return exception.Message; }
+    }
+
+    public static void Save(AppSettings settings, AssemblyDefinitionAsset assembly)
+    {
+        if (settings == null) throw new ArgumentNullException(nameof(settings));
+        var name = assembly != null ? Validate(assembly) : string.Empty;
+        if (assembly != null)
+        {
+            EnsureRequiredReferences(assembly);
+            if (ApplyHybridCLRSettings == null)
+                throw new InvalidOperationException("HybridCLR 编辑器集成未就绪,请安装 HybridCLR 并等待编译完成。");
+        }
+        ApplyHybridCLRSettings?.Invoke(assembly);
+        Undo.RecordObject(settings, "Select hot-patch assembly");
+        settings.HotPatchAssemblyName = name;
+        EditorUtility.SetDirty(settings);
+    }
+}

+ 2 - 0
Editor/HotPatchAssemblySelection.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: cdcc205bab5052a44a57c25a77336bfb

+ 11 - 0
Editor/HotPatchResourceActions.cs

@@ -0,0 +1,11 @@
+using System;
+
+public static class HotPatchResourceActions
+{
+    public static Func<string> FindLatestResources;
+    public static Func<bool> IsBuildRunning;
+    public static Action<bool> ApplyResources;
+
+    public static string LatestDirectory => FindLatestResources?.Invoke();
+    public static bool IsBuilding => IsBuildRunning?.Invoke() ?? false;
+}

+ 2 - 0
Editor/HotPatchResourceActions.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 196d730f3033d4d4babbcbeb463bb7ad

+ 178 - 0
Editor/HotPatchSourceSync.cs

@@ -0,0 +1,178 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+using Newtonsoft.Json.Linq;
+using UnityEditor;
+using UnityEditor.Compilation;
+using UnityEngine;
+
+
+public static class HotPatchSourceSync
+{
+    public static string AssemblyName => AppSettings.RequireHotPatchAssemblyName();
+    public const string Begin = "#if UNITY_EDITOR";
+    public const string End = "#endif";
+    const string ManifestPath = "ProjectSettings/HotPatchSources.json";
+
+    public static void SyncMenu()
+    {
+        try { Synchronize(); Debug.Log("[热补丁] 源码同步完成,等待 Unity 编译。"); }
+        catch (Exception e) { Debug.LogException(e); }
+    }
+
+    public static string FindAssemblyPath()
+    {
+        var assembly = HotPatchAssemblySelection.Find(AssemblyName);
+        HotPatchAssemblySelection.Validate(assembly);
+        return AssetDatabase.GetAssetPath(assembly);
+    }
+
+    public static string RemoveEditorEnvelope(string source)
+    {
+        var text = source.TrimStart('\uFEFF').Replace("\r\n", "\n").Trim();
+        if (!text.StartsWith(Begin + "\n", StringComparison.Ordinal) || !text.EndsWith("\n" + End, StringComparison.Ordinal))
+            throw new InvalidDataException("Sources 脚本缺少热补丁最外层 UNITY_EDITOR 包装。");
+        var body = text.Substring(Begin.Length + 1, text.Length - Begin.Length - End.Length - 2);
+
+        int depth = 0;
+        foreach (var line in body.Split('\n'))
+        {
+            var directive = line.TrimStart();
+            if (directive.StartsWith("#if ", StringComparison.Ordinal)) depth++;
+            else if (directive.StartsWith("#endif", StringComparison.Ordinal))
+            { if (--depth < 0) throw new InvalidDataException("Sources 条件编译嵌套不正确。"); }
+        }
+        if (depth != 0) throw new InvalidDataException("Sources 条件编译未闭合。");
+        return body + "\n";
+    }
+
+    public static string PackageRoot => UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(AppSettings).Assembly)?.resolvedPath
+        ?? throw new InvalidOperationException("找不到 AppRuntimes 包。");
+
+    public static bool Synchronize(bool refresh = true)
+    {
+        if (EditorApplication.isPlayingOrWillChangePlaymode) throw new InvalidOperationException("请先退出 Play Mode。");
+        var asmPath = FindAssemblyPath();
+        var root = (Path.GetDirectoryName(asmPath) + "/HotPatch").Replace('\\', '/');
+        var sourceRoot = Path.Combine(PackageRoot, "Runtime/Sources");
+        var desired = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+        foreach (var source in Directory.GetFiles(sourceRoot, "*.cs", SearchOption.AllDirectories))
+        {
+            var relative = source.Substring(sourceRoot.Length + 1).Replace('\\', '/');
+            desired.Add(root + "/" + relative, RemoveEditorEnvelope(File.ReadAllText(source)));
+        }
+        if (desired.Count == 0) throw new InvalidOperationException("Sources 没有可复制的脚本。");
+        var previous = File.Exists(ManifestPath) ? JObject.Parse(File.ReadAllText(ManifestPath)) : new JObject();
+        var oldRoot = (string)previous["root"] ?? root;
+        RequireChild("Assets", oldRoot);
+        if (!oldRoot.EndsWith("/HotPatch", StringComparison.Ordinal) && !oldRoot.EndsWith("/Generated/HotPatch/Sources", StringComparison.Ordinal))
+            throw new InvalidDataException("旧生成目录不是热补丁目录。");
+        var owned = previous["files"] as JObject ?? new JObject();
+        foreach (var item in owned.Properties())
+        {
+            RequireChild(oldRoot, item.Name);
+            if (!item.Name.EndsWith(".cs", StringComparison.Ordinal)) throw new InvalidDataException("生成记录包含非脚本路径。");
+            if (File.Exists(item.Name) && Hash(File.ReadAllText(item.Name)) != (string)item.Value)
+                throw new InvalidOperationException("生成文件被手工修改,请先合并到 Sources: " + item.Name);
+        }
+        foreach (var item in desired)
+            if (File.Exists(item.Key) && owned[item.Key] == null && File.ReadAllText(item.Key) != item.Value)
+                throw new InvalidOperationException("热补丁目标文件冲突: " + item.Key);
+
+        var targetFolder = Path.GetDirectoryName(asmPath);
+        var names = new[] { "AppRuntimes", "ClientCrypto", "Https", "FBHandler", "DictionaryExtensions", "NativeAppInfo", "DeviceTimeZone" };
+        foreach (var file in Directory.GetFiles(targetFolder, "*.cs", SearchOption.AllDirectories))
+        {
+            if (owned[file.Replace('\\', '/')] != null) continue;
+            if (Path.GetFullPath(file).StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) continue;
+            if (CompilationPipeline.GetAssemblyNameFromScriptPath(file.Replace('\\', '/')) != AssemblyName) continue;
+            var text = File.ReadAllText(file);
+            if (names.Any(n => System.Text.RegularExpressions.Regex.IsMatch(text, @"\bclass\s+" + n + @"\b")))
+                throw new InvalidOperationException("发现重复业务类型,请移除旧副本: " + file);
+        }
+        var asm = JObject.Parse(File.ReadAllText(asmPath));
+        var references = ((JArray)asm["references"] ?? new JArray()).Values<string>().Where(r => !IsOldRuntimeReference(r)).ToList();
+        foreach (var reference in new[] { "AppRuntimes.Base", "UniTask", "UnityEngine.UI", "UniWebView-CSharp", "Unity.Advertisement.IosSupport" })
+            if (!references.Contains(reference)) references.Add(reference);
+        asm["references"] = new JArray(references); asm["autoReferenced"] = false;
+        desired[asmPath] = asm.ToString() + "\n";
+        var generatedManifest = new JObject();
+        foreach (var item in desired.Where(p => p.Key != asmPath)) generatedManifest[item.Key] = Hash(item.Value);
+
+        if (oldRoot != root)
+        {
+            foreach (var item in owned.Properties())
+            {
+                var destination = root + item.Name.Substring(oldRoot.Length);
+                if (!desired.ContainsKey(destination) || !File.Exists(item.Name + ".meta")) continue;
+                if (File.Exists(destination + ".meta")) throw new InvalidOperationException("迁移目标已有 GUID,请先处理冲突: " + destination);
+                desired[destination + ".meta"] = File.ReadAllText(item.Name + ".meta");
+            }
+        }
+        desired[ManifestPath] = new JObject { ["root"] = root, ["assemblyName"] = AssemblyName, ["files"] = generatedManifest }.ToString() + "\n";
+        var removed = owned.Properties().Select(p => p.Name).Where(p => !desired.ContainsKey(p)).ToArray();
+        var changes = desired.Where(p => !File.Exists(p.Key) || File.ReadAllText(p.Key) != p.Value).ToArray();
+        if (changes.Length == 0 && removed.Length == 0) return false;
+        var touched = changes.Select(p => p.Key).Concat(removed.SelectMany(p => new[] { p, p + ".meta" })).Distinct().ToArray();
+        var backups = touched.ToDictionary(p => p, p => File.Exists(p) ? File.ReadAllBytes(p) : null);
+        AssetDatabase.StartAssetEditing();
+        try
+        {
+            foreach (var change in changes)
+            { Directory.CreateDirectory(Path.GetDirectoryName(change.Key)); File.WriteAllText(change.Key, change.Value, new UTF8Encoding(false)); }
+            foreach (var path in removed)
+            { if (File.Exists(path)) File.Delete(path); if (File.Exists(path + ".meta")) File.Delete(path + ".meta"); }
+        }
+        catch
+        {
+            foreach (var backup in backups)
+                if (backup.Value == null) { if (File.Exists(backup.Key)) File.Delete(backup.Key); }
+                else File.WriteAllBytes(backup.Key, backup.Value);
+            throw;
+        }
+        finally { AssetDatabase.StopAssetEditing(); }
+        if (refresh) AssetDatabase.Refresh();
+        return true;
+    }
+
+    public static void VerifySynchronized()
+    {
+        var path = FindAssemblyPath();
+        var root = Path.GetDirectoryName(path) + "/HotPatch";
+        var sources = Path.Combine(PackageRoot, "Runtime/Sources");
+        var expected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+        foreach (var source in Directory.GetFiles(sources, "*.cs", SearchOption.AllDirectories))
+        {
+            var output = Path.Combine(root, source.Substring(sources.Length + 1));
+            expected.Add(Path.GetFullPath(output));
+            if (!File.Exists(output) || File.ReadAllText(output) != RemoveEditorEnvelope(File.ReadAllText(source)))
+                throw new InvalidOperationException("热补丁源码未同步,请执行 资源构建/一键打包资源。");
+        }
+        if (Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories).Any(p => !expected.Contains(Path.GetFullPath(p))))
+            throw new InvalidOperationException("HotPatch 目录包含过期或未托管脚本,请执行同步并处理冲突。");
+    }
+
+    static bool IsOldRuntimeReference(string value)
+    {
+        if (value == "AppRuntimes" || value == "AppRuntimes.Sources.Editor") return true;
+        if (!value.StartsWith("GUID:", StringComparison.Ordinal)) return false;
+        var path = AssetDatabase.GUIDToAssetPath(value.Substring(5));
+        if (!File.Exists(path)) return false;
+        var name = (string)JObject.Parse(File.ReadAllText(path))["name"];
+        return name == "AppRuntimes" || name == "AppRuntimes.Sources.Editor";
+    }
+
+    static void RequireChild(string root, string file)
+    {
+        if (!Path.GetFullPath(file).StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
+            throw new InvalidDataException("生成记录包含目录外路径。");
+    }
+    public static string Hash(string text)
+    {
+        using var hash = SHA256.Create();
+        return BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "").ToLowerInvariant();
+    }
+}

+ 1 - 4
Runtime/Scripts/ClientCrypto.cs.meta → Editor/HotPatchSourceSync.cs.meta

@@ -1,11 +1,8 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: c28df7daae70834419c5ab93a55a47f7
+guid: 6f2eb4ff214e4b43aada028d1ae0d825
 MonoImporter:
 MonoImporter:
   externalObjects: {}
   externalObjects: {}
   serializedVersion: 2
   serializedVersion: 2
   defaultReferences: []
   defaultReferences: []
   executionOrder: 0
   executionOrder: 0
   icon: {instanceID: 0}
   icon: {instanceID: 0}
-  userData: 
-  assetBundleName: 
-  assetBundleVariant: 

+ 7 - 7
Editor/LocalFacebookSdk.cs

@@ -24,14 +24,14 @@ internal static class LocalFacebookSdk
             if (importer == null || !importer.GetCompatibleWithPlatform(BuildTarget.iOS))
             if (importer == null || !importer.GetCompatibleWithPlatform(BuildTarget.iOS))
                 throw new BuildFailedException("Local Facebook SDK must be enabled for iOS: " + assetPath);
                 throw new BuildFailedException("Local Facebook SDK must be enabled for iOS: " + assetPath);
 
 
-            // PluginImporter exports and links the complete static XCFramework.
-            // Static archives must not be added to Embed Frameworks.
+                                                                                
+                                                                     
             string xcframework = Path.Combine(sdkRoot, module + ".xcframework");
             string xcframework = Path.Combine(sdkRoot, module + ".xcframework");
             if (!File.Exists(Path.Combine(xcframework, "Info.plist")))
             if (!File.Exists(Path.Combine(xcframework, "Info.plist")))
                 throw new BuildFailedException("Missing local Facebook XCFramework: " + xcframework);
                 throw new BuildFailedException("Missing local Facebook XCFramework: " + xcframework);
 
 
-            // Static linking does not copy framework resources. Preserve manifests
-            // in separate app resource bundles for Xcode privacy report aggregation.
+                                                                                   
+                                                                                     
             string manifest = Path.Combine(xcframework,
             string manifest = Path.Combine(xcframework,
                 "ios-arm64_arm64e/" + module + ".framework/PrivacyInfo.xcprivacy");
                 "ios-arm64_arm64e/" + module + ".framework/PrivacyInfo.xcprivacy");
             if (!File.Exists(manifest))
             if (!File.Exists(manifest))
@@ -68,8 +68,8 @@ internal static class LocalFacebookSdk
         project.SetBuildProperty(frameworkTarget, "CLANG_ENABLE_MODULES", "YES");
         project.SetBuildProperty(frameworkTarget, "CLANG_ENABLE_MODULES", "YES");
         project.SetBuildProperty(frameworkTarget, "SWIFT_VERSION", "5.0");
         project.SetBuildProperty(frameworkTarget, "SWIFT_VERSION", "5.0");
 
 
-        // Swift autolinking locates compatibility archives in the selected Xcode
-        // toolchain for either device or simulator; no hardcoded Xcode paths.
+                                                                                 
+                                                                              
         foreach (string target in new[] { mainTarget, frameworkTarget })
         foreach (string target in new[] { mainTarget, frameworkTarget })
         {
         {
             project.AddBuildProperty(target, "LIBRARY_SEARCH_PATHS", "$(inherited)");
             project.AddBuildProperty(target, "LIBRARY_SEARCH_PATHS", "$(inherited)");
@@ -81,7 +81,7 @@ internal static class LocalFacebookSdk
             project.AddBuildProperty(target, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks");
             project.AddBuildProperty(target, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks");
         }
         }
 
 
-        // Apply ARC only to our credentials bridge, preserving other plug-ins.
+                                                                               
         foreach (string sourcePath in project.GetRealPathsOfAllFiles(PBXSourceTree.Source))
         foreach (string sourcePath in project.GetRealPathsOfAllFiles(PBXSourceTree.Source))
         {
         {
             if (Path.GetFileName(sourcePath) != "FacebookDynamicCredentials.m")
             if (Path.GetFileName(sourcePath) != "FacebookDynamicCredentials.m")

+ 1 - 1
ThirdParty/GUPS/Editor.meta → Editor/PackageSetup.meta

@@ -1,5 +1,5 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: 9ba901855a2bb064b8b8eb05c8b21248
+guid: bca5d8c30dcac3e46bb608c18b537309
 folderAsset: yes
 folderAsset: yes
 DefaultImporter:
 DefaultImporter:
   externalObjects: {}
   externalObjects: {}

+ 8 - 0
Editor/PackageSetup/AppRuntimes.PackageSetup.Editor.asmdef

@@ -0,0 +1,8 @@
+{
+  "name": "AppRuntimes.PackageSetup.Editor",
+  "references": [],
+  "includePlatforms": ["Editor"],
+  "overrideReferences": true,
+  "precompiledReferences": [],
+  "autoReferenced": true
+}

+ 1 - 1
ThirdParty/GUPS/Editor/Source/GUPS.Editor.asmdef.meta → Editor/PackageSetup/AppRuntimes.PackageSetup.Editor.asmdef.meta

@@ -1,5 +1,5 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: abd131a95530e1a449fc8066dcb03a9f
+guid: a309ca78b741f4641a2cc8dbdb340e0d
 AssemblyDefinitionImporter:
 AssemblyDefinitionImporter:
   externalObjects: {}
   externalObjects: {}
   userData: 
   userData: 

+ 101 - 0
Editor/PackageSetup/EditorPackageInstaller.cs

@@ -0,0 +1,101 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UnityEditor;
+using UnityEditor.PackageManager;
+using UnityEditor.PackageManager.Requests;
+using UnityEngine;
+using PackageInfo = UnityEditor.PackageManager.PackageInfo;
+
+// All AppRuntimes package requests share one queue: UPM operations must be sequential.
+internal sealed class EditorPackageInstaller
+{
+    static readonly List<EditorPackageInstaller> Pending = new List<EditorPackageInstaller>();
+    static EditorPackageInstaller active;
+    static AddRequest request;
+    static double nextCheck;
+    readonly string name, url, label, key, retryHint;
+
+    internal EditorPackageInstaller(string name, string url, string label, string key, string retryHint)
+    {
+        this.name = name;
+        this.url = url;
+        this.label = label;
+        this.key = key;
+        this.retryHint = retryHint;
+    }
+
+    internal bool IsInstalled => PackageInfo.GetAllRegisteredPackages().Any(package => package.name == name);
+    internal bool IsInstalling => active == this || Pending.Contains(this) && !IsInstalled;
+    internal string LastError => SessionState.GetString(key + ".PackageError", "");
+
+    internal void Retry()
+    {
+        if (active == this || IsInstalled) return;
+        SessionState.EraseBool(key + ".PackageAttempted");
+        SessionState.EraseString(key + ".PackageError");
+        Schedule();
+    }
+
+    internal void Schedule()
+    {
+        if (!Pending.Contains(this)) Pending.Add(this);
+        nextCheck = EditorApplication.timeSinceStartup + 1;
+        EditorApplication.update -= Update;
+        EditorApplication.update += Update;
+    }
+
+    static void Update()
+    {
+        if (request != null)
+        {
+            if (!request.IsCompleted) return;
+            var completed = request;
+            var installer = active;
+            request = null;
+            active = null;
+            if (completed.Status == StatusCode.Success)
+            {
+                SessionState.EraseString(installer.key + ".PackageError");
+                Debug.Log("[AppRuntimes] " + installer.label + " package installed. Wait for compilation to finish.");
+            }
+            else installer.ReportFailure(completed.Error?.message ?? "Package Manager did not return an error message.");
+            nextCheck = EditorApplication.timeSinceStartup + 1;
+            return;
+        }
+        if (Pending.Count == 0)
+        {
+            EditorApplication.update -= Update;
+            return;
+        }
+        if (EditorApplication.timeSinceStartup < nextCheck || EditorApplication.isCompiling || EditorApplication.isUpdating ||
+            EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer) return;
+        var next = Pending[0];
+        Pending.RemoveAt(0);
+        if (next.IsInstalled)
+        {
+            SessionState.EraseString(next.key + ".PackageError");
+            return;
+        }
+        if (SessionState.GetBool(next.key + ".PackageAttempted", false)) return;
+        SessionState.SetBool(next.key + ".PackageAttempted", true);
+        try
+        {
+            Debug.Log("[AppRuntimes] Installing the missing " + next.label + " package: " + next.url);
+            active = next;
+            request = Client.Add(next.url);
+        }
+        catch (Exception exception)
+        {
+            active = null;
+            next.ReportFailure(exception.Message);
+        }
+    }
+
+    void ReportFailure(string message)
+    {
+        SessionState.SetString(key + ".PackageError", message);
+        Debug.LogWarning("[AppRuntimes] " + label + " package installation failed: " + message +
+            "\n" + retryHint + " Or add this Git URL in Package Manager: " + url);
+    }
+}

+ 2 - 0
Editor/PackageSetup/EditorPackageInstaller.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 923581a47d8a4f129961090dedc348b5

+ 16 - 0
Editor/PackageSetup/HybridCLRPackageSetup.cs

@@ -0,0 +1,16 @@
+using UnityEditor;
+
+[InitializeOnLoad]
+public static class HybridCLRPackageSetup
+{
+    public const string PackageName = "com.code-philosophy.hybridclr";
+    public const string PackageUrl = "https://gitee.com/focus-creative-games/hybridclr_unity.git#v9.0.3";
+    static readonly EditorPackageInstaller Installer = new EditorPackageInstaller(
+        PackageName, PackageUrl, "HybridCLR", "AppRuntimes.HybridCLR", "Open AppSettings and retry.");
+
+    static HybridCLRPackageSetup() => Installer.Schedule();
+    public static bool IsInstalled => Installer.IsInstalled;
+    public static bool IsInstalling => Installer.IsInstalling;
+    public static string LastError => Installer.LastError;
+    public static void RetryInstallation() => Installer.Retry();
+}

+ 2 - 0
Editor/PackageSetup/HybridCLRPackageSetup.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fe9a0cb0483b5094e92d93015d00e6e2

+ 60 - 0
Editor/PackageSetup/LaunchTemplateSetup.cs

@@ -0,0 +1,60 @@
+using System;
+using System.IO;
+using UnityEditor;
+using UnityEngine;
+using PackageInfo = UnityEditor.PackageManager.PackageInfo;
+
+public static class LaunchTemplateSetup
+{
+    [MenuItem("AppSettings/Load Launch Templates", false, 100)]
+    public static void LoadLaunchTemplates()
+    {
+        try { EnsureLaunchTemplate(); }
+        catch (Exception exception) { Debug.LogError("[AppRuntimes] Could not install the Launch template: " + exception.Message); }
+    }
+
+    [MenuItem("AppSettings/Load Launch Templates", true, 100)]
+    static bool CanLoadLaunchTemplates() => !EditorApplication.isCompiling && !EditorApplication.isUpdating
+        && !EditorApplication.isPlayingOrWillChangePlaymode && !BuildPipeline.isBuildingPlayer;
+
+    public static void EnsureLaunchTemplate()
+    {
+        const string destination = "Assets/Launch";
+        if (Directory.Exists(destination))
+        {
+            Debug.Log("[AppRuntimes] Assets/Launch already exists; its contents were preserved.");
+            return;
+        }
+        var package = PackageInfo.FindForAssembly(typeof(LaunchTemplateSetup).Assembly)
+            ?? throw new InvalidOperationException("AppRuntimes must be installed through Package Manager.");
+        if (CopyIfMissing(Path.Combine(package.resolvedPath, "Templates~/Launch"), destination))
+        {
+            AssetDatabase.Refresh();
+            Debug.Log("[AppRuntimes] Copied the Launch template to Assets/Launch.");
+        }
+    }
+
+    internal static bool CopyIfMissing(string source, string destination)
+    {
+        if (Directory.Exists(destination)) return false;
+        if (!Directory.Exists(source)) throw new DirectoryNotFoundException("Launch template missing: " + source);
+        // Stage outside Assets so an interrupted copy cannot leave a partially imported Launch.
+        var staging = Path.Combine("Library", "AppRuntimesLaunch-" + Guid.NewGuid().ToString("N"));
+        try
+        {
+            CopyDirectory(source, staging);
+            Directory.Move(staging, destination);
+            if (File.Exists(source + ".meta") && !File.Exists(destination + ".meta"))
+                File.Copy(source + ".meta", destination + ".meta");
+            return true;
+        }
+        finally { if (Directory.Exists(staging)) Directory.Delete(staging, true); }
+    }
+
+    static void CopyDirectory(string source, string destination)
+    {
+        Directory.CreateDirectory(destination);
+        foreach (var file in Directory.GetFiles(source)) File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));
+        foreach (var directory in Directory.GetDirectories(source)) CopyDirectory(directory, Path.Combine(destination, Path.GetFileName(directory)));
+    }
+}

+ 2 - 0
Editor/PackageSetup/LaunchTemplateSetup.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8d17117798634c86a8ca41379291cb08

+ 29 - 0
Editor/PackageSetup/UnityMcpPackageSetup.cs

@@ -0,0 +1,29 @@
+using UnityEditor;
+using UnityEngine;
+
+public static class UnityMcpPackageSetup
+{
+    public const string PackageName = "com.coplaydev.unity-mcp";
+    public const string PackageUrl = "https://github.com/CoplayDev/unity-mcp.git?path=/MCPForUnity#main";
+    static readonly EditorPackageInstaller Installer = new EditorPackageInstaller(
+        PackageName, PackageUrl, "Unity MCP", "AppRuntimes.UnityMcp", "Use AppSettings/Install Unity MCP.");
+
+    public static bool IsInstalled => Installer.IsInstalled;
+    public static bool IsInstalling => Installer.IsInstalling;
+    public static string LastError => Installer.LastError;
+
+    [MenuItem("AppSettings/Install Unity MCP", false, 101)]
+    public static void Install()
+    {
+        if (IsInstalled)
+        {
+            Debug.Log("[AppRuntimes] Unity MCP is already installed.");
+            return;
+        }
+        Installer.Retry();
+    }
+
+    [MenuItem("AppSettings/Install Unity MCP", true, 101)]
+    static bool CanInstall() => !IsInstalling && !EditorApplication.isCompiling && !EditorApplication.isUpdating
+        && !EditorApplication.isPlayingOrWillChangePlaymode && !BuildPipeline.isBuildingPlayer;
+}

+ 2 - 0
Editor/PackageSetup/UnityMcpPackageSetup.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 82735eec79a64c8fb060adc65fc2a45c

+ 184 - 0
Editor/S3ResourceUploader.cs

@@ -0,0 +1,184 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Xml.Linq;
+
+public sealed class S3UploadFile
+{
+    public string LocalPath;
+    public string Key;
+    public long Size;
+    public bool IsManifest => Path.GetFileName(Key).Equals("manifest.json", StringComparison.OrdinalIgnoreCase)
+        || Path.GetFileName(Key).Equals("manifest_hot.json", StringComparison.OrdinalIgnoreCase);
+}
+
+public static class S3ResourceUploader
+{
+    public static string TargetPrefix(string downloadUrl)
+    {
+        if (string.IsNullOrWhiteSpace(downloadUrl))
+            throw new ArgumentException("请先填写 DownloadUrl,再上传资源。");
+        if (!Uri.TryCreate(downloadUrl, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http"))
+            throw new ArgumentException("DownloadUrl 必须是 HTTP(S) 地址。");
+        var segments = uri.AbsolutePath.Trim('/').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList();
+        if (segments.Count > 0 && segments.Last().EndsWith(".json", StringComparison.OrdinalIgnoreCase)) segments.RemoveAt(segments.Count - 1);
+        if (segments.Count == 0) throw new ArgumentException("DownloadUrl 必须包含上传目标目录,不能是域名根路径。");
+        var prefix = Uri.UnescapeDataString(segments.Last());
+        if (prefix == "." || prefix == ".." || prefix.Any(c => c == '/' || c == '\\' || char.IsControl(c)))
+            throw new ArgumentException("DownloadUrl 最后一级目录不合法。");
+        return prefix;
+    }
+
+    public static List<S3UploadFile> CreatePlan(string directory, string prefix)
+    {
+        var root = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
+        if (root.Length == 0 || root.EndsWith(":")) root += Path.DirectorySeparatorChar;
+        var rootPrefix = root.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
+        if (!Directory.Exists(root)) throw new DirectoryNotFoundException("上传目录不存在。");
+        var files = new List<S3UploadFile>();
+        Visit(root);
+        foreach (var file in files)
+            if (Encoding.UTF8.GetByteCount(file.Key) > 1024 || file.Key.Contains("\\") || file.Key.Any(char.IsControl) || file.Key.Split('/').Any(p => p == "." || p == ".."))
+                throw new IOException("S3 对象路径不合法或超过 1024 字节: " + file.Key);
+        return files.OrderBy(f => f.IsManifest ? 1 : 0).ThenBy(f => f.Key, StringComparer.Ordinal).ToList();
+
+        void Visit(string current)
+        {
+            if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0)
+                throw new IOException("上传目录包含符号链接,请使用实际目录: " + current);
+            var entries = Directory.GetFileSystemEntries(current);
+            if (entries.Length == 0)
+            {
+                var relative = current.Length == root.Length ? "" : current.Substring(rootPrefix.Length).Replace('\\', '/') + "/";
+                files.Add(new S3UploadFile { Key = prefix + "/" + relative });
+            }
+            foreach (var path in entries)
+            {
+                var attributes = File.GetAttributes(path);
+                if ((attributes & FileAttributes.ReparsePoint) != 0) throw new IOException("上传目录包含符号链接: " + path);
+                if ((attributes & FileAttributes.Directory) != 0) { Visit(path); continue; }
+                long size = new FileInfo(path).Length;
+                if (size > 5L * 1024 * 1024 * 1024) throw new IOException("单个文件超过 5 GiB,不能直接上传: " + path);
+                files.Add(new S3UploadFile { LocalPath = path, Key = prefix + "/" + path.Substring(rootPrefix.Length).Replace('\\', '/'), Size = size });
+            }
+        }
+    }
+
+    public static string EncodePath(string path) => string.Join("/", path.Split('/').Select(Uri.EscapeDataString));
+
+    public static string Authorization(string method, string canonicalPath, string query, IDictionary<string, string> headers,
+        string payloadHash, string region, S3UploadCredentials credentials, DateTime utc)
+    {
+        var sorted = headers.OrderBy(h => h.Key, StringComparer.Ordinal).ToArray();
+        var signedHeaders = string.Join(";", sorted.Select(h => h.Key));
+        var canonicalHeaders = string.Concat(sorted.Select(h => h.Key + ":" + h.Value.Trim() + "\n"));
+        var canonical = method + "\n" + canonicalPath + "\n" + query + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + payloadHash;
+        var date = utc.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
+        var scope = date + "/" + region + "/s3/aws4_request";
+        var toSign = "AWS4-HMAC-SHA256\n" + utc.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture) + "\n" + scope + "\n" + Hash(Encoding.UTF8.GetBytes(canonical));
+        var key = Hmac(Hmac(Hmac(Hmac(Encoding.UTF8.GetBytes("AWS4" + credentials.SecretKey.Trim()), date), region), "s3"), "aws4_request");
+        return "AWS4-HMAC-SHA256 Credential=" + credentials.AccessKey.Trim() + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + Hex(Hmac(key, toSign));
+    }
+
+    public static async Task UploadAsync(IReadOnlyList<S3UploadFile> files, string bucket, string region,
+        S3UploadCredentials credentials, Action<int, string, long, long> progress, CancellationToken cancellationToken, HttpMessageHandler transport = null)
+    {
+        S3UploadSettings.ValidateDestination(bucket, region);
+        S3UploadSettings.ValidateCredentials(credentials);
+        using var handler = transport ?? new HttpClientHandler { AllowAutoRedirect = false };
+        using var client = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
+        long total = files.Sum(f => f.Size), completed = 0;
+        for (int index = 0; index < files.Count; index++)
+        {
+            cancellationToken.ThrowIfCancellationRequested();
+            var file = files[index];
+            progress?.Invoke(index, file.Key, completed, total);
+            for (int attempt = 0; ; attempt++)
+            {
+                try
+                {
+                    using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+                    timeout.CancelAfter(TimeSpan.FromMinutes(30));
+                    using Stream stream = file.LocalPath == null ? new MemoryStream() : new FileStream(file.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, true);
+                    if (stream.Length != file.Size) throw new IOException("文件在上传前发生改变,请重新选择目录: " + file.Key);
+                    var payloadHash = await HashAsync(stream, timeout.Token).ConfigureAwait(false);
+                    stream.Position = 0;
+                    var host = "s3." + region + ".amazonaws.com";
+                    var path = "/" + bucket + "/" + EncodePath(file.Key);
+                    var now = DateTime.UtcNow;
+                    var headers = new Dictionary<string, string>
+                    {
+                        { "host", host }, { "x-amz-content-sha256", payloadHash },
+                        { "x-amz-date", now.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture) }
+                    };
+                    if (!string.IsNullOrWhiteSpace(credentials.SessionToken)) headers.Add("x-amz-security-token", credentials.SessionToken.Trim());
+                    using var request = new HttpRequestMessage(HttpMethod.Put, "https://" + host + path);
+                    request.Content = new ProgressContent(stream, bytes => progress?.Invoke(index, file.Key, completed + bytes, total), timeout.Token);
+                    request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(file.Key.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ? "application/json" : "application/octet-stream");
+                    request.Headers.TryAddWithoutValidation("Cache-Control", file.IsManifest ? "no-cache, max-age=0, must-revalidate" : "no-cache");
+                    foreach (var header in headers) request.Headers.TryAddWithoutValidation(header.Key, header.Value);
+                    request.Headers.TryAddWithoutValidation("Authorization", Authorization("PUT", path, "", headers, payloadHash, region, credentials, now));
+                    using var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, timeout.Token).ConfigureAwait(false);
+                    if (!response.IsSuccessStatusCode)
+                    {
+                        if (attempt < 2 && ((int)response.StatusCode >= 500 || (int)response.StatusCode == 429))
+                        { await Task.Delay(1000 * (attempt + 1), cancellationToken).ConfigureAwait(false); continue; }
+                        var code = "Unknown";
+                        try { code = XDocument.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Root?.Element("Code")?.Value ?? code; }
+                        catch (System.Xml.XmlException) { }
+                        if (!System.Text.RegularExpressions.Regex.IsMatch(code, @"\A[A-Za-z0-9]+\z")) code = "Unknown";
+                        throw new IOException("S3 上传失败: HTTP " + (int)response.StatusCode + " / " + code + " / " + file.Key);
+                    }
+                    break;
+                }
+                catch (HttpRequestException) when (attempt < 2)
+                { await Task.Delay(1000 * (attempt + 1), cancellationToken).ConfigureAwait(false); }
+            }
+            completed += file.Size;
+            progress?.Invoke(index + 1, file.Key, completed, total);
+        }
+    }
+
+    static async Task<string> HashAsync(Stream stream, CancellationToken token)
+    {
+        using var sha = SHA256.Create();
+        var buffer = new byte[81920];
+        int count;
+        while ((count = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0)
+            sha.TransformBlock(buffer, 0, count, buffer, 0);
+        sha.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
+        return Hex(sha.Hash);
+    }
+
+    public static string Hash(byte[] bytes) { using var sha = SHA256.Create(); return Hex(sha.ComputeHash(bytes)); }
+    static string Hex(byte[] bytes) => BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant();
+    static byte[] Hmac(byte[] key, string text) { using var hmac = new HMACSHA256(key); return hmac.ComputeHash(Encoding.UTF8.GetBytes(text)); }
+
+    sealed class ProgressContent : HttpContent
+    {
+        readonly Stream source;
+        readonly Action<long> progress;
+        readonly CancellationToken token;
+        public ProgressContent(Stream source, Action<long> progress, CancellationToken token)
+        { this.source = source; this.progress = progress; this.token = token; }
+        protected override bool TryComputeLength(out long length) { length = source.Length; return true; }
+        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
+        {
+            var buffer = new byte[81920];
+            int count; long sent = 0;
+            while ((count = await source.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0)
+            {
+                await stream.WriteAsync(buffer, 0, count, token).ConfigureAwait(false);
+                sent += count; progress?.Invoke(sent);
+            }
+        }
+    }
+}

+ 2 - 0
Editor/S3ResourceUploader.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8e55b87f63af90e4189e716c68064ab6

+ 85 - 0
Editor/S3UploadController.cs

@@ -0,0 +1,85 @@
+using System;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using UnityEditor;
+using UnityEngine;
+
+public static class S3UploadController
+{
+    public static bool IsUploading { get; private set; }
+    static CancellationTokenSource cancellation;
+    static readonly object progressLock = new object();
+    static string currentKey;
+    static long sentBytes, totalBytes;
+    static int completedFiles, totalFiles;
+    static double nextProgress;
+
+    public static async void ChooseAndUpload(string downloadUrl)
+    {
+        if (IsUploading || HotPatchResourceActions.IsBuilding || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer) return;
+        bool locked = false;
+        try
+        {
+            var latest = HotPatchResourceActions.LatestDirectory;
+            if (string.IsNullOrEmpty(latest)) throw new InvalidOperationException("没有可用的最近打包资源,请先执行一键打包资源。");
+            var prefix = S3ResourceUploader.TargetPrefix(downloadUrl);
+            var configuration = S3UploadSettings.LoadConfiguration();
+            var bucket = configuration.Bucket;
+            var region = configuration.Region;
+            S3UploadSettings.ValidateDestination(bucket, region);
+            var credentials = S3UploadSettings.LoadCredentials();
+            S3UploadSettings.ValidateCredentials(credentials);
+            var directory = EditorUtility.OpenFolderPanel("选择上传资源文件夹", latest, "");
+            if (string.IsNullOrEmpty(directory)) return;
+            var files = S3ResourceUploader.CreatePlan(directory, prefix);
+            EditorPrefs.SetString("AppRuntimes.S3.LastFolder", directory);
+            IsUploading = true;
+            cancellation = new CancellationTokenSource();
+            totalFiles = files.Count; completedFiles = 0; sentBytes = totalBytes = 0; currentKey = "准备上传"; nextProgress = 0;
+            EditorApplication.LockReloadAssemblies(); locked = true;
+            EditorApplication.update += ShowProgress;
+            EditorApplication.quitting += Cancel;
+            EditorApplication.playModeStateChanged += OnPlayMode;
+            Debug.Log("[资源上传] 开始上传到 s3://" + bucket + "/" + prefix + "/,对象数: " + files.Count);
+            await Task.Run(() => S3ResourceUploader.UploadAsync(files, bucket, region, credentials, SetProgress, cancellation.Token));
+            EditorApplication.update -= ShowProgress;
+            Debug.Log("[资源上传] 上传完成: s3://" + bucket + "/" + prefix + "/");
+            EditorUtility.ClearProgressBar();
+            EditorUtility.DisplayDialog("上传资源", "上传完成,共 " + files.Count + " 个对象。\ns3://" + bucket + "/" + prefix + "/", "确定");
+        }
+        catch (OperationCanceledException) { Debug.LogWarning("[资源上传] 上传已取消或请求超时,可重新上传。"); }
+        catch (Exception exception)
+        {
+            EditorApplication.update -= ShowProgress;
+            Debug.LogError("[资源上传] " + exception.Message);
+            EditorUtility.ClearProgressBar();
+            EditorUtility.DisplayDialog("上传资源失败", exception.Message, "确定");
+        }
+        finally
+        {
+            EditorApplication.update -= ShowProgress;
+            EditorApplication.quitting -= Cancel;
+            EditorApplication.playModeStateChanged -= OnPlayMode;
+            EditorUtility.ClearProgressBar();
+            cancellation?.Dispose(); cancellation = null;
+            IsUploading = false;
+            if (locked) EditorApplication.UnlockReloadAssemblies();
+        }
+    }
+
+    static void SetProgress(int count, string key, long sent, long total)
+    { lock (progressLock) { completedFiles = count; currentKey = key; sentBytes = sent; totalBytes = total; } }
+    static void ShowProgress()
+    {
+        if (EditorApplication.timeSinceStartup < nextProgress) return;
+        nextProgress = EditorApplication.timeSinceStartup + .1;
+        lock (progressLock)
+        {
+            var progress = totalBytes > 0 ? (float)((double)sentBytes / totalBytes) : (float)completedFiles / Math.Max(1, totalFiles);
+            if (EditorUtility.DisplayCancelableProgressBar("上传资源到 S3", completedFiles + "/" + totalFiles + "  " + currentKey, progress)) Cancel();
+        }
+    }
+    static void Cancel() => cancellation?.Cancel();
+    static void OnPlayMode(PlayModeStateChange state) { if (state == PlayModeStateChange.ExitingEditMode) Cancel(); }
+}

+ 2 - 0
Editor/S3UploadController.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 18ff799cfb1eee846bf86d9f140fcfb4

+ 73 - 0
Editor/S3UploadSettings.cs

@@ -0,0 +1,73 @@
+using System;
+using System.IO;
+using System.Text.RegularExpressions;
+using UnityEngine;
+
+public sealed class S3UploadCredentials
+{
+    public string AccessKey;
+    public string SecretKey;
+    public string SessionToken;
+}
+
+[Serializable]
+public sealed class S3UploadConfiguration
+{
+    public string Bucket = "ios-games";
+    public string Region = "us-east-1";
+    public string AccessKey = "";
+    public string SecretKey = "";
+    public string SessionToken = "";
+}
+
+public static class S3UploadSettings
+{
+    const string MissingConfigurationMessage = "请在 AppRuntimes 包的 Editor/Config/S3UploadSettings.json 中配置 S3 上传参数。";
+    public static string ConfigurationPath => AppHelpPackagePaths.FullPath("Editor/Config/S3UploadSettings.json");
+    public static string Bucket => LoadConfiguration().Bucket;
+    public static string Region => LoadConfiguration().Region;
+
+    public static S3UploadConfiguration LoadConfiguration()
+    {
+        if (!File.Exists(ConfigurationPath)) throw new InvalidOperationException(MissingConfigurationMessage);
+        try
+        {
+            return JsonUtility.FromJson<S3UploadConfiguration>(File.ReadAllText(ConfigurationPath))
+                ?? throw new InvalidOperationException(MissingConfigurationMessage);
+        }
+        catch (Exception)
+        {
+            // Do not include JSON contents in diagnostics: this file contains credentials.
+            throw new InvalidOperationException("无法读取包内 S3 配置,请检查 Editor/Config/S3UploadSettings.json。");
+        }
+    }
+
+    public static S3UploadCredentials LoadCredentials()
+    {
+        var configuration = LoadConfiguration();
+        return new S3UploadCredentials
+        {
+            AccessKey = configuration.AccessKey?.Trim(),
+            SecretKey = configuration.SecretKey?.Trim(),
+            SessionToken = configuration.SessionToken?.Trim()
+        };
+    }
+
+    public static void ValidateCredentials(S3UploadCredentials credentials)
+    {
+        if (credentials == null || string.IsNullOrWhiteSpace(credentials.AccessKey) || string.IsNullOrWhiteSpace(credentials.SecretKey))
+            throw new InvalidOperationException(MissingConfigurationMessage);
+        foreach (var value in new[] { credentials.AccessKey, credentials.SecretKey, credentials.SessionToken })
+            if (value != null && (value.Contains("\n") || value.Contains("\r"))) throw new ArgumentException("AWS credentials must not contain line breaks.");
+    }
+
+    public static void ValidateDestination(string bucket, string region)
+    {
+        if (string.IsNullOrWhiteSpace(bucket) || string.IsNullOrWhiteSpace(region))
+            throw new ArgumentException(MissingConfigurationMessage);
+        if (!Regex.IsMatch(bucket, @"\A[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]\z") || bucket.Contains(".."))
+            throw new ArgumentException("S3 Bucket 格式不正确。");
+        if (!Regex.IsMatch(region, @"\A[a-z]{2}(?:-[a-z]+)+-\d+\z"))
+            throw new ArgumentException("S3 Region 格式不正确。");
+    }
+}

+ 2 - 0
Editor/S3UploadSettings.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2a881bf1a44b9964da539bf34a3072db

+ 8 - 8
Editor/XcodePluginLayout.cs

@@ -9,7 +9,7 @@ using UnityEditor.iOS.Xcode;
 
 
 internal static class XcodePluginLayout
 internal static class XcodePluginLayout
 {
 {
-    private const string PackageName = "come.app.runtimes";
+    private static string PackageName => AppHelpPackagePaths.Name;
     private static readonly string[] ExportRoots = { "Frameworks", "Libraries" };
     private static readonly string[] ExportRoots = { "Frameworks", "Libraries" };
     private static readonly string[] PackageFolders = { "Runtime", "ThirdParty" };
     private static readonly string[] PackageFolders = { "Runtime", "ThirdParty" };
 
 
@@ -19,8 +19,8 @@ internal static class XcodePluginLayout
         var project = new PBXProject();
         var project = new PBXProject();
         project.ReadFromFile(projectPath);
         project.ReadFromFile(projectPath);
 
 
-        // Work on Unity's canonical serialization. Keep all file/build GUIDs, target
-        // memberships, embed settings and per-file compiler flags intact.
+
+
         string projectText = FlattenGroups(project.WriteToString());
         string projectText = FlattenGroups(project.WriteToString());
         var moves = new List<KeyValuePair<string, string>>();
         var moves = new List<KeyValuePair<string, string>>();
         foreach (string root in ExportRoots)
         foreach (string root in ExportRoots)
@@ -45,8 +45,8 @@ internal static class XcodePluginLayout
             }
             }
         }
         }
 
 
-        // Check every collision before changing the export. Identical files from
-        // an append export are safe; different files require a clean export folder.
+
+
         var destinations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
         var destinations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
         foreach (var move in moves)
         foreach (var move in moves)
         {
         {
@@ -56,12 +56,12 @@ internal static class XcodePluginLayout
                     + ". Export to an empty folder or remove the conflicting plugin.");
                     + ". Export to an empty folder or remove the conflicting plugin.");
         }
         }
 
 
-        // Validate the rewritten project before moving any files.
+
         project.ReadFromString(projectText);
         project.ReadFromString(projectText);
         foreach (var move in moves)
         foreach (var move in moves)
         {
         {
             Directory.CreateDirectory(Path.GetDirectoryName(move.Value));
             Directory.CreateDirectory(Path.GetDirectoryName(move.Value));
-            if (File.Exists(move.Value)) File.Delete(move.Key); // Identical, checked above.
+            if (File.Exists(move.Value)) File.Delete(move.Key);
             else File.Move(move.Key, move.Value);
             else File.Move(move.Key, move.Value);
         }
         }
         foreach (string root in ExportRoots)
         foreach (string root in ExportRoots)
@@ -137,7 +137,7 @@ internal static class XcodePluginLayout
 
 
     private static bool FilesEqual(string first, string second)
     private static bool FilesEqual(string first, string second)
     {
     {
-        // Unity's Mono FileStream needs the extended prefix for deep XCFramework paths on Windows.
+
         if (Path.DirectorySeparatorChar == '\\')
         if (Path.DirectorySeparatorChar == '\\')
         {
         {
             first = @"\\?\" + Path.GetFullPath(first);
             first = @"\\?\" + Path.GetFullPath(first);

+ 2 - 2
Editor/XcodePostprocessor.cs

@@ -42,13 +42,13 @@ public static class XcodePostprocessor
         string frameworkTarget = project.GetUnityFrameworkTargetGuid();
         string frameworkTarget = project.GetUnityFrameworkTargetGuid();
         LocalFacebookSdk.Configure(project, mainTarget, frameworkTarget, buildPath);
         LocalFacebookSdk.Configure(project, mainTarget, frameworkTarget, buildPath);
 
 
-        // Swift Runtime 必须放在 App 的 Frameworks 目录。
+                                                  
         project.SetBuildProperty(
         project.SetBuildProperty(
             mainTarget,
             mainTarget,
             "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES",
             "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES",
             "YES");
             "YES");
 
 
-        // 禁止放进 UnityFramework.framework/Frameworks。
+                                                    
         project.SetBuildProperty(
         project.SetBuildProperty(
             frameworkTarget,
             frameworkTarget,
             "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES",
             "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES",

+ 10 - 102
README.md

@@ -1,111 +1,19 @@
-# AppRuntimes
+# app_runtimes_hot
 
 
-Technical Name:`come.app.runtimes`;Display Name:`AppRuntimes`;Unity 基线:6000.3。
+Unity AppRuntimes package with a HybridCLR hot patch module.
 
 
-## 本地开发
+After importing AppRuntimes through Package Manager, the Editor automatically installs the missing `com.code-philosophy.hybridclr` package from the official Git mirror at `v9.0.3`. Existing HybridCLR installations are preserved. AppSettings shows installation status and a retry button if installation fails. See [package installation](Documentation~/HotPatch.md#package-installation) for details.
 
 
-本仓库是 UPM 包。使用 Unity 工程作为开发宿主,在 Package Manager 选择 **Install package from disk**,选中本仓库根目录的 `package.json`。在 Unity 的 Packages/AppRuntimes 中编辑脚本或资源,修改会保存到本仓库。
+Select **AppSettings/Install Unity MCP** to install missing [Unity MCP](https://github.com/CoplayDev/unity-mcp) from `https://github.com/CoplayDev/unity-mcp.git?path=/MCPForUnity#main`. Unity MCP installation is manual; startup and status checks never schedule it. Package installations run sequentially and preserve existing versions. Use **AppSettings/Load Launch Templates** to copy `Templates~/Launch` into `Assets/Launch`, including the scene, script, assembly definition and their metadata. An existing Launch folder is preserved. Launch is not copied automatically at startup. The AppSettings menu lists **Open Settings** first, followed by a separator, **Load Launch Templates**, then **Install Unity MCP**.
 
 
-`unity_ab_framework` 与本仓库同级时,宿主的 `Packages/manifest.json` 使用:
+AppSettings includes 上传资源 for recursive S3 uploads. This internal package stores shared S3 configuration in `Editor/Config/S3UploadSettings.json`; AppSettings has no S3 configuration form. See the [S3 upload guide](Documentation~/S3Upload.md) for configuration, destination paths, and manifest publication order.
 
 
-```json
-"come.app.runtimes": "file:../../app_runtimes"
-```
+Save adds missing `AppRuntimes.Base` and `Unity.Advertisement.IosSupport` references to the selected game assembly. 一键打包资源 remains disabled until the assembly and game scene are saved and both references are present. Unsaved assembly/scene selections also disable the window button.
 
 
-路径相对于宿主的 `Packages` 文件夹,参见 [Unity 本地包路径说明](https://docs.unity.com/en-us/engine/6000.3/manual/packages-list/dependencies-lp/upm-localpath)。
+The [Hot Patch guide](Documentation~/HotPatch.md) covers the Sources wrapper, original and update resource builds, DownloadUrl, and incremental resource updates.
 
 
-新增资源后等待 Unity 导入,资源和生成的 `.meta` 一起提交。在 Unity 中移动或重命名资源以保留 GUID;在文件管理器中操作时必须同时移动对应 `.meta`。不要删除或重新生成已有 `.meta`。
+Application code stays in `Runtime/Sources`, where `UNITY_EDITOR` excludes it from Player compilation. Select the hot patch assembly in AppSettings and click Save to synchronize HybridCLR settings. Original builds check Install and Generate/All, then delete the target HotPatch directory. Update builds copy changed Sources into that directory and remove only the outer wrapper. The loader uses the saved assembly name to load the DLL, then scans for and invokes methods marked with HotPatchInitializer. The original DLL does not require an initializer. NativeApi.cs in AppRuntimes.Base contains only AppInfo, TimeZone, and Dialog; other SDKs retain their own AOT native interfaces.
 
 
-## Git 安装与升级
+The 资源构建 menu contains only 一键打包资源. It builds both original and update resources into `Build/HotUpdate/AllRes_<timestamp>`, keeps only original resources in StreamingAssets, and removes the generated HotPatch sources before publishing. Launch extracts original resources into a temporary cache, compares the remote manifest, and downloads changed resources.
 
 
-提交并推送包内容后,其他项目可通过 Git URL 安装:
-
-```text
-https://git.usgamewin.com/ios-games/app_runtimes.git
-```
-
-发布时更新 `package.json` 版本和 CHANGELOG,提交并创建对应标签,再让使用工程固定标签,例如发布 `v1.0.0` 后使用 `https://git.usgamewin.com/ios-games/app_runtimes.git#v1.0.0`。本仓库根目录就是包根目录,无需 `?path=`。
-
-## 依赖与平台
-
-内置 UniTask 2.5.11、UniWebView 6.8.1、Facebook SDK、EDM4U 1.2.187、GUPS/Obfuscator。保留各 SDK 原有平台代码、原生插件和导入设置,包括 Android、iOS、Windows 与 macOS 相关内容;没有将运行时程序集限制到 iOS。DOTween 本体、设置、宏及 UniTask DOTween 适配均已移除。
-
-仅声明以下直接依赖:
-
-| 依赖 | 用途 |
-| --- | --- |
-| `com.unity.ads.ios-support` | iOS ATT 授权 |
-| `com.unity.nuget.newtonsoft-json` | JSON 接口数据 |
-| `com.unity.ugui` | Loading 和对话框 UI |
-| `com.unity.modules.androidjni` | Android 原生桥接及 SDK |
-| `com.unity.modules.imageconversion` | UniWebView 截图、Facebook 图片处理 |
-| `com.unity.modules.jsonserialize` | SDK 的 JsonUtility |
-| `com.unity.modules.unitywebrequest` | HTTP 请求 |
-
-UI/IMGUI 模块由 UGUI 间接引入。Input System 和 Addressables 按接入项目需要安装,适配程序集按包是否存在启用;不会更改项目的 Active Input Handling。UniTask 的物理、粒子、AssetBundle 等适配沿用上游条件编译。
-
-避免在接入工程再次安装同一份 UniTask、UniWebView、Facebook SDK、EDM4U 或 GUPS,以免出现重复程序集或 GUID。第三方组件的原有许可证继续适用,见 [Third Party Notices](Third%20Party%20Notices.md)。
-
-Android 的 Facebook Maven 依赖由保留的 EDM4U/Gradle 解析;AndroidManifest、Gradle 模板属于接入工程。iOS 使用随包提供的 Facebook XCFramework,不再通过 CocoaPods 重复下载。UniWebView 原有平台限制仍适用,例如 Windows Editor 使用占位实现。
-
-iOS 导出后会自动移除 `Frameworks` 和 `Libraries` 中的 `come.app.runtimes` 包目录及 `Runtime` / `ThirdParty` 中间层,采用普通 Assets 插件的布局:`Frameworks/FacebookSDK`、`Frameworks/UniWebView`、`Libraries/FacebookSDK`、`Libraries/IAPiOS` 和 `Libraries/Plugins/iOS`。同时更新 Xcode 分组、文件引用和搜索路径,保留文件 GUID、编译标记及链接/嵌入配置。其他 UPM 包的目录不受影响。首次切换或插件内容更新后建议导出到空目录;目标路径已有不同内容时构建会报冲突,不会覆盖已有插件。
-
-GUPS 的 DLL 使用宿主 `Assets/GUPS/Obfuscator` 作为可写目录。Package 会在编辑器启动及构建开始前创建 Settings、Cache、Log、Temp 目录和对应元数据;缺少 `Settings/Obfuscator_Settings.json` 时复制包内默认配置,已有配置及 GUID 保持不变。SDK 代码继续由 Package 管理,构建过程中不会写入包目录。包内默认配置启用混淆,空工程验证也会实际运行混淆流程。
-
-GUPS 默认只自动选择 `Assets` 下的程序集;迁入 UPM 后需在 **Project Settings → GuardingPearSoftware → Obfuscator → Settings** 的 **Obfuscate external assemblies** 中加入 `AppRuntimes`。包内默认模板已包含此项;已存在的工程配置会被保留,旧工程需补充此项(JSON 键为 `Obfuscate_Assembly_Additional_Assembly_Array`)。无需开启全部 Packages 程序集的混淆。验证会检查 GUPS 实际选中的程序集,以及 IL2CPP 输入 DLL 中的类型和方法名,避免仅凭“构建成功”或生成日志判断混淆生效。
-
-Obfuscator 设置页的图标、开关及折叠按钮直接读取 Package 内的 `ThirdParty/GUPS/Obfuscator/Editor/Gui/Resources`。其路径硬编码在厂商 `GUPS.Obfuscator.Editor.dll` 中,本包已将 14 处 GUI 资源路径调整为 Package 路径,并保留调试符号;配置、日志等可写路径仍使用宿主目录。以后替换该 SDK 的 DLL/PDB 后,执行 `Tools~/Patch-GupsGuiResources.ps1 -UnityPath <Unity.exe绝对路径>` 重新应用路径修补;脚本会检查资源存在、其他 IL 指令及模块标识不变,重复执行不会再次修改文件。
-
-## 配置与使用
-
-包内 `Editor/DefaultSettings` 保存来自 `unity_ab_framework` 当前配置的三份默认模板。Unity 编辑器启动、安装包或脚本重编译后,会在资源导入完成时检查并补齐缺失配置:
-
-| 默认模板 | 宿主生成位置 |
-| --- | --- |
-| `AppSettings.asset` | `Assets/Resources/AppSettings.asset` |
-| `FacebookSettings.asset` | `Assets/Resources/FacebookSettings.asset` |
-| `settings.asset` | `Assets/Editor/UniWebView/settings.asset` |
-
-只复制缺失的配置,已有文件及其 GUID 保持不变。AppSettings、FacebookSettings 已存在于其他可通过 `Resources.Load` 读取的位置时(包括旧的 `Assets/AppHelp/Resources`),继续使用已有资产,不再创建重复配置。新复制的资产使用独立 GUID,修改宿主配置不会改变包内模板;更新包内模板也不会覆盖已有工程配置。
-
-模板放在 Editor 目录,不进入运行时 Resources。以后调整新工程的默认值,请修改包内模板。打开 **AppSettings → Open Settings** 修改当前工程的 App 和 Facebook 参数;UniWebView 配置在 **Preferences → UniWebView** 中修改。
-
-```csharp
-AppRuntimes.Initialization();
-if (await AppRuntimes.CheckVersion())
-{
-    // 在这里停止游戏背景音乐。
-    return;
-}
-// 继续游戏启动流程。
-```
-
-自定义 asmdef 的调用方引用 `AppRuntimes`;直接使用 UniTask API 时再引用 `UniTask`。可从 Package Manager 导入 App Startup 示例。
-
-## IAP 与 StreamingAssets
-
-`Runtime/IAP` 包含原工程的 `IAPWrapper` 和 `IAPAndroidImpl`,归入 `AppRuntimes` 程序集;原 `IAPiOS` 目录完整迁至 `ThirdParty/IAPiOS`,保留 StoreKit 1、StoreKit 2、Swift、StoreKit 测试配置及原有 `.meta`。调用方无需再复制这些脚本或原生文件。
-
-这份 IAP 代码沿用 Facebook 示例中的商品 ID(`com.fbsdk.unity.*`);迁移没有更改购买逻辑,接入真实商品时需调整对应配置和代码。
-
-共享的 `meta.mp4` 和 `meta-logo.png` 存放在包根目录 `StreamingAssets~`。末尾的 `~` 避免 Unity 将原始文件当作普通资源导入;构建处理器通过 [Unity 的 StreamingAssets 构建接口](https://docs.unity.com/en-us/engine/6000.3/script-reference/unityeditor/build/buildplayercontext/addadditionalpathtostreamingassets) 自动加入成品,保留文件名和子目录,排除 `.meta` 与隐藏文件,无需复制到宿主工程。
-
-编辑器和成品共用的读取路径使用:
-
-```csharp
-string path = AppRuntimesStreamingAssets.GetPath("meta-logo.png");
-```
-
-编辑器下返回 Package 中的文件路径;成品中返回 `Application.streamingAssetsPath` 下的路径。Android/WebGL 返回 URL,使用 `UnityWebRequest` 读取。成品中已有的 `Application.streamingAssetsPath + "/meta-logo.png"` 用法仍然有效;编辑器下需使用上述辅助方法。
-
-以后增加共享文件,放入 `StreamingAssets~` 即可随包更新;这个目录不会自动生成新文件的 `.meta`,已有 `.meta` 留存即可,新增原始文件不需要 `.meta`。原 StreamingAssets 文件夹的元数据归档为该目录内的 `.folder.meta`,避免 Unity 对被忽略的目录产生孤立元数据提示。宿主自己的 StreamingAssets 可继续保留,但与包内文件重名会使构建报错,应重命名以避免覆盖。
-
-## 验证
-
-仅验证 iOS 构建;保留其他平台支持,但本次不对其他平台构建作验证承诺。
-
-运行 `python Tools~/validate_package.py` 检查包布局、GUID、程序集与平台文件。使用 PowerShell 执行 `Tools~/Validate-iOS.ps1 -UnityPath <Unity.exe绝对路径>`,会创建独立工程,只安装此包,并验证配置、Loading 预制体、IAP 原生源码导出、StreamingAssets 内容、IL2CPP 高裁剪和 Xcode 工程导出。可传 `-SourceProject <宿主工程路径>` 验证宿主快照;原工程不会被测试脚本改变。
-
-Xcode 编译、签名及真机运行需在对应 macOS/iOS 环境完成。
-
-给验证命令添加 `-SettingsOnly` 可只检查编辑器配置:启动自动生成、默认值一致、独立 GUID、已有自定义值保留、单个缺失文件补齐,以及旧 Resources 路径兼容。配置行为测试只会修改验证脚本创建的临时工程。
+In the Editor, Launch waits until the game scene is loaded and active before invoking the initializer from `AppRuntimes.Sources.Editor`. This call and the Sources assembly are excluded from Player builds. Players continue to initialize the downloaded hot-update DLL through its tagged methods.

+ 17 - 18
Runtime/AppRuntimes.asmdef

@@ -1,20 +1,19 @@
 {
 {
-    "name": "AppRuntimes",
-    "rootNamespace": "",
-    "references": [
-        "GUID:f51ebe6a0ceec4240a699833d6309b23",
-        "GUID:941d6d2e4fdb0f641835be01a9c65a5e",
-        "GUID:4ca033ee547ec451c8a2d3c33d7620ad",
-        "GUID:00c479e63b1c74419820a39073267645",
-        "UnityEngine.UI"
-    ],
-    "includePlatforms": [],
-    "excludePlatforms": [],
-    "allowUnsafeCode": false,
-    "overrideReferences": false,
-    "precompiledReferences": [],
-    "autoReferenced": true,
-    "defineConstraints": [],
-    "versionDefines": [],
-    "noEngineReferences": false
+  "name": "AppRuntimes",
+  "rootNamespace": "",
+  "references": [
+    "GUID:f51ebe6a0ceec4240a699833d6309b23",
+    "GUID:4ca033ee547ec451c8a2d3c33d7620ad",
+    "GUID:00c479e63b1c74419820a39073267645",
+    "GUID:2bafac87e7f4b9b418d9448d219b01ab"
+  ],
+  "includePlatforms": [],
+  "excludePlatforms": [],
+  "allowUnsafeCode": false,
+  "overrideReferences": false,
+  "precompiledReferences": [],
+  "autoReferenced": true,
+  "defineConstraints": [],
+  "versionDefines": [],
+  "noEngineReferences": false
 }
 }

+ 5 - 0
Runtime/HotPatch.meta

@@ -0,0 +1,5 @@
+fileFormatVersion: 2
+guid: 3746880e74fd4bf2bf6b4ab1b4f4f68e
+folderAsset: yes
+DefaultImporter:
+  externalObjects: {}

+ 7 - 0
Runtime/HotPatch/HotPatch.Runtime.asmdef

@@ -0,0 +1,7 @@
+{
+  "name": "HotPatch.Runtime",
+  "references": ["AppRuntimes.Base", "HybridCLR.Runtime", "UniTask", "Unity.Advertisement.IosSupport"],
+  "autoReferenced": false,
+  "defineConstraints": ["HOT_PATCH_HYBRIDCLR"],
+  "versionDefines": [{"name":"com.code-philosophy.hybridclr","expression":"0.0.0","define":"HOT_PATCH_HYBRIDCLR"}]
+}

+ 4 - 0
Runtime/HotPatch/HotPatch.Runtime.asmdef.meta

@@ -0,0 +1,4 @@
+fileFormatVersion: 2
+guid: b2da1f3b234a44ab970313c7a86340f0
+AssemblyDefinitionImporter:
+  externalObjects: {}

+ 47 - 0
Runtime/HotPatch/HotPatchBundleLoader.cs

@@ -0,0 +1,47 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading;
+using Cysharp.Threading.Tasks;
+using UnityEngine;
+
+namespace HotPatch
+{
+    public static class HotPatchBundleLoader
+    {
+        public static readonly IReadOnlyList<string> AotAssemblyNames = Array.AsReadOnly(new[]
+            { "mscorlib.dll", "Newtonsoft.Json.dll", "System.Core.dll", "UniTask.dll" });
+
+        public static async UniTask<AssetBundle> LoadAsync(string path, string kind, CancellationToken ct)
+        {
+            ct.ThrowIfCancellationRequested();
+            HotPatchLog.Info("bundle_load_start kind=" + kind + " path=" + path);
+
+            var bundle = await AssetBundle.LoadFromFileAsync(path).ToUniTask();
+            if (ct.IsCancellationRequested)
+            {
+                if (bundle != null) bundle.Unload(true);
+                ct.ThrowIfCancellationRequested();
+            }
+            if (bundle == null) throw new InvalidDataException("Failed to load AssetBundle: " + path);
+            HotPatchLog.Info("bundle_load_complete kind=" + kind + " name=" + bundle.name);
+            return bundle;
+        }
+
+        public static async UniTask<byte[]> ReadDllAsync(AssetBundle bundle, string dllName, CancellationToken ct,
+            HotPatchResource expected = null)
+        {
+            ct.ThrowIfCancellationRequested();
+            var assetName = dllName + ".bytes";
+            var asset = await bundle.LoadAssetAsync<TextAsset>(assetName).ToUniTask() as TextAsset;
+            ct.ThrowIfCancellationRequested();
+            if (asset == null) throw new InvalidDataException("DLL missing from bundle: " + assetName);
+            var bytes = asset.bytes;
+            if (expected != null && (bytes.LongLength != expected.size ||
+                !string.Equals(HotPatchHash.Of(bytes), expected.sha256, StringComparison.OrdinalIgnoreCase)))
+                throw new InvalidDataException("DLL verification failed inside bundle: " + dllName);
+            HotPatchLog.Info("bundle_dll_read name=" + dllName + " bytes=" + bytes.Length);
+            return bytes;
+        }
+    }
+}

+ 2 - 0
Runtime/HotPatch/HotPatchBundleLoader.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: ea65ecc166959c24c8b8d727be6a4ae3

+ 35 - 0
Runtime/HotPatch/HotPatchLaunchResources.cs

@@ -0,0 +1,35 @@
+using System;
+using System.Threading;
+using Cysharp.Threading.Tasks;
+
+namespace HotPatch
+{
+    public sealed class HotPatchLaunchResources : ILaunchResources
+    {
+        public string GameSceneName => AppSettings.RequireGameSceneName();
+        public string LoadedScenePath => HotPatchService.LoadedScenePath;
+        public string LoadedVersion => HotPatchService.LoadedVersion;
+        public bool HasLoadedAssembly => HotPatchService.LoadedAssembly != null;
+        public bool RequiresRestart => HotPatchService.RequiresRestart;
+
+        public async UniTask LoadAsync(Action<string, float> progress, CancellationToken cancellationToken)
+        {
+            await HotPatchService.LoadAndInitializeAsync(value => progress?.Invoke(value.Stage, value.Value), cancellationToken);
+        }
+
+        public void MarkEntryFailed() => HotPatchService.MarkEntryFailed();
+
+#if UNITY_EDITOR
+        public bool UseEditorSceneLoading
+        {
+            get
+            {
+                var settings = UnityEngine.Resources.Load<AppSettings>("AppSettings");
+                return !settings.UseLocalHotPatchResources && string.IsNullOrWhiteSpace(settings.DownloadUrl);
+            }
+        }
+
+        public void InitializeEditor() => HotPatchService.InvokeInitialization(System.Reflection.Assembly.Load("AppRuntimes.Sources.Editor"));
+#endif
+    }
+}

+ 2 - 0
Runtime/HotPatch/HotPatchLaunchResources.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 778f9542c30d32f43a6c5093dd73a093

+ 174 - 0
Runtime/HotPatch/HotPatchManifest.cs

@@ -0,0 +1,174 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text.RegularExpressions;
+using UnityEngine;
+
+namespace HotPatch
+{
+    [Serializable]
+    public sealed class HotPatchManifest
+    {
+        public int schemaVersion = 4;
+        public string platform;
+        public string playerBuildId;
+        public string version;
+        public string assemblyName;
+        public string gameSceneName;
+        public string gameScenePath;
+        public bool developmentBuild;
+        public HotPatchResource[] resources = Array.Empty<HotPatchResource>();
+
+        public HotPatchResource[] aotBundles = Array.Empty<HotPatchResource>();
+        public HotPatchResource aotBundle
+        {
+            get => (aotBundles ?? Array.Empty<HotPatchResource>()).SingleOrDefault();
+            set => aotBundles = value == null ? Array.Empty<HotPatchResource>() : new[] { value };
+        }
+
+        public HotPatchResource[] aotMetadata = Array.Empty<HotPatchResource>();
+
+        public void Validate(string expectedAssembly, string expectedPlatform, string expectedScene = null)
+        {
+            if (schemaVersion != 4 || (aotBundles?.Length ?? 0) > 1 || assemblyName != expectedAssembly || platform != expectedPlatform ||
+                string.IsNullOrWhiteSpace(gameSceneName) || (expectedScene != null && gameSceneName != expectedScene) ||
+                !IsScenePath(gameScenePath, gameSceneName) ||
+                string.IsNullOrWhiteSpace(playerBuildId) || string.IsNullOrWhiteSpace(version) || resources == null || resources.Length == 0)
+                throw new InvalidDataException("Invalid resource manifest version, platform, assembly, or scene. Use schemaVersion 4 bundle resources.");
+            var names = new System.Collections.Generic.HashSet<string>(StringComparer.OrdinalIgnoreCase);
+            int assemblies = 0, scenes = 0;
+            foreach (var resource in resources)
+            {
+                if (resource == null || !HotPatchResource.IsBundleName(resource.name) || !names.Add(resource.name) ||
+                    resource.size <= 0 || !HotPatchHash.IsValid(resource.sha256))
+                    throw new InvalidDataException("Resource names are duplicate or unsafe, or a valid size / SHA-256 is missing.");
+                if (resource.kind == HotPatchResource.AssemblyKind)
+                {
+                    if (resource.name != HotPatchResource.AssemblyBundleName(assemblyName)) throw new InvalidDataException("Invalid hot-update bundle name in the manifest.");
+                    assemblies++;
+                }
+                else if (resource.kind == HotPatchResource.SceneKind)
+                {
+                    if (resource.name != HotPatchResource.SceneBundleName(gameSceneName)) throw new InvalidDataException("Invalid scene bundle name in the manifest.");
+                    scenes++;
+                }
+                else throw new InvalidDataException("Update resources can contain only hot-update assembly and scene bundles: " + resource.kind);
+            }
+            if (assemblies != 1 || scenes != 1) throw new InvalidDataException("The resource manifest must contain one hot-update assembly bundle and one scene bundle.");
+            if (aotBundle != null && (aotBundle.name != "aot.bundle" || aotBundle.kind != HotPatchResource.AotBundleKind ||
+                aotBundle.size <= 0 || !HotPatchHash.IsValid(aotBundle.sha256)))
+                throw new InvalidDataException("Invalid AOT bundle manifest.");
+            foreach (var resource in aotMetadata ?? Array.Empty<HotPatchResource>())
+                if (resource == null || resource.kind != HotPatchResource.AotKind || !HotPatchResource.IsValidName(resource.name) ||
+                    !names.Add(resource.name) || resource.size <= 0 || !HotPatchHash.IsValid(resource.sha256))
+                    throw new InvalidDataException("Invalid installed AOT metadata manifest.");
+        }
+
+        public void ValidateAgainst(HotPatchManifest original)
+        {
+            if (original == null) throw new ArgumentNullException(nameof(original));
+            Validate(original.assemblyName, original.platform, original.gameSceneName);
+            if (playerBuildId != original.playerBuildId || developmentBuild != original.developmentBuild)
+                throw new InvalidDataException("Update resources are incompatible with the installed AOT baseline. Update the application package.");
+            if (aotBundle != null && !aotBundle.SameContent(original.aotBundle))
+                throw new InvalidDataException("The AOT bundle cannot be replaced by a remote update.");
+            var aot = aotMetadata ?? Array.Empty<HotPatchResource>();
+            var bundledAot = original.aotMetadata ?? Array.Empty<HotPatchResource>();
+
+
+            if (aot.Length != 0 && (aot.Length != bundledAot.Length || aot.Any(r => !bundledAot.Any(r.SameContent))))
+                throw new InvalidDataException("AOT metadata must be extracted from the application package and cannot be replaced by a remote update.");
+        }
+
+        public bool SameVersion(HotPatchManifest other) => other != null && schemaVersion == other.schemaVersion &&
+            assemblyName == other.assemblyName && platform == other.platform && playerBuildId == other.playerBuildId &&
+            gameSceneName == other.gameSceneName && gameScenePath == other.gameScenePath &&
+            ((aotBundle == null && other.aotBundle == null) || (aotBundle != null && aotBundle.SameContent(other.aotBundle))) &&
+            developmentBuild == other.developmentBuild && version == other.version &&
+            SameResources(resources, other.resources) && SameResources(aotMetadata, other.aotMetadata);
+
+        static bool SameResources(HotPatchResource[] first, HotPatchResource[] second)
+        {
+            first = first ?? Array.Empty<HotPatchResource>(); second = second ?? Array.Empty<HotPatchResource>();
+            return first.Length == second.Length && first.All(r => second.Any(r.SameContent));
+        }
+
+        public HotPatchResource AssemblyResource => resources.Single(r => r.kind == HotPatchResource.AssemblyKind);
+        public HotPatchResource SceneResource => resources.Single(r => r.kind == HotPatchResource.SceneKind);
+
+        public static bool IsScenePath(string path, string scene) => !string.IsNullOrEmpty(path) &&
+            path.StartsWith("Assets/", StringComparison.Ordinal) && !path.Contains("..") && !path.Contains('\\') &&
+            path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase) && Path.GetFileNameWithoutExtension(path) == scene;
+    }
+
+    [Serializable]
+    public sealed class HotPatchResource
+    {
+        public const string AssemblyKind = "assembly-bundle";
+        public const string SceneKind = "scene-bundle";
+        public const string AotBundleKind = "aot-bundle";
+        public const string AotKind = "aot";
+        public string name;
+        public string kind;
+        public long size;
+        public string sha256;
+
+
+        public string RelativePath
+        {
+            get
+            {
+                if (!HotPatchHash.IsValid(sha256)) throw new InvalidDataException("Invalid resource SHA-256.");
+                if (kind == AotBundleKind) return "aot.bundle";
+                if (kind == AotKind)
+                {
+                    if (!IsValidName(name)) throw new InvalidDataException("Invalid AOT file name.");
+                    return name + ".bytes";
+                }
+                return "files/" + sha256.ToLowerInvariant() + ".bundle";
+            }
+        }
+
+        public bool SameContent(HotPatchResource other) => other != null && name == other.name && kind == other.kind &&
+            size == other.size && string.Equals(sha256, other.sha256, StringComparison.OrdinalIgnoreCase);
+
+        public static bool IsValidName(string value) => value != null &&
+            Regex.IsMatch(value, @"\A[\p{L}\p{N}_.-]+\.dll\z") && !value.Contains("..");
+        public static bool IsBundleName(string value) => value != null &&
+            Regex.IsMatch(value, @"\A[\p{L}\p{N}_. -]+\.bundle\z") && !value.Contains("..");
+        public static string AssemblyBundleName(string name) => "hotupdate." + name.ToLowerInvariant() + ".bundle";
+        public static string SceneBundleName(string name) => "scene." + name.ToLowerInvariant() + ".bundle";
+    }
+
+    public readonly struct HotPatchProgress
+    {
+        public readonly string Stage;
+        public readonly float Value;
+        public readonly ulong DownloadedBytes;
+        public readonly long TotalBytes;
+        public HotPatchProgress(string stage, float value, ulong downloaded = 0, long total = 0)
+        { Stage = stage; Value = Mathf.Clamp01(value); DownloadedBytes = downloaded; TotalBytes = total; }
+    }
+
+    public static class HotPatchHash
+    {
+        public static bool IsValid(string value) => value != null && Regex.IsMatch(value, "\\A[0-9a-fA-F]{64}\\z");
+        public static string Of(byte[] bytes)
+        {
+            using var sha = SHA256.Create();
+            return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant();
+        }
+        public static string OfFile(string path)
+        {
+            using var stream = File.OpenRead(path);
+            using var sha = SHA256.Create();
+            return BitConverter.ToString(sha.ComputeHash(stream)).Replace("-", "").ToLowerInvariant();
+        }
+        public static void RequireHttp(Uri uri)
+        {
+            if (uri == null || !uri.IsAbsoluteUri || (uri.Scheme != "https" && uri.Scheme != "http"))
+                throw new InvalidDataException("The hot patch URL must be an absolute HTTP(S) URL.");
+        }
+    }
+}

+ 1 - 4
Runtime/Scripts/FBHandler.cs.meta → Runtime/HotPatch/HotPatchManifest.cs.meta

@@ -1,11 +1,8 @@
 fileFormatVersion: 2
 fileFormatVersion: 2
-guid: f9302bec8feaff54abb15ed327474cf6
+guid: dc3fa34340a743b0b90f6790337e57f6
 MonoImporter:
 MonoImporter:
   externalObjects: {}
   externalObjects: {}
   serializedVersion: 2
   serializedVersion: 2
   defaultReferences: []
   defaultReferences: []
   executionOrder: 0
   executionOrder: 0
   icon: {instanceID: 0}
   icon: {instanceID: 0}
-  userData: 
-  assetBundleName: 
-  assetBundleVariant: 

+ 299 - 0
Runtime/HotPatch/HotPatchResourceStore.cs

@@ -0,0 +1,299 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using Cysharp.Threading.Tasks;
+using UnityEngine;
+using UnityEngine.Networking;
+
+namespace HotPatch
+{
+    public sealed class HotPatchLocalResources
+    {
+        public string RootPath { get; }
+        public HotPatchManifest Manifest { get; }
+        public HotPatchManifest BundledManifest { get; }
+        public HotPatchLocalResources(string rootPath, HotPatchManifest manifest, HotPatchManifest bundledManifest)
+        { RootPath = rootPath; Manifest = manifest; BundledManifest = bundledManifest; }
+        public string GetPath(HotPatchResource resource) => Path.Combine(RootPath, resource.RelativePath);
+    }
+
+                                                                                                                              
+    public static class HotPatchResourceStore
+    {
+        public const string ManifestFileName = "manifest.json";
+
+        public static async UniTask<HotPatchLocalResources> LoadBundledAsync(Uri bundledManifestUri,
+            string cacheDirectory, string assemblyName, string platform, Action<HotPatchProgress> progress, CancellationToken ct, string sceneName = null)
+        {
+            progress?.Invoke(new HotPatchProgress("Checking version", 0));
+            var json = await ReadTextAsync(bundledManifestUri, ct);
+            var manifest = Parse(json);
+            ValidateBundledManifest(manifest, assemblyName, platform, sceneName);
+            var root = Path.Combine(cacheDirectory, "LocalTest", HotPatchHash.Of(Encoding.UTF8.GetBytes(json)));
+            var resources = new[] { manifest.aotBundle }.Concat(manifest.resources).ToArray();
+            HotPatchLog.Info("local_test_cache path=" + root + " version=" + manifest.version);
+            for (int i = 0; i < resources.Length; i++)
+            {
+                ct.ThrowIfCancellationRequested();
+                var resource = resources[i];
+                var destination = Path.Combine(root, resource.RelativePath);
+                if (!IsVerified(destination, resource))
+                    await DownloadFileAsync(new Uri(bundledManifestUri, resource.RelativePath), destination, resource,
+                        bytes => progress?.Invoke(new HotPatchProgress("Checking version", .8f * (i + (float)bytes / resource.size) / resources.Length)), ct);
+            }
+            ct.ThrowIfCancellationRequested();
+            SaveManifest(Path.Combine(root, ManifestFileName), manifest);
+            HotPatchLog.Info("local_test_ready version=" + manifest.version + " remote_requests=0");
+            progress?.Invoke(new HotPatchProgress("Loading resources", .8f));
+            return new HotPatchLocalResources(root, manifest, manifest);
+        }
+
+        static void ValidateBundledManifest(HotPatchManifest manifest, string assemblyName, string platform, string sceneName)
+        {
+            manifest.Validate(assemblyName, platform, sceneName);
+            if (manifest.aotBundle == null || manifest.aotMetadata == null ||
+                !manifest.aotMetadata.Select(r => r.name).OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n)))
+                throw new InvalidDataException("Original resources must include an AOT bundle and verification records for all four AOT DLLs.");
+        }
+
+        public static async UniTask<HotPatchLocalResources> SynchronizeAsync(Uri bundledManifestUri, Uri remoteManifestUri,
+            string cacheDirectory, string assemblyName, string platform, Action<HotPatchProgress> progress, CancellationToken ct, string sceneName = null)
+        {
+            remoteManifestUri = RemoteManifestUri(remoteManifestUri?.AbsoluteUri);
+            var elapsed = System.Diagnostics.Stopwatch.StartNew();
+            HotPatchLog.Info($"sync_start assembly={assemblyName} platform={platform} bundled={HotPatchLog.SafeUrl(bundledManifestUri)} remote={HotPatchLog.SafeUrl(remoteManifestUri)}");
+            progress?.Invoke(new HotPatchProgress("Checking version", 0));
+            var original = Parse(await ReadTextAsync(bundledManifestUri, ct));
+            HotPatchLog.Info($"bundled_manifest platform={original.platform} build={original.playerBuildId} version={original.version}");
+            ValidateBundledManifest(original, assemblyName, platform, sceneName);
+            var root = Path.Combine(cacheDirectory, HotPatchHash.Of(Encoding.UTF8.GetBytes(original.playerBuildId)));
+            Directory.CreateDirectory(root);
+            HotPatchLog.Info("cache_path path=" + root);
+            var manifestPath = Path.Combine(root, ManifestFileName);
+                                                                                                 
+            var aotMetadata = original.aotMetadata ?? Array.Empty<HotPatchResource>();
+            var aotPath = Path.Combine(root, original.aotBundle.RelativePath);
+            if (!IsVerified(aotPath, original.aotBundle))
+                await DownloadFileAsync(new Uri(bundledManifestUri, original.aotBundle.RelativePath), aotPath, original.aotBundle,
+                    bytes => progress?.Invoke(new HotPatchProgress("Checking version", .1f * (float)bytes / original.aotBundle.size)), ct);
+            var local = TryReadLocal(manifestPath, original);
+            if (local != null && !local.resources.Any(r => IsVerified(Path.Combine(root, r.RelativePath), r)))
+                local = null;
+            if (local == null)
+            {
+                HotPatchLog.Info("cache_restore source=StreamingAssets reason=missing_or_invalid");
+                for (int i = 0; i < original.resources.Length; i++)
+                {
+                    var resource = original.resources[i];
+                    var destination = Path.Combine(root, resource.RelativePath);
+                    if (!IsVerified(destination, resource))
+                        await DownloadFileAsync(new Uri(bundledManifestUri, resource.RelativePath), destination, resource,
+                            bytes => progress?.Invoke(new HotPatchProgress("Checking version", .1f + .1f * (i + (float)bytes / resource.size) / original.resources.Length)), ct);
+                    ct.ThrowIfCancellationRequested();
+                }
+                local = Parse(JsonUtility.ToJson(original));
+                SaveManifest(manifestPath, local);
+            }
+            else HotPatchLog.Info("cache_reuse version=" + local.version);
+
+            progress?.Invoke(new HotPatchProgress("Checking version", .2f));
+            var fresh = new UriBuilder(remoteManifestUri);
+            fresh.Query = fresh.Query.TrimStart('?') + (fresh.Query.Length > 0 ? "&" : "") + "hotpatch=" + DateTime.UtcNow.Ticks;
+            var remote = Parse(await ReadTextAsync(fresh.Uri, ct, true));
+            HotPatchLog.Info($"remote_manifest platform={remote.platform} build={remote.playerBuildId} version={remote.version}");
+            remote.ValidateAgainst(original);
+            var previous = local.resources.ToDictionary(r => r.name, StringComparer.OrdinalIgnoreCase);
+            var changed = remote.resources.Where(resource =>
+                !previous.TryGetValue(resource.name, out var old) || !resource.SameContent(old) ||
+                !IsVerified(Path.Combine(root, resource.RelativePath), resource)).ToArray();
+                                                                                                         
+            changed = changed.Where(r => !IsVerified(Path.Combine(root, r.RelativePath), r)).ToArray();
+            long total = changed.Sum(r => checked(r.size)), completed = 0;
+            HotPatchLog.Info($"version_compare local={local.version} remote={remote.version} changedFiles={changed.Length} transferBytes={total}");
+            foreach (var resource in changed)
+            {
+                ct.ThrowIfCancellationRequested();
+                var bundled = original.resources.FirstOrDefault(r => r.SameContent(resource));
+                var source = new Uri(bundled != null ? bundledManifestUri : remoteManifestUri, resource.RelativePath);
+                await DownloadFileAsync(source, Path.Combine(root, resource.RelativePath), resource,
+                    bytes => progress?.Invoke(new HotPatchProgress(bundled != null ? "Repairing local resources" : "Downloading updates",
+                        .2f + .6f * (float)((completed + (double)bytes) / Math.Max(1, total)),
+                        (ulong)completed + bytes, total)), ct);
+                completed += resource.size;
+            }
+            ct.ThrowIfCancellationRequested();
+                                                                                                                  
+            remote.aotMetadata = aotMetadata;
+            remote.aotBundle = original.aotBundle;
+            bool unchanged = local.SameVersion(remote);
+            if (!unchanged) SaveManifest(manifestPath, remote);
+            HotPatchLog.Info("manifest_" + (unchanged ? "unchanged" : "committed") + " path=" + manifestPath);
+            RemoveObsoleteFiles(root, remote);
+            HotPatchLog.Info($"sync_complete version={remote.version} changedFiles={changed.Length} transferBytes={total} elapsedMs={elapsed.ElapsedMilliseconds}");
+            progress?.Invoke(new HotPatchProgress(unchanged && changed.Length == 0 ? "Resources are up to date" : "Local resources updated", .8f, (ulong)total, total));
+            return new HotPatchLocalResources(root, remote, original);
+        }
+
+        static HotPatchManifest TryReadLocal(string path, HotPatchManifest original)
+        {
+            if (!File.Exists(path)) return null;
+            try
+            {
+                var manifest = Parse(File.ReadAllText(path));
+                manifest.ValidateAgainst(original);
+                return manifest;
+            }
+            catch (Exception e) when (e is IOException || e is ArgumentException || e is InvalidOperationException)
+            {
+                HotPatchLog.Warning("cache_manifest_invalid path=" + path + " reason=" + e.Message);
+                return null;
+            }
+        }
+
+        public static HotPatchManifest Parse(string json)
+            => JsonUtility.FromJson<HotPatchManifest>(json) ?? throw new InvalidDataException("The resource manifest is empty.");
+
+        public static bool IsVerified(string path, HotPatchResource resource)
+            => File.Exists(path) && new FileInfo(path).Length == resource.size &&
+               string.Equals(HotPatchHash.OfFile(path), resource.sha256, StringComparison.OrdinalIgnoreCase);
+
+        static void SaveManifest(string path, HotPatchManifest manifest)
+        {
+            var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
+            try
+            {
+                File.WriteAllText(temp, JsonUtility.ToJson(manifest, true), new UTF8Encoding(false));
+                CommitFile(temp, path);
+            }
+            finally { if (File.Exists(temp)) File.Delete(temp); }
+        }
+
+        static void RemoveObsoleteFiles(string root, HotPatchManifest manifest)
+        {
+            var retained = new HashSet<string>(manifest.resources.Select(r => Path.GetFileName(r.RelativePath)), StringComparer.OrdinalIgnoreCase);
+            var files = Path.Combine(root, "files");
+            if (!Directory.Exists(files)) return;
+            foreach (var file in Directory.GetFiles(files))
+            {
+                var name = Path.GetFileName(file);
+                if (retained.Contains(name) || !Regex.IsMatch(name, @"\A(?:[0-9a-f]{64}(?:\.bundle|(?:\.dll|\.bundle)?\.bytes)|download-[0-9a-f]{32}\.tmp)\z")) continue;
+                File.Delete(file);
+            }
+        }
+
+        public static Uri StreamingManifestUri()
+        {
+            return ManifestUriFromStreamingPath(Application.streamingAssetsPath);
+        }
+
+                                                                                             
+        public static Uri RemoteManifestUri(string downloadUrl)
+        {
+            if (!Uri.TryCreate(downloadUrl?.Trim(), UriKind.Absolute, out var uri))
+                throw new InvalidOperationException("Configure a valid hot patch DownloadUrl in AppSettings.");
+            HotPatchHash.RequireHttp(uri);
+            var builder = new UriBuilder(uri) { Fragment = string.Empty };
+            if (!builder.Path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
+                builder.Path = builder.Path.TrimEnd('/') + "/" + ManifestFileName;
+            return builder.Uri;
+        }
+
+        public static Uri ManifestUriFromStreamingPath(string streamingAssetsPath)
+        {
+            var path = streamingAssetsPath.TrimEnd('/', '\\') + "/" + ManifestFileName;
+                                                                                     
+            return new Uri(path.Contains("://") ? path : Path.GetFullPath(path));
+        }
+
+        static async UniTask<string> ReadTextAsync(Uri uri, CancellationToken ct, bool noCache = false)
+        {
+            var elapsed = System.Diagnostics.Stopwatch.StartNew();
+            HotPatchLog.Info("manifest_request url=" + HotPatchLog.SafeUrl(uri));
+            try
+            {
+                using var request = UnityWebRequest.Get(uri.AbsoluteUri);
+                request.timeout = 30;
+                if (noCache) request.SetRequestHeader("Cache-Control", "no-cache, no-store");
+                var operation = request.SendWebRequest();
+                while (!operation.isDone)
+                {
+                    if (ct.IsCancellationRequested) { request.Abort(); ct.ThrowIfCancellationRequested(); }
+                    await UniTask.Yield(ct);
+                }
+                ct.ThrowIfCancellationRequested();
+                if (request.result != UnityWebRequest.Result.Success) throw RequestFailure("Failed to read resource manifest", uri, request);
+                HotPatchLog.Info($"manifest_response url={HotPatchLog.SafeUrl(uri)} status={request.responseCode} bytes={request.downloadedBytes} elapsedMs={elapsed.ElapsedMilliseconds}");
+                return Encoding.UTF8.GetString(request.downloadHandler.data).TrimStart('\uFEFF');
+            }
+            catch (Exception e)
+            {
+                HotPatchLog.Warning($"manifest_failed url={HotPatchLog.SafeUrl(uri)} elapsedMs={elapsed.ElapsedMilliseconds} type={e.GetType().Name} reason={e.Message}");
+                throw;
+            }
+        }
+
+        static IOException RequestFailure(string message, Uri uri, UnityWebRequest request)
+                                                                                     
+            => new IOException(message + ": HTTP " + request.responseCode + " / " +
+                HotPatchLog.SafeUrl(uri) + " / " + request.error);
+
+        public static async UniTask DownloadFileAsync(Uri uri, string destination, HotPatchResource resource,
+            Action<ulong> progress, CancellationToken ct)
+        {
+            var elapsed = System.Diagnostics.Stopwatch.StartNew();
+            bool remote = uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps;
+            var action = remote ? "download" : "extract";
+            HotPatchLog.Info($"{action}_start name={resource.name} bytes={resource.size} sha256={resource.sha256} url={HotPatchLog.SafeUrl(uri)} destination={destination}");
+            Directory.CreateDirectory(Path.GetDirectoryName(destination));
+                                                                                                    
+            var temp = Path.Combine(Path.GetDirectoryName(destination), "download-" + Guid.NewGuid().ToString("N") + ".tmp");
+            try
+            {
+                long nextProgressMs = 1000;
+                using (var request = UnityWebRequest.Get(uri.AbsoluteUri))
+                {
+                    request.timeout = 30;
+                    request.downloadHandler.Dispose();
+                    request.downloadHandler = new DownloadHandlerFile(temp) { removeFileOnAbort = true };
+                    var operation = request.SendWebRequest();
+                    while (!operation.isDone)
+                    {
+                        if (ct.IsCancellationRequested) { request.Abort(); ct.ThrowIfCancellationRequested(); }
+                        if (request.downloadedBytes > (ulong)resource.size)
+                        { request.Abort(); throw new InvalidDataException("The resource exceeds the size declared in the manifest: " + resource.name); }
+                        progress?.Invoke(request.downloadedBytes);
+                        if (elapsed.ElapsedMilliseconds >= nextProgressMs)
+                        {
+                            HotPatchLog.Info($"{action}_progress name={resource.name} bytes={request.downloadedBytes}/{resource.size} percent={Math.Min(100, request.downloadedBytes * 100d / resource.size):F0}");
+                            nextProgressMs = elapsed.ElapsedMilliseconds + 1000;
+                        }
+                        await UniTask.Yield(ct);
+                    }
+                    ct.ThrowIfCancellationRequested();
+                    if (request.result != UnityWebRequest.Result.Success) throw RequestFailure("Failed to read resource: " + resource.name, uri, request);
+                    HotPatchLog.Info($"{action}_response name={resource.name} status={request.responseCode} bytes={request.downloadedBytes}");
+                }
+                if (!IsVerified(temp, resource)) throw new InvalidDataException("Resource size or SHA-256 verification failed: " + resource.name);
+                CommitFile(temp, destination);
+                HotPatchLog.Info($"{action}_complete name={resource.name} bytes={resource.size} percent=100 sha256=verified elapsedMs={elapsed.ElapsedMilliseconds} destination={destination}");
+                progress?.Invoke((ulong)resource.size);
+            }
+            catch (Exception e)
+            {
+                HotPatchLog.Warning($"{action}_failed name={resource.name} url={HotPatchLog.SafeUrl(uri)} elapsedMs={elapsed.ElapsedMilliseconds} type={e.GetType().Name} reason={e.Message}");
+                throw;
+            }
+            finally { if (File.Exists(temp)) File.Delete(temp); }
+        }
+
+        static void CommitFile(string temp, string destination)
+        {
+            if (File.Exists(destination)) File.Replace(temp, destination, null);
+            else File.Move(temp, destination);
+        }
+    }
+}

+ 2 - 0
Runtime/HotPatch/HotPatchResourceStore.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2e61e2f682f178341bd64f9ddd9019f3

+ 216 - 0
Runtime/HotPatch/HotPatchService.cs

@@ -0,0 +1,216 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+using Cysharp.Threading.Tasks;
+using HybridCLR;
+using UnityEngine;
+
+namespace HotPatch
+{
+                                                                                           
+    public static class HotPatchService
+    {
+        public static Assembly LoadedAssembly { get; private set; }
+        public static bool RequiresRestart { get; private set; }
+        public static string LoadedVersion { get; private set; }
+        public static string LoadedScenePath { get; private set; }
+        static AssetBundle sceneBundle;
+        static bool busy, initialized;
+        static readonly HashSet<string> loadedMetadata = new HashSet<string>();
+
+        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
+        static void ResetEditorSession()
+        {
+            if (sceneBundle != null) sceneBundle.Unload(false);
+            sceneBundle = null; LoadedScenePath = null;
+            LoadedAssembly = null; LoadedVersion = null;
+            RequiresRestart = busy = initialized = false;
+            loadedMetadata.Clear();
+        }
+
+        public static UniTask<Assembly> LoadAndInitializeAsync(Action<HotPatchProgress> progress, CancellationToken cancellationToken)
+            => LoadAndInitializeAsync(AppSettings.RequireHotPatchAssemblyName(), progress, cancellationToken);
+
+        public static async UniTask<Assembly> LoadAndInitializeAsync(string assemblyName,
+            Action<HotPatchProgress> progress, CancellationToken cancellationToken)
+        {
+            if (busy) throw new InvalidOperationException("A hot patch is already loading.");
+            if (RequiresRestart) throw new InvalidOperationException("The assembly has already been loaded. Restart the app before retrying.");
+            if (initialized)
+            {
+                if (LoadedAssembly.GetName().Name != assemblyName) throw new InvalidOperationException("A different hot patch assembly is already loaded in this process.");
+                HotPatchLog.Info("assembly_reuse name=" + assemblyName + " version=" + LoadedVersion);
+                return LoadedAssembly;
+            }
+            busy = true;
+            try
+            {
+                await UniTask.SwitchToMainThread(cancellationToken);
+                HotPatchLog.Info($"load_start assembly={assemblyName} platform={CurrentPlatform()} appVersion={Application.version} unity={Application.unityVersion}");
+                var settings = Resources.Load<AppSettings>("AppSettings");
+                var sceneName = AppSettings.RequireGameSceneName();
+                bool localOnly = settings != null && settings.UseLocalHotPatchResources;
+                bool synchronize = true;
+#if UNITY_EDITOR
+                synchronize = localOnly || settings != null && !string.IsNullOrWhiteSpace(settings.DownloadUrl);
+#endif
+                HotPatchLocalResources local = null;
+                if (synchronize)
+                {
+                    var cache = Path.Combine(Application.temporaryCachePath, "HotUpdate");
+                    if (localOnly)
+                    {
+                        HotPatchLog.Info("local_test_start source=StreamingAssets remote_updates=disabled");
+                        local = await HotPatchResourceStore.LoadBundledAsync(HotPatchResourceStore.StreamingManifestUri(), cache,
+                            assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
+                    }
+                    else
+                    {
+                        var manifestUri = HotPatchResourceStore.RemoteManifestUri(settings != null ? settings.DownloadUrl : null);
+                        local = await HotPatchResourceStore.SynchronizeAsync(HotPatchResourceStore.StreamingManifestUri(), manifestUri,
+                            cache, assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
+                    }
+                    progress?.Invoke(new HotPatchProgress("Loading resources", .82f));
+                    var aotBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.BundledManifest.aotBundle), "aot", cancellationToken);
+                    try
+                    {
+                        foreach (var aot in local.BundledManifest.aotMetadata)
+                        {
+                            var bytes = await HotPatchBundleLoader.ReadDllAsync(aotBundle, aot.name, cancellationToken, aot);
+#if !UNITY_EDITOR
+                            if (loadedMetadata.Contains(aot.name)) continue;
+                            HotPatchLog.Info($"aot_load_start name={aot.name} bytes={bytes.Length}");
+                            var result = RuntimeApi.LoadMetadataForAOTAssembly(bytes, HomologousImageMode.SuperSet);
+                            HotPatchLog.Info($"aot_load_result name={aot.name} result={result}");
+                            if (result != LoadImageErrorCode.OK)
+                                throw new InvalidOperationException("Failed to load AOT metadata: " + aot.name + " / " + result);
+                            loadedMetadata.Add(aot.name);
+#endif
+                        }
+                    }
+                    finally { aotBundle.Unload(true); }
+                    progress?.Invoke(new HotPatchProgress("Loading resources", .87f));
+                    var dllBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.AssemblyResource), "assembly", cancellationToken);
+                    try
+                    {
+                        var bytes = await HotPatchBundleLoader.ReadDllAsync(dllBundle, assemblyName + ".dll", cancellationToken);
+#if !UNITY_EDITOR
+                        if (AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == assemblyName))
+                            throw new InvalidOperationException("The hot patch assembly was loaded prematurely. Rebuild the host application.");
+                                                                                       
+                        RequiresRestart = true;
+                        HotPatchLog.Info($"assembly_load_start name={assemblyName} version={local.Manifest.version} bundleSha256={local.Manifest.AssemblyResource.sha256}");
+                        LoadedAssembly = Assembly.Load(bytes);
+                        if (LoadedAssembly.GetName().Name != assemblyName) throw new InvalidDataException("The DLL assembly name inside the bundle is incorrect.");
+                        LoadedVersion = local.Manifest.version;
+                        HotPatchLog.Info($"assembly_load_complete name={assemblyName} version={LoadedVersion}");
+#else
+                        HotPatchLog.Info("editor_bundle_verified version=" + local.Manifest.version + " execution=editor-local");
+#endif
+                    }
+                    finally { dllBundle.Unload(true); }
+                }
+#if UNITY_EDITOR
+                                                                                                 
+                LoadedAssembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(a => a.GetName().Name == assemblyName)
+                    ?? throw new InvalidOperationException("Sync sources and wait for compilation to finish first.");
+                LoadedVersion = "editor-local";
+#endif
+                RequiresRestart = true;
+#if !UNITY_EDITOR
+                progress?.Invoke(new HotPatchProgress("Loading resources", .91f));
+                InvokeInitialization(LoadedAssembly);
+#endif
+                if (local != null)
+                {
+                    progress?.Invoke(new HotPatchProgress("Loading resources", .93f));
+                    sceneBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.SceneResource), "scene", cancellationToken);
+                    var paths = sceneBundle.GetAllScenePaths();
+                    LoadedScenePath = paths.SingleOrDefault(p => string.Equals(p, local.Manifest.gameScenePath, StringComparison.OrdinalIgnoreCase))
+                        ?? throw new InvalidDataException("The scene bundle does not contain the game scene specified in the manifest: " + local.Manifest.gameScenePath);
+                    HotPatchLog.Info("scene_bundle_ready path=" + LoadedScenePath);
+                }
+#if UNITY_EDITOR
+                else
+                {
+                    var paths = UnityEditor.AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }).Select(UnityEditor.AssetDatabase.GUIDToAssetPath)
+                        .Where(p => Path.GetFileNameWithoutExtension(p) == sceneName).ToArray();
+                    if (paths.Length != 1) throw new InvalidOperationException("The local game scene is missing or its name is not unique: " + sceneName);
+                    LoadedScenePath = paths[0];
+                    HotPatchLog.Info("editor_local_scene path=" + LoadedScenePath);
+                }
+#endif
+                initialized = true;
+                RequiresRestart = false;
+                progress?.Invoke(new HotPatchProgress("Loading resources", .95f));
+                HotPatchLog.Info("load_complete assembly=" + assemblyName + " version=" + LoadedVersion);
+                return LoadedAssembly;
+            }
+            catch (Exception e)
+            {
+                if (sceneBundle != null) sceneBundle.Unload(false);
+                sceneBundle = null; LoadedScenePath = null;
+                HotPatchLog.Warning($"load_failed assembly={assemblyName} requiresRestart={RequiresRestart} type={e.GetType().Name} reason={e.Message}");
+                throw;
+            }
+            finally { busy = false; }
+        }
+
+        public static void InvokeInitialization(Assembly assembly)
+        {
+            if (assembly == null) throw new ArgumentNullException(nameof(assembly));
+            var methods = assembly.GetTypes()
+                .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
+                .Select(m => new { Method = m, Attribute = m.GetCustomAttribute<HotPatchInitializerAttribute>(false) })
+                .Where(m => m.Attribute != null)
+                .OrderBy(m => m.Attribute.Order)
+                .ThenBy(m => m.Method.DeclaringType.FullName, StringComparer.Ordinal)
+                .ThenBy(m => m.Method.Name, StringComparer.Ordinal).ToArray();
+                                                                                             
+                                                                                    
+            foreach (var item in methods)
+            {
+                var method = item.Method;
+                if (!method.IsStatic || method.ContainsGenericParameters || method.ReturnType != typeof(void) ||
+                    method.GetParameters().Length != 0 || method.IsAbstract ||
+                    (method.Attributes & MethodAttributes.PinvokeImpl) != 0 ||
+                    method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute), false))
+                    throw new InvalidOperationException("[HotPatchInitializer] must be a non-generic, parameterless, non-async static void method: " + method.DeclaringType.FullName + "." + method.Name);
+            }
+            foreach (var item in methods)
+            {
+                try
+                {
+                    HotPatchLog.Info("initializer_start method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name);
+                    item.Method.Invoke(null, null);
+                    HotPatchLog.Info("initializer_complete method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name);
+                }
+                catch (TargetInvocationException e)
+                { throw new InvalidOperationException("Hot patch initialization failed: " + item.Method.DeclaringType.FullName + "." + item.Method.Name, e.InnerException ?? e); }
+            }
+        }
+
+        public static void MarkEntryFailed() => RequiresRestart = true;
+
+        static string CurrentPlatform()
+        {
+#if UNITY_EDITOR
+            return UnityEditor.EditorUserBuildSettings.activeBuildTarget.ToString();
+#else
+            switch (Application.platform)
+            {
+                case RuntimePlatform.WindowsPlayer: return "StandaloneWindows64";
+                case RuntimePlatform.Android: return "Android";
+                case RuntimePlatform.IPhonePlayer: return "iOS";
+                case RuntimePlatform.OSXPlayer: return "StandaloneOSX";
+                case RuntimePlatform.LinuxPlayer: return "StandaloneLinux64";
+                default: throw new PlatformNotSupportedException("Hot patches are not configured for this platform.");
+            }
+#endif
+        }
+
+    }
+}

+ 8 - 0
Runtime/HotPatch/HotPatchService.cs.meta

@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 68528da41aaf4f99b355d2087e69bd09
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}

+ 38 - 0
Runtime/HotPatch/HotPatchUnityGenericReferences.cs

@@ -0,0 +1,38 @@
+using UnityEngine;
+using UnityEngine.Scripting;
+
+namespace HotPatch
+{
+
+
+
+    [Preserve]
+    internal static class HotPatchUnityGenericReferences
+    {
+#if UNITY_IOS
+        [Preserve]
+        static System.Type PreserveIosSupport() => typeof(Unity.Advertisement.IosSupport.ATTrackingStatusBinding);
+#endif
+
+        [Preserve]
+        static void Preserve(GameObject go, Component component)
+        {
+            go.AddComponent<Component>();
+            go.GetComponent<Component>();
+            go.GetComponentInChildren<Component>();
+            go.GetComponentInChildren<Component>(true);
+            go.GetComponentsInChildren<Component>();
+            go.GetComponentsInChildren<Component>(true);
+            component.GetComponent<Component>();
+            component.GetComponentInChildren<Component>();
+            component.GetComponentsInChildren<Component>();
+            component.GetComponentsInChildren<Component>(true);
+            Object.FindAnyObjectByType<Object>();
+            Object.FindFirstObjectByType<Object>();
+            Object.Instantiate<Object>(go);
+            Resources.Load<Object>("");
+            Resources.LoadAll<Object>("");
+            JsonUtility.FromJson<object>("{}");
+        }
+    }
+}

+ 2 - 0
Runtime/HotPatch/HotPatchUnityGenericReferences.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f0838cadfa52f6d49856139035438fe7

+ 37 - 19
Runtime/Plugins/iOS/AppRuntimesNative.mm

@@ -5,6 +5,37 @@
 
 
 extern "C" UIViewController *UnityGetGLViewController(void);
 extern "C" UIViewController *UnityGetGLViewController(void);
 
 
+static void ShowNetworkDialog(const char *message, void (*callback)(int), bool allowCancel)
+{
+    NSString *text = message ? [NSString stringWithUTF8String:message] : @"";
+    dispatch_async(dispatch_get_main_queue(), ^{
+        UIViewController *presenter = UnityGetGLViewController();
+        while (presenter.presentedViewController != nil)
+            presenter = presenter.presentedViewController;
+        if (presenter.isBeingDismissed || presenter.isBeingPresented)
+        {
+            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 10), dispatch_get_main_queue(), ^{
+                ShowNetworkDialog([text UTF8String], callback, allowCancel);
+            });
+            return;
+        }
+        if (presenter == nil || presenter.view.window == nil)
+        {
+            callback(0);
+            return;
+        }
+
+        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Network Error"
+            message:text preferredStyle:UIAlertControllerStyleAlert];
+        [alert addAction:[UIAlertAction actionWithTitle:(allowCancel ? @"Retry" : @"retry") style:UIAlertActionStyleDefault
+            handler:^(UIAlertAction *action) { callback(1); }]];
+        if (allowCancel)
+            [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
+                handler:^(UIAlertAction *action) { callback(0); }]];
+        [presenter presentViewController:alert animated:YES completion:nil];
+    });
+}
+
 extern "C"
 extern "C"
 {
 {
     int AppRuntimes_GetEnableUnityLog()
     int AppRuntimes_GetEnableUnityLog()
@@ -28,24 +59,11 @@ extern "C"
 
 
     void AppRuntimes_ShowDialog(const char *message, void (*callback)(int))
     void AppRuntimes_ShowDialog(const char *message, void (*callback)(int))
     {
     {
-        NSString *text = message ? [NSString stringWithUTF8String:message] : @"";
-        dispatch_async(dispatch_get_main_queue(), ^{
-            UIViewController *presenter = UnityGetGLViewController();
-            while (presenter.presentedViewController != nil)
-                presenter = presenter.presentedViewController;
-            if (presenter == nil || presenter.view.window == nil)
-            {
-                callback(0);
-                return;
-            }
-
-            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Network Error"
-                message:text preferredStyle:UIAlertControllerStyleAlert];
-            [alert addAction:[UIAlertAction actionWithTitle:@"Retry" style:UIAlertActionStyleDefault
-                handler:^(UIAlertAction *action) { callback(1); }]];
-            [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
-                handler:^(UIAlertAction *action) { callback(0); }]];
-            [presenter presentViewController:alert animated:YES completion:nil];
-        });
+        ShowNetworkDialog(message, callback, true);
+    }
+
+    void AppRuntimes_ShowRetryDialog(const char *message, void (*callback)(int))
+    {
+        ShowNetworkDialog(message, callback, false);
     }
     }
 }
 }

+ 8 - 0
Runtime/Scripts/AppRuntimes.Base.asmdef

@@ -0,0 +1,8 @@
+{
+  "name": "AppRuntimes.Base",
+  "references": [
+    "UniTask",
+    "UnityEngine.UI"
+  ],
+  "autoReferenced": false
+}

+ 4 - 0
Runtime/Scripts/AppRuntimes.Base.asmdef.meta

@@ -0,0 +1,4 @@
+fileFormatVersion: 2
+guid: 8466735c35074ba7a84ebeae368991ae
+AssemblyDefinitionImporter:
+  externalObjects: {}

+ 12 - 0
Runtime/Scripts/AppRuntimesEvents.cs

@@ -0,0 +1,12 @@
+using System;
+using UnityEngine;
+
+public static class AppRuntimesEvents
+{
+    public static event Action OnPlatformOpen;
+
+    public static void RaisePlatformOpen() => OnPlatformOpen?.Invoke();
+
+    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
+    private static void ResetEvents() => OnPlatformOpen = null;
+}

+ 2 - 0
Runtime/Scripts/AppRuntimesEvents.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: de31ea43f7e09ff488dced7c5794af45

+ 38 - 2
Runtime/Scripts/AppSettings.cs

@@ -1,10 +1,46 @@
-using GUPS.Obfuscator.Attribute;
 using UnityEngine;
 using UnityEngine;
 
 
-[DoNotObfuscateClass]
+[UnityEngine.Scripting.APIUpdating.MovedFrom(true, sourceNamespace: "", sourceAssembly: "AppRuntimes", sourceClassName: "AppSettings")]
 public sealed class AppSettings : ScriptableObject
 public sealed class AppSettings : ScriptableObject
 {
 {
+    private static AppSettings instance;
+    public static AppSettings Instance
+    {
+        get
+        {
+            if(!instance)
+            {
+                instance = Resources.Load<AppSettings>("AppSettings");
+            }            
+            return instance;
+        }
+    }
+
+
     public string AppAddress = string.Empty;
     public string AppAddress = string.Empty;
     public string AppChannel = string.Empty;
     public string AppChannel = string.Empty;
     public string PrivacyUrl = string.Empty;
     public string PrivacyUrl = string.Empty;
+    [Tooltip("Absolute HTTP(S) URL of the hot patch resource directory or manifest.json")]
+    public string DownloadUrl = string.Empty;
+    [HideInInspector] public bool UseLocalHotPatchResources;
+    [Tooltip("Hot patch assembly name, saved after selecting an asmdef in the AppSettings window")]
+    public string HotPatchAssemblyName = string.Empty;
+    [Tooltip("Game scene to open after loading the hot patch. Built as a separate scene AssetBundle and excluded from the Player scene list.")]
+    public string GameSceneName = string.Empty;
+
+    public static string RequireGameSceneName()
+    {
+        var settings = Resources.Load<AppSettings>("AppSettings");
+        if (settings == null || string.IsNullOrWhiteSpace(settings.GameSceneName))
+            throw new System.InvalidOperationException("Enter the game scene name in AppSettings and click Save.");
+        return settings.GameSceneName.Trim();
+    }
+
+    public static string RequireHotPatchAssemblyName()
+    {
+        var settings = Resources.Load<AppSettings>("AppSettings");
+        if (settings == null || string.IsNullOrWhiteSpace(settings.HotPatchAssemblyName))
+            throw new System.InvalidOperationException("Select the hot patch assembly in AppSettings and click Save.");
+        return settings.HotPatchAssemblyName;
+    }
 }
 }

+ 0 - 220
Runtime/Scripts/ClientCrypto.cs

@@ -1,220 +0,0 @@
-using System;
-using System.Security.Cryptography;
-using System.Text;
-using UnityEngine;
-
-#if UNITY_EDITOR
-using UnityEditor;
-
-public class CryptoTools : EditorWindow
-{
-    private string input = string.Empty;
-    private string output = string.Empty;
-    private string errorMessage = string.Empty;
-    private Vector2 inputScrollPosition;
-    private Vector2 outputScrollPosition;
-
-    [MenuItem("Tools/Crypto Tools")]
-    private static void OpenWindow()
-    {
-        var window = GetWindow<CryptoTools>("Crypto Tools");
-        window.minSize = new Vector2(520f, 420f);
-        window.Show();
-    }
-
-    private void OnGUI()
-    {
-        EditorGUILayout.Space(8f);
-        EditorGUILayout.LabelField("ClientCrypto 字符串加密/解密", EditorStyles.boldLabel);
-        EditorGUILayout.Space(4f);
-
-        EditorGUILayout.LabelField("输入");
-        inputScrollPosition = EditorGUILayout.BeginScrollView(
-            inputScrollPosition,
-            GUILayout.MinHeight(120f));
-        input = EditorGUILayout.TextArea(input, GUILayout.ExpandHeight(true));
-        EditorGUILayout.EndScrollView();
-
-        EditorGUILayout.Space(6f);
-        using (new EditorGUILayout.HorizontalScope())
-        {
-            if (GUILayout.Button("加密", GUILayout.Height(30f)))
-            {
-                TransformInput(ClientCrypto.EncryptString);
-            }
-
-            if (GUILayout.Button("解密", GUILayout.Height(30f)))
-            {
-                TransformInput(ClientCrypto.DecryptString);
-            }
-
-            if (GUILayout.Button("清空", GUILayout.Width(80f), GUILayout.Height(30f)))
-            {
-                input = string.Empty;
-                output = string.Empty;
-                errorMessage = string.Empty;
-                GUI.FocusControl(null);
-            }
-        }
-
-        if (!string.IsNullOrEmpty(errorMessage))
-        {
-            EditorGUILayout.Space(6f);
-            EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
-        }
-
-        EditorGUILayout.Space(8f);
-        EditorGUILayout.LabelField("输出");
-        outputScrollPosition = EditorGUILayout.BeginScrollView(
-            outputScrollPosition,
-            GUILayout.MinHeight(120f));
-        output = EditorGUILayout.TextArea(output, GUILayout.ExpandHeight(true));
-        EditorGUILayout.EndScrollView();
-
-        using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(output)))
-        {
-            using (new EditorGUILayout.HorizontalScope())
-            {
-                if (GUILayout.Button("复制输出"))
-                {
-                    EditorGUIUtility.systemCopyBuffer = output;
-                    ShowNotification(new GUIContent("已复制"));
-                }
-
-                if (GUILayout.Button("输出作为输入"))
-                {
-                    input = output;
-                    errorMessage = string.Empty;
-                }
-            }
-        }
-    }
-
-    private void TransformInput(Func<string, string> transform)
-    {
-        try
-        {
-            output = transform(input);
-            errorMessage = string.Empty;
-            GUI.FocusControl(null);
-        }
-        catch (Exception exception)
-        {
-            output = string.Empty;
-            errorMessage = exception.Message;
-        }
-    }
-
-}
-
-
-#endif
-
-
-public static class ClientCrypto
-{
-    private const string Secret = "ios-platform-api-v2";
-
-    public static string EncryptString(string value)
-    {
-        using (var sha256 = SHA256.Create())
-        using (var aes = Aes.Create())
-        {
-            aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Secret));
-            aes.Mode = CipherMode.CBC;
-            aes.Padding = PaddingMode.PKCS7;
-            aes.GenerateIV();
-
-            byte[] plainBytes = Encoding.UTF8.GetBytes(value);
-            byte[] cipherBytes;
-
-            using (var encryptor = aes.CreateEncryptor())
-            {
-                cipherBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
-            }
-
-            byte[] output = new byte[aes.IV.Length + cipherBytes.Length];
-            Buffer.BlockCopy(aes.IV, 0, output, 0, aes.IV.Length);
-            Buffer.BlockCopy(cipherBytes, 0, output, aes.IV.Length, cipherBytes.Length);
-
-            return "v2:" + Base64UrlEncode(output);
-        }
-    }
-
-    public static string DecryptString(string value)
-    {
-        if (string.IsNullOrEmpty(value) || !value.StartsWith("v2:"))
-        {
-            throw new ArgumentException("加密字符串格式不正确 >> " + value);
-        }
-
-        byte[] bytes = Base64UrlDecode(value.Substring(3));
-        byte[] iv = new byte[16];
-        byte[] cipherBytes = new byte[bytes.Length - 16];
-
-        Buffer.BlockCopy(bytes, 0, iv, 0, 16);
-        Buffer.BlockCopy(bytes, 16, cipherBytes, 0, cipherBytes.Length);
-
-        using (var sha256 = SHA256.Create())
-        using (var aes = Aes.Create())
-        {
-            aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Secret));
-            aes.IV = iv;
-            aes.Mode = CipherMode.CBC;
-            aes.Padding = PaddingMode.PKCS7;
-
-            using (var decryptor = aes.CreateDecryptor())
-            {
-                byte[] plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
-
-                return Encoding.UTF8.GetString(plainBytes);
-            }
-        }
-    }
-
-    public static string EncryptJson(string json)
-    {
-        return EncryptString(json);
-    }
-
-    public static string DecryptJson(string encrypted)
-    {
-        try
-        {
-            return DecryptString(encrypted);
-        }
-        catch (Exception e)
-        {
-            Debug.LogError($"error: {e}");
-            return string.Empty;
-        }
-
-    }
-
-    private static string Base64UrlEncode(byte[] bytes)
-    {
-        return Convert.ToBase64String(bytes)
-            .TrimEnd('=')
-            .Replace('+', '-')
-            .Replace('/', '_');
-    }
-
-    private static byte[] Base64UrlDecode(string value)
-    {
-        string base64 = value.Replace('-', '+').Replace('_', '/');
-
-        switch (base64.Length % 4)
-        {
-            case 2:
-                base64 += "==";
-                break;
-            case 3:
-                base64 += "=";
-                break;
-        }
-
-        return Convert.FromBase64String(base64);
-    }
-
-
-}

+ 10 - 0
Runtime/Scripts/FacebookNativeBridge.cs

@@ -0,0 +1,10 @@
+using System.Runtime.InteropServices;
+
+
+public static class FacebookNativeBridge
+{
+#if UNITY_IOS && !UNITY_EDITOR
+    [DllImport("__Internal")]
+    public static extern void IOS_FBSetDynamicCredentials(string appId, string clientToken);
+#endif
+}

+ 2 - 0
Runtime/Scripts/FacebookNativeBridge.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 718b9ad3d054b4144bcece5ed017553e

+ 14 - 0
Runtime/Scripts/HotPatchInitializerAttribute.cs

@@ -0,0 +1,14 @@
+using System;
+using UnityEngine.Scripting;
+
+namespace HotPatch
+{
+
+    [Preserve]
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
+    public sealed class HotPatchInitializerAttribute : Attribute
+    {
+        public int Order { get; }
+        public HotPatchInitializerAttribute(int order = 0) => Order = order;
+    }
+}

+ 2 - 0
Runtime/Scripts/HotPatchInitializerAttribute.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 141785fecd7a5ae4889387a9fa797aa3

+ 17 - 0
Runtime/Scripts/HotPatchLog.cs

@@ -0,0 +1,17 @@
+using System;
+using UnityEngine;
+
+namespace HotPatch
+{
+
+    public static class HotPatchLog
+    {
+        public const string Prefix = "[HotPatch]";
+        public static void Info(string message) => Debug.Log(Prefix + " " + message);
+        public static void Warning(string message) => Debug.LogWarning(Prefix + " " + message);
+
+
+        public static string SafeUrl(Uri uri) => uri == null ? "<none>" :
+            uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);
+    }
+}

+ 2 - 0
Runtime/Scripts/HotPatchLog.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 6fc3435cd62f98c44bc2f1142e6da25f

+ 18 - 0
Runtime/Scripts/ILaunchResources.cs

@@ -0,0 +1,18 @@
+using System;
+using System.Threading;
+using Cysharp.Threading.Tasks;
+
+public interface ILaunchResources
+{
+    string GameSceneName { get; }
+    string LoadedScenePath { get; }
+    string LoadedVersion { get; }
+    bool HasLoadedAssembly { get; }
+    bool RequiresRestart { get; }
+    UniTask LoadAsync(Action<string, float> progress, CancellationToken cancellationToken);
+    void MarkEntryFailed();
+#if UNITY_EDITOR
+    bool UseEditorSceneLoading { get; }
+    void InitializeEditor();
+#endif
+}

+ 2 - 0
Runtime/Scripts/ILaunchResources.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 5d357ac2e89e34747be892100ad3c4e2

+ 9 - 0
Runtime/Scripts/ILaunchView.cs

@@ -0,0 +1,9 @@
+using System;
+
+public interface ILaunchView
+{
+    bool IsAvailable { get; }
+    void ResetProgress();
+    void ReportProgress(string stage, float progress);
+    void ShowError(string message, Action retry);
+}

+ 2 - 0
Runtime/Scripts/ILaunchView.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 33b3f500969c4834699f4d12349e1e72

+ 150 - 0
Runtime/Scripts/LaunchApp.cs

@@ -0,0 +1,150 @@
+using System;
+using System.Threading;
+using Cysharp.Threading.Tasks;
+using HotPatch;
+using UnityEngine;
+using UnityEngine.SceneManagement;
+
+public sealed class LaunchApp
+{
+    readonly Scene launchScene;
+    readonly ILaunchView view;
+    readonly ILaunchResources resources;
+    readonly CancellationToken cancellationToken;
+
+    public bool IsRunning { get; private set; }
+    public bool IsResourcesReady { get; private set; }
+    public bool IsCompleted { get; private set; }
+
+    public LaunchApp(Scene launchScene, ILaunchView view, ILaunchResources resources, CancellationToken cancellationToken)
+    {
+        this.launchScene = launchScene;
+        this.view = view ?? throw new ArgumentNullException(nameof(view));
+        this.resources = resources ?? throw new ArgumentNullException(nameof(resources));
+        this.cancellationToken = cancellationToken;
+    }
+
+    bool CanRun => !cancellationToken.IsCancellationRequested && view.IsAvailable;
+
+    /// <summary>Updates resources, then invokes onUpdated or opens the game scene when no callback is supplied.</summary>
+    public async UniTask RunAsync(Action onUpdated = null)
+    {
+        if (IsRunning || IsCompleted || !CanRun) return;
+        IsRunning = true;
+        bool showRetryDialog = false;
+        try
+        {
+            HotPatchLog.Info("launch_start scene=" + resources.GameSceneName);
+            if (!IsResourcesReady)
+            {
+                view.ResetProgress();
+                Report("Checking version", 0);
+                await resources.LoadAsync(Report, cancellationToken);
+                cancellationToken.ThrowIfCancellationRequested();
+                IsResourcesReady = true;
+            }
+            if (onUpdated != null) Report("Update complete", 1);
+        }
+        catch (Exception exception)
+        {
+            showRetryDialog = HandleFailure(exception);
+            if (!showRetryDialog) return;
+        }
+        finally
+        {
+            IsRunning = false;
+        }
+        if (showRetryDialog)
+        {
+            ShowRetryDialog(() => RunAsync(onUpdated).Forget(Debug.LogException));
+            return;
+        }
+        if (!CanRun) return;
+        // Release the update guard before invoking user code so the callback can open the scene.
+        if (onUpdated != null) onUpdated();
+        else await OpenSceneAsync();
+    }
+
+    /// <summary>Opens the game scene using resources prepared by a successful RunAsync callback.</summary>
+    public async UniTask OpenSceneAsync()
+    {
+        if (IsRunning || IsCompleted || !CanRun) return;
+        if (!IsResourcesReady)
+            throw new InvalidOperationException("Resources are not ready. Wait for RunAsync to finish updating before opening the game scene.");
+        IsRunning = true;
+        bool showRetryDialog = false;
+        Scene gameScene = default;
+        try
+        {
+            var sceneName = resources.GameSceneName;
+            if (SceneManager.GetSceneByName(sceneName).isLoaded)
+                throw new InvalidOperationException(sceneName + " is already open. Restart the app.");
+            HotPatchLog.Info("scene_load_start scene=" + sceneName + " version=" + resources.LoadedVersion);
+            Report("Loading resources", .95f);
+            var scenePath = resources.LoadedScenePath;
+            AsyncOperation operation;
+#if UNITY_EDITOR
+            if (resources.UseEditorSceneLoading)
+                operation = UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(scenePath, new LoadSceneParameters(LoadSceneMode.Additive));
+            else
+#endif
+                operation = SceneManager.LoadSceneAsync(scenePath, LoadSceneMode.Additive);
+            if (operation == null) throw new InvalidOperationException("Unable to open game scene: " + sceneName);
+            await operation.ToUniTask(progress: Progress.Create<float>(value => Report("Loading resources", .95f + .04f * value)));
+            gameScene = SceneManager.GetSceneByPath(scenePath);
+            cancellationToken.ThrowIfCancellationRequested();
+            if (!gameScene.isLoaded || !SceneManager.SetActiveScene(gameScene))
+                throw new InvalidOperationException("Failed to activate game scene: " + sceneName);
+            HotPatchLog.Info("scene_load_complete scene=" + sceneName + " version=" + resources.LoadedVersion);
+            Report("Loading resources", 1);
+            await UniTask.Yield();
+            cancellationToken.ThrowIfCancellationRequested();
+            LaunchSceneInput.Transfer(launchScene, gameScene);
+#if UNITY_EDITOR
+            await UniTask.NextFrame(cancellationToken: cancellationToken);
+            HotPatchLog.Info("editor_initialization_start scene=" + gameScene.name);
+            resources.InitializeEditor();
+            HotPatchLog.Info("editor_initialization_complete scene=" + gameScene.name);
+#endif
+            await SceneManager.UnloadSceneAsync(launchScene);
+            IsCompleted = true;
+        }
+        catch (Exception exception)
+        {
+            showRetryDialog = HandleFailure(exception);
+            if (gameScene.IsValid() && gameScene.isLoaded) await SceneManager.UnloadSceneAsync(gameScene);
+        }
+        finally
+        {
+            IsRunning = false;
+        }
+        if (showRetryDialog) ShowRetryDialog(() => RunAsync().Forget(Debug.LogException));
+    }
+
+    bool HandleFailure(Exception exception)
+    {
+        IsResourcesReady = false;
+        HotPatchLog.Warning("launch_failed type=" + exception.GetType().Name + " message=" + exception.Message);
+        if (cancellationToken.IsCancellationRequested || exception is OperationCanceledException) return false;
+        if (resources.HasLoadedAssembly) resources.MarkEntryFailed();
+        Debug.LogException(exception);
+        return true;
+    }
+
+    void ShowRetryDialog(Action retry)
+    {
+        if (!CanRun) return;
+        HotPatchLog.Info("retry_dialog_open requiresRestart=" + resources.RequiresRestart);
+        view.ShowError(NativeDialog.NetworkErrorMessage, () =>
+        {
+            if (!CanRun) return;
+            HotPatchLog.Info("retry_dialog_confirmed");
+            retry();
+        });
+    }
+
+    void Report(string stage, float progress)
+    {
+        if (CanRun) view.ReportProgress(stage, progress);
+    }
+}

+ 2 - 0
Runtime/Scripts/LaunchApp.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d004ae1fb692189438fa77b3f25fa184

+ 65 - 0
Runtime/Scripts/LaunchSceneInput.cs

@@ -0,0 +1,65 @@
+using System;
+using System.Linq;
+using HotPatch;
+using UnityEngine;
+using UnityEngine.EventSystems;
+using UnityEngine.SceneManagement;
+
+
+public static class LaunchSceneInput
+{
+    public static EventSystem Transfer(Scene launchScene, Scene gameScene)
+    {
+        if (!launchScene.IsValid() || !launchScene.isLoaded || !gameScene.IsValid() || !gameScene.isLoaded || launchScene == gameScene)
+            throw new ArgumentException("Input transfer requires two different loaded scenes.");
+
+        var gameSystems = SystemsIn(gameScene);
+        var launchSystems = SystemsIn(launchScene);
+        var selected = gameSystems.FirstOrDefault(IsUsable);
+        var source = "game";
+        if (selected == null && IsUsable(EventSystem.current) && EventSystem.current.gameObject.scene != launchScene)
+        {
+
+            selected = EventSystem.current;
+            source = "shared";
+        }
+        if (selected == null)
+        {
+            selected = launchSystems.FirstOrDefault(IsUsable);
+            source = "launch";
+        }
+        if (selected == null)
+        {
+            selected = new GameObject("EventSystem", typeof(EventSystem), typeof(StandaloneInputModule)).GetComponent<EventSystem>();
+            SceneManager.MoveGameObjectToScene(selected.gameObject, gameScene);
+            source = "created";
+        }
+        else if (selected.gameObject.scene == launchScene)
+        {
+
+            selected.transform.SetParent(null, true);
+            SceneManager.MoveGameObjectToScene(selected.gameObject, gameScene);
+        }
+
+        foreach (var duplicate in launchSystems.Concat(gameSystems).Where(system => system != selected))
+        {
+            foreach (var module in duplicate.GetComponents<BaseInputModule>()) module.enabled = false;
+            duplicate.enabled = false;
+        }
+        EventSystem.current = selected;
+        if (selected.currentSelectedGameObject != null && selected.currentSelectedGameObject.scene == launchScene)
+            selected.SetSelectedGameObject(null);
+        if (selected.firstSelectedGameObject != null && selected.firstSelectedGameObject.scene == launchScene)
+            selected.firstSelectedGameObject = null;
+
+        HotPatchLog.Info("scene_input_ready source=" + source + " scene=" + selected.gameObject.scene.name +
+            " modules=" + string.Join(",", selected.GetComponents<BaseInputModule>().Where(module => module.isActiveAndEnabled).Select(module => module.GetType().Name)));
+        return selected;
+    }
+
+    static EventSystem[] SystemsIn(Scene scene) => scene.GetRootGameObjects()
+        .SelectMany(root => root.GetComponentsInChildren<EventSystem>(true)).ToArray();
+
+    static bool IsUsable(EventSystem system) => system != null && system.isActiveAndEnabled &&
+        system.GetComponents<BaseInputModule>().Any(module => module.isActiveAndEnabled);
+}

+ 2 - 0
Runtime/Scripts/LaunchSceneInput.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 76605615ca2add8409b8a7a76b67bffc

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません