프로그래밍

UV Mapping

dEtH 2010. 6. 24. 10:21

http://en.wikipedia.org/wiki/UV_mapping
http://en.wikipedia.org/wiki/Sphere_mapping
final int C = 8;
PImage[] imgs;
PImage tex;
int px, py;
boolean prerendered = false;
PImage sphereMapped(PImage tex, int R, float offsetx, float offsety, float zoom, boolean bilinear) { PImage img = createImage(R, R, ARGB); img.loadPixels(); tex.loadPixels(); for (int i = 0; i < img.pixels.length; i++) { float r = img.width / 2; float x = i % img.width - img.width / 2, y = i / img.width - img.height / 2; float a = min(1, r - sqrt(x*x + y*y)) * 255; x /= r; y /= r; float u = acos(x / sqrt(1- y*y)) / PI; float v = acos(y) / PI; u = u / zoom; v = v / zoom; u += offsetx; u = ceil(u) - u; v += offsety; v = ceil(v) - v; u *= tex.width - 1; v *= tex.height - 1; float ur = u - floor(u); u = floor(u); float vr = v - floor(v); v = floor(v); int idx = (int)(u + v * tex.width); color c = !bilinear ? tex.pixels[idx] : lerpColor( lerpColor(tex.pixels[idx], tex.pixels[idx+1], ur), lerpColor(tex.pixels[idx+tex.width], tex.pixels[idx+tex.width+1], ur), vr ); //img.pixels[i] = color(red(c), green(c), blue(c), alpha(c) * a / 255); img.pixels[i] = color(red(c), green(c), blue(c), a); } return img; }
void setup() { size(320, 320); smooth(); textFont(loadFont("SegoeUI-12.vlw")); tex = loadImage("p.png"); tex.loadPixels(); imgs = new PImage[C*C]; for (int n = 0; n < C*C; n++) imgs[n] = sphereMapped(tex, 32, n % C / (float)C, n / C / (float)C, 1.0, true); /* // export images PGraphics g = createGraphics(33*C + 1, 33*C + 1, JAVA2D); g.beginDraw(); for (int i = 0; i < C*C; i++) g.image(imgs[i], 1 + i%C * 33, 1 + i/C * 33); g.endDraw(); g.save("balls.png"); px = width/2; py = height/2; */ }
void draw() { px = (px * 9 + mouseX ) / 10; py = (py * 9 + mouseY - 16) / 10; //background(128); fill(128, 96); rect(0, 0, width, height); fill(0, 64); text("Click to switch Prerendering Mode: " + prerendered, 4+2, 14+2); fill(255); text("Click to switch Prerendering Mode: " + prerendered, 4, 14); noStroke(); fill(0, 64); ellipse(px, py + 16, 30, 20); imageMode(CENTER); if (prerendered) { int idx = (int)(px/5) % C + (int)(py/5) % C * C; idx = (C*C + idx) % (C*C); image(imgs[idx], px, py); } else { image(sphereMapped(tex, 32, px * 0.02, py * 0.02, 1.0, true), px, py); } }
void mouseClicked() { prerendered = !prerendered; }