Making a Voxel-Based Shooter – Part 11-2: Snazzy Lighting

As promised, here is “Part 2” to my post about creation tools! Separating this post from the last still feels a little weird to me, as I actually programmed both parts simultaneously (not literally at the same time… you know what I mean), but I have reasoning which bears the semblance of logic. Since my previous post was mostly about where I’m going with the project (i.e. making a level-editor), I felt I should save what changes I made to the lighting engine for another post, both to maintain focus and to abstain from writing obscenely long blog entries. In the interest of thwarting the sinister forces of irony, let’s get started right away.

For our first course of action, let me show you how lighting has changed since the last update:

The screencaps are ordered from oldest on the left to newest on the right.It's just like when you see those "XBONE VS. PS4 VS. PC GRAFIX COMPARISON" videos except different.

The screencaps are ordered from oldest on the top to newest on the bottom.
It’s just like when you see those “XBONE VS. PS4 VS. PC GRAFIX COMPARISON” videos except different.

And now, a bit of history: When I first began working on lighting in this game, I wasn’t even sure that I’d want to keep it. It was actually, more or less, an experiment to help me decide how I wanted the game to look. If you take a peek at Part 10, you can see what it looked like at that time. It was something that could pass as light, if you had an amazing imagination, but it hadn’t achieved the effect I was hoping to make. I thought I could take it further.

So then I made smooth lighting. This time, I blended multiple light values together for each vertex of each cube in order to smooth the lighting out a bit, and I set the light inside of solid blocks to zero to create some sort of artificial ambient occlusion. Then, I thought I could take it further still, so I made the ambient occlusion less intense in brighter areas and more intense in darker areas. Then, I thought I could still take it further… Now I think you get the idea.

There is a fine line between making progress on your game and losing yourself in “feature creep.” Looking back, I realize I have done way more with lighting in this game than I had ever planned out. And yet, I think it was for the best. For me, being a programmer without any sense of art, spending this much time on lighting has helped me to establish some sort of mood for this game – a mood that I plan to expand upon in the future. At the very least, it helps to inspire me and guide me in the right direction if that makes any sense. I want to make a game that, in a certain way, molds itself around the way this lighting works. If the lighting were not to work out the way I wanted it to, I’d have to shoot for a different mood altogether. This is not to say that another mood would be bad or any less valid – just different. In the end, was lighting a valuable pursuit? Am I even done with it yet? I don’t really know, but I feel like, aside from the dev console, I finally have a solid feature in the game that seems to play well with others. Anyway, let’s take a look at how this actually works.

Lighting in this game, prior to this update, was basically “Minecraft light.” The way the light reacted with blocks, how it smoothed, and how ambient occlusion worked in both games were for all intents and purposes identical. In exploring more of this game, however, I noticed some things that needed to change. The first aspect of lighting that had to be fixed was the seams between light emanating from different light sources. This is only really noticeable in instances when you have light sources with very large radii, as in the first screencap in the image above. It’s something that I can’t describe in any way other than “awkward.”

What happens is a “light-emitting” block sends out six “lights” (one for each side) which can each branch in up to six different directions if nothing gets in its way. Each time it moves from one voxel to the next, it decreases in its light value until it eventually hits zero and stops being light anymore. If it comes across a voxel marked “solid” or a voxel with a light value greater than or equal to its own, it stops. This creates the illusion of light which reacts semi-realistically with solid objects. As we’ve seen before, though, it looks rather silly when it runs into other light. It just gets stopped in its tracks like there’s some invisible barrier it cannot surpass. As we all know, light is not territorial in this way in real life. The solution I found was to, instead of cutting light off as it hits another light, add its light value to the value the voxel it is testing already has. Here is my first attempt:

I seriously cannot explain this, but I thought it looked pretty neat.

I seriously cannot explain this, but I thought it looked pretty neat.

What has happened here? Every time I place another light source, the pattern is completely different. Oh well, maybe I’ll have to steal some of this code if I ever make a noise generator later. I changed around a few lines and then got this:

It's like a low-res photo of the inside of a tree from the early nineteenth century!

It’s like a low-res photo of the inside of a tree from the early nineteenth century!

Now this is interesting. I can count two things going wrong here. The first is the fact that the light levels seem to be restarting every couple of blocks. Logically, the center of this should be insanely bright, while it fades out towards the edges. Instead we get this interesting-yet-not-what-we-want ring pattern. The reason why, I discovered, is again because of the way we’re storing data here. In order to use as little memory as possible, the light value of each voxel is stored in an “unsigned char” datatype, which can hold all integer values between and including 0 and 255. This system works great unless you’re exceeding the upper or lower limits. In this case, we’re telling the program to assign values entirely too large for our unsigned char, for example, the number 1418. The computer realizes that this number is too large to be stored there, so it simply divides 256 from the value and assigns the voxel the remainder: a light value of 138. In other terms:

// this is the value we try to assign to our light
int input_val = 1418;
// this is the value that is actually assigned
unsigned char light_val = input_val % 256;

Interestingly enough, I don’t need to fix this because the solution to the second problem fixes the first one as well. The second problem is quite frankly that we’re even adding these light values together like this at all. If I were add an upper limit to light values in order to fix the first problem, I’d have only solved one problem to cause another. Any area where light would reach this limit would look saturated and washed out. It’s like looking at a picture of trees in the winter in which the sky appears to be a perfectly homogeneous white backdrop. That’s ugly, and we don’t want our lighting to be ugly.

The solution is to never reach that maximum value. In the dark, light should act as normal, but when one light is added to more light, enough to surpass a value of 255 should never be added. I found that implementing a decreasing linear relationship between the “percent of light value to add” to a voxel and the “existing light value” of the voxel seemed to do the trick. This is what I mean:

Pic 78

With this in place, lighting goes from what it looks like in screencap 1 to how it looks in screencap 2. Bam.

Ok, finally we can talk about colored light! But first, the necessary explanation of “why.” If anybody ever asks me why I program something, I simply reply, “It gives me more practice.” If I’m trying to actually make a “finished” product, however, this automated response could land me in a difficult situation where, no matter how much I learn, I’m getting almost nowhere. That is why, in a similar manner to avoiding “feature creep,” I need to focus on only building features that progress the project and postpone superfluous learning for another time and another place. Anyway, that’s not important. I’m just trying to distract you from the fact that I have no solid justification for implementing colored light.

Moving on.

Straight white light is boring right? I mean, I’d be hard-pressed to find it anywhere in real life other than in Dark Souls (manifest in the strange white light constantly emanating from the character). I imagine that’s why it looks so unnatural. So what the heck, let’s see how we could possibly make not-unnatural light work in our game.

Again, in the interest of saving RAM (and hard drive storage when saving levels), I’m not willing to sacrifice the elegance of a single unsigned char for each light value. What this means is that we cannot have more than one color of light at any given time being expressed on our stage (that is, each kind of light can only be one color. Ambient light, for example, could be a different color than our dynamic voxel lighting). Even with this limitation, light can look interesting. Put your mental-image-construction cap on. Ok? Now, close your eyes.

CLOSE YOUR EYES! And perhaps find a friend to read this next paragraph to you.

Ok, now picture a white wall, vast, imposing, blank. There is no light. Now see, there is a torch against the wall and it is burning hot with fire. See how the light starts out bright and then gets dimmer and darker as it fades into the darkness? That’s the effect we’re going for. You should now feel all warm and fuzzy inside.

You may open again. My approach to achieving this effect is to apply a specific color to a specific shade of light. More intensity corresponds to a lighter color, and less intensity corresponds to a darker color. I fiddled with some numbers in the rendering code, and this is what I got:

You can clearly see that the color I have chosen is orange. Specifically, #FFCC7F

You can clearly see that the color I have chosen is orange. Specifically, #FFCC7F

Those two cubes with a different texture are emitting light, and the environment is reacting by being extremely orange. Also, take a look at that ambient occlusion. It’s disturbing. Not only is it adding instead of subtracting light, but it’s also more intense in brighter areas and less intense in darker areas. This must be fixed.

Luckily for me and for the fate of the game, lighting was just going through a phase at the time. I don’t want to go into too much detail here, but essentially, I had to split up a couple functions and effectively calculate two different colors of light to put them together. I have one set of functions governing the orange light and another set governing ambient occlusion. After the program finds the color of the orange light determined by the gradient I’ve specified, it subtracts the value of the ambient occlusion from each color (RGB) proportional to its existing value. What we end up with looks a little like this:

[Portal 2 reference here]. Oh look 3D TEXT!

[Portal 2 reference here]

Well, I’m satisfied… at least for now. Lighting has significantly improved over the last few blog posts, and I hope to put it to rest for as long as I don’t find any problems with it. In the future, I don’t plan to spend so much time on just one feature, but, since this one will be integral to gameplay, I made a little excuse for it.

Holy moly! This is the longest post I’ve ever written, coming up on the 2k mark here. Let’s pretend like I never said anything about writing a brief post. See you next time!

Advertisement
Privacy Settings

Making a Voxel-Based Shooter – Part 11: Creation Tools

Another great title for this update could be “Adding User-Friendliness,” but I thought that might be a bit pretentious, given that the developer console is still the user’s primary interface with the game. Even so, this project is now much more user-friendly than it ever has been, now with BRAND-NEW features including better gravity, better collision, more consistent multiplayer, better textures (arguably), and of course an “improved” dev console! With all of this stark improvement, you’d think somebody would have offered to publish my game for me already. Anyhow, I’m fairly confident that you’re not reading this so that you can watch me ramble on and on about what little improvements I made. Let’s focus on the progress we’ve made towards developing a playable game (definitely the straight and narrow path these days).

Aside #1: By the way, welcome back! Or welcome anew! Whether you’ve read this blog before and have inexplicably chosen to return five months since the last update to read this one, or whether you happened upon this page by some stroke of serendipity, I appreciate your presence. (Hey, five months isn’t too bad… At least I’m being consistent.)

Any game worth beans relies on some form of game engine to deal with low-level functionality such as rendering (making pretty images appear on the screen), controlling sound, and saving, loading, and modifying game assets. Some game engines you may have heard of before are the Unreal Engine, CryEngine, or Source. These are just a few of the many that are out there, and each has its own strengths and weaknesses. If you’re somebody with enough money, and you just can’t settle for less, you can rake out the cash to purchase the rights to use one of the big-name game engines. Realistically, this is pointless unless you have a massive budget for a massive game. I, however, have zero budget and zero deadlines, so sacrificing money for time is not really a priority. That is why I have decided to make my own engine (yes, there are engines out there that are relatively cheap to free like Unity Free, but it’s way more fun to take up the challenge of doing it myself). It may seem like the circuitous way of going about making a game, but it makes sense. Promise. So yeah, this update is focused on my game engine, affectionately dubbed “Creation Tools.”

This is where I refer back to the beginning of this post. The best game engines out there are the ones that are the most user-friendly (in this case, developer-friendly). My endeavor with this update was to move some of the control and robustness of the oh-so bland-looking dev console to a more elegant user interface. A good interface for the engine means a happy developer, and a happy developer means, most likely, a better game.

Aside #2: By the way, when I say “game engine” in reference to my project, I really don’t mean some separate software that I use to create this game. Instead, think of it more like a “mode” in the game. I can switch in and out of controlling the world and playing the world with a simple command. It’s a lot like how creative mode works in Minecraft, but this one gives you more control over what’s going on.

They say a picture is worth a thousand words, so I suppose I’ll throw a picture at you before I babble too excessively:

Pic 66

So, the first thing you’ll notice is that the reticle looks much fancier now. See those four pixels in the center? That’s basically the biggest improvement I wanted to show you.

Naah, actually I do believe I have a shot of that in the last post. There is a lot to talk about in this screencap, but I want to start with the vertical bar on the side. That’s a hotbar, allowing me to quickly navigate between several (silly) block textures. This is extremely useful because I can now see what block I’m going to place before I place it, and selecting a block to place is much simpler and more painless than typing in the block id in the command console. There are even tabs at the top! I can swap between tabs on the hotbar by pressing either Q or E, and with 10 blocks per tab, this means that I currently support up to 30 different block types. Of course, I can expand it later, but since I haven’t even made that many textures, there’s no point. The next nugget to which I’d like to draw your attention is the highlight on the block I am currently aiming at. The white box indicates the block I wish to edit, and the faded grid lines give a faint impression of where other blocks could lie on the same plane as the selected block face. I’ve found that the lines coming off of the corners of the cube face there really help to measure distances while also managing to not be a visual nuisance.

I have to say that, at this point in the project, I’m pleasantly surprised with how well each part of the program holds up. With each new feature I add, there’s always the possibility that it will break something else or expose a never-before-seen bug. Most of the time, in the past, this was the case. Frequently, the bugs would manifest themselves in the likes of falling through the floor on occasion, getting stuck in the ceiling, being unable to connect to the server, or removing three of the six walls from existence. These I can usually resolve in anywhere from half an hour to a few days. Once I’ve addressed a bug, however, the part of the program that originally caused the bug tends to leave me alone, and I can forgive and forget. A great example of this would be what I have called in the code “bullet collision.” This chunk of code dictates how bullets (or projectiles in general) interact with my environment, and it was all fun and games until I started using it for highlighting blocks on the screen. The game decides which block the player aims at by shooting bullets at very high speeds as frequently as it can and returning the coordinates of its collision. Then, with this information, the the rendering code draws a white outline around the collision coordinates. To make a long story short, this exposed a nasty bullet collision bug where bullets would occasionally lose sight of their life goals as a speedy projectile and forget to collide with anything. It took me a couple of months to find the right solution. Now, so far as I can tell, bullet collision is working as well as ever, and placing blocks in a room has never been easier.

We are nearing the end of this post, but wait! Don’t leave yet. This doesn’t mean you’ll be stuck anticipating the next post for five more months. I’ve decided to break this update into three different parts because there are just too many new features to reasonably cover in one post. Hopefully now you have a better understanding of where I’m going with world creation, and next time we will take a look at saving and loading and the implications thereof.

Ok, I feel bad for leaving you with just one screencap after so long. Here is one more (and it’s a GIF!!):

It moves!

This is what it looks like when another person is shooting a bullet through a tube with holes in it in multiplayer.

EDIT: Ok, maybe I should have thought this out a little bit better. Yes, I have added features involving saving, loading, naming, washing, feeding, whatever rooms, but it doesn’t really warrant writing an entire post about it since it’s relatively straightforward without any amusing accompanying screencaps. Sorry for the confusion! Part 11-2 instead covers changes in the game’s lighting.

Making a Voxel-Based Shooter – Part 10: Lighting, Opto, and Blocks!

Oh my, what’s that I hear? Is that the sound of a New Blog Post?

No, of course not! Blog posts don’t make any noise at all (at least not from my end of things), but you probably aren’t mistaken if you think you’re currently looking at one. Yes, it has been five months since Part 9, and yes, I miss you too.

Part 10, hmm. Doesn’t that mean I should have something especially special in store to share? 10 is a multiple of 10, after all, the very basis of the decimal system. Also considering that I’ve built this post up for so long (5 months of suspense… it works like that, right?), I sure as anything better have made some interesting content to share with the Web of the World. Luckily for me, and for you if you are reading this voluntarily, I have expanded this project in as many degrees of freedom as I can comprehend since we last met.

Let us begin with the more minor improvements. I looked at my game (5 months ago) and thought, “Huh, what can I do to make this project more intuitive?” I know that words like “intuitive” and “streamlined” are pretentious words flung around by game developers which often indicate that some features have been cut from development, but this is not the case here. I’m instead adding features to make the gameplay experience a tad more bearable. Among these features include smoother movement, independent of frame-rate I might add; the ability to fly and easily create/destroy blocks while editing, nice touches for when one wishes to edit; and a form of auto-complete for the command console that is not infuriating in any way so far as I can tell. Through testing, I’ve tweaked these and added other small features here and there, which all contribute to generating a more unified experience overall. There are more of these to come, actually, but the more I make, the more I realize that I could be making more! And more! … And more! Yikes, there’s a lot to add to the project at this point and in so many different areas, but it’s smarter to remain focused on the important aspects of the project rather than to be distracted by the smaller ones.

Now, on to the good stuff. You’re probably wondering by now why I haven’t talked much about anything that you read about in this post’s title yet (save for the blocks, but those have been in it since the beginning. Have you been paying attention?). I can’t tell you exactly why I’ve been doing that, but I can tell you that it is time to move on. Okay, lighting! What kind of lighting? I’m glad you asked. The kind of lighting that I want is the kind of light that you get when you put some light-emitting source somewhere, and light emits from it. Sound good? I think so too. The real challenge, conceptually, is the idea of having light blocked by walls and other various sorts of objects when it tries to go through them. To accomplish this, in-game, we need a way for “light” to emanate from a source and to check (as it moves from one voxel to the next) if it’s going to collide with a solid block.  To the best of my knowledge, this is considered to be, aptly named, “voxel lighting.” For testing purposes, let’s make the block of id = 2 our light source. For now the light does not travel outward; it should just light up the block where our light source is:

Pic 37That’s a start! It shows us that, at the very least, something is happening, and the game still runs – two positive things. Now let’s have the light actually emit from the block. The way this works is that I have a function that takes in a block location, light intensity, and total light radius. It checks all 6 adjacent blocks to it’s source to see if they are solid or not. If the block it checks is not solid, it will call itself yet again, making this into what is known as a recursive function! This time, it uses the new block’s location and a new, less intense, intensity. This continues to happen until all of the paths that the light travels eventually dwindle down to an intensity of less-than-or-equal-to 0, making them imperceptible to the human eye (or any sort of eye, for that matter). This light information is then used by the rendering procedure to color each face of each block to its respective brightness. Let’s see how it looks now:

Pic 38Neat! Not only does this work with static lights like these blocks, but it also works with dynamic ones, like if you shoot a focused beam of energy down a dark hallway to light it up as you find your way to your bedroom for the night.

Now, here’s where things get messy. See that frame-rate at the bottom-right of the screen? That’s 62, and I’m not limiting it to that. That’s my computer trying to run all of this as fast as it can, and though 62 frames-per-second is what many games shoot for (as most monitors I imagine run at 60 Hz), this will soon become unacceptable as more features are added. As the fps drops, the game appears more “jumpy” or “jittery,” and I’d prefer that I have more wiggle room with the frame-rate than this. That’s when we turn to what is known as optimization. Optimization is what happens when you find the places in your program that are eating up the most processing power, and you make them eat up as little power as possible. Usually, with games, the most time is spent rendering all of the pretty graphics. This is where I focus my attention. With some additions such as discerning between static and dynamic lights, re-calculating dynamic lights only when necessary, not rendering unseen cube faces, and saving the world mesh in memory, we get a significantly higher frame-rate and end up with something like this:

pic 43Err… this:

pic 42I mean… this…?

Pic 39Needless to say, I broke many things during this process.

Now that we have all of our ducks in a row, it’s time to go back to rounding out the gameplay experience a little. As I stare at the lighting for a while, I become increasingly distracted by the blockiness of it all. I mean, yeah, the world is entirely composed of blocks, but it’s still too… blocky. It would be nice to have a way to smooth it out – to make it more appealing to look at. Actually, the picture you see above sparked an idea in my mind. Do you see how the black smoothly grades into the purple? It reminded me that my graphics environment (OpenGL, remember?) will automatically interpolate the colors between the points on every polygon, allowing me to have smooth transitions between colors on each face of each cube. Smooth lighting? I think affirmative.

Here’s a highly scientific diagram that I drew to help illustrate how smooth lighting works:

Smooth Lighting Diagram

The black square outline in the center represents the face of the cube being tested for lighting, and its four corners are numbered. In order to accomplish smooth lighting on this cube’s face, each corner needs to take the average light from each adjacent block. For example, corner 3 will hold the value of the average light levels of cubes 8, 5, 6, and 7. Once each of the four corners has the correct light value set, the program moves on to the next cube face and then the next, until it is finished. When rendering time finally comes around, OpenGL interpolates the color values of each of the corners and makes a nice-looking cube face. Here is a scene with the usual lighting in place:

Pic 49and here is that same scene with smooth lighting:

Pic 50As you can see, the difference in frame-rate between the two scenes is unobjectionable, but it makes everything much easier to look at. Here’s another screencap of smooth lighting, just for kicks:

Pic 52This project is certainly shaping up to look like something! Having lighting and optimization relatively in place at the moment really takes a huge burden off of my chest. I am excited to get to the juicy new stuff, but unfortunately I don’t have any of it to show as of right now. It will come soon enough, though! Be prepared, next time we’ll take a look at the effects of Reggae on the human psyche.

Making a Voxel-Based Shooter – Part 9: Multiplayer

It’s here! The largest component of the game that I had my doubts about has finally been more or less implemented. It’s fairly raw at the moment, but polishing it up a little should not be terribly difficult. Let’s see how this was done.

It’s quite simple actually, how the “multiplayer” system is set up. You have a bunch of clients running the game, and you have a server as their intermediary. The clients once per frame each beam their current status (i.e. name, player location, player rotation, etc.) to the server, and the server replies directly by chucking a huge message right back containing the information of all of the other clients. If the clients send too many messages to the server at a time, the server just happily (and quickly) eats its way through the queue, and the world keeps spinning. The clients, if without a response from the server after a given period of time, give up talking and return an “error.” This system is a whole lot like a translator, rapidly translating for several people simultaneously who each have their own individual language and attention spans. The only real difference is that the computers do it approximately 753,000 times faster.

In practice, the server should be sending a package of info to each client at least 20 times each second. This means that the clients should each be doing about the same for the server. That may sound like a lot, but the computers eat it for breakfast, so they’re okay. The basic order of operations for the client when connected to a server looks a little like this:

1) Receive and interpret message

2) Take user input and alter game accordingly

3) Send message to server

4) Render all the things

5) Repeat until game is closed (or crashes)

If it isn’t connected to a server, it will skip steps 1 and 3.

Okay, so now that you know everything about there is to know about how it works, let’s take a look at how it looks in the game:

Pic 36

(that guy with the fancy red outline is another player)

That’s pretty neat huh? I thought so. Well, in case you haven’t heard enough of this whole multiplayer thing yet, here’s a nice video of it.

Making a Voxel-Based Shooter – Part 8: Setting the Stage for Multiplayer

I’m back, now with a brand new post about brand new things. These things include little improvements (excluding optimization [which shall come at a later date]) that contribute to the general preparation for multiplayer. I was actually preparing to make a single post regarding the addition of multiplayer, but I have decided to split it up into (at least) two separate posts in order to avoid one mammoth post hogging all of the other ones.

First off, I must say something regarding my previous post. SDL_ttf is a very nice library with a variety of functions, but what I didn’t realize at the time was that it is not necessarily intended for videogames – not ones that wish to run quickly anyway. It essentially cut my framerate in half every time I rendered text, so I had to devise an alternate solution. My solution was to generate some sort of sprite sheet for the text. This actually works quite well for my project, given that the text is already a very low resolution. All I had to do was allocate an 8×8 space for each character in a 256×256 texture, and now I have a wonderful place from which to texture things with text! I could use a smaller image file, but I want to give myself the option to have variations in the text (such as borders or shadows) sometime in the future. Since OpenGL (what I use to render textures) renders much more quickly than SDL, this was the obvious solution for my troubles. Here’s what a part of that text texture image looks like:

Pic 33

Now that that is all sorted out, what else did I add/fix? Well, a long-running issue I had ignored until recently was that my game didn’t run on other computers other than my own. Now it does. After I pinpointed the perpetrator and punished it, it decided to behave, and now it runs freely about every computer I’ve tried it on since! Another thing is that I added some subtle fog, just to add to the atmosphere (it’ll make more sense when I get to the post about lighting!). Here’s what the project looks like at the moment:

Pic 31

“Whoa, that’s different!” you say. Yes, yes it is. That new block texture you see is a sample texture from my totally cool texture artist. Also, that “white noise” stuff you see on the ground in the distance is fixable, and I know how; I’ve just decided not to spend the time on it quite yet (this picture is at a fortunate angle because that texture artifact usually looks much worse).

The final change I made to the visuals is text color. I am able to do this dynamically with code, which means that I only need white text in my text sprite sheet. I’ve decided to make green stand for success and red stand for failure, just like in real life!

Pic 32

As you can see here, “global.connect” is a new command I have not mentioned yet. This is what you would use to connect to a server in multiplayer, where the name of the host would come after the ‘=’ sign. At the moment, multiplayer is a WIP, but Post 9 shall cover my work on it extensively! Until then, laters.

Making a Voxel-Based Shooter – Part 7: The Command Console

Here I am, back from the dead with another blog post! Last time we left off, I was slowing down at a constant pace until the updates I was making to my game each week dwindled down to about 1 – 5 new lines of code, content clearly not worthy of making a blog post about (although a video was totally acceptable…?). Since then I have decided not to force myself to make an update each Saturday if I absolutely have no new content to share (and today is a Monday, so you can imagine how far, mentally, I have strayed from my initial template). All of that aside, I can tell you that this “week,” I have some new content to share with you (cue the confetti)! I’m pretty pumped to talk about it, and I’m sure you’re eager for me to close my intro paragraph.

Ok, now that we are all on the same page, we can finally get to the actual meat of what I’ve been building up to: the command console! Yes, this is another update that does not particularly distinguish my game from anyone else’s in any striking or extraordinary way, but I must say that I am quite proud of its function and flexibility, both of which I will address somewhere in the post TBD (don’t let me forget!).

First things first (or third, as the case may be), let me tell you what it is I have made. It is a command console, where I am essentially able to, as the programmer (or potentially one of those “end user” things), edit values of variables within the game’s code at run-time. Pretty neat, right? Well, in reality, the user is constantly changing variables within the game’s code when he plays it (often even triggering chain reactions of variable changes), but the console gives you the ability to change variables that normally dictate but are not effected by gameplay. For example, a variable you might wish to change is the character’s jump height. All you need to do is, in the console, type something like “char.jumppow = 2,” and voilà! Your character now jumps with a “jumppow” of 2 (whatever that means), but I’m sure whatever you changed with the console has enhanced your overall gaming experience. Now, let’s get on to what it is one has to do to implement such a thing.

To put it simply, there is a lot involved. At least, it takes a lot to get started. Essentially, I set out with the task to give my game the ability to handle text, so, as usual when exploring lands unseen, I consulted the interwebs. The internet, for once, actually has a surprising lack of information on this subject. Actually, no, strike that. It has a surplus of information on the subject, including tons of various methods of implementation with varying degrees of complexity and versatility. And after hours of searching through complex documentation and useless forums (more on those in a future post *fumes of rage*) for the best option for me, I finally settled on SDL_TTF. This stands for Simple DirectMedia Layer True Type Font. All you need to pay attention to, though, is that this is a branch of SDL (basically another library created by the same people who made SDL and is thus compatible [big plus]), and it deals with True Type Fonts. This is probably the font file type of choice on your system.

Ok, enough introduction to what we’re doing, let’s get on to the pictures! As I’m sure you can imagine, my first encounters with SDL_TTF and subsequent attempts at making it work did not bode well (neither for my game nor for my sanity). Finally, after several rage-inducing attempts and variations of my approach, this is what I get as a result:

Pic 25

Yeah, it’s a square with blended vertex colors set at an angle. Believe it or not, this is actually a step in the right direction. The results I was getting before this were fatal errors, so getting something to actually display on the screen was a relief. What I did was disable all other visuals of the game because I wanted to eliminate all other possible elements of my game that could be tampering with SDL_TTF. This was part of the sample code that I was modifying, and I had forgotten to take it out. Once I removed our lovely square and wrote a function for rendering and handling text, this is what resulted:

Pic 26

The text reads, “Hello, world! / A line right underneath / Yay text rendering.” A bit hard to read? Yes, I agree, and it’s not just the font. It looks like somebody flipped the text upside-down! Indeed, I have. The reason? Well, as it turns out, this is something I did not cover in my previous posts, but when loading PNG files with SDL, it decides (for no real reason other than it’s own fiendish ambition) to load them flipped vertically. In most cases, however, this is not desired, so I flipped the PNG texture vertically again to counteract whatever SDL thought it was doing. What resulted, unbeknownst to me, was that every texture loaded from there on out, apparently including fonts, was to be vertically flipped. So, after this issue was located and the proper code was added to flip all textures vertically a third time, the desired results were attained:

Pic 27

Great! Believe it or not, our most arduous tasks are behind us. Now we just need to composite this on top of what we normally render onto the screen and add some features to it. Of course, the next step is to re-enable that code that does the normal rendering magic. When I did this, I noticed that there was a black background to each text box, a feature I did not intend to keep. After some more internet websearch discovery adventure, I put in a line of code to tell OpenGL to render stuff a bit differently:

Pic 28

Wow, I think my tendency to tell OpenGL to change one thing for me but instead receive several bonus changes as a result has become a chronic illness. As you can clearly see, there is no black background behind any of the text boxes, but OpenGL decided to make a few changes of its own along the way. Though it looks cool, it has to go.

Pic 29

Ok, we’re almost there! By this screenshot (taken at the end of a programming moment of inspiration) I have fixed the “texture blending” issue, have changed the font to something more legible, and have added input functionality! The next few steps are also the final ones. Phew!

Pic 30

Since getting into the details of how I made this part would take too long and are largely uninteresting (mainly because I suffered no emotional pain as a result of this step), let me summarize the main points for you:

– There is now a black two-toned backdrop for the text to rest nicely on (animated entry!).

– The console toggles its visibility with a single press of the “~/`” key.

– The input box for text now has a blinking “_” to show where your next letters shall appear when typed (animated entry!).

– There is now an input “log” for all of the commands (or “not” commands) that you may enter in (animated entry!).

– There is error handling too, so if the user (or me) types in something nonsensical (at least in the eyes of the computer), the program will catch it and smack your hand with a ruler (that’s what all those “Syntax Error”s are about).

Well, there you go! We now have a working command console! Also, before I forget, what I meant by saying that it is flexible is that it is easy for me to create more console commands for the disposal of the user. There is hardly anything that I need to change in the code to add them, so you can expect to see more coming up here and there as the posts go on. In addition to this, it would not be out of the question for me to write some “auto-complete” code to make console-commanding an easier process if the number of different commands becomes unwieldy (I’m thinking like a sort of pop-up window that lists all possible commands beginning with the letter you type or something along those lines). Anyway, thank you for reading! The next portion of my game I plan to add is large. And when I say large, I mean it’s going to take up at least two blog posts. I won’t spoil any of the fun yet, but I can tell you that it’s my favorite element of the game so far, albeit, the one that requires the most research… See you then!

Voxel-Based Distractions – Ep. 1: Ace of Spades and Minecraft

Well, I have to say, still no new VBS update this week. I was too busy acquiring “inspiration” from my sources, i.e., Ace of Spades and Minecraft. These two games are both addictive AND voxel-based (do those characteristics sound familiar? Hint hint). No, just joking. I don’t find shooting lasers at walls all that addicting either (I do have “voxel-based” going for me though…). Anyway, now that the season of cross country has come to a bitter-sweet and schedule-freeing end, my Precious shall get a little bit more attention. My “precious” project, that is… All THTABA references aside, we should at least see a glimpse of a working command console by next week. Until then, enjoy a montage of me making a fool of myself on the internet:

Making a Voxel-Based Shooter – Part 6.5: Moving Slowly

Yes, this week’s update is about moving slowly. However, it’s not referring to the game character’s speed, but rather, mine. I’ve been incredibly busy this week, so being able to invest the time to create an entirely new update was nearly impossible. I made some minor changes and cleaned up my code a bit, but, in terms of new functionality/fun, this update is limited. Next week should be much less intense, so a normal update is most likely. My next goal of implementation in the game is a command console, where we will be able to input game commands at run-time and make neat things happen on the fly, as opposed to restarting it each time we want to make a change. Oh, also, here’s a demonstration video of this week’s pseudo-update!

Making a Voxel-Based Shooter – Part 6: Sparks

Now that we have all of the collision working for laser bullets, we should make something interesting happen when they collide with an object, right? Right. So, what do we do? We add (something with resemblance to) sparks! They should be an interesting way to denote the destruction of a bullet. Basically, I did not use any techniques not previously discussed in past blog posts to accomplish this, which is why this post will be shorter than usual. The methods I used include a list to hold all of the sparks (and other prospective particles) in memory, simple movement code, collision code similar to the bullet’s collision code, and a recycled texture. Along with all of this monotony, I chose to try something new this week: a YouTube video. For this, I created a splash logo, recorded game footage, picked some elevator music, and it was good to go! I’ll probably do more of these video things in the future as well, provided I can get my better microphone working. Regardless, enjoy!

Making a Voxel-Based Shooter – Part 5: Laser Bullets

Wow, this moment is quite exciting for me. I’ve always been fascinated with the Star Wars style of lasers, and now we’re finally able to put them in our game. However, it might be the most involved step we’ve taken in this project thus far.

First of all, these lasers are projectiles; bullets, if you will. They will basically be the same thing as bullets, actually, but I chose lasers instead because they are obviously much cooler. Anyway, for our lasers, I quickly realized my shortcomings a couple posts ago with the type of texture file I was using. With the switch from BMP to PNG, we now have an alpha channel, so we are able to accomplish such things as this:

As you can see there, we have sort of small, orange box things and another, longer orange box thing that trails off into faded squares. For now, those are our reticule and laser textures, in respective order. What we do next is, in our render loop, find a place after everything on stage has been rendered, and render the reticule separately there. That way, it won’t interfere with on-screen objects, and on-screen objects get to mind their own business. Our result is this:

 

(The darker-green, inner border on the block textures is just something I added to make the visuals slightly more bearable)

Now we can see the center of our screen at all times! That is a very useful feature. Also, it may be useful for aiming later on, but we’re not quite there yet.

When I began working on making laser bullets work, I ran into problems. Lots of problems. I hadn’t initially realized all of the new things I would have to learn to be able to incorporate a dynamic number of independently rotating and moving 3D objects into my game. Suffice to say, it was an adventure. But, as with all adventures, you need to take your first step somewhere. For us, this first step is to add a dynamic number of cubes when the user left-clicks that don’t look like, rotate like, or move like laser bullets. What I did is “borrow” some of the code I used to draw the environment and then change the texture and make it pop up wherever the character is when the user clicks. And thus, the result:

I had jumped around a bit to emphasize the neatness of stationary blue cubes. One hurdle I had to overcome (or rather stumble over several times) was finding the best way to control a dynamically growing (and potentially shrinking) number of bullets in the game. If you remember, I used arrays to handle the cubes, but the size of arrays can neither grow nor shrink. It’s static, but it does have the advantage of speed and simplicity. Basically, I found the template type “list”, which can grow and shrink, and it allows you to add and remove things from whichever place of the list you please. It is truly quite handy, though a little more difficult to work with than an array.

Next step: Give the “bullets” correct textures, rotation, and movement. This step was just about as error-ridden as the last one, mostly due to the rotation part. I tried countless methods of managing the rotation until I finally found the magic equations. One slightly humorous result of one attempt was that I told all of the bullets to keep the rotation of the character’s view. So, where the character looks is where the bullet would be facing if it is shot. What I didn’t expect, however, is that it would repeatedly be set to the character’s rotation in each update. In essence, if you turned 90 degrees after shooting a bullet, you would have a sideways-moving bullet.

With this step implemented, we now have a fancy little bullet that can fly according its own free will. (but not really)

And, since I was very happy with my rotation and movement maths, I decided to take this picture as well:

Here, the laser bullets are moving at ridiculously slow speeds, but it does create kind of a neat effect.

Moving on to the final step in adding bullets to our game (for the time being), we find that we need to perform collision detection. This is an interesting step because it’s actually handled quite differently from the character’s collision detection.

Again, this is a two-part process. First, it picks out the possible victim cubes for collision testing, and then it tests them. Picking out cubes for testing was actually about the same as it was for the character, but the actual testing was different. This time, we treat the bullet as a line in 3D space. I worked out a fun little algorithm for discerning whether the line has passed through the cube or not and on which side, and that’s all we need! There were some minor (major!) issues along the way, but they managed to get ironed out. Now we have working collision detection (and sort-of reaction) for the laser bullets, and, as an added bonus, it works correctly no matter how fast or slow the bullet is moving (a great feature for sniper bullets). Here is a picture of me testing it:

Yep, it appears to be working just fine…

Well, that’s it for adding laser bullets to our game for the moment. In Part 6, we get a little fancy with our collision reaction and add particles to the mix.