7.2 Bites 输入与主循环
ApplicationContext 不仅管窗口与资源,还承担整帧的主循环:每帧开头 pollEvents() 把平台事件翻译成 Bites 统一事件,再按类型分发给一组 InputListener。这一节看事件数据结构、监听器回调、分发逻辑与事件消费循环。
本章与站内既有内容的分工
7.1 讲了上下文如何串起启动流程并注册为 FrameListener;这一节深入它的 frameStarted 里实际执行的部分——pollEvents() 与 _fireInputEvent()。输入事件模型是 Bites 层独有的抽象,不依赖某个渲染后端的窗口系统;7.3 的 Sample 正是通过继承 InputListener 接收这里分发的事件。
事件数据:Event union 与具体事件结构
Bites 没有为每种输入建类层次,而是用 C 风格的 Event union:首字段 type 决定读哪个成员。键盘、鼠标按键、鼠标滚轮、鼠标移动、触控、文本输入、摇杆/手柄各有独立结构:
// Components/Bites/include/OgreInput.h:Event(v14.6.3 源码摘录,已删减)
struct Keysym {
Keycode sym;
unsigned short mod;
};
struct KeyboardEvent {
int type;
Keysym keysym;
unsigned char repeat;
};
struct MouseMotionEvent {
int type;
int x, y;
int xrel, yrel;
int windowID;
};
struct MouseButtonEvent {
int type;
int x, y;
unsigned char button;
unsigned char clicks;
};
struct MouseWheelEvent {
int type;
int y;
};
struct TouchFingerEvent {
int type;
int fingerId;
float x, y;
float dx, dy;
};
struct TextInputEvent {
int type;
const char* chars;
};
union Event
{
int type;
KeyboardEvent key;
MouseButtonEvent button;
MouseWheelEvent wheel;
MouseMotionEvent motion;
TouchFingerEvent tfinger;
TextInputEvent text;
AxisEvent axis;
ButtonEvent cbutton;
HatEvent hat;
};
EventType 枚举从 KEYDOWN 一直排到 JOYHATMOTION;注意枚举顺序本身承担了语义:type <= TEXTINPUT 的都是「窗口相关事件」,而 CONTROLLER*/JOY* 手柄事件与窗口无关。这个顺序被分发逻辑直接依赖(见下文)。
监听器:InputListener 回调集合
InputListener 是一组可覆写的回调。默认全部返回 false;按约定返回 true 表示事件已处理、不再向后传播(InputListenerChain 会利用这一点):
// Components/Bites/include/OgreInput.h:InputListener(v14.6.3 源码摘录,已删减)
struct _OgreBitesExport InputListener {
virtual ~InputListener() {}
virtual void frameRendered(const Ogre::FrameEvent& evt) { }
virtual bool keyPressed(const KeyboardEvent& evt) { return false;}
virtual bool keyReleased(const KeyboardEvent& evt) { return false; }
virtual bool touchMoved(const TouchFingerEvent& evt) { return false; }
virtual bool touchPressed(const TouchFingerEvent& evt) { return false; }
virtual bool touchReleased(const TouchFingerEvent& evt) { return false; }
virtual bool mouseMoved(const MouseMotionEvent& evt) { return false; }
virtual bool mouseWheelRolled(const MouseWheelEvent& evt) { return false; }
virtual bool mousePressed(const MouseButtonEvent& evt) { return false; }
virtual bool mouseReleased(const MouseButtonEvent& evt) { return false; }
virtual bool textInput(const TextInputEvent& evt) { return false; }
virtual bool axisMoved(const AxisEvent& evt) { return false; }
virtual bool hatMoved(const HatEvent& evt) { return false; }
virtual bool buttonPressed(const ButtonEvent& evt) { return false; }
virtual bool buttonReleased(const ButtonEvent& evt) { return false; }
};
上下文用 std::multimap(InputListenerList)持有监听器,addInputListener 插入、removeInputListener 按 (win, lis) 对删除;同一监听器可注册多次。frameRenderingQueued 里遍历所有监听器调用 frameRendered(evt),让它们做每帧 UI 更新。
分发:_fireInputEvent 按类型路由
_fireInputEvent 先把 Event 复制一份(Apple 平台对鼠标坐标做 retina 缩放),然后遍历监听器。两条规则值得注意:窗口过滤与 FINGERDOWN 的特殊顺序:
// Components/Bites/src/OgreApplicationContextBase.cpp:ApplicationContextBase::_fireInputEvent(v14.6.3 源码摘录,已删减)
void ApplicationContextBase::_fireInputEvent(const Event& event, uint32_t windowID) const
{
Event scaled = event;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
if (event.type == MOUSEMOTION)
{
// assumes all windows have the same scale
float viewScale = getRenderWindow()->getViewPointToPixelScale();
scaled.motion.x *= viewScale;
scaled.motion.y *= viewScale;
}
...
#endif
for(const auto & li : mInputListeners)
{
// gamepad events are not window specific
if(li.first != windowID && event.type <= TEXTINPUT) continue;
InputListener& l = *li.second;
switch (event.type)
{
case KEYDOWN:
l.keyPressed(event.key);
break;
case KEYUP:
l.keyReleased(event.key);
break;
case MOUSEBUTTONDOWN:
l.mousePressed(scaled.button);
break;
case MOUSEBUTTONUP:
l.mouseReleased(scaled.button);
break;
case MOUSEWHEEL:
l.mouseWheelRolled(event.wheel);
break;
...
case FINGERDOWN:
// for finger down we have to move the pointer first
l.touchMoved(event.tfinger);
l.touchPressed(event.tfinger);
break;
case FINGERUP:
l.touchReleased(event.tfinger);
break;
...
case CONTROLLERBUTTONDOWN:
l.buttonPressed(event.cbutton);
break;
case CONTROLLERBUTTONUP:
l.buttonReleased(event.cbutton);
break;
}
}
}
窗口过滤的写法 li.first != windowID && event.type <= TEXTINPUT 是纯枚举序的技巧:键盘/鼠标/滚轮/触控/文本事件都带窗口归属,若监听器注册在另一个窗口就跳过;而手柄事件(CONTROLLER*/JOY*)序号大于 TEXTINPUT,第一个条件短路为假,因此所有监听器都能收到。FINGERDOWN 之所以先 touchMoved 再 touchPressed,是为了把「指针先移动到触点」这个隐式移动合成出来,监听器只需处理按压本身。
主循环:pollEvents 消费 SDL 事件
ApplicationContextSDL::pollEvents() 是平台具体的事件循环:每帧从 SDL 队列取一个事件翻译后交给 _fireInputEvent。SDL_QUIT 直接请求结束渲染;窗口尺寸变化直接转成 RenderWindow::resize;鼠标移动/按键要跳过 SDL 从触摸仿真出来的 SDL_TOUCH_MOUSEID,避免触摸屏把鼠标事件和触摸事件重复发两遍:
// Components/Bites/src/OgreApplicationContextSDL.cpp:ApplicationContextSDL::pollEvents(v14.6.3 源码摘录,已删减)
void ApplicationContextSDL::pollEvents()
{
if(mWindows.empty())
{
// SDL events not initialized
return;
}
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
mRoot->queueEndRendering();
break;
case SDL_WINDOWEVENT:
if(event.window.event != SDL_WINDOWEVENT_RESIZED)
continue;
for(auto & window : mWindows)
{
if(event.window.windowID != SDL_GetWindowID(window.native))
continue;
Ogre::RenderWindow* win = window.render;
win->resize(event.window.data1, event.window.data2);
windowResized(win);
}
break;
...
// touches arrive as finger events, so skip the mouse events SDL emulates from them
case SDL_MOUSEMOTION:
if(event.motion.which != SDL_TOUCH_MOUSEID)
_fireInputEvent(convert(event), event.window.windowID);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
if(event.button.which != SDL_TOUCH_MOUSEID)
_fireInputEvent(convert(event), event.window.windowID);
break;
default:
_fireInputEvent(convert(event), event.window.windowID);
break;
}
}
}
convert(event) 把 SDL 事件翻译成 Bites Event,同时把 SDL 的窗口 id 一并传出,供 _fireInputEvent 做窗口过滤。frameStarted → pollEvents → _fireInputEvent → 监听器回调,这条链就是 Bites 示例的主循环输入通路。
宿主输入和渲染回调的边界
Bites 负责把窗口事件和输入分派到应用。宿主时钟可决定模拟步进,Root 管理渲染回调。要在外部循环中明确哪个时点采集输入、更新场景和请求退出。
固定输入序列,在宿主记录输入、模拟、renderOneFrame 返回值与关闭事件。用原生帧探针交叉核对 false 所影响的阶段。
宿主输入与渲染帧的交接
sequenceDiagram
participant W as 窗口与输入
participant H as 宿主循环
participant S as 场景状态
participant R as Root
W-->>H: 输入与退出事件
H->>H: 按模拟时钟计算步数
H->>S: 推进逻辑并提交节点变换
H->>R: renderOneFrame
R-->>H: 返回是否继续
opt 请求退出或帧返回 false
H->>H: 停止输入和新任务,开始关停
end
源码定位
Components/Bites/include/OgreInput.h:EventType(36-50)、具体事件结构(59-106)、Eventunion(108-120)、InputListener(182-199)、InputListenerChain(206-)Components/Bites/src/OgreApplicationContextBase.cpp:addInputListener(354-357)、removeInputListener(360-363)、frameRenderingQueued(365-372)、_fireInputEvent(427-502)Components/Bites/src/OgreApplicationContextSDL.cpp:pollEvents(152-211)Components/Bites/include/OgreApplicationContextBase.h:InputListenerList(317)、_fireInputEvent(140)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现事件分发与主循环:Event union、InputListener 默认回调、_fireInputEvent 的窗口过滤与 FINGERDOWN 顺序、pollEvents 的 SDL_QUIT 结束标记。它与 src/ogre-ext-07-2-bites-input-loop.cpp 逐字节一致:
// file: src/ogre-ext-07-2-bites-input-loop.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-07-2-bites-input-loop.cpp -o bin/ogre-ext-07-2-bites-input-loop && ./bin/ogre-ext-07-2-bites-input-loop
//
// 复现 Bites 输入事件模型与主循环
// (对应 OgreInput.h 108-120、182-199、OgreApplicationContextBase.cpp 427-502、
// OgreApplicationContextSDL.cpp 152-211):
// Event union 承载 type + 各具体事件结构;
// InputListener 回调集合默认返回 false;
// _fireInputEvent 按 event.type 路由,gamepad 事件(type > TEXTINPUT)不按窗口过滤,
// FINGERDOWN 先 touchMoved 再 touchPressed;
// pollEvents 循环消费事件,SDL_QUIT 触发 queueEndRendering。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
namespace ogre_repro {
// EventType(OgreInput.h 36-50 的 EventType 简化)
enum EventType {
SDL_QUIT = 1,
KEYDOWN,
KEYUP,
MOUSEMOTION,
MOUSEBUTTONDOWN,
MOUSEBUTTONUP,
MOUSEWHEEL,
FINGERDOWN,
TEXTINPUT,
CONTROLLERBUTTONDOWN,
EVENT_COUNT
};
// 具体事件结构(OgreInput.h 59-106 简化)
struct KeyboardEvent { int type; int sym; unsigned short mod; unsigned char repeat; };
struct MouseButtonEvent { int type; int x, y; unsigned char button; };
struct MouseWheelEvent { int type; int y; };
struct TouchFingerEvent { int type; int fingerId; float x, y; };
struct TextInputEvent { int type; const char* chars; };
struct ButtonEvent { int type; int which; unsigned char button; };
// Event union(OgreInput.h 108-120)
union Event {
int type;
KeyboardEvent key;
MouseButtonEvent button;
MouseWheelEvent wheel;
TouchFingerEvent tfinger;
TextInputEvent text;
ButtonEvent cbutton;
};
// InputListener(OgreInput.h 182-199):默认回调返回 false
struct InputListener {
virtual ~InputListener() = default;
virtual bool keyPressed(const KeyboardEvent&) { return false; }
virtual bool keyReleased(const KeyboardEvent&) { return false; }
virtual bool mouseMoved(int /*x*/, int /*y*/) { return false; }
virtual bool mouseWheelRolled(const MouseWheelEvent&) { return false; }
virtual bool mousePressed(const MouseButtonEvent&) { return false; }
virtual bool mouseReleased(const MouseButtonEvent&) { return false; }
virtual bool touchMoved(const TouchFingerEvent&) { return false; }
virtual bool touchPressed(const TouchFingerEvent&) { return false; }
virtual bool textInput(const TextInputEvent&) { return false; }
virtual bool buttonPressed(const ButtonEvent&) { return false; }
};
// 计数记录监听器
struct Recorder : InputListener {
int keyPressedCount = 0, keyReleasedCount = 0;
int mousePressedCount = 0, mouseReleasedCount = 0;
int wheelCount = 0, textCount = 0, buttonCount = 0;
int touchMovedCount = 0, touchPressedCount = 0;
std::vector<int> touchOrder; // 1=touchMoved, 2=touchPressed
int lastKeySym = 0;
unsigned char lastButton = 0;
int lastX = 0, lastWheelY = 0;
std::string lastChars;
bool keyPressed(const KeyboardEvent& e) override { keyPressedCount++; lastKeySym = e.sym; return true; }
bool keyReleased(const KeyboardEvent& e) override { keyReleasedCount++; (void)e; return true; }
bool mousePressed(const MouseButtonEvent& e) override {
mousePressedCount++; lastButton = e.button; lastX = e.x; return true;
}
bool mouseReleased(const MouseButtonEvent& e) override { mouseReleasedCount++; (void)e; return true; }
bool mouseWheelRolled(const MouseWheelEvent& e) override { wheelCount++; lastWheelY = e.y; return true; }
bool touchMoved(const TouchFingerEvent&) override { touchMovedCount++; touchOrder.push_back(1); return true; }
bool touchPressed(const TouchFingerEvent&) override { touchPressedCount++; touchOrder.push_back(2); return true; }
bool textInput(const TextInputEvent& e) override { textCount++; lastChars = e.chars ? e.chars : ""; return true; }
bool buttonPressed(const ButtonEvent& e) override { buttonCount++; (void)e; return true; }
};
// 对应 ApplicationContextBase(OgreApplicationContextBase.cpp 354-363、427-502)
class ApplicationContext {
public:
void addInputListener(uint32_t win, InputListener* lis) {
mInputListeners.emplace_back(win, lis);
}
void removeInputListener(uint32_t win, InputListener* lis) {
for (size_t i = 0; i < mInputListeners.size(); ++i) {
if (mInputListeners[i].first == win && mInputListeners[i].second == lis) {
mInputListeners.erase(mInputListeners.begin() + static_cast<long>(i));
return;
}
}
}
// _fireInputEvent(OgreApplicationContextBase.cpp 427-502)
void fire(const Event& event, uint32_t windowID) {
for (const auto& li : mInputListeners) {
// gamepad events are not window specific
if (li.first != windowID && event.type <= TEXTINPUT) continue;
InputListener& l = *li.second;
switch (event.type) {
case KEYDOWN: l.keyPressed(event.key); break;
case KEYUP: l.keyReleased(event.key); break;
case MOUSEBUTTONDOWN: l.mousePressed(event.button); break;
case MOUSEBUTTONUP: l.mouseReleased(event.button); break;
case MOUSEWHEEL: l.mouseWheelRolled(event.wheel); break;
case FINGERDOWN:
// for finger down we have to move the pointer first
l.touchMoved(event.tfinger);
l.touchPressed(event.tfinger);
break;
case TEXTINPUT: l.textInput(event.text); break;
case CONTROLLERBUTTONDOWN: l.buttonPressed(event.cbutton); break;
default: break;
}
}
}
// pollEvents(OgreApplicationContextSDL.cpp 152-211):SDL_QUIT 结束渲染
void pollEvents(const std::vector<Event>& queue) {
for (const auto& ev : queue) {
if (ev.type == SDL_QUIT) { queueEndRendering(); continue; }
fire(ev, 0);
}
}
void queueEndRendering() { mEndRendering = true; }
bool isEndRendering() const { return mEndRendering; }
void clearEndRendering() { mEndRendering = false; }
private:
std::vector<std::pair<uint32_t, InputListener*>> mInputListeners; // 对应 InputListenerList
bool mEndRendering = false;
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// 默认回调返回 false(OgreInput.h 182-199)
InputListener plain;
KeyboardEvent ke{KEYDOWN, 0x61, 0, 0};
CHECK(!plain.keyPressed(ke));
Recorder rec;
ApplicationContext ctx;
ctx.addInputListener(0, &rec); // 窗口 0
// KEYDOWN -> keyPressed,携带 keysym
Event key{};
key.type = KEYDOWN;
key.key = KeyboardEvent{KEYDOWN, 0x61, 0, 0};
ctx.fire(key, 0);
CHECK(rec.keyPressedCount == 1);
CHECK(rec.lastKeySym == 0x61);
// KEYUP -> keyReleased
Event up{};
up.type = KEYUP;
up.key = KeyboardEvent{KEYUP, 0x61, 0, 0};
ctx.fire(up, 0);
CHECK(rec.keyReleasedCount == 1);
// MOUSEBUTTONDOWN -> mousePressed(button/x)
Event mb{};
mb.type = MOUSEBUTTONDOWN;
mb.button = MouseButtonEvent{MOUSEBUTTONDOWN, 42, 84, 1};
ctx.fire(mb, 0);
CHECK(rec.mousePressedCount == 1);
CHECK(rec.lastButton == 1);
CHECK(rec.lastX == 42);
// MOUSEBUTTONUP -> mouseReleased
Event mu{};
mu.type = MOUSEBUTTONUP;
mu.button = MouseButtonEvent{MOUSEBUTTONUP, 42, 84, 1};
ctx.fire(mu, 0);
CHECK(rec.mouseReleasedCount == 1);
// MOUSEWHEEL -> mouseWheelRolled
Event wh{};
wh.type = MOUSEWHEEL;
wh.wheel = MouseWheelEvent{MOUSEWHEEL, -3};
ctx.fire(wh, 0);
CHECK(rec.wheelCount == 1);
CHECK(rec.lastWheelY == -3);
// TEXTINPUT -> textInput
Event tx{};
tx.type = TEXTINPUT;
tx.text = TextInputEvent{TEXTINPUT, "ogre"};
ctx.fire(tx, 0);
CHECK(rec.textCount == 1);
CHECK(rec.lastChars == "ogre");
// FINGERDOWN 先 touchMoved 再 touchPressed(OgreApplicationContextBase.cpp 473-477)
Event fg{};
fg.type = FINGERDOWN;
fg.tfinger = TouchFingerEvent{FINGERDOWN, 1, 0.5f, 0.25f};
ctx.fire(fg, 0);
CHECK(rec.touchMovedCount == 1);
CHECK(rec.touchPressedCount == 1);
CHECK(rec.touchOrder.size() == 2);
CHECK(rec.touchOrder[0] == 1);
CHECK(rec.touchOrder[1] == 2);
// 鼠标/键盘事件按窗口过滤:窗口 1 的监听器收不到窗口 0 的事件
Recorder rec1;
ctx.addInputListener(1, &rec1);
Event key2{};
key2.type = KEYDOWN;
key2.key = KeyboardEvent{KEYDOWN, 0x62, 0, 0};
ctx.fire(mb, 0);
CHECK(rec1.mousePressedCount == 0);
CHECK(rec1.keyPressedCount == 0);
// 键盘事件同样按窗口过滤,窗口 1 收不到窗口 0 的 KEYDOWN
ctx.fire(key2, 0);
CHECK(rec1.keyPressedCount == 0);
// gamepad 事件不按窗口过滤:窗口 1 的监听器也收到(event.type > TEXTINPUT)
Event cb{};
cb.type = CONTROLLERBUTTONDOWN;
cb.cbutton = ButtonEvent{CONTROLLERBUTTONDOWN, 0, 1};
ctx.fire(cb, 0);
CHECK(rec.buttonCount == 1);
CHECK(rec1.buttonCount == 1);
// 双监听器都收到窗口 0 的键盘事件(rec 是窗口 0,rec1 是窗口 1 收不到)
ctx.fire(key2, 0);
CHECK(rec.keyPressedCount == 3); // 1(0x61) + 2(key2)
CHECK(rec1.keyPressedCount == 0);
// removeInputListener 后不再分发(rec 仍正常接收)
ctx.removeInputListener(1, &rec1);
ctx.fire(key2, 0);
CHECK(rec1.keyPressedCount == 0); // 不再增长
CHECK(rec.keyPressedCount == 4);
// pollEvents:SDL_QUIT 触发 queueEndRendering,普通事件照常分发
ctx.clearEndRendering();
Event quit{};
quit.type = SDL_QUIT;
std::vector<Event> queue{key2, quit};
ctx.pollEvents(queue);
CHECK(rec.keyPressedCount == 5); // 1(0x61) + 3(key2) + 1(pollEvents 队列)
CHECK(ctx.isEndRendering());
return lab::report("07-2 Bites 输入与主循环");
}
本机实测(Apple clang,clang++ -std=c++20 -Wall):编译通过(零警告),断言 28/28 通过。
小结
- 输入事件是 C 风格
Eventunion:首字段type决定读哪个具体结构。 InputListener是一组默认返回false的虚回调;true表示事件已处理。_fireInputEvent按type路由;type <= TEXTINPUT的事件按窗口过滤,手柄事件全员广播。FINGERDOWN合成「先移动后按下」:先touchMoved再touchPressed。pollEvents每帧消费 SDL 事件,SDL_QUIT走queueEndRendering,鼠标事件跳过 SDL 触摸仿真 id。
阅读导航:上一节:7.1 Bites 应用上下文 · 下一节:7.3 示例工程结构 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。