《OGRE 3D 渲染引擎原理与架构》6.3 影响器

影响器在每个活跃粒子上逐帧施加效果:ParticleAffector 定义纯虚 _affectParticles,具体子类如 ColourFaderAffector 做每秒颜色增量加饱和、ScaleAffector 做尺寸缩放夹取、DirectionRandomiserAffector 按 scope 加方向噪声。lab 复现三种语义。

6.3 影响器

发射器把粒子「生」出来,接下来就是影响器的事:在粒子整个生命周期里,逐帧改变它的颜色、尺寸、方向、加速度。OGRE 把这类对象统一抽象成 ParticleAffector,它与发射器共用同一套插件注册体系——ParticleSystemManager::addAffectorFactory 注册类型,粒子脚本里按名引用。这一节讲抽象接口与三个自带实现。

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

helio 四卷没有粒子影响器抽象;cg 三卷讲过颜色插值公式。这里解析真实 OGRE 的 ParticleAffector 纯虚接口,以及 ParticleFX 插件里三个最小实现:颜色渐变、尺寸缩放、方向随机化。

ParticleAffector:一个纯虚函数

ParticleAffector 的核心只有一个纯虚方法。派生类只要实现它,就能被系统在每帧调用:

// OgreMain/include/OgreParticleAffector.h:ParticleAffector 类(v14.6.3 源码摘录,已删减)
    class _OgreExport ParticleAffector : public StringInterface, public FXAlloc
    {
    protected:
        /// Name of the type of affector, MUST be initialised by subclasses
        String mType;

        /** Internal method for setting up the basic parameter definitions for a subclass.

            Because StringInterface holds a dictionary of parameters per class, subclasses need to
            call this to ask the base class to add it's parameters to their dictionary as well.
            Can't do this in the constructor because that runs in a non-virtual context.
        @par
            The subclass must have called it's own createParamDictionary before calling this method.
        */
        void addBaseParameters(void) { /* actually do nothing - for future possible use */ }

        ParticleSystem* mParent;
    public:
        ParticleAffector(ParticleSystem* parent): mParent(parent) {}

        /** Virtual destructor essential. */
        virtual ~ParticleAffector();

        /** Method called to allow the affector to initialize all newly created particles in the system.

            This is where the affector gets the chance to initialize it's effects to the particles of a system.
            The affector is expected to initialize some or all of the particles in the system
            passed to it, depending on the affector's approach.
        @param
            pParticle Pointer to a Particle to initialize.
        */
        virtual void _initParticle(Particle* pParticle)
                {
                    /* by default do nothing */
                    (void)pParticle;
                }

        /** Method called to allow the affector to 'do it's stuff' on all active particles in the system.

            This is where the affector gets the chance to apply it's effects to the particles of a system.
            The affector is expected to apply it's effect to some or all of the particles in the system
            passed to it, depending on the affector's approach.
        @param
            pSystem Pointer to a ParticleSystem to affect.
        @param
            timeElapsed The number of seconds which have elapsed since the last call.
        */
        virtual void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) = 0;

        /** Returns the name of the type of affector.

            This property is useful for determining the type of affector procedurally so another
            can be created.
        */
        const String &getType(void) const { return mType; }

    };

两个虚方法分工明确:

方法作用
_initParticle(Particle*)新粒子出生时调用,默认什么都不做
_affectParticles(ParticleSystem*, Real)每帧对系统内活跃粒子施加效果,纯虚

mType 由子类在构造函数里填(如 "ColourFader"、"Scaler"),getType() 返回它供反射与脚本解析使用。

ColourFaderAffector:每秒增量 + 饱和

ParticleFX 自带的影响器都遵循同一个模式:把「每秒调整量」乘以 timeElapsed,再遍历活跃粒子。颜色渐变的实现:

// PlugIns/ParticleFX/src/OgreColourFaderAffector.cpp:ColourFaderAffector::_affectParticles(v14.6.3 源码摘录)
    void ColourFaderAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed)
    {
        // Scale adjustments by time
        auto dc = ColourValue(mRedAdj, mGreenAdj, mBlueAdj, mAlphaAdj) * timeElapsed;

        for (auto p : pSystem->_getActiveParticles())
        {
            p->mColour = (ColourValue((uchar*)&p->mColour) + dc).saturateCopy().getAsBYTE();
        }
    }

三个要点:

  1. 增量按秒定义:mRedAdj 等是「每秒」的颜色变化量,先乘 timeElapsed 得到本帧增量 dc——高帧率下每帧只动一点点,观感平滑。
  2. 逐字节打包的颜色:p->mColour 是 uint32(RGBA 字节打包),ColourValue((uchar*)&p->mColour) 把字节解读成浮点颜色,getAsBYTE() 再打包回去。
  3. saturateCopy() 夹取:加完 dc 后各分量饱和到 [0,1],保证亮度不越界。

成员与 setter(头文件):

// PlugIns/ParticleFX/include/OgreColourFaderAffector.h:ColourFaderAffector(v14.6.3 源码摘录,已删减)
        static CmdRedAdjust msRedCmd;
        static CmdGreenAdjust msGreenCmd;
        static CmdBlueAdjust msBlueCmd;
        static CmdAlphaAdjust msAlphaCmd;

    protected:
        float mRedAdj;
        float mGreenAdj;
        float mBlueAdj;
        float mAlphaAdj;
    };

构造函数里 mType = "ColourFader" 并注册 red/green/blue/alpha 四个参数(脚本里写 colour_fader 块)。注意 OGRE 里没有独立的 DirectionAffector——方向类的行为由 DirectionRandomiserAffector 覆盖。

ScaleAffector:尺寸缩放

ScaleAffector 的 mType 是 "Scaler"。逐帧实现几乎和颜色渐变同构,只是多了非负夹取:

// PlugIns/ParticleFX/src/OgreScaleAffector.cpp:ScaleAffector::_affectParticles(v14.6.3 源码摘录)
    void ScaleAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed)
    {
        // Scale adjustments by time
        float ds = mScaleAdj * timeElapsed;

        for (auto p : pSystem->_getActiveParticles())
        {
            float w = std::max(0.0f, p->getOwnWidth() + ds);
            float h = std::max(0.0f, p->getOwnHeight() + ds);
            p->setDimensions(w, h);
        }
    }

ds 是本帧的宽高增量,std::max(0.0f, ...) 把宽度/高度夹在非负区间——粒子只会缩小到消失,不会「反向翻过去」。此外它覆写了 _initParticle,让新粒子出生时按 mScaleRange 随机缩放到初始尺寸:

// PlugIns/ParticleFX/src/OgreScaleAffector.cpp:ScaleAffector::_initParticle(v14.6.3 源码摘录)
    void ScaleAffector::_initParticle(Particle* p)
    {
        float w = p->getOwnWidth();
        float h = p->getOwnHeight();
        float s = Math::RangeRandom(mScaleRange[0], mScaleRange[1]);
        p->setDimensions(s * w, s * h);
    }

DirectionRandomiserAffector:按 scope 挑粒子加噪声

方向随机化不是直接设方向,而是在原方向上叠加随机噪声,模拟「翻涌」的粒子云。它有 randomness(每轴噪声强度)、scope(受影响粒子比例)、keep_velocity(是否保持原速率)三个参数:

// PlugIns/ParticleFX/src/OgreDirectionRandomiserAffector.cpp:DirectionRandomiserAffector::_affectParticles(v14.6.3 源码摘录)
    void DirectionRandomiserAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed)
    {
        Real length = 0;

        for (auto p : pSystem->_getActiveParticles())
        {
            if (mScope > Math::UnitRandom())
            {
                if (!p->mDirection.isZeroLength())
                {
                    if (mKeepVelocity)
                    {
                        length = p->mDirection.length();
                    }

                    p->mDirection += Vector3(Math::RangeRandom(-mRandomness, mRandomness) * timeElapsed,
                        Math::RangeRandom(-mRandomness, mRandomness) * timeElapsed,
                        Math::RangeRandom(-mRandomness, mRandomness) * timeElapsed);

                    if (mKeepVelocity)
                    {
                        p->mDirection *= length / p->mDirection.length();
                    }
                }
            }
        }
    }

逻辑拆开看:

  1. if (mScope > Math::UnitRandom())——每个粒子一次均匀随机判断,scope=1.0 全受影响,scope=0 全不受影响。
  2. 跳过零长度方向(避免除以零)。
  3. 每轴在 [-mRandomness, mRandomness] * timeElapsed 内加噪声。
  4. mKeepVelocity 时,先把原长度存进 length,加完噪声后按 length / newLength 缩放,把速度大小还原、只改变方向。

OGRE 自带的影响器不止这三个,ParticleFX 还提供 ColourInterpolatorAffector(多点颜色插值)、LinearForceAffector(恒定力)、DeflectorPlaneAffector(反弹平面)等,但它们的骨架都是「纯虚 _affectParticles + 每秒增量乘时间 + 遍历活跃粒子」。

源码定位

上游引用固定到 OGRE v14.6.3 源码 。

可运行产物:C++ 最小验证

下面用纯 C++ 复现影响器的逐帧语义。它与 src/06-3-particle-affector.cpp 逐字节一致:

// file: src/06-3-particle-affector.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/06-3-particle-affector.cpp -o bin/06-3-particle-affector && ./bin/06-3-particle-affector
//
// 复现 ParticleAffector 抽象接口与三个具体影响器(对应 OgreParticleAffector.h 的
//   ParticleAffector、PlugIns/ParticleFX 的 ColourFaderAffector/ScaleAffector/
//   DirectionRandomiserAffector):
//   ParticleAffector 定义纯虚 _affectParticles(ParticleSystem*, Real),子类逐帧覆写;
//   ColourFaderAffector 把每秒颜色增量乘以 timeElapsed 后加到每个活跃粒子颜色上,再 saturate 到 [0,1];
//   ScaleAffector 每秒缩放量乘以 timeElapsed,宽/高用 max(0, x) 夹取;
//   DirectionRandomiserAffector 按 scope 随机挑选粒子,在 [-randomness, randomness] 加噪声,
//     keepVelocity 时按原长度缩放恢复速度。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <vector>

namespace ogre_repro {

struct Vec3 {
  float x, y, z;
  Vec3 operator+(const Vec3& o) const { return {x + o.x, y + o.y, z + o.z}; }
  Vec3 operator*(float s) const { return {x * s, y * s, z * s}; }
  float dot(const Vec3& o) const { return x * o.x + y * o.y + z * o.z; }
  float length() const { return std::sqrt(dot(*this)); }
};

// 固定种子伪随机,保证断言可复现
static uint64_t gSeed = 0xD1B54A32D192ED03ull;
static float randUnit() {
  gSeed ^= gSeed << 13;
  gSeed ^= gSeed >> 7;
  gSeed ^= gSeed << 17;
  return static_cast<float>((gSeed >> 8) & 0xFFFFFF) / static_cast<float>(1 << 24);
}
static float randRange(float min, float max) { return min + (max - min) * randUnit(); }
static float clamp01(float v) { return std::max(0.0f, std::min(1.0f, v)); }

// 对应 OgreParticle 的 mColour:RGBA 浮点表示(OGRE 用 uint32 打包字节,语义相同)
struct Colour {
  float r, g, b, a;
  Colour operator+(const Colour& o) const { return {r + o.r, g + o.g, b + o.b, a + o.a}; }
  // 对应 ColourValue::saturateCopy():各分量夹到 [0,1]
  Colour saturated() const { return {clamp01(r), clamp01(g), clamp01(b), clamp01(a)}; }
};

// 对应 OgreParticle.h 的 Particle
struct Particle {
  Colour colour{1, 1, 1, 1};
  float width = 1.0f;    // getOwnWidth()
  float height = 1.0f;   // getOwnHeight()
  Vec3 direction{0, 1, 0};
};

// 极简 ParticleSystem:只维护活跃列表(对应 _getActiveParticles())
class ParticleSystem {
 public:
  void add(const Particle& p) { mActive.push_back(p); }
  std::vector<Particle>& active() { return mActive; }
  const std::vector<Particle>& active() const { return mActive; }

 private:
  std::vector<Particle> mActive;
};

// 对应 OgreParticleAffector.h 的 ParticleAffector:纯虚逐帧影响
class ParticleAffector {
 public:
  virtual ~ParticleAffector() = default;
  virtual void initParticle(Particle& p) { (void)p; }  // 默认不做,对应 _initParticle
  virtual void affectParticles(ParticleSystem& ps, float dt) = 0;  // 对应 _affectParticles
};

// 对应 ColourFaderAffector:每秒颜色增量 + saturate
class ColourFaderAffector : public ParticleAffector {
 public:
  void setAdjust(float r, float g, float b, float a) {
    mRedAdj = r;
    mGreenAdj = g;
    mBlueAdj = b;
    mAlphaAdj = a;
  }
  void affectParticles(ParticleSystem& ps, float dt) override {
    Colour dc{mRedAdj * dt, mGreenAdj * dt, mBlueAdj * dt, mAlphaAdj * dt};
    for (auto& p : ps.active()) {
      p.colour = (p.colour + dc).saturated();
    }
  }

 private:
  float mRedAdj = 0, mGreenAdj = 0, mBlueAdj = 0, mAlphaAdj = 0;
};

// 对应 ScaleAffector:每秒缩放量 + max(0, x) 夹取
class ScaleAffector : public ParticleAffector {
 public:
  void setAdjust(float rate) { mScaleAdj = rate; }
  void affectParticles(ParticleSystem& ps, float dt) override {
    float ds = mScaleAdj * dt;
    for (auto& p : ps.active()) {
      p.width = std::max(0.0f, p.width + ds);
      p.height = std::max(0.0f, p.height + ds);
    }
  }

 private:
  float mScaleAdj = 0.0f;
};

// 对应 DirectionRandomiserAffector:按 scope 选粒子,加噪声,keepVelocity 恢复长度
class DirectionRandomiserAffector : public ParticleAffector {
 public:
  void setRandomness(float v) { mRandomness = v; }
  void setScope(float v) { mScope = v; }
  void setKeepVelocity(bool v) { mKeepVelocity = v; }
  void affectParticles(ParticleSystem& ps, float dt) override {
    for (auto& p : ps.active()) {
      if (mScope > randUnit()) {
        float len = p.direction.length();  // 保存原速度
        p.direction = p.direction + Vec3{randRange(-mRandomness, mRandomness) * dt,
                                         randRange(-mRandomness, mRandomness) * dt,
                                         randRange(-mRandomness, mRandomness) * dt};
        if (mKeepVelocity && len > 1e-6f) {
          p.direction = p.direction * (len / p.direction.length());
        }
      }
    }
  }

 private:
  float mRandomness = 1.0f;
  float mScope = 1.0f;
  bool mKeepVelocity = false;
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  // --- ColourFaderAffector:每秒颜色增量,逐帧缩放,饱和到 [0,1] ---
  ColourFaderAffector fader;
  fader.setAdjust(-1.0f, 0.5f, 0.0f, 0.0f);  // 每秒 r-1, g+0.5
  Particle a;
  Particle b;
  b.colour = Colour{0.5f, 0.0f, 0.0f, 1.0f};
  ParticleSystem ps;
  ps.add(a);
  ps.add(b);

  fader.affectParticles(ps, 0.5f);  // dt=0.5 -> dc=(-0.5, +0.25, 0, 0)
  CHECK_EQ(ps.active()[0].colour.r, 0.5f);  // 1 - 0.5
  CHECK_EQ(ps.active()[0].colour.g, 1.0f);  // 1 + 0.25 饱和到 1
  CHECK_EQ(ps.active()[0].colour.b, 1.0f);
  CHECK_EQ(ps.active()[1].colour.r, 0.0f);  // 0.5 - 0.5

  fader.setAdjust(-2.0f, 0.0f, 0.0f, 0.0f);
  fader.affectParticles(ps, 1.0f);  // dc=(-2, 0, 0, 0)
  CHECK_EQ(ps.active()[0].colour.r, 0.0f);  // 0.5 - 2 -> 负值饱和到 0

  fader.setAdjust(0.0f, 2.0f, 0.0f, 0.0f);
  fader.affectParticles(ps, 1.0f);  // dc=(0, 2, 0, 0)
  CHECK_EQ(ps.active()[1].colour.g, 1.0f);  // 0 + 2 -> 饱和到 1
  CHECK_EQ(ps.active()[1].colour.b, 0.0f);  // 不受 g 调整影响

  // --- ScaleAffector:每秒缩放量,宽/高非负夹取 ---
  ScaleAffector scaler;
  scaler.setAdjust(-0.5f);          // 每秒 -0.5
  Particle c;
  c.width = 1.0f;
  c.height = 2.0f;
  ParticleSystem ps2;
  ps2.add(c);
  scaler.affectParticles(ps2, 1.0f);
  CHECK_EQ(ps2.active()[0].width, 0.5f);
  CHECK_EQ(ps2.active()[0].height, 1.5f);

  scaler.setAdjust(-2.0f);
  scaler.affectParticles(ps2, 1.0f);  // 0.5 - 2 -> 夹到 0
  CHECK_EQ(ps2.active()[0].width, 0.0f);

  scaler.setAdjust(0.25f);
  scaler.affectParticles(ps2, 2.0f);  // 0 + 0.5
  CHECK_EQ(ps2.active()[0].width, 0.5f);
  CHECK_EQ(ps2.active()[0].height, 0.5f);  // 1.5 - 2 -> 0,再 +0.5 -> 0.5

  // --- DirectionRandomiserAffector:scope 挑选 + 噪声 + 可选保速度 ---
  DirectionRandomiserAffector randomiser;
  randomiser.setRandomness(0.2f);
  randomiser.setScope(1.0f);         // 100% 粒子受影响
  randomiser.setKeepVelocity(false);

  Particle d;
  d.direction = Vec3{1, 0, 0};
  ParticleSystem ps3;
  ps3.add(d);
  CHECK_EQ(ps3.active()[0].direction.x, 1.0f);  // 初始方向
  randomiser.affectParticles(ps3, 1.0f);
  float lenNoKeep = ps3.active()[0].direction.length();
  CHECK(ps3.active()[0].direction.x != 1.0f);   // 噪声改变方向
  CHECK(std::abs(lenNoKeep - 1.0f) > 1e-4f);    // 不保速度 -> 长度改变

  randomiser.setKeepVelocity(true);
  Particle e;
  e.direction = Vec3{1, 0, 0};
  ParticleSystem ps4;
  ps4.add(e);
  randomiser.affectParticles(ps4, 1.0f);
  float lenKeep = ps4.active()[0].direction.length();
  CHECK(std::abs(lenKeep - 1.0f) < 1e-4f);      // 保速度 -> 长度不变

  randomiser.setScope(0.0f);                    // 0% 受影响
  Particle f;
  f.direction = Vec3{1, 0, 0};
  ParticleSystem ps5;
  ps5.add(f);
  randomiser.affectParticles(ps5, 1.0f);
  CHECK_EQ(ps5.active()[0].direction.x, 1.0f);  // scope=0 完全不动
  CHECK_EQ(ps5.active()[0].direction.y, 0.0f);

  return lab::report("06-3 影响器");
}

本机实测(Apple clang 16,clang++ -std=c++20):编译通过(-Wall 零警告),断言 18/18 通过。

小结

  • ParticleAffector 的核心是纯虚 _affectParticles(ParticleSystem*, Real),逐帧被系统调用。
  • 自带影响器统一「每秒增量 × timeElapsed + 遍历活跃粒子」的骨架。
  • ColourFaderAffector:颜色增量后 saturateCopy() 饱和到 [0,1],RGBA 字节打包/解包。
  • ScaleAffector:宽高加 ds 后用 max(0, x) 夹取,另用 _initParticle 按 mScaleRange 给初始尺寸。
  • DirectionRandomiserAffector:scope 挑粒子、每轴加噪声、keep_velocity 还原速率。
  • 影响器与发射器共用插件注册体系,扩展只需子类化 + 注册工厂。

阅读导航:上一节:6.2 发射器 · 下一节:7.1 地形组件 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析》15.3 落地:从 Neo4j 到自研图引擎
  2. 《大规模分布式计算深入解析·图计算与图数据库内核》 · 目录与学习路径(45 篇)
  3. 《大规模分布式计算深入解析》15.2 十一卷主线:从切分到图