《游戏编辑器技术原理与架构》4.3 图集打包

一张图集 = 一堆小图塞进一个大矩形。本节用最朴素的 shelf 算法实现 AtlasPacker——按高度降序排、同一行从左到右放、放不下换行、单边超限拒绝;6 条用例本机真跑,钉住「矩形不重叠、换行 y 递增、超限被拒」三条打包不变量。

4.3 图集打包

游戏里几百张 UI 小图不能各占一个纹理——draw call 会爆炸。把它们合进一张图集(atlas),渲染时一次绑定一张纹理。图集导入的核心算法是矩形装箱:一堆尺寸各异的矩形,塞进一个大矩形,尽量不浪费空间。工业级有 skyline、maxrects 等精装算法;本节用最朴素的 shelf(货架) 算法,它是理解所有装箱算法的起点。

本节的 AtlasPacker:

  • packAtlas(items, maxWidth):输入小图清单,输出图集尺寸 + 每张小图的位置。
  • shelf 策略:按高度降序排,同一 shelf 从左到右放,放不下换行。
  • 单边超过 maxWidth 的 item 直接 rejected。

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

主题站内既有内容本节做什么
纹理参数4.2 纹理参数与压缩设置图集是一张特殊纹理,也受 maxSize 约束
导入器框架3.1 导入器注册与分发图集打包是 .png 导入流水线的一个阶段
头解析4.1 图像解码与格式归一每张小图的宽高从哪来?头解析

shelf 算法:一行是一层

shelf 的核心直觉:把矩形按高度降序排好,从左上角开始,一行(shelf)从左到右码,放不下就换行到下一 shelf。为什么按高度降序?因为先放高个子,矮个子更容易填进高个子留下的缝隙——如果先放矮的,高的可能把整行顶得过高,浪费空间。

算法里两个「放不下」的判据要分清:

  • item.w > maxWidth || item.h > maxWidth:单边超限,任何打包方案都救不了,直接拒绝。
  • shelfY + item.h > maxWidth:当前列放不下(下一 shelf 会顶出边界),也拒绝。

为什么测试要断言「矩形不重叠」

打包算法的致命 bug 不是「不紧凑」,而是「重叠」——两个矩形叠在一起,渲染时小图互相盖脸。所以测试里专门写了一个 overlap 函数,对打包结果做两两检测:任何一对都不重叠,才是一次合法打包。这是打包算法的第一不变量,比装箱率重要得多——紧凑是优化,不重叠是正确。

对标图集输入与布局结果

Unity Sprite Atlas 提供待打包对象、旋转和边距等设置。Cocos Creator 的 Auto Atlas 以图集配置管理精灵的收集与打包。helio 示例接收已选定的矩形输入,用 shelf 算法计算位置。矩形 ID 用于对应打包结果。完整图集还需要复制像素并生成供运行时采样的区域信息。 Unity Sprite Atlas · Cocos Auto Atlas

可运行产物:6 条用例

下面 src/atlas-packer.ts 层级 L1,完整可编译,命令 node --test test/04-3-atlas-packer.test.ts:

// file: src/atlas-packer.ts
// tier: L1
// verify: node --test test/04-3-atlas-packer.test.ts
//
// 资产管线(第四章):图集打包。
// 一张图集 = 一堆小图塞进一个大矩形。AtlasPacker 用最朴素的 shelf
// (货架)算法:按高度降序排,同一行从左到右放,放不下换行。够快、够稳、
// 够解释——工业级会用 skyline / maxrects 追求更紧的装箱率,但 shelf 是
// 理解所有打包算法的最小起点。

export interface AtlasItem {
  id: string;
  w: number;
  h: number;
}

export interface Rect {
  x: number;
  y: number;
  w: number;
  h: number;
}

export interface PackedResult {
  /** 图集最终宽(= maxWidth)。 */
  atlasWidth: number;
  /** 图集最终高(所有 shelf 的累计高度)。 */
  atlasHeight: number;
  /** id → 在图集内的位置。 */
  placements: Map<string, Rect>;
  /** 放不下的 id(单边超过 maxWidth 或图集装不下)。 */
  rejected: string[];
}

/** shelf 打包:按高降序,同一 shelf 从左到右,放不下换行。 */
export function packAtlas(items: AtlasItem[], maxWidth = 1024): PackedResult {
  const placements = new Map<string, Rect>();
  const rejected: string[] = [];
  const sorted = [...items].sort((a, b) => b.h - a.h);
  let shelfY = 0;
  let shelfX = 0;
  let shelfH = 0;
  for (const item of sorted) {
    if (item.w > maxWidth || item.h > maxWidth) {
      rejected.push(item.id);
      continue;
    }
    if (shelfX + item.w > maxWidth) {
      // 当前 shelf 放不下 → 换行
      shelfY += shelfH;
      shelfX = 0;
      shelfH = 0;
    }
    if (shelfY + item.h > maxWidth) {
      rejected.push(item.id);
      continue;
    }
    placements.set(item.id, { x: shelfX, y: shelfY, w: item.w, h: item.h });
    shelfX += item.w;
    shelfH = Math.max(shelfH, item.h);
  }
  return {
    atlasWidth: maxWidth,
    atlasHeight: shelfY + shelfH,
    placements,
    rejected,
  };
}

三个游标各有职责:shelfX 是当前行已占宽度、shelfY 是当前行起始高度、shelfH 是当前行最高高度。换行那一刻 shelfY += shelfH 用的正是上一行的最大高度——一行的高度由最高的 item 决定,这是 shelf 的代价与机会。

可运行产物:6 条用例

下面是 test/04-3-atlas-packer.test.ts 层级 L1,命令 node --test test/04-3-atlas-packer.test.ts:

// file: test/04-3-atlas-packer.test.ts
// tier: L1
// verify: node --test test/04-3-atlas-packer.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { packAtlas, type Rect } from '../src/atlas-packer.ts';

/** 两个矩形是否相交(重叠则打包非法)。 */
function overlap(a: Rect, b: Rect): boolean {
  return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
}

test('单个 item 放在图集左上角', () => {
  const r = packAtlas([{ id: 's1', w: 64, h: 64 }]);
  assert.equal(r.placements.get('s1')!.x, 0);
  assert.equal(r.placements.get('s1')!.y, 0);
  assert.equal(r.rejected.length, 0);
});

test('同 shelf 多个 item 从左到右排开,互不重叠', () => {
  const r = packAtlas([
    { id: 'a', w: 100, h: 50 },
    { id: 'b', w: 60, h: 50 },
    { id: 'c', w: 40, h: 50 },
  ]);
  assert.equal(r.rejected.length, 0);
  const rects = [...r.placements.values()];
  for (let i = 0; i < rects.length; i++) {
    for (let j = i + 1; j < rects.length; j++) {
      assert.equal(overlap(rects[i], rects[j]), false, '打包矩形不得重叠');
    }
  }
});

test('按高度降序排:最高者先放,占据首 shelf 最左', () => {
  const r = packAtlas([
    { id: 'low', w: 50, h: 20 },
    { id: 'tall', w: 50, h: 80 },
  ]);
  const tall = r.placements.get('tall')!;
  const low = r.placements.get('low')!;
  assert.equal(tall.x, 0); // 最高者先放,x=0
  assert.equal(tall.y, 0);
  assert.ok(low.x > tall.x); // 矮者排在后面(同一 shelf 更靠右)
});

test('超出 maxWidth 的 item 被拒绝(rejected)', () => {
  const r = packAtlas([{ id: 'huge', w: 2048, h: 2048 }], 1024);
  assert.deepEqual(r.rejected, ['huge']);
  assert.equal(r.placements.size, 0);
});

test('换行:第一 shelf 放不下时第二行 y 递增', () => {
  const r = packAtlas([
    { id: 'w1', w: 700, h: 100 },
    { id: 'w2', w: 700, h: 100 },
  ], 1024);
  const first = r.placements.get('w1')!;
  const second = r.placements.get('w2')!;
  assert.equal(first.y, 0);
  assert.equal(second.x, 0); // 换行后回到 x=0
  assert.equal(second.y, 100); // 新 shelf 从上一 shelf 高度下方开始
  assert.equal(r.atlasHeight, 200);
});

test('图集高度 = 所有 shelf 累计高度,placement 完整', () => {
  const items = [
    { id: 'a', w: 100, h: 100 },
    { id: 'b', w: 200, h: 50 },
    { id: 'c', w: 300, h: 80 },
  ];
  const r = packAtlas(items, 512);
  assert.equal(r.rejected.length, 0);
  assert.equal(r.placements.size, 3);
  assert.equal(r.atlasWidth, 512);
  assert.ok(r.atlasHeight >= 100); // 至少装下最高的 item
});

本机实测(Node v26.5.0,node --test test/04-3-atlas-packer.test.ts):tests 6、pass 6、fail 0,耗时约 40 ms。

第二条的「两两不重叠」是打包正确性的第一断言——一个循环把三张图的九种两两组合全部验过。第四条把「单边超限直接拒绝」钉死。第五条精确验证换行语义:第二行从 y=100(上一 shelf 的高度)开始。

小结

  • 图集 = 矩形装箱;shelf 算法按高度降序、同行走位、放不下换行。
  • 三个游标:shelfX 当前行已占、shelfY 行起始高、shelfH 行最大高。
  • 两个「放不下」判据:单边超限(拒绝)、当前列放不下(拒绝)。
  • 不重叠是正确性,紧凑是优化——测试必须断言前者。
  • 下一节进入模型资产:glTF 解析与模型导入——JSON 结构、节点树、网格与材质引用。

阅读导航:上一节:4.2 纹理参数与压缩设置 · 下一节:5.1 glTF 解析与模型导入 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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