找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/resource/findobjects/ScriptlessLevelBundleDownloader.ts
1import { assetManager } from "cc";
2import { Framework } from "../../../Framework";
3import { ResourceMode } from "../ResourceFrameConfig";
4
5interface ScriptlessBundleConfig {
6 name?: string;
7 base?: string;
8 hasPreloadScript?: boolean;
9 isZip?: boolean;
10}
11
12type BundleDownloadComplete = (error: Error | null, data?: ScriptlessBundleConfig) => void;
13type BundleDownloadHandler = (
14 nameOrUrl: string,
15 options: Record<string, any>,
16 onComplete: BundleDownloadComplete,
17) => void;
18
19interface CocosDownloaderInternals {
20 handlers: Record<string, BundleDownloadHandler>;
21 _downloadJson: (
22 url: string,
23 options: Record<string, any>,
24 onComplete: BundleDownloadComplete,
25 ) => void;
26}
27
28interface CocosAssetManagerInternals {
29 cacheManager?: {
30 makeBundleFolder: (bundleName: string) => void;
31 };
32}
33
34interface SystemRegisterContext {
35 register: (
36 moduleId: string,
37 dependencies: string[],
38 declare: (exportModule: (exports: Record<string, any>) => void) => {
39 setters?: Array<(moduleExports: Record<string, any>) => void>;
40 execute: () => void;
41 },
42 ) => void;
43}
44
45interface GlobalSystemRegister {
46 System?: SystemRegisterContext;
47}
48
49/**
50 * 让远程关卡 Bundle 直接读取 config,不依赖小游戏代码包中的 bundle-scripts/index.js。
51 * 仅适用于不包含独立业务脚本的纯资源关卡 Bundle。
52 */
53export class ScriptlessLevelBundleDownloader {
54 private static isRegistered: boolean = false;
55 // 保存安装前的 handler,专项模块退出时撤销自己的全局适配。
56 private static originalHandler: BundleDownloadHandler | null = null;
57 private static installedHandler: BundleDownloadHandler | null = null;
58 private static registeredBundleModules: Set<string> = new Set();
59
60 public static Register(): void {
61 if (this.isRegistered) {
62 return;
63 }
64
65 const downloader = assetManager.downloader as typeof assetManager.downloader & CocosDownloaderInternals;
66 const originalHandler = downloader.handlers.bundle as BundleDownloadHandler | undefined;
67 if (!originalHandler) {
68 throw new Error("Cocos bundle download handler not found");
69 }
70
71 const handler: BundleDownloadHandler = (
72 nameOrUrl: string,
73 options: Record<string, any>,
74 onComplete: BundleDownloadComplete,
75 ): void => {
76 const bundleName = this.GetBundleName(nameOrUrl);
77 if (!this.isRegistered || !this.IsRemoteLevelBundle(nameOrUrl, bundleName)) {
78 originalHandler(nameOrUrl, options, onComplete);
79 return;
80 }
81 this.DownloadRemoteLevelBundleConfig(nameOrUrl, bundleName, options, onComplete);
82 };
83 this.originalHandler = originalHandler;
84 this.installedHandler = handler;
85 downloader.register("bundle", handler);
86
87 this.isRegistered = true;
88 console.log("[ScriptlessLevelBundleDownloader] Registered");
89 }
90
91 /** 仅撤销自己的注册,不覆盖之后由其他模块安装的 handler。 */
92 public static Unregister(): void {
93 if (!this.isRegistered) return;
94 const downloader = assetManager.downloader as typeof assetManager.downloader & CocosDownloaderInternals;
95 if (downloader.handlers.bundle === this.installedHandler && this.originalHandler) {
96 downloader.register("bundle", this.originalHandler);
97 }
98 this.isRegistered = false;
99 this.originalHandler = null;
100 this.installedHandler = null;
101 // System 模块在进程中仍存在,保留去重集合以免重启后重复注册。
102 }
103
104 private static IsRemoteLevelBundle(nameOrUrl: string, bundleName: string): boolean {
105 const isLevelBundle = /^level\d+(?:_\d+)?$/i.test(bundleName);
106 const isRemoteUrl = /^https?:\/\//i.test(nameOrUrl);
107 return isLevelBundle && isRemoteUrl;
108 }
109
110 private static GetBundleName(nameOrUrl: string): string {
111 const normalizedUrl = nameOrUrl.replace(/[?#].*$/, "").replace(/\/+$/, "");
112 const lastSlashIndex = normalizedUrl.lastIndexOf("/");
113 return normalizedUrl.slice(lastSlashIndex + 1);
114 }
115
116 private static DownloadRemoteLevelBundleConfig(
117 bundleUrl: string,
118 bundleName: string,
119 options: Record<string, any>,
120 onComplete: BundleDownloadComplete,
121 ): void {
122 const version = String(options.version || "");
123 const normalizedBundleUrl = bundleUrl.replace(/\/+$/, "");
124 // 模拟服务无哈希;正式远端必须有版本,避免加载错误资源。
125 let configName = "config.json";
126 if (Framework.Res.Config.ResourceMode !== ResourceMode.LocalSimulateRemote) {
127 if (!version) {
128 onComplete(new Error(`Bundle version is missing: ${bundleName}`));
129 return;
130 }
131 configName = `config.${version}.json`;
132 }
133 const configUrl = `${normalizedBundleUrl}/${configName}`;
134 options.__cacheBundleRoot__ = bundleName;
135
136 const assetManagerInternals = assetManager as typeof assetManager & CocosAssetManagerInternals;
137 assetManagerInternals.cacheManager?.makeBundleFolder(bundleName);
138 console.log(`[ScriptlessLevelBundleDownloader] Download config: ${configUrl}`);
139
140 const downloader = assetManager.downloader as typeof assetManager.downloader & CocosDownloaderInternals;
141 downloader._downloadJson(configUrl, options, (error: Error | null, data?: ScriptlessBundleConfig): void => {
142 if (error) {
143 onComplete(error);
144 return;
145 }
146
147 const config = data || null;
148 if (!config) {
149 onComplete(new Error(`Bundle config is empty: ${configUrl}`));
150 return;
151 }
152 if (config.name !== bundleName) {
153 onComplete(new Error(`Bundle config name mismatch: expected=${bundleName}, actual=${config.name || ""}`));
154 return;
155 }
156 if (config.hasPreloadScript !== false) {
157 onComplete(new Error(`Bundle is not scriptless: ${bundleName}`));
158 return;
159 }
160 if (config.isZip) {
161 onComplete(new Error(`Scriptless zipped Bundle is not supported: ${bundleName}`));
162 return;
163 }
164
165 try {
166 this.RegisterEmptyBundleModule(bundleName);
167 } catch (registerError) {
168 let errorMessage = String(registerError);
169 if (registerError instanceof Error) {
170 errorMessage = registerError.message;
171 }
172 onComplete(new Error(`Register scriptless Bundle module failed: ${bundleName}, ${errorMessage}`));
173 return;
174 }
175
176 config.base = `${normalizedBundleUrl}/`;
177 onComplete(null, config);
178 });
179 }
180
181 /** 复刻 Cocos 为纯资源 Bundle 生成的空 index.js 注册行为。 */
182 private static RegisterEmptyBundleModule(bundleName: string): void {
183 if (this.registeredBundleModules.has(bundleName)) {
184 return;
185 }
186
187 const globalSystem = globalThis as typeof globalThis & GlobalSystemRegister;
188 const system = globalSystem.System;
189 if (!system) {
190 throw new Error("System.register is unavailable");
191 }
192
193 const chunkModuleId = `chunks:///_virtual/${bundleName}`;
194 const prerequisiteModuleId = `virtual:///prerequisite-imports/${bundleName}`;
195
196 system.register(chunkModuleId, [], () => ({
197 execute: (): void => {},
198 }));
199
200 system.register(prerequisiteModuleId, [chunkModuleId], (exportModule) => ({
201 setters: [(moduleExports): void => {
202 const exports: Record<string, any> = {};
203 for (const key of Object.keys(moduleExports)) {
204 if (key !== "default" && key !== "__esModule") {
205 exports[key] = moduleExports[key];
206 }
207 }
208 exportModule(exports);
209 }],
210 execute: (): void => {},
211 }));
212
213 this.registeredBundleModules.add(bundleName);
214 console.log(`[ScriptlessLevelBundleDownloader] Registered empty module: ${prerequisiteModuleId}`);
215 }
216}
讲解217 行
纯资源关卡包下载适配人工通读

ScriptlessLevelBundleDownloader.ts

替换引擎 bundle 下载处理器,让不含业务脚本的远程关卡包直接读取 config.json,并补注册空的 System 模块。寻物加载器在 Init 安装、DeInit 撤销,通用项目不会受影响。

先看 Register 如何包装原处理器,再看 DownloadRemoteLevelBundleConfig 的校验链,最后看空模块注册。

特殊处理与易错点

20属性handlers(Record<string, BundleDownloadHandler>):该模块的运行态字
53注释ScriptlessLevelBundleDownloader:让远程关卡 Bundle 直接读取 config,不依赖小游戏代码包中的 bundle-sc
56注释保存安装前的 handler,专项模块退出时撤销自己的全局适配。
60方法保存引擎原 bundle 处理器并注册包装处理器,重复调用直接返回,缺失原处理器时抛错。
92方法若当前处理器仍是自己安装的则恢复原处理器,并清空两个处理器引用和注册标记。
102注释System 模块在进程中仍存在,保留去重集合以免重启后重复注册。
104方法同时判断包名是否为 level 加数字、地址是否为 http 开头,两者都满足才接管。
110方法去掉查询串、哈希和末尾斜杠后取最后一段,得到 Bundle 名。
116方法按模式决定配置文件名,校验配置字段后注册空模块,把 base 指向 Bundle 地址并回调成功。
125注释模拟服务无哈希;正式远端必须有版本,避免加载错误资源。
182方法注册空的 chunk 与 prerequisite 模块,已注册过则跳过。