Last active
December 16, 2016 21:04
-
-
Save zacharycarter/955427d26c2a45137dac7df7885a35a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static Texture generateNormalMapTexture(int width, int height, Pixmap pm) { | |
pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888); | |
texture = new Texture(width, height, Pixmap.Format.RGBA8888); | |
for (int x = 0; x < width; x++) { | |
for (int y = 0; y < height; y++) { | |
Vector3 currentVertex = new Vector3(x, getPixelWrap(x, y, width, height, pm), y); | |
Vector3 pU = new Vector3(x + 1, getPixelWrap(x + 1, y, width, height, pm), y); | |
Vector3 pV = new Vector3(x, getPixelWrap(x, y + 1, width, height, pm), y + 1); | |
Vector3 dpU = negate(currentVertex.cpy().sub(pU)); | |
Vector3 dpV = currentVertex.cpy().sub(pV); | |
Vector3 normal = dpU.cpy().crs(dpV).nor(); | |
Vector3 normalRGB = normal.cpy().scl(0.5f).add(0.5f); | |
pixmap.drawPixel(x, y, new Color(normalRGB.x, normalRGB.y, normalRGB.z, 1).toIntBits()); | |
} | |
} | |
PixmapIO.writePNG(Gdx.files.getFileHandle("normalmap.png", Files.FileType.Local), pixmap); | |
texture.setWrap(Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge); | |
texture.draw(pixmap, 0, 0); | |
return texture; | |
} | |
private static final float getPixelWrap(int x, int y, int width, int height, Pixmap pixmap) { | |
if(MathUtils.isPowerOfTwo(width) && MathUtils.isPowerOfTwo(height)) { | |
if (x < 0 || x >= width) x = (width + x) & (width - 1); | |
if (y < 0 || y >= height) y = (height + y) & (height - 1); | |
return pixmap.getPixel(x,y); | |
} else { | |
if (x < 0 || x >= width || y < 0 || y >= height) { | |
return pixmap.getPixel((y + height) % height,(x + width) % width); | |
} else { | |
return pixmap.getPixel(y,x); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment