Thursday, April 10, 2008

How I tell ++preincrement and postincrement++ apart.

The rules of C operators are byzantine; the best thing you can say about them is that they make some idioms very terse, e.g.
while(*p++) { }
You could go crazy trying to remember the operator precedent rules if you don't use them all the time. But the way I remember the two forms of ++ gets at a deeper issue, so it's more than just C trivia.

First, let us recall that ++a will increment the variable a and return the new value; a++ will increment a adn return the old value. I suppose that Kernigan and Richie, while "designing C" (between bong hits) thought that having the ++ after a would help make it clear that the increment happened after, um, other stuff. In partiular, while(*a++) evaluates the thing pointed to by a for not being zero before incrementing. (But then it increments no matter what. Cute.)

I suspect that I am like virtually all C programmers in that I learned to use post-increment for whatever reason, e.g.
for (n = 0; n < 5; n++)
Now step into the world of C++. Consider the implementation of ++ when our variable is not a simple integer, but rather a very expensive C++ object.

The pre-increment is easy. We change our object to be one more, and then that object is used in the next expression. But post-increment is a lot more expensive. We have to...
  1. Make a new object that is a copy of the object that is being incremented.
  2. Increment the old object.
  3. Use the new object later in the expression.
  4. The new object is in fact a temporary variable invented by the compiler, so it will get destroyed.
In fact, it's even worse...because of the way the operators are written, there will actually be two temporary variables, two copies, and two destroys. If creating, or deleting copies of your object is even remotely expensive, post-increment is much more expensive than pre-increment.

And in that is both a lesson in C++ and how to remember what's going on. In three parts:
  1. Always default to using pre-increment when you can. Make it a habbit to pre-increment, because post-increment can cost you and pre-increment never will.
  2. Remember that post-increment is the "expensive" one, that's how you can tell them apart.
  3. The more expensive post-increment also has the weirder signature when overloaded, e.g. operator++(int), not just operator++().

Monday, March 31, 2008

The Superiority of Ranges

When it comes to describing an interval (whether it is a range in memory, a range on the screen, a range of times) if you work in C/C++, your life will become easier once you recognize the truth: the language wants you to work using "begin/end+1" for ranges.

To clarify the problem, when we have to describe a range of values, there are typically three ways that programmers use a pair of integrals to describe the range:
  1. First item, number of items ("start/length")
  2. First item, last included item ("start/end")
  3. Fisrt item, one past last item ("start/end+1")
This third way is the best way...I don't say that lightly...but after years and years of programming, I find that code using start/end+1 comes out cleaner and simpler every time.

First, why not start/end? Well, the nice thing about start/end+1 is that the length of the range is just end-start. When you use start/end, you have to do the awkward (end-start+1).

Range checks also become inconsistent...basically you want to have your regions defined inclusive on one side and exclusive on the other. In other words, being in the range should be true if x >= x1 && x < x2. What's good about this is that if the end value of one range is equal to the start value of another, the two perfectly align, and the two cover an interval completely. With start/end notation, you get tons of off-by-one situations.

Similarly, start/length simply requires you to write more code. Consider start/end+1...a number of useful operations become trivial:
  • The union of [x1,x2) and [y1,y2) is just [min(x1,y1),max(x2,y2))
  • The intersection of the two is [max(x1,y1),min(x2,y2))
  • A range is empty if x2 <= x1
  • Containment and asymmetric set differences are all equally clean.
Try rewriting the above logic with either start/end or start/length and I think you'll that start/end+1 gives you the simplest code.

Tuesday, March 25, 2008

Message Q's and Sins

Well, it's been at least a year since I ranted about how much I love message queues, so what the heck. Every programmer has a pet idiom and for me the message queue is it - from my perspective it represents one of the cleanest ways to add parallelism to an app.
  • When an algorithm isn't naturally parallel, pipelining is often the best way to split it across cores. Message queues are great for creating the links between the pipeline stages.
  • Message queues naturally solve the problem of resource ownership without extra locking. Since the message cannot be at the send and receive side of the queue at the same time, "owning the message = owning the resource" gives you clean resource allocation. Because there are no locks, you don't have to worry about dead-lock cases or locks getting contested.
A typical message-queue design in X-Plane involves two queues - one sends work to be done to a worker thread and the other sends the results back to the main thread. The worker thread blocks and only runs when there are tasks and the main thread polls the "done queue" periodically at times when it can handle the results. There can be more than one worker thread if desired.

When evaluating this kind of design we have to consider two performance aspects: throughput and latency.

For throughput message-queue designs work pretty well. We can easily scale up the number of worker threads based on the number of cores and simply pile a huge number of tasks into the work queue - that'll keep all of those cores busy.

Where message queue designs don't work as well is latency. When we queue a new task to be done, we have no idea how long it will take to get done, but we know the answer is "longer than if we didn't have a worker thread". Besides the time for the message to get to the thread (that thread might be asleep and have to wake up and then wait for CPU time) we also might have a whole pile of messages ahead of us. Some designs use priority message queues to get preferential dispatch of messages, but even then all threads might be busy. (Even more complexity can be added to try to address that case.)

We also pick up latency on the return side, since the main thread has to check for finished results, which might only happen once per simulation frame.

Fortunately for X-Plane, the kinds of things we push out to threads usually aren't very latency sensitive - we build up 3-d scenery, but we queue it well before we arrive at that location, so the additional latency is acceptable.

Sunday, March 02, 2008

The Greatest 24 Pages Ever

(Okay, that might be a slight exaggeration but...)

Everything you wanted to know about the Radeon 9500 - X1900 but were afraid to ask. (PDF)

The reason I love this document so much is the scope it covers: exactly how the hardware is different from the specs. One of the tricky aspects of programming advanced OpenGL applications these days is that a lot of the fine print can't be expressed in terms of the extensions. For example:
  • The R300/R400 (X100-X850) GPUs will render to floating point bufferers, but do not provide alpha testing, alpha blending, or fog on the back end of the frame buffer.
  • The R500 GPUs (X1000-X1900) will render floating point buffers with alpha and blending but only if the floating point buffer is 16 bitgs, not 32 bits. Fog is still not an option.
If you violate these constraints the GL will fall back to software rendering, which is usually not what you want. You can discover all of these things in beta and slowly work up a profile of supported hardware (there are "only" 8 distinct revisions of pixel-shader-capable graphics cards out there between nVidia and ATI) but when a document comes along and spells out all the fine print (including stuff you might not otherwise know), well, that's a gift!!!

One thing I learned that I would never have figured out: glClear gives better fill rate than simply over-painting the Z buffer on the R300.

The document even discusses internal precisions. (Hey X-Plane users...this is why your water looks "square" and "pixelated" on pre-X1000 Radeons; lower internal floating point precision and other R300/R400 hardware limititations.)

As far as I know, this is the closest thing by nVidia.

Sunday, February 17, 2008

Creating OpenGL Objects in a Second Thread - Mac, Linux, Windows

This blog entry explains how to set up OpenGL to create new OpenGL "objects" (vertex buffer objects, display lists, and textures) from a second thread. The benefits of this technique are:
  • It moves CPU-intensive driver operations to a second core even if the driver is not multi-threaded internally*. CPU-based on-the-fly texture compression would be an example where you can get a win.
  • It allows you to move the entire process of building up and loading a scene-graph to a second thread, regardless of the use of OpenGL loading commands (like building of VBOs).
  • Because there is no use of the main thread, the main rendering loop can continue to run at full speed (assuming the user has a dual-core machine).
The basic strategy is to build an OpenGL context for each worker thread that will do loading such that the contexts share objects (display lists, etc.) with the main rendering thread's OpenGL context.

(This information comes from in-field tests; if you work on the GL implementation and spot something wrong, or if you find in deployment that this doesn't work, please let me know. Also a warning: the latest version of this code hasn't been in-field very wrong - in the past edge cases have appeared that have caused us to redesign threaded loading more times than I'd like to admit.)

A warning on thread safety: OpenGL's asynchronous nature (sequential deferred execution within a context) leads to some tricky threading bugs that you wouldn't normally see - see this blog post for examples of what can go wrong.

Terminology

While the structures differ between AGL/CGL (Macintosh), WGL (Windows) and GLX (Linux/X11) there are some common features in the way the window manager and the GL interface.
  • "Pixel Format." All three operating systems define a pixel format as an opaque description of a series of properties for a rendering context. In my tests, I use the same pixel format for all contexts.
  • "Drawable." Basically any window, full screen destination, or off-screen hardware accelerated buffer is a "drawable", and it defines where the result of GL commands to a context end up.
Macintosh

The Macintosh is probably the easiest OS to set this up on, because you don't need to use a drawable for the loader contexts.
  1. Create new contexts for each worker thread, using the main rendering context as a source for shared objects.
  2. In the start of the worker thread, set the worker thread's context to be current.
Windows

On Windows, you'll need to do all of the creation work inside the worker thread:
  1. Get a DC from the main window. This should create a new DC that your worker thread can use. (There is apparently nothing wrong with requesting multiple DCs from a single window.)
  2. Create a new context for the worker thread.
  3. Set the new context to share objects with your main context.
  4. Set the worker context to current using the DC you acquired.
Note that your main thread will have to temporarily drop the main context as its current context - otherwise you'll get a "resource busy" error when you try to share contexts - the main thread effectively has that context locked when in use, so you'll want to set the main thread's current context to null, then set it back when done.

Also note that you can't use window-owned or class-owned DCs in this design because either of those will cause you to get back one DC every time you call GetDC and you really need a unique DC for each thread. Be sure to release the DC on the same thread you use to acquire it!

Linux

Linux is similar to the Macintosh, except that the worker threads need a drawable. For this I used p-buffers.
  1. The main thread creates a new context, shared with the main context.
  2. The worker thread makes a new small pbuffer for itself.
  3. The worker thread sets the worker context as current, using the pbuffer as its drawable.
I tried using the main window as the drawable for all threads, but this causes some kind of locking or thrashing between threads and hurts performance of the main renderer. Extra hidden windows were unreliable for reasons I was not able to determine.

Alternatives

The alternative to this design is to use an RPC-like mechanism to execute all OpenGL activity in the main thread, e.g. once per frame pick up any OpenGL work to be done from worker threads, run it, then let them continue. This has some advantages and disadvantages:
  • On the pro side, it doesn't require multiple contexts - you may find that some drivers do better executing everything on one context.
  • OpenGL work is done at the same time in every frame, possibly resulting in more controlled operation, particularly on single-threaded machines.
  • On the con side, loader code that needs to create OpenGL objects before proceeding (to keep memory footprint down, for example) may operate slowly since it has limited access to the GL.
* This assumes that the driver is not multi-threaded internally, but is capable of performing these CPU-based operations without locking out the render thread via a mutex...a big assumption that I cannot validate or invalidate at this point.

Monday, February 11, 2008

popen, Windows, and quotes

Turns out that this won't work very well on Windows:

popen("\"C:\\some dir\\some_file.exe\" \"input file\"");
But this will:

popen("\"\"C:\\some dir\\some_file.exe\" \"input file\"\"");
Those coming from Unix-land would think the second example has one too many quotes; here's more info.

Wednesday, January 30, 2008

The Absense of Evidence...

...is not evidence of absense! This is definitely true when it comes to bugs. We could spend a year and not prove that X-Plane is bug free, but it only takes a minute to prove that it has bugs.

(This isn't unlike an NP-complete problem like prime number factoring; the asymmetry of proof provides the protection.)

Can you tell I've been reading "The Black Swan"? A book that's very relevant financially these days. Perhaps the tragedy of the housing bubble is that it moved everyone's houses from Mediocristan to Extremistan* without the people that owned the houses (that'd be all of us) noticing. Or perhaps we've been in Extremistan for a long time and just didn't realize.

* (These are Taleb's made up names for systems that experience the law of big numbers vs. systems that experience chaotic outlier events.)