Remix.run Logo
The gold standard of optimization: A look under the hood of RollerCoaster Tycoon(larstofus.com)
214 points by mariuz 7 hours ago | 74 comments
netcoyote an hour ago | parent | next [-]

Warcraft 1 (1994), Warcraft 2 (1995), and StarCraft (1998) all use power-of-2 aligned map sizes (64 blocks, 128 blocks, and 256 blocks) so the shift-factor could be pre-computed to avoid division/multiplication, which was dang slow on those old 386/486 computers.

Each map block was 2x2 cells, and each cell, 8x8 pixels. Made rendering background cells and fog-of-war overlays very straightforward assembly language.

All of Warcraft/etc. had only a few thousand lines of assembly language to render maps/sprites/fonts/fog-of-war into the offscreen buffer, and to blit from the offscreen buffer to the screen.

The rest of the code didn't need to be in assembly, which is too time-consuming to write for code where the performance doesn't matter. Everything else was written in portable assembler, by which I mean C.

Edit:

By way of comparison, Blackthorne for Super Nintendo was all 85816 assembly. The Genesis version (Motorola 68000) and DOS version (Intel 80386) were manually transcribed into their respective assembly languages.

The PC version of Blackthorne also had a lot of custom assembler macros to generate 100K of rendering code to do pixel-scrollable chunky-planar VGA mode X (written by Bryan Waters - https://www.mobygames.com/person/5641/bryan-waters/).

At Blizzard we learned from working on those console app ports that writing assembly code takes too much programmer time.

Edit 2:

I recall that Comanche: Maximum Overkill (1992, a voxel-based helicopter simulator) was written in all assembly in DOS real mode. A huge technical feat, but so much work to port to protected mode that I think they switched to polygon-rendering for later versions.

maxglute 11 minutes ago | parent | prev | next [-]

Is there a place to find stories of recent game optimization? What's most ridiculous on like quick inverse square route. As someone who spent way too much time vraying in prior life, I still can't believe we got real time ray tracing.

applfanboysbgon 5 hours ago | parent | prev | next [-]

> Imagine a programmer asking a game designer if they could change their formula to use an 8 instead of a 9.5 because it is a number that the CPU prefers to calculate with. There is a very good argument to be made that a game designer should never have to worry about the runtime performance characteristics of binary arithmetic in their life, that’s a fate reserved for programmers

Numeric characteristics are absolutely still a consideration for game designers even in 2026, one that influences what numbers they use in their game designs. The good ones, anyways. There are, of course, also countless bad developers/designers who ignore these things these days, but not because it is free to do so; rather, because they don't know better, and in many cases it is one of many silent contributing factors to a noticeable decrease in the quality of their game.

cogman10 3 hours ago | parent | next [-]

> Numeric characteristics are absolutely still a consideration for game designers even in 2026, one that influences what numbers they use in their game designs. The good ones, anyways.

I used to think like this, not anymore.

What convinced me that these sort of micro-optimizations just don't matter is reading up on the cycle count of modern processors.

One a Zen 5, Integer addition is a single cycle, multiplication 3, and division ~12. But that's not the full story. The CPU can have 5 inflight multiplications running simultaneously. It can have about 3 divisions running simultaneously.

Back in the day of RCT, there was much less pipelining. For the original pentium, a multiplication took 11 cycles, division could take upwards of 46 cycles. These were on CPUs with 100 Mhz clock cycles. So not only did it take more cycles to finish, couldn't be pipelined, the CPUs were also operating at 1/30th to 1/50th the cycle rate of common CPUs today.

And this isn't even touching on SIMD instructions.

Integer tricks and optimizations are pointless. Far more important than those in a modern game is memory layout. That's where the CPU is actually going to be burning most it's time. If you can create and do operations on a int[], you'll be MUCH faster than if you are doing operations against a Monster[]. A cache miss is going to mean anywhere from a 100 to 1000 cycle penalty. That blows out any sort of hit you take cutting your cycles from 3 to 1.

Pannoniae 2 hours ago | parent | next [-]

This is all true but IMO forest for the trees.... For example the compiler basically doesn't do anything useful with your float math unless you enable fastmath. Period. Very few transformations are done automatically there.

For integers the situation is better but even there, it hugely depends on your compiler and how much it cheats. You can't replace trig with intrinsics in the general case (sets errno for example), inlining is at best an adequate heuristic which completely fails to take account what the hot path is unless you use PGO and keep it up to date.

I've managed to improve a game's worst case performance better by like 50% just by shrinking a method's codesize from 3000 bytes to 1500. Barely even touched the hot path there, keep in mind. Mostly due to icache usage.

The takeaway from this shouldn't be that "computers are fast and compilers are clever, no point optimising" but more that "you can afford not to optimise in many cases, computers are fast."

cogman10 2 hours ago | parent | next [-]

I actually agree with you.

My point wasn't "don't optimize" it was "don't optimize the wrong thing".

Trying to replace a division with a bit shift is an example of worrying about the wrong thing, especially since that's a simple optimization the compiler can pick up on.

But as you said, it can be very worth it to optimize around things like the icache. Shrinking and aligning a hot loop can ensure your code isn't spending a bunch of time loading instructions. Cache behavior, in general, is probably the most important thing you can optimize. It's also the thing that can often make it hard to know if you actually optimized something. Changing the size of code can change cache behavior, which might give you the mistaken impression that the code change was what made things faster when in reality it was simply an effect of the code shifting.

WalterBright 2 hours ago | parent | prev [-]

I originally got into writing compilers because I was convinced I could write a better code generator. I succeeded for about 10 years in doing very well with code generation. But then all the complexities of the evolving C++ (and D!) took up most of my time, and I haven't been able to work much on the optimizer since.

Fortunately, D compilers gdc and ldc take advantage of the gcc and llvm optimizers to stay even with everyone else.

rcxdude 2 hours ago | parent | prev [-]

Also, it's unusual for a game to be CPU bottlenecked nowadays, and if it is, it's probably more constrained on memory bandwidth than raw FLOPS.

timschmidt 5 hours ago | parent | prev | next [-]

Absolutely. I have written a small but growing CAD kernel which is seeing use in some games and realtime visualization tools ( https://github.com/timschmidt/csgrs ) and can say that computing with numbers isn't really even a solved problem yet.

All possible numerical representations come with inherent trade-offs around speed, accuracy, storage size, complexity, and even the kinds of questions one can ask (it's often not meaningful to ask if two floats equal each other without an epsilon to account for floating point error, for instance).

"Toward an API for the Real Numbers" ( https://dl.acm.org/doi/epdf/10.1145/3385412.3386037 ) is one of the better papers I've found detailing a sort of staged complexity technique for dealing with this, in which most calculations are fast and always return (arbitrary precision calculations can sometimes go on forever or until memory runs out), but one can still ask for more precise answers which require more compute if required. But there are also other options entirely like interval arithmetic, symbolic algebra engines, etc.

One must understand the trade-offs else be bitten by them.

ryandrake 3 hours ago | parent [-]

Back in the early, early days, the game designer was the graphic designer, who also was the programmer. So, naturally, the game's rules and logic aligned closely with the processor's native types, memory layout, addressing, arithmetic capabilities, even cache size. Now we have different people doing different roles, and only one of them (the programmer) might have an appreciation for the computer's limits and happy-paths. The game designers and artists? They might not even know what the CPU does or what a 32 bit word even means.

Today, I imagine we have conversations like this happening:

Game designer: We will have 300 different enemy types in the game.

Programmer: Things could be really, really faster if you could limit it to 256 types.

Game designer: ?????

That ????? is the sign of someone who is designing a computer program who doesn't understand the basics of computers.

WalterBright 2 hours ago | parent [-]

I wrote the Intellivision Mattel Roulette cartridge game back in the 1970s. It was all in assembler on a 10 bit (!) CPU. In order to get the game to fit in the ROM, you had to do every feelthy dirty trick imaginable.

exmadscientist 2 hours ago | parent | prev | next [-]

Related to that, for a consumer electronics product I worked on using an ARM Cortex-M4 series microcontroller, I actually ended up writing a custom pseudorandom number generation routine (well, modifying one off the shelf). I was able to take the magic mixing constants and change them to things that could be loaded as single immediates using the crazy Thumb-2 immediate instructions. It passed every randomness test I could throw at it.

By not having to pull in anything from the constant pools and thereby avoid memory stalls in the fast path, we got to use random numbers profligately and still run quickly and efficiently, and get to sleep quickly and efficiently. It was a fun little piece of engineering. I'm not sure how much it mattered, but I enjoyed writing it. (I think I did most of it after hours either way.)

Alas, I don't think it ever shipped because we eventually moved to an even smaller and cheaper Cortex-M0 processor which lacked those instructions. Also my successor on that project threw most of it out and rewrote it, for reasons both good and bad.

lukan 4 hours ago | parent | prev | next [-]

"and in many cases it is one of many silent contributing factors to a noticeable decrease in the quality of their game"

Game designers are not so constrained anymore by the limits of the hardware, unless they want to push boundaries. Quality of a game is not just the most efficient runtime performance - it is mainly a question if the game is fun to play. Do the mechanics work. Are there severe bugs. Is the story consistent and the characters relatable. Is something breaking immersion. So ... frequent stuttering because of bad programming is definitely a sign of low quality - but if it runs smooth on the targets audience hardware, improvements should be rather done elsewhere.

scns 4 hours ago | parent | next [-]

> it is mainly a question if the game is fun to play.

10000x this. Miyamoto starts with a rudimentary prototype and asks himself this. Sadly it seems for many fun is an afterthought they try to patch in somehow.

calvinmorrison an hour ago | parent [-]

When Halo 2 (anniversary edition? ) was released there was also a video on in the game about the development. The point that always stuck with me was "you must nail that 2 seconds that will keep people playing forever". The core mechanic of that game is just excellent.

sublinear 4 hours ago | parent | prev [-]

This way of thinking has caused at least a few prominent recurring bugs I can think of.

Texture resolution mismatches causing blurriness/aliasing, floating point errors and bad level design causing collision detection problems (getting stuck in the walls), frame rate and other update rates not being synced causing stutter and lag (and more collision detection problems), bad illumination parameters ruining the look they were going for, numeric overflow breaking everything, bad approximations of constants also breaking everything somewhere eventually, messy model mesh geometry causing glitches in texturing, lighting, animation, collision, etc.

There's probably a lot more I'm not thinking of. They have nothing to do "with the hardware", but the underlying math and logic.

They're also not bugs to "let the programmer figure out". Good programmers and designers work together to solve them. I could just as easily hate on the many criminally ugly, awkward, and plain unfun games made by programmers working alone, but I'll let someone else do that. :)

WalterBright 2 hours ago | parent | next [-]

> getting stuck in the walls

I remember the early Simpsons video game. Sometimes, due to some bug in it (probably a sign error), you could go through the walls and see the rendered scenery from the other side. It was like you went backstage in a play. It would have made a great Twilight Zone episode!

lukan 4 hours ago | parent | prev [-]

Game designer != game engine designer

(But it definitely helps if the game designer knows of the technical limits)

sublinear 4 hours ago | parent [-]

Sorry, I'm not super familiar with professional game dev, but I am familiar with professional web dev. The problems seem similar, as evidenced by the constant complaining here on HN about the state of the web.

Who formats or cleans up the assets and at least oversees that things are done according to a consistent spec, process, and guidelines? Is that not a game designer or someone under their leadership?

I think in all the cases I gave, what might be completely delegated to "engine design" really should be teamwork with game design and art direction too. This is what the top-level comment was talking about. Even when a game is "well made", they just adopted someone else's standards and that sucks all the soul out of it. This is a common problem in all creative work.

(adding this due to reply depth): Coordination is a big aspect of design and can often be the most impactful to the result.

lukan 4 hours ago | parent [-]

It depends how big the studio is, but a job of a game designer is usually not cleaning up assets. It is to well, design the game. The big picture.

lifis 3 hours ago | parent | prev | next [-]

That makes no sense since multiplication has been fast for the last 30 years (since PS1) and floating point for the last 25 years (since PS2) and anyway numbers relevant for game design are usually used just a few times per frame so only program size matters, which has not been significantly constrained for the last 40 years (since NES)

WalterBright 2 hours ago | parent | prev | next [-]

I remember the older driving games. They'd progressively "build" the road as you progressed on it. Curves in the road were drawn as straight line segments.

Which wasn't a problem, but it clearly showed how the programmers improvised to make it perform.

rkagerer 2 hours ago | parent | prev | next [-]

Now that's what being a full stack programmer really means.

edflsafoiewq 5 hours ago | parent | prev [-]

Examples?

mort96 4 hours ago | parent | next [-]

I think Minecraft's lighting system is a good example: there are 16 different brightness levels, from 0 to 15. This allows the game to store light levels in 4 bytes per block.

Similarly, redstone has 16 power levels: 0 to 15. This allows it to store the power level using 4 bits. In fact, quite a lot of attributes in Minecraft blocks are squeezed into 4 bits. I think the system has grown to be more flexible these days, but I'm pretty sure the chunk data structure used to set aside 4 bits for every block for various metadata.

And of course, the world height used to be at 255 blocks. Every block's Y position could be expressed as an 8-bit integer.

A voxel game like that is a good example of where this kind of efficiency really matters since there's just so much data. A single 1616256 chunk is 65.5k blocks. If a game designer says they want to add a new light source with brightness level 20, or a new kind of redstone which can go 25 blocks, it might very well be the right choice to say no.

tosti 3 hours ago | parent [-]

I don't think Minecraft would be considered a cornerstone of optimal programming.

helterskelter 2 hours ago | parent | next [-]

The 4 bit stuff is a hangover from Mojang having to squeeze every bit of perf from their Java based engine that they could. Their original sound engine was so sketchy that C418's (music composer) minimalist sound is partly because it really couldn't handle much more than what got released.

MS has been loosening up on the 4 bits limit and have created a CPP variant of Minecraft which performs better, but they've also introduced their unified login garbage that has almost made me give up Minecraft completely.

Pannoniae 2 hours ago | parent [-]

Hey, this isn't entirely accurate!

The 4-bit stuff is a hangover from Notch doing this (I'd maybe even say a similar-calibre programmer to Chris Sawyer...). The sound has nothing to do with technical limits, that's a post-facto rationalisation.

The game never played midi samples, it was always playing "real" audio. The style was an artistic choice, many similar retro-looking games were using chiptune and the sorts. It's a deliberate juxtaposition...

The CPP variant doesn't really perform better anymore either.

helterskelter an hour ago | parent [-]

Fair enough, I mostly meant to point out some of those design decisions predate MS, as much as I love to hate on them. The music was just an interesting bit of trivia I read the other day.

Pannoniae 13 minutes ago | parent [-]

Yeah, 100% :) Ironically, the design constraints are one of the big things which made it work so much! If it was designed in a "traditional" way, it would have been much less ambitious.

mort96 an hour ago | parent | prev | next [-]

Minecraft is, and always has been, handling vast amounts of data at pretty good performance. It's not an impossibly difficult task, many other people have made voxel game engines which are better, but it's something you can't do without paying attention to these things. Every voxel engine with remotely reasonable performance needs to carefully count bits used per block.

kulahan 2 hours ago | parent | prev [-]

The entire program doesn't need to be a cornerstone of optimal programming for this one example to hold true.

andai 5 hours ago | parent | prev | next [-]

https://en.wikipedia.org/wiki/Nuclear_Gandhi

From what I heard, there was a Civilization game which suffered from an unsigned integer underflow error where Gandhi, whose aggression was set to 0, would become "less aggressive" due to some event in the game, but due to integer underflow, this would cause his aggression to go to 255, causing him to nuke the entire map.

The article says this was just an urban legend though. Well, real or not, it's a perfect example of the principle!

luaKmua 5 hours ago | parent [-]

Indeed an urban legend. Sid Meier himself debunked in his memoir, which is a pretty great read.

hcs 5 hours ago | parent | prev | next [-]

Not the same thing but I was reminded of a joke about the puzzle game Stephen's Sausage Roll:

> I have calculated the value of Pi on Sausage Island and found it to be 2.

https://web.archive.org/web/20240405034314/https://twitter.c...

bombcar 3 hours ago | parent | prev | next [-]

Read all of the Factorio Friday Facts https://factorio.com/blog/ - a number of the more obscure bug/performance issues come down to making something fit naturally into a value the CPU can handle.

plopz 3 hours ago | parent | prev | next [-]

One of the main issues with Kerbal Space Program is instability caused by floating point numbers. I know Starcraft 2 was built upon integers.

Gigachad 3 hours ago | parent [-]

Floating point issues are less a problem of performance here but one of precision. Particularly being a space game, the coordinates can be massive resulting in the precision deteriorating enough to cause issues.

Waterluvian 5 hours ago | parent | prev | next [-]

Not really an example that proves any point, but one that comes to mind from a 20-year-old game:

World of Warcraft (at least originally) encoded every item as an ID. To keep the database simple and small (given millions of players with many characters with lots of items): if you wanted to permanently enchant your item with an upgrade, that was represented essentially as a whole new item. The item was replaced with a different item (your item + enchant). Represented by a different ID. The ID was essentially a bitmask type thing.

This meant that it was baked into the underlying data structures and deep into the core game engine that you could never have more than one enchant at a time. It wasn't like there was a relational table linking what enchants an item in your character's inventory had.

The first expansion introduced "gems" which you could socket into items. This was basically 0-4 more enchants per item. The way they handled this was to just lengthen item Ids by a whole bunch to make all that bitmask room.

I might have gotten some of this wrong. It's been forever since I read all about these details. For a while I was obsessed with how they implemented WoW given the sheer scale of the game's player base 20 years ago.

ErroneousBosh 4 hours ago | parent | prev [-]

Going way back into history, the Alesis MIDIVerb reverb unit had a really simple DSP core made out of discrete logic chips. It could add a memory location to an accumulator and divide it by two, invert it, add it and divide it by two, or store it in ram either inverted or not and divide the accumulator by two.

Four instructions, in about eight chips.

By combining shifts and adds Keith Barr was able to devise all the different filter and delay coefficients for 63 different reverb programs (the 64th one was just dead passthrough).

youarentrightjr 4 hours ago | parent | prev | next [-]

> The same trick can also be used for the other direction to save a division: NewValue = OldValue >> 3; This is basically the same as NewValue = OldValue / 8; RCT does this trick all the time, and even in its OpenRCT2 version, this syntax hasn’t been changed, since compilers won’t do this optimization for you.

(emphasis mine)

Not at all true. Assuming the types are such that >> is equivalent to /, modern compilers will implement division by a power of two as a shift every single time.

evandale 18 minutes ago | parent | prev | next [-]

The pathfinding section reminded me that there's a YouTube steamer, Marcel Vos, who goes into a deep dive of how the pathfinding works.

https://youtu.be/twU1SsFP-bE

He has lots of videos that are deep dives into how RCT works and how things are implemented!

troad an hour ago | parent | prev | next [-]

> When reading through OpenRCT2’s source, there is a common syntax that you rarely see in modern code, lines like this:

> NewValue = OldValue << 2;

I disagree with the framing of this section. Bit shifts are used all the time in low-level code. They're not just some archaic optimisation, they're also a natural way of working with binary data (aka all data on a computer). Modern low-level code continues to use lots of bit shifts, bitwise operators, etc.

Low-level programming is absolutely crucial to performant games. Even if you're not doing low-level programming yourself, you're almost certainly using an engine or library that uses it extensively. I'm surprised an article about optimisation in gaming, of all things, would take the somewhat tired "in ye olde days" angle.

Rendello 14 minutes ago | parent [-]

I learned these low-level bit tricks by reading TempleOS' HolyC source code. I remember feeling like a genius when I worked out what this line does:

dc->color=c++&15;

Hint: it's from this "Lines" demo program, whose source is here: https://web.archive.org/web/20180906060723/https://templeos....

And this is what it looks like when it runs (ignore the fact it's running in Minecraft): https://youtu.be/pAN_Fza6Vy8?t=38

HelloUsername 6 hours ago | parent | prev | next [-]

Fun read, thx! I'd also recommend more about RCT:

"Interview with RollerCoaster Tycoon's Creator, Chris Sawyer (2024)" https://news.ycombinator.com/item?id=46130335

"Rollercoaster Tycoon (Or, MicroProse's Last Hurrah)" https://news.ycombinator.com/item?id=44758842

"RollerCoaster Tycoon at 25: 'It's mind-blowing how it inspired me'" https://news.ycombinator.com/item?id=39792034

"RollerCoaster Tycoon was the last of its kind [video]" https://news.ycombinator.com/item?id=42346463

"The Story of RollerCoaster Tycoon" https://www.youtube.com/watch?v=ts4BD8AqD9g

fweimer 6 hours ago | parent | prev | next [-]

What language is this article talking where compilers don't optimize multiplication and division by powers of two? Even for division of signed integers, current compilers emit inline code that handles positive and negative values separately, still avoiding the division instruction (unless when optimizing for size, of course).

shakow 5 hours ago | parent | next [-]

That's what I would have thought as well, but looks like that on x86, both clang and gcc use variations of LEA. But if they're doing it this way, I'm pretty sure it must be faster, because even if you change the ×4 for a <<2, it will still generate a LEA.

https://godbolt.org/z/EKj58dx9T

shaggie76 4 hours ago | parent | next [-]

Not only is LEA more flexible I believe it's preferred to SHL even for simple operations because it doesn't modify the flags register which can make it easier to schedule.

adrian_b 4 hours ago | parent | prev [-]

They use LEA for multiplying with small constants up to 9 (not only with powers of two, but also with 3, 5 and 9; even more values could be achieved with two LEA, but it may not be worthwhile).

For multiplying with powers of two greater or equal to 16, they use shift left, because LEA can no longer be used.

cjbgkagh 5 hours ago | parent | prev [-]

It was written in assembly so goes through an assembler instead of a compiler.

rawling 4 hours ago | parent [-]

I assume GP is talking about the bit in the article that goes

> RCT does this trick all the time, and even in its OpenRCT2 version, this syntax hasn’t been changed, since compilers won’t do this optimization for you.

cjbgkagh 3 hours ago | parent [-]

That makes more sense, I second their sentiment, modern compilers will do this. I guess the trick is knowing to use numbers that have these options.

bombcar 3 hours ago | parent [-]

There was a recent article on HN about which compiler optimizations would occur and which wouldn't and it was surprising in two ways - first, it would make some that you might not expect, and it would not make others that you would - because in some obscure calling method, it wouldn't work. Fixing that path would usually get the expected optimization.

bluelightning2k 4 hours ago | parent | prev | next [-]

Great write up. Thank you. Really great!

I was reminded of the factorio blog. That game's such a huge optimization challenge even by today's standards and I believe works with the design.

One interesting thing I remember is if you have a long conveyor belt of 10,000 copper coils, you can basically simplify it to just be only the entry and exit tile are actually active. All the others don't actually have to move because nothing changes... As long as the belts are fully or uniformly saturated. So you avoid mechanics which would stop that.

plopz 3 hours ago | parent [-]

I was pretty disappointed with how Factorio reworked how fluids worked in the expansion. The old system had its quirks and the new system is obviously more performant, but it throws realism out the window which is a bummer.

Cpoll 13 minutes ago | parent | next [-]

I don't miss it. I also found Satisfactory's old fluid system (with concepts like sloshing) wildly unintuitive. I'll go so far as to say that accurate fluid dynamics is detrimental to any game that's not about beavers and water table management.

Starlevel004 2 hours ago | parent | prev [-]

The old system was nonfunctional and any base that used lots of fluids (like modded ones, or new space age ones) were constantly running up against nonsensical mechanics.

sroerick 6 hours ago | parent | prev | next [-]

I had always heard about how RCT was built in Assembly, and thought it was very impressive.

The more I actually started digging into assembly, the more this task seems monumental and impossible.

I didn't know there was a fork and I'm excited to look into it

kevincox 3 hours ago | parent | next [-]

Programming in assembly isn't really "hard" it mostly takes lots of discipline. Consistency and patterns are key. The language also provides very little implicit documentation, so always document which arguments are passed how and where, what registers are caller and callee saved. Of course it is also very tedious.

Now writing very optimized assembly is very hard. Because you need to break your consistency and conventions to squeeze out all the possible performance. The larger "kernel" you optimize the more pattern breaking code you need to keep in your head at a time.

markus_zhang an hour ago | parent | prev | next [-]

Back then a lot of people started with assembly because that was the only way to make games quick enough. Throughout the years they accumulated tons of experience and routines and tools.

Not saying that it was not a huge feat, but it’s definitely a lot harder to start from scratch nowadays, even for the same platform.

mikkupikku 5 hours ago | parent | prev [-]

Macros. Lots of macros.

cogman10 2 hours ago | parent | next [-]

Yup. I've done a bit of assembly and it's really only a little harder than doing C. You simply have to get familiar with your assembler and the offered macros. Heck, I might even say that it's simpler than basic.

timschmidt 5 hours ago | parent | prev [-]

And presumably generous use of code comments

MisterTea 2 hours ago | parent | prev | next [-]

While it has been a while since playing RCT, one thing that was really nice about the game is that it runs flawlessly under Wine.

I really wish I could see the source code.

lefty2 5 hours ago | parent | prev | next [-]

> The same trick can also be used for the other direction to save a division:

> NewValue = OldValue >> 3;

You need to be careful, because this doesn't work if the value is negative. A

whizzter 4 hours ago | parent | next [-]

Most CPU's has signed and unsigned right shift instructions (left shift is the same), so yes it works (You can test this in C by casting a signed to unsigned before shifting).

The biggest caveat is that right shifting -1 still produces -1 instead of 0, but that's usually fine for much older game fixed-point maths since -1 is close enough to 0.

adrian_b 3 hours ago | parent | prev [-]

It works fine when the value is negative.

However, there is a quirk of the hardware of most CPUs that has been inherited by the C language and by other languages.

There are multiple ways of defining integer division when the dividend is not a multiple of the divisor, depending on the rounding rule used for the quotient.

The 2 most frequently used definitions is to have a positive remainder, which corresponds to rounding the quotient by using the floor function, and to have a remainder of the same sign with the quotient, which corresponds to rounding the quotient by truncation.

In most CPUs, the hardware is designed such that for signed integers the division instruction uses the second definition, while the right shift uses the first definition.

This means that when the dividend is a multiple of the divisor, division and right shift are the same, but otherwise the quotient may differ by one unit due to different rounding rules.

Because of this, compilers will not replace automatically divisions with right shifts, because there are operands where the result is different.

Nevertheless, the programmer can always replace a division by a power of two with a right shift. In all the programs that I have ever seen, either the rounding rule for the quotient does not matter or the desired definition for the division is the one with positive remainder, i.e. the definition implemented by right shift.

In those cases when the rounding rule matters, the worrisome case is when you must use division not when you can use right shift, so you must correct the result to correspond to rounding by floor, instead of the rounding by truncation provided by the hardware. For this, you must not use the "/" operator of the C language, but one of the "div" functions from "stdlib.h", or you may use "/" but divide the absolute values of the operands, after which you compute the correct signed results.

londons_explore 5 hours ago | parent | prev | next [-]

> it turns an optimization done out of technical necessity into a gameplay feature

And this folks is why an optimizing compiler can never beat sufficient quantities of human optimization.

The human can decide when the abstraction layers should be deliberately broken for performance reasons. A compiler cannot do that.

nulltrace 3 hours ago | parent | next [-]

The LEA-vs-shift thread here kind of proves the point. Compilers are insanely good at that stuff now. Where they completely fall short is data layout. I had a message parser using `std::map<int, std::string>` for field lookup and the fix was just... a flat array indexed by tag number. No compiler is ever going to suggest that. Same deal with allocation. I spent a while messing with SIMD scanning and consteval tricks chasing latency, and the single biggest win turned out to be boring. Switched from per-message heap allocs to a pre-allocated buffer with `std::span` views into the original data. ~12 allocations per message down to zero. Compiler will optimize the hell out of your allocator code, it just won't tell you to stop calling it.

timschmidt 5 hours ago | parent | prev | next [-]

Agreed. It really requires an understanding of not just the software and computer it's running on, but the goal the combined system was meant to accomplish. Maybe some of us are starting to feed that sort of information into LLMs as part of spec-driven development, and maybe an LLM of tomorrow will be capable of noticing and exploiting such optimizations.

gwern 3 hours ago | parent | prev [-]

End-to-end optimization in action! Although I'd've liked more than 1 example (pathfinding) here.

sghiassy 4 hours ago | parent | prev | next [-]

Another great optimization is storing the year as two digits, because you only need the back half…

… oh wait, nvm. Don’t preoptimize!

seba_dos1 3 hours ago | parent [-]

There's a vast space between premature optimization and not caring about optimization until it bites you, and both extremes make you (or someone else) miserable.

ZebusJesus 3 hours ago | parent | prev [-]

so I don't thin the rust people are gonna be happy with non memory safe assembly