Wednesday, December 19, 2012

Design Pattern: Hidden Treasure

Overview

When a game has obscured goals or items that the player must find in order to use, but need not find in order to progress, the pattern in use is called Hidden Treasure. The treasure must at once provide an advantage and novelty; a weapon that differs only in that it is more powerful is just as unsatisfying as one that is only a re-skin of vanilla content.

Note again that Hidden Treasure is not required to progress; it can certainly make progression easier, but in order to qualify it cannot be strictly mandatory.

Hidden Treasure is a common feature of many games, but is prominent in any game within the RPG continuum as the pattern lends itself to quest systems.

Purpose

The Hidden Treasure pattern is put to use in three mutually independent ways.

  • Encouraging exploration – The promise of an advantage and novelty gives the player reason to explore the game world, and thus Hidden Treasure can be used to get the player moving; only effective if the presence of the Hidden Treasure is made apparent early on.
  • Creating replay value – Ubiquitous Hidden Treasure is most likely going to require multiple play-throughs in order discover all of it. If the Hidden Treasure is well-formed, then the advantage and novelty of the treasure will give life to the replay instead of playing solely to Skinner Box mechanics.
  • Enthralling the player – The treasure becomes the object of the 'Just one more…' compulsion. Not necessarily a bad use, but Hidden Treasure should also provide something more than just a cheap way to keep the player playing.

Examples

Good

  • Costume Quest – Peppered throughout the game are the materials and plans for new costumes; each costume provides a different set of attacks, spells, and over-world abilities to a party member. The costumes are not required to progress, but some costumes make the endgame easier. Searching for costumes will also reward you with more side quests, currency, and help uncover plot points.
  • TESV: Skyrim – Most magical items fall into this category, and the Elder Scolls games in general blur the lines between 'required' and 'optional' treasure depending on how you play the game and what you personally see as the goal of playing it. Strongly geared towards replayability and enthralling the player.
  • AOE II: Age of Kings – The Relics on the map are Hidden Treasure; their novel and powerful bonuses provide an incentive for players to explore the map as well as add flavor to warfare.

Sunday, November 18, 2012

GalCivII: Appeal to Tradition

I hope you did not think I was done talking about GalCiv II.  Because I am not.  See?  Yeah.

I have gotten back to modding GalCiv II; I started with Tolmekian's TechTree Fixes and have systematically gone through and edited the thousands of lines of text to remove the corn from the poorly executed science fiction flavor.

It has not been pretty.  As I have already spoken about, Twilight of Arnor the was a rushed game, and the text of the game has never been particularly inspiring.  Apart from typographic and spelling errors, much of it is simply bad writing, and usually very conversational in tone.

You cannot blame them, of course: with no designated professional writer and what was clearly a habitually rushed and under-funded operation had no time for editorial duties.  Plus, the game still plays well.

What I wanted to get into today is the world-building traps that are easy to get oneself into when writing about fictional cultures.

Here is the text from a United Planets Council question:

"In a galaxy filled with different kinds of beings, it can be a challenge to get our civilians to see eye-to-eye. While many ideas have been brought to the table, the most obvious way to bring our people together is through a Galactic Olympiad. Next year, all attending races will come together to compete in different events. As the hosting race will see a 20 bc per week economic increase during the competition, we must vote on a venue."

The thing to notice here is the statement that an Olympiad is somehow the most self evident way to bring together a coalition of space fairing alien species in mutual respect and admiration.  And that is simply monumentally misinformed and ethnocentric.

Like much of GalCiv's flavor and fluff, it operates under the assumption that at the end of the day all the galactic species are basically humans: two legs, two arms, a head, bilateral symmetry, a sense of the individual and its accomplishments, and all of them no more than six to seven feet tall.  This would be acceptable if they had not already taken pains to subvert that trope.  The Arcean are twelve feet tall, and the Drath are ten feet tall.  The only entertainment mentioned of Drengin practice are blood sports.  Tori are implied to be semi-amphibious, and the Yor are a collective consciousness of robotic beings.

Even if they all do have a cultural tradition of sports, there is little hope that any particular species will have much skill in any sports that another species plays.  Disregarding physical attributes, species simply have different specializations.  The Korx are deceitful tradesmen; their sports might include mock UN style trade negotiations.  Drengin engineer their laborers, and would be completely within their rights to simply engineer the perfect players for every sport on the docket.  And let us not forget that the Thalan are from the future and are on a mission to save the universe; the very idea that they would waste time to foster interstellar dialogue is laughable.

Saturday, November 17, 2012

Duncan Phyfe: Tear-Down Pt. 1

I am still developing the ability to do complicated projects in a rational order, so the table work jumps around a little bit.  I try to think ahead enough in order to avoid disaster, and some editing magic makes it seem like I do these things less sporadically than I do.  Still, this is all in a bit of a strange order of execution, complicated by the mess now resident in the workshop.

I left off talking about the stops on the under side of the wings, but that is going to be deeper in the post.  Before I elaborate on the project itself, I need to talk about tear-downs.  Restoration and repair work always brings with it the threat of the unknown; you never know what is hiding under the surface of the piece and it is more than likely that what you think you need to do is only a small part of what you will end up doing.  It that a professional opinion?  No, not really; it is merely what I have learned from the things we have had to fix over the years.  Okay, and a little bit of television.

If you can manage to disassemble the piece and know you can put it back together, then you know you have not missed anything that needs work.  That is a big if, though.  You need to be methodical and disciplined to pull it off, two traits my family is not know for, so I have to be extra careful.

The first trick I use for furniture is cardboard.  This style and age of table basically ensures that there are going to be a lot of screws and hardware in a tear-down.  The older furniture is, it is generally more likely that it is held together with purely wooden joints and animal glues.  But if there are going to be screws, cardboard is your best friend.

You cut out a piece of a cereal box and make a simple line drawing to indicate the piece somehow; for the wing hinges I drew the table top's shape when extended and the seams of the wings.  Then you punch holes through the cardboard in the pattern of the screws you are going to remove; as you remove them you place them on the diagram where they go.  Of course, find a way to unambiguously indicate the orientation of the piece relative to the drawing; masking tape and a soft, slightly dull pencil are a good choice.

This allows you keep track of the screws; you can know at a glance if one has fallen out or disappeared, and you can easily put them back precisely where they came from (which sometimes is important).  It also makes them far more portable and you will not confuse similar screws from different parts of the piece.

Now, on to the tear-down.  The first thing I did was experiment to see how easily the finish would come off.  I used a razor blade like a small cabinet scrapper; the finish popped off easily.  Then I removed the wings and set them aside.

Next, I needed to make a cabinet scraper.  I had been putting it off for ages, so now seemed like a good time to finally get it over with.  I have a saw or three I have acquired just for the purpose of being metal donors, and an old Keystone franeksteined with mismatched machine screws was first up.  I will talk about making those in a different post.

After getting the scraper all squared up and raising a burr, I laid into the table top's core carefully but forcefully.  It made quick work of the failed finish:


Why didn't I use sandpaper?  Funny thing about working wood with hand tools: sharpness maintenance matters a lot more.  Handplanes, hand saws, and chisels need to be very sharp, but they also need to be able to to be sharpened, so a hand saw tooth is not nearly as hard as a circular saw blade's carbide tooth, and a handplane iron is not nearly as hard as a power planer blade may be, because they are intended to be sharpened by the craftsperson, and often at that.

Sandpaper, however, is a literally disposable cutting device, although its action is more like shreading than cutting.  Sandpaper is indispensable in many situations, but if hand tools are going to get anywhere near the piece afterwards, you cannot use it.  The sandpaper will leave grit in the pores of the wood, and that grit will dull the blades of handplanes and saws.  The scraper will dull faster too, but of all my tools I am the least worried about the scraper in this situation.  It is only a piece of saw plate, after all.

Since I need to plane off a little bit of the surface to get through the Minwax and some water stains, I opted not to use sandpaper.  Also, this thing has already been finished twice; no need to raise the grain or risk scorping* the wood with over-zealous sanding to get it level all over again.  And the scraper leaves a silky smooth finish that sandpaper has a hard time matching in the same span of time.

Something to be careful of when using a cabinet scraper like this on boards: you are liable to gouge the edges if you use as much force and flection as you do on the middle of the board.  The scraper usually does not leave deep gouges, so they are easy to fix, but it of course is better if you manage to avoid them altogether.

You will notice a bottle of bleach: I went after the clearly visible black water stains.  Success?  Not especially.  I have some pictures, but it is nothing special.  Since I am going to plane off a little of the table top anyway, I will return to that subject later.

Next up are the wings, which are in four pieces.  The outer boards have those stops and thumb screws, you will remember, and the mysterious evidence of the stops having been on the other side of the wings at some point.  This is one of those places where the decay of knowledge comes in:


This is one of the previous locations of a stop, and it is clear that whoever moved them did not know how to treat animal based glues (which should surprise no one).  See that flaky film?  That is the glue that held the stop in place, while screws reinforce it against shearing.  It is britle now, but that is not evidence of the glue's weakness, because we must remember that the person who moved the stops left the residue.  They would have only done this if it was difficult (for them) to remove it in the first place.  Moisture has eroded the glue now, and it flakes cleanly off.

In order to facilitate refinishing the top, I need to remove the stops and the thumb screws so they lie flat.  Unlike our mystery repairer, I know that hide glues are easily reversed: all you need is a hot knife.

I have a small paring knife I keep around for odd tasks that need a knife but are too rough for a good one.  After removing the screws, I ran that over a propane torch a bit to heat it up until it just started to turn a shade blonde, turned off the torch, and then carefully cut around the stop and pried, slowly working into the glue.  Once you get enough leverage, it pops off:


There is a little heat blistering in the finish because of the knife, but the great thing about shellac finishes is that they can be repaired without any seams or threat of delamination.

The thumb screws have a threaded thumb bolt, a nut, and thread through a brass ring embedded in the wood.  When I get to repairing the aforementioned previous repairs I'll go into that more.

Next I stripped the wings with the scraper.  The square half of the wings were pretty easy to clamp on my (not so good) carpentry bench, but clamping the outer boards in the bench required a little trickery since the corners are broadly radiused:


While I pick on my factory-formed workbench, it manages to get things done (except flattening boards; not really sturdy enough for that).  The bench dogs have square heads but round shafts, a feature that is easier to manufacture and, despite confusing like three different ways a European workbench can work, has advantages, like swiveling bench dogs that still have a wide bearing face.

The white pieces of wood sit against one bench dog a piece and contact the radiused corners tangentially.  On the other side of the board are two bench dogs.  As I tightened the vice, it pushes the board forward, but the white wooden pieces force it to move to the right into the other bench dogs, clamping the board firmly in place with no special jig or vice.  This only works, of course, when the combined width of the white wood and board is greater than the space between the front and rear rows of bench dog mortices.

And that is where the table is right now.  The next task is to remove all the hardware and treat it with Evaporust and lacquer stripper, and to clean the mildew and mold caked onto the undercarriage.

*"scorp" is another word for an in-shave.  I use it as a verb to indicate the creation of shallow depressions in a wooden surface by power sanders or over-zealous scraping.

Credits:  I of course would be nowhere without the knowledge of Patrick Edwards concerning animal based glues; my credits list permanently includes Roy Underhill, Peter Follansbee, and Chris Schwarz, too.  But really, what hand-tooler doesn't?

Duncan Phyfe: Collecting Evidence

Woodworking is prominent among my many hobbies.  Well, at least at the moment it is.  It is a natural activity for me; my great great grandfather Henry H. was a carriage wright, his son Michael C. was a carpenter, great great (great?) uncle Sumner was...well they say he was a carpenter or handyman, but I think some of the Hopkins magic was lost on him.  My mother has pretty much always been in the habit of refinishing furniture, her father makes I think what would be called 'craftsman' furniture, and doll house furniture, and my father has worked on carpentry and, on occasion, refinishing.

And on top of that I have great great gramps' and great gramps' tools.  Most of them, anyway, but is a story for another time.  Or I already wrote about it; I do not remember.

My mother has collected a number or fine pieces of furniture over the years, and there is a lot of sad sad story that goes with them, but I will not dwell on that.  Because today I am talking about doing something about it: today I am talking about furniture restoration.

It is no surprise to most anyone that furniture is not as 'nice' as it used to be.  At least not here in the United States.  U.S. Americans* live fast paced lives and the economic-media complex continually fosters a culture of disposability.  Houses are not homes, they are investments, cars are not precious tools, they are merely a thing that gets you from point A to point B.  Combine that with an iconoclastic relationship with whatever the previous generation valued, and U.S. Americans have a generally cold attitude towards antiques and fine furniture these days.  There is ample evidence that this is changing, but for the moment it is a lonely world for furniture.  Consequently, the skills and knowledge needed to maintain fine furniture is lacking and the decay of that knowledge over the decades has not been kind to pieces.


Take my mother's Duncan Phyfe style dining table as an example.  It has spent about five or more years in a shipping container ("on-site storage unit"), which turned out to be a fantastic way to make sure all your cherished valuables are exposed to a high-humidity, moldy environment.  Family politics and a noted surplus of "stuff" means that, like it or not, this was pretty much unavoidable; oh well!

We got his table from a yard sale in very nice shape.  It is solid Mahogany through and through; the only part that is not Mahogany is the spar on the inside that serves to synchronize the two pieces of the table top as they separate; it is instead made of veneered Poplar (aka, Tulip Poplar, not to be confused with Tulipwood or the wood of actual poplars).

On to the damage.  The high humidity of the container has swollen the wood; luckily the table is solid Mahogany and not veneered (except for the Poplar spar on the inside).  I have a pile of veneered pieces that completely delaminated in the dampness; one piano bench completely fell apart.  Hardwoods have it easier, too, since they are less vascular.  The table did not swell as much as other pieces made of Pine or the like; some of those have changed dimensions so much that they have split stiles and rails.  How the joinery was designed helped a great deal; this is not a rigid box being forced into a shape but an elegant assemblage of pieces all connected so that they may move but not break.

The table is old enough to not only have been finished with a shellac, but also the glue used was clearly animal hide based; the ends of the wings have completely fallen off, cleanly, indicating it was not shearing that cracked a more modern glue (or, more likely, force the wood to crack instead), but moisture that degraded an organic glue.  This is a good thing: it makes the repairs easier, and animal glues are not weaker than modern glues, but they are reversible.

Most ferrous metallic hardware is rusted; after I got into the tear-down I found little evidence of rust so severe that threads eroded or screws seized in their holes.  The components of the table splitting sync mechanism are better off due to the amount of grease congealed on them.  All the brass hardware, which consists of the four leg tips and the threads for the thumb screws on the wings, are intact.  The leg tips had been lacquered some time before hand and the threads were tightly sealed by the thumb screws.

The previous owners said that they had paid for the table top to be refinished.  No one needed to be told that, of course, because whoever this mysterious refinisher was they failed to match the original finish of the rest of the table.  Instead of a gorgeous and deep burgundy shellac based finish, they instead used a similarly dark but distinctly more yellowy-brown modern finish in acrylic or urethane.  That would have been okay on an old Oak piece, but here it was jarring and the contrast only highlighted a sickly palor hidden in the color.

I can even tell you what color it is: along the edge of one wing there are four distinct splotches of what I readily recognize as a Minwax stain and finish; it is either Red Oak or Red Chestnut.  There are also three faint dart-shaped divets in the table top that still cling to the Minwax; clearly the table was very beaten up when it was refinished and the refinisher did not want to sand any further lest they end up with a 5/8" thick table top instead of a hair shy of 3/4".  On top of the Minwax stain the acrylic or urethane finish was applied.

After being put through the gauntlet of the storage unit, the results were predictable.  While the undercarriage looks like this:


The table top looks like this:


The shellac finish, though run throughout with fine cracks and some separation, is intact.  The table top, on the other hand, failed completely.  Moisture has swollen the wood, and the inelastic nature of the modern finish caused it to crackle and peel off.

But under closer investigation it is clear that this table has been repaired no fewer than three times before the table top was refinished.  The thumb screws thread into brass rings embedded in a circular blind mortise on the underside of the outer board of the wings; the size of the ring is such that it will eventually work loose.  This happened twice before, and the previous mortices are evident; they have been corked not with milled plugs but cut dowels.  Consequently the staining of the repair only highlights the contrast between end grain and long grain, not to mention the oval shape dowels take on when they dry.  Furthermore the slight overlap of the mortices ensures that the brass ring will work loose faster the next time.

The last repair, and this looks to be the only respectable previous repair, the top of one of the arching supports snapped off and was replaced skillfully with a clean cut and a new end.  The staining ended up much darker, but it does match the hue.

There is one anomaly in the history of the table, and that is the stops on the wings.  These small blocks of wood are on the underside to force the table top to stop rotating once it has done so through a right angle; the table top core also has two stops.

But on the wings, opposite their current location, there is clear evidence of the stops having been the other away 'round:


The only way this makes sense is if either the wings have been removed then swapped, or the entire table top has been removed then put back on 180 degrees contrary to how it originally was.  I have not yet encounter similar evidence of the core's stops being moved, so I assume the wings have been swapped.

I'll talk more about the stops in the next post about this table, where I go through some tear-down and initial treatments.

* Eww, that sounds almost wrong-er than "Americans", but I agree with friends that it is silly that U.S. citizens are referred to as "Americans" as if we own the continent.

Sunday, August 12, 2012

How Chrono Should Have Worked

Last post (ages ago, as usual), I mentioned that at the time we couldn't figure out how to make the core idea of Chronoscient work; the shmup genre is usually formulated such that it already gives you information on the future by the use of pattern-driven enemies.  Shmups are known for frenetic gameplay and seemingly impossible situations that are only resolved by reflex and more reflex.

It would seem that someone finally did figure out an angle on the time theme that would have worked in Chrono.  Or rather, they probably came up with it at around the same time we were scratching our heads and having heated arguments over "'splosions" versus "tactical puzzle solving"*.  Super T.I.M.E. Force uses ghosts of your character from previous play-throughs as defenders.  You can even save your past self and this former-you can help defend...well you know, screw the fabric of time space.

*I was on the 'splosion side.

Thursday, March 15, 2012

Design Pattern: Plot Mechanic

Overview

When the overarching theme of a game is driven by a unique mechanic, the game is using the Plot Mechanic pattern. It is the game design equivalent of a plot device in film and literature. TVTropes defines a plot device as "an object or character in the story whose purpose is purely to drive the plot or resolve situations." A Plot Mechanic is the same idea, but it renders it with gameplay instead of narrative.

Purpose

It may seem that any mechanic of a given game could be considered a Plot Mechanic, since game mechanics are the 'words' of the language of game design, but by that logic everything in a story would be a plot device. Thus, the Plot Mechanic has the same sort of central 'bigness' that a plot device has. It has to represent the agency of the player that facilitates gameplay; summoning demons, controlling time, transforming between different creatures.

Usage

As it is in film and literature, the Plot Mechanic can be a dangerous trap. Like plot devices, Plot Mechanics can come off as boring, stale, or simply lazy. You may find movie tie-ins can suffer from this: a fan-favorite element of the film is turned into a mechanic upon which and the whole enterprise is expected to rest, based solely on how well it sold on the silver screen.

It can be a great place to start, however, and it seems that often that is where we start. How often do we sit down and think, "I want to make a game where X can do Y"? Relying on the Plot Mechanic like this can be good for small games, experiments, and prototypes, but the larger the project the more thought and iteration it will require.

Examples

  • The Darkness – The plot mechanic is the name of the game. 'Nough said.
  • Braid – You can control and manipulate time in various ways; no one is going to argue this game didn't pull it off brilliantly. In fact, almost all of the mechanics in the entire game have to do with it.
  • Banjo Kazooie: – You can flip between the two characters, as I remember, which leads to a whole bunch of great little abilities.

Counter Example

  • Chronoscient – Chrono started with the idea by our lead for "a space shooter where you can see the future." Got a lot of cool words in there, and who doesn't love some good time-bending gameplay? But in the end, we found that we simply could not figure out how to get the idea to work. Space shooters are so fast and intense, how do you communicate the future without overloading the player? I think in retrospect, we did not understand that space shooters already gave you information about the future: the swarms of enemies and heavily deterministic behaviors give you all the info you need in order to predict what is going to happen. Maybe when we revisit it, we will be wiser and use the more generic statement "a space shooter where time is a dimension of gameplay".

Wednesday, February 1, 2012

Design Pattern: Progression Exhaustion

Overview

Progression Exhaustion is the inversion of the Progression Track; thus it employs the principle of Diminishing Returns instead of Thematic Capital. Improvement modeled with Progression Exhaustion grants more for less for sticking to a particular theme, you get less for more.

Purpose

The incentives are the opposite and the use is the opposite: encourage the player to branch out and not specialize their experience. Using both progression tracking and exhaustion together is an effective way to coax balance out of a player's development, especially in RPGs.

Example

  • HERO System – HERO System uses 3d6 as the central gauge of success. The probabilities of rolling a number on the range [3,18] follow a pronounced bell curve. The modifier a Skills or Characteristic grants to a roll changes linearly with respect to the points spent, and the opposition value of rolls starts at 9-. The result is that each for additional point you spend on a skill you get less of an improvement to your rolls. At some point around a 85% success rate, it becomes better to start spending points elsewhere.

    In terms of gameplay, this means that players rarely improve a skill to 100% competency; they spend points more wisely and anything they do push to and beyond the max will be an essential, flavorful part of their character.

Design Pattern: Progression Track

Overview

The Progression Track rewards thematic player development. The player is offered a number of choices and some number of them continue or reinforce the theme of previously choices. A choice that continues the thrust of previous decisions is rewarded by a lower cost while thematically dissonant choices cost more. This cost is either nominal or is folded into the opportunity cost of not continuing a pattern of decisions.

The easiest examples to recognize are those that involve a flavor of upgrading: if you are presented with a choice between improving your ability to do an ollie and how far you can grind. Previously you may have improved your grinding; then the latter choice may be cheaper simply because it is more in line with your previously decisions. On the other hand, if you haven't even begun to explore ollies, then it may be more advantageous to improve a skill you already excel at than to invest in a brand new one.

Purpose

Progression tracks are a great way to encourage player specialization, and so often show up in RPG's. Naturally steering a character towards a certain style of play using progression tracks is also a good way to preserve elements of the game for a second play-through.

Usage

The much maligned and often shallow morality systems found in games often use this pattern, though usually in an uninteresting way. It is usually far easier and grants greater advantage to simply be more evil than to suddenly have a change of heart. These systems try to compartmentalize and categorize the real world of grey areas and moral ambiguity, digesting real questions and ethical complexity into an easy to process model that the player can make decisions about and the game itself can actually simulate.

Usually that process removes the very interest from the content that intrigued us in the first place; a contemporary computer is a cold calculating machine, and making it run a game while modeling human emotion and morality in enough detail to preserve sufficient nuance is ill-advised. This is why the best uses of morality are not contrived but probable and grey while having little to no actual mechanical consequences. There are quests in Skyrim, for instance, which end with a simple decision, ones which the player does not have complete or wholly reliable information about and which do not provide any answers when they conclude. The player is already involved in the story enough that the simple act of making the decision is all that is needed to interact with them and the fact that there are little to no mechanical consequences does not detract from the effect on the player.

Examples

  • D&D – In D&D, the aforementioned Feats have a number of progression tracks in them: Power Attack to Cleave to Great Cleave. You have to have the previous Feat in order to acquire the next one in the set. Furthermore the Class system makes for an a progression track as well since Multiclassing is expensive.
  • Monopoly – In this originally educational and satirical take on capitalism, improving a property you have already developed can be more lucrative than improving undeveloped property, provided that the property is placed well, as the rent will be greatly increased.

Design Pattern: Ability Slot

An ability slot is similar to an upgrade of choice, but the choices available do not represent a permanent change to a game entity's abilities.  Instead, the entity has a certain number of slots which abilities 'take up' when equipped.

I cannot think of a real example where this would be used and not be pigeon-holed, but that does not mean it can't and hasn't been done.  Certainly, one could have a game where the player's character has three slots and only three abilities to fill them with, but with the option of putting an ability in multiple slots, thus augmenting that particular ability at the cost of flexibility.

An important feature of ability slots is that shuffling abilities around is in some way a hassle.  For instance, you may not be able to do so during combat or outside of a certain location.

Examples

D&D

A magic-user in D&D has a certain number of spells they can cast per day, unless you're a heathen and play 4.0 where you have a certain number of spells per battle, because who wants to deal with all of that pesky role playing business anyway.*

You of course need to learn the spells first, but after that, you can prepare any spells you have for the day.

FPS's

FPS's basically always have ability slots in the form of weapon choice; while gaining access to the weapon is usually an upgrade of course, which weapons you have equipped is almost always an ability slot.  Many games have dual-wielding now, and Skyrim of course makes double-equipping a spell a whole lot of fun.

Raiden

I'll be honest and say I played a fan homage Flash version of Raiden on the internet, but the important thing here is the fact that you have one ability slot, your weapon type, and three types of weapon.  Raiden also exhibits the design pattern upgrade track.

*Seriously, do not play 4.0.  Having spells per battle instead of spells per day messes with the tenuous sense of scarcity in a game where magic users were already incredibly powerful after a certain level.  The skill Intimidate can't be used outside of combat; I suppose it is better to simply kill all your enemies than to save one to interrogate later.

Monday, January 30, 2012

Design Pattern: Upgrade

The upgrade is a pattern that is applied all the time to games.  The player is allowed to make a decision to improve a game entity in some way.  Upgrades always cost something to acquire, usually a resource and/or time.

Upgrades come in two flavors: upgrades of course and upgrades of choice.

The former covers upgrades where you will get the upgrade just by playing and often represent an expansion of player skill and game difficulty.  In classic FPS's, like Doom, gaining access to a new weapon as you play through the levels is an example of an upgrade of course.  A more colloquial term for this flavor would be ability curve, where over the course of play (see the name?) the player's abilities expand.  Upgrades of course are useful for in-play tutorials.

The latter is the type of upgrade which pertains to the customization of a game entity.  Usually, upgrades of choice are pigeon-holed in some way; that is, there are more choices of upgrades than there are chances to upgrade, either by a restriction on the number of upgrades or by availability of upgrade resources.  This forces the player to make a choice concerning how they want to improve.  The former type of pigeon-holing is more easy described as expansion slots while the latter is an example of scarcity.

Examples

Age of ... Series

The technologies of the games are upgrades of choice almost universally, though some only grant access to other technologies to be researched.  Researching techs in most games including the Age of ... Series is almost always done with scarcity; you can research everything, but time and resources are scarce enough that you usually have to make decisions.

D&D

As characters progress in D&D (3.0 and later, at least), they are allowed to add Feats to their character.  Feats are special abilities that allow you to break the normal rules in some way, ostensibly because the character has become just that awesome.

There are many many dozens of feats, and no source book or expansion is complete without a list of new feats to make your characters especially over-powered.  Since these are permanent additions to character abilities, they are pigeon-holed upgrades of choice, or expansion slots.


Halo, DOOM, etc.

FPS's almost always use upgrades of course; as you play, you gain access to more types of weapons.  The resource you expend in these situations is usually only the time it takes to play to t a given level where access to a weapon is granted.

Design Pattern: Complementary Mechanics

Complementary mechanics are a coupling of mechanics where each reinforces the other in order to result in a desirable player behaviors.  The best complementary mechanics reinforce each other as well as encourage player behaviors that relate to each mechanic; I'm calling this type 'completely complementary mechanics'.

Complementary mechanics are a very effective way to silently pressure a player into strategic actions with them not necessarily being aware of the greater importance of those actions.  They must be carefully designed, however, so that the resultant behavior is fairly obvious given the mechanics involved.

Examples

Chess

If you are familiar with chess strategy, then you know that building a pawn wall is very important.  The pawns, though weak individually, become a powerful tool that thwarts opponent movement when used together.

In order for it to work, a pawn wall must be zig-zag shaped; pawns capture diagonally, so for one to protect another, they must all be adjacent diagonally.  To complement the fact that they capture diagonally, pawns can move one or two spaces on their first move, making the most basic pawn wall, a two space wide zig-zag one space in front of all of a players more powerful pieces, mostly trivial to accomplish.

Because most chess pieces cannot hop over allied pieces, the complementary mechanics of pawns naturally force you to move them into a defensive structure that is porous enough to let your pieces through but strong enough to repel opponent pieces until the mid-game.

Mechanics: Pawn capturing, one-or-two first move
Resultant Behaviors: building a pawn wall, opening maneuvering room for more powerful pieces

Sins of a Solar Empire

To achieve the next tech tier, you need a certain number of research labs.  You can also only build a certain number of structures around each planet.  Since there are numerous structures you could build and limited slots to build them in, the only choices you have as a player are to colonize more worlds or upgrade more worlds to get more slots to build more labs to research more techs to protect all those worlds and structures you colonized or built.  Planets also incur a cost to operate until they are completely upgraded.

This is an example of completely complementary mechanics.

Mechanics: tech tiers need more research structures, only so many structure slots per planet
Resultant Behavior: colonize more planets, upgrade planets, and later, research more techs to protect your investments

Battlefleet Gothic

A game of space battles in the Warhammer 40,000 universe, whose table-top wargame is probably Games Workshop's most widely known offering.  I don't know much about the history of naval type war games, but I get a strong sense from BG that there is a lot of influence from past games going on.

In BG, you must always move your ships (unless a ship is under special orders that involve some tradeoffs) because of the huge amount of momentum they have.  This forces play to be dynamic and constantly changing.  Ships also are harder to hit from the front and ever harder to hit from the rear, so positioning is a vital component of the game.

By forcing the player to always move their ships, the game is forcing you to make tactical decisions every turn which it rewards you with by making ships have a varying degree of difficulty to attack based on relative position.

Mechanics: forcing the player to move, variable armor based on relative position
Resultant Behavior: fast-paced and tactical play

Monday, January 16, 2012

Galactic Civilizations II: Role Reversal

I'll begin the discussion of the writing in Galactic Civilizations II with two factions that are seminal in the development of the immediate background of the game's universe: the Drengin (DREN-jin) and the Arcean (AR-seen). factions that begin the back story, at least on the wiki.  I am no expert on structure or writing, but I am not half bad, and analyzing the bad is a fantastic why to learn what makes something good.

Drengin

Ostensibly, the Drengin are a cruel and deceitful empire.  They are said to be both incredibly evil and clever at the same time.  Their society is supported via the use of 'slavelings', and they are keen to use other species as such.  Even their technology is researched by slaves.  They are often characterized as 'clever' in their evil plots.

Comparable Species: Cardassians

Arcean

The Arcean are basically drawn as a foil to the Drengin; they are of a similarly warlike stock, but are more honorable warriors of tradition and galantry instead of warmongering overlords.  The flavor text describes them as being "[not] evil, they just don't care".  That is fairly vague in terms of their actual values, so I will assume that it means that they just act based on an alien morality, with an emphasis on honor and power.  They want to control the galaxy and seem to think they are the perfect species to do it.

Comparable Species: Klingons

The Arceno-Drengi War

Eons ago, the Drengin and Arcean came to blows; unsurprising since they both have a desire to be galactic conquerors.  Together they constructed the first stargates, some 300,000 yaers ago, but the devious Drengin decided to start a war with literally the only other superpower they knew of in the galaxy.  In 98,000 B.C.E..

The Arcean, being ready for them, deactivated the stargate on their end in the middle of the Drengin fleet's traversal, stranding them halfway to the Arcean homeworld.  The Arcean then destroyed the invasion fleet, and the two species went their separate ways.

The Drengin Enslave the Tori

In an unexplained manner the Drengin locate the fledgling Tori species; semi-aquatic and peace-loving.  They construct a stargate and send it hurtling through space towards Toria.  70,000 years later the stargate arrives and the Drengin swarm through it, conquering the Tori easily.  Some 26,000 years later, the Tori realize that maintaining a strangle hold on Toria through a stargate is expensive and that the Drengin must be over extended, and a surprise attack manages to kick the Drengin out of Tori space.

The Arcean Attempt to Trick Humanity, Screw up the Galaxy Instead

The Arcean run into the Altarians at some point, but the relationship becomes one of mutual respect, or mentorship.  Eventually the Arcean come across the Sol system, and send Humanity the plans for a stargate of their own.  Of course, with their eyes on conquering the budding race instead of allying with them, the Arcean's plans have no method to turn off the gate once activated.

Humanity does not notice this detail, and instead focuses on the physics and technology implied by the design.  Since they have already developed fully functional nuclear fusion, they are in a position to make the spatial warping mechanisms of the stargate into a portable device.  They do so, and construct the first Hyperdrive.  They quickly disseminate the design to the entire galaxy, effectively creating an arms race of colonization and military buildup.

Interstellar Travel: It Can't Work That Way

There is a huge problem of timescale, here.  In 298,000 B.C.E., the Arcean and Drengin make contact and design the first stargates.  That figure is taken from the fact that the Arcean and Drengin meet before Homo Sapiens walked the earth plus a hundred thousand years.  200,000 years later, in about 98,000 B.C.E., the Drengin start a war with the Arcean which ends badly for the Drengin.

When the two part ways, things start to get very odd indeed.  The Drengin discover the Tori; since there is no stargate to Toria, they must have found it via exploration.  It was by unmanned probe, and it occurred some 100,000 years ago.  70,000 years later the stargate arrives and Toria is enslaved.

Arcean and Drengin: Problems

The major issue here is that the Drengin have never demonstrated any cleverness and the Arcean are not shown to be the stubborn, honor and tradition bound race they are supposed to be.  Their dispositions as presented are quite the opposite.

The Drengin attempt to invade a far flung star system by simply sending it a complete stargate, which is slow and error prone and certainly not clever.  The Arcean take the sneaky approach and send only the plans, allowing the target to work themselves half to death to build a device that will spell their own doom.  Drengin come off as arrogant and brutish, while the Arcean have a candid and diplomatic approach.  The Drengin have crappy diplomacy, which no clever race would have.  It must also be mentioned that the write ups for the unique Arcean techs characterize Human engineering as not being clever enough.

Then we have the problems of distance and travel time.  We know that a stargate allows travel at 0.165 light years a week.  This is a fudgey measurement since it is adjusted for the warping of spacetime (yay plot devices).  That means that one year in a stargate journey translates to 8.58 light years.  We know that Arcean space and Drengin space are one year in a stargate separate from the Artificial Gravity tech flavor text, and that is likely between homesystems.  Problem is, when the Arcean deactivated the stargate on their end, the Drengin fleet were trapped thousands of light years away from home.  Even if adjusted parsecs are for the benefit of the star map and reperesent a full 3.26 lightyears in unwarped space, that still leaves Drengi and Arcea only 169 lightyears apart.

What's worse, the Arcean Empire manages to not only trap the Drengin fleet in the middle of nowhere, they get out to that fleet and crush it in a timely manner.  Quite a feet for a species who has a stated penalty to interstellar travel.  And if a Stargate can be deactivated in the middle of a journey safely, why are they still only point-to-point devices?  Seems like a cleverly designed network of gates would allow you to travel to most important system fairly quickly if you can turn the gate off in the middle of a journey.

So after that debacle, which among other things implies that the Drengin never arrived in the Arcean systems even though that same tech flavor text insists that they did, the Arcean never open their stargate to Drengi again.

So what?  The Drengin immediately after their defeat find the Torians and send a Stargate their way, fully constructed, and wait 70,000 years for it to arrive at Toria, a figure the Drengin are more than willing to accept.  That means that the Drengin would only have to travel at a speed of 765 kilometers per second to reach Arcea in the same amount of time in the worst case scenario of distance.  That's only about 50% more than the escape velocity of our solar system.  If the Drengin are so patient, and have the resources to build a stargate only to send it off to invade a planet in several millenia, why didn't they just attack the Arcean Empire again?

In all of this, no mention is made of exactly, or even vaguely, how interstellar communications work.  They seem to be instantaneous, though space travel is not.  And that brings up another issue.  The Arcean find Earth and send plans to a stargate through their remote probe.  How long did all of that take?

Well, when the humans recieve the plans, they invent Hyperdrive and give it to everyone.  By that time, the Torians have long been independent, so it has to be more than say, 140,000 years as the Drengin had to discover the Torians and that would take at least 70,000 years.  We also know that traveling via the stargate to Arcea from Earth will take 10 years, so the two are separated by 86 ly or 1695 ly.  Now, assuming the Arcean home system is similar to Sol and the probe is somehow able, after a very long journey, to manuver for orbital insertion into Earth's gravity, and with the benefit of instantaneous communications, but with finite fuel supplies and conventional propulsion, it'd be traveling at maybe 525 km/s (the escape velocity from our solar system relative to the Milky Way).  If we stick to adjusted parsecs being full parsecs in unwarped space, then it would take the Arean probe 1.02 million years to get to Earth.

In context, 1.02 million years ago was just after the extinction of Homo Erectus.  In the GalCivII backstory, its about the length of time it took Humanity in a very recognizable form to invent Hyperdrive.  It also means that between the time of the expulsion of the Drengin from the Torian systems and the time of the game, 860,000 years had past.

I'm not sure this makes any sense.  Are we supposed to believe that a mortal alien species can afford to wait a million years to interact with another species and still be interested in conquering them?  Or even 70,000 years?  And what were they doing that whole time? If Humanity managed to discover and perfect fusion technology in perhaps half of the time the other important species have been around, why didn't those species figure it out themselves?.  It seems highly impossible that a space-fairing race would spend that much time hanging around, waiting for probes to report, and not once become curious about how stars make energy and at least attempt to replicate it experimentally.  And no argument of a lack of curiosity is valid, since the Arcean have space probes that work thousands of light years away and over millions of years.  They are guilty of curiosity by association with such exploratory devices.

On top of that, these races had become accustomed to plotting things on a geologic time scale, and suddenly, with the power of  Hyperdrive, they become capable, and very eager, to develop at a more Human pace.  They even reproduce at a competitive rate, which is odd since the Humans live on such a hastier time scale it would be reasonable to assume that they could out-reproduce the other races.

Finally, we need ask how exactly the Drengin and Arcean fought battles in space without having any space weapons.  You need to research these weapons in the game, so how the Arcean fleet wiped out the Drengin fleet in deep space is a serious question.  Since energy production is the primary stumbling block in the game's narrative, one would assume missile weaponswould be the standard arms until the power needed to run rail guns and energy weapons was available, but we do not see this and the game's AI actually has a tendency to avoid missile technologies.

Sunday, January 15, 2012

Galactic Civilizations II

GalCiv II.  If you aren't familiar, GalCiv II is a turn-based strategy game by Stardock, released in 2006.  It's gotten Editor's Choice, top notch reviews, best Strategy Game, and that's just the awards listed on the Wikipedia page.

But really, it's a great game.  Its awesome, actually.  If you haven't played it, well, then you should probably just go buy the gold or platinum or other precious metal edition.  While its downloading, I'll mention that the shear number of options you have is mind-boggling; this game was made for serious strategy fans by serious strategy fans.  A friend of mine says it is "deep".  There are two written play-throughs that are simply a joy to read ( here and here ), and give you a taste of what you can do and some of the brilliance of the AI players.

But what a more casual gamer might not realize is that GalCiv II: Twilight of the Arnor (TA), the final expansion, is broken.  Okay, this game is pretty 'old' by now, and given some of the stuff I've found to help  in poking around in data files, I doubt that it is really news to anyone who has cracked the hood of the game or paid attention to the patches.

I certainly did not realize how far the rabbit hole of broken it went.  I got the game freshman year, back when it had no expansions.  That game was compelling and very fun, and very, very, very hard (for me, anyway, but that is a different story).  I always end up at least pondering modding any PC game I have; its in this programmer's blood.  And though I wasn't a very skilled programmer yet, looking at the data files of GalCiv II, I realized that something was wrong.  Nowadays, I call that feeling the 'stink' of bad code.

You can tell when code is bad by the data files that support the program and the type of bugs that are discovered.  For instance, in Maya3D, you can crash the application by entering a negative number of subdivisions in the Subdivision Surface modifier's dialog box.  If you know anything about how Maya was stitched together, you know that the front end is mostly a collection of scripts that get interpreted by the Maya kernel, where all the sexy stuff happens.  Thus, this crash is completely avoidable and, in a word, stupid.  No one thought to validate the field values before sending it off to the kernel, and since you're converting one type of geometry into another, the kernel eats that negative value and one can only assume it goes straight into the subdivision algorithm code and the whole program crashes somewhere between starting to generate the new geometry and displaying it.

That code smells.  It smells like dead animals.  You know its stupid and that only unclear thinking went into the system, idea and feature tacked on, one after another, with little control or overall vision.  With that in mind, I will present something from GalCiv II completely out of context:



        <Weapons ID="Beam Weapon theory">
            <Category>Trade</Category>
            <Cost>50</Cost>
            <Group>None</Group>
            <Alignment>None</Alignment>
            <WillingnessToTrade>80</WillingnessToTrade>
        </Weapons>



This is a snippet from one of the tech tree files in TA, specifically from the Iconian faction.  Notice anything odd?  Like, a Beam Weapon technology being categorized as Trade?

The categories of techs are used by the AI to aide in prioritizing research; they have nothing to do with the visual presentation of technologies (that's the Group).  The tech trees are littered with these sorts of things; if you want all the information on the tech trees and many other tidbits of "WTF?!", you can read this discussion on the GalCivII forums.  I had no part if uncovering this quagmire, mind you.  Those guys are the detectives, not me.

In short: miss-categorization of  techs in TA makes the AIs in the game act like morons.  They don't research their unique technologies, they don't get very far, they hit roadblocks before getting to the techs that they need to even contend for dominance.  Two of the AI personalities are broken, some tech-trees are basically engineered to thwart attempts by the computer to play well, and to top it all off, the AI is incapable of using spore ships or terror stars.  It just won't.  And those are big elements of the things TA provides.

It's getting late, so I'm going to turn in for bed.  Tolmekian, MarvinTosh, and qrtxian did the work on the techs structure, and next time I hope to get into the badness that is the writing in GalCivII.

P.S. GalCivII, like so many other fantastic, buggy, glitchy, sometimes horridly designed games before it, is still one of my favorites.  I love the Stardock guys for doing this game, and I speak so disparagingly of the guts because it warrants lamentation.  It is still a great game even with so many problems by the time TA was released.  I hope the Stardock guys don't hate me.

Friday, December 9, 2011

Miniature Wargames are a Racket

Don't get me wrong, I love the things.  Well, more accurately, I love that they exist.  I dabbled a little bit with Warhammer 40k after getting an Eldar model, and found the modeling part of the hobby stimulating.

The rest of it, though, was not only daunting but expensive.  Very expensive.  And my area and school simply did not support the demographic that plays these sorts of games, so there was no community support either.

Games Workshop (GW) dominates this genre of table top games where armies crafted, both in miniature form and function, by the players are pitted against one another on a table top battlefield.  GW is headquartered in Nottinghamshire, and like Denmark's LEGO brand has the unfortunate property that its origin's currency is far more valuable than greenbacks.  That and the expense of producing what a friend calls " a complete hobby" and especially one of the quality of GW's work makes these things cost a lot. 

Note that I do not mean that GW makes a great product and everyone else makes something on par with green army men.  I mean that GW manages a huge number of properties accompanied by a complete line of modeling supplies, literature, rules, miniatures, events, and dedicated stores and does so with an overall very good end product.  Other companies put out comparable wargames that are cheaper and in terms of rules are probably superior.  But I am not familiar with them, except in passing, and my experience with this hobby is almost entirely in the realm of making and painting the miniatures, and mostly GW at that.

It has been said* of the table top wargame minis that there are three choices, cheap, good quality, and variety.  You of course can only pick two; GW opts for the last two.  Seriously, the number of options you have in any given GW model is stupid and I suppose the cost of the hobby can be mitigated somewhat if you keep with it because of the supply of extra bits you accumulate.

As usual, I ranted much about a subject that is tangential to what I really wanted to talk about, and that is the cost of wargaming modeling supplies.  They are numerous and specialized, from lichens and mosses to paint and finishes, there is an entire sub-market devoted to the supplies to make little plastic things look good.  In terms of performance, good modeling products need to be well suited to their task and engineered to deal with it well.  They most economically come in small packages because the rate of use is much smaller than other crafts.  They must stand up to repeated abuse, be easy to use effectively, and be something that young teenage males, the main demographic, can handle without too much of a mess.

And I think we've been conditioned to believe that makes these supplies expensive.  This is not true; the supplies we get from dedicated modeling suppliers are expensive.  Take flock for bases.  You can buy it for $4 in half cups, or make it for almost free in gallons.  Graded sand for bases as well; buy it at $0.083 a gram or buy it at $0.0065 a gram (A.C. Moore does sell a more natural color that matches the Citadel product, but it is not on the web site; in my store its in with the floral Styrofoam).  You can also get your sand from outdoors if you live in a sandy area like me.

What about paint?  Those little Citadel paints are fantastic, and fantastically expensive.  An once of paint for $4.  The colors last a long time, and the metallic colors are the best in acrylic model paint, but what about all that primer?  400 ml of acrylic white spray primer for $15.75.  Or 350 mL of enamel spray primer for $4.  Don't like spraying?  $0.30/mL for acrylic white or $0.06/mL for Liquitex Basics white.  The latter, when used the same way Citadel says to use their paints, makes a tougher, flexible, less brush-mark prone primer layer.

Painting Grey knights or some army that is mostly metallic and requires a lot of paint?  Don't spend a boat load on small pots of metallic paints, mix your own in appropriate quantities (about two bottles of pigment and one bottle of medium gets you an equivalent of $73 of Citadel paint for $16, and it can be any color metallic you want).  I did this for a friend's large aircraft model, intending to bring up images of old polished aluminum planes from the mid 20th century; it worked perfectly for dry brushing over black.  You can also buy Plaid brand metallic paints, which are comparable to Citadel's in quality, are cheaper, come in more colors, and a few even come in large bottles**.  There is one light green shade in particular that would be well suited to Necrons.

Moss speaks for itself.  There are also cheap bags of sea shells and glass shards, as well as plastic crystal chunks and Styrofoam in all manner of shapes and sizes ant craft stores.  Seashells in particular are just the sort of thing large monsters can use.

So don't go buying "official" supplies when you don't need to.  Use your smarts and look around craft stores that you would never think of for products to abuse for things the designers never thought of.

*Okay, in a paper or actual print article, this would never fly.  Its the literary equivalent of "I heard from a guy this one time..." and it is usually lazy.  However, I could not tell you where I read this other than in some forum discussion that involved Reaper Miniatures and the exorbitant cost of minis in general.  Searching for the quote is time I don't have, not to mention a difficult thing to get through Google.

**Craft grade acrylic paints are good to use, but try the brand out first before doing so.  Plaid is thick and creamy and will usually perform as well as a Citadel color, just don't water them down as much as a Citadel paint.  You should usually varnish your minis anyway, but craft paint will usually demand it.  Plaid metallic colors won't, though.

Monday, December 5, 2011

Saving Time and Saving Money

Recently, I had one of those "ah-ha!" moments while reading an XKCD comic.  Given my family's inclination to ostensibly save money, no matter the cost, it is not surprising that I never equated the act of saving money to the act of saving time.

If the comic and that sentence do not spell it out clearly enough, it basically breaks down like this: the oppurtunity cost of saving money is the time you spent doing so.  As XKCD points out, if you spend 9 minutes or more to save a dollar, you are working for $6.66 an hour or less.  This is an essential insight to saving money, and as usual, brings to mind the old adage that "time is money".

Combine it with another favorite of mine, "if you don't have time to do it correctly now, how do you expect to have time to fix it later?" and you have a powerful way to reason about your handiwork.

  • Take your time to do good quality work because every minute you spend doing it right saves at least another minute later fixing what you botched.
  • Avoid materials and methods that are unfamiliar or too involved to acquire (unless the above applies, of course).  You save time learning the new techniques and avoid using those techniques poorly, thus sidestepping possible mishaps.
  • Plan ahead and in some detail so that when you are out on a job or gathering supplies you have thought of everything you need and thus will not waste an hour picking up things you forgot.
It all seems like common sense, but it is not obvious how dire the consequences are.  For instance, say you are building a deck.  If you needed four more 2x4's than you bought, and the lumber yard is 20 minutes away, you must spend $5.00 in gas to buy $10.00 in lumber and spend an hour doing so.  If you are making $30 an hour, now you are making $15 and you have to spend an hour more later.  Do that twice a week over a three week contract, and you have to spend an additional day working and $240+ of your customer's money.

Now what if, in a similar and even more likely situation, you bought enough lumber but because you did not double check your measurement, you need those four 2x4's to fix what you botched.  If it took 45 minutes to measure, layout, and cut that lumber, then find out it was wrong, that is $22.50 and the better part of an you wasted.  Now you have to work two more days and spend more than half a grand of customer money, and that is if you are working alone!

Two working days and half a grand or 30 seconds and three cents.  Those are your choices, so you should probably double check everything you measure. Every time.

Friday, December 2, 2011

Swizzle that vector! Part 2

Well, after a long day trapped in the barn cleaning (it looks presentable now!) I return for the second part of implementing swizzling in C++.  I left off at the reasoning for using the functional operator and multiple arguments of a swizzle class, with the tantalizing hint that getting the error checking to work at compile time was weird.

So, here is the problem.  We have a Vec2, that is, a two component vector.  It should only be able to use swizzle components for the two components it has, that is, X and Y.  Something like:

vector2( x, y, x);

is valid but:

vector2( x, z, y );

should not be and ideally should throw some error at compile time.  Also, every vector type can use the swizzle components of the vector types that are smaller than it:

vector3( x, z, y );

It is clear that we can use inheritance to enforce this, but we must be careful.  When I first tried this, I made the mistake of inheriting in the direction that seemed the most logical, but that was in fact wrong.  Your gut instinct is to have the 3 component swizzles inherit from the 2 component swizzles:

class Swizz2;
class Swizz3 : public Swizz2;
class Swizz4 : public Swizz3;

But this does not solve the problem: it would mean that a Vec4 can only use the 4th component swizzle, W.  We are not following the Is A... principle here because we went with what felt natural.  It is correctly written:

class Swizz4;
class Swizz3 : public Swizz4;
class Swizz2 : public Swizz3;

And when we implement the functional operator for a Vec2 or a Vec3:

Vec2 operator() ( Swizz2 const& a, Swizz2 const& b ) const;
Vec2 operator() ( Swizz3 const& a, Swizz3 const& b ) const;

we can be sure that the operator will take only X, Y, and Z components in the Vec3 but only X and Y in the Vec2.

The final step to make all this safe from the user is to lock down the swizzle classes so that no one can alter what they mean (well, at least not easily).  I did this first by making the internal fields that govern how a particular instance of the Swizz2, Swizz3, and Swizz4 classes are used to swap components around private.  The swizzle classes are declared in the header file but omit their implementation, along with a class called SwizzleFactory:

class SwizzleFactory;
class Swizz4;
class Swizz3;
class Swizz2;

This makes it so that any other translation unit can use the classes but cannot do much with them.  In the implementation file, SwizzleFactory is declared a friend of the Swizz# classes, whose only useful constructors are private.  The swizzle components names are also declared in the header file:

extern Swizz2 const x;

/** etc. */

And then defined in the implementation by using the factory methods of a static SwizzleFactory instance:

Swizz2 const x = factory.MakeSwizz2( 1 );

Since the implementation file is the only place where the factory is defined, it is the only place where it can be instantiated. Thus, that translation unit is the only place where the swizzle classes can be defined and the whole system remains very safe from user intervention, unless they do something stupid and ugly.  To top it all off, the whole things lives in the namespace GFX, just in case you really need to use x as a variable name (do not do that).

Swizzle that vector! Part 1

If you have used OpenGL since version 2.0, you should be familiar with GLSL, the incidentally redundant 'Graphics Language Shading Language' (technically 'OpenGL Shading Language', but the "GL" stands for the above, sooooo...).

A nifty feature of GLSL is that it's primitive* linear algebra types, vectors, can use something called 'swizzling' to return a new primitive from the arbitrarily rearranged components of the first.  If you have the 3 component vector "vector1", for example, you can return a vector with the X and Z components swapped thusly:

vector1.zyx;

You can also construct vectors of a different order, that is, a different number of components:

vector1.zzyx;

This is really handy in shaders and linear algebra in general because you sometimes need to do just that, such as switching between coordinate systems.

But of course, C++ does not have this feature itself.  Not that it should, mind you; it is not a linear algebra language.  But when I was working on my own mathematics library for my work on computer graphics, I figured that if my vector package was to be really useful I should try to implement something like swizzling.

That is really difficult, as it turns out.  You cannot use the exact same syntax as GLSL and have something sensible; doing so would require all vector objects to store within themselves a copy of every combination and permutation of their four components as a field, which comes out to something like 4^4 == 256 additional float's per vector.  Memory is cheap these days, but it is not that cheap, not to mention its nauseating.

Some malign the option, but in C++ you can (and should) overload operators for your classes.  Thus, you could use the functional or subscripting operators, () and [], respectively, and have the swizzle combinations as separate, static objects with a name corresponding to the combination. Something like:


/** ... */
static SwizzleClass xyzz;
/** ... */

class Vec4 {
/** ... */
Vec4 operator() ( const SwizzleClass swizz ){ /**...*/ }
/** ... */
};


Which would be sufficient and replicate the functionality as is.  However, I found this method ugly; it felt too much like shoehorning something foreign into C++, the kind of thing a good Lisp programmer might pull if they tried to implement closures into C++ without thinking about it too much.  I was also a little worried about memory swapping; with some 256 static memory objects flying around, it sounded like a recipe for a speed bump**.

I also realized that there was something else I could make it do that GLSL could not: negate individual components.  The syntax in GLSL precludes this because it just stings component names together.  So I instead opted for using the functional operator with multiple arguments.  These arguments would be of a Swizzle class and have the negation operator overloaded so that one may write:

vector1( x, -y, y );

The number of arguments dictates the return type of the operator.  This method also solves a crucial typing issue: a two component vector cannot use swizzles for components it does not have, such as Z or W, but static, named permutations do not easily allow for this check at compile time and instead we would have to either throw exceptions or use a confusing system of classes and a royal mess of operator overloads.  That makes debugging linear algebra code blocks very difficult.  Using individual component swizzles like this allows us to solve that problem using the type system more directly, but the solution itself is a little unintuitive and will be the subject of a later post.

*To be clear, 'primitive' in the programming sense, that is, it is a feature of the core language and not a class or type implemented in it.

**The rule is "profile, then optimize".  I never profiled this option because it was a hassle to write all those permutations up when I was certain it was a bad idea for any number of reasons, memory being only one of them.  It is likely it would not have had dire implications as far as memory goes.

P.S. The HTML generated by this editor is a train wreck when it comes to changing fonts.

Thursday, December 1, 2011

I can hear the planes now...

I live in a farm house that my...great great grandfather built, if I have that right.  That was 120 years ago.  He was a carriage maker and wheelwright; the workshop was in the house next door, powered by steam.  Whatever happened to those old behemoth machines is anyone's guess.

Anyway, the barn is what was built first and what was used to build the rest.  Gramps (that is, my great grandfather) had his workshop in the barn, off to the left.  When we had to rebuild the barn's rear wall and foundation because it was sliding off, the interior got an overhaul, and ever since my father and I have been working to get it all into a coherent workshop.  That was a long while ago, and its had three layouts or more since then, but this time I think it is a keeper.

Now, not every person can claim to live in a house built a century ago by family and filled with the detritus of all that time.  Save the large machines, some unknown number of planes from GGGF's tool chest, and anything that went with the blacksmith shop*, I have located all the tools and I am currently in the middle of returning them to working order.

This has been hard; three generations have been in possession of these things with little to no knowledge of how to take care of them, let alone use them.  The "hand tool revival" has been a great help as the information is now out there for anyone to access, but rust, moisture, and insects are fierce adversaries.  I seriously doubt that today's tools could have survived so long under these conditions.

I suppose I am obligated to put some pictures up of this fabled workshop, but that will have to wait a little while longer.  Still a mess in there what with the crates of tools awaiting a long bath in Evaporust**.

*The blacksmith shop was donated to a local museum, tools and all.  The paperwork got fouled up, but when it got moved upon the closing of that museum to a new location and rebuilt, we stepped in and my mother got to help dedicate it.  Cool stuff, and I hear that in the summer there is a real blacksmith there to educate people.

**Just Google it.  Evaporust is a fantastic product that dissolves rust without harsh chemicals and easy disposal.  The process etches the surface very slightly if you leave the steel or iron in for a long time, say overnight, which some tools need.  The matte grey and black finish this leaves can be easily removed with a wire brush and some metal polish.  A side effect of the etching is that sharp edges and points get sharper.  I have yet to test it on a clean, dull file, but it seems to sharpen files as well.  Citric Acid is another solution that works a little slower, though I have not tried it myself.

Wednesday, November 23, 2011

#1

A friend once said to me "How many civilians did I kill?"

Actually, that wasn't to me, it was to our game master at the time.  And I've since had a bit of a falling out with him so he might not like the term 'friend'.  Don't worry, they weren't real civilians.  You see, we were staking out an airport in this Cyberpunk campaign and...wait, that wasn't what I was going to talk about.

Ahh, yes: a friend once said to me "Mike, you should really have a blog because you're always finding these nifty little tidbits."  Not the exact words, but close.  He is of course completely correct; I'm usually collecting random information all the time, and I generally am capable of bringing all of it to bare at any given time on any given project.

Oh yes, projects.  I have a lot of them, and I've never been good at finishing them.  With ADD, you need to really concentrate and be religious about something to get it done.  And that's real ADD, mind you, not the colloquial flavor where we chock all lapses in focus to a medical disorder.  I've been working on this, but it is slow going.

An up side to it is that I find a wide range of stuff interesting.  Cooking, woodworking, painting, miniatures, drawing, programming, whatever.  I can do and have done a lot of things, often to great praise (okay, maybe not even often, but I make good stuff).

What makes it possible is realizing that everything has something to do with everything else.  Understanding linguistics helps you name things better in your programs, knowing how the eye perceives makes 3D graphics easier to write, physics and leverage makes your carpentry easier, and chemistry allows you to understand your recipes.  Understanding the connectedness of how everything works allows you to store a great deal more information because you can reason from base principles instead of memorizing reams of facts.

So expect posts on a wide range of subjects.  These next few days will probably be a mixture of the culinary and the arboreal.