Tuesday, June 17, 2008

Firefox 3: A Five Act Tragedy

Act I: The Hype

I first heard of the Firefox Download Day at the office, from a co-worker. It wasn't a dark and stormy night, however much we all wished it to be -- the A/C was on the blink yet again.

Naturally, my curiosity was piqued. I've been using Firefox for years now and I've grown used to it and a bunch of add-ons for it. Sure, it had a couple of annoying bugs, but I could live with those. Of course, a new and improved version was likely to get rid of them, which would have been incentive enough to check it out.

So I went to the "Spread Firefox!" site to find out what the fuss was all about. When I found that Mozilla not only planned to give us all a new version of my browser of choice, but also establish a Guiness World Record, I was hooked. I pledged right away and also scheduled a reminder in my Google Calendar, to make sure I wouldn't forget.

Act II: The Outage

It seems childish in retrospect, but I got really excited. Not only was I going to get my hands on the hottest piece of software on the Web, but I was also going to be a part of the effort to set a Guiness World Record. And I wasn't the only one around: a few other co-workers were as excited about this as I was.

When the big day finally came, I made sure I was busy working to keep my mind off the wait. The time passed quickly enough and when the clock was finally done ticking its way to 1 pm, I went back to the Firefox site. That's when I got my first surprise: the site was down.

It's not unusual for a site to be brought down to its knees by overwhelming interest, but I would have expected Mozilla to be prepared. After all, they were the ones who did their best to attract all that attention. Why make a fuss if you can't cope with the results?

After a couple of hours of doing a Wile E. Coyote impression, Mozilla finally got its stuff together and I was finally able to download my copy. Once it was on my disk, I wasted no more time and clicked through the install impatiently. At last, the moment of truth was at hand: I launched Firefox 3!

Act III: The Incompatibility

The first thing my new Firefox did was to check my add-ons. It then proceeded to notify me that less than half of them had updates compatible with version 3 of Firefox. That left more than half of my add-ons disabled.

Being a coder means that an essential part of your job is to imagine worst cases for your code, so
I generally try to be an optimist about everything else, just to balance things out. Therefore I surmised that the Mozilla site was still experiencing difficulties. Did I mention that my optimism is rarely founded?

I spent some time fumbling with the new user interface, only to find out that the developers didn't stop at adding the add-on search into Firefox itself. They also decided to remove the link that took the users directly to the add-on page. I ended up checking manually and the add-on page was working quite well, thank you.

That's where I felt Mozilla managed to set a record, although it wasn't the one they were hoping for: I went from enthusiastic to disappointed in less than 5 minutes since I installed their software. What were they thinking?

Pretend you're in charge of developing a rather successful software product. One of the key advantages it has over the competition is its extensibility. There's a huge variety of add-ons for it and they do lots of different things, ranging from silly to extremely useful. Even though your users might be dissatisfied with some aspects of your software, they would still be reluctant to change to a product that doesn't have the add-ons they use. So what do you do when you decide to develop a shiny new version of your product?

The fashionable answer seems to be "break the add-ons that worked nicely with the older versions", even though the history teaches us the opposite.

Okay, I understand that you can't always maintain compatibility. Sometimes, preserving compatibility is in direct conflict with a higher-priority design goal and you just have to go ahead and break stuff. What you do in those situations is to try to minimize the damage, which is what Mozilla tried to do. But what do you do about the stuff the remains broken?

Here's what you do: you make your installer check the compatibility and report to user before installing the new version and breaking your user's stuff.

Act IV: The Retreat

Once again life conspired to remind me why I'm a late adopter. After a minute or two of staring at the list of things I wouldn't be able to use with Firefox 3, I decided to go back to version 2. A routine check of my download folder revealed that I apparently got rid of the installer at some point in time. No big deal, I can download it from the Firefox site, right?

Wrong! There is no link to Firefox 2 anywhere on the whole page. No matter how hard you try, you won't be offered a chance to turn back. And I tried very hard, trust me. Among other things, I tried typing "firefox 2" into the search box. That particular attempt rewarded me with zero results. I didn't even get a link to a press release or release notes for Firefox 2. Zilch. Firefox 2 has been exterminated.

Despite all its pictures of birds and balloons and a smiling Sun, the message Mozilla is sending its users is loud and clear: "Assume the position!"

In the end, I found the download link on www.firefox2.com, a site that features a prominent notice that it isn't associated with Mozilla in any way. It worked for me, but it probably won't work for you. As I'm writing, I'm also looking at the new content of the site, where every occurence of "Firefox 2" has been replaced with "Firefox 3", except the site URL, of course.

Just in case you really need to go back, the solution is to grab the Firefox 3 download link and change it manually to request the version 2.0.0.14. For example, the correct link to download the English (US) version of Firefox 2.0.0.14 for Windows is:
http://download.mozilla.org/?product=firefox-2.0.0.14&os=win&lang=en-US


Act V: The Repose

Having successfully overcome the unexpected difficulties, I decided it was time to wrap things up and go back to work. I installed Firefox 2 over its younger sibling and launched it. My optimism was proven unfounded yet again: Firefox neatly crashed when it tried to load my saved session.

I tried a few things before I stopped fighting the inevitable and uninstalled Firefox. Hoping fervently that the problem would be solved this time, I reinstalled it and launched it.

By this time I was more than a mite miffed or a tad testy: I was positively pissed off. In the spirit of their decision that I won't need version 2 ever again, Mozilla obviously didn't bother to test the downgrade process.

Fortunately, it turned out that no drastic measures were necessary. I was back to Firefox 2 and all my add-ons worked again.

Epilogue

While writing this post, I stumbled upon this article that explains how to make older add-ons work with new Firefox. In short, it describes a quick hack that makes Firefox skip the step where it checks for add-on compatibility. The article was about version 3.0rc1, so I don't know whether this will work in the final release. I didn't try it and I don't intend to. I prefer to wait until all the add-ons I use are updated. Having a new browser that's shiny and sleek is cool, but being able to use it my way is way cooler.

Thursday, May 15, 2008

Piracy is Here to Stay

"With great power comes great responsibility." Wise words, Uncle Ben, but someone at BioWare wasn't listening. For those who hate following links, the short version of the story is that BioWare was going to implement draconian anti-piracy measures in Mass Effect and Spore for PC. In the end, they won't be doing it, but it wasn't for the lack of trying. Indeed, I tend to agree with Penny Arcade when it comes to predicting the next step in the war on piracy, a war that has a long history of going overboard.

What's interesting is the widespread reaction among the gamers:
Not only does this not make me want to buy the game, this makes me want to download a pirated and cracked copy even more
Funny, isn't it? I mean, when someone mentions using RFID for shoplifting prevention, you'll hear all sorts of privacy concerns and doubts about usefulness of such a system, but you won't hear people say they'll go shoplifting in protest.

So what is it that makes us perceive and react to piracy in such a different way? Let's take a look at some of the factors involved. Be warned, though: there's no magical happy ending to this story. Whether the hero defeats the villain and gets the girl remains to be seen.

Thou Shalt Not

Back where I originally come from, some 15 years ago, shops didn't have any shoplifting prevention mechanisms besides humans and, if the shop was large enough, mirrors. We all knew shoplifting was wrong, that it was stealing, that it was crime. We also knew that getting caught would have serious repercussions. Yet there were kids who did it. Not out of necessity, either. They did it for fun. It was challenging. It was a game.

Where am I going with this? There are several points I'm trying to make here. First of all, crime has a lot to do with perception. Sure, there's law, with its letter and its spirit and a bunch of lawyers and politicians to play with it. If you break the law, you're a criminal and that should be it. And yet, none of those kids saw themselves as criminals.

Second, it's in people's nature to do as they wish and rules be damned. You can try to educate them, to impress upon them that such behavior is wrong, but there will still be those who will do it and for a variety of reasons, too.

It might sound like I'm trying to justify piracy, theft and crime in general. I'm not. I'm trying to point out that they will always exist and that reasons for it are not as monolithical as we would like to believe. After all, it would be a lot simpler if people committed crimes because they're evil, but the world doesn't work that way. And if we want to do something about a problem, we have to understand the cause.

Can't Touch This

Every time I rent a DVD, I have to watch one of the MPAA's anti-piracy videos. There's no way to skip it, of course, so each time I'm freshly reminded of the first and foremost difference between stealing and piracy: intangibility. In order to steal a car, a handbag, a television or a DVD, just like in the video, you have to reach out and grab something tangible. There might be a lot of objects like that one, but there is only one of that particular object and it's not yours. Taking possession of it is clearly identifiable as a crime.

Things are not as intuitive with music, movies and software. Sure, if someone invites me to their house to watch a DVD with them, it's not a crime. They're sharing their property with me of their own will. If they offer to give me a lift in their car, it's the same sort of thing. But you can't copy a car like you can a song, can you? You can't parody a car, either, or quote it.

Intellectual property is a complicated and muddled concept and requires an equaly complicated and muddled definition of fair use. With the massification of the digital content and media, things got even more complicated and muddled, which brings us to the chaos we're living nowadays.

And chaos it is. How else would you call it when in one corner you have people who demand that all the digital content be free, as in free beer, and in the other corner you have giants like RIAA suing random individuals?

The Age of Middlemen

So far we've looked at some of the factors causing the piracy. But what about the effects of it? Organizations like MPAA and RIAA are claiming that they are losing money. Publishers like EA are complaining about the same thing.

Let's get one thing clear from the start: developers need game sales to survive. They develop games for living and their money comes from sales, just like your money comes from the job you're doing. There is no doubt that if you install and play their game on your computer without buying it, you're using the products of their work without them receiving your money for it.

Notice, however, that I haven't mentioned publishers in previous paragraph. What does RIAA stand for? Recording Industry Association of America. The keyword here is "recording". The people RIAA represent are those who make money by selling sound recordings of music. That used to be very straightforward: they used to sell records.

Vinyl records are a bitch to duplicate. As long as they were the medium for sound reproduction, the recording industry could control the music industry by controlling the medium itself. The advent of magnetic tapes brought the first crisis. The big guys freaked out, tried to defend their territory and lost. That was the major turning point in the history of copyright.

Evolution

Notice how MPAA is making a lot less fuss than RIAA? You know why? Their industry kept evolving. Sure, nowadays you can watch DVDs on your HDTV in your home-theater, but nothing beats seeing the very first screening of the long-awaited movie in your theater of choice. Besides, everyone and their grandmother will have seen the movie before it comes out on a DVD.

The first important factor here is that movie industry still has a meaningful experience to offer to their customers, beyond merely distributing the medium on which the content is stored. The second important factor is that there's ample segmentation. You can choose how much you care about a movie: will you go to a theater or buy a DVD? Or you might rent it before deciding whether to buy it. Or you might just wait for it to come out on cable. Plenty of options out there.

RIAA, on the other hand, got stuck. They just sat there while their golden goose spread its wings and flied away. Well, they didn't just sit. They kicked and screamed and made a hell of a fuss. They're still doing it, in fact. But they failed to adapt and are paying the price for it.

It's something I realized when I went to a Dream Theater concert in March this year. These guys didn't only play their instruments and sing their songs. No, they staged such an impressive multimedia spectacle, that I didn't even mind the fact that they didn't play most of my favorite songs. After a show like that, which in itself must have made them a pretty penny, they could've sold me their newest album without needing the middleman at all.

Or could they?

Eye of the Beholder

Piracy, like I said, has a lot to do with perception. You can call it culture or mindset or education, but the fact is that I don't know many people here in Chile who buy their music. If you look at it from their point of view, the reasoning is simple: why should they? It's out there on the Internet, for free. We all use MP3 players these days, so why should anyone pay for an overpriced lump of plastic that later you have to insert in a drive and rip and transfer to your player before you can listen to it comfortably?

Musicians, that's why. People who make that music need the money. Then again, the record industry screwed things up on that front too. The public perceives them as people who take huge cuts of profits and exploit the authors. It doesn't make piracy right, but it makes it justifiable in people's eyes. We come again to perception.

And perception is a lot bigger problem than most of us would like to admit. Could Dream Theater really have sold us their music directly, without going through the recording industry? Why would we buy it, when we're so accustomed to getting our music for free?

Detox: Rehab or Jail?

A habit is formed. How do we break it? MPAA seems to think the answer lies in the propaganda. The effects remain to be seen, but I personally doubt it will have any significant effect. RIAA, on the other hand, thinks the answer lies in the law enforcement. We've all seen how that's working out so far and I think we can agree that the idea is laughable.

What about software? Specifically, what about games? The software industry in general is not as monolithical as recording or motion picture industry. For example, applications targeted at big corporations don't have to worry about piracy too much, but their target is not as big as the home user market. Each type of software has its own worries, but games are in a particularly hairy situation.

The problem with the games industry is that it resembles the recording industry. As the saying goes, the developers make the game and the publishers make the money. They're not limited to being middlemen, though. Often they also finance the development, which gives them a bit of versatility when it comes to surviving the paradigm shifts. However, the fact remains that the online distribution channels will be making the publishers' role as middlemen increasingly obsolete as time passes. Of course, online distribution brings its own middlemen, as casual game developers are discovering.

Safe Hex: ACME Copy Protection

So how does the software industry fight piracy? We geeks tend to believe that everything can be solved by technology. Thus the copy protection mechanisms.

Now, wiser geeks know that technology is not an answer to everything. As Fravia used to teach, there is no copy protection that cannot be broken. The one time I thought I found an exception to that rule was when I used Kali. I was wrong, of course. The program itself is just a client for the centralized service and, as such, it can be copied as freely as you want. It's semantics, I know, but it's important.

The reason why it's important is because that solution doesn't apply to most games. The most notable exception are the MMOs. Incidentally, it's a pretty important factor for the popularity of this genre among the developers.

The rest of the genres have to choose whether to use copy protection mechanisms or not. If they do, they have to decide how strong to make it. Unfortunately, strong often means "problematic for the legitimate customer" along with "difficult to circumvent". This is what creates reactions of outrage, such as the reactions to the abortive attempt to "secure" Mass Effect and Spore.

No Silver Bullet

Okay, so the neither the propaganda nor the law enforcement nor the technology solve our problem. What's the answer, then?

Unfortunately, nothing worth doing is ever easy. First of all, there is no silver bullet. There's no magical solution to this mess. You can bet that the real solution won't bring you quick bucks and instant happiness.

I'm no expert on these matters and I can't say with certainty how to deal with this. However, I have a hunch and I'm willing to bet it's a good one: nurture the market.

Take the situation here in Chile. For one thing, games are outlandishly expensive. It's not just the price itself, it's how that price compares to people's earnings and other products. Second, there are too few stores selling games and their selection usually leaves a lot to wish for. There are too many obsolete games and too many crap games and too few hot items. Third, the same comments apply when it comes to renting games. Still, there are people who buy games. We do it because we like those games, we appreciate the effort it took to make them and proud to own them. But there's a lot of room for improvement.

What about countries like United States? Adapt. MMOs are just one trend. The Sims games are innovative in that they introduce a social component and allow people to create whole communities around them. Episodic content is another idea that has yet to be fully explored. Who knows what interesting new idea will come along next?

Above all, nurture the market. I don't know any comic book fan that opted to photocopy a comic book instead of buying it. They love comic books. They're quite fanatical about them. Games need the same kind of fans. And they sure as hell won't get them by treating their customers like criminals and making games even harder to install.

And Yet It Moves

So, what, piracy is here to stay and we have to learn to deal with it? Is that it? All this writing and I have no groundbreaking solution?

Yes, that's more or less it. I did warn you at the beginning that the future is still uncertain. Yet I'm sure it's not a dark one. Consider the fact that Sins of a Solar Empire has no copy protection and doesn't seem to need one. Consider the fact that casual games are successful enough to make Rockstar VP nervous.

Are "hardcore" PC games a dying market, then? Not at all. There will always be market for them and, if the industry does its homework, it won't be just a niche market. Though the lessons to learn may be hard, failing to learn them won't be fun, neither for the industry nor for the gamers.

Monday, May 12, 2008

Assassin's Creed

How can you know whether a game is good without playing it? You can't, really. It wouldn't be fun if you could, right? Fortunately, there are people out there who play games and then tell you about their experience. Some of them do it professionally, some of them just because they think the world really needs to know about those games. Assassin's Creed is one of those games that are good enough to make me want to join the latter group. However, unlike most such games, it also has defects that appeal to my inner ranter. Perfect blogging material.

Just to make it clear, this is not a traditional review, rich in detail and sprinkled with screenshots. My goal is not to give you a detailed description of what you experience as you play Assassin's Creed. If that's what you're looking for, then I recommend the Gamespot reviews, for Xbox 360, PS3 and PC. What I'm focusing on here are the strengths and weaknesses of the game. The idea is to help people who never played it before and people interested in game design.

Still with me? Okay, let's delve into Assassin's Creed.

Stunning Visuals

You know how games always look a lot better in reviews and trailers than when you actually play them? I expected the same to happen with Assassin's Creed. To say that I was surprised is a huge understatement. This game is simply beautiful.

My PC has a dated CPU -- the installer warned me that I don't fulfill the requirements -- but my nVidia 7900 GTX more than compensates for it. Even so, I can't configure the graphics to maximum quality and detail. Or rather, I could if I didn't mind playing a slideshow instead of a game. As it is, the graphics are still stunning.

Everything is richly textured and beautifully illuminated. Each city has its own personality. The devastating aftermath of war in Acre makes itself evident not only in its burned houses and damaged city walls, but it also permeates the very atmosphere of the city, thanks to the greyish lighting that stands in contrast to golden colors of Damascus and Jerusalem.

The animations flow smoothly and every now and then you'll get a very dramatic angle that showcases your prowess at swordplay during a fight with guards. Of course, sometimes the game will get it wrong and you'll get a spectacular shot of a tree or a merchant stand between you and the camera.

Another excellent detail is the blurring effect the game applies when you lock on a target. It's supposed to make you feel like an assassin focusing intently on his victim and it does a great job.

Parkour

When I first saw the word "parkour" my reaction went along the lines of "huh?" It turns out that most of us know of it as "free running". It also turns out that it's not the same thing at all. I won't pretend I'm an expert and, for that same reason, I won't explain the difference. You have Wikipedia for that and you can blame them for any eventual error in it. Suffice it to say that the gameplay of Assassin's Creed incorporates parkour in a most enjoyable way.

I remember that one of my friends once proposed to make a game about free running. We shot down that idea for various reasons -- where the hell were we going to get money for an AAA game anyway? -- and one of them was the fact that we thought it wouldn't be interesting on its own, that it needed something more. I still believe that, especially after playing Assassin's Creed. There's something immensely satisfying about ending your crazy race over rooftops with a spectacular pounce and stab that brings your hapless victim down with a startled, strangled cry.

By the way, if you're into game development, I highly recommend reading this Gamasutra article on parkour in Assassin's Creed and Crackdown.

Music and Sound Effects

When I heard that Jesper Kyd composed the soundtrack for the game I had high hopes and I wasn't disappointed. I personally think that he didn't outdo his work in Silent Assassin, but the score is still great: subtle enough not to intrude on your experience, yet dramatic enough to establish the appropriate mood.

I also liked the way NPCs contribute to the game's atmosphere: preachers, beggars, merchants and passers-by all have something to say and they do it in a way that successfully recreates the bustle of a living city. Of course, they have their limitations. If you start paying a lot of attention to them, you'll find them repetitive; but if you focus on your mission, like an assassin is supposed to, they'll provide a rich auditive tapestry to serve as a background.

Good Plot

I firmly believe that games are essentially stories created, in part, by players. Whenever you find yourself gushing with enthusiasm while you describe a match of Unreal Tournament to your friends, you're telling them a story. That said, games don't necessarily need a plot. But if you're going to play an assassin, it's good to have something to motivate you to kill your victims, right?

I'm usually quite critical about plots. It comes from being a fan of books in an age where most people read only newspapers or technical books, if that. I am glad to say that Assassin's Creed has a rather good plot. It's interesting and it's not shallow. Not one among the characters is what he or she seems to be at the first glance. There are layers to be peeled and they reveal that the world around you is not black and white, even though it would be a lot easier on your conscience that way.

Altaïr himself, the character which you control, is a decidedly unpleasant person at the beginning, not likeable at all. You might think it's dangerous gamble to do that to the character with whom you're supposed to identify, but it works out surprisingly well.

Major Cliffhanger

Few are the works that can get away with a cliffhanger. Endymion pulled it off and lived to tell (the rest of) the tale. Assassin's Creed tried to pull it off and excelled at pissing me off. And everyone else, judging by the reactions.

Yes, it's true that almost all of the mysteries that plagued you during the game are resolved at the end. But that's not enough for a satisfying ending. I don't know about people at Ubisoft, but I like closure at the end of the game. It doesn't hurt the sequel at all, just look at the Sands of Time. Here's an idea, Ubisoft: go read Jim Butcher's article about story climaxes. Just in case it doesn't help immediately, the ingredient you're missing is what he calls "resolution".

Cheesy Dialogue

Like I said, I'm a fan of books. That makes me spoiled when it comes to things like plot, dialogue and character development. I'm aware of that and I try to keep it under control when I'm criticizing a game. After all, games are a different medium and one of the worst kinds of game designer is the failed writer.

That said, I have to draw the line somewhere. In case of Assassin's Creed, I drew it here:
Rafiq: He must be stopped!
Altaïr: That's why I'm here.
I don't mind a certain amount of cliché in games. I don't require voice actors to be perfect. But some of Altaïr's lines are way too cheesy to tolerate. It doesn't help that Philip Shahbaz, the voice of Altaïr, seems to have exactly one tone of voice. I guess it's supposed to sound arrogant and menacing, which suits Altaïr's personality admirably, but even so, you cannot apply it to everything you say. Sooner or later, your players start perceiving you as sulky instead of menacing.

To be fair, I should state that not all of the dialogue is cheesy. Al Mualim has some excellent lines and his voice, Peter Renaday, did a very good job.

In-yer-face Interface

Just as I started with the most gushing praise of the best features, so I kept the worst for the last. Many reviews complain about the repetitive nature of the gameplay, but I don't find that to be such a big problem. Solving it would have been quite costly and the developers did their best to mitigate it by offering the player a variety of investigation missions and giving him the liberty to choose which to play and which to skip.

The worst problem, however, comes from some monumentally bad decisions that were perfectly avoidable. All of them have to do with the interface, but the crown jewel among them is the decision to give the player the freedom to move during the cut scenes.

Picture the following situation: After doing lots of investigative work that helped you decided where, when and how you'll assassinate your victim, you finally have him in sight. He's talking to someone else and nobody is paying any attention to you at all. You're free to move, so you start creeping towards his back. You're in position, the moment is perfect and you press the button. And nothing happens. You press the button repeatedly, muttering "stab him, dammit!" It's useless. You're in a cut scene and nothing you do will have any effect. The developers gave you a completely useless freedom and the only thing they achieved is to confuse you.

And they took away a number of very useful freedoms from you, such as the freedom to skip a cut scene or a tutorial. It's an old lesson, but people at Ubisoft haven't learned it. They didn't let you skip the cutscenes in Prince of Persia and they don't let you do it in Assassin's Creed either. Come on, people, it's a Twinkie Denial Condition!

They also took away your freedom to load and save as you wish, which is another Twinkie Denial Condition. While I appreciate that the game saves automatically whenever I finish a task or get to a checkpoint, I still hate it that I have to let the guards kill me if my assassination attempt didn't go the way I wanted, so that the game will reload the last save.

Then there's also the matter of quitting the game or switching the profile. To exit the game, I first have to exit to the Animus, then exit from the Animus, then "quit" the game, then select a profile (which one? doesn't matter, I want to quit) and then finally exit the game. Oh, and I have to confirm that I wish to exit, just in case I went through all that work by accident. Yes, I know this is probably only a PC issue and that the PC version suffers a lot more from not being properly adapted to keyboard and mouse, but it's still incredibly annoying. The keyboard and mouse problem can at least be solved, by plugging in a gamepad.

Conclusion

Don't get me wrong. I loved Assassin's Creed and I can't wait for the sequel, even though Philip Shahbaz will again be Altaïr's voice. I mean, let's give the guy a second chance, right? Seriously, though, I loved the game. Despite the obvious and perfectly avoidable problems, I recommend it warmly.

And if Ubisoft learns from their mistakes, the sequel should be even better.

Back in Blog

Well, I think I finally got the hang of this being-a-dad thing; at least enough to get back to blogging. Suuuure, blame it all on the baby, that's convenient. Heh.

Anyway, things have been hectic in my life, but I'm back and I have stuff to rant about again. That said, I'm probably going to blog less code and include more variety. Oh and the posts are probably going to be shorter. Like this one. Not everything has to be a great story or an essay, right?

Tuesday, November 6, 2007

.NUTS: Yield Not, Waste Not

Everyone agrees that iterators are cool. They're so cool, they've got their own design pattern. Even cooler than that, they made the folks at Sun introduce some (gasp!) new syntax into Java. Not to be outdone, C# goes even further: not only can you use iterators easily, you can also roll your own generators using the yield keyword. How cool is that?

To Litter or Not to Litter
As it turns out, it's not as cool as it sounds. If you care about memory allocation and garbage, then using yield is a bad idea. Before I go any further, let's explore this concern itself. Why would anyone care about memory allocation in a language with a garbage collector? Isn't the whole purpose of the garbage collector to abstract away memory allocation and help avoid all those nasty pointer-related bugs? If you find yourself nodding along to these questions, then I suggest that you read Joel's Law of Leaky Abstractions.

The reasons to care about garbage are diverse. In my case, it's because I'm working with XNA. That means that if I make too much garbage at the wrong time, the garbage collector will fire up and mess up my frame rate. As Shawn Hargreaves explained, there are two ways to prevent this. Myself, I prefer what he calls the Right Frequency Path, which is why using yield is a bad idea for me.

There are other kinds of software, where garbage might not be as critical an issue as in games, but you should still be aware of it. Too much garbage can cripple the performance of any system.

Garbage Generators

So far I have only claimed that yield is wasteful. Let's take a look at why it's so. Consider this short program:
using System;
using System.Collections.Generic;
using System.Text;

namespace Sandbox
{
 static class IteratorTest
 {
     public static IEnumerable<int> FibonacciYield(int max)
     {
         if (max > 1)
         {
             int a = 1;
             int b = 1;

             yield return a;
             yield return b;

             int c = a + b;

             while (c < max)
             {
                 yield return c;
                 a = b;
                 b = c;
                 c = a + b;
             }
         }
     }
 }

 class Program
 {
     static void Main(string[] args)
     {
         int sum = 0;
         for (int l = 0; l < 100000; l++)
         {
             foreach (int i in IteratorTest.FibonacciYield(17))
             {
                 sum += i;
             }
         }
         Console.WriteLine(sum);
     }
 }
}

Running CLR Profiler on this program might surprise you. Although there is no explicit allocation in the code, plenty of memory winds up in the landfill. The culprit is a class with a weird name: <FibonacciYield>d__0. In this simple example, it is responsible for a whopping 3.4 MB garbage pile. Where did that come from?

That's the price one has to pay for the magic. After all, when you write your own generator with yield, you're returning IEnumerable<T>, without even instancing it, let alone implementing it. But the return value has to come from somewhere and that somewhere is a compiler-generated class. If you run Reflector on the program and then take a look at the method FibonacciYield, you'll get this:
public static IEnumerable<int> FibonacciYield(int max)
{
  <FibonacciYield>d__0 d__ = new <FibonacciYield>d__0(-2);
  d__.<>3__max = max;
  return d__;
}

Just as suspected, that's where and how allocation happens. But what about our mysterious compiler-generated class with an ugly name?

Under The Hood

The dissasembly of the <FibonacciYield>d__0 class shows not only an implementation of IEnumerable<int> interface, but also a full-fledged IEnumerator<int> implementation. It has all the stuff a generator should have: the Current property, the Reset method and the MoveNext method.

At first, the code might look intimidating -- all this came out of that short method?! -- but a closer look reveals certain patterns. For example, take a look at the fields:
private int <>1__state;
private int <>2__current;
public int <>3__max;
public int <a>5__1;
public int <b>5__2;
public int <c>5__3;
public int max;

The <1>__state and <2>__current fields have to do with how the yield keyword itself works and I'll get back to them in a few moments. The rest show an interesting pattern: the local variables in the original method turn into <a>5__1, <b>5__2 and <c>5__3 fields, whereas the max argument becomes <>3__max field. But what about the max field? Why have both max and <>3__max? And why convert local variables into fields in the first place?

To answer that, remember how the foreach loop works: by calling the MoveNext method of the IEnumerator<T> interface and inspecting its Current property, until MoveNext returns false. This means that the state of whatever you're doing in your generator has to be preserved between two calls to MoveNext. In our case, the local variables of the original method are a part of the state that has to be preserved.

Speaking of state, the magic is explained when you look at the implementation of the MoveNext method:
private bool MoveNext()
{
   switch (this.<>1__state)
   {
       case 0:
           this.<>1__state = -1;
           if (this.max <= 1)
           {
               break;
           }
           this.<a>5__1 = 1;
           this.<b>5__2 = 1;
           this.<>2__current = this.<a>5__1;
           this.<>1__state = 1;
           return true;

       case 1:
           this.<>1__state = -1;
           this.<>2__current = this.<b>5__2;
           this.<>1__state = 2;
           return true;

       case 2:
           this.<>1__state = -1;
           this.<c>5__3 = this.<a>5__1 + this.<b>5__2;
           while (this.<c>5__3 < this.max)
           {
               this.<>2__current = this.<c>5__3;
               this.<>1__state = 3;
               return true;
           Label_00C5:
               this.<>1__state = -1;
               this.<a>5__1 = this.<b>5__2;
               this.<b>5__2 = this.<c>5__3;
               this.<c>5__3 = this.<a>5__1 + this.<b>5__2;
           }
           break;

       case 3:
           goto Label_00C5;
   }
   return false;
}

This is the heart of the compiler-generated finite state machine designed to react correctly to subsequent calls to MoveNext. The initial state is 0. Every time the compiler encounters a yield return statement, it creates a new state and generates the code that:
  1. sets <>1__state to the new state
  2. sets <>2__current to the value in yield return
  3. returns true.
By the way, don't try to plug this code back into the sample program. The C# compiler will reject it, for reasons about which I will rant in another post.

The final mystery is resolved by looking at the GetEnumerator method implementation:
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
   IteratorTest.<FibonacciYield>d__0 d__;
   if (Interlocked.CompareExchange(ref this.<>1__state, 0, -2) == -2)
   {
       d__ = this;
   }
   else
   {
       d__ = new IteratorTest.<FibonacciYield>d__0(0);
   }
   d__.max = this.<>3__max;
   return d__;
}

After doing some tedious deciphering, this turns out to mean the following: if MoveNext That has already been called on this particular object, then create a fresh clone; if not, return this object. That's why we have both <>3__max and max: since arguments can be used as local variables within a method, the former is the original value supplied to FibonacciYield and the latter serves as a "local variable" field.

Making It Tidy

Now that we know how yield works, we can concentrate on avoiding memory allocation. Fortunately, C# allows you to write generators without implementing the IEnumerator<T> interface, as documented in help file:
In C#, it is not strictly necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach; as long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of allowing you to define the return type of Current to be more specific than object, thereby providing type-safety.

Omitting the interfaces, in this case, has the added advantage of being able to implement a generator as a struct, without it getting boxed later. Your final generator would look like this:
public struct ScroogeGenerator
{
    private int state;
    private int current;
    private int max;
    private int a;
    private int b;
    private int c;

    public ScroogeGenerator(int max)
    {
        this.state = 0;
        this.max = max;
        current = a = b = c = 0;
    }

    public int Current
    {
        get { return current; }
    }

    public bool MoveNext()
    {
        switch (state)
        {
            case 0:
                if (max <= 1) break;
                a = 1;
                b = 1;
                state = 1;
                current = a;
                return true;
            case 1:
                state = 2;
                current = b;
                return true;
            case 2:
                c = a + b;
                if (c >= max) break;
                a = b;
                b = c;
                current = c;
                return true;
        }
        return false;
    }

    public void Reset()
    {
        throw new Exception("The method or operation is not implemented.");
    }

    public ScroogeGenerator GetEnumerator() { return this; }
}

A few things to keep in mind:
  • When you write your own value-type generator, make sure you never cast it into an interface, or it will get boxed and make garbage. The best way to ensure that is not to implement any of the IEnumerable or IEnumerator interfaces.
  • The C# foreach loop does not call the Reset method. You can leave it unimplemented or empty if you'll use your generator in C# foreach loops only.
  • Don't reuse an instance of a value-type generator across different foreach loops. If you intend to do that, implement Reset and call it manually before reusing the generator.

Wednesday, September 19, 2007

.NUTS: Cemented Collections

Another month has passed. My intention was to write another post sooner -- especially because I already had material for it -- but time flies when one is immersed in work. Now that I have some free time, I can sit down and share another one of my .NET anecdotes. And so, without further ado, welcome back to my .NUTS column.

Deja Vu

If there's one thing that defines a modern language as much as its syntax, it's the way it handles collections. Therefore, it shouldn't be such a big surprise that most of my encounters with .NET quirks stem from the differences between its collection classes and those I've used in Java. Still, I hope this is won't turn out to be a tradition, otherwise I will have to rename this column to "Collection Corner".

This particular tale, just like the last one, starts with the Dictionary generic class. Specifically, it starts with my need to be informed when someone manipulates its contents. The classes I was writing had a rather simple purpose: associate event handlers with different input controller events. One class managed keyboard events, another mouse events and yet another gamepad events. Each one of these classes exposed at least one read-only property of appropriate Dictionary type. All went smoothly until I decided that I needed to know when someone added, removed or changed the handler for an event.

Keep Me Posted

The first logical thing to do was to check the documentation and see whether the Dictionary class itself offered the desired functionality. Despite my years of experience with Java collection framework, I hoped Microsoft would surprise me pleasantly. Good thing that I didn't bet on it, though. After all these years of evolution, the two most sophisticated mainstream languages still don't offer the fundamental courtesy provided by Delphi's good old TStringList class.

Just like I expected, I decided I would have to implement the desired behavior myself. The logical choice seemed to be to override whatever manipulates the collections contents: the Add, Remove and Clear methods, and the indexer. If you have any .NET experience, you're probably chuckling at my naïveté by now; if you don't, then I'll keep you in suspense a bit longer.

Virtually Polymorphic

Perhaps the greatest difference between Java and .NET, certainly the one I find most difficult to get used to, is the way they handle inheritance polymorphism. In Java, all non-private methods are virtual by default. If you don't want the derived classes to override a method, you have to explicitly declare it as final. Once a method is declared as final, your derived classes cannot contain a method with the same name.

In .NET, all methods are non-virtual by default. If you want a method to be overridable, you have to explicitly declare it as virtual. If you're overriding a method, you have to include the override keyword. If you want to keep a virtual method from being overridden, you have to declare it as sealed. And if you want to introduce a new method with the same name in the derived class, you have to use the new keyword.

At first, this seems like a lot of fuss to achieve virtually the same results, pardon the pun. However, these differences are extremely important, as they represent different design philosophies. The .NET way makes you think twice before you decide which parts of your code will be flexible and which set in stone. As Eric Lippert will tell you, this mitigates the notorious Fragile Base Class problem, which should be cool, right?

No Jack For Plug

The aforementioned philosophical differences are not all about how many polymorphic angels can dance on the head of a non-private pin. There are some very practical consequences of making all your methods non-virtual by default. One of these consequences is rather unfortunate: none of the methods in the Dictionary class are virtual. In other words, there's no way to modify the behavior of the Dictionary class so that you get a notification if its contents change. Or is there?

Everyone is really excited about the shiny new features in C# 3, such as partial methods. It will be interesting to see whether the collection classes will benefit from this change. I haven't downloaded Orcas yet, so I don't know. I won't hold my breath, though. Besides, a new version of the language and the surrounding framework won't help those who need to extend the collection classes now. What solution could they use?

Interface/Off

Fortunately, there is a way to hack around both the language limitations and the rigid design of the collection classes, without too much work. The key is to fall back to the interface polymorphism. Where before I exposed my dictionary as a read-only property of generic Dictionary type, now I have to change its type to generic IDictionary interface.

The second step is to include the IDictionary interface in the list of base types for my dictionary class, like this:
class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IDictionary<TKey, TValue>
{
// ...
}

How does this help? It makes sure that the compiler will remap the interface methods to the corresponding methods in the class. If there is a method in MyDictionary whose signature corresponds to an IDictionary method, it will be mapped to it; if not, an inherited method will be used.

The final step is to declare the methods you want to modify as new methods:
public new void Add(TKey key, TValue value)
{
   // ...
   base.Add(key, value);
   // ...
}

That's all there is to it, really. Some things haven't changed that much since the bad old times of COM and COM+.

Monday, August 13, 2007

.NUTS: Enum Conundrum

Welcome to .NUTS

I've been avoiding .NET for quite a long time. It's not that I'm an anti-Microsoft zealot, it's just that I used to code in Java at work and I figured that one platform full of frustrating limitations was more than enough. Recently, however, I decided to learn XNA on my own free time and that means getting involved with .NET and C#. It turned out to be just as frustrating as I feared, but at least it provided me with some nice blog material. Thus is the .NUTS "column" born in my blog, to document all that is weird in the .NET world. Expect stuff that might make you giggle, goggle and groan.

Enums Revisited

I first encountered the concept of enumerated types when I learned Pascal. Before that I owned a Commodore, so I dabbled in Simons' BASIC and 6502 assembler. Therefore, I didn't approach enums the way a C programmer might -- as a cleaner way of defining constants -- but as a way of defining a completely new type that accepts only those identifiers I define. The difference is subtle, but important: it shapes your attitude.

In .NET, enums have, obviously, inherited a lot of baggage from COM, which, in turn, comes from C. Furthermore, that baggage has been squeezed to fit the .NET luggage rack, where everything is an object, even the value types. Of course, value types are not really first-class objects, because they have to be boxed first. All in all, .NET enums are a part of a very leaky abstraction.

Starting Point

My journey of discovery started with an innocent little detail inside an excellent post on Shawn Hargreaves' blog. If you haven't read it yet, I strongly recommend it. I found it quite enlightening, especially the following advice:
If you use an enum type as a dictionary key, internal dictionary operations will cause boxing. You can avoid this by using integer keys, and casting your enum values to ints before adding them to the dictionary.
I found it strange that ints don't get boxed, while enums do. However, I was in a hurry to cobble my prototype together, so I just wrote it off as another one of those language eccentricities one encounters occasionally.

A couple of weeks later, I mentioned this to a friend of mine, who has been working in .NET since it first came out. He was even more flabbergasted: "That's weird. I mean, Microsoft keeps harping on how generic collections allow you to avoid unnecessary boxing. Seeing as how enum is one of the most common types for dictionary keys, the whole thing doesn't make sense at all."

That got me even more intrigued, enough to overcome my laziness and make me start poking around. This is where things started getting really interesting.

Now, those of you who don't care about the why and want the solution, skip to the part called "Finish Line", down below, near the end of this post.

Still reading? Okay, let's roll up those sleeves...

Stage 1: Observation

The obvious first step was to confirm Shawn's claim and work from there. For that, I armed myself with CLR Profiler (thanks to Mike Stall's blog) and I hammered out the following piece of code:
using System;
using System.Collections.Generic;
using System.Text;

namespace Sandbox
{
    enum TestEnum
    {
        e10,
        e9,
        e8,
        e7,
        e6,
        e5,
        e4,
        e3,
        e2,
        e1
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<TestEnum, int> dict = new Dictionary<TestEnum, int>();

            for (int l = 0; l < 100000; l++)
            {
                TestEnum x = (TestEnum) (l % 10);
                dict[x] = 100000 - (int) x;
            }

            for (TestEnum x = TestEnum.e10; x <= TestEnum.e1; x++)
            {
                Console.WriteLine(dict[x]);
            }
        }
    }
}
The results were as bad as Shawn predicted: the code allocated 4,825,246 bytes (more than 4.5 MB), out of which 74.61% were instances of Sandbox.TestEnum type. If an enum is winding up on the heap like that, it must be getting boxed.

The next thing I did was to change the Main method to look like this:
        static void Main(string[] args)
        {
            Dictionary<int, int> dict = new Dictionary<int, int>();

            for (int l = 0; l < 100000; l++)
            {
                int x = l % 10;
                dict[x] = 100000 - (int) x;
            }

            for (int x = 0; x < 10; x++)
            {
                Console.WriteLine(dict[x]);
            }
        }
The profiler reported 24,692 allocated bytes, with nothing sticking out as especially wasteful. It was clear that .NET handled ints and enums differently, even though they are both value types.

CLR Profiler has a very neat feature that allows you to find out which part(s) of the code allocated the memory, by right-clicking on the offending bar in the histogram view and selecting the "Show Who Allocated" option. That will open the allocation graph view, which in my enum case looked like this:
(click on the image to enlarge)

Apparently, my enum was being boxed by ObjectEqualityComparer, inside the Insert method in the generic Dictionary class. Culprit identified, time to move on to the next stage.

Stage 2: Under the Hood

Contrary to my first impulse -- whip out the IL Disassembler -- I decided to first check whether the help files mentioned ObjectEqualityComparer. No such luck. ILDASM it is, then. The disassembly of Insert method in the generic Dictionary class revealed the following interesting snippet:
  IL_001e:  ldfld      class System.Collections.Generic.IEqualityComparer`1<!0> class System.Collections.Generic.Dictionary`2<!TKey,!TValue>::comparer
  IL_0023:  ldarg.1
  IL_0024:  callvirt   instance int32 class System.Collections.Generic.IEqualityComparer`1<!TKey>::GetHashCode(!0)
So my suspect, ObjectEqualityComparer, is an implementation of an IEqualityComparer interface, contained in the comparer field inside my Dictionary object. Here's what help file says about IEqualityComparer:
This interface allows the implementation of customized equality comparison for collections. That is, you can create your own definition of equality for type T, and specify that this definition be used with a collection type that accepts the IEqualityComparer generic interface. In the .NET Framework, constructors of the Dictionary generic collection type accept this interface.

A default implementation of this interface is provided by the Default property of the EqualityComparer generic class. The StringComparer class implements IEqualityComparer of type String.
A bit more digging in help files revealed this:
Dictionary requires an equality implementation to determine whether keys are equal. You can specify an implementation of the IEqualityComparer generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic equality comparer EqualityComparer.Default is used. If type TKey implements the System.IEquatable generic interface, the default equality comparer uses that implementation.
So how does the EqualityComparer.Default get defined? According to the help file, like this:
The Default property checks whether type T implements the System.IEquatable generic interface and if so returns an EqualityComparer that uses that implementation. Otherwise it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

In other words, the boxing happens because my enum doesn't implement IEquatable interface. The funny thing is that Int32 value type implements IEquatable, as does every other primitive numeric type. Yet enums don't. When you stop to think of it, it sounds logical: the Enum value type can't implement IEquatable because that would theoretically allow you to compare any enum to any other enum and obtain bogus results. Not that I'm convinced by that argument, but it's really a moot point, seeing as how I can't change that myself. That leaves looking for a workaround, which brings us to the last stage.

Stage 3: The Lesser Evil

Once you're reduced to looking for a workaround, your job is to look for the least dirty and the least ugly solution. The first thing I tried was to make my enum implement the IEquatable interface. Naturally, there was no way to make C# swallow that syntax. Next I tried setting the EqualityComparer<TestEnum>.Default property, but unfortunately it's read-only. Finally, grudgingly, I conceded to write my own implementation of IEqualityComparer. The first attempt was to write it as a generic class, but when C# complained about not being able to explicitly cast an unknown value type to int (within my GetHashCode method) it finally drove the lesson home: .NET generics are definitely not the same thing as C++ templates.

The final solution looked like this:
    class TestEnumComparer : IEqualityComparer<TestEnum>
    {
        public static readonly TestEnumComparer Instance = new TestEnumComparer();

        #region IEqualityComparer<TestEnum> Members

        public bool Equals(TestEnum x, TestEnum y)
        {
            return (x == y);
        }

        public int GetHashCode(TestEnum obj)
        {
            return (int) obj;
        }

        #endregion
    }
The dictionary declaration would then look like this:
            Dictionary<TestEnum, int> dict = new Dictionary<TestEnum, int>(TestEnumComparer.Instance);

Finish Line

To sum it up, for each enum type you intend to use as a dictionary key, you'll have to write your implementation of IEqualityComparer and pass it to Dictionary constructor. For each enum type you'll have to type 18 lines of boilerplate code -- you can squeeze it into less, I know -- but that's a relatively small price to pay for avoiding the memory waste caused by boxing your keys. I just wish it wasn't that ugly, but at least it's simple enough. Stay tuned for more .NUTS in the future.