Edit: Nevermind, some guy already posted code twice as fast haha
…old message:
Took me a while to figure out how to tween colors really fast, so maybe some more people can use this.
Drawing 262144 pixes from perlin noise, went from 40 ms to 6 ms, and it does not have any disadvantages (exept color maps may be a bit more complex because it uses ints).
For maximum speed it ignores the alpha of both colors, and uses the parameter alpha to set the amount of the second color to blend.
Blend function:
public static int TweenColor(int c1, int c2, int a){
int r = (c1 & 0xFF0000) >> 16;
int g = (c1 & 0x00FF00) >> 8;
int b = c1 & 0x0000FF;
int rd = r + (((((c2 & 0xFF0000) >> 16) - r) * a) >> 8);
int gd = g + (((((c2 & 0x00FF00) >> 8) - g) * a) >> 8);
int bd = b + (((((c2 & 0x0000FF)) - b) * a) >> 8);
return 0xFF000000 | (rd << 16) | (gd << 8) | bd;
}
Its possible to keep the color map like its implemented normally, if you convert the colors to ints before starting the drawing loop.
Color[] c = new Color[] { }; //Fill color array
int[] colormap = new int[c.length];
for(int i = 0; i < c.length; i++){ colormap[i] = c[i].hashCode(); }
Example:
public static BufferedImage fillTerrain(int[] depthmap, Color[] c, int width, int height){
BufferedImage img = ... //Create image
int maxacces = width*height;
int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
int max = c.length-1;
int[] colormap = new int[c.length];
for(int i = 0; i < max; i++){ colormap[i] = c[i].hashCode(); }
int var, index = 0;
//Fill image
for(int acces = 0; acces < maxacces; acces++){
index = depthmap[acces]>>8;
var = depthmap[acces] % 256;
pixels[acces] = TweenColor(colormap[index], colormap[index + 1], var);
}
return img;
}