mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-20 23:52:40 +08:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eec2a1693b | |||
| 632f9b442f | |||
| 8ce19b658e | |||
| 07f2c5fb43 | |||
| 9b17fd6165 | |||
| e2795f9ecd | |||
| 89a412e0d6 | |||
| aef31099d8 | |||
| 89f8768e57 | |||
| 424be5d0b2 |
@@ -567,7 +567,7 @@ export class Sprite extends UIRenderer {
|
||||
if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
|
||||
const rtMatName = `rt-${mat.name}`;
|
||||
let rtMat = builtinResMgr.get(rtMatName) as Material | null;
|
||||
if (!rtMat) {
|
||||
if (!rtMat || !rtMat.passes.length) {
|
||||
rtMat = new Material(rtMatName);
|
||||
rtMat.copy(mat, { defines: { SAMPLE_FROM_RT: true } });
|
||||
builtinResMgr.addAsset(rtMatName, rtMat);
|
||||
|
||||
@@ -536,7 +536,7 @@ export class UIRenderer extends Renderer {
|
||||
const mat = this._updateBuiltinMaterial();
|
||||
this.setSharedMaterial(mat, 0);
|
||||
if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
|
||||
this.getMaterialInstance(0)!.recompileShaders({ USE_ALPHA_TEST: true });
|
||||
this.getMaterialInstance(0)?.recompileShaders({ USE_ALPHA_TEST: true });
|
||||
}
|
||||
this._updateBlendFunc();
|
||||
}
|
||||
@@ -600,16 +600,24 @@ export class UIRenderer extends Renderer {
|
||||
*/
|
||||
public _updateBlendFunc (): void {
|
||||
// todo: Not only Pass[0].target[0]
|
||||
let target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0];
|
||||
const renderMat = this.getRenderMaterial(0);
|
||||
if (!renderMat || !renderMat.passes[0]) {
|
||||
return;
|
||||
}
|
||||
let target = renderMat.passes[0].blendState.targets[0];
|
||||
this._dstBlendFactorCache = target.blendDst;
|
||||
this._srcBlendFactorCache = target.blendSrc;
|
||||
if (this._dstBlendFactorCache !== this._dstBlendFactor || this._srcBlendFactorCache !== this._srcBlendFactor) {
|
||||
target = this.getMaterialInstance(0)!.passes[0].blendState.targets[0];
|
||||
const matInstance = this.getMaterialInstance(0);
|
||||
if (!matInstance || !matInstance.passes[0]) {
|
||||
return;
|
||||
}
|
||||
target = matInstance.passes[0].blendState.targets[0];
|
||||
target.blend = true;
|
||||
target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
|
||||
target.blendDst = this._dstBlendFactor;
|
||||
target.blendSrc = this._srcBlendFactor;
|
||||
const targetPass = this.getMaterialInstance(0)!.passes[0];
|
||||
const targetPass = matInstance.passes[0];
|
||||
targetPass.blendState.setTarget(0, target);
|
||||
targetPass._updatePassHash();
|
||||
this._dstBlendFactorCache = this._dstBlendFactor;
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
import { CULL_MESHOPT, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
||||
|
||||
import { sys, logID, error } from '../../core';
|
||||
import { sys, error, debugID } from '../../core';
|
||||
|
||||
import { game } from '../../game';
|
||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||
@@ -53,7 +53,7 @@ function initDecoderASM (asm_factory: any): Promise<void> {
|
||||
MeshoptDecoder.decodeGltfBuffer = asm_factory.decodeGltfBuffer;
|
||||
MeshoptDecoder.useWorkers = asm_factory.useWorkers;
|
||||
MeshoptDecoder.decodeGltfBufferAsync = asm_factory.decodeGltfBufferAsync;
|
||||
logID(14202);
|
||||
debugID(14202);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ function initDecoderWASM (wasm_factory: any, wasm_url: string): Promise<void> {
|
||||
MeshoptDecoder.decodeGltfBuffer = wasm_factory.decodeGltfBuffer;
|
||||
MeshoptDecoder.useWorkers = wasm_factory.useWorkers;
|
||||
MeshoptDecoder.decodeGltfBufferAsync = wasm_factory.decodeGltfBufferAsync;
|
||||
logID(14203);
|
||||
debugID(14203);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -195,8 +195,8 @@ function define (className, baseClass, options): any {
|
||||
renderName = 'render_stage';
|
||||
}
|
||||
// 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里
|
||||
if (globalThis.EditorExtends) {
|
||||
globalThis.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
|
||||
if (window.EditorExtends) {
|
||||
window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,13 +204,7 @@ function define (className, baseClass, options): any {
|
||||
// cc-class is defined by `cc.Class({/* ... */})`.
|
||||
// In such case, `options.ctor` may be `undefined`.
|
||||
// So we can not use `options.ctor`. Instead, we should use `cls` which is the "real" registered cc-class.
|
||||
// Emit via globalThis.EditorExtends to ensure the event reaches
|
||||
// both the engine-internal and the scene-bundle event systems.
|
||||
if (globalThis.EditorExtends) {
|
||||
globalThis.EditorExtends.emit('class-registered', cls, frame, className);
|
||||
} else {
|
||||
EditorExtends.emit('class-registered', cls, frame, className);
|
||||
}
|
||||
EditorExtends.emit('class-registered', cls, frame, className);
|
||||
}
|
||||
|
||||
if (frame) {
|
||||
|
||||
@@ -26,7 +26,7 @@ import { instantiateWasm, ensureWasmModuleReady } from 'pal/wasm';
|
||||
import { BUILD, LOAD_BOX2D_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||
|
||||
import { game } from '../../game';
|
||||
import { error, sys, IVec2Like, log } from '../../core';
|
||||
import { error, sys, IVec2Like, log, debug } from '../../core';
|
||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||
|
||||
// eslint-disable-next-line import/no-mutable-exports
|
||||
@@ -148,7 +148,7 @@ function initWasm (wasmFactory, wasmUrl: string): Promise<void> {
|
||||
}).catch((err) => reject(errorMessage(err)));
|
||||
},
|
||||
}).then((Instance: any) => {
|
||||
log('[box2d]:box2d wasm lib loaded.');
|
||||
debug('[box2d]:box2d wasm lib loaded.');
|
||||
B2 = Instance;
|
||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||
});
|
||||
@@ -158,7 +158,7 @@ function initAsm (asmFactory): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const errorMessage = (err: any): string => `[box2d]: box2d asm lib load failed: ${err}`;
|
||||
asmFactory().then((instance: any) => {
|
||||
log('[box2d]:box2d asm lib loaded.');
|
||||
debug('[box2d]:box2d asm lib loaded.');
|
||||
B2 = instance;
|
||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||
});
|
||||
|
||||
@@ -27,7 +27,7 @@ import { EDITOR, DEBUG, TEST, EDITOR_NOT_IN_PREVIEW } from 'internal:constants';
|
||||
import { IRigidBody2D } from '../spec/i-rigid-body';
|
||||
import { IBoxShape, ICircleShape, IPolygonShape, IBaseShape } from '../spec/i-physics-shape';
|
||||
import { IPhysicsWorld } from '../spec/i-physics-world';
|
||||
import { errorID, log } from '../../core';
|
||||
import { debug, errorID, log } from '../../core';
|
||||
import { ECollider2DType, EJoint2DType } from './physics-types';
|
||||
import { IJoint2D, IDistanceJoint, ISpringJoint, IFixedJoint, IMouseJoint,
|
||||
IRelativeJoint, ISliderJoint, IWheelJoint, IHingeJoint } from '../spec/i-physics-joint';
|
||||
@@ -110,7 +110,7 @@ export interface IPhysicsSelector {
|
||||
}
|
||||
|
||||
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS2D]: register ${id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: register ${id}.`);
|
||||
selector.backend[id] = wrapper;
|
||||
if (!selector.physicsWorld || selector.id === id) {
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
@@ -124,12 +124,12 @@ function switchTo (id: IPhysicsEngineId): void {
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
||||
//selector.physicsWorld.destroy();//todo
|
||||
if (!TEST) log(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
|
||||
if (!TEST) debug(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
|
||||
mutableSelector.id = id;
|
||||
mutableSelector.wrapper = selector.backend[id];
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
} else {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS2D]: using ${mutableSelector.id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: using ${mutableSelector.id}.`);
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
||||
import { BUILD, LOAD_BULLET_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||
import { game } from '../../game';
|
||||
import { error, log, sys } from '../../core';
|
||||
import { debug, error, sys } from '../../core';
|
||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||
import type { BulletCache } from './bullet-cache';
|
||||
|
||||
@@ -106,7 +106,7 @@ function initWASM (wasmFactory, wasmUrl: string): Promise<void> {
|
||||
}).catch((err) => reject(errorMessage(err)));
|
||||
},
|
||||
}).then((instance: any) => {
|
||||
log('[bullet]:bullet wasm lib loaded.');
|
||||
debug('[bullet]:bullet wasm lib loaded.');
|
||||
bt = instance as Bullet.instance;
|
||||
globalThis.Bullet = bt as any;
|
||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||
@@ -117,7 +117,7 @@ function initASM (asmFactory): Promise<void> {
|
||||
if (asmFactory != null) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return asmFactory().then((instance: any) => {
|
||||
log('[bullet]:bullet asm lib loaded.');
|
||||
debug('[bullet]:bullet asm lib loaded.');
|
||||
bt = instance as Bullet.instance;
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
import { IPhysicsWorld } from '../spec/i-physics-world';
|
||||
import { IRigidBody } from '../spec/i-rigid-body';
|
||||
import { IBoxCharacterController, ICapsuleCharacterController } from '../spec/i-character-controller';
|
||||
import { errorID, IVec3Like, warn, cclegacy, log } from '../../core';
|
||||
import { errorID, IVec3Like, warn, cclegacy, debug } from '../../core';
|
||||
import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum';
|
||||
import { PhysicsMaterial } from '.';
|
||||
|
||||
@@ -125,7 +125,7 @@ function updateLegacyMacro (id: string): void {
|
||||
}
|
||||
|
||||
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS]: register ${id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS]: register ${id}.`);
|
||||
selector.backend[id] = wrapper;
|
||||
if (!selector.physicsWorld || selector.id === id) {
|
||||
updateLegacyMacro(id);
|
||||
@@ -147,13 +147,13 @@ function switchTo (id: IPhysicsEngineId): void {
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
||||
selector.physicsWorld.destroy();
|
||||
if (!TEST) log(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
|
||||
if (!TEST) debug(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
|
||||
updateLegacyMacro(id);
|
||||
mutableSelector.id = id;
|
||||
mutableSelector.wrapper = selector.backend[id];
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
} else {
|
||||
if (!EDITOR && !TEST) log(`[PHYSICS]: using ${id}.`);
|
||||
if (!EDITOR && !TEST) debug(`[PHYSICS]: using ${id}.`);
|
||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
}
|
||||
if (worldInitData) {
|
||||
@@ -185,7 +185,7 @@ export function constructDefaultWorld (data: IWorldInitData): void {
|
||||
if (!worldInitData) worldInitData = data;
|
||||
if (!selector.runInEditor) return;
|
||||
if (!selector.physicsWorld) {
|
||||
if (!TEST) log(`[PHYSICS]: using ${selector.id}.`);
|
||||
if (!TEST) debug(`[PHYSICS]: using ${selector.id}.`);
|
||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||
const world = mutableSelector.physicsWorld = createPhysicsWorld();
|
||||
world.setGravity(worldInitData.gravity);
|
||||
|
||||
@@ -817,11 +817,20 @@ export class LightResource {
|
||||
this.lightIndex.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Adds a light to the light buffer and returns its byte offset.
|
||||
* @zh 将光源添加到光源缓冲区,并返回其字节偏移量。
|
||||
* @param light @en The light to add. @zh 要添加的光源。
|
||||
* @param bHDR @en Whether HDR rendering is enabled. @zh 是否启用 HDR 渲染。
|
||||
* @param exposure @en The camera exposure value. @zh 相机曝光值。
|
||||
* @param shadowInfo @en The shadow settings, or null if shadows are disabled. @zh 阴影设置,若禁用阴影则为 null。
|
||||
* @returns @en The byte offset of the light in the light buffer. @zh 光源在光源缓冲区中的字节偏移量。
|
||||
*/
|
||||
addLight (light: Light, bHDR: boolean, exposure: number, shadowInfo: Shadows | null): number {
|
||||
// Already added
|
||||
const existingLightID = this.lightIndex.get(light);
|
||||
if (existingLightID !== undefined) {
|
||||
return existingLightID;
|
||||
return existingLightID * this.elementSize;
|
||||
}
|
||||
|
||||
if (!this.lightBuffer) {
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@
|
||||
import { cclegacy } from './core/global-exports';
|
||||
import { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
||||
import { Device, deviceManager } from './gfx';
|
||||
import { settings, Settings, warnID, Pool, macro, log } from './core';
|
||||
import { settings, Settings, warnID, Pool, macro, log, debug } from './core';
|
||||
import { PipelineEventProcessor } from './rendering/pipeline-event';
|
||||
import type { Root as JsbRoot } from './root';
|
||||
|
||||
@@ -242,7 +242,7 @@ rootProto.setRenderPipeline = function (customPipeline: boolean) {
|
||||
if (customPipeline) {
|
||||
cclegacy.rendering.createCustomPipeline();
|
||||
ppl = oldSetPipeline.call(this, null);
|
||||
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
} else {
|
||||
// pipeline should not be created in C++, ._ctor need to be triggered
|
||||
if (cclegacy.legacy_rendering) {
|
||||
|
||||
+3
-3
@@ -23,7 +23,7 @@
|
||||
*/
|
||||
|
||||
import { USE_XR } from 'internal:constants';
|
||||
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory } from './core';
|
||||
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory, debug } from './core';
|
||||
import { DebugView } from './rendering/debug-view';
|
||||
import { Camera, CameraType, Light, Model, TrackingType } from './render-scene/scene';
|
||||
import type { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
||||
@@ -380,11 +380,11 @@ export class Root {
|
||||
isCreateDefaultPipeline = true;
|
||||
this._pipeline = this._customPipeline!;
|
||||
// Use default _pipelineEvent
|
||||
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||
} else {
|
||||
const rppl: (PipelineRuntime & IPipelineEvent) = legacy_rendering.createDefaultPipeline();
|
||||
isCreateDefaultPipeline = true;
|
||||
log(`Using legacy pipeline`);
|
||||
debug(`Using legacy pipeline`);
|
||||
|
||||
this._classicPipeline = rppl!;
|
||||
this._pipeline = this._classicPipeline;
|
||||
|
||||
@@ -244,6 +244,20 @@
|
||||
"faceCount": 0.1
|
||||
}
|
||||
]
|
||||
},
|
||||
"legacyFbxImporter": false,
|
||||
"allowMeshDataAccess": true,
|
||||
"addVertexColor": false,
|
||||
"generateLightmapUVNode": false,
|
||||
"meshOptimizer": {
|
||||
"enable": false,
|
||||
"algorithm": "simplify",
|
||||
"simplifyOptions": {
|
||||
"targetRatio": 1,
|
||||
"enableSmartLink": true,
|
||||
"agressiveness": 7,
|
||||
"maxIterationCount": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.22",
|
||||
"version": "4.0.0-alpha.24",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.22",
|
||||
"version": "4.0.0-alpha.24",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.22",
|
||||
"version": "4.0.0-alpha.24",
|
||||
"description": "Cocos Creator is a cross-platform 2D & 3D game engine written in C++ and TypeScript, licensed under MIT.",
|
||||
"homepage": "http://www.cocos.com",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
const cacheManager = require('./cache-manager');
|
||||
const { readText, readArrayBuffer, readJson, loadSubpackage, getUserDataPath, _subpackagesPath } = require('./fs-utils');
|
||||
|
||||
//cc.assetManager.fsUtils = ral.fsUtils;
|
||||
const { readText, readArrayBuffer, readJson, getUserDataPath } = require('./fs-utils');
|
||||
|
||||
const REGEX = /^https?:\/\/.*/;
|
||||
|
||||
const downloader = cc.assetManager.downloader;
|
||||
const parser = cc.assetManager.parser;
|
||||
const presets = cc.assetManager.presets;
|
||||
downloader.maxConcurrency = 12;
|
||||
downloader.maxRequestsPerFrame = 64;
|
||||
presets.scene.maxConcurrency = 12;
|
||||
downloader.maxConcurrency = 30;
|
||||
downloader.maxRequestsPerFrame = 60;
|
||||
presets.preload.maxConcurrency = 15;
|
||||
presets.preload.maxRequestsPerFrame = 30;
|
||||
presets.scene.maxConcurrency = 32;
|
||||
presets.scene.maxRequestsPerFrame = 64;
|
||||
presets.bundle.maxConcurrency = 32;
|
||||
presets.bundle.maxRequestsPerFrame = 64;
|
||||
|
||||
const subpackages = {};
|
||||
const loadedScripts = {};
|
||||
|
||||
function downloadScript (url, options, onComplete) {
|
||||
if (typeof options === 'function') {
|
||||
onComplete = options;
|
||||
options = null;
|
||||
options = {};
|
||||
}
|
||||
|
||||
if (loadedScripts[url]) {
|
||||
onComplete && onComplete();
|
||||
return;
|
||||
onComplete && onComplete();
|
||||
return;
|
||||
}
|
||||
|
||||
download(url, (src, options, onComplete) => {
|
||||
@@ -97,19 +98,14 @@ function downloadJson (url, options, onComplete) {
|
||||
download(url, parseJson, options, options.onFileProgress, onComplete);
|
||||
}
|
||||
|
||||
function downloadArrayBuffer (url, options, onComplete) {
|
||||
download(url, parseArrayBuffer, options, options.onFileProgress, onComplete);
|
||||
}
|
||||
|
||||
function loadFont (url, options, onComplete) {
|
||||
// nodejs 环境没有 document/FontFace API,不支持字体加载
|
||||
const fontFamilyName = _getFontFamily(url);
|
||||
|
||||
const fontFace = new FontFace(fontFamilyName, `url('${url}')`);
|
||||
document.fonts.add(fontFace);
|
||||
|
||||
fontFace.load();
|
||||
fontFace.loaded.then(() => {
|
||||
onComplete(null, fontFamilyName);
|
||||
}, () => {
|
||||
cc.warnID(4933, fontFamilyName);
|
||||
onComplete(null, fontFamilyName);
|
||||
});
|
||||
onComplete(null, fontFamilyName);
|
||||
}
|
||||
|
||||
function _getFontFamily (fontHandle) {
|
||||
@@ -126,6 +122,9 @@ function _getFontFamily (fontHandle) {
|
||||
} else {
|
||||
fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`;
|
||||
}
|
||||
if (fontFamilyName.indexOf(' ') !== -1) {
|
||||
fontFamilyName = `"${fontFamilyName}"`;
|
||||
}
|
||||
return fontFamilyName;
|
||||
}
|
||||
|
||||
@@ -143,11 +142,11 @@ function downloadBundle (nameOrUrl, options, onComplete) {
|
||||
url = nameOrUrl;
|
||||
cacheManager.makeBundleFolder(bundleName);
|
||||
} else if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
|
||||
url = `${downloader.remoteServerAddress}remote/${bundleName}`;
|
||||
cacheManager.makeBundleFolder(bundleName);
|
||||
} else {
|
||||
url = `assets/${bundleName}`;
|
||||
}
|
||||
url = `${downloader.remoteServerAddress}remote/${bundleName}`;
|
||||
cacheManager.makeBundleFolder(bundleName);
|
||||
} else {
|
||||
url = `assets/${bundleName}`;
|
||||
}
|
||||
const config = `${url}/cc.config.${version ? `${version}.` : ''}json`;
|
||||
options.__cacheBundleRoot__ = bundleName;
|
||||
downloadJson(config, options, (err, response) => {
|
||||
@@ -159,7 +158,7 @@ function downloadBundle (nameOrUrl, options, onComplete) {
|
||||
out && (out.base = `${url}/`);
|
||||
|
||||
if (out.hasPreloadScript) {
|
||||
const js = `${url}/index.${version ? `${version}.` : ''}${out.encrypted ? 'jsc' : `js`}`;
|
||||
const js = `${url}/index.${version ? `${version}.` : ''}${out.encrypted ? 'jsc' : 'js'}`;
|
||||
downloadScript(js, options, (err) => {
|
||||
if (err) {
|
||||
onComplete(err, null);
|
||||
@@ -173,10 +172,6 @@ function downloadBundle (nameOrUrl, options, onComplete) {
|
||||
});
|
||||
}
|
||||
|
||||
function downloadArrayBuffer (url, options, onComplete) {
|
||||
download(url, parseArrayBuffer, options, options.onFileProgress, onComplete);
|
||||
}
|
||||
|
||||
const originParsePVRTex = parser.parsePVRTex;
|
||||
const parsePVRTex = function (file, options, onComplete) {
|
||||
readArrayBuffer(file, (err, data) => {
|
||||
@@ -240,6 +235,7 @@ downloader.register({
|
||||
'.pkm': downloadAsset,
|
||||
'.astc': downloadAsset,
|
||||
|
||||
// Font
|
||||
'.font': downloadAsset,
|
||||
'.eot': downloadAsset,
|
||||
'.ttf': downloadAsset,
|
||||
@@ -267,6 +263,7 @@ downloader.register({
|
||||
'.dbbin': downloadAsset,
|
||||
'.skel': downloadAsset,
|
||||
|
||||
// Video
|
||||
'.mp4': downloadAsset,
|
||||
'.avi': downloadAsset,
|
||||
'.mov': downloadAsset,
|
||||
@@ -281,6 +278,7 @@ downloader.register({
|
||||
});
|
||||
|
||||
parser.register({
|
||||
// Image
|
||||
'.png': downloader.downloadDomImage,
|
||||
'.jpg': downloader.downloadDomImage,
|
||||
'.bmp': downloader.downloadDomImage,
|
||||
@@ -290,10 +288,13 @@ parser.register({
|
||||
'.tiff': downloader.downloadDomImage,
|
||||
'.image': downloader.downloadDomImage,
|
||||
'.webp': downloader.downloadDomImage,
|
||||
|
||||
// Compressed texture
|
||||
'.pvr': parsePVRTex,
|
||||
'.pkm': parsePKMTex,
|
||||
'.astc': parseASTCTex,
|
||||
|
||||
// Font
|
||||
'.font': loadFont,
|
||||
'.eot': loadFont,
|
||||
'.ttf': loadFont,
|
||||
@@ -319,6 +320,7 @@ parser.register({
|
||||
'.fnt': parseText,
|
||||
'.plist': parsePlist,
|
||||
|
||||
// Binary
|
||||
'.binary': parseArrayBuffer,
|
||||
'.bin': parseArrayBuffer,
|
||||
'.dbbin': parseArrayBuffer,
|
||||
@@ -327,10 +329,9 @@ parser.register({
|
||||
'.ExportJson': parseJson,
|
||||
});
|
||||
|
||||
var transformUrl = function (url, options) {
|
||||
function transformUrl (url, options) {
|
||||
let inLocal = false;
|
||||
let inCache = false;
|
||||
|
||||
if (REGEX.test(url) && !url.startsWith('file://')) {
|
||||
if (options.reload) {
|
||||
return { url };
|
||||
@@ -339,16 +340,22 @@ var transformUrl = function (url, options) {
|
||||
if (cache) {
|
||||
inCache = true;
|
||||
url = cache;
|
||||
} else {
|
||||
const tempUrl = cacheManager.getTemp(url);
|
||||
if (tempUrl) {
|
||||
inLocal = true;
|
||||
url = tempUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
inLocal = true;
|
||||
if(url.startsWith('file://')) {
|
||||
if (url.startsWith('file://')) {
|
||||
url = globalThis.nodeEnv.require('url').fileURLToPath(url);
|
||||
}
|
||||
}
|
||||
return { url, inLocal, inCache };
|
||||
};
|
||||
}
|
||||
|
||||
cc.assetManager.transformPipeline.append((task) => {
|
||||
const input = task.output = task.input;
|
||||
@@ -372,7 +379,5 @@ cc.assetManager.transformPipeline.append((task) => {
|
||||
const originInit = cc.assetManager.init;
|
||||
cc.assetManager.init = function (options) {
|
||||
originInit.call(cc.assetManager, options);
|
||||
const subpacks = cc.settings.querySettings('assets', 'subpackages');
|
||||
subpacks && subpacks.forEach((x) => subpackages[x] = `${_subpackagesPath}${x}`);
|
||||
cacheManager.init();
|
||||
};
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
const { makeDirSync, copyFile, downloadFile, deleteFile, rmdirSync, getUserDataPath } = require('./fs-utils');
|
||||
const { makeDirSync, copyFile, deleteFile, readJsonSync, writeFileSync, rmdirSync, getUserDataPath, isOutOfStorage } = require('./fs-utils');
|
||||
|
||||
let checkNextPeriod = false;
|
||||
let writeCacheFileList = null;
|
||||
@@ -65,9 +65,17 @@ const cacheManager = {
|
||||
},
|
||||
|
||||
init () {
|
||||
//TODO(qgh): Read the configuration file
|
||||
this.cacheDir = `${getUserDataPath()}/${this.cacheDir}`;
|
||||
this.cachedFiles = new cc.AssetManager.Cache();
|
||||
const cacheFilePath = `${this.cacheDir}/${this.cachedFileName}`;
|
||||
const result = readJsonSync(cacheFilePath);
|
||||
if (result instanceof Error || !result.version) {
|
||||
if (!(result instanceof Error)) rmdirSync(this.cacheDir, true);
|
||||
this.cachedFiles = new cc.AssetManager.Cache();
|
||||
makeDirSync(this.cacheDir, true);
|
||||
writeFileSync(cacheFilePath, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
|
||||
} else {
|
||||
this.cachedFiles = new cc.AssetManager.Cache(result.files);
|
||||
}
|
||||
this.tempFiles = new cc.AssetManager.Cache();
|
||||
},
|
||||
|
||||
@@ -80,7 +88,7 @@ const cacheManager = {
|
||||
|
||||
_write () {
|
||||
writeCacheFileList = null;
|
||||
//TODO(qgh): Write to the configuration file
|
||||
writeFileSync(`${this.cacheDir}/${this.cachedFileName}`, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
|
||||
},
|
||||
|
||||
writeCacheFile () {
|
||||
@@ -102,22 +110,20 @@ const cacheManager = {
|
||||
const { srcUrl, isCopy, cacheBundleRoot } = this.cacheQueue[id];
|
||||
const time = Date.now().toString();
|
||||
|
||||
let localPath = '';
|
||||
|
||||
if (cacheBundleRoot) {
|
||||
localPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
} else {
|
||||
localPath = `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
}
|
||||
|
||||
const localPath = cacheBundleRoot
|
||||
? `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`
|
||||
: `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`;
|
||||
function callback (err) {
|
||||
if (err) {
|
||||
console.log('cannot support');
|
||||
// if (isOutOfStorage(err.message)) {
|
||||
// self.outOfStorage = true;
|
||||
// self.autoClear && self.clearLRU();
|
||||
// return;
|
||||
// }
|
||||
if (err) {
|
||||
// 不确定错误是否和runtime一致,得测试下
|
||||
if (isOutOfStorage(err.message)) {
|
||||
self.outOfStorage = true;
|
||||
self.autoClear && self.clearLRU();
|
||||
return;
|
||||
} else {
|
||||
// 打印出错信息
|
||||
console.warn(err);
|
||||
}
|
||||
} else {
|
||||
self.cachedFiles.add(id, { bundle: cacheBundleRoot, url: localPath, lastTime: time });
|
||||
self.writeCacheFile();
|
||||
@@ -138,7 +144,6 @@ const cacheManager = {
|
||||
cacheFile (id, srcUrl, cacheEnabled, cacheBundleRoot, isCopy) {
|
||||
cacheEnabled = cacheEnabled !== undefined ? cacheEnabled : this.cacheEnabled;
|
||||
if (!cacheEnabled || this.cacheQueue[id] || this.cachedFiles.has(id)) return;
|
||||
|
||||
this.cacheQueue[id] = { srcUrl, cacheBundleRoot, isCopy };
|
||||
if (!checkNextPeriod && !this.outOfStorage) {
|
||||
checkNextPeriod = true;
|
||||
@@ -164,28 +169,25 @@ const cacheManager = {
|
||||
const caches = [];
|
||||
const self = this;
|
||||
this.cachedFiles.forEach((val, key) => {
|
||||
if (self._isZipFile(key) && cc.assetManager.bundles.find((bundle) => bundle.base.indexOf(val.url) !== -1)) return;
|
||||
if (val.bundle === 'internal') return;
|
||||
caches.push({ originUrl: key, url: val.url, lastTime: val.lastTime });
|
||||
});
|
||||
caches.sort((a, b) => a.lastTime - b.lastTime);
|
||||
caches.length = Math.floor(caches.length / 3);
|
||||
// cache length above 3 then clear 1/3, or clear all caches
|
||||
if (caches.length < 3) {
|
||||
console.warn('Insufficient storage, cleaning now');
|
||||
} else {
|
||||
caches.length = Math.floor(caches.length / 3);
|
||||
if (caches.length === 0) {
|
||||
cleaning = false;
|
||||
return;
|
||||
}
|
||||
for (let i = 0, l = caches.length; i < l; i++) {
|
||||
const cacheKey = `${cc.assetManager.utils.getUuidFromURL(caches[i].originUrl)}@native`;
|
||||
cc.assetManager.files.remove(cacheKey);
|
||||
this.cachedFiles.remove(caches[i].originUrl);
|
||||
}
|
||||
|
||||
clearTimeout(writeCacheFileList);
|
||||
this._write();
|
||||
function deferredDelete () {
|
||||
const item = caches.pop();
|
||||
self._removePathOrFile(item.originUrl, item.url);
|
||||
deleteFile(item.url, self._deleteFileCB.bind(self));
|
||||
if (caches.length > 0) {
|
||||
setTimeout(deferredDelete, self.deleteInterval);
|
||||
} else {
|
||||
@@ -200,19 +202,6 @@ const cacheManager = {
|
||||
const path = this.cachedFiles.remove(url).url;
|
||||
clearTimeout(writeCacheFileList);
|
||||
this._write();
|
||||
this._removePathOrFile(url, path);
|
||||
}
|
||||
},
|
||||
|
||||
_removePathOrFile (url, path) {
|
||||
if (this._isZipFile(url)) {
|
||||
if (this._isZipFile(path)) {
|
||||
deleteFile(path, this._deleteFileCB.bind(this));
|
||||
} else {
|
||||
rmdirSync(path, true);
|
||||
this._deleteFileCB();
|
||||
}
|
||||
} else {
|
||||
deleteFile(path, this._deleteFileCB.bind(this));
|
||||
}
|
||||
},
|
||||
@@ -225,18 +214,6 @@ const cacheManager = {
|
||||
makeDirSync(`${this.cacheDir}/${bundleName}`, true);
|
||||
},
|
||||
|
||||
unzipAndCacheBundle (id, zipFilePath, cacheBundleRoot, onComplete) {
|
||||
const time = Date.now().toString();
|
||||
const targetPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}`;
|
||||
const self = this;
|
||||
makeDirSync(targetPath, true);
|
||||
console.log('cannot support');
|
||||
},
|
||||
|
||||
_isZipFile (url) {
|
||||
return url.slice(-4) === '.zip';
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
cc.assetManager.cacheManager = module.exports = cacheManager;
|
||||
|
||||
@@ -26,15 +26,19 @@ const fsUtils = {
|
||||
|
||||
fs,
|
||||
|
||||
initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout) {
|
||||
console.log("initJsbDownloader: nodejs does not support")
|
||||
isOutOfStorage (errMsg) {
|
||||
return errMsg.indexOf('ENOSPC') !== -1;
|
||||
},
|
||||
|
||||
getUserDataPath() {
|
||||
return path.join(globalThis.nodeEnv.userDataPath, "writablePath");
|
||||
initJsbDownloader (jsbDownloaderMaxTasks, jsbDownloaderTimeout) {
|
||||
console.log('initJsbDownloader: nodejs does not support');
|
||||
},
|
||||
|
||||
checkFsValid() {
|
||||
getUserDataPath () {
|
||||
return path.join(globalThis.nodeEnv.userDataPath, 'writablePath');
|
||||
},
|
||||
|
||||
checkFsValid () {
|
||||
if (!fs) {
|
||||
cc.warn('can not get the file system!');
|
||||
return false;
|
||||
@@ -42,7 +46,7 @@ const fsUtils = {
|
||||
return true;
|
||||
},
|
||||
|
||||
deleteFile(filePath, onComplete) {
|
||||
deleteFile (filePath, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.unlink(fullFilePath, (e) => {
|
||||
if (e) {
|
||||
@@ -54,24 +58,24 @@ const fsUtils = {
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
fullPathForFilename(filename, forceReturnFullpath = false) {
|
||||
if(filename.length <= 0){
|
||||
return "";
|
||||
|
||||
fullPathForFilename (filename, forceReturnFullpath = false) {
|
||||
if (filename.length <= 0) {
|
||||
return '';
|
||||
}
|
||||
if(path.isAbsolute(filename)) {
|
||||
if (path.isAbsolute(filename)) {
|
||||
return filename;
|
||||
}
|
||||
const newFilename = path.normalize(filename);
|
||||
const projectPath = '';
|
||||
const fullpath = path.join(projectPath, newFilename);
|
||||
if(fs.pathExistsSync(fullpath) || forceReturnFullpath) {
|
||||
if (fs.pathExistsSync(fullpath) || forceReturnFullpath) {
|
||||
return fullpath;
|
||||
}
|
||||
return "";
|
||||
return '';
|
||||
},
|
||||
|
||||
saveFile(srcPath, destPath, onComplete) {
|
||||
saveFile (srcPath, destPath, onComplete) {
|
||||
const fullSrcPath = fsUtils.fullPathForFilename(srcPath);
|
||||
const fullDestPath = fsUtils.fullPathForFilename(destPath, true);
|
||||
fs.ensureDirSync(path.dirname(fullDestPath));
|
||||
@@ -89,7 +93,7 @@ const fsUtils = {
|
||||
});
|
||||
},
|
||||
|
||||
copyFile(srcPath, destPath, onComplete) {
|
||||
copyFile (srcPath, destPath, onComplete) {
|
||||
const fullSrcPath = fsUtils.fullPathForFilename(srcPath);
|
||||
const fullDestPath = fsUtils.fullPathForFilename(destPath, true);
|
||||
fs.ensureDirSync(path.dirname(fullDestPath));
|
||||
@@ -106,7 +110,7 @@ const fsUtils = {
|
||||
});
|
||||
},
|
||||
|
||||
writeFile(filePath, data, encoding, onComplete) {
|
||||
writeFile (filePath, data, encoding, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath, true);
|
||||
fs.writeFile(fullFilePath, data, encoding, (e) => {
|
||||
if (e) {
|
||||
@@ -116,13 +120,13 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
writeFileSync(filePath, data, encoding) {
|
||||
writeFileSync (filePath, data, encoding) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath, true);
|
||||
try {
|
||||
fs.writeFile(fullFilePath, data, encoding);
|
||||
fs.writeFileSync(fullFilePath, data, encoding);
|
||||
return null;
|
||||
} catch (e) {
|
||||
const err = new Error(`Failed to write file synchronously: "${filePath}" (resolved: "${fullFilePath}") - ${e.message}`);
|
||||
@@ -131,7 +135,7 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
readFile(filePath, encoding, onComplete) {
|
||||
readFile (filePath, encoding, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.readFile(fullFilePath, encoding, (e, data) => {
|
||||
if (e) {
|
||||
@@ -141,10 +145,10 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null, data);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
readDir(dirPath, onComplete) {
|
||||
readDir (dirPath, onComplete) {
|
||||
const fullDirPath = fsUtils.fullPathForFilename(dirPath);
|
||||
fs.readdir(fullDirPath, (e, files) => {
|
||||
if (e) {
|
||||
@@ -154,18 +158,18 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null, files);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
readText(filePath, onComplete) {
|
||||
readText (filePath, onComplete) {
|
||||
fsUtils.readFile(filePath, 'utf8', onComplete);
|
||||
},
|
||||
|
||||
readArrayBuffer(filePath, onComplete) {
|
||||
readArrayBuffer (filePath, onComplete) {
|
||||
fsUtils.readFile(filePath, '', onComplete);
|
||||
},
|
||||
|
||||
readJson(filePath, onComplete) {
|
||||
readJson (filePath, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.readJson(fullFilePath, (e, jsonObj) => {
|
||||
if (e) {
|
||||
@@ -175,10 +179,10 @@ const fsUtils = {
|
||||
} else {
|
||||
onComplete && onComplete(null, jsonObj);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
readJsonSync(filePath) {
|
||||
readJsonSync (filePath) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
try {
|
||||
return fs.readJsonSync(fullFilePath);
|
||||
@@ -189,10 +193,10 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
makeDirSync(dirPath, recursive) {
|
||||
makeDirSync (dirPath, recursive) {
|
||||
const fullDirPath = fsUtils.fullPathForFilename(dirPath, true);
|
||||
try {
|
||||
fs.mkdirSync(fullDirPath, { recursive: recursive });
|
||||
fs.mkdirSync(fullDirPath, { recursive });
|
||||
return null;
|
||||
} catch (e) {
|
||||
const err = new Error(`Make directory failed: "${dirPath}" (resolved: "${fullDirPath}") - ${e.message}`);
|
||||
@@ -201,10 +205,10 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
rmdirSync(dirPath, recursive) {
|
||||
rmdirSync (dirPath, recursive) {
|
||||
const fullDirPath = fsUtils.fullPathForFilename(dirPath);
|
||||
try {
|
||||
fs.rmSync(fullDirPath, { recursive: recursive });
|
||||
fs.rmSync(fullDirPath, { recursive });
|
||||
return null;
|
||||
} catch (e) {
|
||||
const err = new Error(`Remove directory failed: "${dirPath}" (resolved: "${fullDirPath}") - ${e.message}`);
|
||||
@@ -213,10 +217,10 @@ const fsUtils = {
|
||||
}
|
||||
},
|
||||
|
||||
exists(filePath, onComplete) {
|
||||
exists (filePath, onComplete) {
|
||||
const fullFilePath = fsUtils.fullPathForFilename(filePath);
|
||||
fs.pathExists(fullFilePath, function (e, exists) {
|
||||
if(e) {
|
||||
fs.pathExists(fullFilePath, (e, exists) => {
|
||||
if (e) {
|
||||
const err = new Error(`File existence check failed: "${filePath}" (resolved: "${fullFilePath}") - ${e.message}`);
|
||||
cc.warn(err.message);
|
||||
return err;
|
||||
@@ -225,7 +229,7 @@ const fsUtils = {
|
||||
});
|
||||
},
|
||||
|
||||
loadSubpackage(name, onProgress, onComplete) {
|
||||
loadSubpackage (name, onProgress, onComplete) {
|
||||
throw new Error('nodejs not implement');
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user