19
Jul
13

What is the size of a signed data type in Visual C++?

So, I was compiling some code the other day with warnings-as-errors enabled, like you do, and I hit a curious one:

 warning C4309: 'initializing' : truncation of constant value

This particular warning is generated when the code attempts to initialize (or assign, or convert) a variable (or parameter) to a value that is larger than the variable’s type can handle. The thing that makes this curious is that the line in question looks something like this:

short const tmp = 0xFFFF;

I’ll save you the bitmath and the Googling for the size of a short in Visual C++ and just tell you that, according to the documentation, a short is 2 bytes (16 bits) and so is 0xFFFF, which sets all 16 bits to 1. The above statement will generate the warning for any values of 0x8FFF and higher. Even more interesting, setting an unsigned short to 0xFFFF does not generate the warning. Does this mean that in VC++, signed shorts are actually 1 bit shorter than unsigned shorts??

Probably not. More likely, this just means that the compiler is being a bit aggressive with this warning. You see, Visual Studio (and g++, for that matter) has no objection to this code:

short const tmp = -0x0001

This is theoretically the exact same value as the first line, because VC++ uses two’s complement (which is not enforced by the C++ standard, by the way, but is used by most compilers) for the binary representation of signed numbers. My (mostly unsubstantiated) guess, though, is that the VC++ compiler throws this warning on the first statement but not the second because 65535, the unsigned value of 0xFFFF, would have to be be truncated to fit into a signed short (where the maximum allowable value is 32767), so the compiler would prefer it if you just used your negative sign to indicate your negativity, rather than the most significant bit, like any sane programmer would.

In this case, I think I’ll just suppress the warning.

14
Jun
13

How to Make a Really Good Game with a Female/Gay/Person of Color Protagonist

Lately, it seems that a number of people believe it’s more difficult to write a game with a female protagonist than one with a male protagonist. As a game industry veteran (four years counts as a veteran, right?), I’m here to tell you that it can be done! Follow these easy tips, and you’ll have an awesome, high-quality game with the protagonist of your choice:

  1. Decide what kind of game you would like to make. You can use any combination of the below, though there are many more:
    1. Shooter
    2. Roguelike
    3. Music
    4. Point-and-Click Adventure
    5. Puzzle
    6. Turn-Based Strategy
    7. RTS
    8. RPG
    9. MMO
    10. Sports
  2. Come up with some really kickass mechanics.
  3. Write high quality code
  4. If your game has a story and a protagonist, construct a fun, relatable story with your protagonist
    1. Consider giving your player the option of choosing their gender/sexual identity/race.
    2. If you’re ever unclear on what sorts of encounters, relationships, or experiences that women, people of color, or gay people have, just ask yourself “What kinds of experiences do people have?”, then do that.
  5. Have a clear art direction.
  6. Playtest and iterate!
  7. Leave plenty of time for QA and bug fixing.
  8. Ship it.

That last one is the most important. Well, the last two. Well, okay, all of them.

Okay, yes, this is a bit snarky, and in fairness, it ignores stories that have a specific focus on gender-based relationships, like rescuing the princess (no, wait, it doesn’t have to be a princess, and the plumber can be male) or guiding a daughter-figure through a dangerous world (no, wait, it doesn’t have to be a daughter, or a father) or sexuality- or race-based relationships (I can’t think of any games that focus specifically on these).

There’s that snark again. Sorry. It’s just that it really is this simple. Of course gender/sexuality/race factors into a character, but for most people, it’s not the most interesting or pivotal aspect of their story.

</rant>

[EDIT: Ugh, I’m the worst. I knew I was forgetting something. You also have to have awesome audio design. Seriously, it’s critical.]

22
May
13

Default assignment operators and const values

It’s been so long! Update: I’ve been working primarily in C++ for the past four months or so. Hooray! I have so many drafts. I’ve really got to just start posting stuff even when it’s not (gasp) perfectly complete. Today, we’ve got another thing that I didn’t actually learn today, and it’s pretty basic, but I encountered a surprisingly bad suggestion from Microsoft’s documentation, and it seemed worth commenting on. You C++ gurus can probably skip this one.

You may recall, lo these many months ago, I posted about warnings-as-errors and why you should enable it. Well, I’m in the position of taking a large existing project and trying to turn that functionality on, and let me tell you, even with a lot of the work done for me — I was not the first, or even the second, engineer to tackle this — it’s no picnic. Reminder: turn on warnings-as-errors from the start of your project.

Anyway, one of the issues that has come up is the following:

c4512: The compiler cannot generate an assignment operator for the given class. No assignment operator was created.

For those of you not in the know, the C++ compiler generates a default copy constructor and assignment operator for you, unless you’ve specified them yourself. This warning simply means that, for some reason, the default assignment operator cannot be generated. Note that if some part of the code were actually attempting to use this operator, the compiler would throw an error, rather than a warning. Microsoft’s documentation on the warning helpfully points out that if you have any const members in your class, you will get this warning because a const member is not modifiable and thus assignment to it will not work. It continues to add that your options for dealing with the warning are the following:

  • Explicitly define an assignment operator for the class.

  • Remove const or the reference operator from the data item in the class.

  • Use the #pragma warning statement to suppress the warning.

The engineer who looked at this before me went for both the first and the second option. The second option is the wrong option, and frankly, Microsoft should be ashamed for even suggesting it. And while the third option is appropriate for some warnings, in this case, completely ignoring the error is almost certainly never the right answer. Even the first option isn’t quite on target, or at least ignores a possible solution.

I haven’t talked about const much in this blog, but I’m a huge fan. If a member variable is declared const, any programmer using that API can assume that once the data is set in the constructor, it will not change. Removing const-ness should not be done lightly, especially when (as in this case) the member is public. Removing this type modifier opens up that member to modification by any other code. Scott Meyers would tell you to “use const whenever possible” because it is such a strong contract, and I’m inclined to agree with him.

As I mentioned before, if any code were actually attempting to use the assignment operator, you would get an actual error — the code could not be generated, so anything attempting to use that code would not compile. So we don’t need an assignment operator. We just need for the compiler not to generate one. The fix for this is easy — declare it private in the header file and don’t define it. You can do this yourself (there are a million examples on the internet), or you can just make your class inherit from boost::noncopyable, which will also declare the copy constructor private, if you happen to be using the Boost libraries already.

This is a really great practice even if you’re not getting this warning. (I believe it’s one of the first item’s in Effective C++.) If you don’t expect your class to be copied, go ahead and declare the copy constructor and the assignment operator private.

27
Nov
12

#1reasonwhy

Every now and again I get the itch to post about women in the game industry. There aren’t very many of us, comparatively speaking. In fact there are even less than there used to be. But usually, I stop myself because I’m not a psychologist, I haven’t done any studies, and who really wants to read my opinions about this sort of thing anyway? In the last 24 hours, though, there was this thing that happened, and I feel the need to comment. Don’t worry — I’ll be brief.

These moments are important. Most of the women I know in the game industry are badasses, mostly because they have to be. There are lots of wonderful, welcoming places for women in the game industry, but I guarantee you that every female game developer you meet has run up against the sexism in this industry at one point or another, whether it’s being groped at an industry event or being told that their successes are a result of their looks or gender. One such experience can be shrugged off — some jerk was acting like a jerk. But when it happens again and again, it gets hard not to believe the hype, and that’s where the badass part comes in.

So, gentlemen, please listen and think when we talk about these things.

And ladies, please stay in the industry or join it. I’m usually lost myself, but I’ll be happy to be your #1reasonmentor if it means you make this industry a little less lonely for women. It really is wonderful to be a part of making these magical experiences.

14
Nov
12

C++ Basics: Static

I’ve been working on this long, boring post about the differences in equality comparison in Perl and Python and the fundamental differences of the two languages, but you know what? I’m sick of Perl and Python! And that post was boring! So let’s talk about C++ instead.

I’m in the unenviable position of not having touched a compiler (for work) in about a year. How do you live, Maitland?, you ask, Without C++, what gives your life meaning? Those are really wonderful questions for another blog, but the fact is, while I’ve learned tons in the last year about Perl and automation (and debugging and debugging and debugging), my C++ knowledge has been getting fuzzier and fuzzier. It’s extremely unnerving. Just yesterday, I opened up one of my favorite books and I freaked out because I saw my second favorite* C++ keyword, static, and, frankly, I wasn’t sure I could remember all of its usage. Thank god I have a blog so I can write it all down.

The static keyword can be the slightest bit tricky because it has several applications, and different implications in different situations. Some people will tell you that it behaves differently or that it means something different in these different situations, but I feel like this point of view overcomplicates the issue. From my point of view, static really just means one thing: it means that for the duration of the program, there will be only one of the described object or function. Once the thing is defined, it’s defined for the lifetime of the program. In fact, static objects don’t even allocate memory from the stack or the heap — they have their own separate memory segment, creatively called static memory.

Static Objects. Static non-member objects are probably the simplest usage of static. They look like this:

static int myInt = 42;

Once this variable is initialized, it’s there for the lifetime of the program. So if, for example, you put this variable in a header file, you can change that object in your functions or class members, and the change will persist. The example above uses an integer, but the concept is the same for user-defined types as well. Static objects are scoped in the same way that any other object is. If the object is declared in a header, it is scoped by the translation unit (i.e., the source and headers required to compile a given source file) that includes it. If it’s declared inside a method or function, like any local variable, it cannot be referenced outside of that method or function.

Static Members. A static member is much like a static object except for the fact that it belongs to a class. A static member is shared by all instances of a class. The biggest implication of this is that you can modify the member completely independently from an instance of the class. For example,

class MyClass
{
public:
  static int m_myInt;
}

MyClass::m_myInt = 0;

is totally valid code! Furthermore, any instances of MyClass can modify that member, and that change will persist until some other instance (or external code) modifies that member. Obviously, making a static non-const member public is fairly dangerous (as is making any member variable public), because you have no way of controlling who can modify it, but a non-public member can be very useful when you want to keep a reference count of something, for example. And when you combine static and const, you have a great way to store immutable data that may want to be scoped and defined at compile time.

One thing worth pointing out about static members is that, unless they are const and integral, you cannot initialize them within the class declaration. Logically, this makes sense, when you consider that you could construct the class multiple times, and, if the static member were initialized within the declaration, it would theoretically be re-initialized every time the class was instantiated. Because a static member is defined for all instances of a class, re-defining it in every instance would violate C++’s one definition rule. (C++ does make an exception for static const integral members, but if I’m being honest, I don’t entirely understand the rationale except “it makes life easier,” which, in fairness, is a good thing.)

Static Methods. Static methods (not to be confused with static functions!) have a lot in common with static members. Like static members, they can be referenced without an instance of the class. The natural implication of this is that static methods cannot reference any non-static members of the class. Because they don’t require state, static methods are especially good when you have software that uses callbacks. They allow you to group functionality with your class even when that functionality does not operate on the class’s state directly.

Static LinkageOkay, here’s where it gets a little tricky. Remember how I said that static really only means one thing? I kinda lied.

So, a long time ago, in a galaxy far, far away, there was a little programming language called C. And it defined static as a keyword, and it was slightly really a lot different from how C++ defines it. If you define (not declare) a method or function as static, the compiler, knowing that it has to be backwards compatible with C, treats this as static linkage. This means that your function or method cannot be referenced outside of the file it’s defined in. I’m sure there are good reasons to do this — certainly, it allows you to write helper functions that you don’t intend to be used outside of a certain file — but I can’t say I’ve ever used it myself.

I feel like I must be forgetting something, but I suppose that’s to be expected, given how rusty I am. Hell, I haven’t even talked about extern or referenced Meyer’s excellent point about how the intialization order of non-local static objects is totally undefined, meaning you should probably avoid that and use a local static variable inside a function instead. But this is getting lengthy, so I think I’ll close it off here. Next time, memory segments?

* My favorite being, of course, const.

20
Sep
12

The Safe Dereference Operator

Once again, I have gone months without writing, and I’m sure all two of my faithful readers are quite disappointed. Personally, I’m just shocked that summer is over already. If I’m being truthful, I thought about writing several times, but I could never come up with something that I learned that wasn’t so specific to my work that it was nearly irrelevant to anything else. (Though, as I write that, I think that I should put together a post about debugging. I do a lot of that, and there are a lot of things to learn there.) Today, however, I am inspired. I ran across this little gem while reviewing a coworker’s code:

foo?.getBar()?.getAttribute("baz")

At first I thought that the file might have been corrupted by the code review tool that we use. But just as I was about to open my mouth, I realized what was going on here. I have discovered a new operator, called the “safe dereference” operator, as it turns out, and I am in love.

If that syntax looks foreign to you, you’re in good company, or at least mine. Basically, that ?. checks if the preceding value is null, and, if it is, returns nullinstead of attempting dereference and throwing a NullPointerException. Because it returns null, you can chain these suckers and just check the final result for null before moving on with your code. Pretty neat, huh? I only see two possible, minor disadvantages. First, there’s no early out. If you have eighteen safe derefs chained, your statement will check for null eighteen times. If you have seventeen safe derefs followed by a regular deref, you may still get a NullPointerException. Second, it could potentially facilitate some really nasty code. Would you want to try to figure out which of those seventeen derefs returned null? Neither would I? That said, there are plenty of situations where you might not have to.

However, before you run off screaming, “I’m going to do this all the time now!” I do have some bad news. Shockingly, this amazingly useful operator isn’t present in every single language in the world. So far, I’ve only seen it in Groovy (a scripting language that compiles to JVM bytecode), and my coworker had previously used it in CoffeeScript (a language that compiles to JavaScript). So that’s very disappointing, but this feature is so useful, I have no doubt we’ll start seeing it pop up all over the place.

For more information, check out the Groovy documentation.

18
May
12

Five things to like about Perl

It’s been a while since I blogged, huh? Look, I never said I was reliable.

If you’re like me, you thought programming was for nerds until the year 2000, when you were surrounded by a bunch of nerds you liked, and then you gave in and admitted you were not-so-secretly a nerd all along and discovered you actually like programming. If that’s the case, you were probably raised to believe that Perl is evil. I certainly was. I heard all of the lousy things about how it’s totally unreadable, and how the variable scoping is weird and kind of leaky if you’re not careful, and how the subroutines are completely not self-documenting, and how it’s totally unreadable. Then I took a job that required me to learn Perl, and while I still don’t love it, I’m making an attempt to embrace new things and not become one of those people who is totally set in her ways and completely resistant to change of any kind. That’s a good thing, right? So, to that end, I give to you a list of things to appreciate about Perl. Read it before you go hatin’:

  1. Regular expressions support. Okay, this is the easy one. If you need to parse a string (or, say, a log file), Perl will make it real easy for you. If you don’t know what regular expressions are, dude, you are missing out. Start with the Wikipedia page (as always) and then check out this awesome cheat sheet. I could do an entire post on regular expressions (and I probably should!), so I won’t go into great detail, but basically, regular expressions provide a language for matching, grouping, and manipulating strings (or substrings) that allows you to operate on said strings in a concise and readable way. That’s right, I just said regular expressions and, by association, Perl were readable. Bring it on (in the comments), haters.
  2. String formatting. It’s a simple pleasure, but, boy howdy do I love the fact that I can reference a variable in a string in Perl. No concatenation, just embedded right in there. Love it.
  3. Compile-time failure. Obviously, this is a feature of all compiled languages, but Perl isn’t a compiled language! As a result, you get (some of) the benefits of a compiled language along with the development and iteration speed of an interpreted language. Pretty nifty, huh?
  4. Brevity. One of the reasons Perl is often unreadable is because you can do a lot in a one-liner. This can be incredibly frustrating, but it can also be incredibly awesome, especially if you do something crazy like add a comment.
  5. 37 ways to do anything. Another reason why people complain about the readability of Perl is the lack of consistency. This is because Perl provides eleventy billion ways to do anything. It’s a blessing and a curse, in that consistency is a good thing, and a hammer isn’t the right tool for every situation. So, it’s nice when you can come up with a screwdriver, even if that screwdriver doesn’t fit into your previously established pattern of hammers.

In all fairness, I still like Python better. I find that it has better support for object-oriented programming, a better (read:existing) type system, and is generally more human-parsable. In fact, I started this post with an attempt to come up with 10 things and gave up after 5. That said, as I learn Perl, perhaps I’ll grow to love it more. Perhaps.

20
Nov
11

Unemployment Survival Guide

I got a new job! As of this past Monday, I’m working as a build engineer at Bioware Austin. I’m super excited, and it’s a super exciting time to be joining the company, seeing as we’re just about to launch this little Star Wars MMO you may have heard of. I have a feeling that it’ll give me a chance to put some of that last survival guide to good use. In the meantime, it’s a good time to post-mort this last bout of unemployment, which, on the whole, went pretty well.

It may go without saying, but successful unemployed life requires a different kind of discipline than having a job. To some degree, I think it’s like being self-employed, except that instead of creating and selling your product and/or service, the goal is usually to (create and) sell yourself. While this affords a huge amount of freedom, I think it’s a hard thing for most Americans. For one thing, most of us have spent some, if not all, of our lives working for someone else, meaning we’re not used to setting our own schedules, making final calls, or even determining priorities. Certainly, we all do these things to some degree in other parts of our lives, like figuring out dinner for the evening or determining how many days to take off for the holidays, but when your whole day is wide open, every day, and you haven’t even necessarily set any goals or deadlines yet, it can be pretty daunting. But we’re game developers, so we’re all used to daunting tasks. We’ll just do what we do with all daunting tasks — break it down!

  • Have goals other than “get a job.” If you’re like me, your first thought when you found yourself unemployed was “Oh, crap, I need a job!” This is a fine and laudable goal, but it’s easy, if you’re career-oriented, to get a kind of tunnel vision, where this is your only goal.  This can be dangerous, and not only for the obvious reasons. You see, despite what Herman Cain has to say about the matter, getting the job you want is something that’s almost entirely out of your control. That’s not to say there’s nothing you can do to work towards the goal of getting your dream job, but when it comes right down to it, there’s no way you can make that employer hire you. As of August 2011, about 9.1% of the population is unemployed like you are, and I’m guessing that about the same number are employed but looking for a new job. Add to that the fact that the video game industry is pretty attractive, and the odds are pretty good that there’s at least one more person out there who is better qualified for that job you want. It sounds pretty bleak when put that way, and it kind of is, particularly if you have no other purpose. So, instead of obsessing over something that’s not in your control, reassess and start making goals that you do have control over, like “exercise 3 times this week” or “make something I’ve never made before for dinner tonight” or “make a single level of my rogue-like work before I go back to playing Batman: Arkham City.” Silly as it might sound, achieving these small goals will give you more confidence (which is key in interviews), and when you really think about it, is your major goal in life really to work for someone?
  • Stick to a schedule (roughly). On the first day of unemployment, I set some goals for myself and told myself that I had plenty of time to get them done. Then, somehow, ten hours had gone by, and I’d done nothing but play Arkham City. I used to think that schedules were mostly for the benefit of coordinating between people, so I’m a little embarrassed to admit that it took nearly a week for me to figure out that I would be much more productive if I imposed a very loose schedule on my day. It wasn’t a crazy rigorous schedule. That wouldn’t have made sense, given that every day was different, and it might have restricted me unnecessarily.  The important thing is that this is a tool to help you get things done — you want your schedule to work for you, rather than the other way around. Mine went a little something like this:
    • 8-9AM: Get up.
    • 9AM-10AM: Code.
    • 10AM-12PM: Play video games, watch TV.
    • 12PM-1:30PM: Gym.
    • 2PM-5PM: Look for jobs, errands, explore Austin, possibly code a bit more.
    • 5PM-12AM: Make something awesome for dinner, free time.
  • Get the word out quickly. I actually stole this from some other list of tips for the unemployed, but I think it bears repeating. When I got laid off, I was embarrassed. I felt like it had to be because I wasn’t good enough, and I didn’t want anybody else to know. The fact is, people get laid off for all sorts of reasons, and potential employers know this. So, while you might be cringing on the inside, suck it up, and tell as many people as you can that you’re looking for a new job. Potential employers aren’t interested in candidates who play hard-to-get. And, while it’s a royal pain to update your resume, if you just sit down and do it, you’ll be done before you know it.
  • Do that stuff you never have time for when you’re employed. This one is pretty straight-forward. Clean your apartment. Go to the bank. Get your glasses fixed. If you have medical insurance, go to the doctor and the dentist. Buy some new clothes, if you have some savings. Check out a new part of town you’ve been meaning to see. Do your taxes, if it’s that time of year. Cook something that takes all day. Work on your personal projects. Read some books. Play an epic, all-day game of Civ. Now is the time, because even though you tell yourself that you’ll do it on weekends and evenings when you’re employed, it’s a hell of a lot easier to take care of it now.
  • Chill. You have just been relieved of a lot of responsibility! Sure, you’ve got bills to pay and things to worry about, but if you’re behind four people in line at Starbucks, all of whom take 10 minutes to order, who cares? You don’t have to be anywhere. You know that saying, “time is money”? It’s not really, for you, anymore. Sure, you’ve got things to do, but free time is no longer a restricted commodity, and you won’t be letting anyone down if you get to the grocery store half an hour later than you expected to.

I could probably overanalyze the unemployed productivity problem for ages, but I’ll stop for now. The last thing I’ll say is that this is a great time to pick up a personal project, if you don’t already have one. I had two in the works, and I ended up making some pretty good progress on one of them, putting the other on the back burner, and picking up a new one. In the process, I learned a few things and stretched my brain a bit. Meanwhile, I relaxed, made some serious progress on my video game and TV queues, and got a lot more healthy. Honestly, I may have to find a way to take a month off every year!

19
Oct
11

The Definition of Irony

Normally, I don’t use social networks to complain about work. I don’t think it’s too much of an exaggeration to say that I pretty much never do it. I figure that it’s just not a great career move, given that everything you put on the internet can come back to haunt you. Yesterday, though, Batman: Arkham City came out. And I have been waiting for that game for months. And I was dealing with a really annoying linker error. So I gave in to my baser urges and sent this tweet:

A few hours later, I learned that my contract was being terminated.

It had nothing to do with the tweet. Or my performance, for that matter. They simply didn’t have work for me. So, I’m looking for work, as a programmer, hopefully with an Austin-area video game company. I have a bit more resume polishing to do, including adding this most recent job, but the most recent version is (and forever will be) here. So, if you’ve got any leads, please do send ’em my way, and if you don’t, just send good vibes. The good news, for all 2 of my loyal readers, is that I now have a lot more time to work on my personal projects, so I’ll probably be blogging a lot more about all of the stupid mistakes I make.

Today, though, I’m playing the hell out of Batman: Arkham City.

14
Oct
11

r.i.p. dmr

It’s been a rough month for technologists. Yesterday, Dennis Ritchie died at the age of 70.

If you’re a programmer, and you don’t know who Ritchie is, you should, because his work has had a serious impact on your life. He’s the co-creator of UNIX, from which Linux, Mac OS X, and CellOS (the PS3 OS) are all descended, just to name a few. He literally wrote the book on C because he created the language.  (The C Programming Language, cowritten with Brian Kernighan. Yeah, it’s that skinny little book gathering dust on your shelf because you’ve been too busy with all of those C++ books.) Even if you’re not a C programmer, if you use C++, Objective C, C#, Java, Python, Ruby, or even some shell scripting languages, you’re using a C descendant, or at least something heavily influenced by C. He played a very major part in shaping the computing world into what it is today.

Thank you for everything, Dennis Ritchie.




About

My name is Maitland Lederer, and I’m a video game developer. I learn stuff you probably already knew and have opinions you've probably already heard. I figured it might be a good idea for me to start writing down the stuff I've learned so I don't have to relearn it. It's not, like, great wisdom or anything. It's just things I happened to learn, usually today.

Header photo by D Sharon Pruitt, used under a Creative Commons License.