《VulkanSceneGraph 1.1.16 源码深度解析》第八章 状态与状态图:StateGroup、StateCommand、StateSwitch

2 阅读1小时+

《VulkanSceneGraph 1.1.16 源码深度解析》第八章 状态与状态图:StateGroup、StateCommand、StateSwitch

8.0 度量、边界与本章要回答的问题

第七章的结论是 Command 刻意做薄(33 个类里 15 个 record 只有一行)。真正决定"这一帧画成什么样"的,是 State 里那几个栈的栈顶。本章处理这些栈的写入方:谁把 StateCommand 压进 slot 3、什么时候弹出来、弹出后上一次录过的状态还算不算数,以及压进去的东西本身又是一包命令会怎样。

先把规模摊开。本章正面处理的核心文件 87 个、合计 13,387 行:

分组文件数行数说明
include/vsg/state/*.h363,002状态命令、资源、着色器、ArrayState 的声明
src/vsg/state/*.cpp357,076编译与录制实现
vk/State.h + State.cpp2566状态栈本体、矩阵栈、视锥栈
vk/ResourceRequirements.h/.cpp2567需求采集器
nodes/StateGroup Bin DepthSorted6526状态节点与排序容器
app/RecordTraversal.h/.cpp2895录制遍历(状态的应用方)
utils/ComputeBounds Intersector4755CPU 侧顶点重建的消费者
合计8713,387—

13,387 行里有三个业务逻辑密集区:ViewDependentState.cpp 1,060 行、GraphicsPipelineConfigurator.cpp 1,013 行、ArrayState.cpp 621 行。本章处理 ArrayState.cpp(8.6)与 GraphicsPipelineConfigurator.cpp(8.10),把 ViewDependentState 留给第十三/二十二章(它是光照与视图相关状态,不是通用状态机制)。真正决定"状态图会不会出错"的,是下面这 394 行:

位置行数内容
state/StateCommand.h + state/StateSwitch.h/.cpp45 + 152slot、容器别名、三套掩码、两套展开
nodes/StateGroup.h/.cpp88 + 59三个 traverse、拷贝构造、序列化
vk/State.h 第 30–85、348–411 行106StateStack、record、push/pop、pushView
app/RecordTraversal.cpp 第 515–529 行 + nodes/Bin.cpp 第 60–164 行15 + 105apply(StateGroup) 与状态快照回放
合计570去掉许可证头与空行后约 394 行有效代码

8.0.1 问题清单:第七章留的六个问题,本章答四个

第七章末尾提了六个问题,其中四个属于本章,两个属于后续章节。先把边界划清,免得读到最后发现"问了没答":

第七章的问题本章位置状态
stateCommands 为什么是 vector<ref_ptr<StateCommand>> 而不是 vector<ref_ptr<Command>>?8.1.3 / 8.3.2本章答
StateCommand::slot 的赋值点之外,还有谁在改 slot?8.2.1 / 8.2.6本章答
ResourceHints::maxSlots 与 ResourceRequirements::maxSlots 是什么关系?8.8.1 / 8.8.4本章答
StateSwitch 怎么在运行时切换状态?8.5 全节本章答(并且发现它切换得不干净)
GraphicsPipeline::_implementation 为什么按 viewID 建多个实现?—第九章(管线对象)答
DescriptorSet::compile 在 context.scratchMemory 里分配 VkWriteDescriptorSet 数组再 release(),两次编译会不会互相覆盖?—第十一章(描述符体系)答

后两问只给答案骨架:GraphicsPipeline::_implementation 的索引确实是 viewID,因为 VkGraphicsPipelineCreateInfo::renderPass 不可变、每个 View 可能对应不同 RenderPass,VSG 按 viewID 各建一个 VkPipeline(第九章展开);DescriptorSet::compile 的 scratchMemory 是线性 bump allocator,release() 整块归还,而 vkUpdateDescriptorSets 在同一函数内同步完成,两次编译不会互相覆盖(第十一章给完整时序表)。

第七章另留的三个悬念(锁顺序、stack[0] 记忆槽、Viewer reset 覆盖不到二级图)已在 7.7.3 / 7.8.3 就地回答,本章只在 8.4、8.7 引用结论。

8.0.2 答案骨架:本章会得到的六个结论(先给,后面逐条证)

  1. slot(StateCommand.cpp:44)(StateCommand.cpp:28) 是没有中心化定义的整数协议:5 处赋值定义 4 类语义,slot 2 被三个不相关的类占用,靠约定而非类型系统维持。
  2. StateGroup 的三个 traverse 语义不一致:RecordTraversal 版只遍历 children(状态命令不产生 vkCmd*,只改 CPU 栈),另外两个版本遍历 stateCommands(StateGroup.cpp:49)(StateGroup.cpp:41)(StateGroup.cpp:26) + children。它是唯一"遍历内容取决于访问者类型"的节点。
  3. StateSwitch(StateSwitch.cpp:22) 的子命令绕过整个状态栈:不进 stateStacks[slot]、不参与记忆、pop 后不恢复;外层没覆盖的 slot 会静默使用错误状态。
  4. ArrayState 的原型克隆丢掉所有子类配置:六个 cloneArrayState(ref_ptr<ArrayState>) 全用父栈内容构造,DisplacementMapArrayState 连无参 clone 都对象切片。
  5. Bin::traverse 的 modelviewMatrixStack(RecordTraversal.cpp:317)(Bin.cpp:66) 只 push 不 pop:单帧内多个 bin 让矩阵栈逐层长高。
  6. StateSwitch 与 PushConstants(PushConstants.cpp:35) 在 in-tree 零调用(仅 ObjectFactory 注册)——这正是上面缺陷能存活到 1.1.16 的原因。

第七章说命令层的策略是"薄封装 + 强约定"。状态层更极端:它是"一个 32 位整数 + 若干不成文约定"。约定被遵守时一切正常;一旦用户写出 GraphicsPipelineConfigurator 没生成过的结构,错误几乎都不报错,只是画错。

8.0.3 阅读路线

这一章 87 个文件、13,387 行,按目录顺序读会淹没在适配器里。按"写入—存储—分派—旁路"四段跳读,每段只读一个核心文件。

第一段(写入方):读 StateCommand 与 slot 协议。 从 include/vsg/state/StateCommand.h:36 的 slot 字段起,看 src/vsg/state/StateCommand.cpp:20 的 slot(rhs.slot) 拷贝如何传播它,再跳到两个极端赋值点——src/vsg/state/PushConstants.cpp:19 的 Inherit(2) 与 src/vsg/state/ViewportState.cpp:21 的 slot = 8。目标是建立"slot 是数据不是类型"的直觉。

第二段(存储方):读 StateStack。 include/vsg/vk/State.h:62 的 push、include/vsg/vk/State.h:67 的 pop、include/vsg/vk/State.h:76 的 record 加起来不到 15 行;record 只比较 stack[pos] 与 stack[0] 就决定是否重录,这是全章不变量的核心。配合 src/vsg/vk/State.cpp:28 的 activeMaxStateSlot = maxSlots.max() 理解记忆槽。

第三段(分派方):读 RecordTraversal::apply(const StateGroup&)。 入口 src/vsg/app/RecordTraversal.cpp:524 的 push(begin, end),配对 src/vsg/app/RecordTraversal.cpp:528 的 pop(begin, end)。把这两行与 include/vsg/nodes/StateGroup.h:75 那个只遍历 children、跳过 stateCommands 的 traverse 重载对照,就懂了 8.3 的"两棵树形状不同"。

第四段(旁路):先读 StateSwitch::record,再读 Bin。 src/vsg/state/StateSwitch.cpp:64 那行直接调 child.stateCommand->record,是全章最大破口;src/vsg/nodes/Bin.cpp:97 用 stateStack.top() 做状态快照,src/vsg/nodes/Bin.cpp:139 却只 push modelviewMatrixStack 不 pop,是"一处做对、一处做错"的对照。

按需分支: CPU 包围体读 8.6 的 cloneArrayState 切片(src/vsg/state/ArrayState.cpp:268);资源池读 8.8 的 maxSlots 采集(src/vsg/vk/ResourceRequirements.cpp:161);只想复现缺陷就跳到 8.13。


8.1 StateCommand:45 行撑起整个体系

8.1.1 45 行里的全部信息

include/vsg/state/StateCommand.h 去掉许可证头(1–13 行)和空行,有效代码 20 行:

#include <vsg/commands/Command.h>

namespace vsg
{
    /// Base class for Vulkan commands associated with state, such as binding graphics
    /// pipelines and descriptor sets for textures, uniform buffers and storage buffers.
    /// StateCommands can be attached directly as nodes in the scene graph, or more typically
    /// assigned to StateGroup nodes to enable push/popping of state.
    class VSG_DECLSPEC StateCommand : public Inherit<Command, StateCommand>
    {
    public:
        explicit StateCommand(uint32_t in_slot = 0) : slot(in_slot) {}
        StateCommand(const StateCommand& rhs, const CopyOp& copyop);

        int compare(const Object& rhs_object) const override;
        void read(Input& input) override;
        void write(Output& output) const override;

        uint32_t slot = 0;

    protected:
        ~StateCommand() override {}
    };
    VSG_type_name(vsg::StateCommand);

    using StateCommands =
        std::vector<ref_ptr<StateCommand>, allocator_affinity_nodes<ref_ptr<StateCommand>>>;
} // namespace vsg

整个类相对 Command 只加了一个 uint32_t slot。它没有新增虚函数,没有重写 record(Command::record 仍是纯虚),没有重写 compile(继承 Compilable 的空实现)。它的全部价值是:

  • 给 State::push 一个可以分派到 stateStacks[slot] 的类型标记;
  • 给 State::push / pop 的迭代器模板一个统一的元素类型;
  • 让 StateGroup::stateCommands 能够表达"这些命令是状态,不是绘制"。

换句话说,StateCommand 不是"能改状态的命令",而是"能被压进状态栈的命令"。这个区别在 8.5 会变成致命问题:StateSwitch 是一个 StateCommand,所以它会被压进栈;但它的 record 又去调用别的 StateCommand,那些子命令没有被压进栈。

8.1.2 为什么 slot 不是 const

uint32_t slot = 0; 是 public、非 const、无 setter。任何持有对象的人都能写 sc->slot = 9;。库自己也这么干:

// src/vsg/state/ViewportState.cpp:19–22
ViewportState::ViewportState()
{
    slot = 8;
}

ViewportState 的构造函数没有走 StateCommand(uint32_t),而是默认构造 StateCommand(0) 之后直接改字段。这是全库唯一一处"构造后写 slot"。其余类都通过基类构造函数传参:

// src/vsg/state/BindDescriptorSet.cpp:26
BindDescriptorSets::BindDescriptorSets() : Inherit(1), ...
// src/vsg/state/GraphicsPipeline.cpp:280
BindGraphicsPipeline::BindGraphicsPipeline() : Inherit(0), ...
// src/vsg/state/PushConstants.cpp:19
PushConstants::PushConstants() : Inherit(2) // slot 0
// src/vsg/state/ViewDependentState.cpp:106
BindViewDescriptorSets::BindViewDescriptorSets() : Inherit(2), // slot 2

slot 可变带来一个时序问题:CollectResourceRequirements 只在 Viewer::compile() 期间采集一次最大值(8.8.3),此后 CommandGraph::maxSlots 与 State::stateStacks.size() 都定死了。如果用户在编译之后改 slot:

auto vp = vsg::ViewportState::create();
viewer->compile();          // maxSlots.view 已被采到 8
vp->slot = 20;              // 编译之后改
// 下一次 record:stateStacks[20] → operator[] 越界

State::push 里是 stateStacks[(*itr)->slot].push((*itr));,std::vector::operator[] 无边界检查。这不是"可能出问题",是确定的越界写。而 slot 是 public 的,没有任何 API 能阻止它。

8.1.3 StateCommands 为什么必须是 ref_ptr<StateCommand>

第七章末尾问的这个问题,答案有两层。

第一层是类型层面的:State::push 需要 slot。

// include/vsg/vk/State.h:367–375
template<typename Iterator>
inline void push(Iterator begin, Iterator end)
{
    for (auto itr = begin; itr != end; ++itr)
    {
        stateStacks[(*itr)->slot].push((*itr));
    }
    dirty = true;
}

第二层是所有权层面的:StateStack(State.h:32) 存的是裸指针。

template<class T>
class StateStack
{
    using Stack = std::array<const T*, STATESTACK_SIZE>;   // 16 个裸指针
    Stack stack;
    size_t pos = 0;
    ...
};

如果元素类型是 Command,StateGroup 一样能持有引用,所以第一层才是决定性理由。但第二层解释了为什么 StateGroup 不能用 std::vector<StateCommand*> 或 observer_ptr——一旦压栈期间有任何一个 ref_ptr 被释放,栈里的裸指针立即悬垂。

第三层是 ref_ptr 的隐式转换,它其实很脆弱。

State::push(ref_ptr<StateCommand> command) 这个重载(第 397–401 行)写的是:

inline void push(ref_ptr<StateCommand> command)
{
    stateStacks[command->slot].push(command);
    dirty = true;
}

8.1.4 allocator_affinity_nodes 的意义

using StateCommands =
    std::vector<ref_ptr<StateCommand>, allocator_affinity_nodes<ref_ptr<StateCommand>>>;

StateGroup::add() 直接 push_back,没有 reserve:从 0 加到 9 个状态命令要经历 1→2→4→8→16 共 5 次重新分配,建 10,000 个 StateGroup 就是 50,000 次分配。这才是亲和分配器存在的理由。

8.1.5 compare / read / write 的契约细节

// src/vsg/state/StateCommand.cpp
StateCommand::StateCommand(const StateCommand& rhs, const CopyOp& copyop) :
    Inherit(rhs, copyop),
    slot(rhs.slot)
{}

int StateCommand::compare(const Object& rhs_object) const
{
    int result = Object::compare(rhs_object);
    if (result != 0) return result;
    const auto& rhs = static_cast<decltype(*this)>(rhs_object);
    return compare_value(slot, rhs.slot);
}

void StateCommand::read(Input& input)
{
    Command::read(input);
    input.read("slot", slot);
}

void StateCommand::write(Output& output) const
{
    Command::write(output);
    output.write("slot", slot);
}

三点:

8.1.6 九个直接派生类

grep -rn "Inherit<StateCommand" include/vsg/ 得到 9 个:

类文件构造时的 slot用途
GraphicsPipelineStatestate/GraphicsPipeline.h:280(基类默认)十个管线状态子类的共同基类
BindGraphicsPipelinestate/GraphicsPipeline.h:1100vkCmdBindPipeline
BindComputePipelinestate/ComputePipeline.h:640(ComputePipeline.cpp:126 显式 Inherit(0))vkCmdBindPipeline 的 compute 版
BindRayTracingPipelineraytracing/RayTracingPipeline.h:840光追管线
BindDescriptorSetsstate/BindDescriptorSet.h:241 + firstSet一次绑多个 descriptor set
BindDescriptorSetstate/BindDescriptorSet.h:911 + firstSet一次绑一个,内存更省
BindViewDescriptorSetsstate/ViewDependentState.h:532视图相关 descriptor set
PushConstantsstate/PushConstants.h:232(注释写 slot 0)vkCmdPushConstants
StateSwitchstate/StateSwitch.h:210(默认)按掩码选择子状态命令

GraphicsPipelineState 又派生 9 个(grep -rn "Inherit<GraphicsPipelineState" include/vsg/state/ 的精确结果):

ColorBlendState   DepthStencilState   DynamicState      InputAssemblyState
MultisampleState  RasterizationState  TessellationState VertexInputState
ViewportState

九个类,四个不同 slot 值(0 / 1+firstSet / 2 / 8),其中一个 ViewportState 是所有 GraphicsPipelineState 里唯一一个改了 slot 的。这张表就是整个状态系统的"协议规范"——它没有出现在任何头文件里,是读 5 个 .cpp 拼出来的。8.2 把它展开。


8.2 slot 编号方案:一个没有文档的协议

8.2.1 五个显式赋值点

全库搜 slot 的写操作,只有这些(不含 StateCommand 自身的构造与序列化):

include/vsg/state/BindDescriptorSet.h:40    Inherit(1),           // slot 1
include/vsg/state/BindDescriptorSet.h:107   Inherit(1),           // slot 1
include/vsg/state/BindDescriptorSet.h:31    Inherit(1 + in_firstSet),
include/vsg/state/BindDescriptorSet.h:98    Inherit(1 + in_firstSet),
include/vsg/state/BindDescriptorSet.h:117   Inherit(1 + in_firstSet),
src/vsg/state/BindDescriptorSet.cpp:26      Inherit(1),
src/vsg/state/ComputePipeline.cpp:126       Inherit(0),
src/vsg/state/GraphicsPipeline.cpp:280      Inherit(0),
src/vsg/state/PushConstants.cpp:19          Inherit(2) // slot 0
src/vsg/state/PushConstants.cpp:24          Inherit(2), // slot 0
src/vsg/state/ViewDependentState.cpp:106    Inherit(2), // slot 2
src/vsg/state/ViewportState.cpp:21          slot = 8;

8.2.2 slot 0:九个类共用的"覆盖槽"

slot 0 里住着:

  • BindGraphicsPipeline(GraphicsPipeline.cpp:318)(GraphicsPipeline.cpp:312)(GraphicsPipeline.cpp:289)、BindComputePipeline(ComputePipeline.cpp:135)、BindRayTracingPipeline
  • GraphicsPipelineState 的 8 个子类(除 ViewportState)
  • StateSwitch(默认构造)

GraphicsPipelineState 的这 8 个子类有一个共同特征:它们的 record 是空实现,只在 VkGraphicsPipelineCreateInfo 的 pNext 链里被读取。看 GraphicsPipeline.h:28–40:

class VSG_DECLSPEC GraphicsPipelineState : public Inherit<StateCommand, GraphicsPipelineState>
{
public:
    GraphicsPipelineState() {}
    ...
    void record(CommandBuffer&) const override {}
};

第七章 7.9.3 讨论"嵌套 16 层 StateGroup 会越界"时提到这 8 个 GraphicsPipelineState 的 record 是空的,那是 16 层栈的场景。这里补上另一半:它们不只是浪费栈空间,放进 stateCommands 会静默吞掉 pipeline 绑定。

8.2.3 1 + firstSet:算术协议与它的边界

BindDescriptorSet(VkPipelineBindPoint in_bindPoint, PipelineLayout* in_pipelineLayout,
                  uint32_t in_firstSet, DescriptorSet* in_descriptorSet) :
    Inherit(1 + in_firstSet),
    ...

边界问题有三:

for (uint32_t slot = 0; slot <= activeMaxStateSlot; ++slot)
    stateStacks[slot].record(*_commandBuffer);

每个 record() 是一次指针比较(大概率相等,跳过)。1002 次比较 × 每帧数千次 dirty(State.cpp:83) → 百万级无用比较。这不崩,只是慢。真正的问题是 STATESTACK_SIZE = 16:无论 firstSet(BindDescriptorSet.cpp:36) 多大,同槽嵌套 16 层仍然越界(第七章 7.9.2)。

其二,BindDescriptorSets(BindDescriptorSet.cpp:42)(BindDescriptorSet.cpp:32)(复数)的 slot 只看 firstSet,不看绑了几个 set。

BindDescriptorSets(..., uint32_t in_firstSet, const DescriptorSets& in_descriptorSets) :
    Inherit(1 + in_firstSet), ...

其三,slot 与 firstSet 的耦合是单向的。 改 bds->firstSet = 3 不会更新 bds->slot(仍是构造时的 1)。两个字段各自可变、必须手工同步,这是典型的"双份真相"。反序列化时两者分别从文件读入,如果文件被手工编辑过,也可能不一致。

8.2.4 slot 2 的三方冲突

这是本章最值得单独列一节的数字。

// src/vsg/state/PushConstants.cpp:18–20
PushConstants::PushConstants() :
    Inherit(2) // slot 0
{
}

// src/vsg/state/ViewDependentState.cpp:104–108
BindViewDescriptorSets::BindViewDescriptorSets() :
    Inherit(2), // slot 2
    pipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS),
    firstSet(0)
{
}

// include/vsg/state/BindDescriptorSet.h:97–98
BindDescriptorSet(..., uint32_t in_firstSet, DescriptorSet* ...) :
    Inherit(1 + in_firstSet),   // firstSet = 1 → slot 2

三个语义完全不相关的命令落到 slot 2:

命令slot 来源做什么
PushConstants硬编码 Inherit(2)vkCmdPushConstants
BindViewDescriptorSets硬编码 Inherit(2)vkCmdBindDescriptorSets(视图级)
BindDescriptorSet(firstSet=1, ...)1 + firstSetvkCmdBindDescriptorSets(set 1)

PushConstants.cpp 的注释 // slot 0 与代码 Inherit(2) 矛盾——这是复制粘贴留下的错误注释,但它恰好暴露了作者的犹豫:写这行时脑子里想的是 slot 0,落笔是 2。而 BindViewDescriptorSets(ViewDependentState.cpp:148)(ViewDependentState.cpp:142)(ViewDependentState.cpp:105) 的注释 // slot 2 是对的。

要避开,用户必须手工改其中一个的 slot(比如 pushConstants->slot = 3),并且在 compile() 之前改,否则 maxSlots 采不到新值。这个操作没有任何 API 支持,也没有任何文档提示。

// src/vsg/state/ViewDependentState.cpp 里的 traverse 路径
// 它不走 StateGroup 的 push,因此不占 slot 2 的栈

所以内置代码不会触发这个冲突。它是"用户 API 的组合陷阱",不是"当前实现的 bug"。这个区分很重要——本章后面几节会反复出现"内置路径安全、用户路径危险"的模式,这是 VSG 状态层的整体特征。

8.2.5 slot 8 与 Slots::view

// src/vsg/state/ViewportState.cpp:19–22
ViewportState::ViewportState()
{
    slot = 8;
}

8 这个数字没有枚举、没有常量、没有注释解释为什么是 8。它是"给 view 级状态留一个远离 pipeline/descriptor 的高编号"的手工选择。相关逻辑在 ResourceRequirements.cpp:

// src/vsg/vk/ResourceRequirements.cpp:237–241
void CollectResourceRequirements::apply(const RenderGraph& rg)
{
    if (rg.viewportState) requirements.maxSlots.view = std::max(requirements.maxSlots.view, rg.viewportState->slot);
    rg.traverse(*this);
}

// :243–248
void CollectResourceRequirements::apply(const View& view)
{
    if (view.camera && view.camera->viewportState)
        requirements.maxSlots.view = std::max(requirements.maxSlots.view, view.camera->viewportState->slot);
    ...
}

Slots 有两个字段:

// include/vsg/vk/Slots.h:20–45
struct Slots
{
    uint32_t state = 0;
    uint32_t view = 0;
    uint32_t max() const { return view > state ? view : state; }
    void update(const Slots& rhs)
    {
        if (rhs.state > state) state = rhs.state;
        if (rhs.view > view) view = rhs.view;
    }
    bool requiresUpdate(const Slots& rhs) const
    {
        return rhs.state > state || rhs.view > view;
    }
};

pushView / popView(State.cpp:71) 是这套二分法的执行端:

// src/vsg/vk/State.cpp:53–63
void State::pushView(ref_ptr<StateCommand> command)
{
    stateStacks[command->slot].push(command);
    activeMaxStateSlot = maxSlots.max();
}

void State::popView(ref_ptr<StateCommand> command)
{
    stateStacks[command->slot].pop();
    activeMaxStateSlot = maxSlots.max();
}

注意 pushView 把 activeMaxStateSlot 提到 max(),而 record() 结束时把它降回 maxSlots.state:

// include/vsg/vk/State.h:348–365
inline void record()
{
    if (dirty)
    {
        for (uint32_t slot = 0; slot <= activeMaxStateSlot; ++slot)
            stateStacks[slot].record(*_commandBuffer);
        activeMaxStateSlot = maxSlots.state;   // ← 回落
        projectionMatrixStack.record(*_commandBuffer);
        modelviewMatrixStack.record(*_commandBuffer);
        dirty = false;
    }
}

8.2.6 为什么没有中心化的枚举

把 8.2.1–8.2.5 合起来看,这套协议的完整定义是:

slot 0        pipeline 绑定(三个 Bind*Pipeline)+ 8 个空 record 的 GraphicsPipelineState
              + StateSwitch(默认值)
slot 1+N      descriptor set 绑定,N = firstSet
slot 2        PushConstants(硬编码)/ BindViewDescriptorSets(硬编码)
              / 任何 firstSet=1 的 BindDescriptorSet
slot 8        ViewportState(构造后赋值)
其它          用户自定义;必须在 compile() 前确定;无上限检查;同槽嵌套 ≤ 15

8.3 StateGroup:三个 traverse 重载与一次不对称的拷贝

8.3.1 88 行头文件的全部信息量

// include/vsg/nodes/StateGroup.h:27–85(节选)
/// StateGroup is a Group node that manages a list of StateCommands that are used during
/// the RecordTraversal for applying state to subgraphs.
/// When the RecordTraversal encounters the StateGroup its StateGroup::stateCommands are
/// pushed to the appropriate vsg::State stacks and when a Command is encountered during
/// the RecordTraversal the current head of these State stacks are applied. After traversing
/// the StateGroup's subgraph the StateGroup::stateCommands are popped from the vsg::State stacks.
class VSG_DECLSPEC StateGroup : public Inherit<Group, StateGroup>
{
public:
    StateGroup();
    StateGroup(const StateGroup& rhs, const CopyOp& copyop = {});

    StateCommands stateCommands;

    /// if the shaders associated with GraphicsPipeline don't treat the array 0 as xyz vertex
    /// then provide an ArrayState prototype to provide custom mapping of arrays to vertices.
    ref_ptr<ArrayState> prototypeArrayState;

    template<class T> bool contains(const T value) const
    { return std::find(stateCommands.begin(), stateCommands.end(), value) != stateCommands.end(); }

    void add(ref_ptr<StateCommand> stateCommand) { stateCommands.push_back(stateCommand); }

    template<class T> void remove(const T value)
    {
        if (auto itr = std::find(stateCommands.begin(), stateCommands.end(), value);
            itr != stateCommands.end()) stateCommands.erase(itr);
    }

public:
    ref_ptr<Object> clone(const CopyOp& copyop = {}) const override
    { return StateGroup::create(*this, copyop); }
    int compare(const Object& rhs) const override;

    template<class N, class V>
    static void t_traverse(N& node, V& visitor)
    {
        for (auto& sc : node.stateCommands) sc->accept(visitor);
        for (auto& child : node.children) child->accept(visitor);
    }

    void traverse(Visitor& visitor) override { t_traverse(*this, visitor); }
    void traverse(ConstVisitor& visitor) const override { t_traverse(*this, visitor); }
    void traverse(RecordTraversal& visitor) const override
    {
        for (auto& child : children) child->accept(visitor);
    }

    void read(Input& input) override;
    void write(Output& output) const override;
protected:
    ~StateGroup() override;
};

数据成员只有两个:StateCommands stateCommands(继承 Group::children 之外新增)和 ref_ptr<ArrayState> prototypeArrayState。全部行为集中在三个 traverse 重载里。

8.3.2 三个 traverse 的分裂:这是全库唯一一例

Node 的遍历接口在第三章讲过:通常 t_traverse 一个模板 + 两个 traverse 重载(Visitor& / ConstVisitor&)。StateGroup 有三个:

重载遍历 stateCommands遍历 children谁调用
traverse(Visitor&)是是CompileTraversal、CollectResourceRequirements 之外的普通 Visitor
traverse(ConstVisitor&) const是是CollectResourceRequirements、ComputeBounds、Intersector
traverse(RecordTraversal&) const否是RecordTraversal::apply(const StateGroup&)
  1. 一次额外的 state->record()(每个状态命令前都调一次);
  2. 状态命令被录制两次(一次遍历时,一次栈顶分派时);
  3. push/pop 完全失去意义——状态成了"按 vector 顺序执行一次"而不是"按栈继承"。

所以跳过是正确的,而且是这套状态继承语义成立的前提。但它带来一个不那么显然的后果:StateGroup 是唯一一个"遍历内容取决于访问者类型"的节点。全库搜 traverse(RecordTraversal&) 的重写:

grep -rn "traverse(RecordTraversal" include/vsg/ | grep -v thirdparty

一个直接后果:ComputeBounds::apply(const StateGroup&) 里必须自己再遍历一次 stateCommands,而不是依赖 stategroup.traverse(*this):

// src/vsg/utils/ComputeBounds.cpp:48–62
void ComputeBounds::apply(const StateGroup& stategroup)
{
    auto arrayState = stategroup.prototypeArrayState
        ? stategroup.prototypeArrayState->cloneArrayState(arrayStateStack.back())
        : arrayStateStack.back()->cloneArrayState();

    for (auto& statecommand : stategroup.stateCommands)
    {
        statecommand->accept(*arrayState);
    }

    arrayStateStack.emplace_back(arrayState);
    stategroup.traverse(*this);
    arrayStateStack.pop_back();
}

结果正确,但这是"三个 traverse 分裂"的隐蔽成本:任何 ConstVisitor 都会自动吃到 stateCommands,而只有 CollectResourceRequirements 需要它(8.8.2 采 slot 与 descriptor)。设计上是"为采集器做的便利,其他访问者一起买单"。

8.3.3 RecordTraversal::apply(const StateGroup&) 的 15 行

// src/vsg/app/RecordTraversal.cpp:515–529
void RecordTraversal::apply(const StateGroup& stateGroup)
{
    GPU_INSTRUMENTATION_L2_NCO(instrumentation, *getCommandBuffer(),
                               "StateGroup", COLOR_RECORD_L2, &stateGroup);

    auto begin = stateGroup.stateCommands.begin();
    auto end = stateGroup.stateCommands.end();

    state->push(begin, end);
    stateGroup.traverse(*this);
    state->pop(begin, end);
}

去掉 instrumentation 与空行,逻辑是 4 行。这 4 行就是整个状态继承系统的全部实现。三个细节:

begin/end 被算了两次。 push 和 pop 用同一对迭代器。pop 的实现:

template<typename Iterator>
inline void pop(Iterator begin, Iterator end)
{
    for (auto itr = begin; itr != end; ++itr)
        stateStacks[(*itr)->slot].pop();
    dirty = true;
}

它不检查 pop 出来的是谁,只是按同样的 slot 顺序各弹一次。这依赖一条不变量:从 push 到 pop 之间,stateCommands 这个 vector 没有被修改,且没有任何其他代码对同一 slot 做了 push/pop。

粗粒度标脏配合 StateStack::record 的 memoization,实际产生的 vkCmd* 次数远小于此——但如果场景图是"每个 draw 一个 StateGroup"的扁平结构,这个数字就是真实的 CPU 开销。

没有 try/catch。 见 8.3.5。

8.3.4 push 与 pop 的配对:一条跨三章的不变量

把第七章 7.9.4 与这里合起来,StateStack 的正确性依赖这些配对:

配对来源pushpop中间是否可能抛异常
StateGroupapply(const StateGroup&) 开头同一个函数结尾是(traverse 里任何节点)
View 的 viewportState::pushView(const View&)State::popView(const View&)是
RenderGraph 的 viewportRenderGraph::accept 里 pushView(viewportState)同函数 popView(viewportState)是
Bin 回放Bin::traverse 里 state->push(begin,end)同循环体末尾 state->pop(begin,end)是
preRenderCommandGraph 嵌套State::inherit 复制栈无需 pop(不同的 State 实例)是

前四行都是"同一个函数里 push/pop",都没有异常保护。C++ 里只要 traverse 抛异常,pop 就不执行,pos 永久偏高。后果链是第七章 7.9.2 推过的:

pos 偏高 → 后续 push 从更高处开始 → 累积到 16 → stack[16] 写到 &pos → 段错误

VSG 的场景图遍历不使用异常(Object::accept 与 Visitor::apply 都没有 noexcept,但库内部不抛),所以这条链在纯内置路径上不会触发。但 StateCommand 与 Node 都是公开可派生的,用户节点里的一个 throw 就够了。

一个最小的防护是 RAII:

struct StateScope {
    State* s; StateCommands::const_iterator b, e;
    StateScope(State* s_, decltype(b) b_, decltype(e) e_) : s(s_), b(b_), e(e_) { s->push(b, e); }
    ~StateScope() { s->pop(b, e); }
};

StateGroup::apply 里换成 StateScope scope(state, begin, end); 一行即可。全库没有这个东西。

8.3.5 拷贝构造的 prototypeArrayState 不走 copyop

// src/vsg/nodes/StateGroup.cpp:24–29
StateGroup::StateGroup(const StateGroup& rhs, const CopyOp& copyop) :
    Inherit(rhs, copyop),
    stateCommands(copyop(rhs.stateCommands)),
    prototypeArrayState(rhs.prototypeArrayState)
{
}

stateCommands 走 copyop(...)(按 flags 决定共享或深拷贝),prototypeArrayState(StateGroup.cpp:58)(StateGroup.h:40) 直接复制 ref_ptr,无条件共享。

ArrayState 的 vertices、arrays、矩阵栈、vertexAttribute 等成员全是 public 可变字段(ArrayState.h:54–64),但 ComputeBounds / Intersector 用 cloneArrayState() 复制工作副本,正常路径不直接改原型。真正的风险在文本:CpuLayoutTechnique.cpp:362 与 GpuLayoutTechnique.cpp:337 把原型设成 create(this) / create(this, text, billboard),持有布局技术对象的裸指针。深拷贝时 StateGroup 与 Text 都被 copyop 克隆,原型却仍指向原始对象;原图销毁后克隆图计算包围体会通过它访问字体与字形缓存,裸指针悬垂(第二十章展开)。

一个次要后果在 compare:prototypeArrayState 在 compare_pointer 里按地址比较。

// src/vsg/nodes/StateGroup.cpp:35–43
int StateGroup::compare(const Object& rhs_object) const
{
    int result = Group::compare(rhs_object);
    if (result != 0) return result;
    const auto& rhs = static_cast<decltype(*this)>(rhs_object);
    if ((result = compare_pointer_container(stateCommands, rhs.stateCommands))) return result;
    return compare_pointer(prototypeArrayState, rhs.prototypeArrayState);
}

compare_pointer 对 Object 比较的是类型 + 值(这里 ArrayState 没重写 compare,所以是地址)。两个深拷贝出来的 StateGroup 因为共享原型,compare 会相等——而 stateCommands 因为被深拷贝了,反而不等。比较结果取决于 CopyOp 的 flags,这一点在不同拷贝策略下不稳定。

8.3.6 contains / remove 的模板约束

template<class T> bool contains(const T value) const
{ return std::find(stateCommands.begin(), stateCommands.end(), value) != stateCommands.end(); }

template<class T> void remove(const T value)
{
    if (auto itr = std::find(stateCommands.begin(), stateCommands.end(), value);
        itr != stateCommands.end()) stateCommands.erase(itr);
}

contains(StateGroup.h:43) 还有一个语义陷阱:它比较的是 ref_ptr 的指针相等,不是 Object::compare 的值相等。两个内容完全一样的 BindDescriptorSet 对象,contains 返回 false。这是"身份查询"不是"值查询",名字容易误导。

8.3.7 read / write 的不对称

void StateGroup::read(Input& input)
{
    Group::read(input);
    input.readObjects("stateCommands", stateCommands);
    input.readObject("prototypeArrayState", prototypeArrayState);
}

void StateGroup::write(Output& output) const
{
    Group::write(output);
    output.writeObjects("stateCommands", stateCommands);
    output.write("prototypeArrayState", prototypeArrayState);
}

8.3.8 compare 的顺序与共享对象的判等


8.4 StateStack:把第七章的机器级结论接到写入方

8.4.1 同槽覆盖是"继承"而不是"冲突"

inline void push(const T* value) { stack[++pos] = value; }
inline void pop() { --pos; }
inline void record(CommandBuffer& commandBuffer)
{
    const T* current = stack[pos];
    if (current != stack[0]) { current->record(commandBuffer); stack[0] = current; }
}

嵌套两个 StateGroup,都往 slot 1 压 BindDescriptorSet:

外层 SG: push(A)  → pos=1, stack[1]=A
         遇到 draw → state->record() → current=A, stack[0]=nullptr → 录 A,stack[0]=A
内层 SG: push(B)  → pos=2, stack[2]=B
         遇到 draw → state->record() → current=B, stack[0]=A → 录 B,stack[0]=B
内层结束: pop()  → pos=1
         遇到 draw → state->record() → current=A, stack[0]=B → 录 A,stack[0]=A
外层结束: pop()  → pos=0

所以这个 memoization 的正确性条件是:

stack[0] 保存的是"上一次实际向命令缓冲写入的对象",而 stack[pos] 保存的是"当前生效的对象"。两者相等 ⟺ 命令缓冲的状态已经与目标一致。

这个条件在所有内置路径上成立,因为唯一的写入方就是 StateStack::record。而 8.5 要讲的 StateSwitch::record 会破坏它:它绕开 StateStack 直接调子命令的 record,写入了命令缓冲却没有更新任何 stack[0]。这是本章最关键的破口。

8.4.2 State::inherit 复制了什么

// src/vsg/vk/State.cpp:77–112
void State::inherit(const State& state)
{
    reserve(state.maxSlots);
    reset();
    dirty = true;

    if ((inheritanceMask & InheritanceMask::INHERIT_VIEW_SETTINGS) != 0) { /* 4 个矩阵字段 */ }

    if ((inheritanceMask & InheritanceMask::INHERIT_STATE) != 0)
    {
        stateStacks = state.stateStacks;
    }

    if ((inheritanceMask & InheritanceMask::INHERIT_VIEWPORT_STATE_HINT) != 0)
        viewportStateHint = state.viewportStateHint;

    if ((inheritanceMask & InheritanceMask::INHERIT_MATRICES) != 0)
    {
        projectionMatrixStack = state.projectionMatrixStack;
        modelviewMatrixStack = state.modelviewMatrixStack;
        _frustumUnit = state._frustumUnit;
        _frustumProjected = state._frustumProjected;
        _frustumStack = state._frustumStack;
    }
}

stateStacks = state.stateStacks 是 std::vector<StateCommandStack> 的赋值,逐元素调 StateStack::operator=:

StateStack& operator=(const StateStack& rhs)
{
    stack = rhs.stack;      // std::array<const T*,16> 全量复制
    pos = rhs.pos;
    dirty();                // stack[0] = nullptr
    return *this;
}

三个后果:

其三,inheritanceMask 默认值是 INHERIT_ALL,但四个 bit 里 1 << 3 是空的。

enum InheritanceMask
{
    INHERIT_STATE = (1 << 0),
    INHERIT_VIEWPORT_STATE_HINT = (1 << 1),
    INHERIT_VIEW_SETTINGS = (1 << 2),
    INHERIT_MATRICES = (1 << 4),
    INHERIT_ALL = INHERIT_STATE | INHERIT_VIEWPORT_STATE_HINT | INHERIT_VIEW_SETTINGS | INHERIT_MATRICES
};

1 << 3 被跳过,没有对应的继承项(枚举值不连续合法,但 INHERIT_ALL = 0b10111)。用户若写 mask & (1<<3) 检查某个继承项,永远得到 0。

8.4.3 activeMaxStateSlot 的四处写入

全库只有四处改 activeMaxStateSlot:

位置值时机
State::reservemaxSlots.max()构造、getOrCreateRecordTraversal 每次调用
State::resetmaxSlots.max()每帧 CommandGraph::record 前(间接)
State::record(末尾)maxSlots.state每次 state->record() 且 dirty 为真
State::pushView / popViewmaxSlots.max()view 作用域进出

record() 只在 dirty == true 时才回落;dirty 为 false 时 activeMax 保持上次的值,后续 record() 会多扫几个空槽(正确但慢)。

8.4.4 dirty 的三类写入方

State::dirty 是单个 bool,被置 true 的地方散布在至少六个文件:

写入方文件语义
State::push / pop(模板与单命令重载)vk/State.h状态栈变了
State::connect → dirtyStateStacks()vk/State.cpp换命令缓冲,全部忘掉
State::pushView / popViewvk/State.cpp不置 dirty
RenderGraph::acceptapp/RenderGraph.cpp写 viewportStateHint
Bin::traversenodes/Bin.cpp排序回放前后各一次
MatrixStack::push/pop/setvk/State.h矩阵栈自己的 dirty(另一个变量)

注意 State::pushView(ref_ptr<StateCommand>) 不置 dirty:

void State::pushView(ref_ptr<StateCommand> command)
{
    stateStacks[command->slot].push(command);
    activeMaxStateSlot = maxSlots.max();
    // 没有 dirty = true
}
apply(View) 第 1 步 dirtyStateStacks() → 置 State::dirty = true
        第 6 步 pushView(viewport)      → 只压栈
        第 9 步 view.traverse           → 第一个叶子命令触发 state->record()

8.4.5 State::reset() 清什么、不清什么

void State::reset()
{
    for (auto& stateStack : stateStacks) stateStack.reset();   // pos=0, stack[0]=nullptr
    activeMaxStateSlot = maxSlots.max();
}

它不清 dirty、viewportStateHint、矩阵栈、视锥栈、inheritViewForLODScaling——只负责状态栈,其余由 Viewer 帧循环分别处理(对比第六章 Context::reset() 漏清 imageInfosToCopy)。

8.4.6 从 push 到 vkCmd* 的完整调用链

把本节与 8.3 合起来,一个 StateCommand 从被放进 stateCommands 到产生 Vulkan 调用,中间经过 8 跳:

1. GraphicsPipelineConfigurator::copyTo(StateCommands&)     建图期,push_back
2. StateGroup::stateCommands                                持有 ref_ptr
3. CollectResourceRequirements::apply(const StateCommand&)   compile 期,采 slot
4. State::reserve(maxSlots)                                  compile 期,resize stateStacks
5. RecordTraversal::apply(const StateGroup&)                帧期,state->push(begin,end)
6. StateStack::push(const T*)                               帧期,stack[++pos] = ptr
7. 叶子命令的 apply → state->record()                        帧期,扫 0..activeMax
8. StateStack::record() → current->record(cb)               帧期,发 vkCmd*(若 current != stack[0])

任何一跳的信息丢失都会导致静默错误:第 3 跳漏采 → 第 4 跳尺寸不足 → 第 5 跳越界;第 5 跳漏 push → 第 8 跳录旧对象;第 8 跳被绕过(8.5)→ 记忆与命令缓冲不同步。整条链没有一个环节做校验。

这条链也是理解 maxSlots 的关键——8.8 会把第 3、4 跳展开成采集器的完整路径。


8.5 StateSwitch:三套掩码,一次绕过状态栈的录制

这是本章的核心。StateSwitch 是全库唯一一个"一个 StateCommand 里装了一组 StateCommand"的类,也是唯一一个把 record() 当作分派器而不是终端调用的类。它的 152 行(61 行 .h + 91 行 .cpp)里藏着本章最重要的一个设计错误。

8.5.1 类的全部定义

// include/vsg/state/StateSwitch.h:19–58
/// StateSwitch is a StateCommand that provides support, during the RecordTraveral,
/// for applying StateCommand children based on passing a mask.
/// Can be used to enable state for specific Views where the StateSwitch child masks
/// are matched with the View mask.
class VSG_DECLSPEC StateSwitch : public Inherit<StateCommand, StateSwitch>
{
public:
    StateSwitch();
    StateSwitch(const StateSwitch& rhs, const CopyOp& copyop = {});

    void add(Mask mask, ref_ptr<StateCommand> sc) { children.emplace_back(Child{mask, sc}); }

    struct Child
    {
        Mask mask = MASK_ALL;
        ref_ptr<StateCommand> stateCommand;
    };

    std::vector<Child> children;

    void compile(Context& context) override;
    void record(CommandBuffer& commandBuffer) const override;

public:
    template<class N, class V>
    static void t_traverse(N& sc, V& visitor)
    {
        for (auto& child : sc.children)
        {
            if ((visitor.traversalMask & (visitor.overrideMask | child.mask)) != MASK_OFF)
                child.stateCommand->accept(visitor);
        }
    }

    void traverse(Visitor& visitor) override { t_traverse(*this, visitor); }
    void traverse(ConstVisitor& visitor) const override { t_traverse(*this, visitor); }

    ref_ptr<Object> clone(const CopyOp& copyop = {}) const override
    { return StateSwitch::create(*this, copyop); }
    int compare(const Object& rhs_object) const override;

    void read(Input& input) override;
    void write(Output& output) const override;
};

注意它没有 traverse(RecordTraversal&) 重载。这很重要:StateSwitch 一旦被放进 StateGroup::stateCommands,录制期根本不会 accept 它——StateGroup::traverse(RecordTraversal&) 跳过整个 stateCommands(StateGroup.cpp:45)(StateGroup.h:73)(StateGroup.h:67)(StateGroup.h:63)。它唯一被触碰的方式是 StateStack::record 调它的 record()。

StateSwitch() 是空构造,走 StateCommand() 的默认参数 in_slot = 0。所以 它的 slot 是 0(8.2.2)。

8.5.2 三套掩码:同一个布尔式,三个数据源

全库里这个掩码表达式出现多次(第三章讲过 Node 的掩码约定):

(visitor.traversalMask & (visitor.overrideMask | child.mask)) != MASK_OFF

StateSwitch 把它用了三次,但每次的数据源不同:

#位置表达式traversalMask 来自overrideMask 来自时机
1StateSwitch::t_traversevisitor.traversalMask & (visitor.overrideMask | child.mask)访问者对象访问者对象编译期 / 采集期 / CPU 遍历期
2StateSwitch::compile无掩码,全部遍历——编译期
3StateSwitch::recordcommandBuffer.traversalMask & (commandBuffer.overrideMask | child.mask)CommandBufferCommandBuffer帧期录制

三套的行为可以完全不同。逐条看。

第 1 套:t_traverse。

for (auto& child : sc.children)
    if ((visitor.traversalMask & (visitor.overrideMask | child.mask)) != MASK_OFF)
        child.stateCommand->accept(visitor);

CollectResourceRequirements 的构造函数里有一行:

// include/vsg/vk/ResourceRequirements.h:104
CollectResourceRequirements() { overrideMask = vsg::MASK_ALL; }

overrideMask = MASK_ALL 时,括号里的 (MASK_ALL | child.mask) 恒为 MASK_ALL,表达式化简为 visitor.traversalMask != MASK_OFF。采集器的 traversalMask 默认也是 MASK_ALL,所以所有子命令都会被遍历,无论 child.mask 是什么。这是有意的:编译期资源采集不能因为某个 View 的掩码而漏掉资源,否则那个 View 一旦被启用就会用到未编译的 pipeline。

但 ComputeBounds 与 Intersector 也是 ConstVisitor,它们的 overrideMask 是默认 MASK_OFF,traversalMask 默认 MASK_ALL。表达式变成 child.mask != MASK_OFF——只要子命令的 mask 非零就访问。所以 CPU 侧包围体计算会把所有分支的几何都算进去,包括当前 View 根本不会绘制的分支。结果是包围体偏大(保守),不会错,但会让 CullNode / LOD 的距离判断偏松。

第 2 套:compile。

// src/vsg/state/StateSwitch.cpp:53–56
void StateSwitch::compile(Context& context)
{
    for (auto& child : children) child.stateCommand->compile(context);
}

同时注意 compile 直接调 child.stateCommand->compile(context),不是 accept(CompileTraversal)。第七章 7.1.2 讲过 Compilable::compile 与 CompileTraversal::apply 是两套并行递归。StateSwitch 走的是前者:它的子命令的 compile 被调用,但子命令的 traverse(Visitor&) 不会被 CompileTraversal 访问。而 CompileTraversal 本身是 Visitor,会通过 StateGroup::t_traverse 访问到 StateSwitch,落到 apply(const Command&) 或 apply(const Compilable&) → 调 StateSwitch::compile。两条路径都通向"子命令的 compile 被调用一次"(可能两次,如果两条都走)。compile 里普遍有幂等保护(_vulkanData[deviceID] 非空就 return),所以重复调用无害。

第 3 套:record。

// src/vsg/state/StateSwitch.cpp:58–67
void StateSwitch::record(CommandBuffer& commandBuffer) const
{
    for (auto& child : children)
    {
        if ((commandBuffer.traversalMask & (commandBuffer.overrideMask | child.mask)) != MASK_OFF)
        {
            child.stateCommand->record(commandBuffer);
        }
    }
}

掩码来自 CommandBuffer 而非访问者。RecordTraversal::apply(const View&) 第 2 步把 cb->traversalMask 设成当前 View 的掩码(第七章 7.3.1),所以录制期选中的分支由 View 的掩码决定——正是 StateSwitch 注释里 "enable state for specific Views" 的设计意图。

把三套合起来,得到一个表:

阶段看到哪些分支决定者
CollectResourceRequirements全部(overrideMask = MASK_ALL)采集器
CompileTraversal / StateSwitch::compile全部无
ComputeBounds / Intersectorchild.mask != MASK_OFF 的分支CPU 遍历器
RecordTraversal → StateSwitch::recordcb->traversalMask 匹配的分支当前 View

不一致本身不产生错误(采集/编译是全集的超集,录制是子集),但它让"这个 StateSwitch 到底代表什么"变成一个依赖上下文的问题。更重要的是,第 4 行做的事与前 3 行完全不同——前 3 行是"访问对象",第 4 行是"直接录制"。

8.5.3 致命处:子命令不进状态栈

现在把 8.4.1 的调用链套到 StateSwitch。

假设用户写了一个"按 View 切换 descriptor set"的结构:

auto sw = vsg::StateSwitch::create();
sw->add(0x01, vsg::BindDescriptorSet::create(VK_PIPELINE_BIND_POINT_GRAPHICS,
                                             layout, /* firstSet */ 3, dsA));
sw->add(0x02, vsg::BindDescriptorSet::create(VK_PIPELINE_BIND_POINT_GRAPHICS,
                                             layout, /* firstSet */ 3, dsB));

auto sg = vsg::StateGroup::create();
sg->add(vsg::BindGraphicsPipeline::create(pipeline));   // slot 0
sg->add(sw);                                            // slot 0(StateSwitch 默认)
sg->addChild(draw);

CollectResourceRequirements 会采到 maxSlots.state = 4(来自子命令 1 + firstSet = 4),State::reserve 于是 stateStacks.resize(5)。到这一步一切正常。

录制期,第一个叶子命令触发 state->record():

slot 0 栈:pos=2, stack[1]=BindGraphicsPipeline, stack[2]=StateSwitch
            → StateStack::record: current = StateSwitch ≠ stack[0] → 调 StateSwitch::record()
                → 匹配子命令 dsA(slot 4)→ 直接 dsA->record(cb) → vkCmdBindDescriptorSets
            → stack[0] = StateSwitch
slot 1..3 栈:pos=0,跳过
slot 4 栈:pos=0,stack[0] 是 nullptr 或不确定值,current = stack[0] → 恒等,跳过

关键在最后一行:slot 4 的栈从来没有被 push 过。dsA 的 slot = 4 这个信息在 record() 里被完全忽略——StateSwitch::record 直接调 child.stateCommand->record(commandBuffer),没经过 State::push,也没更新 stateStacks[4].stack[0]。

现在退出 StateGroup,进入下一个 StateGroup(比如另一个材质,没有 slot 4 的状态命令):

slot 0 栈:pop 两次 → pos=0,下一个 SG push 新 pipeline → record 会重录它
slot 4 栈:pos=0,stack[0] 仍是上一次的值(nullptr 或某次遗留),
           current = stack[0] → 相等 → 跳过
           ⇒ GPU 上仍然绑着 dsA!

而 VSG 认为"slot 4 没有变化",所以不会重绑。后续所有 draw 都在用 dsA 的 descriptor set,直到某个 StateGroup 恰好往 slot 4 push 了一个不同的对象,或者下一帧 State::connect 触发 dirtyStateStacks() 把记忆清掉。

这是本章的第一个硬缺陷,可以精确描述:

StateSwitch::record 绕过了 StateStack 的 push/记忆/pop 三步,直接向命令缓冲写状态。任何被子命令修改、但外层 StateGroup 没有覆盖的 slot,在 pop 之后都不会被恢复,也不会被重录。

三条附加观察:

其一,子命令的 slot 字段成了纯装饰。 采集器读了它(maxSlots 因此变大),但录制期不用它。8.2.3 算过"firstSet=1000 会造出 1002 个栈"——如果那个 BindDescriptorSet 是 StateSwitch 的子命令,这 1002 个栈里 slot 1001 永远空着,纯浪费 136 KB。

其二,_currentPipelineLayout 永远不会被设置。 全库只有三个地方调 CommandBuffer::setCurrentPipelineLayout:GraphicsPipeline.cpp:315(BindGraphicsPipeline::record)、ComputePipeline.cpp:161、RayTracingPipeline.cpp:257。它们全是 Bind*Pipeline 的 record,也就是 slot 0 的命令。8.5.3 的场景里 slot 0 的栈顶是 StateSwitch,BindGraphicsPipeline 被吞掉,于是 setCurrentPipelineLayout 一次都不调。

后果落在 MatrixStack::record:

auto pipeline = commandBuffer.getCurrentPipelineLayout();
auto stageFlags = commandBuffer.getCurrentPushConstantStageFlags();
if (pipeline == 0 || stageFlags == 0) return;      // 保持 dirty = true

pipeline(GraphicsPipeline.cpp:295) 保持 0,所有 vkCmdPushConstants 都不发,而 dirty 永远是 true(return 不清 dirty),每帧每个叶子命令都白跑一次两次比较。第七章 7.3.1 把这叫"dirty 的语义是未完成而不是已变更"——StateSwitch 让这个"未完成"变成永久状态。

这两点合起来,StateSwitch 放进 StateGroup::stateCommands 的默认用法就是坏的:要么 pipeline 被吞,要么 descriptor 泄漏,通常两者同时发生。

8.5.4 为什么 in-tree 没暴露

grep -rn "StateSwitch::create\|StateSwitch>" --include=*.cpp src/
# src/vsg/io/ObjectFactory.cpp:254:    add<vsg::StateSwitch>();
grep -rn "PushConstants::create\|PushConstants>" --include=*.cpp src/
# src/vsg/io/ObjectFactory.cpp:252:    add<vsg::PushConstants>();

全库只有 ObjectFactory 的两行注册。没有任何 src/ 文件创建过这两个类的实例。它们是"为序列化与用户 API 保留的类",从未被 VSG 自己的示例、Builder、配置器、加载器走过。

这解释了 8.5.3 与 8.2.4 能存活到 1.1.16:没有回归测试覆盖它们。也解释了为什么 PushConstants.cpp 里 Inherit(2) // slot 0 这个矛盾注释没人改——它从来没被读过第二遍。

同样的检查对 BindViewDescriptorSets(ViewDependentState.cpp:112) 不成立:它由 ViewDependentState 内部创建并通过 traverse 直接录制,是热路径。但那条路径不经过 StateGroup,所以也不占 slot 栈,8.2.4 的三方冲突仍然不触发。

8.5.5 StateSwitch 的 compare 有一个 C++ 层面的小问题

// src/vsg/state/StateSwitch.cpp:32–51
int StateSwitch::compare(const Object& rhs_object) const
{
    int result = Object::compare(rhs_object);
    if (result != 0) return result;

    auto& rhs = static_cast<decltype(*this)>(rhs_object);
    ...
}

decltype(*this) 是 const StateSwitch&,这行 static_cast 合法。但它跳过了 StateCommand::compare,调的是 Object::compare。

后果:StateSwitch 的 slot 不参与比较。两个 children 相同、slot 分别为 0 与 5 的 StateSwitch,compare 返回 0;SharedObjects 会当成同一个对象共享,于是 slot=5 的图用 slot=0 的对象去 push,行为改变。

8.5.6 read / write 的 uint32_t 截断

void StateSwitch::read(Input& input)
{
    StateCommand::read(input);
    children.resize(input.readValue<uint32_t>("children"));
    for (auto& child : children)
    {
        input.read("child.mask", child.mask);
        input.read("child.stateCommand", child.stateCommand);
    }
}

void StateSwitch::write(Output& output) const
{
    StateCommand::write(output);
    output.writeValue<uint32_t>("children", children.size());
    for (auto& child : children)
    {
        output.write("child.mask", child.mask);
        output.write("child.stateCommand", child.stateCommand);
    }
}

children.size() 是 64 位 size_t,writeValue<uint32_t> 截断到 32 位(超过 40 亿个分支才溢出);Mask(StateSwitch.h:31) 是 uint64_t(core/Mask.h:20),按 64 位读。两者位宽不同但独立,无 bug。

8.5.7 如果要修,最小改动是什么

StateSwitch 的问题不是"少写一行",而是它的抽象选错了层级。三条可能的修法,代价递增:

修法 C:展开成多个 StateGroup。 建图期按 mask 生成 N 个 StateGroup,各挂一个 Layer/Switch 选择。零内核改动、完全复用现有机制,代价是节点数 ×N,且 mask 必须在建图期确定。

从 VSG 的整体风格看,修法 A 最贴合:StateSwitch 本质上是一个"状态组选择器",它应该是一个节点而不是一个状态命令。当前把它做成 StateCommand,是为了能塞进 StateGroup::stateCommands 这个现成的容器——一个便利性的选择,代价是绕过了整套栈语义。

结论:没有一行补丁,只有结构性重构。这也解释了为什么 1.1.16 里它还是原样——一个从未被内置代码使用、用户很少碰的类,重构优先级最低。

8.5.8 与第七章三个悬念的呼应

第七章问"stack[0] 记忆槽恰好正确的依赖链有多长"——8.4.1 把它写成明确不变量,8.5.3 给出第一个真正打破它的内置类。答案是:所有能写命令缓冲的路径都必须更新 stack[0],而 StateSwitch 是唯一不更新的。

由此可以把整层的模式命名:正确性不由代码保证,而由"所有写入方遵守同一个不成文协议"保证。协议四条:

  1. 状态只能通过 StateStack::record 写入命令缓冲;
  2. push 与 pop 严格配对,中间不抛异常;
  3. 同槽嵌套深度 < 16;
  4. 所有 slot 在 compile() 前冻结。

StateSwitch 违反第 1 条,8.3.4 的异常路径违反第 2 条,第七章 7.9.2 的 16 层嵌套违反第 3 条,8.1.2 的运行时改 slot 违反第 4 条。四条各有一个可定位的破口,全库没有一条检查。


8.6 ArrayState 与 prototypeArrayState:CPU 侧重建 GPU 顶点

StateGroup 的第二个数据成员 ref_ptr<ArrayState> prototypeArrayState 与状态栈毫无关系。它服务于另一条完全独立的链路:在 CPU 上把 GPU 用特殊方式处理的顶点,还原成一组 vec3,以便 ComputeBounds、Intersector 能算出正确的包围体与交点。

8.6.1 为什么需要它

场景图里的几何默认假设"array 0 是 vec3Array,每个元素是一个本地坐标顶点"。ComputeBounds 只要把 vertices 用当前矩阵栈变换一下再取 min/max 就行。但以下情况会打破这个假设:

技术GPU 上做了什么CPU 上看到的 vec3Array 是什么
实例化平移shader 用 location=7 的 per-instance 平移量偏移顶点只有一份基础网格,没有每个实例的位置
实例化 TRSshader 用 location 7/8/9 的平移/旋转/缩放同上
位移贴图shader 采样纹理、沿法线偏移顶点未位移的基础网格
Billboardshader 让四边形始终朝向相机一个平面四边形
GPU 文本排版shader 从字形缓冲区取顶点空的或非几何数据

若照搬基础网格算包围体,实例化后的所有实例会被当成一个,剔除与拾取全错。ArrayState 就是这个"CPU 侧镜像 shader 行为"的扩展点。StateGroup::prototypeArrayState 告诉遍历器:"我这棵子树的顶点要这样解释"。

8.6.2 原型模式的两个 cloneArrayState

// include/vsg/state/ArrayState.h:33–43
virtual ref_ptr<ArrayState> cloneArrayState()
{
    return ArrayState::create(*this);
}

/// clone the specified ArrayState
virtual ref_ptr<ArrayState> cloneArrayState(ref_ptr<ArrayState> arrayState)
{
    return ArrayState::create(*arrayState);
}

两个重载的语义不同,而且都写在基类里:

  • 无参版本:克隆 this(原型自己)。
  • 带参版本:克隆传入的 arrayState(父栈的工作副本),完全忽略 this。

ComputeBounds::apply(const StateGroup&) 的用法(8.3.2 引过):

auto arrayState = stategroup.prototypeArrayState
    ? stategroup.prototypeArrayState->cloneArrayState(arrayStateStack.back())
    : arrayStateStack.back()->cloneArrayState();

所以:

  • 有原型时,调的是带参版本。虚分派落在原型的动态类型上(决定"新对象是什么类"),而构造参数是 arrayStateStack.back()(决定"新对象带什么数据")。
  • 无原型时,调无参版本,虚分派落在父栈工作副本的类型上,复制它的全部内容。

这是一套"类型来自原型、状态来自父栈"的原型模式。设计意图是对的:进入一个 StateGroup 时,顶点数组、矩阵栈、拓扑都应该继承外层,只把"如何解释顶点"换成新的实现。

六个派生类的带参实现全部是同一个模板:

// src/vsg/state/ArrayState.cpp(六处,逐字同构)
ref_ptr<ArrayState> NullArrayState::cloneArrayState(ref_ptr<ArrayState> arrayState)
{ return NullArrayState::create(*arrayState); }
ref_ptr<ArrayState> TranslationArrayState::cloneArrayState(ref_ptr<ArrayState> arrayState)
{ return TranslationArrayState::create(*arrayState); }
ref_ptr<ArrayState> TranslationRotationScaleArrayState::cloneArrayState(ref_ptr<ArrayState> arrayState)
{ return TranslationRotationScaleArrayState::create(*arrayState); }
ref_ptr<ArrayState> DisplacementMapArrayState::cloneArrayState(ref_ptr<ArrayState> arrayState)
{ return DisplacementMapArrayState::create(*arrayState); }
ref_ptr<ArrayState> TranslationAndDisplacementMapArrayState::cloneArrayState(ref_ptr<ArrayState> arrayState)
{ return TranslationAndDisplacementMapArrayState::create(*arrayState); }
ref_ptr<ArrayState> BillboardArrayState::cloneArrayState(ref_ptr<ArrayState> arrayState)
{ return BillboardArrayState::create(*arrayState); }

8.6.3 硬缺陷:原型的子类配置全部丢失

TranslationArrayState::create(*arrayState) 中,arrayState 解引用后的静态类型是 ArrayState&,匹配的是下面这个构造函数:

// src/vsg/state/ArrayState.cpp:258–260
TranslationArrayState::TranslationArrayState(const ArrayState& rhs) :
    Inherit(rhs)
{
}

Inherit(rhs) 把 ArrayState 基类部分拷过去,函数体是空的。看基类的拷贝构造复制了哪些字段:

// src/vsg/state/ArrayState.cpp:37–48
ArrayState::ArrayState(const ArrayState& rhs, const CopyOp& copyop) :
    Inherit(rhs, copyop),
    localToWorldStack(rhs.localToWorldStack),
    worldToLocalStack(rhs.worldToLocalStack),
    topology(rhs.topology),
    vertex_attribute_location(rhs.vertex_attribute_location),
    vertexAttribute(rhs.vertexAttribute),
    vertices(rhs.vertices),
    proxy_vertices(rhs.proxy_vertices),
    arrays(rhs.arrays)
{
}

只复制这 8 项。TranslationArrayState(ArrayState.cpp:251) 自己的两个成员——

uint32_t translation_attribute_location = 7;
AttributeDetails translationAttribute;

——完全不复制,用类内默认初始化器重建。于是:

auto proto = vsg::TranslationArrayState::create();
proto->translation_attribute_location = 3;     // 用户按自己的 shader 改了 location
sg->prototypeArrayState = proto;
// ComputeBounds 遍历到 sg:
//   proto->cloneArrayState(parent) → TranslationArrayState::create(*parent)
//   → TranslationArrayState(const ArrayState&) → translation_attribute_location = 7
//   → getAttributeDetails(vas, 7, ...) 找的是 location 7,而 shader 用的是 3
//   → translationAttribute 保持全 0 → vertexArray() 里 arrays[0].cast<vec3Array>()
//     拿到的是基础顶点数组,不是平移数组

更严重的是同类拷贝也丢字段:

// src/vsg/state/ArrayState.cpp:371–378
DisplacementMapArrayState::DisplacementMapArrayState(const DisplacementMapArrayState& rhs) :
    Inherit(rhs)
{
}

DisplacementMapArrayState::DisplacementMapArrayState(const ArrayState& rhs) :
    Inherit(rhs)
{
}

对比 TranslationArrayState(const TranslationArrayState& rhs) 与 BillboardArrayState(const BillboardArrayState& rhs):

TranslationArrayState::TranslationArrayState(const TranslationArrayState& rhs) :
    Inherit(rhs),
    translation_attribute_location(rhs.translation_attribute_location),
    translationAttribute(rhs.translationAttribute)
{
}

这两个是正确的,显式复制了子类字段。DisplacementMapArrayState 与 TranslationAndDisplacementMapArrayState 是漏的。所以缺陷的分布是:

类同类拷贝构造从 ArrayState 构造结论
ArrayState—复制 8 项基类,正确
NullArrayState默认(无状态)默认正确
TranslationArrayState复制 2 项不复制无参 clone 正确,带参 clone 丢配置
TranslationRotationScaleArrayState复制 6 项不复制同上
DisplacementMapArrayState不复制不复制两个 clone 都丢配置
TranslationAndDisplacementMapArrayState不复制不复制同上
BillboardArrayState复制 2 项不复制无参 clone 正确,带参 clone 丢配置

修复的最小改法是给每个派生类的 Xxx(const ArrayState& rhs) 构造加上子类字段的复制——但 rhs 是基类引用,拿不到那些字段。所以要么把它改成模板/双重分派,要么让 cloneArrayState(ref_ptr<ArrayState>) 采用"先无参克隆自己,再从父栈覆盖基类字段":

ref_ptr<ArrayState> cloneArrayState(ref_ptr<ArrayState> parent) override
{
    auto result = TranslationArrayState::create(*this);   // 保留子类配置
    static_cast<ArrayState&>(*result) = *parent;          // 继承父栈状态
    return result;
}

这需要 ArrayState 有一个可访问的赋值运算符(当前只有拷贝构造,编译器会生成 operator=)。六处都要改,且要处理 ArrayState 是 Object 派生、ref_ptr 语义的问题。不是一行补丁,但比 8.5.7 的 StateSwitch 简单得多。

8.6.4 getAttributeDetails:从 Vulkan 描述反查 CPU 数组

// src/vsg/state/ArrayState.cpp:63–84
bool ArrayState::getAttributeDetails(const VertexInputState& vas, uint32_t location,
                                     AttributeDetails& attributeDetails)
{
    for (const auto& attribute : vas.vertexAttributeDescriptions)
    {
        if (attribute.location == location)
        {
            for (const auto& binding : vas.vertexBindingDescriptions)
            {
                if (attribute.binding == binding.binding)
                {
                    attributeDetails.binding = attribute.binding;
                    attributeDetails.format = attribute.format;
                    attributeDetails.offset = attribute.offset;
                    attributeDetails.stride = binding.stride;
                    attributeDetails.inputRate = binding.inputRate;
                    return true;
                }
            }
        }
    }
    return false;
}

两层线性扫描(attribute × binding),返回时不做任何检查:

  • inputRate 读进来了但从来不用。VK_VERTEX_INPUT_RATE_INSTANCE 与 VK_VERTEX_INPUT_RATE_VERTEX 在 CPU 侧应该区别对待(前者按 instance 索引、后者按 vertex 索引),但 vertexArray(instanceIndex) 的实现里直接 arrays[binding].cast<vec3Array>() 然后按 instanceIndex 取——假定所有属性都是 per-instance。对 vertex_attribute_location=0 的基础顶点属性,它没用 instanceIndex,所以没问题;但对 translation_attribute_location,如果 shader 声明成 per-vertex,CPU 侧仍按 instance 解释,结果错。
  • 找不到时返回 false,调用方全部忽略返回值:
void ArrayState::apply(const VertexInputState& vas)
{
    getAttributeDetails(vas, vertex_attribute_location, vertexAttribute);
}
void TranslationArrayState::apply(const VertexInputState& vas)
{
    getAttributeDetails(vas, vertex_attribute_location, vertexAttribute);
    getAttributeDetails(vas, translation_attribute_location, translationAttribute);
}

于是 attributeDetails(ArrayState.cpp:77) 保持全 0(binding=0, stride=0, offset=0, inputRate=VERTEX),后续 arrays[0] 被当作目标。8.6.3 的例子正是这个路径。

  • AttributeDetails::format 读进来只被 ArrayState::apply(const Data&) 用了一次:
if (vertexAttribute.stride > 0 && (vertexAttribute.format == VK_FORMAT_R32G32B32_SFLOAT))

8.6.5 applyArray 与两个 applyArrays 的判空不一致

void ArrayState::applyArray(uint32_t binding, const ref_ptr<BufferInfo>& in_array)
{
    if (in_array && in_array->data) applyArray(binding, in_array->data);
}

void ArrayState::applyArrays(uint32_t firstBinding, const BufferInfoList& in_arrays)
{
    if (arrays.size() < (in_arrays.size() + firstBinding))
        arrays.resize(in_arrays.size() + firstBinding);
    for (size_t i = 0; i < in_arrays.size(); ++i)
    {
        arrays[firstBinding + i] = in_arrays[i]->data;      // ← 无判空
    }
    ...
}

8.6.6 vertexArray() 的空指针风险

TranslationArrayState::vertexArray:

auto translations = arrays[translationAttribute.binding].cast<vec3Array>();
if (translations && (instanceIndex < translations->size()))
{
    auto translation = translations->at(instanceIndex);
    auto new_vertices = vsg::vec3Array::create(static_cast<uint32_t>(vertices->size()));
    ...
}
return vertices;

DisplacementMapArrayState::vertexArray 更直接:

auto normals = arrays[normalAttribute.binding].cast<vec3Array>();
auto texcoords = arrays[texcoordAttribute.binding].cast<vec2Array>();
if (texcoords->size() != vertices->size()) return {};
if (normals->size() != vertices->size()) return {};

8.6.7 ComputeBounds / Intersector 的 arrayStateStack

// src/vsg/utils/ComputeBounds.cpp:37–41
ComputeBounds::ComputeBounds(ref_ptr<ArrayState> intialArrayState)
{
    arrayStateStack.reserve(4);
    arrayStateStack.emplace_back(intialArrayState ? intialArrayState : ArrayState::create());
}

reserve(4) 是嵌套深度的估计(MatrixTransform → StateGroup → StateGroup → Geometry);超过时 vector 重新分配,但元素是 ref_ptr,移动不失效。Intersector.cpp:47–48 有一模一样的两行,两个类各自维护 arrayStateStack 与 matrixStack,前 70 行几乎逐字重复——第七章 7.10.5 讲的 PipelineBarrier/WaitEvents 重复在 utils 层的复现。

ComputeBounds::apply(const StateGroup&) 里的 push/pop:

arrayStateStack.emplace_back(arrayState);
stategroup.traverse(*this);
arrayStateStack.pop_back();

与 RecordTraversal::apply(const StateGroup&) 一样没有异常保护。但这里 pop_back() 丢的是 ref_ptr,不会像 StateStack::pos 那样留下野值——最多是栈里多一层,下次遍历结果偏保守。所以异常安全的严重程度低得多。

NullArrayState 的用途在 ArrayState.h:99–102 的注释里写得很清楚:把子树的几何从包围体/求交计算里排除。它的实现:

void NullArrayState::apply(const vsg::vec3Array&) { vertices = {}; }
void NullArrayState::apply(const vsg::Data&) { vertices = {}; }

两个重载都清空 vertices。之后 ComputeBounds 的 if (!arrayState.vertices) return; 就会跳过几何。这是给"shader 把几何搬到了完全不同的位置"的场景用的——与其算错,不如不算。

8.6.8 文本布局的两个 ArrayState(为什么要留给第二十章)

src/vsg/text/CpuLayoutTechnique.cpp:362
    stategroup->prototypeArrayState = CpuLayoutTechniqueArrayState::create(this);
src/vsg/text/GpuLayoutTechnique.cpp:337
    stateGroup->prototypeArrayState = GpuLayoutTechniqueArrayState::create(this, text, billboard);

create(this, ...) 把布局技术对象或 Text 节点传给原型,这些指针不在 Object 的引用图里、序列化时不重建(8.3.5 的直接后果)。另一条装配路径是 GraphicsPipelineConfigurator::copyTo(ref_ptr<StateGroup>, ...):

// src/vsg/utils/GraphicsPipelineConfigurator.cpp:1000–1013
bool GraphicsPipelineConfigurator::copyTo(ref_ptr<StateGroup> stateGroup, ref_ptr<SharedObjects> sharedObjects)
{
    if (copyTo(stateGroup->stateCommands, sharedObjects))
    {
        stateGroup->prototypeArrayState = getSuitableArrayState();
        return true;
    }
    return false;
}

getSuitableArrayState() 是:

ref_ptr<ArrayState> GraphicsPipelineConfigurator::getSuitableArrayState() const
{
    if (shaderSet && shaderHints)
        return shaderSet->getSuitableArrayState(shaderHints->defines);
    else
        return {};
}

它按 shader 的 defines(编译宏)选一个 ArrayState 子类。这是"shader 决定 CPU 侧解释方式"的自动化路径,也是 8.6.3 的缺陷最可能被调用的地方——用户通过 ShaderSet 注册自定义宏,配置器返回一个带自定义 location 的原型,然后 cloneArrayState(parent) 把配置丢掉。第十章讲 ShaderSet 时会回到这条链。

Builder.cpp:165 也有一句 stateGroup->prototypeArrayState = graphicsPipelineConfig->getSuitableArrayState();,与配置器的 copyTo(StateGroup) 重复——两条装配路径做同一件事,说明这个字段的赋值没有统一的入口。


8.7 Bin:把状态快照下来,排序,再回放

Bin 是 DepthSorted / Layer 的目的地。第七章 7.8.4 第 11 步讲过:apply(const View&) 在 view.traverse 之后、popView 之后才录 bin。本节补上 Bin 内部做了什么,并更正第七章的一处说法。

8.7.1 Bin::add 快照了什么

// src/vsg/nodes/Bin.cpp:60–107
void Bin::add(State* state, double value, const Node* node)
{
    Element element;
    const auto& mv = state->modelviewMatrixStack.top();
#if 1
    if (!_matrices.empty() && _matrices.back() == mv)
        element.matrixIndex = static_cast<uint32_t>(_matrices.size()) - 1;   // 只与最后一个比
    else
    {
        element.matrixIndex = static_cast<uint32_t>(_matrices.size());
        _matrices.push_back(mv);
    }
#else
    element.matrixIndex = _matrices.size();
    _matrices.push_back(mv);
#endif
    element.stateCommandIndex = static_cast<uint32_t>(_stateCommands.size());
    for (const auto& stateStack : state->stateStacks)
        if (stateStack.size() > 0)
        {
            _stateCommands.push_back(stateStack.top());
            ++element.stateCommandCount;
        }
    element.child = node;
    _binElements.emplace_back(static_cast<float>(value), static_cast<uint32_t>(_elements.size()));
    _elements.push_back(element);
}

一次 add 记录四样东西:模型视图矩阵(去重后的索引)、当前所有非空状态栈的栈顶指针、子节点裸指针、排序键。

8.7.2 #if 1 里的是 RLE,不是缓存

#else 是"每次都 push"的朴素实现,被 #if 1 永久关掉。与第五章 #if TRANSFER_BUFFERS 改 1 就编译失败不同,这里改成 #if 0 能编译,只是变慢——无害的死代码。

8.7.3 排序键从 double 压成 float

add 的 value 参数是 double:

// src/vsg/app/RecordTraversal.cpp:311–323
void RecordTraversal::apply(const DepthSorted& depthSorted)
{
    if (state->intersect(depthSorted.bound))
    {
        const auto& mv = state->modelviewMatrixStack.top();
        const auto& center = depthSorted.bound.center;
        auto distance = -(mv[0][2] * center.x + mv[1][2] * center.y
                        + mv[2][2] * center.z + mv[3][2]);
        addToBin(depthSorted.binNumber, distance, depthSorted.child);
    }
}

distance 是 dvec3 与 dmat4 的乘积,全程 double。但 Bin::add 存进 _binElements(Bin.cpp:118) 时是:

_binElements.emplace_back(static_cast<float>(value), static_cast<uint32_t>(_elements.size()));
using KeyIndex = std::pair<float, uint32_t>;

double → float 的显式截断。float 的尾数是 24 位,相对精度约 1.2e-7。对于大地形(相机在原点,物体在 1e6 米外),深度值的绝对分辨率约 0.06 米——两个相距 5 cm 的透明面会得到相同的键。

排序时:

std::sort(_binElements.begin(), _binElements.end(),
          [](const KeyIndex& lhs, const KeyIndex& rhs) { return lhs.first < rhs.first; });

std::sort 对相等键不保证稳定顺序,所以精度碰撞会导致透明物体的绘制顺序随机(std::sort 的实现是 introsort,相等元素的相对顺序取决于分区过程)。表现是"远处两个透明面闪烁/穿插"。

8.7.4 Bin::traverse 的矩阵栈只 push 不 pop

// src/vsg/nodes/Bin.cpp:109–172
void Bin::traverse(RecordTraversal& rt) const
{
    auto state = rt.getState();
    switch (sortOrder) { /* ASCENDING / DESCENDING / NO_SORT 的 std::sort */ }
    uint32_t previousMatrixIndex = static_cast<uint32_t>(_matrices.size());
    state->pushFrustum();
    state->dirty = true;

    for (const auto& keyElement : _binElements)
    {
        const auto& element = _elements[keyElement.second];
        if (element.matrixIndex != previousMatrixIndex)
        {
            state->modelviewMatrixStack.push(_matrices[element.matrixIndex]);   // ← 无对应 pop
            state->applyFrustum();
            state->dirty = true;
            previousMatrixIndex = element.matrixIndex;
        }
        if (element.stateCommandCount > 0)
        {
            auto begin = _stateCommands.begin() + element.stateCommandIndex;
            auto end = begin + element.stateCommandCount;
            state->push(begin, end);
            element.child->accept(rt);
            state->pop(begin, end);                                            // ← 状态栈配平
        }
        else element.child->accept(rt);
    }
    state->popFrustum();
    state->dirty = true;
}

把栈操作列成一张配对表:

栈pushpop配平?
stateStacks[*]state->push(begin,end)state->pop(begin,end)是(同一循环体)
_frustumStackstate->pushFrustum()(循环外 1 次)state->popFrustum()(循环外 1 次)是
modelviewMatrixStackpush(...)(每次矩阵变化 1 次)无否

state->applyFrustum() 只做 _frustumStack.top().set(...) 与 computeLodScale(...),不碰矩阵栈。循环里没有任何 modelviewMatrixStack.pop()。

后果:

  1. 单帧内累积。 previousMatrixIndex 初值是 _matrices.size()(一个不可能等于任何有效索引的值),所以第一个元素必定 push 一次。之后每次矩阵变化再 push。一个 bin 有 K 个不同矩阵,modelviewMatrixStack 就长高 K 层。
  2. 多 bin 累积。 apply(const View&) 第 11 步是 for (bin : view.bins) bin->accept(*this),每个 bin 都调一次 traverse。第二个 bin 开始时矩阵栈已经比第一个高。而 Bin::traverse 里 state->applyFrustum() 用的是 modelviewMatrixStack.top()——栈顶是上一个 bin 最后压进去的矩阵,直到本 bin 第一次 push 才被覆盖。
  3. 跨帧不累积,靠的是 set 而非 pop。 apply(const View&) 第 7 步 setProjectionAndViewMatrix 会调 modelviewMatrixStack.set(viewMatrix),而 MatrixStack::set 是 matrixStack = {}; matrixStack.emplace(matrix);——清空整个栈。所以每个 View 开始时矩阵栈被重置为深度 1。多 View 场景里,第二个 View 不受第一个影响。

所以这个缺陷的准确边界是:单帧、单个 View 内,多个 bin 或单个 bin 内多个不同矩阵,会让 modelviewMatrixStack 单调增长,且 top() 在回放过程中被前一个元素的值污染。

更实质的影响是 MatrixStack::record():

inline void record(CommandBuffer& commandBuffer)
{
    if (dirty)
    {
        ...
        mat4 newmatrix(matrixStack.top());      // dmat4 → mat4 降精度
        vkCmdPushConstants(commandBuffer, pipeline, stageFlags, offset,
                           sizeof(newmatrix), newmatrix.data());
        dirty = false;
    }
}

8.3.4 的表里把 Bin 回放列为"state->push/pop 配对正确"——那是状态栈配对正确,矩阵栈不配对。两条栈的异常安全性在这里也不对称:状态栈用 push/pop 成对,矩阵栈只有 push。

8.7.5 更正第七章:viewport 状态并没有丢

第七章 7.8.4 第 11 步的结论是:

bin 里的 StateGroup 会重新 push 自己的状态(包括 pipeline、descriptor set),但 viewport 不会被重新 push——因为 slot 8 已经弹空了。所以 bin 里的 draw 用的是一个"没有 viewport 命令"的命令缓冲状态,继承自 RenderGraph::accept 里 vkCmdSetViewport 的结果。

后半句"viewport 是命令缓冲全局状态,vkCmdSetViewport 之后所有 draw 都用它"是对的,但前半句漏了 Bin::add 的状态快照。

时间线是:

apply(View) 第 6 步  pushView(camera->viewportState)   → slot 8 栈 pos=1
          第 9 步  view.traverse → DepthSorted::accept
                    → addToBin → Bin::add(state, ...)
                      → for (stateStack : state->stateStacks)
                          if (size()>0) _stateCommands.push_back(stateStack.top())
                      ⇒ slot 8 的 viewportState 被快照进 _stateCommands
          第 10 步 popView(camera->viewportState)      → slot 8 栈 pos=0
          第 11 步 bin->accept(rt) → Bin::traverse
                    → state->push(begin,end)
                      ⇒ 快照里的 viewportState 被 push 回 slot 8
                    → element.child->accept(rt) → 叶子命令 → state->record()
                      ⇒ StateStack<StateCommand>[8].record() 会调 viewportState->record()
                    → state->pop(begin,end)

所以 viewport 被重新 push 了,而且每个 bin 元素都会重新 push 一次(快照里包含它)。StateStack::record 的记忆槽会在第一次录过之后跳过后续重复,所以 vkCmdSetViewport 实际只发一次——这正是 8.4.1 说的"粗粒度标脏 + 细粒度记忆"。

更正后的完整说法是:

bin 录制时 viewport 状态由 Bin::add 的快照 + Bin::traverse 的回放恢复,不是靠命令缓冲的全局状态继承。第七章说"viewport 不会被重新 push"是错的;正确的部分只有"bin 录制发生在 popView 之后"。

这个更正也解释了 Bin::add 为什么要遍历所有 state->stateStacks 而不是只存"变化的部分":它必须完整重建录制时刻的栈状态,因为 popView、外层的 pop 都已经发生过了。这是一个真正的状态快照/回滚机制,而不是排序容器顺手做的优化。

8.7.6 addToBin 的空 ref_ptr

// src/vsg/app/RecordTraversal.cpp:701–704
void RecordTraversal::addToBin(int32_t binNumber, double value, const Node* node)
{
    bins[binNumber - minimumBinNumber]->add(state, value, node);
}

bins 是 RecordTraversal 的成员,apply(const View&) 第 4 步填充:

int32_t min_binNumber = 0;
int32_t max_binNumber = 0;
for (const auto& bin : view.bins) { /* 更新 min/max */ }
minimumBinNumber = min_binNumber;
bins.resize(max_binNumber - min_binNumber + 1);
for (auto& bin : view.bins)
{
    bins[bin->binNumber - min_binNumber] = bin;
    bin->clear();
}

第七章 7.8.4 已指出这点,Bin 侧的呼应:clear() 只对注册过的 bin 调用,没注册的编号连清理机会都没有。DepthSorted::binNumber 是可设的 int32_t,必须与 view.bins 手工同步——又一次"双份真相"。


8.8 ResourceHints 与 ResourceRequirements:提示与需求的闭环

第七章预告里问"为什么前者是提示、后者是需求"。答案在 ResourceRequirements.cpp 的两行里。

8.8.1 两个方向的数据流

// src/vsg/vk/ResourceRequirements.cpp:69(方向一:提示并入需求)
void ResourceRequirements::apply(const ResourceHints& h)
{
    maxSlots.update(h.maxSlots);                       // 只调大
    externalNumDescriptorSets += h.numDescriptorSets;
    for (auto& [type, count] : h.descriptorPoolSizes) descriptorTypeMap[type] += count;
    minimumBufferSize = std::max(minimumBufferSize, h.minimumBufferSize);
    minimumDeviceMemorySize = std::max(minimumDeviceMemorySize, h.minimumDeviceMemorySize);
    minimumStagingBufferSize = std::max(minimumStagingBufferSize, h.minimumStagingBufferSize);
}

// :100–116(方向二:需求导出成提示)
ref_ptr<ResourceHints> CollectResourceRequirements::createResourceHints(uint32_t tileMultiplier) const
{
    auto hints = ResourceHints::create();
    hints->maxSlots = requirements.maxSlots;
    hints->numDescriptorSets = requirements.computeNumDescriptorSets() * tileMultiplier;
    hints->descriptorPoolSizes = requirements.computeDescriptorPoolSizes();
    for (auto& ps : hints->descriptorPoolSizes) ps.descriptorCount *= tileMultiplier;
    hints->dynamicData = requirements.dynamicData;
    hints->containsPagedLOD = requirements.containsPagedLOD;
    return hints;
}

所以:

  • ResourceHints 是"外部注入的下界":用户可以把它挂在 Node 的 auxiliary 上(checkForResourceHints 用 object.getObject<ResourceHints>("ResourceHints")),告诉采集器"即使图上没看到,也要为这些资源预留空间"。典型用途是 DatabasePager 运行时才加载的瓦片——编译期图上根本没有它们,只能靠 hints 预留。
  • ResourceRequirements 是"遍历整张图后算出的实际需求":CollectResourceRequirements 跑完一遍,createResourceHints() 可以把结果写回成一个 ResourceHints,供下一次编译或下一批瓦片复用。

update 与所有 std::max 都只能调大(第六章 6.14 讲过六个 max 两赋值)。所以闭环是单调的:

hints(下界) ──update──▶ requirements(采集结果) ──createResourceHints──▶ hints'(≥ hints)

hints' 永远不小于输入。这个性质保证了"运行时新增瓦片不会让已分配的池变小",代价是场景图删减后 maxSlots 不回落——8.3.6 的 StateGroup::remove 之后 maxSlots 过时,根源就在这里。

8.8.2 采集器只认 StateCommand 的 slot

// src/vsg/vk/ResourceRequirements.cpp:159–163
void CollectResourceRequirements::apply(const StateCommand& stateCommand)
{
    if (stateCommand.slot > requirements.maxSlots.state)
        requirements.maxSlots.state = stateCommand.slot;
    stateCommand.traverse(*this);
}

就两行。第一行采 slot,第二行继续遍历子对象(descriptor、buffer、image)。

也就是说采集器与录制器对 StateSwitch 的理解完全相反:

采集器录制器
看到什么StateSwitch 本身(slot 0)+ 所有子命令(slot 4)只有 StateSwitch 本身(slot 0 栈顶)
子命令进 stateStacks 吗不进,但 slot 被采不进,slot 被忽略
结果stateStacks.resize(5)slot 4 永远空

这是"采集与录制不对称"最干净的一个例子。采集器把 4 记进 maxSlots,State::reserve 老老实实扩了容,State::record() 每帧多扫一个空槽——而那个槽从来没有内容。这不是越界,是纯粹的浪费,且浪费量随 firstSet 线性增长(8.2.3 的 1002 个栈)。

8.8.3 六跳传播链的完整版

第七章 7.9.4 给过一个四跳链,本章把两端补齐成六跳:

0. ResourceHints(用户挂在节点 auxiliary 上)
     │  CollectResourceRequirements::apply(const ResourceHints&) → maxSlots.update()
     ▼
1. CollectResourceRequirements::apply(const StateCommand&) → requirements.maxSlots.state
     │  Viewer::compile() → CollectResourceRequirements 遍历整图
     ▼
2. Context::resourceRequirements.maxSlots
     │  CompileTraversal::apply(CommandGraph&) → commandGraph.maxSlots.update(...)
     ▼
3. CommandGraph::maxSlots
     │  CommandGraph::getOrCreateRecordTraversal()
     ▼
4. RecordTraversal::create(maxSlots) / getState()->reserve(maxSlots)
     │  State::reserve
     ▼
5. State::stateStacks.resize(max() + 1)
     │  RecordTraversal::apply(const StateGroup&)
     ▼
6. State::push → stateStacks[slot].push(...) → StateStack::record → vkCmd*

六跳跨了 5 个模块(state/ vk/ app/ io/ nodes/),没有任何一跳做校验。8.4.6 的八跳链是这六跳加上帧期的两跳。

一个具体的时序结论:CommandGraph::record 的第一句是 getOrCreateRecordTraversal(),它会 reserve(maxSlots)。第七章 7.9.4 论证过"即使 assignInstrumentation 提前用 {0,0} 建了 State,record 第一行也会补救"。本章补上另一半:如果 compile() 根本没跑(用户手写 CommandGraph 然后直接 record),maxSlots 停在 {0,0},stateStacks.size() == 1,而 BindGraphicsPipeline 是 slot 0(安全),任何 BindDescriptorSet(slot 1)都会越界写。Viewer::compile() 不是可选步骤,它是 stateStacks(State.cpp:95) 尺寸的唯一来源。

8.8.4 RenderGraph / View 的 view 槽采集

void CollectResourceRequirements::apply(const RenderGraph& rg)
{
    if (rg.viewportState)
        requirements.maxSlots.view = std::max(requirements.maxSlots.view, rg.viewportState->slot);
    rg.traverse(*this);
}

void CollectResourceRequirements::apply(const View& view)
{
    if (view.camera && view.camera->viewportState)
        requirements.maxSlots.view = std::max(requirements.maxSlots.view, view.camera->viewportState->slot);
    ...
}

这两处是 maxSlots.view 的唯一写入点。注意 rg.viewportState 与 view.camera->viewportState 是两个不同的 ViewportState 对象,都会有 slot 8。第七章 7.6 讲过 RenderGraph::accept 里 pushView(viewportState)、apply(const View&) 里 pushView(camera->viewportState)——同 slot 8 会被 push 两次,内层覆盖外层,StateStack(State.h:42) 深度 +2。这也是第七章"16 层嵌套越界"的一个加速项:一个标准的 View + RenderGraph 结构,任何 slot 的基线深度就已经是 1–2 了。


8.9 36 个头文件:状态命令族的完整分类

include/vsg/state/ 下 36 个头文件、3,002 行,可以按"是否产生 vkCmd*"分成四类:

类别代表record 行为
Vulkan 对象封装(不进 StateGroup)Buffer Image ImageView Sampler DescriptorSet DescriptorSetLayout PipelineLayout ShaderModule ShaderStage BufferInfo ImageInfo ArrayState material.h ResourceHints QueryPool BufferView Image.h无 record,只有 compile
状态命令(进 StateGroup)StateCommand BindDescriptorSet GraphicsPipeline ComputePipeline PushConstants StateSwitch ViewDependentState发 vkCmdBind*/vkCmdPushConstants
GraphicsPipelineState 子类VertexInputState InputAssemblyState RasterizationState MultisampleState DepthStencilState ColorBlendState TessellationState DynamicState ViewportState8 个空实现;ViewportState 发 vkCmdSetViewport/SetScissor
描述符具体类型Descriptor DescriptorBuffer DescriptorImage DescriptorTexelBufferView无 record,填充 VkWriteDescriptorSet

分类按主要用途,有重叠:GraphicsPipeline.h 同时含 GraphicsPipelineState、GraphicsPipeline、BindGraphicsPipeline。

三个值得记的事实:

其二,BindGraphicsPipeline::record 按 viewID 取实现。 GraphicsPipeline.cpp:315 附近的 record 会 setCurrentPipelineLayout(...),而 vk(deviceID) / _implementation[viewID] 的多实现机制是第九章的主题。本章只确认一点:CommandBuffer::viewID 是第七章 7.3.1 列的 9 个遍历上下文成员之一,由 apply(const View&) 第 2 步设置。所以"按 viewID 选 pipeline"与"按 slot 选状态命令"是两套并行的分派:前者在 BindGraphicsPipeline::record 内部,后者在 State::push 里。


8.10 GraphicsPipelineConfigurator 怎么生成 stateCommands

8.6.8 引了 copyTo(ref_ptr<StateGroup>),这里看它填入的具体内容。

// src/vsg/utils/GraphicsPipelineConfigurator.cpp:820–848(节选)
bool GraphicsPipelineConfigurator::copyTo(StateCommands& stateCommands,
                                          ref_ptr<SharedObjects> sharedObjects)
{
    bool stateAssigned = false;

    bool pipelineUnique = true;
    for (const auto& sc : inheritedState)
        if (compare_pointer(sc, bindGraphicsPipeline) == 0) pipelineUnique = false;

    if (pipelineUnique)
    {
        if (sharedObjects)
        {
            std::scoped_lock<std::recursive_mutex> lock(sharedObjects->mutex);
            sharedObjects->share(layout->setLayouts);
            sharedObjects->share(layout);
            graphicsPipeline->layout = layout;
            sharedObjects->share(graphicsPipeline);
            sharedObjects->share(bindGraphicsPipeline);
        }
        stateCommands.push_back(bindGraphicsPipeline);      // slot 0
        stateAssigned = true;
    }
    if (descriptorConfigurator) { /* 生成 BindDescriptorSet(s),slot 1+firstSet */ }
    ...
}

三个设计点:

inheritedState 去重。 配置器维护一个 StateCommands inheritedState(来自父 StateGroup),只有 bindGraphicsPipeline 不在其中时才 push。这是"嵌套 StateGroup 不重复绑同一个 pipeline"的优化——但注意它用的是 compare_pointer(...)(8.3.6 讲过这是深比较),对大型 GraphicsPipeline 会一路比到 ShaderStage 的 SPIR-V 数据。每次 copyTo 都要对 inheritedState 里每个元素做一次这个比较。

DisableInheritedState 是一个局部 Visitor。 copyTo 里定义了一个内嵌类,任务是遍历 inheritedState,把已经被父级绑定过的 set 编号从 descriptorConfigurator->descriptorSets 里 reset() 掉:

void apply(BindViewDescriptorSets& bvds) override
{ if (bvds.firstSet < descritorSets.size()) descritorSets[bvds.firstSet].reset(); }
void apply(BindDescriptorSet& bds) override
{ if (bds.firstSet < descritorSets.size()) descritorSets[bds.firstSet].reset(); }
void apply(BindDescriptorSets& bds) override { /* 按范围逐个 reset */ }

sharedObjects->share(...) 的锁。 配置器加 std::scoped_lock<std::recursive_mutex> 一次锁住 4 次 share(recursive_mutex 是必要的,share(graphicsPipeline) 内部会再 share 子对象)。代价是建图期串行——多线程 copyTo 会排队。这是本章唯一一处与状态相关的显式同步,对比第七章 ExecuteCommands 的 latch 是录制期同步。


8.11 缺陷清单与数字表

#结论定位严重度
1StateSwitch::record 绕过状态栈,子命令状态在 pop 后不恢复StateSwitch.cpp:58–67高(静默画错)
2StateSwitch 默认 slot 0,与 BindGraphicsPipeline 同槽,pipeline 绑定被吞StateSwitch.h:24、GraphicsPipeline.cpp:280高
3cloneArrayState(ref_ptr<ArrayState>) 六处全部丢弃子类配置ArrayState.cpp:228/268/323/386/493/570高(包围体错)
4DisplacementMapArrayState 同类拷贝构造也切片,无参 clone 同样丢配置ArrayState.cpp:371–378中
5Bin::traverse 的 modelviewMatrixStack 只 push 不 popBin.cpp:137–141中(矩阵污染)
6Bin 排序键 double → float 后存进 KeyIndex,std::sort 不稳定导致远处透明面闪烁Bin.cpp:104、Bin.h:69中
7slot 2 三方冲突(PushConstants / BindViewDescriptorSets / firstSet=1)PushConstants.cpp:19、ViewDependentState.cpp:106、BindDescriptorSet.h:98中(用户 API 陷阱)
8编译后改 slot → stateStacks[slot] 越界写,无检查State.h:372中
9StateSwitch::compare 不调基类,slot 不参与比较StateSwitch.cpp:34低
10StateGroup 拷贝构造的 prototypeArrayState 不走 copyopStateGroup.cpp:27低(深拷贝共享)
11push/pop 无异常保护,异常路径触发第七章的 16 层越界链RecordTraversal.cpp:524–528低(罕见)
12DisplacementMapArrayState::vertexArray 三处不判空ArrayState.cpp:~440低(特定数据)
13两类 in-tree 零调用,仅 ObjectFactory 注册ObjectFactory.cpp:252/254元事实
度量值
本章核心文件87 个 / 13,387 行
决定成败的有效代码约 394 行 / 8 个文件
state/ 目录36 个 .h(3,002 行)+ 35 个 .cpp(7,076 行)
StateCommand 直接派生类9
GraphicsPipelineState 子类9(8 个 record 为空)
slot 显式赋值点5 个语义位置
prototypeArrayState 赋值点4
StateSwitch 掩码语义 / setCurrentPipelineLayout 调用点3 套 / 3 处

8.12 源码索引

文件关键行号对应结论
state/StateCommand.h26–43slot 字段与 StateCommands 别名
state/StateCommand.cpp24–45slot 的 read/write
state/ViewportState.cpp19–22构造后 slot = 8
state/PushConstants.cpp18–25Inherit(2) // slot 0 的矛盾注释
state/ViewDependentState.cpp104–108 / 148–154Inherit(2) 与 BindViewDescriptorSets::record
state/BindDescriptorSet.h30–31 / 97–98 / 116–117slot = 1 + firstSet 的三个构造
state/GraphicsPipeline.h28–40GraphicsPipelineState 的空 record
nodes/StateGroup.h66–78三个 traverse 重载
nodes/StateGroup.cpp24–43拷贝构造共享原型、compare 顺序
app/RecordTraversal.cpp311–323 / 515–529 / 701–704double 距离、push/traverse/pop、addToBin
vk/State.h30–85 / 348–407StateStack、State::record、push/pop
vk/State.cpp25–112reserve/reset/connect/inherit/pushView
vk/Slots.h20–45update / max
state/StateSwitch.h41–48t_traverse 的掩码表达式
state/StateSwitch.cpp32–67compare 漏基类、compile、record
state/ArrayState.h33–43两个 cloneArrayState 重载
state/ArrayState.cpp37–48 / 63–84 / 152–178 / 258–260 / 371–378 / 432–460基类 8 项、属性查找、判空不一致、切片构造、三处不判空
utils/ComputeBounds.cpp37–62arrayStateStack 与 stateCommands 双遍历
nodes/Bin.cpp60–172状态快照、float 排序键、矩阵栈不配对
vk/ResourceRequirements.cpp69 / 100–117 / 159–163 / 237–248hints 闭环、采 slot、采 view 槽
utils/GraphicsPipelineConfigurator.cpp820–905 / 992–1013copyTo(StateCommands&)、getSuitableArrayState
io/ObjectFactory.cpp252 / 254PushConstants / StateSwitch 的唯一出现处
GraphicsPipeline.cpp / ComputePipeline.cpp / RayTracingPipeline.cpp315 / 161 / 257setCurrentPipelineLayout 的三个调用点

8.13 可复现验证

验证 1:slot 赋值点与 in-tree 零调用。

grep -rn "Inherit([0-9]\|slot = [0-9]" include/vsg/state/ src/vsg/state/ \
  | grep -v "maxSlots\|stateStacks\|slots"

期望 5 类:Inherit(1)、Inherit(1 + in_firstSet)、PushConstants.cpp 的 Inherit(2)、ViewDependentState.cpp 的 Inherit(2)、ViewportState.cpp 的 slot = 8。其中 PushConstants.cpp 的 // slot 0 与代码 Inherit(2) 并存,是最容易自查的一条。再跑 grep -rn "StateSwitch::create\|PushConstants::create" --include=*.cpp src/,期望无输出;只有 ObjectFactory.cpp:252/254 的两行注册。

验证 2:StateSwitch 的子命令不进状态栈。

验证 3:cloneArrayState(ArrayState.cpp:570)(ArrayState.cpp:493)(ArrayState.cpp:386)(ArrayState.cpp:323)(ArrayState.cpp:318) 丢配置(纯 CPU,无需设备)。

auto proto = vsg::TranslationArrayState::create();
proto->translation_attribute_location = 3;
auto cloned = proto->cloneArrayState(vsg::ArrayState::create());
auto* t = cloned.cast<vsg::TranslationArrayState>();
// t->translation_attribute_location:期望 3,实际 7

再加一条:proto->cloneArrayState()(无参)后 dm_binding 是否回到 7(DisplacementMapArrayState)。

验证 4:Bin 矩阵栈不配对。

在 Bin::traverse 前后各打印一次 state->modelviewMatrixStack.size(),跑 2 个 bin、每 bin 若干不同 MatrixTransform 的场景。期望:进入时深度 1、退出时 > 1、第二个 bin 进入时 > 第一个 bin 进入时;跨帧开始时回到 1(setProjectionAndViewMatrix 的 set 清空)。

验证 5:编译后改 slot 的越界。

验证 6:六个 cloneArrayState(ref_ptr<ArrayState>) 逐字同构。

grep -n "cloneArrayState(ref_ptr<ArrayState>" src/vsg/state/ArrayState.cpp

期望恰好 6 行(228/268/323/386/493/570),每行的函数体都是 XxxArrayState::create(*arrayState),忽略传入对象的子类字段。这直接证明 8.6.3 的"类型来自原型、状态来自父栈"实现反了。

验证 7:STATESTACK_SIZE 只在头文件定义一次。

grep -rn "STATESTACK_SIZE" include/vsg/vk/State.h src/vsg/

期望只有 2 处(定义 :28 与 Stack 别名 :38),没有运行时可配置的入口。因此同槽嵌套 16 层越界是硬编码上界,无法通过 API 抬高。

验证 8:maxSlots.view 只有两个写入点。

grep -n "maxSlots.view" src/vsg/vk/ResourceRequirements.cpp

期望 2 行(239/247),分别对应 RenderGraph::viewportState 与 View::camera->viewportState。这证明 8.4.3 里 max() 的 view 分量来源唯一,slot 8 的二分采集没有第三条路径。

验证 9:setCurrentPipelineLayout 只有 slot 0 命令会调。

grep -rn "setCurrentPipelineLayout" src/vsg/state/

期望命中 GraphicsPipeline.cpp:315(graphics)与 ComputePipeline.cpp:161(compute)两处 record。两者都是 slot 0 的 Bind*Pipeline,因此 StateSwitch 吞掉 slot 0 后 _currentPipelineLayout 永不设置——8.5.3 的结论不依赖画面即可确认。

验证 10:只有少数节点重写 traverse(RecordTraversal&)。

grep -rn "traverse(RecordTraversal" include/vsg/ | grep -v thirdparty

期望 StateGroup 与 Bin 是其中语义被真正改变的两个(前者跳过 stateCommands,后者排序回放),其余多为 t_traverse 转发或空实现。这支撑 8.3.2"两棵树形状不同"与 8.7 的结论。

验证 11:prototypeArrayState 的文本布局赋值只有两处。

grep -rn "prototypeArrayState" src/vsg/text/

期望 CpuLayoutTechnique.cpp:362 与 GpuLayoutTechnique.cpp:337,两者都把 create(this, ...) 的对象裸指针存进原型——正是 8.3.5 悬垂风险的来源。


8.14 陷阱表

陷阱触发条件后果源码坐标规避
把一个 VertexInputState 子类误放进 StateGroup::stateCommands类型系统允许(它是 StateCommand),record 为空静默吞掉真正的 BindGraphicsPipeline,画面空白include/vsg/state/GraphicsPipeline.h:39只把产生 vkCmd* 的命令放进 stateCommands
用 StateSwitch 按 View 切换 descriptor set放进 StateGroup 的 stateCommandspipeline 被 slot 0 吞、descriptor 状态在 pop 后泄漏src/vsg/state/StateSwitch.cpp:64改成多个 StateGroup + Switch/Layer(8.5.7 修法 C)
同一 StateGroup 里放 PushConstants 和 BindDescriptorSet(firstSet=1)两者 slot 都是 2后 push 者覆盖前者,前者不发 vkCmd*src/vsg/state/PushConstants.cpp:19编译前手工把其中一个 slot 改到空闲编号
给 prototypeArrayState 子类设自定义 attribute locationComputeBounds 调带参 cloneArrayState子类配置被重置成类内默认值src/vsg/state/ArrayState.cpp:268改 cloneArrayState,或直接给 ComputeBounds 传 initialArrayState
编译后运行时改 sc->slotslot 是 public 非 conststateStacks[slot] 越界写include/vsg/vk/State.h:62所有 slot 在 Viewer::compile() 之前确定
只注册 bin 5、图里用默认 binNumber=0 的 DepthSortedbins[0] 是空 ref_ptraddToBin 解引用空指针崩溃src/vsg/app/RecordTraversal.cpp:703注册 bin 0,或把所有 DepthSorted 的 binNumber 设成 5
用 ComputeBounds 处理位移贴图几何texcoords/normals/vertices 不判空vertexArray() 空指针解引用src/vsg/state/ArrayState.cpp:443保证 VertexInputState location 与 ArrayState 字段完全对应
手写 CommandGraph 后直接 record()没跑 Viewer::compile(),maxSlots={0,0}slot 1 的命令越界src/vsg/vk/State.cpp:25必须走 Viewer::compile() 或手工填 CommandGraph::maxSlots
给 BindDescriptorSet 传很大的 firstSetslot = 1 + firstSet 无上限检查造出成千上万个空栈,每帧空转src/vsg/vk/ResourceRequirements.cpp:161校验 firstSet < VkPipelineLayoutCreateInfo::setLayoutCount
同一 StateGroup 混用批量与单个 BindDescriptorSet两者 slot=1+firstSet,绑定顺序由 vector 决定后录的覆盖先录的,顺序反直觉include/vsg/state/BindDescriptorSet.h:31显式排序 stateCommands,或只保留一种形式
改 bds->firstSet 却不同步 bds->slot两个字段各自可变双份真相,反序列化后可能不一致include/vsg/state/BindDescriptorSet.h:51把 slot 设为私有并提供 setter 同步二者
把两个 children 相同、slot 不同的 StateSwitch 交给 SharedObjectsStateSwitch::compare 漏了基类调用slot 不参与比较,被误判为同一对象共享src/vsg/state/StateSwitch.cpp:34改写 compare 调用 StateCommand::compare
深拷贝含 prototypeArrayState 的 StateGroup原型直接复制 ref_ptr 不走 copyop克隆图共享原型,原图销毁后悬垂src/vsg/nodes/StateGroup.cpp:27对原型也走 copyop(...)
给 DisplacementMapArrayState 做无参 cloneArrayState()DisplacementMapArrayState(const ArrayState&) 对象切片子类字段全部重置src/vsg/state/ArrayState.cpp:376同类拷贝构造显式复制子类字段
依赖 push/pop 之间不抛异常RecordTraversal 无 try/catchpos 永久偏高,累积到 16 越界src/vsg/app/RecordTraversal.cpp:524用 RAII StateScope 包裹(8.3.4)
场景里多个 bin 或单 bin 多矩阵Bin::traverse 只 push modelviewMatrixStack 不 pop矩阵栈逐层长高、top() 被污染src/vsg/nodes/Bin.cpp:139依赖每帧 set() 清空,勿在 bin 后放依赖外层矩阵的几何
大地形透明物体排序排序键 double → float 且 std::sort 不稳定相距很近的透明面键相同、顺序随机闪烁include/vsg/nodes/Bin.h:69把 KeyIndex::first 改成 double
用 ConstVisitor 遍历 StateGroupt_traverse 会遍历 stateCommandsComputeBounds 等把状态命令遍历两遍、无效果虚调用src/vsg/utils/ComputeBounds.cpp:50自定义访问者按需要跳过 stateCommands
用非 VK_FORMAT_R32G32B32_SFLOAT 的顶点位置格式ArrayState::apply(Data&) 只支持这一种格式vertices 被置空,vertexArray() 解引用崩src/vsg/state/ArrayState.cpp:434用 vec3Array 或统一成 R32G32B32_SFLOAT
希望 ViewportState 的 slot 8 恒被采集挂到 Node 而非 View/RenderGraph被采进 state 而非 view 分量src/vsg/vk/ResourceRequirements.cpp:247把视口状态挂在 camera->viewportState 上
StateSwitch 的子命令里放 BindGraphicsPipeline子命令 record 会调 setCurrentPipelineLayout触发 dirtyStateStacks(),掩盖 descriptor 泄漏src/vsg/state/GraphicsPipeline.cpp:315不要把 pipeline 绑定放进 StateSwitch 子命令
依赖 State::dirty 在 pushView 后被置位pushView(ref_ptr<StateCommand>) 不置 dirty空 View 里 dirty 留到下一帧src/vsg/vk/State.cpp:53依赖 apply(View) 第 1 步的 dirtyStateStacks()

8.15 结论

  1. slot 是一个 32 位整数协议,没有类型、没有枚举、没有文档、没有边界检查。 五处赋值点定义了四类语义,slot 2 被三个不相关的类占用,slot 与 firstSet 是双份真相。所有 slot 必须在 Viewer::compile() 前冻结。

  2. StateGroup 的三个 traverse 重载让同一张图在编译期与录制期呈现不同形状。 录制期跳过 stateCommands 是状态继承语义成立的前提,但任何 ConstVisitor 都会自动吃到这些状态命令,ComputeBounds 甚至把它们遍历两遍。

  3. StateSwitch 是本章最严重的缺陷。 它的子命令绕过 StateStack,不进槽、不参与记忆、pop 后不恢复;它自己默认 slot 0 又会吞掉 BindGraphicsPipeline,导致 _currentPipelineLayout 永不设置、vkCmdPushConstants 全不发。三套掩码语义、compare 漏掉基类、in-tree 零调用——一个从未被测试过的公开 API。

  4. ArrayState 的原型克隆把"类型来自原型、状态来自父栈"实现成了"类型和状态都来自父栈"。 六个 cloneArrayState(ref_ptr<ArrayState>) 全部丢弃子类配置;DisplacementMapArrayState 连同类拷贝都对象切片。所有可配置的 attribute location 字段在 StateGroup 用法下失效。

  5. Bin 同时做对了状态快照和做错了矩阵栈。 状态栈的 push/pop 完整配对,成功把 popView 之后的 viewport 状态恢复回来(这一条更正了第七章);modelviewMatrixStack 却只 push 不 pop,多 bin 场景逐层长高。排序键从 double 压成 float,把第四章建立的大地形精度在最后一步丢掉。

  6. maxSlots 的六跳传播链是整层的生命线。 ResourceHints(下界)→ 采集器 → Context → CommandGraph → RecordTraversal → State::reserve → stateStacks。全是单向 max/update,只增不减;任何一跳缺席都会让 stateStacks 尺寸不足。

  7. 所有权的三处裸指针(StateStack::stack、Bin::_stateCommands、CommandBuffer::state)都靠"同一帧内同步使用"的时序保证,没有任何引用持有。

整体评价:命令层是"薄封装 + 强约定",状态层是"一个整数 + 四条不成文协议"——只经 StateStack::record 写入、push/pop 严格配对、同槽嵌套 < 16、compile 前冻结 slot。本章为每条找到一个可定位破口,全库无一条运行时检查。正确性唯一来自 Viewer::compile() + GraphicsPipelineConfigurator 生成的标准图;一旦手写结构偏离,错误几乎都是静默画错。


8.16 批判性结论

8.16.1 一个整数撑起的类型系统

把状态身份压成一个 uint32_t,是状态层所有便利与缺陷的共同源头。构造函数只在初始化列表写 slot(in_slot)(include/vsg/state/StateCommand.h:26),拷贝再复制一次(src/vsg/state/StateCommand.cpp:20),判等靠 compare_value(slot, rhs.slot)(src/vsg/state/StateCommand.cpp:37)。它从不被升级成枚举:既能是 BindDescriptorSet 的 1 + firstSet 算术结果(include/vsg/state/BindDescriptorSet.h:51),也能被 ViewportState 直接赋成 8。扩展性是真的——用户不改头文件就能发明槽位——但构建期本可拦截的错误全被推到无检查的运行期。

容器侧 StateCommands 用带 allocator_affinity_nodes 的 vector(include/vsg/state/StateCommand.h:43),保证元素类型统一,这是类型系统唯一真正起作用的地方;分派侧却退化成 stateStacks[slot] 裸下标——入口强类型,出口裸下标。firstSet 与 dynamicOffsets 是两个独立可变字段(include/vsg/state/BindDescriptorSet.h:58),改前者不会同步后者,是典型的双份真相。

Slots 用 max() 取 state 与 view 较大值(include/vsg/vk/Slots.h:27),用 update() 单调合并(include/vsg/vk/Slots.h:33),用 requiresUpdate() 判断是否需要更新(include/vsg/vk/Slots.h:40)——只是在两个整数上再包一层整数,没有引入任何类型约束。update() 只增不减,副作用是场景删减后 maxSlots 永远过时。全部算法问题归结为"只增不减"与"无界访问"两条。

8.16.2 静默失败:错误模型的四种形态

本章反复出现"静默"。散落各节的失败可归为四种,成因相同——写入方绕过唯一授权检查点——表现不同。

覆盖型:多个语义无关的 StateCommand 落在同一槽,StateStack::record 只录栈顶,前一个对象整周期不发命令;StateSwitch 以 Child 容器管理子命令(include/vsg/state/StateSwitch.h:35),默认槽却与 BindGraphicsPipeline 同为 0。绕过型:StateSwitch::record 用 commandBuffer.traversalMask 筛选分支后直接调子命令 record(src/vsg/state/StateSwitch.cpp:62),stateCommand 被直接执行(src/vsg/state/StateSwitch.cpp:48),既不 push 也不更新记忆槽。切片型:DisplacementMapArrayState 的 normalAttribute 依赖的配置在从基类引用构造的拷贝里丢失(src/vsg/state/ArrayState.cpp:443 的读取路径即依赖它)。泄漏型:Bin::traverse 把 previousMatrixIndex 初值设成 _matrices.size()(src/vsg/nodes/Bin.cpp:127),保证第一个元素必定压栈,循环内再无配对弹出。

四种共用诊断特征:Vulkan 验证层不报错——它们产生的是合法命令序列,只是内容不对。StateGroup 的录制重载只遍历 children(include/vsg/nodes/StateGroup.h:75),把 stateCommands 完全交给栈分派;一旦分派被绕过,没有组件持有"应有状态"的副本。prototypeArrayState 在 compare_pointer 里按地址比较(src/vsg/nodes/StateGroup.cpp:42),连判等都发现不了语义差异。静默不是偶然,是架构没留自检接口。

8.16.3 所有权:三处裸指针的共性与差异

状态层有三处裸指针,生命周期都靠"同帧同步使用"维系,失效后果差异很大。StateStack::stack 是容量硬编码为 16 的 std::array<const T*, STATESTACK_SIZE>(include/vsg/vk/State.h:38);Bin::_stateCommands 是 std::vector<const StateCommand*>(include/vsg/nodes/Bin.h:57),由 Bin::add 以 stateStack.top() 逐个填入(src/vsg/nodes/Bin.cpp:97);第三处是 CommandBuffer::state。三者都不持引用计数,都假设写入与消费之间对象不被销毁。

差异有三:其一容量风险,定长数组写越界踩相邻成员,动态数组只会读到失效指针;其二后果,矩阵栈的 stack[16] 正好覆盖 pos,越界写破坏栈深本身;其三恢复,State::connect 换命令缓冲时调 dirtyStateStacks()(src/vsg/vk/State.cpp:46)软重置,Bin 每帧由 clear() 清空。

StateStack() = default 让 stack 未初始化,reset() 只把 stack[0] 置空(include/vsg/vk/State.h:51),其余 15 槽保持不确定值——实践中不崩只因 record() 在 pos=0 时读的恰是被清零的槽 0,正确性是巧合。required_size 按 activeMaxStateSlot + 1 算(src/vsg/vk/State.cpp:31),扩容的新栈同样没 reset()。把"未初始化内存恰好安全"当不变量,是这里最值得警惕的。

8.16.4 记忆槽:一个未被写进文档的性能契约

StateStack::record 的核心是 const T* current = stack[pos],只有 current != stack[0] 才调 current->record() 并更新 stack[0](include/vsg/vk/State.h:76)。stack[0] 因而不是普通槽位,而是"上次真正写入命令缓冲的对象"的记忆。push 写到 stack[++pos](include/vsg/vk/State.h:62),pop 只做 --pos(include/vsg/vk/State.h:67),都不碰记忆槽——这正是 pop 后能重录旧栈顶的原因。

契约可精确表述:栈 0 记"命令缓冲当前生效对象",栈顶记"场景图此刻期望对象",相等则不发命令。正确性依赖更强约束——所有写命令缓冲的路径都必须更新栈 0;StateSwitch::record 是唯一违反者。State::dirty 是全局布尔,push 与 pop 都置位(include/vsg/vk/State.h:57),一次置位触发全槽扫描;activeMaxStateSlot 在 reserve() 与 reset() 里被设成 maxSlots.max()(src/vsg/vk/State.cpp:43),在 record() 末尾回落到 maxSlots.state——这是跨函数握手,只看 push 会完全漏掉。

记忆槽把"减少 vkCmd* 调用"的性能优化变成正确性的承重墙。slots 只增不减,配合全槽扫描,意味着用过 firstSet=1000 的图即使删掉那条命令,每帧仍扫过一千多个空槽。性能契约与正确性契约纠缠在同一数组里,是这段设计最难维护的部分。

8.16.5 采集期与录制期:一棵树的两套真相

CollectResourceRequirements::apply(const StateCommand&) 只有两行:比较并更新 requirements.maxSlots.state,再调 stateCommand.traverse(*this)(src/vsg/vk/ResourceRequirements.cpp:161、src/vsg/vk/ResourceRequirements.cpp:162)。意图是"采集槽位 + 下钻子对象",把 StateSwitch 的所有子命令纳入视野;录制期则依据 commandBuffer.traversalMask 只选一个分支。同一子树,采集器眼里全分支,录制器眼里单分支。

这不是 bug,是采集必须保守:若按录制掩码裁剪,未启用分支一旦切入就会用到未编译管线。代价是 maxSlots 虚高——createResourceHints 把 requirements.maxSlots 原样写回(src/vsg/vk/ResourceRequirements.cpp:104),虚高值被下一批瓦片继承。ResourceHints 的 apply 把 minimumBufferSize 与提示值做 std::max(src/vsg/vk/ResourceRequirements.cpp:81),containsPagedLOD 只置真不置假(src/vsg/vk/ResourceRequirements.cpp:152)——整个采集系统环绕"只增不减"设计。

view 维度更不对称:RenderGraph 的 viewportState 与 View 的 camera->viewportState 分别写 maxSlots.view(src/vsg/vk/ResourceRequirements.cpp:239、src/vsg/vk/ResourceRequirements.cpp:247),是两个不同对象却都占槽 8。采集当 view 类资源单独记账,录制当同一槽嵌套覆盖——两套真相各有道理,接缝却没有注释。读者必须同时跑"采集全遍历"和"录制单分派"两个模型。

8.16.6 原型模式:类型来自哪里,数据来自哪里

prototypeArrayState 的意图:进入 StateGroup 子树时,顶点数组解释方式换成原型指定的子类,数组内容、矩阵栈、拓扑继承父栈。ArrayState 提供两个 cloneArrayState 重载(include/vsg/state/ArrayState.h:40),无参克隆自己,带参克隆传入的父栈对象——虚分派在原型上决定"造出哪个类",参数决定"填进什么数据",是干净的原型构想。

实现却把构想削平。六个派生类的带参版都写成 XxxArrayState::create(*arrayState):TranslationArrayState 如此(src/vsg/state/ArrayState.cpp:268),因 arrayState 静态类型是基类 ArrayState&,匹配到从基类引用构造的拷贝构造,子类字段一个都不复制。它明明有 translationAttribute 需保留(src/vsg/state/ArrayState.cpp:253),带参克隆后却回到默认值 7;getAttributeDetails 仍用默认 location 查 VertexInputState(src/vsg/state/ArrayState.cpp:432、src/vsg/state/ArrayState.cpp:434),查不到返回全零描述,最终 displacementMap 指向错误 binding。

分布不均匀:TranslationArrayState 与 BillboardArrayState 的同类拷贝显式复制子类字段,无参克隆正确;DisplacementMapArrayState 两个拷构造都是空 Inherit(rhs)(src/vsg/state/ArrayState.cpp:376),连同类克隆都切片,比"全都错"更难排查。applyArrays 的 BufferInfoList 版逐元素取 in_arrays[i]->data 不判空(src/vsg/state/ArrayState.cpp:157),DataList 版用 std::copy(src/vsg/state/ArrayState.cpp:170),安全级别取决于传哪种重载。设计正确、逐类实现偷懒、没有测试覆盖偷懒的类。

8.16.7 排序容器:一个机制里同时做对和做错

Bin 是全章最富戏剧性的类:同一文件里一个机制完整实现,另一个有明显疏漏。Bin::add 先把所有非空状态栈栈顶快照进 _stateCommands(src/vsg/nodes/Bin.cpp:93),再把元素连同排序键存入 _binElements(include/vsg/nodes/Bin.h:70)。这使 Bin::traverse 能在 popView 之后把视口状态压回——第七章"viewport 会丢"因此被更正:没丢,是被快照保存了,是状态快照/回滚机制的一次正确落地。

矩阵栈却是另一回事。Bin::traverse 在矩阵变化时 state->modelviewMatrixStack.push(_matrices[element.matrixIndex])(src/vsg/nodes/Bin.cpp:139),循环结束只调 popFrustum()(src/vsg/nodes/Bin.cpp:166),没有任何矩阵 pop;状态命令的 push/pop 在同一循环体里成对出现(src/vsg/nodes/Bin.cpp:154),矩阵栈却只进不出。单元素内部正确,元素之间第二个的 applyFrustum 读到前一个遗留的栈顶。

排序键是第三处缺陷。apply(const DepthSorted&) 用 double 全程算 distance(src/vsg/app/RecordTraversal.cpp:319),addToBin 以 minimumBinNumber 定位容器(src/vsg/app/RecordTraversal.cpp:703),但 Bin::add 把 distance 截成 float 存进 KeyIndex;std::sort 对相等键不稳定,远处两个深度相近的透明面顺序随机。binNumber 与 view.bins 又是双份真相(include/vsg/nodes/Bin.h:37),未注册编号留空 ref_ptr,addToBin 解引用即崩。172 行的类里四件事三件有问题,且都集中在"排序"这一与状态管理无关的职能上——把 Bin 拆成"快照回放"与"排序容器",或能解释为何前者正确而后者频繁出错。

8.16.8 缺陷为何存活:零调用与测试盲区

StateSwitch 与 PushConstants 在 in-tree 中除 ObjectFactory 注册外没有任何创建点。StateSwitch 的 clone 与 compare 声明都在头文件(include/vsg/state/StateSwitch.h:53),基础设施齐全,却没有 src/ 文件实例化它;PushConstants 的 record 实现存在(src/vsg/state/PushConstants.cpp:53),从未被内部路径调用。两个最严重缺陷恰好落在两个零调用的类上,不是巧合——从未被示例、Builder、加载器走过的类,不可能有回归测试覆盖,PushConstants 构造函数里 Inherit(2) // slot 0 这种代码与注释矛盾的地方也无人修正。

另外两处藏在"默认路径安全、特定数据才触发"的盲区。DisplacementMapArrayState 切片只在用户启用位移贴图且用 prototypeArrayState 时暴露;Bin 矩阵栈泄漏只在单帧多 bin 时累积,而每帧 set() 又清零,掩盖了跨帧后果。ComputeBounds::apply(const StateGroup&) 显式遍历 stateCommands(src/vsg/utils/ComputeBounds.cpp:50),让 NullArrayState 扩展点正常工作,却让不相关的 ConstVisitor 承担空转开销——正确性没问题,性能没人量。存活机制归纳为:公开 API 缺少用户、默认配置绕开缺陷、后果是静默画错而非崩溃。

BindComputePipeline 的 record 在 compute 路径按 deviceID 取管线(src/vsg/state/ComputePipeline.cpp:158),与 graphics 按 viewID 形成对照,两者都只在 slot 0 生效。这类"能工作但仅覆盖主路径"的实现遍布状态层。批判若只停在"这些是 bug",会错失更重要的判断:这是把正确性托付给使用约定的系统,约定既无文档也无断言,唯一守门人是 Viewer::compile() 生成的标准图。

8.16.9 修复代价的分级

按修复代价分级,能判断哪些值得动。最便宜一级是"加一行边界检查":STATESTACK_SIZE 是编译期常量(include/vsg/vk/State.h:28),同槽嵌套 16 层越界可在 push 里加检查变成可诊断失败;pushView / popView 成对改写 activeMaxStateSlot(src/vsg/vk/State.cpp:59、src/vsg/vk/State.cpp:65),加断言不需改调用方。修改局部、无兼容负担,唯一障碍是没人愿意第一个动。

中间一级是"补齐拷贝语义":给六个 cloneArrayState 派生实现补子类字段复制,或改成先无参克隆保留配置再覆盖基类字段;applyArrays 的空 ref_ptr 判空(src/vsg/state/ArrayState.cpp:152)加一次判断即可。不改公开接口,但会改变深拷贝与序列化结果,需回归测试配合。

最贵一级是结构性重构:StateSwitch 无法用一行补丁解决,它把 record 当分派器用,而 record 拿不到 State*,无法把子命令压回栈;强行调 commandBuffer.state->push(child) 会在 State::record() 遍历栈时修改正在被遍历的容器,引入新时序问题。只能改继承结构——把 StateSwitch 从 StateCommand 改成 Group,或建图期展开成多个 StateGroup。

修复顺序该按"触发概率 × 后果"排。Bin 的 KeyIndex 从 float 改 double(include/vsg/nodes/Bin.h:69)成本极低收益明确,应最先做;StateSwitch 重构成本最高触发最少,可靠文档警告过渡。所有廉价修复指向同一主题——把不成文约定变成运行时可诊断失败。状态层缺的不是聪明设计,而是三行 if:槽位越界检查、栈深检查、子命令判空。

8.16.10 三条可被源码直接验证的硬结论

本节落到三条以文件行号直接复核、不依赖画面与驱动的硬结论。

硬结论一:StateSwitch::record 绕过状态栈,破坏记忆槽不变量。 它在 src/vsg/state/StateSwitch.cpp:62 用 commandBuffer.traversalMask 与 overrideMask 算分支,命中子命令被直接录制,全程没有 State::push、没有更新 stack[0]、没有 pop。结合 StateStack::record 在 include/vsg/vk/State.h:76 的"current != stack[0] 才录"逻辑:被子命令修改而外层 StateGroup 未覆盖的槽,pop 后既不恢复也不重录——覆盖型与绕过型叠加,全章最严重。

硬结论二:Bin::traverse 的 modelviewMatrixStack 只 push 不 pop。 压栈在 src/vsg/nodes/Bin.cpp:139,其后 applyFrustum() 依赖这个栈顶;循环体与函数末尾有 state->pop(begin, end) 与 popFrustum(),却找不到任何 modelviewMatrixStack.pop()。单帧多 bin 或多矩阵让该栈单调增长,top() 被前一个元素污染,正确性只在每帧 set() 清空时恢复。

硬结论三:cloneArrayState(ref_ptr<ArrayState>) 的系统性切片。 src/vsg/state/ArrayState.cpp:268 的 TranslationArrayState 带参克隆把基类引用解引用后传给 create(*arrayState),因 arrayState 静态类型是 ArrayState&,构造时不复制 translationAttribute;同形态还在同文件 318、386、493、570 行。displacementMap 的读取路径在 src/vsg/state/ArrayState.cpp:441 依赖这些字段,用户配置被静默丢弃——六个实现逐字同构,修复必须六处同改。

三条各对应 8.5、8.7、8.6 的核心论断,共同点是证据都在十行窗口内,不需运行程序。这也解释了本章为何强调"可读性即可验证"——在一个自觉遵守不成文约定的系统里,代码审查是唯一可行的质量保证,前提是坐标级可定位性。


8.17 下章预告

状态图结束。下一个问题:被压进 slot 0 的 BindGraphicsPipeline,里面的 VkPipeline 是怎么来的?

第九章 管线对象:GraphicsPipeline / ComputePipeline / PipelineLayout 要回答:

  • GraphicsPipeline::_implementation 是一个 vector,索引为什么是 viewID 而不是 deviceID?第七章讲过 VSG_MAX_DEVICES = 1,那多实现的理由是什么?
  • GraphicsPipeline::compile(Context&) 里 VkGraphicsPipelineCreateInfo 的 renderPass 从哪来?为什么一个 GraphicsPipeline 不能跨 RenderPass 复用?
  • 九个 GraphicsPipelineState 的 record 全是空的,那它们的 compile 做了什么?pNext 链的顺序由谁决定?
  • PipelineLayout::compile 里 pushConstantRanges 与 _currentPushConstantStageFlags 的关系:为什么 MatrixStack::record 只读 front().stageFlags?

以及本章留下的一个悬念:

  • StateSwitch 如果要重构,序列化格式怎么迁移(.vsgb 里存着 slot 与 children)?