Blog about (Web-) Programming, Graphics and Games.

05.02.2011

Skybox algorithm


For the Wloom project a skybox was needed. A skybox is a large box around a scene, with sky texture. The textures of the 6 planes of the box can be calculated from a single picture.

The algorithm for this transformation is outlined as follows: For every texture point of the box-planes calculate two angles relative to the center of the box: a horizontal angle ax, where value 0 represents north, PI/2 east, PI south and 3PI/2 west; and a vertical angle ay, with a range from value 0 (=top) to PI (=bottom). From the original picture the color at the coordinates of the two angles is now taken and drawn towards the texture-point of the box-plane. Below the exact algorithm, written in Java, is listed.
for (int y=0;y<=w;y++) 
for (int x=0;x<=w;x++) {
double xh=x-w*0.5;
double lh=w*0.5;
double ax=PI/4+Math.atan2(xh,lh);
double ay=Math.atan2(Math.sqrt(xh*xh+lh*lh),-y+lh);
b.setRGB(x,y+w,getRGB(ax*biw/(PI*2),ay*bih/PI));
b.setRGB(x+w*2,y+w,getRGB((ax+PI)*biw/(PI*2),ay*bih/PI));

ax=PI/4+Math.atan2(lh,-x+lh);
b.setRGB(x+w,y+w,getRGB(ax*biw/(PI*2),ay*bih/PI));
b.setRGB(x+w*2,y+w*2,getRGB((ax+PI)*(biw-0.5)/(PI*2),ay*bih/PI));

double yh=y-lh;
ax=3*PI/4+Math.atan2(xh,yh);
ay=PI/2-Math.atan2(lh,Math.sqrt(xh*xh+yh*yh));
b.setRGB(x+w,y,getRGB(ax*biw/(PI*2),ay*bih/PI));
ax-=PI/2;
b.setRGB(x+w,y+w*2,getRGB(biw-1-ax*biw/(PI*2),bih-1-ay*bih/PI));
}
The shown skybox is used in the next version of the WebGL game Wloom, which will be posted soon.