From 136a7fcbfabb2f0b0b3e340213e36a548715a370 Mon Sep 17 00:00:00 2001 From: Eleni Maria Stea Date: Sun, 20 Aug 2017 23:56:12 +0300 Subject: [PATCH] added linear interpolation in image to use it at the terrain generation --- src/image.cc | 41 +++++++++++++++++++++++++++++++++++++---- src/image.h | 4 +++- src/terrain.cc | 2 +- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/image.cc b/src/image.cc index a99f75a..82d8cd1 100644 --- a/src/image.cc +++ b/src/image.cc @@ -121,11 +121,8 @@ bool Image::load(const char *fname) return true; } -Vec4 Image::lookup_nearest(float u, float v) const +Vec4 Image::get_pixel(int x, int y) const { - int x = (int)(u * w) % w; - int y = (int)(v * h) % h; - if(is_float) { return ((Vec4*)pixels)[y * w + x]; } @@ -138,4 +135,40 @@ Vec4 Image::lookup_nearest(float u, float v) const color.w = pptr[3] / 255.0; return color; +} + +Vec4 Image::lookup_nearest(float u, float v) const +{ + int x = (int)(u * w) % w; + int y = (int)(v * h) % h; + + return get_pixel(x, y); +} + +Vec4 Image::lookup_linear(float u, float v, float du, float dv) const +{ + /* bottom left */ + int x0 = (int)(u * w) % w; + int y0 = (int)(v * h) % h; + int x1 = (x0 + 1) % w; + int y1 = (y0 + 1) % h; + + /* uv coordinates at the img corners */ + float u0 = (float)x0 / (float)w; + float v0 = (float)y0 / (float)h; + float u1 = (float)(x0 + 1) / (float)w; + float v1 = (float)(y0 + 1) / (float)h; + + float tu = (u - u0) / (u1 - u0); + float tv = (v - v0) / (v1 - v0); + + Vec4 p00 = get_pixel(x0, y0); + Vec4 p01 = get_pixel(x0, y1); + Vec4 p11 = get_pixel(x1, y1); + Vec4 p10 = get_pixel(x1, y0); + + Vec4 ptop = lerp(p01, p11, tu); + Vec4 pbot = lerp(p00, p10, tu); + + return lerp(pbot, ptop, tv); } \ No newline at end of file diff --git a/src/image.h b/src/image.h index ec5228d..3f3ba54 100644 --- a/src/image.h +++ b/src/image.h @@ -27,8 +27,10 @@ public: bool load(const char *fname); + Vec4 get_pixel(int x, int y) const; + Vec4 lookup_nearest(float u, float v) const; - //TODO lookup_linear + Vec4 lookup_linear(float u, float v, float du, float dv) const; }; #endif // IMAGE_H_ \ No newline at end of file diff --git a/src/terrain.cc b/src/terrain.cc index c4db7ed..0f10074 100644 --- a/src/terrain.cc +++ b/src/terrain.cc @@ -115,7 +115,7 @@ float Terrain::get_height(float u, float v) const sn = sn * 0.5 + 0.5; if(params.coarse_heightmap.pixels) { - Vec4 texel = params.coarse_heightmap.lookup_nearest(u, v); + Vec4 texel = params.coarse_heightmap.lookup_linear(u, v, 1.0 / params.tile_usub, 1.0 / params.tile_vsub); sn *= texel.x; } return sn; -- 1.7.10.4