《游戏编辑器技术原理与架构》1.3 引用计数与生命周期

资产是共享资源:一个纹理可能被十个材质引用。本节实现 AssetLibrary 引用计数——register 登记、acquire 取用递增、release 释放递减、归零卸载、unloaded 才可销毁;生命周期状态机 registered→loaded→unloaded→destroyed;6 条用例本机真跑,钉住「归零即卸载、销毁后拒绝复活」两条硬规则。

1.3 引用计数与生命周期

资产是共享资源:一张 hero.png 可能被三个材质、两个 prefab、一段 UI 同时引用。谁持有、谁释放必须算清楚——算不清楚,要么提前卸载(有人还在用,界面花掉),要么永不释放(内存泄漏,编辑器越用越肥)。引用计数就是给每个资产记「现在有几个人在用」:有人用就留在内存,没人用了就卸下。

本节的 AssetLibrary 用引用计数管理每个资产的完整生命周期:

  • register(id):登记一个资产(零引用)。
  • acquire(id):取用一次,引用 +1;首次取用从 registered 升为 loaded。
  • release(id):释放一次,引用 -1;归零即卸载(unloaded)。
  • destroy(id):销毁资产——只有 unloaded 能销毁,销毁后拒绝复活。

本章与站内既有内容的分工

主题站内既有内容本节做什么
引用计数helio 1.3 引用计数与生命周期释放那篇在引擎运行期做;本节在编辑器资产库做,多了「销毁」这一档
资源模型helio 1.1 资源模型:GUID 与依赖图引用计数是即时计数;依赖图是静态全图(第 9 章)
生命周期状态机1.1 源资产与导入资产1.1 管「源变了没」,本节管「内存里存不存」;两条状态轴正交

两个状态轴不能混

细心的读者会发现两章在谈不同的「状态」:1.1 的 dirty/imported/stale 描述源文件与产物的同步关系;本节的 registered/loaded/unloaded/destroyed 描述产物在内存里的生死。它们是两条正交的轴——一个资产可以「已重导(imported)但尚未加载(registered)」,也可以「已加载(loaded)但源文件刚变(stale)」。真实编辑器正是这么运转的:导入与加载是两件事,源变化只标记产物过期,不影响它正在内存中被使用。

为什么 release 归零才卸载

release 把引用数减到 0 的那一刻,资产立刻 unloaded。为什么要「立刻」而不是等一个 GC?因为编辑器需要确定性:内存什么时候释放是可预期的,不是「看心情」。used() 返回当前所有被引用的资产,这是「内存里到底有什么」的精确答案——编辑器做卸载报告、内存统计都靠它。而 destroy 是更强的一档:只有 unloaded(没人用了)的资产才允许销毁,销毁后 acquire 直接拒绝——它不允许「刚销毁的资产被人一把抓住复活」。

对标引用释放与实际卸载

Unity Addressables 用引用计数追踪加载及释放,资产所在的 AssetBundle 是否仍被持有会影响内存回收时机。Godot 的 Resource 继承 RefCounted,由引用生命周期驱动计数。Cocos Creator 提供 addRef() 和 decRef(),供调用方管理动态引用。helio 的状态机将计数归零建模为状态变化,实际释放 CPU 或 GPU 资源需要接入宿主。 Unity Addressables 内存管理 · Godot Resource · Cocos Asset

可运行产物:6 条用例

下面 src/asset-lifetime.ts 层级 L1,完整可编译,命令 node --test test/01-3-reference-count-lifetime.test.ts:

// file: src/asset-lifetime.ts
// tier: L1
// verify: node --test test/01-3-reference-count-lifetime.test.ts
//
// 资产管线(第一章):引用计数与生命周期。
// 资产是共享资源:一个纹理可能被十个材质引用。谁持有、谁释放必须算清楚,
// 否则要么提前卸载(别处还在用)、要么永不释放(内存泄漏)。AssetLibrary
// 用引用计数管理每个资产的生命周期:registered(登记,零引用)→ loaded
// (有引用,内存中)→ unloaded(引用归零,卸下)→ destroyed(销毁,可回收)。

export type AssetState = 'registered' | 'loaded' | 'unloaded' | 'destroyed';

interface Entry {
  state: AssetState;
  refs: number;
}

export class AssetLibrary {
  readonly #entries = new Map<string, Entry>();

  /** 登记一个资产 id(零引用,registered)。重复登记返回 false。 */
  register(id: string): boolean {
    if (this.#entries.has(id)) return false;
    this.#entries.set(id, { state: 'registered', refs: 0 });
    return true;
  }

  /** 取用一次:引用计数 +1;首次取用把资产从 registered 升为 loaded。 */
  acquire(id: string): boolean {
    const e = this.#entries.get(id);
    if (!e || e.state === 'destroyed' || e.state === 'unloaded') return false;
    e.refs += 1;
    if (e.state === 'registered') e.state = 'loaded';
    return true;
  }

  /**
   * 释放一次:引用计数 -1;归零时卸载(unloaded)。返回剩余引用数。
   * 返回 -1 表示 id 未登记或已被销毁。
   */
  release(id: string): number {
    const e = this.#entries.get(id);
    if (!e || e.state === 'destroyed' || e.state === 'unloaded') return -1;
    e.refs -= 1;
    if (e.refs === 0) e.state = 'unloaded';
    return e.refs;
  }

  state(id: string): AssetState | undefined {
    return this.#entries.get(id)?.state;
  }

  refs(id: string): number {
    return this.#entries.get(id)?.refs ?? 0;
  }

  /** 当前被引用(refs > 0 且已加载)的资产 id。 */
  used(): string[] {
    const out: string[] = [];
    for (const [id, e] of this.#entries) {
      if (e.state === 'loaded' && e.refs > 0) out.push(id);
    }
    return out;
  }

  /** 销毁:仅 unloaded(零引用且已卸下)可销毁;销毁后不可再取用。 */
  destroy(id: string): boolean {
    const e = this.#entries.get(id);
    if (!e || e.state !== 'unloaded') return false;
    e.state = 'destroyed';
    return true;
  }
}

release 的返回值值得解读:返回剩余引用数,-1 表示「id 不存在或已销毁」。这个返回值让调用方能区分「我释放的是一次合法引用」还是「我对一个不存在/已死的资产喊话」——后者往往意味着调用方自己的生命周期记账错了,早暴露比晚崩溃好。

可运行产物:6 条用例

下面是 test/01-3-reference-count-lifetime.test.ts 层级 L1,命令 node --test test/01-3-reference-count-lifetime.test.ts:

// file: test/01-3-reference-count-lifetime.test.ts
// tier: L1
// verify: node --test test/01-3-reference-count-lifetime.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { AssetLibrary } from '../src/asset-lifetime.ts';

test('register 后状态为 registered、引用数为 0', () => {
  const lib = new AssetLibrary();
  assert.equal(lib.register('tex/hero'), true);
  assert.equal(lib.state('tex/hero'), 'registered');
  assert.equal(lib.refs('tex/hero'), 0);
});

test('重复登记被拒绝', () => {
  const lib = new AssetLibrary();
  lib.register('tex/hero');
  assert.equal(lib.register('tex/hero'), false);
});

test('acquire 递增引用数,首次取用升为 loaded', () => {
  const lib = new AssetLibrary();
  lib.register('tex/hero');
  assert.equal(lib.acquire('tex/hero'), true);
  assert.equal(lib.state('tex/hero'), 'loaded');
  assert.equal(lib.refs('tex/hero'), 1);
  lib.acquire('tex/hero');
  assert.equal(lib.refs('tex/hero'), 2);
});

test('release 递减引用数,归零时卸载为 unloaded', () => {
  const lib = new AssetLibrary();
  lib.register('tex/hero');
  lib.acquire('tex/hero');
  lib.acquire('tex/hero');
  assert.equal(lib.release('tex/hero'), 1);
  assert.equal(lib.state('tex/hero'), 'loaded');
  assert.equal(lib.release('tex/hero'), 0);
  assert.equal(lib.state('tex/hero'), 'unloaded');
});

test('未登记的 acquire/release 返回失败标记', () => {
  const lib = new AssetLibrary();
  assert.equal(lib.acquire('ghost'), false);
  assert.equal(lib.release('ghost'), -1);
});

test('生命周期闭环:registered→loaded→unloaded→destroyed,销毁后不可取用', () => {
  const lib = new AssetLibrary();
  lib.register('tex/hero');
  lib.acquire('tex/hero');
  lib.release('tex/hero');
  assert.equal(lib.state('tex/hero'), 'unloaded');
  assert.equal(lib.destroy('tex/hero'), true);
  assert.equal(lib.state('tex/hero'), 'destroyed');
  assert.equal(lib.acquire('tex/hero'), false); // 已销毁,拒绝复活
  assert.equal(lib.used().includes('tex/hero'), false);
});

本机实测(Node v26.5.0,node --test test/01-3-reference-count-lifetime.test.ts):tests 6、pass 6、fail 0,耗时约 35 ms。

第四条钉住「归零即卸载」:两次 acquire 后 release 一次还剩 1、仍 loaded,再 release 归零变 unloaded——卸载与引用数同步,不拖延。第六条是完整闭环,最后一行 used() 排除已销毁资产,证明「销毁」真的把它从活动清单里摘掉了。

小结

  • 引用计数 = 资产共享时的记账本:acquire +1、release -1、归零即卸载。
  • 生命周期四态:registered → loaded → unloaded → destroyed。
  • destroy 只认 unloaded:没人用了才准销毁,销毁后拒绝复活。
  • 导入(1.1)与加载(本节)是两条正交的状态轴,真实编辑器两者并存。
  • 下一节把资产收进数据库:资产数据库:扫描与内容哈希——全量扫描、哈希比对、增量导入。

阅读导航:上一节:1.2 资产元数据与稳定 GUID · 下一节:2.1 资产数据库:扫描与内容哈希 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析·向量数据库与 AI 检索内核》 · 目录与学习路径(45 篇)
  2. 《大规模分布式计算深入解析》15.3 自研向量引擎:可执行骨架与工程缺口
  3. 《大规模分布式计算深入解析》14.1 Milvus:组件架构、段管理与检索链路