Thursday, June 12, 2014

Cornell Boxing

I recently read the Voxel Cone Tracing paper which got me playing with rendering code again.

The Cornell Box, rendered with one point light and no shadows
Same scene voxelized at 128^3 and ray marched
Sampling the same volume texture at a coarser LOD

Monday, December 5, 2011

I can see forever



Draw distance: 400 m
Loaded chunks: 132,651
Median frame time: 4 ms
Representative scene: nope.avi

Thursday, November 10, 2011

FPGA fun

I recently purchased an FPGA development board and an LCD to go with it. This is what I've made it do so far:



The display is run by a simple character-based driver. The 800x480 screen is broken into 8x8 character tiles, and the pixel values are scanned out on the fly at 60 Hz.

I plan to use this display driver to debug a CPU (that I haven't written yet) by replacing parts of the text ROM with live links to CPU state. This means I can debug before the CPU has any I/O capabilities, showing all of the registers on-screen and maybe even looking into pipeline state.

Thursday, June 9, 2011

mvminer can start asynchronous jobs

Before today, mvminer was a single-threaded program. Today, mvminer has a job queue and can load chunks in the background! Gone are the days of waiting several minutes for the (horribly slow) texture generator to run 1,048,576 times before the display comes up.

Mapping tiles into the virtual texture and loading vertices cause a slight pause while they block the GL thread, so I will build rate limiters into their classes. Right now the virtual tile map and shared vertex buffer can only be operated from the GL thread; they should buffer changes and submit them in reasonably-sized batches per frame.

Here are a few screenshots taken as chunks load around the origin:


mvminer has started loading


oh my this texture generator is slow


mvminer continues to load

As always in the first undesigned iteration, this implementation is a complete hack (the asynchronous jobs are all queued up on startup and aren't owned -- quitting before they finish causes a segfault as their working sets are reclaimed by the system).

Once the code is cleaner again I will need to start on a "loading manager" (not sure of the clearest name for it). This system will maintain a prioritized record of nearby chunks and, if they are loaded, their exposed tile counts. It will issue all of the load/save/map-tiles/unmap-tiles requests.

mvminer has semi-static shared vertex buffers



This image was rendered in a single draw call from a shared VBO/IBO polygon pool. Right now it can hold 1M tiles in a 32MB VBO with a 24MB IBO. The index buffer is extra large since I have to use 32-bit indices, but it ends up being a huge performance win when the polygon pool is only partially full; unused polygons can be made explicitly degenerate by zeroing out the indices.

I may end up switching back to unindexed triangle soup in a 48MB VBO depending on performance. (or 32MB of unindexed quads, but quads are deprecated in newer GL releases) The goal will be to keep the polygon pool and virtual tile map full at all times, prioritizing exposed tiles closest to the player. Of course, none of that logic has been implemented yet, and the indexed-triangle solution is better for a scene like this where the buffers are only 22% full.

Thursday, May 26, 2011

mvminer update - textures and physics

I've put in a few evenings working on mvminer's renderer. I have implemented a unique texturing system and I just finished throwing in a complete-hack physics test.

One of my design goals for mvminer is for each block to have a unique, procedurally-generated texture. This will make single material structures more interesting and opens up possibilities for player paintings or other dynamic texture changes.


The first implementation of unique texturing

When I first got it working I wasn't doing actual seeded procedural textures. The screenshot above uses rand() to fill in the index half of a bunch of DXT1 blocks, the color half being selected from a table based on block type. That, of course, is completely nondeterministic and is unrelated to spatial location. With the basics working, I implemented a straightforward Perlin noise function that takes an absolute world location.


The inside of a large box textured with a few octaves of Perlin noise

The result looks pretty good! At some point in here I decided to fix block sizes at 0.5 m to a side (half of Minecraft's block size) and texture resolution at 8x8 per block face. To get a better idea of the noise's spatial qualities I hacked a sphere generator into the new-chunk generation code:


Behold the dirtsphere

For comparison, I set up a similar screenshot, but with each block having a randomized origin location. This represents what a user-created structure would look like, with spatially distant blocks brought together.


Dirtsphere, chaos edition

At this point I was getting tired of waiting for texture generation. Generating ~3000 tiles was taking about 20 seconds, so I switched back to rand() to work on some other things. First up, a simple terrain generator.


mvminer is a game about dirt

I switched the Perlin tile generator back on for that screenshot, and it took a few minutes to come up. My plan is to generate batches of noise, computing corner gradients once per batch and then lerping (well, quintic-erping) a bunch of samples in a tight loop, but that can be done later.

Last night I decided to try integrating a physics engine. I had used the Open Dynamics Engine in a previous project and I was getting to know it quite well, but the limited collision detection system was getting annoying. I thought it was time to try Bullet, so I downloaded the latest archive, built it, and had a horrible hack implementation up and running in a few hours.


There's something odd about this box ... could this be what they call rotation?

Once again, it's a complete hack. I need to code up a solid local physics entity system. Minecraft has weird behavior out in the Far Lands, where 32-bit floats start to have much less sub-integer precision. I intend to avoid that by segmenting the simulation along chunk boundaries and keeping coordinates nice and small. Eventually I'd like to remove Bullet in favor of a custom fixed-point physics system, for the dual purposes of absolute determinism and educational wheel reinvention.

Up next, an in-depth description of the virtual tile map system that makes unique texturing possible (and easy!).

Sunday, March 6, 2011

Switching projects

So I've been playing Minecraft. That game eats hours. It's lots of fun, but I find myself wanting more. The Nether/Nexus doesn't work in multiplayer. Textures aren't mipmapped when minified. The set of movable objects is very limited. Redstone is cool, but could be used for so much more. And what does a developer do when existing software isn't quite perfect? Roll your own!

The core mechanics of Minecraft are very simple. The world is an expansive cubic grid of blocks, 128 blocks high but almost unbounded in width and depth. Most blocks are static until modified by outside influences. The potential data set of a world is huge, so it is divided into 16x16 chunks (spanning the full 128 blocks vertically). These chunks are generated procedurally on demand and are persisted to disk.

This I could do. My physics sandbox project has gone into full-on analysis paralysis, and (let's admit it) reinventing wheels in a fresh codebase is just fun.

Possible extensions:

  • 4D coordinate system: Entering the Nether/Nexus would just be a coordinate transformation. Shift x/y/z to align with the new world and update w.

  • Free blocks: Detached blocks become physically simulated. Every collision is between two unit cubes!

  • Stress and fracture: Collisions trigger a local static stress analysis. Nothing ever bends, but world blocks can be freed and free blocks can be separated.

Friday, August 20, 2010

Parts

Today the engine has Parts, which are a collection of mass, collision solids, and visual models. Parts can be initialized from a simple text format:
Part {
version 1
mass Sphere { radius 0.5 density 100 }
solid Sphere { radius 0.5 material wood }
model Model { file media/test/sphere.model }
}


It's a sphere!

Here's a more interesting example:
Part {
version 1
mass Sum {
Box { size 1 1 1 density 100 }
Xform { Sphere { radius 0.5 density 100 } pos 1 0 0 }
Xform { Sphere { radius 0.5 density 100 } pos -1 0 0 }
Xform { Sphere { radius 0.5 density 100 } pos 0 1 0 }
Xform { Sphere { radius 0.5 density 100 } pos 0 -1 0 }
Xform { Sphere { radius 0.5 density 100 } pos 0 0 1 }
Xform { Sphere { radius 0.5 density 100 } pos 0 0 -1 }
}
solid Box { size 1 1 1 material wood }
solid Sphere { radius 0.5 material wood pos 1 0 0 }
solid Sphere { radius 0.5 material wood pos -1 0 0 }
solid Sphere { radius 0.5 material wood pos 0 1 0 }
solid Sphere { radius 0.5 material wood pos 0 -1 0 }
solid Sphere { radius 0.5 material wood pos 0 0 1 }
solid Sphere { radius 0.5 material wood pos 0 0 -1 }
model Model { file media/test/crate.model }
model Model { file media/test/sphere.model pos 1 0 0 }
model Model { file media/test/sphere.model pos -1 0 0 }
model Model { file media/test/sphere.model pos 0 1 0 }
model Model { file media/test/sphere.model pos 0 -1 0 }
model Model { file media/test/sphere.model pos 0 0 1 }
model Model { file media/test/sphere.model pos 0 0 -1 }
}


It's a whatever!

Now I'll see if I can advance the GUI system enough to give me a part palette.

Monday, June 21, 2010

Project Mod SVN 41

Activity! I produces it!

Tonight's code is a quick addition to the FPSPlayer class. It's a tool switcher that is fed the player's input and hooks into the player's drawHUD() method. The UI isn't the prettiest, but it's a concrete enhancement and it works.

Friday, June 18, 2010

FPS player, move tool, and bomb tool

It's been a while since the last post, so let's post! Motivation is always an issue.

Revision 39 from way back in April brought the the things I have to show off today. First, there is a partially implemented FPS-style player controller. WSAD moves and the mouse looks around. There is a system for swappable tools (though no swapping GUI at the moment) featuring a move tool (like Garry's Mod's physgun) and a bomb tool (to apply inverse-square-with-distance forces in an area).


The move tool in action, rearranging an orderly stack of boxes into a disorderly non-stack of boxes.


The move tool abusing a car's suspension.


The bomb tool, just after detonation.


The bomb tool, a bit longer after detonation.

Sunday, January 10, 2010

Not dead

Today I implemented PNG screenshots, and will no longer appear to be dead. Here is the car player I've been putting time into, modeled on a 2001 Pontiac Sunfire. Except for the being composed of two planes thing.

I'm going to start using Google Code's bug tracker to set goals. Following the screenshotter, the current enhancement is the addition of an FPS-style player. Completing that should bring the level of user-visible functionality up to where mod (mod1, as in not mod2 or mod3) was before I decided to abandon it and rewrite the project twice.

Monday, August 10, 2009

Project Mod SVN 14

SVN commit log:

  • Moved lighting to eye space to reduce roundoff error.

  • Added PeriodicBroadcastGame and ListenerGame to start testing very simple client/server game state transfer.

  • Fixed some horrible errors in newmath/Matrix{2,3,4}, which weren't really being used before.

  • Added ability to get the inverse() or inverseTranspose() of a Matrix{2,3,4}.

  • Added a ReadByteStream to go with the WriteByteStream.

  • Implemented better bzip2 support in {Read,Write}ByteStream.

  • Added SDL_net to build-system3.

  • Core classes State, Body, Solid, Constraint, and Light are serializeable through toBytes() and fromBytes().

  • TODO: implement toBytes() and fromBytes() in Controller.



The window on the left is sending a game state packet over UDP to the window on the right, which is displaying it from a fixed viewpoint. :3

Wednesday, August 5, 2009

Deferred shadow maps

After a bit of time off I made the deferred shader not be a hack and added colored, shadow mapped lighting. Code will be in SVN 11, maybe tomorrow evening.

In this screenshot, the car thingy has three colored spot lights attached to its front:


Edit: SVN 11 committed.

Saturday, July 25, 2009

Project Mod SVN 10

Tonight I added an HDR deferred shading system:

  • A simple shader writes surface color, normal, and world position to a trio of RGBA16F screen-sized textures.

  • The blend target (a fourth RGBA16F screen-sized texture) is cleared.

  • For each light in the scene one of the light shaders uses the three deferred textures to compute the light's contribution to each pixel, which is added to the blend target.

  • The tone mapping shader exposes and gamma corrects each blended pixel and writes them to the back buffer


I'm cheating right now by hard coding a point light and a spot light into the renderer code, but it should be easy enough to generalize. The code is a bit ugly, but it's all confined to the renderer class.







Up next: shadow mapping.

Friday, July 24, 2009

Project Mod SVN 9

Here's the evening's update. I implemented controllers, which basically have a step function and can manipulate things. Player is a subclass of controller with two additional functions: getViewPos and getViewQuat. The game client uses these to control the camera. To test the framework I wrote a CarPlayer class that manages a few rigid bodies and constraints to make a simple front wheel drive car with steering.



Next up:

  • Lighting - I implemented a hacky shadow mapping system after SVN 7 which looked really nice, but I set it aside because the code was so ugly. I'll need to think of a way to keep the GL state management code out of the SinglePlayerGame class, and maybe split some of the texture/model management from the GUI class into some kind of video state manager.

  • Screenshot / video capture - For the spamming of YouTube, and because this build looks much cooler in motion.

  • More test textures and models - This will not be one of those cool but ugly open source projects.

Thursday, July 23, 2009

Project Mod SVN 8

This car thingy consists of five rigid bodies, five collision objects, and four hinge constraints. Keyboard input applies locally-aligned torque to each wheel. Up next: controller objects. These will be non-physical, but will be allowed to interact with bodies, solids, and constraints. The player object will be a special controller subclass with access to input devices and ability to control the viewpoint.

Tuesday, July 21, 2009

Project Mod work

I've been working on Project Mod, my grand vision for an open-source-powered multiplayer physics sandbox game. As usual, I've thrown out a good chunk of the old code and have started (mostly) anew. This time my first focus has been a usable GUI layer for configuration and game selection. I just committed SVN revision 5, and this is what it looks like:


Main menu with some buttons


Video settings menu with buttons, a drop list, and a checkbox

At the moment the "game" is just a white rotating quad, but the core code incorporates ODE and should give me tumbling boxes soon enough.

For anyone interested (all zero of you subscribers from the internets):
Google Code project page
SVN repository

Building on Linux is easy: go to the /mod3client folder and make run, or make all && build/linux/mod3client if you really like typing. Building on Windows works, but isn't as automated. I've made it work with Visual C++ 2008 Express, after setting up all the requisite libraries, by dumping the source into a Win32 Console Application and changing a few project settings.

Up next: importing my old model loader, and upgrading the game to involve something exciting like box sliding.

Thursday, April 16, 2009

GPU Global Illumination

By this point it must be clear that my hobby programming has a very short attention span.


A purplish glow is cast on the wall. The ceiling is softly illuminated by reflections from the floor.


Some color bleeding is visible on the wall and floor. The spheres display the captured incident light at each probe point.


Wide view with indirect lighting disabled.


Wide view with indirect lighting enabled.

This demo divides the space in a small room into a voxel grid. Light probes (16x16 cube maps) are captured at the center points of each voxel, arranged as tiles on a huge 96x4096 RGB16F texture. This texture is then modulated by the first nine real spherical harmonic basis functions and rendered to a set of nine more 96x4096 RGB16F textures, three per pass. These nine huge float textures are reduced and rearranged in a number of passes to a set of nine 8x8x4 RGB16F volume textures representing the (rather low-resolution) incident light at every point in the room as a set of real spherical harmonic coefficients. The final pass is rendered using these volume textures to provide one bounce of interpolated indirect light in addition to the direct light cast by the static and camera-mounted spot lights.

Whew.

To summarize, this demo renders a scene with one bounce of indirect light, based on real spherical harmonic coefficients interpolated from a regular grid of 256 light probes.

The sample scene runs at about 15 FPS on my aging desktop with an NVIDIA GeForce 7800 GT.

Now to optimize the slow out of it.

Saturday, March 14, 2009

C++ pointer-to-member-function events

I made an Event class that can be hooked with a member function from any class. I ended up using a combination of virtual functions, templates, and nested classes, and I was just pleased enough with the result to blag about it for a while.

Static example

class Foo {
private:
  Event _wasFrobbed;
  
public:
  Foo() { }
  Event::PublicEvent& wasFrobbed() { return _wasFrobbed.pub(); }
  void Frob() { _wasFrobbed.Fire(); }
};

void CharlesWasFrobbed() {
  cout << "Charles was frobbed\n";
}

void Test1() {
  Foo charles;
  
  //Hooking his event
  charles.wasFrobbed().Hook(&CharlesWasFrobbed);
  
  //Frobbing him
  charles.Frob();
  
  //Unhooking his event
  charles.wasFrobbed().Unhook(&CharlesWasFrobbed);
}

That's easy enough to use, but not so impressive on its own. The fun part is that it works with pointers to member functions as well!

Pointer-to-member-function example

class Bar {
private:
  Foo* _pfoo;
  
public:
  void NoticeFrob() {
    cout << "a Bar was witness to a frobbing\n";
  }
  
  Bar(Foo* pfoo) : _pfoo(pfoo) {
    //Hook the target Foo's event
    _pfoo->wasFrobbed().Hook(this, &Bar::NoticeFrob);
  }
  
  ~Bar() {
    //Unhook the target Foo's event
    _pfoo->wasFrobbed().Unhook(this, &Bar::NoticeFrob);
  }
};

void Test2() {
  Foo winston;
  Bar nigel(&winston);
  
  //Frobbing Winston ... Nigel will notice
  winston.Frob();
}

Next step: add a template parameter to the Event class itself so the event can fire with an argument.

Sunday, February 1, 2009

Networking model

I've been reading up on how Valve's Source engine handles network play, and I've come up with an outline for how I want this to work in Project Mod.

The key feature is a deliberate addition of input latency, sacrificing some snappiness for a smoother appearance on the client. Clients sample the local player's controls and send them to the server at the world's step rate (200 Hz at the moment, one step per 5 ms), but tagged for a future step. Source defaults to 100 ms. The server operates in the future, collecting controls packets, simulating the world, and sending periodic bunched updates to all clients.

When network latency is less than (input latency - update interval) and no packets are dropped, every client will already have the current world state stored in a buffer when it's time to refresh the screen. This means no prediction, no extrapolation, and zero jittering for ping up to 80 ms, at the cost of a consistent input latency of 100 ms. This delay could of course be adjusted for connections with higher or lower average latency, or even disabled for a local single player game.

I'll post more as I attempt to implement it.