From ae60a8cb1a30e204e7f60969fe6245e510cca0ff Mon Sep 17 00:00:00 2001 From: John Tsiombikas Date: Fri, 16 Sep 2016 06:58:57 +0300 Subject: [PATCH] initial commit, first gear --- .gitignore | 4 + Makefile | 27 ++ src/gear.cc | 112 +++++ src/gear.h | 71 +++ src/geom.cc | 334 +++++++++++++ src/geom.h | 73 +++ src/main.cc | 146 ++++++ src/mesh.cc | 1438 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/mesh.h | 247 ++++++++++ src/meshgen.cc | 883 ++++++++++++++++++++++++++++++++++ src/meshgen.h | 23 + src/opengl.h | 6 + 12 files changed, 3364 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 src/gear.cc create mode 100644 src/gear.h create mode 100644 src/geom.cc create mode 100644 src/geom.h create mode 100644 src/main.cc create mode 100644 src/mesh.cc create mode 100644 src/mesh.h create mode 100644 src/meshgen.cc create mode 100644 src/meshgen.h create mode 100644 src/opengl.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fe1e9f6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.o +*.swp +*.d +anti diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8a5b897 --- /dev/null +++ b/Makefile @@ -0,0 +1,27 @@ +src = $(wildcard src/*.cc) +obj = $(src:.cc=.o) +dep = $(obj:.o=.d) +bin = anti + +CXXFLAGS = -std=c++11 -pedantic -Wall -g +LDFLAGS = $(libgl_$(sys)) -lm -lgmath + +sys = $(shell uname -s) +libgl_Linux = -lGL -lGLU -lglut -lGLEW +libgl_Darwin = -framework OpenGL -framework GLUT -lGLEW + +$(bin): $(obj) + $(CXX) -o $@ $(obj) $(LDFLAGS) + +-include $(dep) + +%.d: %.cc + @$(CPP) $(CXXFLAGS) $< -MM -MT $(@:.d=.o) >$@ + +.PHONY: clean +clean: + rm -f $(obj) $(bin) + +.PHONY: cleandep +cleandep: + rm -f $(dep) diff --git a/src/gear.cc b/src/gear.cc new file mode 100644 index 0000000..6450c65 --- /dev/null +++ b/src/gear.cc @@ -0,0 +1,112 @@ +#include +#include "gear.h" +#include "meshgen.h" + +Gear::Gear() + : axis(0, 0, 1) +{ + pdist = 0; + angle = 0; + nteeth = 42; + radius = 80; + teeth_length = 5; + thickness = 5; + bevel = 1.5; + + mesh = 0; +} + +Gear::~Gear() +{ + delete mesh; +} + +void Gear::draw() const +{ + if(!mesh) { + if(!((Gear*)this)->gen_mesh()) { + abort(); + } + } + calc_matrix(); + + glPushMatrix(); + glMultMatrixf(xform[0]); + + mesh->draw(); + + /* + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + glColor3f(0, 1, 0); + mesh->draw_normals(); + glPopAttrib(); + */ + + glPopMatrix(); +} + +static Vec2 rev_pos(float u, float v, void *cls) +{ + Gear *gear = (Gear*)cls; + + float y = ((v - 1.0 / 3.0) / (1.0 / 3.0) - 0.5); + if(y < -0.5) y = -0.5; + if(y > 0.5) y = 0.5; + y *= gear->thickness; + + if(v < 0.001 || v > 0.999) { + return Vec2(0, -y); + } + + float nt = (float)gear->nteeth * 4.0; + + int part = (int)(u * nt) % 4; /* 4 parts to a tooth /#\_ */ + float t = fmod(u * nt * 4.0, 1.0); + + float offs; + switch(part) { + case 0: + offs = t; + break; + case 1: + offs = 1.0f; + break; + case 2: + offs = 1.0f - t; + break; + case 3: + offs = 0.0f; + } + + float inner_rad = gear->radius - gear->teeth_length; + return Vec2(inner_rad + offs * gear->teeth_length, -y); +} + +bool Gear::gen_mesh() +{ + mesh = new Mesh; + gen_revol(mesh, nteeth * 4, 3, rev_pos, 0, this); + mesh->explode(); + mesh->calc_face_normals(); + + Mat4 rot; + rot.rotation_x(M_PI / 2.0); + mesh->apply_xform(rot, rot); + + mesh->set_vis_vecsize(6.0); + return true; +} + +void Gear::calc_matrix() const +{ + Vec3 up = Vec3(0, 1, 0); + if(1.0 - fabs(dot(up, axis)) < 1e-4) { + up = Vec3(0, 0, -1); + } + Vec3 right = normalize(cross(up, axis)); + up = cross(axis, right); + + xform = Mat4(right, up, axis); + xform.translate(pos); +} diff --git a/src/gear.h b/src/gear.h new file mode 100644 index 0000000..5fde21f --- /dev/null +++ b/src/gear.h @@ -0,0 +1,71 @@ +#ifndef GEAR_H_ +#define GEAR_H_ + +#include +#include +#include "mesh.h" + +/* distance unit: millimeters + * angle unit: radians + */ + +class Gear; +struct GearPin; +struct GearSlot; + +struct GearPin { + float radius; + float height; + + Gear *parent; + /* position in polar coordinates on the parent gear */ + float pos_dist, pos_angle; + + GearSlot *conn_slot; /* slot connection */ +}; + +struct GearSlot { + float radius, length; + + Gear *parent; + /* position in polar coordinates on the parent gear */ + float pos_dist_min, pos_dist_max, pos_angle; + + GearPin *conn_pin; /* pin connection */ +}; + +class Gear { +private: + Mesh *mesh; + + mutable Mat4 xform; + void calc_matrix() const; + + float contour(float u); + +public: + Vec3 pos, axis; /* implicitly defines a plane eqn. */ + float pdist; /* derived: distance of plane from origin */ + + float angle; /* current angle of the gear */ + + int nteeth; /* number of teeth */ + + float radius; /* total radius of the gear, including teeth */ + float teeth_length; /* how far teeth extend past the radius */ + float thickness; /* thickness of the gear along the Z axis */ + + float bevel; /* bevel size */ + + std::vector pins; + std::vector slots; + + Gear(); + ~Gear(); + + void draw() const; + + bool gen_mesh(); +}; + +#endif // GEAR_H_ diff --git a/src/geom.cc b/src/geom.cc new file mode 100644 index 0000000..23391a7 --- /dev/null +++ b/src/geom.cc @@ -0,0 +1,334 @@ +#include +#include +#include +#include "geom.h" + +GeomObject::~GeomObject() +{ +} + + +Sphere::Sphere() +{ + radius = 1.0; +} + +Sphere::Sphere(const Vec3 ¢, float radius) + : center(cent) +{ + this->radius = radius; +} + +void Sphere::set_union(const GeomObject *obj1, const GeomObject *obj2) +{ + const Sphere *sph1 = dynamic_cast(obj1); + const Sphere *sph2 = dynamic_cast(obj2); + + if(!sph1 || !sph2) { + fprintf(stderr, "Sphere::set_union: arguments must be spheres"); + return; + } + + float dist = length(sph1->center - sph2->center); + float surf_dist = dist - (sph1->radius + sph2->radius); + float d1 = sph1->radius + surf_dist / 2.0; + float d2 = sph2->radius + surf_dist / 2.0; + float t = d1 / (d1 + d2); + + if(t < 0.0) t = 0.0; + if(t > 1.0) t = 1.0; + + center = sph1->center * t + sph2->center * (1.0 - t); + radius = std::max(dist * t + sph2->radius, dist * (1.0f - t) + sph1->radius); +} + +void Sphere::set_intersection(const GeomObject *obj1, const GeomObject *obj2) +{ + fprintf(stderr, "Sphere::intersection undefined\n"); +} + +bool Sphere::intersect(const Ray &ray, HitPoint *hit) const +{ + float a = dot(ray.dir, ray.dir); + float b = 2.0 * ray.dir.x * (ray.origin.x - center.x) + + 2.0 * ray.dir.y * (ray.origin.y - center.y) + + 2.0 * ray.dir.z * (ray.origin.z - center.z); + float c = dot(ray.origin, ray.origin) + dot(center, center) - + 2.0 * dot(ray.origin, center) - radius * radius; + + float discr = b * b - 4.0 * a * c; + if(discr < 1e-4) { + return false; + } + + float sqrt_discr = sqrt(discr); + float t0 = (-b + sqrt_discr) / (2.0 * a); + float t1 = (-b - sqrt_discr) / (2.0 * a); + + if(t0 < 1e-4) + t0 = t1; + if(t1 < 1e-4) + t1 = t0; + + float t = t0 < t1 ? t0 : t1; + if(t < 1e-4) { + return false; + } + + // fill the HitPoint structure + if(hit) { + hit->obj = this; + hit->dist = t; + hit->pos = ray.origin + ray.dir * t; + hit->normal = (hit->pos - center) / radius; + } + return true; +} + + +AABox::AABox() +{ +} + +AABox::AABox(const Vec3 &vmin, const Vec3 &vmax) + : min(vmin), max(vmax) +{ +} + +void AABox::set_union(const GeomObject *obj1, const GeomObject *obj2) +{ + const AABox *box1 = dynamic_cast(obj1); + const AABox *box2 = dynamic_cast(obj2); + + if(!box1 || !box2) { + fprintf(stderr, "AABox::set_union: arguments must be AABoxes too\n"); + return; + } + + min.x = std::min(box1->min.x, box2->min.x); + min.y = std::min(box1->min.y, box2->min.y); + min.z = std::min(box1->min.z, box2->min.z); + + max.x = std::max(box1->max.x, box2->max.x); + max.y = std::max(box1->max.y, box2->max.y); + max.z = std::max(box1->max.z, box2->max.z); +} + +void AABox::set_intersection(const GeomObject *obj1, const GeomObject *obj2) +{ + const AABox *box1 = dynamic_cast(obj1); + const AABox *box2 = dynamic_cast(obj2); + + if(!box1 || !box2) { + fprintf(stderr, "AABox::set_intersection: arguments must be AABoxes too\n"); + return; + } + + for(int i=0; i<3; i++) { + min[i] = std::max(box1->min[i], box2->min[i]); + max[i] = std::min(box1->max[i], box2->max[i]); + + if(max[i] < min[i]) { + max[i] = min[i]; + } + } +} + +bool AABox::intersect(const Ray &ray, HitPoint *hit) const +{ + Vec3 param[2] = {min, max}; + Vec3 inv_dir(1.0 / ray.dir.x, 1.0 / ray.dir.y, 1.0 / ray.dir.z); + int sign[3] = {inv_dir.x < 0, inv_dir.y < 0, inv_dir.z < 0}; + + float tmin = (param[sign[0]].x - ray.origin.x) * inv_dir.x; + float tmax = (param[1 - sign[0]].x - ray.origin.x) * inv_dir.x; + float tymin = (param[sign[1]].y - ray.origin.y) * inv_dir.y; + float tymax = (param[1 - sign[1]].y - ray.origin.y) * inv_dir.y; + + if(tmin > tymax || tymin > tmax) { + return false; + } + if(tymin > tmin) { + tmin = tymin; + } + if(tymax < tmax) { + tmax = tymax; + } + + float tzmin = (param[sign[2]].z - ray.origin.z) * inv_dir.z; + float tzmax = (param[1 - sign[2]].z - ray.origin.z) * inv_dir.z; + + if(tmin > tzmax || tzmin > tmax) { + return false; + } + if(tzmin > tmin) { + tmin = tzmin; + } + if(tzmax < tmax) { + tmax = tzmax; + } + + float t = tmin < 1e-4 ? tmax : tmin; + if(t >= 1e-4) { + + if(hit) { + hit->obj = this; + hit->dist = t; + hit->pos = ray.origin + ray.dir * t; + + float min_dist = FLT_MAX; + Vec3 offs = min + (max - min) / 2.0; + Vec3 local_hit = hit->pos - offs; + + static const Vec3 axis[] = { + Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1) + }; + //int tcidx[][2] = {{2, 1}, {0, 2}, {0, 1}}; + + for(int i=0; i<3; i++) { + float dist = fabs((max[i] - offs[i]) - fabs(local_hit[i])); + if(dist < min_dist) { + min_dist = dist; + hit->normal = axis[i] * (local_hit[i] < 0.0 ? 1.0 : -1.0); + //hit->texcoord = Vec2(hit->pos[tcidx[i][0]], hit->pos[tcidx[i][1]]); + } + } + } + return true; + } + return false; + +} + +Plane::Plane() + : normal(0.0, 1.0, 0.0) +{ +} + +Plane::Plane(const Vec3 &p, const Vec3 &norm) + : pt(p) +{ + normal = normalize(norm); +} + +Plane::Plane(const Vec3 &p1, const Vec3 &p2, const Vec3 &p3) + : pt(p1) +{ + normal = normalize(cross(p2 - p1, p3 - p1)); +} + +Plane::Plane(const Vec3 &normal, float dist) +{ + this->normal = normalize(normal); + pt = this->normal * dist; +} + +void Plane::set_union(const GeomObject *obj1, const GeomObject *obj2) +{ + fprintf(stderr, "Plane::set_union undefined\n"); +} + +void Plane::set_intersection(const GeomObject *obj1, const GeomObject *obj2) +{ + fprintf(stderr, "Plane::set_intersection undefined\n"); +} + +bool Plane::intersect(const Ray &ray, HitPoint *hit) const +{ + float ndotdir = dot(normal, ray.dir); + if(fabs(ndotdir) < 1e-4) { + return false; + } + + if(hit) { + Vec3 ptdir = pt - ray.origin; + float t = dot(normal, ptdir) / ndotdir; + + hit->pos = ray.origin + ray.dir * t; + hit->normal = normal; + hit->obj = this; + } + return true; +} + +float sphere_distance(const Vec3 ¢, float rad, const Vec3 &pt) +{ + return length(pt - cent) - rad; +} + +// TODO version which takes both radii into account +float capsule_distance(const Vec3 &a, float ra, const Vec3 &b, float rb, const Vec3 &pt) +{ + Vec3 ab_dir = b - a; + float ab_len_sq = length_sq(ab_dir); + + if(fabs(ab_len_sq) < 1e-5) { + // if a == b, the capsule is a sphere with radius the maximum of the capsule radii + return sphere_distance(a, std::max(ra, rb), pt); + } + float ab_len = sqrt(ab_len_sq); + + Vec3 ap_dir = pt - a; + + float t = dot(ap_dir, ab_dir / ab_len) / ab_len; + if(t < 0.0) { + return sphere_distance(a, ra, pt); + } + if(t >= 1.0) { + return sphere_distance(b, rb, pt); + } + + Vec3 pproj = a + ab_dir * t; + return length(pproj - pt) - ra; +} + +#if 0 +float capsule_distance(const Vec3 &a, float ra, const Vec3 &b, float rb, const Vec3 &pt) +{ + Vec3 ab_dir = b - a; + + if(fabs(length_sq(ab_dir)) < 1e-5) { + // if a == b, the capsule is a sphere with radius the maximum of the capsule radii + return sphere_distance(a, std::max(ra, rb), pt); + } + float ab_len = length(ab_dir); + + Vec3 ap_dir = pt - a; + Vec3 rotaxis = normalize(cross(ab_dir, ap_dir)); + + Mat4 rmat; + rmat.set_rotation(rotaxis, M_PI / 2.0); + Vec3 right = rmat * ab_dir / ab_len; + + // XXX I think this check is redundant, always false, due to the cross product order + //assert(dot(right, ab_dir) >= 0.0); + if(dot(right, ab_dir) < 0.0) { + right = -right; + } + Vec3 aa = a + right * ra; + Vec3 bb = b + right * rb; + + // project pt to the line segment bb-aa, see if the projection lies within the interval [0, 1) + Vec3 aabb_dir = bb - aa; + float aabb_len = length(aabb_dir); + Vec3 aap_dir = pt - aa; + + float t = dot(aap_dir, aabb_dir / aabb_len) / aabb_len; + if(t < 0.0) { + return sphere_distance(a, ra, pt); + } + if(t >= 1.0) { + return sphere_distance(b, rb, pt); + } + + Vec3 ppt = aa + aabb_dir * t; + Vec3 norm = ppt - pt; + float dist = length(norm); + + if(dot(norm, right) < 0.0) { + // inside the cone + dist = -dist; + } + return dist; +} +#endif diff --git a/src/geom.h b/src/geom.h new file mode 100644 index 0000000..aabf266 --- /dev/null +++ b/src/geom.h @@ -0,0 +1,73 @@ +#ifndef GEOMOBJ_H_ +#define GEOMOBJ_H_ + +#include "gmath/gmath.h" + +class GeomObject; +class SceneNode; + +struct HitPoint { + float dist; //< parametric distance along the ray + Vec3 pos; //< position of intersection (orig + dir * dist) + Vec3 normal; //< normal at the point of intersection + const void *obj; //< pointer to the intersected object + const SceneNode *node; + Ray ray; +}; + +class GeomObject { +public: + virtual ~GeomObject(); + + virtual void set_union(const GeomObject *obj1, const GeomObject *obj2) = 0; + virtual void set_intersection(const GeomObject *obj1, const GeomObject *obj2) = 0; + + virtual bool intersect(const Ray &ray, HitPoint *hit = 0) const = 0; +}; + +class Sphere : public GeomObject { +public: + Vec3 center; + float radius; + + Sphere(); + Sphere(const Vec3 ¢er, float radius); + + void set_union(const GeomObject *obj1, const GeomObject *obj2); + void set_intersection(const GeomObject *obj1, const GeomObject *obj2); + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + +class AABox : public GeomObject { +public: + Vec3 min, max; + + AABox(); + AABox(const Vec3 &min, const Vec3 &max); + + void set_union(const GeomObject *obj1, const GeomObject *obj2); + void set_intersection(const GeomObject *obj1, const GeomObject *obj2); + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + +class Plane : public GeomObject { +public: + Vec3 pt, normal; + + Plane(); + Plane(const Vec3 &pt, const Vec3 &normal); + Plane(const Vec3 &p1, const Vec3 &p2, const Vec3 &p3); + Plane(const Vec3 &normal, float dist); + + void set_union(const GeomObject *obj1, const GeomObject *obj2); + void set_intersection(const GeomObject *obj1, const GeomObject *obj2); + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + +float sphere_distance(const Vec3 ¢, float rad, const Vec3 &pt); +float capsule_distance(const Vec3 &a, float ra, const Vec3 &b, float rb, const Vec3 &pt); + +#endif // GEOMOBJ_H_ diff --git a/src/main.cc b/src/main.cc new file mode 100644 index 0000000..c4696f6 --- /dev/null +++ b/src/main.cc @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#else +#include +#endif +#include "gear.h" + +bool init(); +void cleanup(); +void display(); +void draw_gears(); +void reshape(int x, int y); +void keyb(unsigned char key, int x, int y); +void mouse(int bn, int st, int x, int y); +void motion(int x, int y); + +static float cam_dist = 2; +static float cam_theta, cam_phi; +static int prev_mx, prev_my; +static bool bnstate[8]; + +static Gear *test_gear; + +int main(int argc, char **argv) +{ + glutInit(&argc, argv); + glutInitWindowSize(1024, 768); + glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); + glutCreateWindow("Antikythera"); + + glutDisplayFunc(display); + glutReshapeFunc(reshape); + glutKeyboardFunc(keyb); + glutMouseFunc(mouse); + glutMotionFunc(motion); + + if(!init()) { + return 1; + } + atexit(cleanup); + + glutMainLoop(); + return 0; +} + +bool init() +{ + glewInit(); + + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + glEnable(GL_NORMALIZE); + + Mesh::use_custom_sdr_attr = false; + + test_gear = new Gear; + test_gear->gen_mesh(); + + return true; +} + +void cleanup() +{ + delete test_gear; +} + +void display() +{ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -cam_dist); + glRotatef(cam_phi, 1, 0, 0); + glRotatef(cam_theta, 0, 1, 0); + + draw_gears(); + + glutSwapBuffers(); + assert(glGetError() == GL_NO_ERROR); +} + +void draw_gears() +{ + /* world scale is in meters, gears are in millimeters, sclae by 1/1000 */ + glPushMatrix(); + glScalef(0.001, 0.001, 0.001); + + test_gear->draw(); + + glPopMatrix(); +} + +void reshape(int x, int y) +{ + glViewport(0, 0, x, y); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + gluPerspective(50.0, (float)x / (float)y, 0.05, 100.0); +} + +void keyb(unsigned char key, int x, int y) +{ + switch(key) { + case 27: + exit(0); + } +} + +void mouse(int bn, int st, int x, int y) +{ + prev_mx = x; + prev_my = y; + bnstate[bn - GLUT_LEFT_BUTTON] = st == GLUT_DOWN; +} + +void motion(int x, int y) +{ + int dx = x - prev_mx; + int dy = y - prev_my; + prev_mx = x; + prev_my = y; + + if(!dx && !dy) return; + + if(bnstate[0]) { + cam_theta += dx * 0.5; + cam_phi += dy * 0.5; + + if(cam_phi < -90) cam_phi = -90; + if(cam_phi > 90) cam_phi = 90; + glutPostRedisplay(); + } + if(bnstate[2]) { + cam_dist += dy * 0.05; + if(cam_dist < 0.0) cam_dist = 0.0; + glutPostRedisplay(); + } +} diff --git a/src/mesh.cc b/src/mesh.cc new file mode 100644 index 0000000..ed4fd98 --- /dev/null +++ b/src/mesh.cc @@ -0,0 +1,1438 @@ +#include +#include +#include +#include +#include "opengl.h" +#include "mesh.h" +//#include "xform_node.h" + +#define USE_OLDGL + +bool Mesh::use_custom_sdr_attr = true; +int Mesh::global_sdr_loc[NUM_MESH_ATTR] = { 0, 1, 2, 3, 4, 5, 6 }; +/* + (int)SDR_ATTR_VERTEX, + (int)SDR_ATTR_NORMAL, + (int)SDR_ATTR_TANGENT, + (int)SDR_ATTR_TEXCOORD, + (int)SDR_ATTR_COLOR, + -1, -1}; +*/ +unsigned int Mesh::intersect_mode = ISECT_DEFAULT; +float Mesh::vertex_sel_dist = 0.01; +float Mesh::vis_vecsize = 1.0; + +Mesh::Mesh() +{ + clear(); + + glGenBuffers(NUM_MESH_ATTR + 1, buffer_objects); + + for(int i=0; iname = name; +} + +const char *Mesh::get_name() const +{ + return name.c_str(); +} + +bool Mesh::has_attrib(int attr) const +{ + if(attr < 0 || attr >= NUM_MESH_ATTR) { + return false; + } + + // if neither of these is valid, then nobody has set this attribute + return vattr[attr].vbo_valid || vattr[attr].data_valid; +} + +bool Mesh::is_indexed() const +{ + return ibo_valid || idata_valid; +} + +void Mesh::clear() +{ + //bones.clear(); + + for(int i=0; i= NUM_MESH_ATTR) { + fprintf(stderr, "%s: invalid attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + if(nverts && num != nverts) { + fprintf(stderr, "%s: attribute count missmatch (%d instead of %d)\n", __FUNCTION__, num, nverts); + return 0; + } + nverts = num; + + vattr[attrib].data.clear(); + vattr[attrib].nelem = nelem; + vattr[attrib].data.resize(num * nelem); + + if(data) { + memcpy(&vattr[attrib].data[0], data, num * nelem * sizeof *data); + } + + vattr[attrib].data_valid = true; + vattr[attrib].vbo_valid = false; + return &vattr[attrib].data[0]; +} + +float *Mesh::get_attrib_data(int attrib) +{ + if(attrib < 0 || attrib >= NUM_MESH_ATTR) { + fprintf(stderr, "%s: invalid attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + vattr[attrib].vbo_valid = false; + return (float*)((const Mesh*)this)->get_attrib_data(attrib); +} + +const float *Mesh::get_attrib_data(int attrib) const +{ + if(attrib < 0 || attrib >= NUM_MESH_ATTR) { + fprintf(stderr, "%s: invalid attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + if(!vattr[attrib].data_valid) { +#if GL_ES_VERSION_2_0 + fprintf(stderr, "%s: can't read back attrib data on CrippledGL ES\n", __FUNCTION__); + return 0; +#else + if(!vattr[attrib].vbo_valid) { + fprintf(stderr, "%s: unavailable attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + // local data copy is unavailable, grab the data from the vbo + Mesh *m = (Mesh*)this; + m->vattr[attrib].data.resize(nverts * vattr[attrib].nelem); + + glBindBuffer(GL_ARRAY_BUFFER, vattr[attrib].vbo); + void *data = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY); + memcpy(&m->vattr[attrib].data[0], data, nverts * vattr[attrib].nelem * sizeof(float)); + glUnmapBuffer(GL_ARRAY_BUFFER); + + vattr[attrib].data_valid = true; +#endif + } + + return &vattr[attrib].data[0]; +} + +void Mesh::set_attrib(int attrib, int idx, const Vec4 &v) +{ + float *data = get_attrib_data(attrib); + if(data) { + data += idx * vattr[attrib].nelem; + for(int i=0; iget_index_data(); +} + +const unsigned int *Mesh::get_index_data() const +{ + if(!idata_valid) { +#if GL_ES_VERSION_2_0 + fprintf(stderr, "%s: can't read back index data in CrippledGL ES\n", __FUNCTION__); + return 0; +#else + if(!ibo_valid) { + fprintf(stderr, "%s: indices unavailable\n", __FUNCTION__); + return 0; + } + + // local data copy is unavailable, gram the data from the ibo + Mesh *m = (Mesh*)this; + int nidx = nfaces * 3; + m->idata.resize(nidx); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); + void *data = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY); + memcpy(&m->idata[0], data, nidx * sizeof(unsigned int)); + glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + + idata_valid = true; +#endif + } + + return &idata[0]; +} + +int Mesh::get_index_count() const +{ + return nfaces * 3; +} + +void Mesh::append(const Mesh &mesh) +{ + unsigned int idxoffs = nverts; + + if(!nverts) { + clone(mesh); + return; + } + + nverts += mesh.nverts; + nfaces += mesh.nfaces; + + for(int i=0; i= NUM_MESH_ATTR) { + return; + } + Mesh::global_sdr_loc[attr] = loc; +} + +/// static function +int Mesh::get_attrib_location(int attr) +{ + if(attr < 0 || attr >= NUM_MESH_ATTR) { + return -1; + } + return Mesh::global_sdr_loc[attr]; +} + +/// static function +void Mesh::clear_attrib_locations() +{ + for(int i=0; i= (int)bones.size()) { + return 0; + } + return bones[idx]; +} + +int Mesh::get_bones_count() const +{ + return (int)bones.size(); +} +*/ + +bool Mesh::pre_draw() const +{ + cur_sdr = 0; + glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr); + + ((Mesh*)this)->update_buffers(); + + if(!vattr[MESH_ATTR_VERTEX].vbo_valid) { + fprintf(stderr, "%s: invalid vertex buffer\n", __FUNCTION__); + return false; + } + + if(cur_sdr && use_custom_sdr_attr) { + // rendering with shaders + if(global_sdr_loc[MESH_ATTR_VERTEX] == -1) { + fprintf(stderr, "%s: shader attribute location for vertices unset\n", __FUNCTION__); + return false; + } + + for(int i=0; i= 0 && vattr[i].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[i].vbo); + glVertexAttribPointer(loc, vattr[i].nelem, GL_FLOAT, GL_FALSE, 0, 0); + glEnableVertexAttribArray(loc); + } + } + } else { +#ifndef GL_ES_VERSION_2_0 + // rendering with fixed-function (not available in GLES2) + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_VERTEX].vbo); + glVertexPointer(vattr[MESH_ATTR_VERTEX].nelem, GL_FLOAT, 0, 0); + glEnableClientState(GL_VERTEX_ARRAY); + + if(vattr[MESH_ATTR_NORMAL].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_NORMAL].vbo); + glNormalPointer(GL_FLOAT, 0, 0); + glEnableClientState(GL_NORMAL_ARRAY); + } + if(vattr[MESH_ATTR_TEXCOORD].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_TEXCOORD].vbo); + glTexCoordPointer(vattr[MESH_ATTR_TEXCOORD].nelem, GL_FLOAT, 0, 0); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + } + if(vattr[MESH_ATTR_COLOR].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_COLOR].vbo); + glColorPointer(vattr[MESH_ATTR_COLOR].nelem, GL_FLOAT, 0, 0); + glEnableClientState(GL_COLOR_ARRAY); + } +#endif + } + glBindBuffer(GL_ARRAY_BUFFER, 0); + + return true; +} + +void Mesh::draw() const +{ + if(!pre_draw()) return; + + if(ibo_valid) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); + glDrawElements(GL_TRIANGLES, nfaces * 3, GL_UNSIGNED_INT, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } else { + glDrawArrays(GL_TRIANGLES, 0, nverts); + } + + post_draw(); +} + +void Mesh::post_draw() const +{ + if(cur_sdr && use_custom_sdr_attr) { + // rendered with shaders + for(int i=0; i= 0 && vattr[i].vbo_valid) { + glDisableVertexAttribArray(loc); + } + } + } else { +#ifndef GL_ES_VERSION_2_0 + // rendered with fixed-function + glDisableClientState(GL_VERTEX_ARRAY); + if(vattr[MESH_ATTR_NORMAL].vbo_valid) { + glDisableClientState(GL_NORMAL_ARRAY); + } + if(vattr[MESH_ATTR_TEXCOORD].vbo_valid) { + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + } + if(vattr[MESH_ATTR_COLOR].vbo_valid) { + glDisableClientState(GL_COLOR_ARRAY); + } +#endif + } +} + +void Mesh::draw_wire() const +{ + if(!pre_draw()) return; + + ((Mesh*)this)->update_wire_ibo(); + + int num_faces = get_poly_count(); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, wire_ibo); + glDrawElements(GL_LINES, num_faces * 6, GL_UNSIGNED_INT, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + post_draw(); +} + +void Mesh::draw_vertices() const +{ + if(!pre_draw()) return; + + glDrawArrays(GL_POINTS, 0, nverts); + + post_draw(); +} + +void Mesh::draw_normals() const +{ +#ifdef USE_OLDGL + int cur_sdr = 0; + glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr); + + Vec3 *varr = (Vec3*)get_attrib_data(MESH_ATTR_VERTEX); + Vec3 *norm = (Vec3*)get_attrib_data(MESH_ATTR_NORMAL); + if(!varr || !norm) { + return; + } + + glBegin(GL_LINES); + if(cur_sdr && use_custom_sdr_attr) { + int vert_loc = global_sdr_loc[MESH_ATTR_VERTEX]; + if(vert_loc < 0) { + glEnd(); + return; + } + + for(size_t i=0; icalc_aabb(); + } + *vmin = aabb.min; + *vmax = aabb.max; +} + +const AABox &Mesh::get_aabbox() const +{ + if(!aabb_valid) { + ((Mesh*)this)->calc_aabb(); + } + return aabb; +} + +float Mesh::get_bsphere(Vec3 *center, float *rad) const +{ + if(!bsph_valid) { + ((Mesh*)this)->calc_bsph(); + } + *center = bsph.center; + *rad = bsph.radius; + return bsph.radius; +} + +const Sphere &Mesh::get_bsphere() const +{ + if(!bsph_valid) { + ((Mesh*)this)->calc_bsph(); + } + return bsph; +} + +/// static function +void Mesh::set_intersect_mode(unsigned int mode) +{ + Mesh::intersect_mode = mode; +} + +/// static function +unsigned int Mesh::get_intersect_mode() +{ + return Mesh::intersect_mode; +} + +/// static function +void Mesh::set_vertex_select_distance(float dist) +{ + Mesh::vertex_sel_dist = dist; +} + +/// static function +float Mesh::get_vertex_select_distance() +{ + return Mesh::vertex_sel_dist; +} + +bool Mesh::intersect(const Ray &ray, HitPoint *hit) const +{ + assert((Mesh::intersect_mode & (ISECT_VERTICES | ISECT_FACE)) != (ISECT_VERTICES | ISECT_FACE)); + + const Vec3 *varr = (Vec3*)get_attrib_data(MESH_ATTR_VERTEX); + const Vec3 *narr = (Vec3*)get_attrib_data(MESH_ATTR_NORMAL); + if(!varr) { + return false; + } + const unsigned int *idxarr = get_index_data(); + + // first test with the bounding box + AABox box; + get_aabbox(&box.min, &box.max); + if(!box.intersect(ray)) { + return false; + } + + HitPoint nearest_hit; + nearest_hit.dist = FLT_MAX; + nearest_hit.obj = 0; + + if(Mesh::intersect_mode & ISECT_VERTICES) { + // we asked for "intersections" with the vertices of the mesh + long nearest_vidx = -1; + float thres_sq = Mesh::vertex_sel_dist * Mesh::vertex_sel_dist; + + for(unsigned int i=0; i 0) { + continue; + } + + // project the vertex onto the ray line + float t = dot(varr[i] - ray.origin, ray.dir); + Vec3 vproj = ray.origin + ray.dir * t; + + float dist_sq = length_sq(vproj - varr[i]); + if(dist_sq < thres_sq) { + if(!hit) { + return true; + } + if(t < nearest_hit.dist) { + nearest_hit.dist = t; + nearest_vidx = i; + } + } + } + + if(nearest_vidx != -1) { + hitvert = varr[nearest_vidx]; + nearest_hit.obj = &hitvert; + } + + } else { + // regular intersection test with polygons + + for(unsigned int i=0; i 0) { + continue; + } + + HitPoint fhit; + if(face.intersect(ray, hit ? &fhit : 0)) { + if(!hit) { + return true; + } + if(fhit.dist < nearest_hit.dist) { + nearest_hit = fhit; + hitface = face; + } + } + } + } + + if(nearest_hit.obj) { + if(hit) { + *hit = nearest_hit; + + // if we are interested in the mesh and not the faces set obj to this + if(Mesh::intersect_mode & ISECT_FACE) { + hit->obj = &hitface; + } else if(Mesh::intersect_mode & ISECT_VERTICES) { + hit->obj = &hitvert; + } else { + hit->obj = this; + } + } + return true; + } + return false; +} + + +// texture coordinate manipulation +void Mesh::texcoord_apply_xform(const Mat4 &xform) +{ + if(!has_attrib(MESH_ATTR_TEXCOORD)) { + return; + } + + for(unsigned int i=0; i abs_ny && abs_nx > abs_nz ? 0 : (abs_ny > abs_nz ? 1 : 2); + + float uv[2], *uvptr = uv; + for(int j=0; j<3; j++) { + if(j == dom) continue; // skip dominant axis + + *uvptr++ = pos[j]; + } + set_attrib(MESH_ATTR_TEXCOORD, i, Vec4(uv[0], uv[1], 0, 1)); + } +} + +void Mesh::texcoord_gen_cylinder() +{ + if(!nverts) return; + + if(!has_attrib(MESH_ATTR_TEXCOORD)) { + // allocate texture coordinate attribute array + set_attrib_data(MESH_ATTR_TEXCOORD, 2, nverts); + } + + for(unsigned int i=0; iget_attrib_data(MESH_ATTR_VERTEX)) { + return; + } + + aabb.min = Vec3(FLT_MAX, FLT_MAX, FLT_MAX); + aabb.max = -aabb.min; + + for(unsigned int i=0; i aabb.max[j]) { + aabb.max[j] = v[j]; + } + } + } + aabb_valid = true; +} + +void Mesh::calc_bsph() +{ + // the cast is to force calling the const version which doesn't invalidate + if(!((const Mesh*)this)->get_attrib_data(MESH_ATTR_VERTEX)) { + return; + } + + Vec3 v; + bsph.center = Vec3(0, 0, 0); + + // first find the center + for(unsigned int i=0; i bsph.radius) { + bsph.radius = dist_sq; + } + } + bsph.radius = sqrt(bsph.radius); + + bsph_valid = true; +} + +void Mesh::update_buffers() +{ + for(int i=0; iget_index_data(); + + for(int i=0; icalc_normal(); + } + return normal; +} + +void Triangle::transform(const Mat4 &xform) +{ + v[0] = xform * v[0]; + v[1] = xform * v[1]; + v[2] = xform * v[2]; + normal_valid = false; +} + +void Triangle::draw() const +{ + Vec3 n[3]; + n[0] = n[1] = n[2] = get_normal(); + + int vloc = Mesh::get_attrib_location(MESH_ATTR_VERTEX); + int nloc = Mesh::get_attrib_location(MESH_ATTR_NORMAL); + + glEnableVertexAttribArray(vloc); + glVertexAttribPointer(vloc, 3, GL_FLOAT, GL_FALSE, 0, &v[0].x); + glVertexAttribPointer(nloc, 3, GL_FLOAT, GL_FALSE, 0, &n[0].x); + + glDrawArrays(GL_TRIANGLES, 0, 3); + + glDisableVertexAttribArray(vloc); + glDisableVertexAttribArray(nloc); +} + +void Triangle::draw_wire() const +{ + static const int idxarr[] = {0, 1, 1, 2, 2, 0}; + int vloc = Mesh::get_attrib_location(MESH_ATTR_VERTEX); + + glEnableVertexAttribArray(vloc); + glVertexAttribPointer(vloc, 3, GL_FLOAT, GL_FALSE, 0, &v[0].x); + + glDrawElements(GL_LINES, 6, GL_UNSIGNED_INT, idxarr); + + glDisableVertexAttribArray(vloc); +} + +Vec3 Triangle::calc_barycentric(const Vec3 &pos) const +{ + Vec3 norm = get_normal(); + + float area_sq = fabs(dot(cross(v[1] - v[0], v[2] - v[0]), norm)); + if(area_sq < 1e-5) { + return Vec3(0, 0, 0); + } + + float asq0 = fabs(dot(cross(v[1] - pos, v[2] - pos), norm)); + float asq1 = fabs(dot(cross(v[2] - pos, v[0] - pos), norm)); + float asq2 = fabs(dot(cross(v[0] - pos, v[1] - pos), norm)); + + return Vec3(asq0 / area_sq, asq1 / area_sq, asq2 / area_sq); +} + +bool Triangle::intersect(const Ray &ray, HitPoint *hit) const +{ + Vec3 normal = get_normal(); + + float ndotdir = dot(ray.dir, normal); + if(fabs(ndotdir) < 1e-4) { + return false; + } + + Vec3 vertdir = v[0] - ray.origin; + float t = dot(normal, vertdir) / ndotdir; + + Vec3 pos = ray.origin + ray.dir * t; + Vec3 bary = calc_barycentric(pos); + + if(bary.x + bary.y + bary.z > 1.00001) { + return false; + } + + if(hit) { + hit->dist = t; + hit->pos = ray.origin + ray.dir * t; + hit->normal = normal; + hit->obj = this; + } + return true; +} diff --git a/src/mesh.h b/src/mesh.h new file mode 100644 index 0000000..50a0d61 --- /dev/null +++ b/src/mesh.h @@ -0,0 +1,247 @@ +#ifndef MESH_H_ +#define MESH_H_ + +#include +#include +#include +#include "gmath/gmath.h" +#include "geom.h" + +enum { + MESH_ATTR_VERTEX, + MESH_ATTR_NORMAL, + MESH_ATTR_TANGENT, + MESH_ATTR_TEXCOORD, + MESH_ATTR_COLOR, + MESH_ATTR_BONEWEIGHTS, + MESH_ATTR_BONEIDX, + + NUM_MESH_ATTR +}; + +// intersection mode flags +enum { + ISECT_DEFAULT = 0, // default (whole mesh, all intersections) + ISECT_FRONT = 1, // front-faces only + ISECT_FACE = 2, // return intersected face pointer instead of mesh + ISECT_VERTICES = 4 // return (?) TODO +}; + +//class XFormNode; + + +class Triangle { +public: + Vec3 v[3]; + Vec3 normal; + bool normal_valid; + int id; + + Triangle(); + Triangle(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2); + Triangle(int n, const Vec3 *varr, const unsigned int *idxarr = 0); + + /// calculate normal (quite expensive) + void calc_normal(); + const Vec3 &get_normal() const; + + void transform(const Mat4 &xform); + + void draw() const; + void draw_wire() const; + + /// calculate barycentric coordinates of a point + Vec3 calc_barycentric(const Vec3 &pos) const; + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + + +class Mesh { +private: + std::string name; + unsigned int nverts, nfaces; + + // current value for each attribute for the immedate mode + // interface. + Vec4 cur_val[NUM_MESH_ATTR]; + + unsigned int buffer_objects[NUM_MESH_ATTR + 1]; + + // vertex attribute data and buffer objects + struct VertexAttrib { + int nelem; // number of elements per attribute range: [1, 4] + std::vector data; + unsigned int vbo; + mutable bool vbo_valid; // if this is false, the vbo needs updating from the data + mutable bool data_valid; // if this is false, the data needs to be pulled from the vbo + //int sdr_loc; + } vattr[NUM_MESH_ATTR]; + + static int global_sdr_loc[NUM_MESH_ATTR]; + + //std::vector bones; // bones affecting this mesh + + // index data and buffer object + std::vector idata; + unsigned int ibo; + mutable bool ibo_valid; + mutable bool idata_valid; + + // index buffer object for wireframe rendering (constructed on demand) + unsigned int wire_ibo; + mutable bool wire_ibo_valid; + + // axis-aligned bounding box + mutable AABox aabb; + mutable bool aabb_valid; + + // bounding sphere + mutable Sphere bsph; + mutable bool bsph_valid; + + // keeps the last intersected face + mutable Triangle hitface; + // keeps the last intersected vertex position + mutable Vec3 hitvert; + + void calc_aabb(); + void calc_bsph(); + + static unsigned int intersect_mode; + static float vertex_sel_dist; + + static float vis_vecsize; + + /// update the VBOs after data has changed (invalid vbo/ibo) + void update_buffers(); + /// construct/update the wireframe index buffer (called from draw_wire). + void update_wire_ibo(); + + mutable int cur_sdr; + bool pre_draw() const; + void post_draw() const; + + +public: + static bool use_custom_sdr_attr; + + Mesh(); + ~Mesh(); + + Mesh(const Mesh &rhs); + Mesh &operator =(const Mesh &rhs); + bool clone(const Mesh &m); + + void set_name(const char *name); + const char *get_name() const; + + bool has_attrib(int attr) const; + bool is_indexed() const; + + // clears everything about this mesh, and returns to the newly constructed state + void clear(); + + // access the vertex attribute data + // if vdata == 0, space is just allocated + float *set_attrib_data(int attrib, int nelem, unsigned int num, const float *vdata = 0); // invalidates vbo + float *get_attrib_data(int attrib); // invalidates vbo + const float *get_attrib_data(int attrib) const; + + // simple access to any particular attribute + void set_attrib(int attrib, int idx, const Vec4 &v); // invalidates vbo + Vec4 get_attrib(int attrib, int idx) const; + + int get_attrib_count(int attrib) const; + + // ... same for index data + unsigned int *set_index_data(int num, const unsigned int *indices = 0); // invalidates ibo + unsigned int *get_index_data(); // invalidates ibo + const unsigned int *get_index_data() const; + + int get_index_count() const; + + void append(const Mesh &mesh); + + // immediate-mode style mesh construction interface + void vertex(float x, float y, float z); + void normal(float nx, float ny, float nz); + void tangent(float tx, float ty, float tz); + void texcoord(float u, float v, float w); + void boneweights(float w1, float w2, float w3, float w4); + void boneidx(int idx1, int idx2, int idx3, int idx4); + + int get_poly_count() const; + + /* apply a transformation to the vertices and its inverse-transpose + * to the normals and tangents. + */ + void apply_xform(const Mat4 &xform); + void apply_xform(const Mat4 &xform, const Mat4 &dir_xform); + + void flip(); // both faces and normals + void flip_faces(); + void flip_normals(); + + void explode(); // undo all vertex sharing + + void calc_face_normals(); // this is only guaranteed to work on an exploded mesh + + // adds a bone and returns its index + /*int add_bone(XFormNode *bone); + const XFormNode *get_bone(int idx) const; + int get_bones_count() const;*/ + + // access the shader attribute locations + static void set_attrib_location(int attr, int loc); + static int get_attrib_location(int attr); + static void clear_attrib_locations(); + + static void set_vis_vecsize(float sz); + static float get_vis_vecsize(); + + void draw() const; + void draw_wire() const; + void draw_vertices() const; + void draw_normals() const; + void draw_tangents() const; + + /** get the bounding box in local space. The result will be cached, and subsequent + * calls will return the same box. The cache gets invalidated by any functions that can affect + * the vertex data (non-const variant of get_attrib_data(MESH_ATTR_VERTEX, ...) included). + * @{ */ + void get_aabbox(Vec3 *vmin, Vec3 *vmax) const; + const AABox &get_aabbox() const; + /// @} + + /** get the bounding sphere in local space. The result will be cached, and subsequent + * calls will return the same box. The cache gets invalidated by any functions that can affect + * the vertex data (non-const variant of get_attrib_data(MESH_ATTR_VERTEX, ...) included). + * @{ */ + float get_bsphere(Vec3 *center, float *rad) const; + const Sphere &get_bsphere() const; + + static void set_intersect_mode(unsigned int mode); + static unsigned int get_intersect_mode(); + static void set_vertex_select_distance(float dist); + static float get_vertex_select_distance(); + + /** Find the intersection between the mesh and a ray. + * XXX Brute force at the moment, not intended to be used for anything other than picking in tools. + * If you intend to use it in a speed-critical part of the code, you'll *have* to optimize it! + */ + bool intersect(const Ray &ray, HitPoint *hit = 0) const; + + // texture coordinate manipulation + void texcoord_apply_xform(const Mat4 &xform); + void texcoord_gen_plane(const Vec3 &norm, const Vec3 &tang); + void texcoord_gen_box(); + void texcoord_gen_cylinder(); + + bool dump(const char *fname) const; + bool dump(FILE *fp) const; + bool dump_obj(const char *fname) const; + bool dump_obj(FILE *fp) const; +}; + +#endif // MESH_H_ diff --git a/src/meshgen.cc b/src/meshgen.cc new file mode 100644 index 0000000..7664aea --- /dev/null +++ b/src/meshgen.cc @@ -0,0 +1,883 @@ +#include +#include "meshgen.h" +#include "mesh.h" + +// -------- sphere -------- + +#define SURAD(u) ((u) * 2.0 * M_PI) +#define SVRAD(v) ((v) * M_PI) + +static Vec3 sphvec(float theta, float phi) +{ + return Vec3(sin(theta) * sin(phi), + cos(phi), + cos(theta) * sin(phi)); +} + +void gen_sphere(Mesh *mesh, float rad, int usub, int vsub, float urange, float vrange) +{ + if(urange == 0.0 || vrange == 0.0) return; + + if(usub < 4) usub = 4; + if(vsub < 2) vsub = 2; + + int uverts = usub + 1; + int vverts = vsub + 1; + + int num_verts = uverts * vverts; + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + mesh->clear(); + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; i *verts, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, int iter) +{ + if(!iter) { + verts->push_back(v1); + verts->push_back(v2); + verts->push_back(v3); + return; + } + + Vec3 v12 = normalize(v1 + v2); + Vec3 v23 = normalize(v2 + v3); + Vec3 v31 = normalize(v3 + v1); + + geosphere(verts, v1, v12, v31, iter - 1); + geosphere(verts, v2, v23, v12, iter - 1); + geosphere(verts, v3, v31, v23, iter - 1); + geosphere(verts, v12, v23, v31, iter - 1); +} + +void gen_geosphere(Mesh *mesh, float rad, int subdiv, bool hemi) +{ + int num_tri = (sizeof icosa_idx / sizeof *icosa_idx) / 3; + + std::vector verts; + for(int i=0; iclear(); + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + + for(int i=0; iclear(); + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; iclear(); + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; iclear(); + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; iclear(); + + int uverts = usub + 1; + int vverts = vsub + 1; + int num_verts = uverts * vverts; + + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = 1.0 / (float)usub; + float dv = 1.0 / (float)vsub; + + float u = 0.0; + for(int i=0; iclear(); + + for(int i=0; i<6; i++) { + Mat4 xform, dir_xform; + Mesh m; + + gen_plane(&m, 1, 1, usub, vsub); + xform.translate(Vec3(0, 0, 0.5)); + xform.rotate(Vec3(face_angles[i][1], face_angles[i][0], 0)); + dir_xform = xform; + m.apply_xform(xform, dir_xform); + + mesh->append(m); + } + + Mat4 scale; + scale.scaling(xsz, ysz, zsz); + mesh->apply_xform(scale, Mat4::identity); +} + +/* +void gen_box(Mesh *mesh, float xsz, float ysz, float zsz) +{ + mesh->clear(); + + const int num_faces = 6; + int num_verts = num_faces * 4; + int num_tri = num_faces * 2; + + float x = xsz / 2.0; + float y = ysz / 2.0; + float z = zsz / 2.0; + + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + static const Vec2 uv[] = { Vec2(0, 0), Vec2(1, 0), Vec2(1, 1), Vec2(0, 1) }; + + // front + for(int i=0; i<4; i++) { + *narr++ = Vec3(0, 0, 1); + *tarr++ = Vec3(1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vec3(-x, -y, z); + *varr++ = Vec3(x, -y, z); + *varr++ = Vec3(x, y, z); + *varr++ = Vec3(-x, y, z); + // right + for(int i=0; i<4; i++) { + *narr++ = Vec3(1, 0, 0); + *tarr++ = Vec3(0, 0, -1); + *uvarr++ = uv[i]; + } + *varr++ = Vec3(x, -y, z); + *varr++ = Vec3(x, -y, -z); + *varr++ = Vec3(x, y, -z); + *varr++ = Vec3(x, y, z); + // back + for(int i=0; i<4; i++) { + *narr++ = Vec3(0, 0, -1); + *tarr++ = Vec3(-1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vec3(x, -y, -z); + *varr++ = Vec3(-x, -y, -z); + *varr++ = Vec3(-x, y, -z); + *varr++ = Vec3(x, y, -z); + // left + for(int i=0; i<4; i++) { + *narr++ = Vec3(-1, 0, 0); + *tarr++ = Vec3(0, 0, 1); + *uvarr++ = uv[i]; + } + *varr++ = Vec3(-x, -y, -z); + *varr++ = Vec3(-x, -y, z); + *varr++ = Vec3(-x, y, z); + *varr++ = Vec3(-x, y, -z); + // top + for(int i=0; i<4; i++) { + *narr++ = Vec3(0, 1, 0); + *tarr++ = Vec3(1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vec3(-x, y, z); + *varr++ = Vec3(x, y, z); + *varr++ = Vec3(x, y, -z); + *varr++ = Vec3(-x, y, -z); + // bottom + for(int i=0; i<4; i++) { + *narr++ = Vec3(0, -1, 0); + *tarr++ = Vec3(1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vec3(-x, -y, -z); + *varr++ = Vec3(x, -y, -z); + *varr++ = Vec3(x, -y, z); + *varr++ = Vec3(-x, -y, z); + + // index array + static const int faceidx[] = {0, 1, 2, 0, 2, 3}; + for(int i=0; iclear(); + + int uverts = usub + 1; + int vverts = vsub + 1; + int num_verts = uverts * vverts; + + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = 1.0 / (float)(uverts - 1); + float dv = 1.0 / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; i 0.5 ? v - dv * 0.25 : v + dv * 0.25; + nextu = rev_vert(fmod(u + du, 1.0), new_v, rfunc, cls); + tang = nextu - pos; + } + + Vec3 normal; + if(nfunc) { + normal = rev_vert(u, v, nfunc, cls); + } else { + Vec3 nextv = rev_vert(u, v + dv, rfunc, cls); + Vec3 bitan = nextv - pos; + if(length_sq(bitan) < 1e-6) { + nextv = rev_vert(u, v - dv, rfunc, cls); + bitan = pos - nextv; + } + + normal = cross(tang, bitan); + } + + *varr++ = pos; + *narr++ = normalize(normal); + *tarr++ = normalize(tang); + *uvarr++ = Vec2(u, v); + + if(i < usub && j < vsub) { + int idx = i * vverts + j; + + *idxarr++ = idx; + *idxarr++ = idx + vverts + 1; + *idxarr++ = idx + 1; + + *idxarr++ = idx; + *idxarr++ = idx + vverts; + *idxarr++ = idx + vverts + 1; + } + + v += dv; + } + u += du; + } +} + + +static inline Vec3 sweep_vert(float u, float v, float height, Vec2 (*sf)(float, float, void*), void *cls) +{ + Vec2 pos = sf(u, v, cls); + + float x = pos.x; + float y = v * height; + float z = pos.y; + + return Vec3(x, y, z); +} + +// ---- sweep shape along a path ---- +void gen_sweep(Mesh *mesh, float height, int usub, int vsub, Vec2 (*sfunc)(float, float, void*), void *cls) +{ + if(!sfunc) return; + if(usub < 3) usub = 3; + if(vsub < 1) vsub = 1; + + mesh->clear(); + + int uverts = usub + 1; + int vverts = vsub + 1; + int num_verts = uverts * vverts; + + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + Vec3 *varr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vec3 *narr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vec3 *tarr = (Vec3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vec2 *uvarr = (Vec2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = 1.0 / (float)(uverts - 1); + float dv = 1.0 / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; i 0.5 ? v - dv * 0.25 : v + dv * 0.25; + nextu = sweep_vert(fmod(u + du, 1.0), new_v, height, sfunc, cls); + tang = nextu - pos; + } + + Vec3 normal; + Vec3 nextv = sweep_vert(u, v + dv, height, sfunc, cls); + Vec3 bitan = nextv - pos; + if(length_sq(bitan) < 1e-6) { + nextv = sweep_vert(u, v - dv, height, sfunc, cls); + bitan = pos - nextv; + } + + normal = cross(tang, bitan); + + *varr++ = pos; + *narr++ = normalize(normal); + *tarr++ = normalize(tang); + *uvarr++ = Vec2(u, v); + + if(i < usub && j < vsub) { + int idx = i * vverts + j; + + *idxarr++ = idx; + *idxarr++ = idx + vverts + 1; + *idxarr++ = idx + 1; + + *idxarr++ = idx; + *idxarr++ = idx + vverts; + *idxarr++ = idx + vverts + 1; + } + + v += dv; + } + u += du; + } +} diff --git a/src/meshgen.h b/src/meshgen.h new file mode 100644 index 0000000..f154c24 --- /dev/null +++ b/src/meshgen.h @@ -0,0 +1,23 @@ +#ifndef MESHGEN_H_ +#define MESHGEN_H_ + +#include "gmath/gmath.h" + +class Mesh; + +void gen_sphere(Mesh *mesh, float rad, int usub, int vsub, float urange = 1.0, float vrange = 1.0); +void gen_geosphere(Mesh *mesh, float rad, int subdiv, bool hemi = false); +void gen_torus(Mesh *mesh, float mainrad, float ringrad, int usub, int vsub, float urange = 1.0, float vrange = 1.0); +void gen_cylinder(Mesh *mesh, float rad, float height, int usub, int vsub, int capsub = 0, float urange = 1.0, float vrange = 1.0); +void gen_cone(Mesh *mesh, float rad, float height, int usub, int vsub, int capsub = 0, float urange = 1.0, float vrange = 1.0); +void gen_plane(Mesh *mesh, float width, float height, int usub = 1, int vsub = 1); +void gen_heightmap(Mesh *mesh, float width, float height, int usub, int vsub, float (*hf)(float, float, void*), void *hfdata = 0); +void gen_box(Mesh *mesh, float xsz, float ysz, float zsz, int usub = 1, int vsub = 1); + +void gen_revol(Mesh *mesh, int usub, int vsub, Vec2 (*rfunc)(float, float, void*), void *cls = 0); +void gen_revol(Mesh *mesh, int usub, int vsub, Vec2 (*rfunc)(float, float, void*), Vec2 (*nfunc)(float, float, void*), void *cls); + +/* callback args: (float u, float v, void *cls) -> Vec2 XZ offset u,v in [0, 1] */ +void gen_sweep(Mesh *mesh, float height, int usub, int vsub, Vec2 (*sfunc)(float, float, void*), void *cls = 0); + +#endif // MESHGEN_H_ diff --git a/src/opengl.h b/src/opengl.h new file mode 100644 index 0000000..deeddd3 --- /dev/null +++ b/src/opengl.h @@ -0,0 +1,6 @@ +#ifndef OPENGL_H_ +#define OPENGL_H_ + +#include + +#endif // OPENGL_H_ -- 1.7.10.4