Final Fantasy 12 might bring me back to the series

January 15th, 2008

I haven’t played a game from the Final Fantasy main series since Final Fantasy 7. I think I’m the only person to have stopped playing the series because of that game. That means FF12 is only the 2nd 3D Final Fantasy game I’ve played, and the first in about 10 years. I’ve only just started, but I think I may end up going back and playing 8-11 once I finish.

FF12 is almost exactly what I’m looking for in an RPG. In fact, it’s what I was hoping DS2 would be. I’m a huge fan of Dungeon Siege, and I had hoped Dungeon Siege 2 would expand on the party command system and the equipment/spell requirement system. FF12 does both of these. And since the battles are in run-time, on the same screen as the world, it feels more like a PC RPG than a Final Fantasy (although the artwork and the story leave no question).

Those two systems I wanted - party commands and equipment/spell requirements - exist in FF12 in the form of gambits and licenses.

Gambits are sets of rules which determine how your party behaves in battles. They are essentially simple logic statements. “If a party member has less than 50% HP, heal them.” “If an enemy is attacking the party leader, attack that enemy.” Combining them lets you have a character who will cast spells and perform other special actions when they’re needed, and just attack when they’re not. This is what Dungeon Siege was lacking. Your mages would only cast spells, repeatedly, until they run out of MP, and then just stand there.

Licenses are how FF12 controls which equipment, spells, and techniques a character can use. Instead of requiring a character class, or level, as previous Final Fantasies and Dungeon Siege have done, all that’s required is a license, of which the player has full control. Of course, there are restrictions. Licenses are organized on a 2D grid, and you can only buy a license if you have an adjacent license. So your mage, which only has staff and robe licences, can’t suddenly get a heavy armor or broad sword license.

The systems aren’t perfect though. Licenses can be tedious, and gambits can be restrictive. And that’s why I want to play FF8-11. I didn’t realise back when the games were new, but the Final Fantasy series has always been full of innovation. FF1 let you choose character classes; FF3 let you change classes; FF56 let you learn spells through espers. Jumping straight from 7 to 12, I’m sure I’ve missed some great gameplay mechanics.

Bloat and verbosity

December 24th, 2007

In his latest rant, Steve Yegge asserts that the worst thing that can happen to a codebase is for it to get too big. He uses a lot of words to make his beliefs clear: too much code is bad; most people don’t think too much code is bad; Java, and similar languages, are verbose; refactoring doesn’t help code size. But in all his words, there wasn’t a lot of reasoning behind what he said.

Fortunately, Jeff Atwood condenses and elaborates, and for the most part he agrees. But they both fail to distinquish between bloated code and verbose code.

Bloat is when code is larger than it should be because of repetition, featuritis, or poor organisation. Bloat is the opposite of elegance.

Verbosity is code that is long because the language requires it, or because of design decisions. Verbosity is the opposite of succinctness.

Code can be bloated but succinct. It can be verbose but elegant. And it can be bloated and verbose. Verbosity can be bad, but bloat is always bad.

In Java, and C#, there’s a lot of boilerplate code. A simple property can take up 15 lines on the screen. A map can take 6. Both can be done in a single line in a language like Ruby.

But does that matter? Is that extra code any harder to manage?

One more thing that Steve asserts is that the claim that the IDE can overcome this verbosity is flawed. This is where I don’t necessarily agree. A good IDE can hide a lot of that boilerplate code from you, can do refactorings that would requires managing the code, and, perhaps most importantly, can highlight the code so it’s easier to see the meat.

Steve’s argument is that the power of the IDE promotes even longer code, requiring even more powerful IDEs and creating a vicious circle. This is true, but it’s ultimately up to the programmers and languages designers to keep their code managable. Just because it’s easy, doesn’t mean you should do it.

Yes, less code is better. And being succinct is better than being verbose. But the latter really isn’t that big of an issue.

Microsoft’s Parallel Processing Framework

December 7th, 2007

4 days ago I wrote about parallel processing.

Sun and Microsoft are constantly working on improving the Java and .NET frameworks. And by the time the average programmer needs it, both will have plenty of support for easy threading.

Today, via Public Sector Developer Weblog:

Microsoft is working on a set of Extensions for the .NET Framework 3.5 (Visual Studio 2008) that will make it dramatically easier for Developers to build “managed code” parallel process applications.

The CTP is now available. I hadn’t heard about it before today, but apparently the word has been out for a few months. There’s a Parallel Programming Team blog, an MSDN Magazine article, and a Hanselminutes podcast about the framework.

I haven’t tried it yet (my computer only has a single core), but it looks interesting.

Overrated code

December 6th, 2007

I’ve had this post on the back-burner for a few months. It wasn’t until I read Only Code Has Value? that I decided to finish it.

If you have well-written code, you can easily understand what the code is doing. However, even the best-written code can’t reveal why it is doing it. That’s because the question of “why” is not centered on the code itself, but on the context it operates in and the design decisions made during the development of the system.

I don’t think I can put it any better than that: there’s no way for code to explain the Why. And without the Why, you are powerless.

Our only hope, our only peace is to understand it, to understand the `why.’ ` Why’ is what separates us from them, you from me. `Why’ is the only real social power, without it you are powerless.

As recently as a couple years ago, I didn’t care much about what code looks like. As long as your program does what it’s supposed to, it’s all good. Sure, it’s nice when other people can easily understand how it works, but that’s not as important. Besides, if they’re to understand the Why, they’ll need some form of documentation anyway. You might as well just put the How in there too.

More recently I’ve been reading blogs and books that promote readable, extensible code. One of the quotes that comes up again and again is from The Structure and Interpretation of Computer Programs:

Programs must be written for people to read, and only incidentally for machines to execute.

That’s a fine theory, and definitely something that we should strive for in practice. But when was the last time you came across a non-trivial piece of code that you immediately understood? Even the most well-written code takes time to read - to understand the How. It would help if you already had the power of knowing the Why.

Maybe we should spend a little less time making sure our code is readable, and start spending some time on the documentation.

Parallel programming is still the future

December 3rd, 2007

From Write Me a Small Program at freeshells.ch:

Don’t let me catch you saying anything like `The multi-core future’. Multi-core is not in the future. How many cores do you have in your current computer? How many in the computers being sold _right now_? How many CPUs? If you ever again say `future’ and `multi-core’ in the same paragraph, and I catch you.

Muli-core processors are becoming more popular every day, and that trend won’t end soon. Steam’s survey shows more than 1 in 3 users mave more than one core (this survey covers gamers, who tend to have more powerful computers than “average users”, so real-world usage rates are probably much lower). When I checked a couple months ago, it was about 1 in 4. Computers in the future will have more and more cores, and developers need to be aware of this. But as a developer, do you need to be actively thinking about it?

I say no.

And it’s not because of adoption rates. A user’s future is a developer’s now. Developers need to design their software for hardware that won’t be used for a year or two. But even if every user had multiple cores, most developers wouldn’t need to worry about it.

The reason is because most software doesn’t need multiple cores, and would not benefit from being multi-threaded. Other than game developers, most programmers don’t do anything that’s CPU-intensive. Most desktop- and web-apps run fine in a single process.

But applications are getting more complex, and eventually even “simple” programs will nned multiple threads. Does that mean developers will suddenly flock to Haskell? Again, no. Language designers are well aware of the situation. Sun and Microsoft are constantly working on improving the Java and .NET frameworks. And by the time the average programmer needs it, both will have plenty of support for easy threading.

If you want to stay ahead of the curve, then yes, you should learn all about parallel programming. The same goes if you’re making games or anything that requires a lot of CPU power. But chances are, it won’t help with what you’re working on now, so you don’t have to worry about it.

Silverlight Limitations

November 20th, 2007

After a couple weeks of learning Silverlight, I’ve come across a number of annoyances which I know will come up again and again.

Centering text

There’s no Alignment attribute for TextBlocks. To center text you need to use an on-load event to reposition the text after it’s created.

No inline custom controls

Let’s say you know you’ll use centered text a lot. So you create a custom control with a TextBlock that centers itself. You want to be able to easily insert is into your XAML.

But you can’t. As I understand it, the purpose of XML is to allow things like this. Even though Silverlight has its own schema to define the tags that can be used, it would be nice to be able to add your own. Even something like a CustomControl tag would be enough. But with Silverlight you have to go back to an on-load event.

Copying brushes

This is one I just experienced a few minutes ago, and I’m not sure how significant it will be. Say you’re making something like a drawing program, and you want to be able to select a color, or brush, and paint with it. I’d like to be able to do something like this:

You can’t, because you would have two objects using the same brush. Even something like r.Fill = currentBrush.Clone() would be nice. This is what I ended up with:

Eww.

But, Silverlight 1.1 is still in alpha, so it’s still being tweaked. There’s a chance some of this will be much easier in the final version.

Resizing a Silverlight canvas

November 10th, 2007

Let’s say you want your Silverlight canvas to resize to fill the browser window, or at least to fill its container.

I expected to find a simple way of defining what happens when the canvas container is resized. Something similar to the Loaded attribute. But it’s a little more complicated than that. We need to handle the event in JavaScript and call our managed code to do the actual resizing from there.

First we set up the managed code to make it callable from JavaScript. To do this you need include to add the [Scriptable] tag to your class and all methods that will be called from JavaScript ([Scriptable] is in System.Windows.Browser). Then, in the page loaded method, register the scriptable methods using WebApplication.Current.RegisterScriptableObject.

Now we can call Resize from JavaScript. All we have to do is set up the event handler. But you can’t declare the event handler in the events section of Silverlight.createObjectEx. I decided to use an old-fashioned JavaScript event handler:

This works when the window is resized, but it won’t work if the canvas container is resized for some other reason. I’ll get to a better solution in a minute, but first let’s look at how it works, because we’re going to keep the contents of the function.

SilverlightControl is the id of the Silverlight object, as defined in the createObjectEx call. Content.basic.Resize is created in the C# code above. “basic” could be anything, but I stuck with what I saw in the tutorial I read.

This almost gets the job done, but it’s better to use the Silverlight resize event. The only way I could find to do this is to set it up in JavaScript after the Silverlight object is created.

onLoad is the function called when the object is created, as specified in the createObjectEx call. And Content.onResize is the resize handler, which unfortunately isn’t in Intellisense, but is in the MSDN article on Silverlight resizing, which appears to be very incomplete and incorrect.

Now just create another JavaScript function with the same code as the resize handler above, and we’re good to go. All that’s left is to actually resize the canvas and the objects. If you just want everything to scale with the canvas, you can use a ScaleTransform and set ScaleX and ScaleY in the C#. The XAML:

And the C#:

In this case, the canvas starts at 640×480, so our scale factors are based on those numbers.

Resizable Silverlight example

That’s all there is to it. Here is the project I made, which includes a slightly more complex Resize method.

Learning Silverlight - part 2

November 5th, 2007

A few days ago I wrote about getting started with Silverlight 1.0. But Silverlight 1.1 is coming in the near future, and for developers, the future is now. The biggest change with 1.1 is that it includes the .NET framework, so applications can use languages like C#, not just JavaScript.

To use 1.1, you need Visual Studio 2008 Beta 2 Standard or Pro (NOT Express), the , and the Silverlight 1.1 SDK.

The best place to get started is at Microsoft’s Silverlight page, in the Getting Started section (imagine that). They start out with a simple clock for the first example.

Silverlight clock

The project is similar to a version 1.0 project. There’s the XAML with the canvas objects and storyboards, and the HTML and the common JavaScript to create the object. But now there’s also a C# class to take the place of the JavaScript. I like learning by doing, and here I decided to learn by adding a millisecond hand.

Each hand is a XAML Paths which is rotated with a simple repeating animation. I copy the SecondHand object to create a msHand and edit its shape. The example uses inline path markup syntax, something I hadn’t come across yet.

The Data attribute here defines a path that starts (M) at (-1.5, 16) (in the Silverlight canvas, (0, 0) is in the top-left), and moves (l) down by (0, 70), then left (3, 0), then up (0, -70), and finally closes (z). That’s the second hand. I want the millisecond hand to be thinner, longer, and darker.

Each path also contains a Path.RenderTransform element which defines its angle, and is needed for the path to rotate. Now to animate it.

This is the second-hand animation, which just changes the object’s angle from 180 to 540 over 1 minute and repeats forever. Adapting it to the millisecond hand is simple:

The only differences are the target and the duration. The final step is the set up the initial condition. The path definitions create all hands pointing down, towards 6, but we want them to represent the current time. This is where the C# codebehind comes in. But first, how do we get to the code-behind? Well, in version 1.0 the Canvas (root) of the XAML file had a Loaded attribute which pointed to the JavaScript function to call upon loading. In 1.1 it’s the same, but there are also a few attributes to define the namespace:

x:Class tells Silverlight that we’re using the ClockCanvas class in SilverlightProject8.dll. The Canvas_Loaded method contains C# code to find the canvas (Canvas can = sender as Canvas), find the animations (DoubleAnimation secAnim = (DoubleAnimation)can.FindName("secondAnimation")), calculate the current time, and move the hands into position:

The To and From properties of the animation object correspond to the respective attributes in the XAML. Adding 180 is done so the “default” is up instead of down (if date.Second is 0, the angle would be 0 and the hand would point down because of the Path definition, but we want it to point up). Duplicate this code for the new millisecond hand and replace .Second with .Millisecond, and we’re done. We now have a 4-hand clock.

Silverlight clock with millisecond hand

Learning Silverlight - part 1

November 2nd, 2007

So I decided to learn Silverlight. I figure it’d be nice to have experience with one of those RIA frameworks - Silverlight, JavaFx, AIR - and Silverlight seems the least evil to me.

My favorite way to learn a new language or framework or technology is to download a few simple examples and try to change them. Tutorials and books are nice, but real, working code has no equal. I started with a photo gallery from Design With Silverlight (which has plenty of other good examples). Load; compile; run. It does what I expect, and I see a few things I can change. But I won’t get into the boring details of what I did with the code, I’m just going to give an overview of how Silverlight works. All the snippits here are modified (simplified) versions of code from the photo gallery example.

A Silverlight app, at least version 1.0, consists of 3 parts: the HTML, the XAML, and the JavaScript. The HTML can be as simple as a div and a call to JavaScript function createSilverlight().

The XAML contains the descriptions of objects and animation in the canvas. Here are a couple examples:

This creates a 600×30 rectangle with a gradient so it’s black on the left, white on the right, and red in the middle. The MouseEnter and MouseLeave attributes define the JavaScript functions that will be called on their respective events. The Canvas.RenderTransform node sets the scale properties of the object. It’s needed in case we want to rescale the object.

This creates a storyboard (basically an animation) that will scale an object 1.5x over 1 second. DoubleAnimationUsingKeyFrames defines what property will be animated, and SplitDoubleKeyFrames defines the times and values.

The JavaScript contains the meat of the application (at least in this example). The most important piece is Silverlight.js, which is distributed by Microsoft and initializes the Silverlight objects. This will be the same in every app, and as far as we’re concerned for now it could be black magic.

Then there’s the app-specific code that does things like handle events.

This is the previously mentioned function called from the HTML page which will create the Silverlight object with the specified properties. Every app will have something like this.

This is the callback for the mouseEnter event, as specified in the first XAML snippit. It looks for the mouseEnter canvas object, defined in the second snippit, and calls begin to start the storyboard. Line 3 sets the target of the storyboard so it points to the same object that fired the event. So if you mouse-over the rectangle, it will call this function, which will run the storyboard and scale the rectangle.

That’s really all there is to getting started. Canvas objects are in the XAML with references to event callbacks. Animations are also in the XAML. And event handlers which can start animations and change object properties are in the JavaScript.

How to use OpenGL in .NET

October 24th, 2007

I decided to port a program of mine that uses OpenGL from C++ to C#. I haven’t done any work using OpenGL with C# yet, and this is what I went through to get started.

The first place to look for OpenGL help is usually NeHe. He has a bunch of tutorials for various OpenGL features, plus some good frameworks to get started. And sure enough, in the Basecode section, there’s NeHeGL C#, plus many of the articles have source code ported to C#.

Download. Compile. Run. The familiar colorful rotating NeHe object shows up. Perfect. Now to look at what it does.

Familiar colorful rotating NeHe object

I already knew how I wanted the program to be structured. I wanted a custom UserControl for the “base” OpenGL stuff that can be shared across different applications - setting up the window context, etc. Then I wanted a control that inherits the base control to do app-specific stuff - actually drawing what needs to be drawn. And that control would be embedded on the form.

And lo and behold, that’s exactly what NeHe has. There’s BaseGL.cs, which is the UserControl that sets of the OpenGL window. The significant portion of the code comes straight from the C++ NeHe basecode: get the HWnd1 and DC2, set up the pixel format descriptor, and set the rendering context. And there’s TestGL.cs, the control specific to the app, which is basically just an OnPaint method and a keypress event handler.

But what I was really looking for was how to communicate to opengl32.dll. The solution comes in the form of three interop classes: OpenGL.cs, GLU.cs, and WGL.cs, courtesy of Colin Fahey and Chris Hegarty. I don’t know much about interops, but as I understand it, they’re like wrappers around unmanaged code. They’re just there to say, “over here, in this dll, is a function that looks like this”.
OpenGL.cs is for opengl32.dll; GLU.cs is for glu32.dll; and WGL.cs has a selection of functions from user32.dll (GetDC, ReleaseDC), gdi32.dll (ChoosePixelFormat, SetPixelFormat) , and opengl32.dll (wglCreateContext, wglMakeCurrent, wglDeleteContext, wglSwapBuffers).

In the end, this just means all OpenGL calls need to use one of these classes, so you have GL.glBegin(GL.GL_TRIANGLES) and WGL.SetPixelFormat.

By including these classes in my project, and making my custom UserControl, I was up and running with a window with a colorful triangle. The only problem is is doesn’t move. Windows doesn’t repaint unless is needs to, or you tell it to. This is as simple as calling Control.Invalidate(). The NeHe code puts this in a timer, so it happens repeatedly:

I don’t need this for what I’m working on, so I just set up event handlers for things like OnMouseDown.

There’s just one more thing I need for now: image loading. In C++ I’ve always been able to find functions for loading different image formats into raw data, but I was sure the .NET framework can do this itself. So I go to lesson 6 at NeHe’s texture mapping tutorial, ported to C#.

Load a bitmap, get the data, and create an OpenGL texture using the data.

Unfortunately, this didn’t quite work. BitmapData.Scan0 returns an IntPtr, but GL.glTexImage2D expects an object[]. The lesson 6 code works because it’s using the CsGL library, something I wanted to avoid for now. But since I have the source code for the interop, I can just change it to something that works, which matches up with what’s in CsGL. Compile and run, and that’s all I need for now.

I said I wanted to avoid using CsGL at first. That’s because I wanted to learn what needs to be done, rather than just use a library to do it for me. But I don’t want to have to include those three interop classes in every future project, so let’s see what CsGL has to offer.

I was hoping I could just change my control to inherit the CsGL OpenGLControl, instead of the NeHe base control, but it doesn’t work. ‘CsGL.OpenGL.OpenGLControl does not contain a definition for AutoScaleMode’ on a line Visual Studio inserted into InitializeComponent. If I remove the line it’ll compile, but it doesn’t run and I can’t load the form in the designer. CsGL is doing something differently than the NeHe basecode. After a quick look at CsGL, I think it has to do with OpenGLControl inheriting Control, not UserControl. A couple quick searches make it clear that I shouldn’t be using CsGL; it’s been discontinued and the Tao Framework is its successor.

Tao is pretty easy to implement. Just add Tao.OpenGl and Tao.Platform.Windows in the using list and make the control inherit SimpleOpenGlControl. A few changes to the code are needed again: in the control constructor you need to call InitializeContexts(), and the Tao class with all the OpenGL definitions is named Gl, not GL.

After all this, what have I learned? Mostly, getting started is a lot harder than it should be. A search for OpenGL C# should take me straight to the Tao Framework. OpenGL.org should have a giant “How to use OpenGL in .NET” link on it’s front page. And a place like NeHe should have a tutorial or article for using OpenGL with .NET, although the ported source code was very helpful. It’s not that getting everything working took too long, it’s just that I was expecting a simple list telling me what to do. So…

How to use OpenGL in a .NET program (Visual Studio 2005 edition):

  1. Download and install the Tao Framework.
  2. Create a new Windows application project.
  3. Create a new User Control in the project.
  4. In the User Control, make the following changes:
    • Add using Tao.OpenGl and using Tao.Platform.Windows.
    • Make the User Control inherit SimpleOpenGlControl.
    • Add a call to InitializeContexts() to the constructor.
    • Add a method to override OnPaint and add your rendering code.
    • (Optional) Add a method to override OnResize.
  5. Add an instance of the User Control to your form.
  6. To force the control to redraw, call Invalidate on the User Control.
  1. window handle []
  2. device context []