Sunday, May 23, 2010

Lugaru - Part 5

In my previous post (Lugaru - Part 4) the first problem I identified was the role and responsibility of the Weapons class. Namely, a single instance of Weapons represented 30 weapons when it should only represent one. The refactoring exercise to correct this started off as a philosophical one, but ended up being VERY beneficial. I'm very happy I did this before tackling the implementation details of Weapons. Here are the major steps I took.
  1. Renamed Weapons to Weapon.
  2. Globals.cpp holds the global instantion of Weapons. It went from this:
Weapons weapons;
to this:
const unsigned int max_weaponinstances = 20;
Weapon weapons[max_weaponinstances];
unsigned int numweapons;
The max_weaponinstances constant comes from Weapons.h.
  1. With max_weaponinstances moved out of Weapons.h, all of the Weapons' attributes that were arrays become single instances. This is because the class is no longer maintaining the state of multiple weapons, just one. There were 44 places this had to be done.
  2. The Weapons class has four class operations - a constructor, destructor, and two others. One called "doStuff" that updates the game state of all the weapons. The other is called "draw" which pushes the weapon illustration down the graphics rendering pipeline. At the top of these two operations are for-loops that iterate over all the weapons in use (stored in numweapons). Those are gone. Instead, they now appear in GameDraw.cpp.
    There were 823 instances of referencing the loop counters in Weapon.cpp
  3. Classes that are dependent on weapons have a slightly different syntax. As an example, in Person.cpp it used to read:
  4. if(weapons.type[weaponids[weaponactive]]==knife) ...
    but now reads:
    if(weapons[weaponids[weaponactive]].type==knife) ...
    I find the new way much more readable since it puts the weapon attribute closed to the thing its being compared to.
  5. Weapons used to contain texture information. In the original design, these would only be registered with OpenGL once. In the new design I didn't want 50 weapons registering the same textures 50 times. To get around this, I made the texture id's global, (*GASP*). I rationalized that refactoring is about going from bad to better, and this let me move on quickly. I have no intention of leaving it this way long term.
Overall, I think this left the code MUCH more readable and improved some design aspects of Lugaru weapons. Next up will be getting some unstanding on the Weapons implementation.

No comments: