Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import expression from 'angular-expressions';
import { stageStateManager } from '@/Core/Modules/stage/stageStateManager';
import { webgalStore } from '@/store/store';
import { logger } from '@/Core/util/logger';
import random from 'lodash/random';

/**
* 提取变量名和表达式
* @param expressionString 表达式字符串,例如 "x = a + 5"
* @returns 包含变量名和表达式,如果无效则返回 undefined
*/
export function extractVariableNameAndExpression(
expressionString: string,
): { variableName: string; expression: string } | undefined {
const equalIndex = expressionString.indexOf('=');
if (equalIndex === -1) {
return undefined;
}

const variableName = expressionString.substring(0, equalIndex).trim();
if (variableName.length === 0) {
return undefined;
}

const expression = expressionString.substring(equalIndex + 1).trim();
if (expression.length === 0) {
return undefined;
}

return { variableName, expression };
}

// 内置函数
const builtinFunctions = {
random: (...args: any[]) => {
return args.length ? random(...args) : Math.random();
},
};

/**
* 评估表达式字符串
* @param expressionString 表达式字符串
* @returns 评估结果,可能是 string、number、boolean 或 undefined
* 但也有可能返回其他类型,取决于表达式的内容和上下文
*/
export function evaluateExpression(expressionString: string): string | number | boolean | undefined {
try {
const evaluate = expression.compile(expressionString);

const stageState = stageStateManager.getCalculationStageState();
const stageVar = stageState.GameVar;
const userData = webgalStore.getState().userData;
const globalVar = userData.globalGameVar;

const scope: any = {};
// 先加入内置函数(最低优先级)
Object.assign(scope, builtinFunctions);
// 然后加入全局变量
Object.assign(scope, globalVar);
// 最后加入舞台变量以保证最高优先级
Object.assign(scope, stageVar);
// 支持 $ 前缀的特殊值
scope['$stage'] = stageState;
scope['$userData'] = userData;

const result = evaluate(scope);
switch (typeof result) {
case 'string':
case 'number':
case 'boolean':
return result;
Comment on lines +46 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

性能优化建议:缓存编译结果与避免对象拷贝

在当前实现中,每次调用 evaluateExpression 都会执行以下操作:

  1. 调用 expression.compile(expressionString) 重新编译表达式。编译是一个涉及词法分析、语法分析和生成 AST 的 CPU 密集型操作。
  2. 使用 Object.assign 浅拷贝 builtinFunctionsglobalVarstageVar。在大型游戏中,变量(尤其是全局变量和舞台变量)的数量可能非常多,频繁的对象创建和属性拷贝会带来显著的 CPU 开销和垃圾回收(GC)压力。

解决方案:

  1. 引入编译缓存:使用 Map 缓存已编译的表达式函数。由于 angular-expressions 编译出的函数是无状态的,因此可以安全地复用。
  2. 使用 Proxy 代理作用域查找:通过 Proxy 动态拦截属性读取,避免每次求值时都进行对象拷贝,从而实现零拷贝(Zero-copy)查找。

以下是优化后的代码建议:

const expressionCache = new Map<string, (scope: any) => any>();

export function evaluateExpression(expressionString: string): string | number | boolean | undefined {
  try {
    let evaluate = expressionCache.get(expressionString);
    if (!evaluate) {
      evaluate = expression.compile(expressionString);
      expressionCache.set(expressionString, evaluate);
    }

    const stageState = stageStateManager.getCalculationStageState();
    const stageVar = stageState.GameVar;
    const userData = webgalStore.getState().userData;
    const globalVar = userData.globalGameVar;

    const scope = new Proxy({} as any, {
      get(_, prop) {
        if (typeof prop !== 'string') return undefined;
        if (prop === '$stage') return stageState;
        if (prop === '$userData') return userData;
        if (stageVar && Object.prototype.hasOwnProperty.call(stageVar, prop)) {
          return stageVar[prop];
        }
        if (globalVar && Object.prototype.hasOwnProperty.call(globalVar, prop)) {
          return globalVar[prop];
        }
        if (Object.prototype.hasOwnProperty.call(builtinFunctions, prop)) {
          return (builtinFunctions as any)[prop];
        }
        return undefined;
      },
      has(_, prop) {
        if (typeof prop !== 'string') return false;
        return (
          prop === '$stage' ||
          prop === '$userData' ||
          (stageVar && Object.prototype.hasOwnProperty.call(stageVar, prop)) ||
          (globalVar && Object.prototype.hasOwnProperty.call(globalVar, prop)) ||
          Object.prototype.hasOwnProperty.call(builtinFunctions, prop)
        );
      },
    });

    const result = evaluate(scope);
    switch (typeof result) {
      case 'string':
      case 'number':
      case 'boolean':
        return result;

default:
logger.warn(`不支持的表达式求值类型: ${typeof result},表达式: ${expressionString}`);
return undefined;
}
} catch (error) {
logger.warn(`表达式求值失败: ${expressionString}`, error);
return undefined;
}
}
12 changes: 9 additions & 3 deletions packages/webgal/src/Core/controller/gamePlay/scriptExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { runScript } from './runScript';
import { logger } from '../../util/logger';
import { restoreScene } from '../scene/restoreScene';
import { webgalStore } from '@/store/store';
import { getValueFromStateElseKey } from '@/Core/gameScripts/setVar';
import { legacyGetValueFromStateElseKey } from '@/Core/gameScripts/setVar';
import { strIf } from '@/Core/controller/gamePlay/strIf';
import cloneDeep from 'lodash/cloneDeep';
import { ISceneEntry } from '@/Core/Modules/scene';
Expand All @@ -13,6 +13,7 @@ import { stageStateManager } from '@/Core/Modules/stage/stageStateManager';
import { jumpToLabel } from '@/Core/gameScripts/label/jumpToLabel';
import { prefetchCurrentSceneByProgress } from '@/Core/util/prefetcher/progressPrefetcher';
import { WEBGAL_NONE } from '@/Core/constants';
import { evaluateExpression } from '@/Core/controller/gamePlay/expressionEvaluation';

const MAX_FORWARD_SCRIPT_EXECUTION = 1000;

Expand All @@ -29,6 +30,11 @@ export const whenChecker = (whenValue: string | undefined): boolean => {
if (whenValue === undefined) {
return true;
}

if (!WebGAL.legacyExpressionParser) {
return Boolean(evaluateExpression(whenValue));
}

// 先把变量解析出来
const valExpArr = whenValue.split(/([+\-*\/()><!]|>=|<=|==|&&|\|\||!=)/g);
const valExp = valExpArr
Expand All @@ -38,7 +44,7 @@ export const whenChecker = (whenValue: string | undefined): boolean => {
if (e.match(/^(true|false)$/)) {
return e;
}
return getValueFromStateElseKey(e, true, true);
return legacyGetValueFromStateElseKey(e, true, true);
} else return e;
})
.reduce((pre, curr) => pre + curr, '');
Expand Down Expand Up @@ -84,7 +90,7 @@ export const scriptExecutor = (depth = 0, options: ScriptExecutionOptions = {})

if (contentExp !== null) {
contentExp.forEach((e) => {
const contentVarValue = getValueFromStateElseKey(e.replace(/(?<!\\)\{(.*)\}/, '$1'));
const contentVarValue = legacyGetValueFromStateElseKey(e.replace(/(?<!\\)\{(.*)\}/, '$1'));
retContent = retContent.replace(e, contentVarValue);
});
}
Expand Down
48 changes: 35 additions & 13 deletions packages/webgal/src/Core/gameScripts/setVar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import get from 'lodash/get';
import random from 'lodash/random';
import { getBooleanArgByKey } from '../util/getSentenceArg';
import { stageStateManager } from '@/Core/Modules/stage/stageStateManager';
import { WebGAL } from '@/Core/WebGAL';
import { evaluateExpression, extractVariableNameAndExpression } from '@/Core/controller/gamePlay/expressionEvaluation';

interface ISetGameVarFromExpressionPayload {
key: string;
Expand Down Expand Up @@ -40,7 +42,13 @@ export const setGameVarFromExpression = ({
if (!normalizedKey) {
return;
}
setGameVar({ key: normalizedKey, value: resolveSetVarValue(value) });

const resolvedValue = resolveSetVarValue(value);
if (resolvedValue === undefined) {
return;
}
setGameVar({ key: normalizedKey, value: resolvedValue });

if (isGlobal) {
logger.debug('设置全局变量:', { key: normalizedKey, value: webgalStore.getState().userData.globalGameVar[normalizedKey] });
if (persistGlobal) {
Expand All @@ -57,27 +65,41 @@ export const setGameVarFromExpression = ({
*/
export const setVar = (sentence: ISentence): IPerform => {
const setGlobal = getBooleanArgByKey(sentence, 'global') ?? false;
if (sentence.content.match(/\s*=\s*/)) {
const key = sentence.content.split(/\s*=\s*/)[0];
const valExp = sentence.content.split(/\s*=\s*/)[1];
setGameVarFromExpression({ key, value: valExp, isGlobal: setGlobal });
if (WebGAL.legacyExpressionParser) {
if (sentence.content.match(/\s*=\s*/)) {
const key = sentence.content.split(/\s*=\s*/)[0];
const valExp = sentence.content.split(/\s*=\s*/)[1];
setGameVarFromExpression({ key, value: valExp, isGlobal: setGlobal });
}
} else {
const extracted = extractVariableNameAndExpression(sentence.content);
if (extracted) {
const { variableName, expression } = extracted;
setGameVarFromExpression({ key: variableName, value: expression, isGlobal: setGlobal });
} else {
logger.error(`setVar 语句格式错误,无法提取变量名和表达式: ${sentence.content}`);
}
}
return createNonePerform();
};

type BaseVal = string | number | boolean | undefined;

export function resolveSetVarValue(valExp: string): string | boolean | number {
export function resolveSetVarValue(valExp: string): string | boolean | number | undefined {
if (!WebGAL.legacyExpressionParser) {
return evaluateExpression(valExp);
}

if (/^\s*[a-zA-Z_$][\w$]*\s*\(.*\)\s*$/.test(valExp)) {
return EvaluateExpression(valExp);
return LegacyEvaluateExpression(valExp);
} else if (valExp.match(/[+\-*\/()]/)) {
const valExpArr = valExp.split(/([+\-*\/()])/g);
const valExp2 = valExpArr
.map((e) => {
if (!e.trim().match(/^[a-zA-Z_$][a-zA-Z0-9_.]*$/)) {
return e;
}
const _r = getValueFromStateElseKey(e.trim(), true);
const _r = legacyGetValueFromStateElseKey(e.trim(), true);
return typeof _r === 'string' ? `'${_r}'` : _r;
})
.reduce((pre, curr) => pre + curr, '');
Expand All @@ -102,7 +124,7 @@ export function resolveSetVarValue(valExp: string): string | boolean | number {
if (!isNaN(Number(valExp))) {
return Number(valExp);
} else {
return getValueFromStateElseKey(valExp, true) ?? '';
return legacyGetValueFromStateElseKey(valExp, true) ?? '';
}
}
return '';
Expand All @@ -111,7 +133,7 @@ export function resolveSetVarValue(valExp: string): string | boolean | number {
/**
* 执行函数
*/
function EvaluateExpression(val: string) {
function LegacyEvaluateExpression(val: string) {
const instance = expression.compile(val);
return instance({
random: (...args: any[]) => {
Expand All @@ -123,7 +145,7 @@ function EvaluateExpression(val: string) {
/**
* 取不到时返回 undefined
*/
export function getValueFromState(key: string) {
export function legacyGetValueFromState(key: string) {
let ret: any;
const stage = stageStateManager.getCalculationStageState();
const userData = webgalStore.getState().userData;
Expand All @@ -142,8 +164,8 @@ export function getValueFromState(key: string) {
/**
* 取不到时返回 {key}
*/
export function getValueFromStateElseKey(key: string, useKeyNameAsReturn = false, quoteString = false) {
const valueFromState = getValueFromState(key);
export function legacyGetValueFromStateElseKey(key: string, useKeyNameAsReturn = false, quoteString = false) {
const valueFromState = legacyGetValueFromState(key);
if (valueFromState === null || valueFromState === undefined) {
logger.warn('valueFromState result null, key = ' + key);
if (useKeyNameAsReturn) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ export const infoFetcher = (url: string): Promise<IGameVar> => {
const appId = String(res);
WebGAL.steam.initialize(appId);
}
if (command === 'Legacy_Expression_Parser') {
WebGAL.legacyExpressionParser = res === true;
}
}
}
});
Expand Down
1 change: 1 addition & 0 deletions packages/webgal/src/Core/webgalCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ export class WebgalCore {
public steam = new SteamIntegration();
public template: WebgalTemplate | null = null;
public styleObjects: Map<string, IWebGALStyleObj> = new Map();
public legacyExpressionParser = false;
}
Loading