fixed terrain rendering - visualized normals
[demo] / src / terrain.cc
index 6bfabe8..bdd787f 100644 (file)
@@ -1,39 +1,85 @@
+#include <gmath/gmath.h>
+
 #include "camera.h"
+#include "gfxapi.h"
 #include "image.h"
+#include "mesh.h"
+#include "meshgen.h"
+#include "object.h"
 #include "scene.h"
 #include "terrain.h"
 
-Terrain::Terrain() {}
+static float calc_height(float u, float v, void *ptr);
+
+Terrain::Terrain()
+{
+       vis_scene = 0;
+}
 
 Terrain::~Terrain()
 {
 }
 
+bool Terrain::init()
+{
+       vis_scene = new Scene;
+
+       return true;
+}
+
+void Terrain::destroy()
+{
+       delete vis_scene;
+}
+
 bool Terrain::generate(const TerrainParams &params)
 {
-       // if(xsz <= 0 || ysz <=0) {
-       //      fprintf(stderr, "Invalid terrain size.\n");
-       //      return false;
-       // }
+       tiles.clear();
 
-       // if(xtiles <= 0 || ytiles <= 0) {
-       //      fprintf(stderr, "Invalid number of terrain tiles.\n");
-       //      return false;
-       // }
+       float txsz = params.xsz / params.xtiles;
+       float tysz = params.ysz / params.ytiles;
 
-       // if(tiles)
-       //      tiles.clear();
+       for(int i=0; i<params.ytiles; i++) {
+               for(int j=0; j<params.xtiles; j++) {
+                       TerrainTile tile;
+                       tile.mesh = gfx_create_mesh();
 
-       // int tsz = xtiles * ytiles;
-       // tiles.resize(tsz);
+                       gen_heightfield(tile.mesh, txsz, tysz, params.max_height,
+                                       params.tile_usub, params.tile_vsub, calc_height,
+                                       (void*)&params);
 
-       // for(int i=0; i<tsz; i++) {
+                       tile.mesh->update_vertex_data();
+                       tiles.push_back(tile);
 
-       // }
+/*
+       the terrain scene stores objects only
+       no need to fill the mat, mesh std::vectors
+*/
+                       Object *o = new Object;
+                       o->mesh = tile.mesh;
+                       o->material = &material;
+                       o->transform = Mat4::identity;
+
+                       vis_scene->objects.push_back(o);
+               }
+       }
        return true;
 }
 
 Scene *Terrain::get_visible(const Camera *camera) const
 {
-       return 0;
+       return vis_scene;
 }
+
+static float calc_height(float u, float v, void *ptr)
+{
+       if(!ptr) {
+               fprintf(stderr, "Terrain parameters not found.\n");
+               return 0;
+       }
+
+       TerrainParams *tp = (TerrainParams*)ptr;
+       float sn = gph::fbm(u * tp->noise_freq, v * tp->noise_freq, tp->num_octaves);
+       /* todo use the image later */
+       return sn;
+}
\ No newline at end of file