So, I rewrote my game in C3
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
So, I rewrote my game in C3
If you are wondering, I wrote this myself with my own two hands. Writing is a nice way to organize my thoughts, I should do it more. Over the past few months I’ve been working on rewriting Traction Point in C3. All the Zig code in the game has been replaced with C3, and the modding SDK will follow when the next playtest version is released.
如果你在好奇,这篇文章是我亲手写的。写作是整理思绪的好方法,我应该多写写。在过去的几个月里,我一直在用 C3 重写《Traction Point》。游戏中所有的 Zig 代码都已被 C3 取代,模组开发工具包(SDK)也将在下一个测试版本发布时跟进。
Why, you ask? Well, ever since I made it possible to hot-reload the game code, it has become an integral part of my workflow for developing the game. Want to tweak a UI element? Make the change and hot-reload the code while the game is running, and it shows up. An animation needing a longer ease-in? Hot-reload and you will see it in seconds. Need a temporary print in the code to isolate a bug in the state of the game? Hot-reload.
你问为什么?好吧,自从我实现了游戏代码的热重载功能后,它就成了我开发工作流程中不可或缺的一部分。想要调整 UI 元素?只需修改代码并在游戏运行时进行热重载,效果就会立即呈现。动画需要更长的缓入效果?热重载一下,几秒钟就能看到结果。需要在代码中临时打印信息来定位游戏状态中的 Bug?热重载即可。
The problem with Zig is that building code on Windows is sloooow. These days Zig has a self-hosted backend which compiles code relatively quickly, at least in debug mode, but unfortunately it’s not yet available on Windows. They even added a form of incremental-compilation, but it doesn’t remove the long LLVM linking times. To give you an idea of what I am talking about, a full build of the Traction Point debug configuration, at a little over 100k LoC of Zig, takes around 24s. Changing a single line and rebuilding, with a warm cache, takes over 15s.
Zig 的问题在于它在 Windows 上的构建速度非常慢。如今 Zig 有了一个自托管后端,编译速度相对较快(至少在调试模式下是这样),但不幸的是,它在 Windows 上尚不可用。他们甚至增加了一种增量编译形式,但这并没有消除漫长的 LLVM 链接时间。为了让你了解我在说什么:在《Traction Point》的调试配置中,超过 10 万行 Zig 代码的完整构建大约需要 24 秒。而在缓存预热的情况下,修改一行代码并重新构建也需要超过 15 秒。
C3 compiles the full game, without caching, in about 3s. I’ve seen it be as fast as 2.6s. Now, this is podracing! It will probably get a bit slower before the game is done, as more code is added, but I am sure you can see the benefits here.
C3 编译整个游戏(不使用缓存)大约只需要 3 秒。我甚至见过它达到 2.6 秒的速度。这才是真正的极速体验!随着游戏开发完成,代码量增加,编译速度可能会变慢一些,但我相信你能看出其中的优势。
What is C3 anyway? C3 is not as widely known as other modern systems programming languages, but it fits the project perfectly. I wanted a language that could act almost as a drop-in replacement for Zig. That meant the memory model needed to be the same (no GC, no RAII), it needed to compile to WASM (for mod support), it needed to be fast (obviously, we are making a game here), and it needed to compile quickly.
C3 到底是什么?C3 不像其他现代系统编程语言那样广为人知,但它非常适合这个项目。我想要一种几乎可以作为 Zig 直接替代品的语言。这意味着内存模型必须相同(没有垃圾回收,没有 RAII),它需要能编译成 WASM(为了支持模组),它必须足够快(显然,我们是在做游戏),而且编译速度要快。
Preferrably it also would be somewhat easy for other people to pick up, and while I am personally quite fond of the Zig syntax, going with a C-derived language like C3 makes a lot of sense for attracting modders in the future.
最好它还能让其他人比较容易上手。虽然我个人非常喜欢 Zig 的语法,但选择像 C3 这样源自 C 的语言,对于未来吸引模组开发者来说是非常合理的。
Q: But what about Odin, Rust, Jai or HotNewLanguage™? A: Yes, some of those might have fit the bill too, but I went with C3. For my purposes, Zig and C3 were similar enough that almost all of the concepts used in the code could be ported over one-to-one, and I could do an almost mechanical translation of the code, which I think was the only way this port was ever going to happen.
问:那 Odin、Rust、Jai 或者那些“热门新语言”呢?答:是的,其中一些可能也符合要求,但我选择了 C3。就我的目的而言,Zig 和 C3 非常相似,代码中使用的几乎所有概念都可以一一对应地移植,我可以进行几乎机械式的代码转换,我认为这是实现这次移植的唯一途径。
Let’s see what the new code looks like, by grabbing a few pieces from a random game component:
让我们看看新代码是什么样子的,摘取自某个随机游戏组件的片段:
struct WireRendererComponent @Component("means.WireRendererComponent") {
GameObjectComponent context;
RenderObject renderObject;
CurvePath3D curvePath;
uint pointCount;
// Exposed properties:
WireRendererGeometryMode geometryMode @Exposed(WireRendererGeometryMode.CURVE_PATH_3D);
AllocString curveDataBlockName @Exposed("");
uint curveSampleResolution @Exposed(16);
AllocString point0Object @Exposed("");
AllocString point1Object @Exposed("");
AllocString materialRef @ExposedResourceRef(ResourceTypeID.MATERIAL, "");
}
// ...
fn void WireRendererComponent.createVisualCurvePath(&self) {
RendererPtr renderer = self.context.getRenderer();
SceneNodePtr parentNode = {};
bool createDedicatedNode = false;
GameObjectPtr gameObject = self.context.getGameObject();
self.pointCount = self.curveSampleResolution;
MeshGeometryPtr geometry = mesh_geometry::newGeometry();
defer geometry.deinit();
MeshGeometryLodLevelPtr lod0 = geometry.addLodLevel();
MeshGeometrySubMeshPtr subMesh = lod0.addSubMesh(VERTEX_FORMAT_TYPE);
self.generateIndicesCurvePath(subMesh);
self.generateGeometryCurvePath(subMesh);
MeshSource meshSource = { .kind = MeshSourceKind.MESH_GEOMETRY_IMMUTABLE, .meshGeometry = geometry };
self.renderObject.init(
renderer, RenderObjectInstanceType.IMMOVABLE, meshSource,
self.materialRef.str(), parentNode, createDedicatedNode, gameObject);
}
C3 supports annotations, both built-in and user-specified, and we are using a few above. Tagging a struct with @Component now makes the game engine treat it as a game object component. Exposed properties, ie. fields you want to show up in the level editor inspector, are just normal fields with @Exposed (or one of its variants) at the end, and the engine handles the rest.
C3 支持内置和用户自定义的注解,我们在上面使用了一些。用 @Component 标记一个结构体,现在可以让游戏引擎将其视为游戏对象组件。暴露的属性(即你希望在关卡编辑器检查器中显示的字段)只是带有 @Exposed(或其变体)后缀的普通字段,剩下的工作由引擎处理。
Overall, the code is pretty similar to C#, or even C++. The most obvious new thing is probably the fn at the start of the function signature. You can see that C3 supports defer just like Zig, so much of the lifetime management and scoping was just a straight copy-paste. In fact, much of the code inside createVisualCurvePath() is literally the same as it is in Zig.
总的来说,这段代码与 C# 甚至 C++ 非常相似。最明显的新东西可能是函数签名开头的 fn。你可以看到 C3 和 Zig 一样支持 defer,所以大部分生命周期管理和作用域处理只是简单的复制粘贴。事实上,createVisualCurvePath() 内部的大部分代码与 Zig 中的代码完全相同。
C3 is also similar to Zig in the sense that it is explicit about many things. There is no RAII, but C3 offers temporary memory pools as a built-in thing, which is nice. Also, you can overload operators for things like math types, so we can do stuff like this:
C3 在许多方面与 Zig 相似,即它对很多事情都非常明确。它没有 RAII,但 C3 内置了临时内存池,这很不错。此外,你可以为数学类型等重载运算符,所以我们可以这样做:
// If we have turned to roughly face the target point, or turned almost 180 degrees, we are done.
Vec3 vehicleToTarget = (self.targetPoint - currentPosition).normalized();
bool reverseTurnComplete = vehicleToTarget.dot(currentForwardDir) > THRESHOLD || angleDiff < -THRESHOLD;
How was the porting done? To be honest, I can’t imagine a better codebase than Traction Point for doing a rewrite like this. Some of you might remember that we already took a look at C3 almost a year ago during a live stream. I’d been experimenting with making it possible to mod the game in different languages by compiling the mods to WASM and running them in a WebAssembly runtime. Thanks to this, one could already do some basic things in C3 back then, and it served as an excellent starting point for the porting work. The first order of business was to expand the modding SDK for C3 enough to build and run the flying scout example mod. I can’t stress enough what a luxury i
移植是如何完成的?老实说,我无法想象还有比《Traction Point》更适合进行这种重写的代码库了。你们中有些人可能还记得,大约一年前我们在直播中已经了解过 C3。我一直在尝试通过将模组编译为 WASM 并在 WebAssembly 运行时中运行,来实现用不同语言为游戏制作模组。多亏了这一点,当时人们已经可以用 C3 做一些基本的事情,这为移植工作提供了一个极好的起点。首要任务是扩展 C3 的模组 SDK,使其足以构建和运行飞行侦察兵(flying scout)示例模组。我怎么强调这种奢侈都不为过……