Most Normal C++ Project: Coding a B2 Stealth Bomber in GTA 3
Comments
Transcript
Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.
Yes, this is me flying around in a B2 stealth bomber in GTA 3. And Mr. Salvatorei Leone is about to find out why Liberty City has no free healthcare. And all of this before GTA 6. In the past, I've analyzed many coding projects. We dived into the code of games like Doom, Quake, Duke Nukem, and many other classics. My goal in the code review series was to give you an understanding of how these game engines work under the hood. And now I decided to start a new series where we go beyond code reviews and start implementing new systems or features into existing projects and also start creating useful new projects of our own from scratch.
And I'm not talking about the color picker or I don't know a to-do app. The core idea of this series is how to approach a big problem with real software engineering methods. not only from a tool chain perspective, but also from a methodical one. And it's not about which IDE you're going to use or I don't know color theme, but how you build systems that help you solve complex problems. This is the first video in the series. And just like in my code review series, I'm going to raise the complexity with every new video. Now, before we continue, I want to say a big thank you to my patronons and YouTube members for helping me create these videos. If you want to get your name on this wall of fame, there's a Patreon link in the description [music] or you can become a YouTube member. A quick disclaimer, this video is for educational purposes only. So today, we're going to do the following. First, we're going to build a RE3 project and get the game running. Then we're going to start creating a development environment that will help us iterate [music] faster. Along the way, we will fix some platform related issues and event polling problem that causes a CPU spike, the camera screen scaling, and we're going to add some telemetry for monitoring the in-game values. Once the development environment is stable, we will start fixing the physics of the dodo plane so we can fly around. Then we're going to add a new aircraft, the B2 stealth bomber with its own blender model, its own flight profile, collision, and a feature to drop bombs.
And finally, we're going to wrap it up with some solid conclusion.
So, the first step was getting the game. And you know how they say if buying isn't owning, then piracy is, come on, bro. Just buy it off eBay. I got this for like seven bucks and now I got GTA 3
forever. Okay, just buy the CD. The second problem was I had zero experience with Blender. So I had to learn Blender by the time I'm done fixing all the code related issues. But let's first get the game running. So before making any changes to any code base, rule number one is do no harm. So don't start
running around just to look busy. Okay, second rule is establish whether the software actually works as intended because the real problem happens when you assume that something works without actually checking it and then you start making changes and you spend hours running in circles trying to understand how your change broke the game only to realize that it never worked in the first place. So in our case, let's start with how is the game even split. If you have watched all my videos, congratulations. You already know that games are usually split into two parts. The engine and the game assets. Oversimplified. The engine loads those assets, takes input, and turns it into well game play. So, the first question is, can we build the engine, connect it to the original assets, and run the game? Now, let's start working. Since we have the game assets from the actual game, we can start installing the dependencies needed for the Mac OS build. Pre-make to generate the build files. GLF for the window and input layer. Open soft for the game audio and
lip SND file and MPG123
for decoding audio files. The project also uses lib RW which is the open- source reimplementation of the renderer library but it is already included as a git subm module so we don't need to install that. Now we can generate the build files and compile. Just as a side note I'm doing this purposefully on a Mac
and it works. The build produces a RE3
binary and now if you run it of course nothing will happen. you still need the game files. So, you place the binary in the folder where you install GTA and run it. If you are born anywhere past the middle line in Europe, you have done this a million times as a kid. And for a certain period of time, I legit thought that this is the like procedure how you install games. You know what I'm talking about. Anyways, you can then launch the game and it runs. That is our hello world. The engine builds, finds the original assets, opens the game, and does not immediately crash. This is our first base. The second base is, does it actually work? I mean, can you play it?
And what I already notice is I see the mouse. It has the GTA cursor, but I can't click anything. I mean, I can click, but the click doesn't register as input. Obviously, the arrow keys seem to work. And so yes, when I press enter, it also works. So this is a mouse input issue.
So let's try to fix it. If you watch some of my other videos, for example, the Doom video, you remember how I talked about having multiple abstraction layers and how a mouse click is input.
It is read somewhere, then translated into a command. The command becomes an event. the event gets into the event queue and then the engine processes it and something happens. Now when you have this type of issue, the mouse click not working, the problem can be anywhere in this chain with some basic common sense
which is a true skill today. You can already eliminate some layers. So since my mouse is working per se and I can see the pointer moving inside the GTA window, I can eliminate the most basic hardware problem, the screen is also displaying the game and the cursor correctly. So this is not a general display failure. Then because the arrow keys and enter work, I know the game can receive at least one kind of input and turn it into an event. This of course does not prove that the entire input system works flawlessly. It only narrows down the problem. So I assume that something in the mouse specific path is failing before the click becomes an event. I also can't rotate the camera in game with the mouse. So it's not only the click but more generally the mouse input. The game is either not reading the mouse state, not processing it correctly, or the menu and camera are both interpreting it incorrectly. I'm not that familiar with the codebase. I mean, I made a video like a year ago, but I can't tell you by hardware to look. So, let's open source dive and search for mouse. If you don't know, source dive is an extension I developed for VS Code. You can get it for free on the marketplace or open VSX registry.
And it also works on VS Codium. So we get some results and this looks very promising. Cpad update mouse. Cpad is
something like control pad I guess. Now inside Cpad update mouse we can see GLFW
get cursor position and GLFW get mouse
button. This is where GLFW enters the
story. GLFW is the portability layer
used by this project this port to ask Mac OS for window and input state without putting Mac OS specific code everywhere in the engine. So the concrete path now looks like this. Mac OS GLFW cpad update mouse menu and
camera. And now if you take a look at this, the whole block here that reads the mouse input, the cursor movement and mouse buttons is guarded by this condition here is foreground app and PS
global cursor is in window. The first part asks whether GTA is the active application, which makes sense. The game should not control the camera while I'm clicking inside another window. And the second part checks whether the cursor is inside the game window through cursor is in window. Now if we are right and this
is the location where the thing breaks we can just set a break point and investigate what goes wrong in this chain of events. So before we start debugging my tool chain looks like this. I'm running off Mac OS. I use the LDB debugger and the code LLDB extension for VS code and we are using apple clang as the compiler on a Linux I would obviously use a different tool chain I use GDB and whatever is available at the moment. I mean the debugger back end can change but the investigation stays the same and I specifically picked Mac OS for this project for various reasons and I'm going to talk about this in a minute. Okay. And now instead of randomly stepping through the entire menu, I place one break point on this condition. Launch the game and add both
expressions to the watch panel.
The first condition is true. So the application correctly knows that it is in the foreground. But the second condition is false. So it believes the cursor is outside the window. Because of that, the valid mouse input reads below this gate never run. The menu and camera
do not receive any mouse data at all. I'm wondering if the game thinks the cursor is outside, why the hell can I still see the cursor moving through the menu? I mean, it also looks like the GTA cursor, right? So let's search for
cursor is in window. That leads us into
the glffw window code. Here we have two
separate callbacks. Cursor call back
receives ordinary cursor movement and writes the visible menu coordinates directly. Cursor enter call back updates
cursor is in window but only when GLFW
reports that the pointer entered or left the window. Okay, that explains it. So
the cursor movement and the click polling do not travel through the same route. The movement call back can keep drawing the menu cursor while the false cursor is in window flag prevents this
update mouse from reading the mouse input. Now if you take a look at the initialization of the flag, you can see it starts as false. So the only place that changes it is the cursor enter call back. And this is the actual platform assumption that breaks on Mac OS in full screen. If the cursor is captured, the pointer already belongs to the game when the window starts. It can't cross the
window border anymore. So there is no new the cursor just entered event. And
this flag remains false forever. Okay, if this is all abstract for you, the easiest way to think about it is this. The code is trying to answer is a person currently inside a room by checking whether somebody saw them walk through the door. But the person was already inside the room and the door is locked. So by just looking at if someone came in
is not really addressing the question. So how we going to fix this? So I'm not going to obviously hardcode the flag now to true because then the game could read the mouse while another application is active. So I keep the foreground check and I start adding new conditions in here. For example, for the hovering or
asking is the cursor captured. So let's start with the cursor is captured. So we define a bool cursor is captured
and then we use the glffw get input mode
window cursor w cursor disabled and then
we define another one for when the cursor is hovered. So all cursor is
hovered get window attribute ps global. So we
select the window and then GLFW
powered equals GLFW true. Okay. And now
we need to add these two conditions to our check. So if foreground app is true
and if any of these three conditions is true then we can read the mouse input.
Okay. So if the cursor is in window, if it's hovered or if it's captured, this
condition shall be true and we should enter this block. Now one important thing to mention is that we haven't changed the original cursor enter state, the original condition. We have just added two new conditions to this thing. Okay, the foreground protection stays exactly where it was. And now we can rebuild it and test it. And we should be able to now enter the game and start clicking and rotate the camera and so on. Okay, after building it, we launch it and it works perfect. Now, hear me
out. Listen, you can of course fix this issue in many different ways. And for anyone thinking if you just use Linux, you wouldn't have any of these issues. You're right. But I picked Mac OS intentionally because I was hoping it will not work out of the box. And this is an extremely trivial example of course. I mean fixing the mouse. Come on. But listen, one of the best exercises to get better at software engineering out there is taking a piece of software and porting it to another platform. making the code run on a piece of hardware that was never intended to be run on in the first place, especially if there are very limited resources on it online, like if nobody ever done it before. Doing this will teach you how computers work under the hood. You will learn much more than just doing another same tutorial over and over again. And this is the number one advice I would give to my younger self when it comes to software engineering because I learned the most when I was doing exactly that on my first job. They basically threw a
30-year-old piece of legacy code at me and told me like make it run on this new microcontroller. There was no chat GPT. There was almost no documentation. I just had some data sheets and that was it. And I don't know if I'm the only person who feels this, but there's a weird satisfaction in getting a piece of software running somewhere it was never intended to run. And I'm not talking specifically about GTA 3 on Mac OS. Come on, this port already works properly. So there is not that much left to fix. I'm talking about the act in general, like taking some code, porting it to an obscure piece of hardware, and finally seeing it run there. Okay, so we have proved that our binary can run against original game data, but this is still not an efficient development environment.
The current development loop would look like this. We change the code. Then we compile it. We launch the game, sit through the startup, load into the world, travel to some, I don't know, test area, find the dodo plane, and finally test one change. And that loop
is about as expensive as it gets. What we want is a fast iteration loop with little overhead as possible. And ideally something like I make a change, build and launch the game and see the result immediately. I mean, if one small physics adjustment takes several minutes to evaluate, you don't need to have a daddy working at Blizzard to know that this is inefficient as hell. And I know
there are even more efficient approaches where you don't have to build everything. So a much better development environment would look something like this. First, the game does not run in full screen, but let's say in something like 800 pixels time 600 pixel window.
That keeps the rest of the screen free so I can watch I'm not going to say what I'm watching, but I can take a look at the code. Okay. Then, ideally, we want to skip the cinematics, cutscenes, and menus. Then I want my character to start somewhere inside a controlled testing arena with lots of space, no NPCs, and
all the vehicles and weapons that I want to test. So for example, in GTA 3, a
good candidate is the airport. Then I
also want to have some sort of reset button. So if I die or get stuck or whatever, I can press this button and then, you know, start all over again. And then I also want to keep an eye on the CPU load. So if one of my changes creates an unintentional hot path, I want to see immediately instead of stacking more work on top of it before the game becomes, you know, unplayable. Okay. And for all of these changes, I want a dedicated developer build configuration so I'm not contaminating the normal game build with my dev functionalities. Okay, so this is the game plan. Okay, so the first thing we're going to create is a separate build configuration. We're going to call it something like re3_dev.
Very creative, I know. And then we're going to put all the repeatable build work into small scripts. Now, let's start building the dev environment. The first problem is the window size. RE3 starts in full screen, but I want to have the editor, debugger, terminal, and the game visible at the same time. Now, I know windowed mode already exists. I could set window to one in the in file and resize the window with my mouse, but that's not what I want. I want the developer build to open at exactly 800x
600 every time automatically without me
having to touch anything. So, we are taking the more difficult way, but this will also help us understand how the project handles the window creation. I'm going to create a dedicated dev tools source file where we can put everything that belongs exclusively to the re3 dev
build configuration. And now I'm going to drop some elite ball knowledge when [music] it comes to investigating code. So stay with me now.
Okay. We could solve the window problem using the primitive method. search the entire code base for words like window, width, height, resolution, and video mode. For example, the problem is that games have this and heights everywhere. Cameras have them, textures have them, menus have them, the head-up display has them, and searching for something like width gives you a gazillion results. So instead of brute forcing the code base, let's take a step back and use the architecture as a clue. At the beginning of the project, we installed several dependencies and we are looking for the place where a window is created. So premake is build stuff. Open lib SND MPG are some audio
libraries. Lib renderware is the rendering layer. And that leaves us with glffw. GLFW is a windowing library and it can
do a bunch of other stuff and the developers did not install a windowing library just to create then an entire Mac OS Windows system from scratch. So
somewhere near the boundary of the program RE3 should eventually call GLFW.
And this is our first clue. A general technique for navigating code bases. Before searching for the feature itself, ask which dependency owns that feature
or which subsystem could possibly own
that feature. And the dependency name can reduce thousands of possible results to a much smaller set. Okay. The second clue is knowing that GLFW exposes a C
API. And if you're familiar with C
libraries, you know that C does not have name spaces like C++ or classes. So C
libraries commonly prefix their function names with the library name. for example, SDL create window or curl easy
in it or I don't know SSL connect and in
case of a C++ API they instead organize names through name spaces or sometimes classes and they use a double colon. So that means if GLFW owns the window, there's a very high chance that I'm looking for a function whose name starts with GLFW and contains something related to window
and ends with a function call. So that's where we're going to leverage regular expression search. And for example in VS
Code, you can do something like this. So forward slashb means start at the word boundary. GLFW is the string that we are looking for. This sequence means we are allowing more characters in the function name. Then we have this asterisk. Then we place our second string which is window. And then again we type the sequence which again allows some other words in the in the full name of the function. And then we write this and open up parenthesis. And now this regular expression reduces the search results to a small list of GLFW window
functions. And now inside lib render for example I find these two calls that look particularly relevant. So these two functions are almost identical. The important difference is the fourth argument. One call passes this monitor
and the other passes nil. Okay, we are
now very confident that this is probably the function we are looking for. Now the question is what is the meaning of these arguments and why we have here a monitor and here we have nil which is null. Why
coders don't know this but you can actually look stuff up. So if you now Google the official GLFW window guide documentation it will tell us everything that we need to know. So they have this example and it explains the arguments. So width is the requested window width. This is the height. This is the text displayed in the title bar. Monitor is used for full screen or null for a normal window. And share means another OpenGL context to share resources with or null. And the guide also shows the two relevant versions. A normal window passes null as the monitor and a full screen window passes a monitor. Now if you're wondering what is the difference between nil or null, nil is simply the null pointer value used by this codebase. So now all of this means that
the first call creates a full screen window on monitor while the second one
creates a normal desktop window. The documentation also explains something that becomes important later. For full screen, the width and height describe the desired monitor video mode. GLFW then searches for the closest mode the monitor supports. And for a normal window, they only describe the requested size of a rectangle inside the existing desktop. Now listen, this is not a live demonstration where I magically hit every nail on the head on the first try. First, I've been analyzing projects for a good while now, so with time, you develop some instincts. Second, I've already read big chunks of this codebase in my previous video. Now, I'm just showing you my mental model when approaching these type of problems. And the last thing that I want with this video or this channel in general is to give someone the impression they are too bad for coding, programming, or whatever. Don't feel bad because you're not good at something. It takes time.
And what if you're not good at something? Who cares? As long as you're interested in it, keep going. You will eventually get better like in anything in life. Okay, let's continue. So, what I'm showing you is the technique that I use to make these investigations as efficient as possible. Okay, now we know where the final window is created. But changing these arguments directly would be the wrong layer. By the time execution reaches create window, lib render has already received a selected width, height, and mode from re3.
So I place a break point on the two calls and inspect. And the break point confirms that GLFW receives the full screen dimensions and a valid monitor pointer. GLFW is therefore doing exactly what is asked to do. I need to find who
gave lib renderware that mode. Okay, so
we already established that passing a monitor pointer to glfw create window creates a full screen window and that call the width and height come from mode mode width and mode mode height. So where does this mode variable come from? If we follow now the mode variable, we will see that it gets its value from this global modes array. But who sets
this index? So if you search for this current mode followed by an equal sign, you will find that there are two similar assignments. One in the SDL implementation and one in the GLFW implementation. Since we're using GLFW, I'm going to follow this branch. Now inside this device set video mode case, current mode gets assigned N. The functions parameters show that N comes from the caller. So who is passing that
value? To find it out, let's put a break point here and restart the game and take a look at the call stack. Okay, so the call stack leads us to PS select device.
So that is where the game passes its mode. Now if you take a look at PS select device, the chosen mode is passed into renderware engine set video mode through a variable called Gcur cell VM.
This probably means game current selected video mode. Now my goal here is to find something that will lead me to the width and height parameters. So if you follow the video mode, we will see these variables prefight.
And the assumption is that these are the window height and width parameters. Right? So that gives me something specific to search for. Where does the game load pref? I'm searching now for previd to see where it gets its value. And one result is in front end where the C file manager read loads data into pref. Now if you take a look at C menu manager load settings, it opens GTA 3
set the saved settings file. And further down in low settings, there's also a call to load any settings which reads the any configuration. Okay, so we have found what we need. The display preferences are loaded before the game chooses its video mode, which means our developer settings need to go between these two steps. Okay, so for the normal game, this behavior should remain untouched. I don't want to change anything in the normal startup. But after the settings have been loaded, the developer configuration can replace them with a temporary value. So before ps
select device runs. So in the glfw file
we can write this if defaf re3 defaf and
then we can start assigning values to this front end menu manager. So press window one selected screen mode one width 800 height 600 and defaf 32. Now
in case you're wondering what are these values. So press window one means use a normal desktop window. Selected screen mode one means select the windowed screen mode. Width is 800 pixels. This is 600 pixels and 32 is the 32bit color
mode. So now the developer configuration can use the temporary window without modifying the player's normal configuration. Okay, I rebuild the game, launch RE3DEV and it immediately exits
with cannot find desired video mode.
This is not good. But uh this error is
useful because it tells us the failure happens before GLFW creates the window.
And if you search now for this exact message, it takes us back to PS select device. So I put a new break point on the failure condition in that function and then run the game again. The previous break point at GLF create window is never reached because the game fails before it gets that far. Okay. So at the break point the state looks like this. Press window true, best window
mode valid and best FS mode which is full screen mode minus one. The requested windowed mode exists. The problem is that the original selector still treats the missing full screen mode as fatal. Even though we are not asking for a full screen, right? And this is where the GLFW documentation becomes useful. Again, for a full screen window, the requested width and height describe a desired monitor video mode.
And GLFW selects the closest supported mode. But when the monitor argument is null, those same values simply describe the size of a normal desktop window. So an 800x 600 window does not need to appear in the monitor's full screen mode list which means that the selector was mixing those two cases together. So imagine it like this. We are requesting 800 by 600 but the selector is looking
for a full screen with 800 by 600. So
that's the mismatch. Okay. Now the fix is to validate and select only the mode that the game actually requested. So I replace the unconditional best full screen mode check with a decision based on what the game actually requested. First I check the prefs windowed. If it
is true I validate best windowed mode and assign it to this GU cell VM.
If it is false, I validate best full screen mode and select that instead. And that is the main fix. A windowed launch can no longer fail just because the monitor does not provide a matching full screen mode. And then there's also this
improved video mode block that also needs a small fix. So I wrapped the width, height, and depth assignments in one more window. Check. We only copy the selected monitor dimensions back into the preferences when the game is in full screen. If it is windowed, we leave our requested 800x 600 dimensions alone.
Okay. After rebuilding, RE3D finally
opens inside a 800x 600 window while the
normal executable keeps its original display configuration. But if I take a look now at this u yeah this does not look good. Our character is somewhere on
the right edge for some reason and the image looks cropped but you know we got
the Mac OS window in a correct size. I
mean this is still a big win. Now let's continue.
[music] Okay. So the window now has the correct size, but the image frame of the game
doesn't seem to fit like properly into this window. It looks enlarged. I mean, the game looks correct per se. We don't see any missing pixels, visual artifacts, like repeating sequences. The image is just bigger than the window. So for me, this looks like a frame buffer issue. Like the frame buffer is larger than the window. If I would have to draw it, it would look something like this. So you have the window, but the frame buffer holds a much bigger image and then it looks cropped out. So what we're going to do now is compare the actual window size and the frame buffer size. Now again, if you look at the documentation, GLFW provides us these two functions. Get window size and more interesting, get frame buffer. So we open the GLFW source file and after RE3 resizes the developer window. I want to get both of these values. You don't need million plugins, add-ons, scripts, test cases. A simple print f will go a long
way, my friend. So we create some variables. Window width, window height, frame buffer width, frame buffer height, and then we use the functions that the GLFW library already provides. get
window size. So, we select the window, window width, window height, and then the same for the frame buffer size.
And then we're going to just put a simple print f in there.
Now build and run it. And the output shows the mismatch. As I assumed, we have a much larger frame buffer than the window. That means before we create the window, we need to tell the frame buffer how big it has to be. Now, if you open the GLFW documentation and go to the window creation, a quick side note, knowing how to read is a big advantage when it comes to software engineering. Okay, if you read the documentation, you eventually come to this chapter, window creation hints, and it already tells us
hints are additional arguments. They can affect the window, frame buffer or context. Now, if you keep reading, you get to this GLFW scale frame buffer. And
I have already read the documentation. So, if you have the time, make yourself a coffee and read it. This specifies whether the frame buffer should be resized based on content scale changes. This can be because of a global user settings change or because the window was moved to a monitor with different scale settings. Exactly what we are looking for. Now we only need to learn how to set it. So we go to the GLFW window. Hint. Okay. Hint. And then value. So we either need to enable or disable this. I'm not sure yet. But if you read this, it sounds like we have to disable it. We don't want rescaling based on a monitor with different scale settings. So in our code, we have to set this hint before the window is created.
somewhere here for example. So if defined apple and defined re3 defaf glffw window hint scale frame buffer
false and if now when we run it we can see that the window matches the frame buffer and also the game looks how it's supposed to look. We finally have a small game window. The lesson from this is read the damn documentation. I know that reading documentation was never the most popular activity. Even before people would just copy paste solutions from Stack Overflow until something worked. But the real transition from junior dev to senior dev happens when you just turn your brain on and start reading documentation and putting all the puzzle pieces together by yourself. Fundamentals like reading the documentation or asking yourself, what am I even trying to do with this? or knowing how to break down a problem properly will always be valuable.
Instead of learning all the vim motions or I don't know setting another hotkey on your keyboard, learn how to read and write technical documentation. I know that the industry is moving towards a scenario where you can turn your brain off and just token max. But let's say for the sake of argument you are a prompt engineer, which I doubt because prompt engineers don't watch my content. They watch people reading AI articles. Even if you are a prompt engineer, whatever that means, you would be much better off if you knew how to feed your AI coding assistant with the right inputs in terms of giving it useful material to work with, useful documentation, useful sources, and useful architectural input. Anyway, I'm drifting away from the topic. So, we finally have now a working window. Now that everything looks like it's supposed to look, what I like doing is taking a look at what is happening under the hood. How high is the CPU load during idle? Why do I do this? Because when I start now changing something, if the CPU load suddenly spikes in some unexpected way, that means that I have created some suboptimal change that creates a hot path and now the engine needs to do some extra laps. Okay.
>> [music]
>> Now let's take a look at the process. So we run this. We want P state CPU time
command-p. And yeah, this does not break the game play, but I mean over 90%. Come on. So
now what we can do is we can run a profiler on this. I'm using the Apple built-in sampling profiler called sample. Then write sample. Yeah, D3
5. And then we give it a file name. The
first number tells it to observe the process for 30 seconds. The second one captures the thread st every 5 milliseconds. Think of it as taking a
thousand of quick snapshots of a worker. If almost every picture shows the same worker doing the same thing, that is where the time is going. Okay. So then we wait 30 seconds and when the command finishes I open the profiler output
and okay in other words 5,200
out of 4,400 main thread snapshots
passed through GLFW's Mac OS event
polling. That's roughly over 90% of the
samples which lines up almost perfectly with the CPU number. This is something many beginner embedded developers do. Pulse something continuously without asking whether it actually needs attention. The next question is whether GLFW itself is slow or whether RE3 is
simply calling it far too often. If you
take a look at the sample, it already gives me the source location in main. So
we open that and follow the game play branch. Okay, if you now take a look at this. So this Paul events checks the pending keyboard, mouse and window events and returns immediately. Then the frame limiter asks whether the next frame is due. If it is not, this branch
does nothing. The outer loop starts again, calls Paul events again, checks
the same clock again, and can repeat that thousands of times before one useful frame is processed. Okay, so the
profiler and the code now are telling us the same story. GLFW is not spending 5
seconds processing one event. RE3 is
keeping the main thread busy by asking over and over again whether anything happened like did it happen did it happen did it happen and whether the next frame is ready now I don't want to ask something like an arbitrary sleep after every frame because that would also delay the input what I need is an
interruptible wait what does that mean that means pause only while the next frame is not due wake immed immediately up when an event arrives or wake up when it's time to process the next frame. So in principle, the loop should work like this. While the game is running, call the pending input and window events. If the next frame is due, process and render the frame. Else wait for either an event or the remaining frame time. We
still process events which are already waiting at the beginning of the loop. The only difference is the empty branch. Instead of immediately starting another lap, the thread waits until something needs attention. Okay. So, GLFW already
provides exactly that operation. Remember reading documentation. So, I can replace the empty early frame branch with its timed event weight. We do something like this. If the apple else gf weight events time out target
frame time minus ms divided by 1,000.
Okay. And then end if. So wait events timeout is the alarm clock. It waits for the remaining time but keyboard mouse and window events can wake it up early.
And the change stays inside game state playing game because the evidence points specifically to gameplay frame pacing. I'm not replacing every event loop in the application with a wait and hoping for the best. Okay, now we can rebuild and run it. If you again take a look at the CPU, the CPU reading falls to roughly 10 to 25% in this capture. But
keep in mind waiting has a small scheduling cost. So it is not free real estate. But the alternative here is deliberately burning almost one complete
core to ask the same question until the next frame arrives. And in my opinion, that's suboptimal. Okay, so we finally
have the window and the CPU is not speed running the greenhouse effect. Now I want to shorten the actual test loop. The startup should skip the logos, cinematics, and menus, but it still has to initialize the engine. incorrectly and then it should load me onto the airport with a dodo plane and I want to have a reset button. [music]
So during the last fix while looking for the event polling I already saw where the state machine is located. So after the poly events we have these game states in it once in it logo in it front
end in it playing game and playing game. The names of the game states already give you the order without having to understand the whole setup. So we have logos and intro in it once in it front end in it playing game and then playing game. The tempting change would be to jump directly into game state playing game. But since we have this in it playing game, I guess this is where we initialize the systems and the world just like in Doom and the other it tech games where they had managers that get initialized before the game starts like video manager, audio manager and so on.
So we going to try to skip as much as possible. So we're going to do something like after startup if defaf redev and
then game state in it once and I'm not
going to hijack the normal run. I'm just trying to add a new branch for the deaf build. Okay. So we also go into the game state in it once and here we call this fast start that we going to define.
Now there's one more dependency hidden behind that transition the game script. GTA 3's compiled SCM scripts coordinate
the story. The existing debug script loader already knows two useful choices.
Main SCM for the normal story and main
free roam SCM for a world without a story startup. Okay. So our prepare fast
start does one very small thing before game play is initialized. It selects option one. So one is free roam and zero
keeps the story. Then we have in it playing game. It calls initialize game. This is the important boundary. Only after it returns do the player world collision and other systems exist. And
that is when we can create the developer scenario. Now I rebuild and launch the game. The game skips the intro cinematics menus and enters the game play directly. So, the fast path works, but we're only inside the game. We're not yet somewhere useful where we can test the dodo, right? Okay. So, let's get the player at the airport.
I was looking through the code if there is something like a place character function and I found this teleport to waypoint. So of course the first question that I asked myself was can I just use this? And then after some analysis um I came to the conclusion technically yes but it is a static focal
debug function built around the map marker. So it reads this target marker position teleports whatever find player entity returns which can also be like uh
claw's current vehicle and it does not reset health controls weather camera or anything. So exposing the function and making it visible to other callers would widen its scope so to speak and still
give us just half of the scenario that we want because it's not resetting the game settings like he





