nanoMMO

Low poly water shader for an MMORPG in C++

Three ways to make the sea move, ripples in the light, smooth waves and flat triangles, the facets picked to match the world, then a shore with foam and a liquid for each land, with lava that glows at the tops of its waves.

Watch on YouTube

We give our MMORPG's sea waves with raylib and GLSL, trying three ways: ripples in the light on a flat sea, smooth waves that move a grid of triangles in the vertex shader, and flat-shaded facets, each triangle lit by its face's normal from dFdx and dFdy, which match our low poly world. Then the sea reads the ground's heights from a texture, so it calms down and foams at the shore, and each land gets a liquid of its own: water, lava that glows at the tops of its waves, and a green ooze. This is episode 43 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.

Topics: Graphics

The code

Each step on screen is a tag in the game's repository. The code at the end of the episode is ep043/end.

  1. 2:44ep043/step-1RipplesBrowseChanges
  2. 12:23ep043/step-2WavesBrowseChanges
  3. 16:36ep043/step-3FacetsBrowseChanges
  4. 18:44ep043/step-4The shoreBrowseChanges
  5. 23:03ep043/step-5A liquid a landBrowseChanges

Transcript

Intro

0:00 Hello and welcome back to episode forty-three, where we're going to give our sea waves, made of flat triangles like the rest of our world, for the water, the lava and the ooze. Let's begin with a quick look at where we're going to be by the end of the episode.

0:15 alice wades into the Meadows' sea, which moves in waves now, each of its triangles lit flat, with foam along the shore, and the sand showing through the shallows. The waves calm down as they reach the beach, and lap at it.

0:28 In the Ashlands, the lava is a liquid of its own, thick and slow, with a dark crust at the shore, and the tops of its waves glow.

0:36 On the website of the series you can find more information about the project. The code for the project is open source on GitHub, tagged at each step of each episode so that you can follow along.

Last time

0:48 Now, before we get to today's work, let's quickly go over what we did last time. Each kind of monster got a loot table in the content, the items it can drop, each with its chance and how many. The content's checks refuse loot that doesn't add up, like a chance of more than one, or an item the items file doesn't have. When a monster dies, the world rolls its loot, and puts what drops into its killer's bag. The chat says what dropped, and what didn't fit. The bots drink potions when they're hurt and wear what they find, so a load test has the servers saving and sending bags. And the world fuzzer moves items to and from any place a client could send, and checks the bags after each input.

Today

1:30 Our sea is one flat square around each island, at sea level, in a single colour for each land, which doesn't move. We're going to try three ways of making it move, and pick the one that suits our world. The first is ripples, where the sea stays flat, and the light on it moves. The second moves the water, with waves that raise and lower a grid of triangles, and light them smoothly. And the third lights each of those triangles flat, the way our ground is lit, so the sea is facets, like the rest of the island. With a way picked, the sea is going to calm down near the shore, go lighter where it's shallow, and foam where it meets the sand. And each land gets a liquid of its own, so the lava is thick and slow, and glows at the tops of its waves. All right, let's get started, with a look at the sea as it is now.

The sea as it is

2:18 alice stands on the north shore of the Meadows. She walks into the sea, up to her knees, which is as deep as the server lets her wade. The sea is a single blue, a little see-through, so the sand shows near the shore, and it doesn't move. As the camera turns, the line where the water meets the beach stays put, as the sea is one square of two triangles, in one colour, which the renderer draws with the world's shader.

Ripples

2:44 The first way leaves the sea flat, and moves the light on it, the way many games scroll a texture of ripples over a flat sea, so the sea needs a shader of its own. It gets a class of its own too, in sea dot h. We take raylib, for the shader and the model, our atmosphere header, for the land's look, and the terrain, as the sea goes round the island. The class is the sea around a land, in the land's look, which moves on its own. Its constructor takes the terrain and the look. The destructor unloads what the sea has on the GPU, so like our other classes that own something there, it can't be copied. Draw draws the sea with the camera, the atmosphere for the light, the bands for cel shading, and the seconds since the window opened, which is what moves it. Above it, we write that it draws the sea as it is a number of seconds in, lit like the world, with the sun's light in bands, or smooth with no bands. Triangles says how many triangles the sea has, for the renderer to count. And the sea keeps its shader and its model, which is raylib's mesh with its material. In sea dot c c, we take raymath, raylib's maths header, for the matrix that puts the sea at sea level. The vertex shader comes first, in a raw string, like our other shaders. It takes each corner's position, and raylib's m v p, the model, the view and the projection in one, which takes the corner to the screen. It takes the model matrix on its own as well, which takes the corner into the world. It hands on where the corner is in the world, which the GPU blends across the triangle, so the fragment shader gets where each of its pixels is in the world. The depth goes on as well, for the fog, like it does in the world's shader. Above the vertex shader goes what it's for: where each pixel is in the world goes on to the fragment shader, which works out the ripples there. Then the fragment shader, with how the ripples work above it: three waves, each its own way and length, tilt the surface that each pixel lights, while the sea stays flat. It takes the uniforms the world's fragment shader takes: the colour, the sun, its light, the ambient light, the fog, the emission and the bands. And two more, the eye, which is where the camera is, and the seconds. The three waves each go their own way, so that they cross, and their pattern doesn't repeat for a long way. Their lengths are a metre and a half, a metre ten and eighty centimetres, in metres, from the top of a wave to the next. Then the most the ripples tilt the surface, and how much of the sun the water reflects to the eye. Main starts the surface's slope at zero, which is flat, and goes through the three waves in a loop, each along its way, normalised to a length of one. For each wave, k is how many radians it goes through in a metre, two pi over its length. Its phase is where the pixel is along the wave's way, times k, plus how far the wave has gone since the start. On deep water, gravity sets how fast a wave's phase goes round, at the square root of nine point eight times k, which carries the longer waves along faster. So each moves as fast as a wave of its length does at sea. A wave's height is the sine of its phase, and its slope goes with the cosine, so we add up the cosines, each along its wave's way, and k tilt sets how steep they get. A surface that slopes up one way has a normal that leans the other way, so the normal is minus the slope, times k tilt, and one up, normalised. The light is worked out like the world's shader does: the sun's share on that normal, in bands when cel shading is on, plus the ambient light and the emission. The glint is the sun reflected off the surface, about the normal, where it comes back to the eye. Where the reflection points at the eye, its dot product with the way to the eye is close to one, and the power of twenty-four keeps a small, bright spot of it. The sea's colour is lit, with the glint added in the sun's colour, then the fog, like everywhere else, and the colour's alpha, so the sea stays see-through. Set sets a uniform by its name, so that each line that sets one is short. The constructor loads the shader from the two strings, with raylib's load shader from memory, which compiles them for the GPU. The mesh is the square the ground's file had, eight times half the terrain's size, so four times as wide as the terrain, as one mesh plane, at sea level, so that the sea goes on past it. Gen mesh plane builds the square and puts it on the GPU, and load model from mesh wraps it in a model with a default material. The model draws with our shader, in the land's sea colour, and the emission is set once, as it's the land's, and doesn't change while we're in it. Unload model leaves the model's shader alone, which we note over the destructor, so the destructor unloads the model, and then the shader. Draw sets the uniforms that can change from one frame to the next. The atmosphere comes first, as the settings window can change it as we play, with its presets for dusk, night, mist and ash. Its uniforms are the way to the sun, which the light comes from, and its light, which the sun adds to a face turned to it. Then the ambient light, which a face gets even when it's turned away from the sun. Then the sky's colour, which the fog fades into, so that far away, the sea fades into the sky like the rest of the world does. And the two distances the fog goes between, in metres from the camera, from where it starts to where it hides everything. Then the bands, as cel shading can be switched on at any time, the eye, for the glint, and the seconds, for the ripples. Then it draws the mesh, moved to sea level, with its material, which carries our shader.

8:27 The sea's square came from sea mesh, in ground dot h, which goes, as the sea makes its own. Its definition goes from ground dot c c too. In renderer dot h, the renderer keeps the sea in a unique pointer, so that it can make a new one for each land, and the sea's emission goes, as the sea keeps that now. The sea was the renderer's one optional, so optional goes from the includes as well. In renderer dot c c, ground dot h goes from the includes, as the renderer doesn't make the sea's mesh any more. Set terrain makes the land's sea, from its terrain and its look, and the chunks are the ground and the trees, which have no bones either. Unload terrain resets the pointer, which unloads the sea. Draw still draws the sea last, so that we see the ground under it, with the camera, the atmosphere, and the bands when cel shading is on. The time is raylib's get time, the seconds since the window opened, which is a double, so we cast it to the float the shader takes. And the renderer counts the sea's draw and its triangles, like it does for the chunks, for the benchmark. In the client's CMakeLists, sea dot c c goes into the client's core, and sea test, which we're going to write once we've seen the ripples, into the client's tests.

9:44 With the ripples, the light on the sea moves, in small waves that cross each other. Close to alice, they look like water, in small bands of light and shade. Further out, a ripple covers fewer than two pixels, and each pixel lands somewhere else on its ripple, so they turn into a pattern of stripes, a moiré. And the sea is still flat, so the line where it meets the sand doesn't move, and next to our island's flat triangles, the ripples look like a picture painted on the water.

10:14 The sea moves with the time, and nothing else moves it, which is what we test, in sea test dot c c. Below sea dot h, we take memory, for the window's pointer, and vector, for the pictures. Then abseil's status or, as our window comes from a create function that returns the window or an error, the atmosphere, for the Meadows' look, our window, GoogleTest, and the terrain, for the Meadows' island. The camera is two hundred metres from the middle, past the shore. It's six metres up, looking down at the water fifteen metres ahead of it, so the picture is nearly all water. So it's out to sea, north of the Meadows' island, looking down at the water. Picture draws the sea alone, and over it, we write what it gives back: the sea as it is a number of seconds in, as each pixel's colour. It draws into a render texture of sixty-four pixels by sixty-four, cleared to black, with our camera, and the sea lit by the Meadows' atmosphere, with no bands. Then it reads the texture back from the GPU as an image, and the image's colours into a vector. It returns that once raylib's copies of the colours, the image and the texture are unloaded, as raylib leaves those to us. Match compares two pictures, pixel by pixel, by their red, green and blue, and says whether they're alike in all of them. It returns false at the first pixel that differs, and true if none does. The test opens a hidden window, through our window's create, as raylib needs a window for the GPU, and asserts that it opened, as nothing can be drawn without it. It makes the Meadows' sea, around the island of seed one. Then it draws the sea at ten seconds in. Drawn again at ten seconds, the picture has to match, pixel for pixel, as nothing but the time moves the sea. And half a second later, the picture can't match, as the waves have moved on.

12:06 Docker builds the client at this step, sped up here, and x v f b run gives the tests a virtual screen to open their window on, as the container has none, and Mesa draws on the CPU. The sea's test passes, along with the renderer's four, one of which draws the terrain and the sea.

Waves

12:23 The second way moves the water, so the sea needs corners to move, and it won't need the terrain any more. In sea dot h, the terrain's header moves over to sea dot c c, and the constructor takes the look alone. A constructor with a single argument can quietly convert a look into a sea, so it's marked explicit. In sea dot c c, we take c math, for rounding, our triangles, which the ground is built from, and the terrain, for the size of its cells and the sea level. The vertex shader's job changes: three waves, each its own way and length, raise and lower each corner of the sea, and their slopes there tilt its normal. The vertex shader moves each corner, so raylib's m v p goes, and it takes the view and the projection on their own, to use once the corner has moved in the world. It takes the seconds, which move over from the fragment shader, and the eye, which the fragment shader keeps for the glint, and hands on a normal, as the waves tilt the surface. The three waves get longer, ten, seven and a little over five metres from the top of one to the next, as they're the shape of the water now. They go up to forty-five centimetres above the still sea, and as far below it. Far from the camera, the waves calm down, from forty metres out to a hundred, where the sea is still. Far away, a cell is a few pixels, and waves that small flicker. The height and the slope start at zero, and the loop moves over from the fragment shader. Its ways, its k and its phase, at the speed of a wave at sea, work as they did for the ripples. It adds up a third of each wave's sine as the corner's height, so the three add up to between minus one and one. And it adds up their slopes, which are the cosines times k, as a wave that goes through more radians in a metre is steeper. The corner goes up by the height, times k height and the calm, and so does its slope, as a lower wave is less steep. The normal leans away from the slope, as with the ripples, and the GPU blends it across each triangle, so the light is smooth. The view and the projection then take the moved corner to the screen. In the fragment shader, the ripples go, and it takes the normal and normalises it, as the vertex shader hands on minus the slope and one up, which is longer than one. It takes the reach in place of the seconds, how far the sea goes from the camera, as the sea has an edge now. The fog goes by how far in front of the camera a pixel is, so off to the side, the edge of the sea could still show. So over its last thirty metres, the sea fades into the sky, wherever the fog ends. The reach is a hundred and sixty metres, a little past where the Meadows' fog ends, in metres from the camera to each side of the sea. The constructor builds a square of the ground's cells, two metres each, so a hundred and sixty cells across. It's a square around the camera, cut into the ground's cells, two triangles each, which the waves move. Corner is a lambda that gives the corner of the grid at a column and a row, with the camera in the middle. Each cell gets two triangles, through triangles' add, the way the ground's are built, in white, as the shader colours them. The sea has fifty-one thousand two hundred triangles, for the GPU to move each frame. The shader gets the reach once, as it doesn't change. In Draw, the sea follows the camera wherever it goes, so the two floats are where the middle of the sea goes this frame. Standard round rounds the camera's x, counted in cells, to the nearest whole cell, which times the cell's size is back in metres. Over it, we write why: each corner of it stays where a corner of the ground is, and the waves, which go by where they are in the world, don't move with it. The camera's z is rounded like its x, and the sea moves there. The renderer makes the sea from the look, and so does the sea's test.

16:16 Now the water moves, in long, soft waves. They roll past alice, and the line where the sea meets the sand moves with them. Far out, the sea calms down, with no stripes. The waves are smooth, though, with soft light across them, like plastic, while the ground and the trees next to them are flat triangles.

Facets

16:36 The third way keeps the waves, and changes the light on them. The facets come from the light, so the vertex shader stops working out the waves' slopes, and the normal goes from both shaders. Over the fragment shader, we write what it does now: each triangle is lit flat, like the ground's, with the normal of its face. The ground's triangles share no corners, so each corner carries the normal of its face, and the light is flat across it. The vertex shader moves one corner at a time, and can't see where the other two went, so the fragment shader works out the face's normal. The GPU runs fragment shaders on squares of two by two pixels at a time. So d F d x and d F d y are how much a value changes from this pixel to the next one across, and to the next one up. For the world position, both changes lie in the triangle's face, so the cross product of the two is its normal, and each pixel of the triangle gets that one normal. Above the line goes that, in short: how far the world moves from this pixel to the next one across and the next one up. Both lie in the triangle's face, so across them is its normal. Which way it points depends on which way the screen's rows run, so where it points down, we turn it up.

17:50 With the facets, the waves are triangles that tilt as the waves go by, each a single shade. Where a triangle faces the sun, it's light, and where it faces away, it's dark, the way the ground's faces are. The sea looks like it's made of the island's triangles now.

18:08 So, we've tried three ways of moving the sea. Ripples keep our two triangles, and do their work at each pixel, but the sea stays flat, so the shore doesn't move, and far out, they'd need to calm down, like the waves do. Waves move the water, with fifty-one thousand two hundred triangles for the GPU to move each frame, but their smooth light looks like plastic in our world. Facets move those triangles too, and light each one flat, like our ground and our trees. Our world is low poly, so the facets are the way we're going to keep, and from here on, we make them look like a sea, near the shore and in each land.

The shore

18:45 Near the shore, the sea is going to calm down and change colour where it's shallow, so it needs to know how deep it is, which comes from the ground under it. In sea dot h, the terrain's header comes back, and so does the constructor's terrain. The sea keeps a texture of the ground's height at each corner of its cells. In sea dot c c, we take vector, for the heights on their way to the GPU. Over the vertex shader, we add that the waves move each corner less where it's shallow. The vertex shader takes the ground's heights as a sampler, which is how a shader reads a texture, along with half the terrain's size and the size of a cell, to find a corner in it. It hands on the gap, from the ground up to the water, at each pixel. And below, how deep the still sea is, which is flat: the GPU doesn't blend it across a triangle, and each of its pixels gets the value at one of its corners, so each triangle has one depth. A corner of the sea is a corner of the ground, as the sea moves a whole cell at a time. So we find which corner of the ground it is, from where it is in the world, and clamp it to the texture. That way, past the edge of the terrain, the shader reads the edge's height, which is under the sea. So it's the corner of the ground's cells under this corner of the sea, which is the edge's past the edge of the terrain. Texel fetch reads one texel, by its column and its row, with no filtering, and its red channel is the height. Below is the sea level minus the ground's height there, as the corner starts at sea level. In the shallows, the waves calm down to a quarter of their height at the shore, and they're at their full height two and a half metres deep, so that they lap at the shore. Once the waves have moved the corner, the gap is how far the water is above the ground. In the fragment shader, the shallows are a pale blue green, mixed in at a little under half, and more see-through, at a little over half the sea's alpha. Where it's shallow, it's lighter, and we see more of the ground through it. And the foam is nearly white, with a little blue in it, and nearly opaque, so it covers the sand under it. From twenty centimetres deep to two metres, the colour goes from the shallows' to the sea's, a triangle at a time, as below is flat. And where the gap closes, under about fourteen centimetres, it foams, which draws a thin line where the water meets the ground. The light falls on the new colour, and the pixel takes its alpha. The constructor takes the terrain again, for the heights. The grid is cut the way the ground's cells are, so the ground under each of the sea's triangles is a single flat triangle of the ground. So both the water and the ground are flat across it, and the gap the GPU blends from the corners is right at each pixel, which we add to what we write over the grid. Along each side, the terrain has one more corner than it has cells. The ground's heights, one float a corner, go into a texture the vertex shader can read. The heights go into a vector of floats, a row of corners at a time, from the terrain's corners. They go to the GPU through raylib's image, which takes a pointer to our pixels, the width and the height, one mipmap, and the format. Uncompressed R thirty-two is a single float a pixel, so the heights go up as they are, below sea level too, without being squeezed into a byte. raylib hands a material's textures to the shader as it draws, so the heights go in the diffuse map, and the shader's location for that map is our ground sampler. The shader gets half the terrain's size and the cell's size, once. Unload model leaves a model's textures alone too, so the destructor unloads the heights, and over it, we add the textures to what unload model leaves alone. The renderer hands the sea the terrain again, and so does the sea's test, the Meadows' island.

22:29 Along the beach, a thin line of foam follows the shore, and the shallows are lighter, with the sand showing through. As alice wades in, the waves around her are small, and further out, where it's deep, they're at their full height. The foam moves as the waves lap at the sand, as the gap opens and closes.

22:47 In the Ashlands, though, the lava has water's shore. It foams white, its shallows go pale and see-through, and its waves roll as fast as water's. The shallows and the foam are constants in the shader, and they're water's, so each land needs its own.

A liquid a land

23:03 A land's look gets what its sea is made of, a liquid, in atmosphere dot h. A liquid is a struct, and over it, we write what it is: what a land's sea is made of, its colours, its waves and its light. Deep is its colour out where it's deep, and its alpha is how much of the ground it hides. Shallow is its colour where it's shallow, near the shore. And edge is its colour along the line where it meets the ground, which is foam on water, and a crust on lava. Height is in metres, from the still surface to the top of a wave. The wavelength is in metres too, from the top of one wave to the next, of the longest of its three waves. The pace is how fast its waves go, where one is as fast as water's. The glint is how much of the sun it reflects to the eye. And the emission moves over from the look: the light it gives off of its own, added to the sun's, where one is as bright as a face turned to a white sun. It's for a wave's middle height, as the top of a wave gives off four times that, and the bottom none. The look's sea becomes a liquid, and the sea's emission goes from the look. The Meadows' water keeps its blue out where it's deep, and its shallows and its foam are the colours the shader worked out, so the water looks like it did. Its waves are forty-five centimetres high and ten metres long, at water's pace, with the glint the shader had. The Ashlands' lava is orange out where it's deep, dark red in its shallows, and its edge is a dark crust, as lava cools where it's thin. Its waves are thirty centimetres high and twelve metres long, at a quarter of water's pace, as lava is thick. It reflects no sun, and gives off point three five at a wave's middle height, so the top of a wave gives off more than the old lava did, and blooms. The Crypt's ooze is green, darker in its shallows, with a pale, glowing edge. Its waves are thirty centimetres high and eight metres long, at two fifths of water's pace, with a little glint, and point three at a wave's middle. In sea dot c c, the vertex shader takes the liquid's height, wavelength and pace as uniforms, in place of its constants. It hands on how high up its wave a corner is, from nought at the bottom to one at the top, flat like below, so a whole triangle glows as one. The three lengths become shares of the liquid's wavelength, the longest a whole one. The loop changes too, as each wave's length comes from the liquid now. So k divides two pi by the liquid's wavelength times the wave's share, and the time goes by at the liquid's pace, which we add to what we write over the phase. The height is called wave now, as the liquid has a height of its own, and the three waves add up to between minus one and one. So half of the wave, plus a half, is the crest, from nought at the bottom to one at the top. The corner then goes up by the liquid's height. In the fragment shader, the crest comes in, flat, like below. It takes the liquid's three colours, deep, shallow and edge, in place of the material's colour, and its glint in place of the constant, and the constants for the shallows and the foam go. The colour goes from the liquid's shallows to its deep, as the depth goes from twenty centimetres to two metres. Then it goes to the liquid's edge, along the line where it meets the ground. The emission goes up with the square of the crest, four times it, so a wave's middle gives off the liquid's emission, its top four times that, and its bottom none. The tops of the waves give off the most light, and the bottoms none, so the lava's tops glow, and its troughs go dark, a triangle at a time. The spot of glint, the power of twenty-four, is called shine now, as glint is the liquid's uniform. Set colour sets a colour as four floats from nought to one, which raylib's color normalize gives us, for the colours' uniforms. The constructor no longer gives the material the sea's colour, and sets the liquid's uniforms once, as a land's liquid doesn't change while we're in it. Its three colours go up as vectors of four floats, and its height, its wavelength and its pace, for the vertex shader, as floats. Then its glint and its emission, for the fragment shader, each set by its name, like the rest.

27:17 Now the lava looks like lava, thick and glowing. Its waves roll slowly, the tops glow orange and bloom, and the troughs go a dark red, so each triangle of it is a shade of its own. Along the shore, it cools to a dark crust.

27:32 And in the Crypt, the green ooze rolls a little faster than the lava, with a pale edge that glows along the stone, and triangles that glow brighter at the tops of its waves.

Wrap-up

27:43 So, today we tried ripples, which move the light on a flat sea, in the fragment shader. Then waves, which move a grid of the ground's cells around the camera, in the vertex shader. And facets, which light each of those triangles flat, with the normal of its face from d F d x and d F d y, and which we kept, as they match our world. The vertex shader reads the ground's heights from a texture, one float a corner, so it knows how deep the sea is. The waves calm down at the shore, the shallows are lighter, and foam runs where the water meets the ground. And each land's look has a liquid, so the lava is thick and slow, crusted at the shore, and glows at the tops of its waves.

Playing it

29:07 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.