We give our MMORPG game events, sent from the C++ server to the clients: an event queue, as Robert Nystrom's Game Programming Patterns calls it, where the world records what happens, and the server decides who reads it. The world records each hit, each blow taken and the health given back as events, next to the kills, levels and the rest it records for the analytics, which leave them out. The protocol gets an event message, and each tick the server sends each player the events near them, in their copy of the land, through the interest management's cells, over TCP so that none are lost, while the world's state goes on over UDP. The client keeps the events apart from the world it draws, and shows each as combat text: the damage over the monster, what it does back in red, healing in green, and a new level in gold. Along the way, a dead monster loses its nameplate, and the bots stop swinging at a body. This is episode 49 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.
Topics: Networking, Gameplay
The code
Each step on screen is a tag in the game's repository. The code at the end of the episode is ep049/end.
Transcript
Intro
0:00 Hi, and welcome to episode forty-nine, where the server is going to send the players events, such as each hit and the damage it did. And the client is going to show them as numbers over the units. Before we build it, let's have a quick look at where it's going.
0:16 By the end of the episode, what happens in a fight reaches the players near it, as events. Each number on screen is one of them, which the world recorded as it stepped, and the server sent to this client over TCP, in the tick it happened. The heal, the hits, the damage that comes back and the level reached each come once, apart from the world's state, which keeps coming over UDP. And the client floats each over the unit it's about, in its colour.
0:45 The series has a website, with more about the project and how it's built. The code is open source, on GitHub, and linked from there, and each episode has a page of its own, with the code at each of its steps.
Last time
0:58 Last time, we took a step back, and wrote no code at all. We went over the forty-seven episodes so far, and what they built, from the client all the way to the analytics. We looked at the practices around the code, such as the tests in CI, the deploys on push and the load tests. And we looked at where the game goes next, with more features, more worlds, and a trading system further down the line.
Today
1:24 Each tick, the server sends each player the units near them, and the client draws the newest it has. The units tell the client how things are, but not what happened in between. Say a skeleton's health goes from fifty to five. The client can work out that it lost forty-five, but not who hit it, or whether two players hit it in a single tick. And a potion drunk as a skeleton hits shows up as a single change, the two added up. Those are events, which happen once, and in episode forty-seven, the world started recording them, for the analytics. So today, the world is going to record the blows and the healing as events too. The protocol gets an event of its own, and the server sends each player the events near them, over TCP, so that none of them are lost. And the client floats them over the units, as combat text, which is how most other games show a fight. I think it's a nice example of what Robert Nystrom's book, Game Programming Patterns, calls an event queue. Whoever records an event doesn't need to know who reads it, and today, there are going to be two readers, the analytics and the players. So, let's get going, with the world on the server, and its events.
Blows as events
2:36 We start in the world's header file, with the event from episode forty-seven, the struct that the world records what happens in. Until now, an event was for the game's analytics, and from today, it's for the players near it as well, a moment after the server records it. The world keeps its events in one list, whoever reads them, so a second reader needs no second list, and we add the fields the players need. The kind gets three new values, at the end of its list. A hit is one that a player lands on a monster, hurt is a hit that a monster lands on a player, and heal is the health that a potion or a skill gives back. The analytics' rows name a player, but the units the clients get carry the id the server gave them, so an event gets the player's id in the world too. The monster can now be the one that hit the player, and a hit gets the monster's id in the world. The monster field is its kind, which says what it is, while the client needs to know which skeleton it was, out of the ones around it. Then the amount, the damage they did, or the health a potion or a skill gave back. Hurt, which takes a monster's health, takes the monster's id now, for the hit's event, and a new helper, heal, gives the player back as much of the health as they're missing. Record takes the player's id next to the player, so that each event it starts has the id as well as the name, and its callers are going to pass it. In the world, using an item heals through the new helper, instead of capping the health right there, and the use's record passes the player's id. Taking a quest passes it too, and so does turning one in, along with its prizes and the level it brings. A swing that lands passes hurt the monster's id, which is its key in the world's map of monsters. Hit looks the monster up by the player's target first, so its key is right there to pass along. The damage it passes is the weapon's, plus five for each level after the first, plus what the player wears adds. A skill heals through heal as well, and passes hurt the id of each monster it hits, as a skill like whirlwind hits all of them in its reach. In hurt, once the monster's health is down, the hit is an event, with the monster's kind, its id, and the damage. The amount is the damage they did, even when the monster had less health left, which is the number most other games show. The kill, and the level it may bring, pass the player's id like the others. Heal works out how much of the health the player is missing, up to what they're given. A player at full health gets nothing back, and no event, so a skill used at full health doesn't show a plus zero. Otherwise, the health goes up, and the event has how much. Loot passes the id along too, and record puts it into each event, with designated initialisers, in the order of the struct's fields. And when a monster's swing lands, the player it hit gets an event of their own, hurt, with the monster's kind and the damage, after their armour took its share. A death passes the player's id like the others.
5:36 The analytics read these events too, through the stream from episode forty-seven. A fight is a hit a second or so for each player in it, which would soon be most of the table, while what we count is the kills. So in the events' header file, for analytics says whether the analytics keep the events of a kind. It takes the kind and nothing else, as the answer depends on the kind alone, and not on who or where. In events, name gets a word for each new kind, hit, hurt and heal, which is how each kind would read in a row. What looks up the monster's name for a hit and a hurt, like for a kill, and a heal is about nothing in the content. For analytics is a switch as well, over the kinds of event. The kinds we had, kills, deaths, loot, prizes, levels, quests taken and turned in, and uses, return true, as they're what the dashboard counts. And the three new ones, hits, hurts and heals, return false. So kills, deaths, loot and the rest go into the table, and the blows and the healing stay out of it, as they're for the players. In the server, record events turns an event into a row when the analytics keep its kind. And it returns before the round trip to Redis when they keep none of them, which, with no kills, is most ticks.
6:50 Now, let's write a quick test that the world records them. The world's test takes algorithm, for ranges find, and our events header, for the kinds the analytics keep. The analytics test from episode forty-seven counts four events, a quest taken, a kill and two drops. Its kill now comes with the hit that did it, and maybe the skeleton's blows back, before it died. So the test drops the kinds the analytics don't keep, with for analytics, next to the levels it dropped already. The new test makes a world with the test's gear, a sword and potions among it, and a player at fifty health, out of a hundred. A skeleton stands a metre away, as in the test of the swing. The player drinks a potion, with use item on the first slot of the bag, then holds attack and swings for a second, while the skeleton fights back. A small lambda finds the first event of a kind, with ranges find and a projection, which compares each event's kind, and not the whole event. It captures the events by reference, so what it finds is in the test's vector, and compares with its end. The heal has the player's id, and forty, which is what the potion gives back. The potion is the test gear's, which heals forty, with a cooldown of ten seconds. The sword's hit has the player's id, the skeleton's id, the one spawn returned, and fifteen, the sword's damage at level one. And the skeleton's blow back has five, its full damage, as the player wears no armour to take a share of it. Each find is checked with assert not equal before we read the event, as reading the end of the vector could crash the test, instead of failing it. And the events' test gets a second test, which checks for analytics and pins down both sides, with a kill and a use kept for the analytics, and a hit and a heal left out. Two of them are kinds the players see, and two are kinds they don't.
8:40 We build the tests at this step, in Docker, and run the world's tests and the events' tests, which need no database. The new test passes, and so does the analytics test from episode forty-seven, with the blows left out of it.
On the wire
8:54 Next, the event goes on the wire, in our proto file. The kinds the players see are an enum of their own: hit, hurt, heal and level. Their values start with event, like our motions start with motion, as protobuf puts the values of all the enums in a file side by side, so two enums can't both have a value called hit. Then the event, which is a lot smaller than the world's. It has its kind, the player it's about, by id, the monster they hit, by id, and the amount, which for a level is the level reached. There's no name, land or position, as the client has those already, for the units near it. Above the message, we write what sets it apart from a unit: a unit comes again each tick, and the newest replaces the one before it, while each event comes once. The world message gets a list of events, as field eighteen, the next number free. They're going to come on their own, over TCP, like the bag and the quests, so that none of them is lost. In the events' header file, we include optional, and the protocol's generated header. For players turns one of the world's events into the protocol's, or gives nothing for a kind the players don't see, such as a quest taken. Std optional holds a value or nothing, which says that more plainly than an empty event would. In events, which includes optional too, for players starts the protocol's event with what all its kinds share, the player's id, and the amount. A hit sets its kind, and the monster's id, as its number goes over the monster, and returns. The monster's id is what the client finds the number's place by. A hurt and a heal set their kinds and return, as their numbers go over the player, whose id is set already. A level's amount is the level reached, from the event's level field, which replaces the amount we set at the top. The other kinds, a kill, a death, loot, a prize, a quest taken or turned in, and a use, give nothing, with std null opt. A kill could show too, but the monster falling over shows it already, and the loot has its line in the chat. So the players get the hits, the blows taken, the healing and the levels, and the rest stays with the analytics. Players get the units in the cells around their own, from episode twenty's interest management, and the events are going to follow those cells. So in the interest header file, near says whether the players in one cell see what happens in another. It takes two cells, and it's a free function next to cell of, as it needs nothing but the cells. In interest, we include c std lib, for std abs on integers. Two cells are near when they're within two cells of each other, along x and along z, which is the square of cells that views gathers a player's units from.
11:38 Next, a quick test of what the players get. It takes optional and the protocol's header, for the event that comes out. The test makes the world's events with designated initialisers, setting what each kind fills in, and leaving the rest at zero. A hit by player three, on monster nine, for fifteen, comes out as the protocol's hit, with its kind, the player's id, the monster's id and the amount, each checked with expect equal. The ids are numbers the test picks, as for players looks nothing up, so the test needs no world. Designated initialisers have to follow the order the struct declares its fields in, so the level's event names the kind, the player, then the level. It leaves the amount at zero, as for players takes a level's amount from its level. A level, with player three reaching level seven, comes out as the protocol's level, with seven as its amount, as that's where the client reads the level reached from. And a quest taken comes out as nothing, which expect false checks, through has value. And the interest test checks near with the cells of the players from the test above it. A player's own cell is near, a player at sixty, minus forty, two cells over, is near, and a player two hundred metres away isn't.
12:53 We build the tests at this step, with the new protocol, and run the events' tests and the interest tests. An event comes out the way the players are going to get it, and near agrees with the cells the players get their units from.
Who sees what
13:07 The server is going to send each player the events in their copy of the land. A dungeon has a copy for each player in it, and a hit in yours isn't something another player in theirs should see. So in the world's header file, an event gets the copy it happened in, which copies fills in, as a world holds no id for the copy it runs in. In the copies' header file, take events says that each event comes with its copy, and in copies, it stamps each of a copy's events with the copy's id, as it moves the event into the list. In the server's header file, record events takes the events now, and show events sends them to the players, after the world goes out, so that a client getting the world over TCP has the units they're about first. In the server, the tick takes the events once, and hands them to record events, then to show events, after the broadcast. Keep in mind that a client getting the world over TCP reads it before the hit, while over UDP the hit can come first, and its number waits for the unit. Record events reads the events it's given, where it took them from the copies before. Show events puts each player's events together in a world message, in a map by their id, so that a player gets a single message a tick. For each event, we get what the players see of it, and its copy, by the id the event has, and skip an event the players don't see, or whose copy has gone. We take the event out of the optional once, right after the check, and the loop below copies it into the list of each player who sees it. The event's cell is where the player was, which for a hit is within the weapon's or the skill's reach of the monster. Each player in that copy, with a session, whose cell is near the event's, gets the event at the end of their list. Then each player's list goes out as a frame, over TCP, through their session, and counts towards the bytes sent, like the bag. And the bot has a check at the top of receive, for the messages it doesn't read, such as the chat, as a message with no land in it would read as the Meadows. A message with events joins that check, with an or. The bot is a player of our own, driven from code, and it goes by the world, by where it is, its health and the monsters near it. So it skips the events, as the numbers would be of no use to it, and the bots in our load tests carry on as before.
15:26 We'll test it with the server running too. The test player in the server's test is our stand-in for a client. It keeps the events it gets, oldest first, behind an accessor, events, which the test reads. They go in a branch of their own, before the chat, as they come in a world with nobody in it, like the bag and the quests. Without the branch, they'd land in the world the test player keeps, and replace it, so they wait in a vector of their own. The new test gives the server content of its own, a sword for each new player, from the test content, and the test skeleton, as the first kind of monster. A spawn puts a skeleton in the Meadows, a metre east of where new players start, which is within the sword's reach. The server starts with that content, on a free port, with a tick of fifty milliseconds, like in the bag's test, where the server had gear of its own. Create also gets the services the fixture set up, for the saves, the logins and the events. So the new server finds the two accounts the fixture made as it set up, in the test's MySQL and Redis, and its terrain comes from a seed of one. We check that the server started, with assert true, and print its status if it didn't, so that a failure says why. Then alice joins, on a connection of her own, through the test's TLS context and the port the server picked. After alice, bob joins too, each saying hello with a token the test issued. Run until runs the server and both connections until its condition holds, for five seconds at most, and here, the condition is that each of them sees the other. Then alice swings at the skeleton, a metre away. The input has attack set, as the client sends it while space is down, and alice sends it once, as the server keeps a player's input until it changes. A lambda, hit, finds the first hit that a player has seen, with ranges find, and a projection on the event's kind. The test runs the server until bob has seen one, which takes about a second, as the sword's swing lands nine tenths of a second in. And bob, beside her, sees her hit land, with her id, the skeleton's, as the first monster, and fifteen, the sword's damage. The hit reaches alice too, as her own cell is near the event's, being where she stood.
17:41 We build the tests at this step, and run the server's tests, with MySQL and Redis, which compose starts for the tests, as the server's players are saved and loaded through them. The new test passes, with bob seeing alice's hit, and the server's other tests still pass, with the tick taking the events once.
Numbers over the units
18:00 On the client, the connection keeps what the server sent last, a world, the chat, the bag and the quests, and the game reads them each frame. The events are different, as each one has to be shown once. So in the connection's header file, we include vector, and take events hands over what's happened since the last time, like take events in the server's world. See adds the events from a message, next to hear, which adds the chat, and they wait in a vector. In the connection, we include utility, for std exchange, and vector. In read, a message's kind is told apart by what's in it. Chat, moves, the bag and the quests each come on their own, with nothing of the world in them, and the events now come on their own too. A message with events goes to see, before the check for chat, as a message with no chat in it goes to receive, as a part of the world. Take events exchanges the vector for an empty one, and returns what it had. See appends a message's events to it, at the end of the vector, so that they stay oldest first, in the order the server sent them.
19:03 The text that rises over the units goes in a header file of its own, combat text, as combat text is what most other games call it. It includes raylib, for the camera and the colour, then c std int, string and vector, our animator, for the figures it's drawn over, and the protocol, for the events it's made from. A popup is a number or a line over a unit, and it's plain data, so it's a struct. It has its text, such as fifteen, or level seven, the unit it rises over, by its id, and whether that's a monster's id or a player's. Monsters and players have ids of their own, so monster seven and player seven are two different units. Then its colour, in raylib's colour type, and a scale, as what's about you is bigger than what's about the other players. Last, its age, in seconds since it came, which says how far it has risen and how faded it is. Combat text holds the popups, in a vector. It's kept apart from the drawing, so that a test can check them without a window, like the jukebox, whose timing of the music is tested without a sound card. Each popup lives a second and a half, long enough to read a number, and short enough that a fight doesn't pile them up. Add makes a popup from an event, for the player whose id is you. Update ages them by the frame's time and drops the old ones, and popups hands them to the drawing, by const reference, so nothing outside changes them. Draw combat text draws each over its figure, through the camera. It's a free function, like draw nameplates, as it keeps no state of its own. The popups start above the nameplates, so the height of a nameplate over a figure's feet is something both files need. In the nameplates' header file, above gets a declaration, with how high over a figure's feet its nameplate goes, in metres. In nameplates, it comes out of the unnamed namespace, where it was private to the nameplates, for combat text to use. A monster's nameplate goes at a metre ninety, and a player's at two metres thirty-five. In combat text, we include imgui, for drawing the text, and raymath, for the vectors. Then come algorithm, for find if and clamp, c float, for the largest float, string, utility, for std move, and vector, and the nameplates' header, for above. The colours go at the top, in the unnamed namespace, as red, green, blue and alpha. White is for a hit, red for a hurt, green for a heal, and gold for a level, the gold of the quest marks. The other players' popups are smaller, at seven tenths, so that your own fight stands out in a crowd, and a level's is half again as big. A popup starts forty centimetres over the nameplate, so that it clears the name and the health bar, and rises a metre and twenty over its life. Add starts a popup over the event's player, at full size when they're you, and at seven tenths when they're not. A hit shows its damage, as a number, over the monster, in white, so it moves the popup onto the monster's id. A hurt shows minus its damage, over the player, in red. A heal shows plus the health, in green, and a level shows the level reached, in gold, and bigger, with level written in front of it. Protobuf's enums are open, so a server newer than this client can send a kind this client has no case for, and the default case skips it. So an older client keeps working while a newer server sends it more kinds of events, and shows the ones it knows. The popup moves into the vector, as we're done with it here. Update adds the frame's time to each age, then erase if drops the ones past their life. Draw combat text draws on ImGui's background list, under the windows, like the nameplates, and works out where the camera faces once, as forward. It takes ImGui's font too, which it sizes for each popup, as each has a size of its own. For each popup, it finds the figure it's about, with ranges find if, by id and by whether it's a monster, and skipping the NPCs, whose ids are a third kind again. A popup whose figure has gone, say a player who left, isn't drawn, and goes once it's old. Its share of its life sets how far it has risen, from forty centimetres over the nameplate, straight up. A point behind the camera would land on the screen anyway, so we skip it, like the nameplates do, with the dot product of the way to it and the way the camera faces. Get world to screen gives the point's place on the screen, in pixels. The popup stays solid for the first half of its life, and fades out over the second, as twice what's left of its life, clamped to one. Its size is two point four times the font's, times its scale, and calc text size A measures the text at that size, so that we can centre it over the figure, with its bottom at the point. A shadow goes two pixels down and to the right, in black, so the number reads on grass and on ash, then the text on top, in its colour, both faded by alpha.
24:06 In the client's main, we include combat text, and keep one next to the animator, for as long as the client runs. Each frame, the events the connection took go into it, with our id from the world, and it ages by the frame's time. Then it's drawn right after the nameplates, so that the numbers go over them. And in the CMake file, combat text joins the client's core library, and its test joins the client's tests.
24:31 Then a quick test for combat text, which needs no window, so it takes c std int, GoogleTest and the protocol. It has a helper, happened, in the unnamed namespace, which makes an event of a kind, by a player, with an amount, and a monster when it's a hit, with zero as its default, as the other kinds have none. The helper sets the kind, the player, the amount and the monster, one by one, with protobuf's setters, on an event it returns by value. Each of the test's events is then a single call. The test has a combat text of its own, and no window. We're player one, and we hit monster seven for fifteen, then player two heals forty, from a potion or a skill, which the event doesn't tell apart. Each add takes the event and our id, one, as the client passes its own, and last, we reach level five. Those make three popups, in the order their events came, and assert equal checks there are three first, as the test reads them by their place. The hit's popup reads fifteen, over unit seven, which is a monster. The heal's reads plus forty, over player two, and not over a monster, and it's smaller than ours, as it's about someone else. And the level's popup reads level five, in the words the player sees. A kind from a newer server, nine, which this client has no case for, adds nothing, so there are still three. Static cast turns nine into the enum, as protobuf's parser keeps the number of a kind that isn't in our proto file. Then half a life goes by, and the popups are all still there, and after the other half, they've all gone.
26:07 We build the client's tests at this step, and run combat text's test, which needs no window. It passes, with each event shown over its unit, in its words, until it fades.
In the game
26:19 Let's see it in the game at this step, with forty bots around, which take the guard's quest and hunt skeletons for it. Second Wind's heal lands in the world's tick, which records it as an event, and the server sends it to each player whose cell is near, us included. Each hit is recorded where it lands, in hurt, with the skeleton's id, so the client knows which body to float the number over. The skeleton's blows come back at one, as the armour takes the rest, and the kill brings a level, which the world records too, as it did for the analytics. The bots' fights reach us through the cells around ours, and come out smaller, as they're about other players. And keep an eye on a skeleton once it's dead, as its nameplate stays over the body, with an empty health bar. The bots around it can carry on swinging at it, too, for up to three seconds.
Leaving the dead alone
27:17 I noticed these two while watching the game, and figured it would be good to sort them out here too. Neither is new, but with the numbers over the units, they stand out. In the nameplates' header file, has nameplate says whether a figure gets one: once its name has come, as names come once a second, and not while it's a dead monster, as there's nothing left to fight. In nameplates, a figure needs a name, and a monster mustn't be dead, going by the motion it's blending to. Draw nameplates skips a figure without one, where it skipped the ones with no name before. A dead player keeps theirs, so that the others can tell who it was. The nameplates get a test of their own, in the client's tests. Then the bots, which swing at the body, starting in the quests' header file, where c std int comes in for the monster's id. A hunt remembers the monster it goes after, by its id, so that the bot can tell once it's dead. And dead says whether the world shows a monster dead, by its id. A monster the world doesn't have isn't dead, as it may be out of sight. In quests, the hunt's errand gets the monster's id from the world, next to where it is, with each of the errand's fields on a line of its own, as a hunt has four of them now. Dead goes over the monsters with ranges any of, for the one with that id, in the dead motion. In the bot's header file, wander in wanders again after a wait, as a private member function, beside the one it calls. Hunting holds the id of the monster the bot swings at, while it hunts, or zero while it doesn't. In the bot, k rethink is how soon a bot thinks again once its monster is dead. A tenth of a second is soon, but leaves time for what it sent last to go out, as two writes on one connection mustn't overlap. As each world arrives, a bot that's hunting checks whether its monster is dead in it. If it is, the bot stops hunting, and wanders again in a moment. Before, it held its swing for its random hold, up to three seconds, and swung at the body for whatever was left of it. Each wander starts with no hunt, and once a hunt reaches its monster, the bot keeps the monster's id as it starts swinging. Wander in is the timer from the end of wander, pulled out, so that both places set that one timer. Setting it again cancels the wait in progress, so wandering starts from the timer, apart from the first time, as the bot logs in.
29:36 And a quick test for each of the two fixes, starting with the nameplates, in a file of their own. Drawing them needs ImGui, while has nameplate needs nothing but a figure. It takes the nameplates' header, the animator's, for the figures, GoogleTest, and the protocol, for the motions. A skeleton, made with designated initialisers as a monster with a name, has a nameplate, and once its motion is the dead one, it hasn't. Then alice, a player, const as the test doesn't change her, with her name and the dead motion, in the order the figure declares them. Like we saw in nameplates, a player who died keeps theirs, so alice still has one. And a figure whose name hasn't come yet has none, made right in the call, with nothing set but that it's a monster. In the bots' quests test, the monsters the bot sees get ids, one, two and three, so that the hunt's errand can name its monster, the third, the skeleton at minus eight. And a new test checks dead, with the monsters the bot sees. The third monster isn't, until its motion is the dead one, and a monster the bot hasn't seen isn't dead either, as it may be out of sight.
30:47 We build the tests at this step, and run the nameplates' test and the bots' quests tests, neither of which needs a server. Both pass, so a dead monster's nameplate goes, and a bot can tell when the monster it hunts is dead.
Wrap-up
31:01 So, today, the world records the blows and the healing as events, with the player's id, the monster's and the amount, which the analytics leave out. The protocol has an event of its own, and the server sends each player the events in their copy that happen near them, a message a tick, over TCP, after the world. And the client floats each over its unit, rising and fading, in its colour, and smaller when it's about someone else. Along the way, a dead monster loses its nameplate, and the bots that hunted it stop swinging at the body.
Playing it
32:22 Let me know in the comments what you'd like to see next. And if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.