1
0
Fork 0

Apply clang llvm formatting

This commit is contained in:
Michaël Lemaire 2015-06-03 14:29:34 +02:00
parent 9d2084b6b5
commit 371731a73b
54 changed files with 6062 additions and 6171 deletions

View file

@ -24,23 +24,32 @@ int SKYBOX = -1;
* pyörähdyskappaletta. Muulloin pisteet lasketaan kuutiollisella * pyörähdyskappaletta. Muulloin pisteet lasketaan kuutiollisella
* interpoloinnilla annettujen pisteiden välillä. * interpoloinnilla annettujen pisteiden välillä.
*/ */
void createLathedSurface(point2d *points, point2d *pointderivates, int count, int slices, int stacks){ void createLathedSurface(point2d *points, point2d *pointderivates, int count,
int slices, int stacks) {
int i, j; int i, j;
point2d *h1, *h2; point2d *h1, *h2;
point2d *derivates; point2d *derivates;
if (pointderivates == NULL) derivates = new point2d[count]; if (pointderivates == NULL)
else derivates = pointderivates; derivates = new point2d[count];
//Derivaatta pisteessä i on (points[i+1]-points[i-1])/2 alkua ja loppua lukuunottamatta else
for (i = 0; i < count; i++){ derivates = pointderivates;
if (pointderivates == NULL || (derivates[i].x == 0 && derivates[i].y == 0)){ // Derivaatta pisteessä i on (points[i+1]-points[i-1])/2 alkua ja loppua
if (i == 0) h1 = &points[0]; // lukuunottamatta
else h1 = &points[i-1]; for (i = 0; i < count; i++) {
if (i == count-1) h2 = &points[count-1]; if (pointderivates == NULL ||
else h2 = &points[i+1]; (derivates[i].x == 0 && derivates[i].y == 0)) {
float dx,dy; if (i == 0)
h1 = &points[0];
else
h1 = &points[i - 1];
if (i == count - 1)
h2 = &points[count - 1];
else
h2 = &points[i + 1];
float dx, dy;
dx = (h2->x - h1->x); dx = (h2->x - h1->x);
dy = (h2->y - h1->y); dy = (h2->y - h1->y);
if (i > 0 && i < count){ if (i > 0 && i < count) {
dx /= 2; dx /= 2;
dy /= 2; dy /= 2;
} }
@ -63,69 +72,70 @@ void createLathedSurface(point2d *points, point2d *pointderivates, int count, in
int i1, i2; int i1, i2;
float t; float t;
float x1, y1, z1, x2, y2, z2, nx1, ny1, nz1, nx2, ny2, nz2; float x1, y1, z1, x2, y2, z2, nx1, ny1, nz1, nx2, ny2, nz2;
for (i = 1; i <= stacks-(stacks/count); i++){ for (i = 1; i <= stacks - (stacks / count); i++) {
sif = (float)i*count/stacks; sif = (float)i * count / stacks;
si = (int)sif; si = (int)sif;
t = sif-si; t = sif - si;
i1 = si; i1 = si;
i2 = si+1; i2 = si + 1;
if (i2 >= count) i2 = count-1; if (i2 >= count)
i2 = count - 1;
p1 = &points[i1]; p1 = &points[i1];
p2 = &points[i2]; p2 = &points[i2];
d1 = &derivates[i1]; d1 = &derivates[i1];
d2 = &derivates[i2]; d2 = &derivates[i2];
//Hermite-käyrä A*t^3 + B*t^2 + C*t + D // Hermite-käyrä A*t^3 + B*t^2 + C*t + D
//Hermite-käyrän derivaatta 3*A*t^2 + 2*B*t + C // Hermite-käyrän derivaatta 3*A*t^2 + 2*B*t + C
//Vakiot A,B,C ja D ovat laskettu siten, että: // Vakiot A,B,C ja D ovat laskettu siten, että:
//1. H(0)=p1; // 1. H(0)=p1;
//2. H(1)=p2; // 2. H(1)=p2;
//3. H'(0)=d1; // 3. H'(0)=d1;
//4. H'(1)=d2; // 4. H'(1)=d2;
// //
//A = d2 - 2*p2 + d1 + 2*p1 // A = d2 - 2*p2 + d1 + 2*p1
//B = -d2 + 3*p2 - 2*d1 - 3*p1 // B = -d2 + 3*p2 - 2*d1 - 3*p1
//C = d1 // C = d1
//D = p1 // D = p1
A.x = d2->x - 2*p2->x + d1->x + 2*p1->x; A.x = d2->x - 2 * p2->x + d1->x + 2 * p1->x;
A.y = d2->y - 2*p2->y + d1->y + 2*p1->y; A.y = d2->y - 2 * p2->y + d1->y + 2 * p1->y;
B.x = - d2->x + 3*p2->x - 2*d1->x - 3*p1->x; B.x = -d2->x + 3 * p2->x - 2 * d1->x - 3 * p1->x;
B.y = - d2->y + 3*p2->y - 2*d1->y - 3*p1->y; B.y = -d2->y + 3 * p2->y - 2 * d1->y - 3 * p1->y;
C.x = d1->x; C.x = d1->x;
C.y = d1->y; C.y = d1->y;
D.x = p1->x; D.x = p1->x;
D.y = p1->y; D.y = p1->y;
newpoint.x = A.x*t*t*t + B.x*t*t + C.x*t + D.x; newpoint.x = A.x * t * t * t + B.x * t * t + C.x * t + D.x;
newpoint.y = A.y*t*t*t + B.y*t*t + C.y*t + D.y; newpoint.y = A.y * t * t * t + B.y * t * t + C.y * t + D.y;
derivate.x = 3*A.x*t*t + 2*B.x*t + C.x; derivate.x = 3 * A.x * t * t + 2 * B.x * t + C.x;
derivate.y = 3*A.y*t*t + 2*B.y*t + C.y; derivate.y = 3 * A.y * t * t + 2 * B.y * t + C.y;
newnormal.x = derivate.y; newnormal.x = derivate.y;
newnormal.y = -derivate.x; newnormal.y = -derivate.x;
glBegin(GL_QUAD_STRIP); glBegin(GL_QUAD_STRIP);
for (j = 0; j <= slices; j++){ for (j = 0; j <= slices; j++) {
float angle = j*2*PI/slices; float angle = j * 2 * PI / slices;
nx2 = sin(angle)*newnormal.x; nx2 = sin(angle) * newnormal.x;
ny2 = newnormal.y; ny2 = newnormal.y;
nz2 = cos(angle)*newnormal.x; nz2 = cos(angle) * newnormal.x;
glNormal3f(nx2, ny2, nz2); glNormal3f(nx2, ny2, nz2);
x2 = sin(angle)*newpoint.x; x2 = sin(angle) * newpoint.x;
y2 = newpoint.y; y2 = newpoint.y;
z2 = cos(angle)*newpoint.x; z2 = cos(angle) * newpoint.x;
glTexCoord2f(j*1.0/slices,1.0-(i*1.0/(stacks-1))); glTexCoord2f(j * 1.0 / slices, 1.0 - (i * 1.0 / (stacks - 1)));
glVertex3f(x2, y2, z2); glVertex3f(x2, y2, z2);
nx1 = sin(angle)*oldnormal.x; nx1 = sin(angle) * oldnormal.x;
ny1 = oldnormal.y; ny1 = oldnormal.y;
nz1 = cos(angle)*oldnormal.x; nz1 = cos(angle) * oldnormal.x;
glNormal3f(nx1, ny1, nz1); glNormal3f(nx1, ny1, nz1);
x1 = sin(angle)*oldpoint.x; x1 = sin(angle) * oldpoint.x;
y1 = oldpoint.y; y1 = oldpoint.y;
z1 = cos(angle)*oldpoint.x; z1 = cos(angle) * oldpoint.x;
glTexCoord2f(j*1.0/slices,1.0-((i-1)*1.0/(stacks-1))); glTexCoord2f(j * 1.0 / slices, 1.0 - ((i - 1) * 1.0 / (stacks - 1)));
glVertex3f(x1, y1, z1); glVertex3f(x1, y1, z1);
} }
glEnd(); glEnd();
@ -139,7 +149,7 @@ void createLathedSurface(point2d *points, point2d *pointderivates, int count, in
GLUquadricObj *spherequadric = gluNewQuadric(); GLUquadricObj *spherequadric = gluNewQuadric();
void createSphere(float r, int slices, int stacks){ void createSphere(float r, int slices, int stacks) {
/*float phi, theta; /*float phi, theta;
int x, y; int x, y;
for (y = 0; y < stacks; y++){ for (y = 0; y < stacks; y++){
@ -152,15 +162,13 @@ void createSphere(float r, int slices, int stacks){
#define DEFAULTSLICES 20 #define DEFAULTSLICES 20
#define DEFAULTSTACKS 10 #define DEFAULTSTACKS 10
void createSphere(float r){ void createSphere(float r) { createSphere(r, DEFAULTSLICES, DEFAULTSTACKS); }
createSphere(r, DEFAULTSLICES, DEFAULTSTACKS);
}
bool solvePointInTriangle(float *position, float *normal, bool solvePointInTriangle(float *position, float *normal, Vertex *v1,
Vertex *v1, Vertex *v2, Vertex *v3, Vertex *v2, Vertex *v3, float *t, float *u,
float *t, float *u, float *v){ float *v) {
float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
float det,inv_det; float det, inv_det;
// find vectors for two edges sharing vert0 // find vectors for two edges sharing vert0
vectorSub(edge1, v2->position, v1->position); vectorSub(edge1, v2->position, v1->position);
@ -169,10 +177,11 @@ bool solvePointInTriangle(float *position, float *normal,
// begin calculating determinant - also used to calculate U parameter // begin calculating determinant - also used to calculate U parameter
vectorCross(pvec, normal, edge2); vectorCross(pvec, normal, edge2);
//if determinant is near zero, ray lies in plane of triangle // if determinant is near zero, ray lies in plane of triangle
det = vectorDot(edge1, pvec); det = vectorDot(edge1, pvec);
if (det > -EPSILON && det < EPSILON) return false; if (det > -EPSILON && det < EPSILON)
return false;
inv_det = 1.0 / det; inv_det = 1.0 / det;
// calculate distance from vert0 to ray origin // calculate distance from vert0 to ray origin
@ -180,14 +189,16 @@ bool solvePointInTriangle(float *position, float *normal,
// calculate U parameter and test bounds // calculate U parameter and test bounds
*u = vectorDot(tvec, pvec) * inv_det; *u = vectorDot(tvec, pvec) * inv_det;
if (*u < 0.0 || *u > 1.0) return false; if (*u < 0.0 || *u > 1.0)
return false;
// prepare to test V parameter // prepare to test V parameter
vectorCross(qvec, tvec, edge1); vectorCross(qvec, tvec, edge1);
// calculate V parameter and test bounds // calculate V parameter and test bounds
*v = vectorDot(normal, qvec) * inv_det; *v = vectorDot(normal, qvec) * inv_det;
if (*v < 0.0 || *u + *v > 1.0) return false; if (*v < 0.0 || *u + *v > 1.0)
return false;
// calculate t, ray intersects triangle // calculate t, ray intersects triangle
*t = vectorDot(edge2, qvec) * inv_det; *t = vectorDot(edge2, qvec) * inv_det;
@ -195,14 +206,11 @@ bool solvePointInTriangle(float *position, float *normal,
return true; return true;
} }
float distanceFromPlane(float point[3], float normal[3], float distance) {
float distanceFromPlane(float point[3], float normal[3], float distance){
return vectorDot(point, normal) + distance; return vectorDot(point, normal) + distance;
} }
void createSkyBox(float x, float y, float z, float w, float h, float l) {
void createSkyBox(float x, float y, float z, float w, float h, float l)
{
glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glClear(GL_DEPTH_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
@ -219,110 +227,119 @@ void createSkyBox(float x, float y, float z, float w, float h, float l)
glPushMatrix(); glPushMatrix();
glLoadMatrixf(modelview); glLoadMatrixf(modelview);
if (SKYBOX > 0){ if (SKYBOX > 0) {
glCallList(SKYBOX); glCallList(SKYBOX);
} } else {
else{
SKYBOX = glGenLists(1); SKYBOX = glGenLists(1);
float d = 1.0/512; float d = 1.0 / 512;
//glPushAttrib(GL_COLOR); // glPushAttrib(GL_COLOR);
glNewList(SKYBOX, GL_COMPILE_AND_EXECUTE); glNewList(SKYBOX, GL_COMPILE_AND_EXECUTE);
// glBindTexture(GL_TEXTURE_2D, SKY_BACK_ID);
//glBindTexture(GL_TEXTURE_2D, SKY_BACK_ID);
skybacktexture->enable(); skybacktexture->enable();
glBegin(GL_QUADS); glBegin(GL_QUADS);
glColor4f(1, 1, 1, 1.0); glColor4f(1, 1, 1, 1.0);
glTexCoord2f(1-d, 1-d); glVertex3f(x + w, y, z); glTexCoord2f(1 - d, 1 - d);
glTexCoord2f(1-d, 0+d); glVertex3f(x + w, y + h, z); glVertex3f(x + w, y, z);
glTexCoord2f(0+d, 0+d); glVertex3f(x, y + h, z); glTexCoord2f(1 - d, 0 + d);
glTexCoord2f(0+d, 1-d); glVertex3f(x, y, z); glVertex3f(x + w, y + h, z);
glTexCoord2f(0 + d, 0 + d);
glVertex3f(x, y + h, z);
glTexCoord2f(0 + d, 1 - d);
glVertex3f(x, y, z);
glEnd(); glEnd();
// glBindTexture(GL_TEXTURE_2D, SKY_FRONT_ID);
//glBindTexture(GL_TEXTURE_2D, SKY_FRONT_ID);
skyfronttexture->enable(); skyfronttexture->enable();
glBegin(GL_QUADS); glBegin(GL_QUADS);
glColor4f(1, 1, 1, 1.0); glColor4f(1, 1, 1, 1.0);
glTexCoord2f(1-d, 1-d); glVertex3f(x, y, z + l); glTexCoord2f(1 - d, 1 - d);
glTexCoord2f(1-d, 0+d); glVertex3f(x, y + h, z + l); glVertex3f(x, y, z + l);
glTexCoord2f(0+d, 0+d); glVertex3f(x + w, y + h, z + l); glTexCoord2f(1 - d, 0 + d);
glTexCoord2f(0+d, 1-d); glVertex3f(x + w, y, z + l); glVertex3f(x, y + h, z + l);
glTexCoord2f(0 + d, 0 + d);
glVertex3f(x + w, y + h, z + l);
glTexCoord2f(0 + d, 1 - d);
glVertex3f(x + w, y, z + l);
glEnd(); glEnd();
// glBindTexture(GL_TEXTURE_2D, SKY_TOP_ID);
//glBindTexture(GL_TEXTURE_2D, SKY_TOP_ID);
skytoptexture->enable(); skytoptexture->enable();
glBegin(GL_QUADS); glBegin(GL_QUADS);
glColor4f(1, 1, 1, 1.0); glColor4f(1, 1, 1, 1.0);
glTexCoord2f(0+d, 0+d); glVertex3f(x + w, y + h, z + l); glTexCoord2f(0 + d, 0 + d);
glTexCoord2f(1-d, 0+d); glVertex3f(x + w, y + h, z); glVertex3f(x + w, y + h, z + l);
glTexCoord2f(1-d, 1-d); glVertex3f(x, y + h, z); glTexCoord2f(1 - d, 0 + d);
glTexCoord2f(0+d, 1-d); glVertex3f(x, y + h, z + l); glVertex3f(x + w, y + h, z);
glTexCoord2f(1 - d, 1 - d);
glVertex3f(x, y + h, z);
glTexCoord2f(0 + d, 1 - d);
glVertex3f(x, y + h, z + l);
/*glTexCoord2f(1.0f, 0+d); glVertex3f(x + w, y + h, z); /*glTexCoord2f(1.0f, 0+d); glVertex3f(x + w, y + h, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + w, y + h, z + l); glTexCoord2f(1.0f, 1.0f); glVertex3f(x + w, y + h, z + l);
glTexCoord2f(0+d, 1.0f); glVertex3f(x, y + h, z + l); glTexCoord2f(0+d, 1.0f); glVertex3f(x, y + h, z + l);
glTexCoord2f(0+d, 0+d); glVertex3f(x, y + h, z);*/ glTexCoord2f(0+d, 0+d); glVertex3f(x, y + h, z);*/
glEnd(); glEnd();
// glBindTexture(GL_TEXTURE_2D, SKY_BOTTOM_ID);
//glBindTexture(GL_TEXTURE_2D, SKY_BOTTOM_ID);
skybottomtexture->enable(); skybottomtexture->enable();
glBegin(GL_QUADS); glBegin(GL_QUADS);
glColor4f(1, 1, 1, 1.0); glColor4f(1, 1, 1, 1.0);
glTexCoord2f(1-d, 0+d); glVertex3f(x, y, z); glTexCoord2f(1 - d, 0 + d);
glTexCoord2f(1-d, 1-d); glVertex3f(x + w, y, z); glVertex3f(x, y, z);
glTexCoord2f(0+d, 1-d); glVertex3f(x + w, y, z + l); glTexCoord2f(1 - d, 1 - d);
glTexCoord2f(0+d, 0+d); glVertex3f(x, y, z + l); glVertex3f(x + w, y, z);
glTexCoord2f(0 + d, 1 - d);
glVertex3f(x + w, y, z + l);
glTexCoord2f(0 + d, 0 + d);
glVertex3f(x, y, z + l);
glEnd(); glEnd();
//glBindTexture(GL_TEXTURE_2D, SKY_LEFT_ID); // glBindTexture(GL_TEXTURE_2D, SKY_LEFT_ID);
skylefttexture->enable(); skylefttexture->enable();
glBegin(GL_QUADS); glBegin(GL_QUADS);
glColor4f(1, 1, 1, 1.0); glColor4f(1, 1, 1, 1.0);
glTexCoord2f(1-d, 0+d); glVertex3f(x, y + h, z); glTexCoord2f(1 - d, 0 + d);
glTexCoord2f(0+d, 0+d); glVertex3f(x, y + h, z + l); glVertex3f(x, y + h, z);
glTexCoord2f(0+d, 1-d); glVertex3f(x, y, z + l); glTexCoord2f(0 + d, 0 + d);
glTexCoord2f(1-d, 1-d); glVertex3f(x, y, z); glVertex3f(x, y + h, z + l);
glTexCoord2f(0 + d, 1 - d);
glVertex3f(x, y, z + l);
glTexCoord2f(1 - d, 1 - d);
glVertex3f(x, y, z);
glEnd(); glEnd();
//glBindTexture(GL_TEXTURE_2D, SKY_RIGHT_ID); // glBindTexture(GL_TEXTURE_2D, SKY_RIGHT_ID);
skyrighttexture->enable(); skyrighttexture->enable();
glBegin(GL_QUADS); glBegin(GL_QUADS);
glColor4f(1, 1, 1, 1.0); glColor4f(1, 1, 1, 1.0);
glTexCoord2f(0+d, 1-d); glVertex3f(x + w, y, z); glTexCoord2f(0 + d, 1 - d);
glTexCoord2f(1-d, 1-d); glVertex3f(x + w, y, z + l); glVertex3f(x + w, y, z);
glTexCoord2f(1-d, 0+d); glVertex3f(x + w, y + h, z + l); glTexCoord2f(1 - d, 1 - d);
glTexCoord2f(0+d, 0+d); glVertex3f(x + w, y + h, z); glVertex3f(x + w, y, z + l);
glTexCoord2f(1 - d, 0 + d);
glVertex3f(x + w, y + h, z + l);
glTexCoord2f(0 + d, 0 + d);
glVertex3f(x + w, y + h, z);
glEnd(); glEnd();
glEndList(); glEndList();
@ -336,7 +353,7 @@ void createSkyBox(float x, float y, float z, float w, float h, float l)
glShadeModel(GL_SMOOTH); glShadeModel(GL_SMOOTH);
} }
void enable2D(void){ void enable2D(void) {
glDisable(GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE); glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
@ -349,7 +366,7 @@ void enable2D(void){
glLoadIdentity(); glLoadIdentity();
} }
void disable2D(void){ void disable2D(void) {
glPopMatrix(); glPopMatrix();
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glPopMatrix(); glPopMatrix();

View file

@ -4,31 +4,24 @@
#include "main.h" #include "main.h"
#include "texture.h" #include "texture.h"
#define SKYFRONT DATAPATH "tback.png"
#define SKYBACK DATAPATH "tfront.png"
#define SKYLEFT DATAPATH "tleft.png"
#define SKYRIGHT DATAPATH "tright.png"
#define SKYTOP DATAPATH "ttop.png"
#define SKYBOTTOM DATAPATH "tbottom.png"
#define DAMAGEHEAD DATAPATH "damagehead.png"
#define SKYFRONT DATAPATH"tback.png" #define DAMAGETORSO DATAPATH "damagetorso.png"
#define SKYBACK DATAPATH"tfront.png" #define DAMAGEHAND DATAPATH "damagehand.png"
#define SKYLEFT DATAPATH"tleft.png" #define DAMAGELEG DATAPATH "damageleg.png"
#define SKYRIGHT DATAPATH"tright.png" #define FACE DATAPATH "perusnaama3.png"
#define SKYTOP DATAPATH"ttop.png"
#define SKYBOTTOM DATAPATH"tbottom.png"
#define DAMAGEHEAD DATAPATH"damagehead.png"
#define DAMAGETORSO DATAPATH"damagetorso.png"
#define DAMAGEHAND DATAPATH"damagehand.png"
#define DAMAGELEG DATAPATH"damageleg.png"
#define FACE DATAPATH"perusnaama3.png"
extern int SKYBOX; extern int SKYBOX;
typedef struct{ typedef struct { float x, y; } point2d;
float x,y;
} point2d;
typedef struct{ typedef struct { float x, y, z; } point3d;
float x,y,z;
} point3d;
extern Texture *flaretexture; extern Texture *flaretexture;
extern Texture *skyfronttexture; extern Texture *skyfronttexture;
@ -40,7 +33,8 @@ extern Texture *skybottomtexture;
extern Texture *damageHead; extern Texture *damageHead;
extern Texture *faceTexture; extern Texture *faceTexture;
void createLathedSurface(point2d *points, point2d *pointderivates, int count, int slices, int stacks); void createLathedSurface(point2d *points, point2d *pointderivates, int count,
int slices, int stacks);
void createSphere(float r, int slices, int stacks); void createSphere(float r, int slices, int stacks);
void createSphere(float r); void createSphere(float r);
@ -48,10 +42,8 @@ float distanceFromPlane(float point[3], float normal[3], float distance);
void createSkyBox(float x, float y, float z, float w, float h, float l); void createSkyBox(float x, float y, float z, float w, float h, float l);
// MUST be called in pairs, enable pushes and disable pops
//MUST be called in pairs, enable pushes and disable pops
void enable2D(void); void enable2D(void);
void disable2D(void); void disable2D(void);
#endif #endif

View file

@ -1,24 +1,20 @@
#include "main.h" #include "main.h"
#include "appearance.h" #include "appearance.h"
#include "utils.h" #include "utils.h"
#include "3dutils.h" #include "3dutils.h"
#include "glapi.h" #include "glapi.h"
Appearance::Appearance(void){ Appearance::Appearance(void) {}
}
void Appearance::prepare(void){
}
void Appearance::prepare(void) {}
/*BoxAppearance::BoxAppearance(void){ /*BoxAppearance::BoxAppearance(void){
setDimension(-1, 1, -1, 1, -1, 1); setDimension(-1, 1, -1, 1, -1, 1);
} }
BoxAppearance::setDimension(float x1, float x2, float y1, float y2, float z1, float z2){ BoxAppearance::setDimension(float x1, float x2, float y1, float y2, float z1,
float z2){
if (x1 > x2) swapFloat(&x1, &x2); if (x1 > x2) swapFloat(&x1, &x2);
if (y1 > y2) swapFloat(&y1, &y2); if (y1 > y2) swapFloat(&y1, &y2);
if (z1 > z2) swapFloat(&z1, &z2); if (z1 > z2) swapFloat(&z1, &z2);
@ -77,40 +73,30 @@ void BoxAppearance::draw(void){
this->material.disable(); this->material.disable();
}*/ }*/
Material *Appearance::getMaterial(void) { return &this->material; }
Material* Appearance::getMaterial(void){ void Appearance::setMaterial(Material matsku) { material = matsku; }
return &this->material;
}
void Appearance::setMaterial(Material matsku){ MultiAppearance::MultiAppearance(void) { appearances = NULL; }
material = matsku;
}
void MultiAppearance::addAppearance(Appearance *appearance) {
MultiAppearance::MultiAppearance(void){
appearances = NULL;
}
void MultiAppearance::addAppearance(Appearance *appearance){
appearancelist *node = new appearancelist; appearancelist *node = new appearancelist;
node->data = appearance; node->data = appearance;
node->next = appearances; node->next = appearances;
appearances = node; appearances = node;
} }
void MultiAppearance::prepare(void){ void MultiAppearance::prepare(void) {
appearancelist *node = appearances; appearancelist *node = appearances;
while (node != NULL){ while (node != NULL) {
node->data->prepare(); node->data->prepare();
node = node->next; node = node->next;
} }
} }
void MultiAppearance::draw(void){ void MultiAppearance::draw(void) {
appearancelist *node = appearances; appearancelist *node = appearances;
while (node != NULL){ while (node != NULL) {
node->data->draw(); node->data->draw();
node = node->next; node = node->next;
} }

View file

@ -8,27 +8,26 @@
/* /*
* Abstract class for drawing objects * Abstract class for drawing objects
*/ */
class Appearance{ class Appearance {
private: private:
public: public:
Material material; Material material;
Appearance(void); Appearance(void);
Material* getMaterial(void); Material *getMaterial(void);
void setMaterial(Material mat); void setMaterial(Material mat);
virtual void prepare(void); virtual void prepare(void);
virtual void draw(void) = 0; virtual void draw(void) = 0;
}; };
struct appearancelist {
struct appearancelist{
Appearance *data; Appearance *data;
appearancelist *next; appearancelist *next;
}; };
class MultiAppearance : public Appearance{ class MultiAppearance : public Appearance {
private: private:
appearancelist *appearances; appearancelist *appearances;
@ -41,4 +40,3 @@ public:
}; };
#endif #endif

View file

@ -5,21 +5,18 @@
#include "audio.h" #include "audio.h"
#define SOUND_FADENONE 0 #define SOUND_FADENONE 0
#define SOUND_FADEIN 1 #define SOUND_FADEIN 1
#define SOUND_FADEOUT 2 #define SOUND_FADEOUT 2
struct soundlist {
struct soundlist{
Sound *sound; Sound *sound;
soundlist *next; soundlist *next;
}; };
soundlist *allsounds = NULL; soundlist *allsounds = NULL;
Sound::Sound(Sound *source) {
Sound::Sound(Sound *source){
memcpy(this, source, sizeof(Sound)); memcpy(this, source, sizeof(Sound));
soundlist *node = new soundlist; soundlist *node = new soundlist;
node->sound = this; node->sound = this;
@ -27,73 +24,72 @@ Sound::Sound(Sound *source){
allsounds = node; allsounds = node;
} }
Sound::Sound(char *filename){ Sound::Sound(char *filename) {
load(filename, SOUNDTYPE_AUTODETECT, false); load(filename, SOUNDTYPE_AUTODETECT, false);
//printf("%s: %p, %p, %p, %p\n", filename, this, stream, sample, module); // printf("%s: %p, %p, %p, %p\n", filename, this, stream, sample, module);
} }
Sound::Sound(char *filename, int type){ Sound::Sound(char *filename, int type) { load(filename, type, false); }
load(filename, type, false);
}
Sound::Sound(char *filename, bool loops){ Sound::Sound(char *filename, bool loops) {
load(filename, SOUNDTYPE_AUTODETECT, loops); load(filename, SOUNDTYPE_AUTODETECT, loops);
//printf("%s: %p, %p, %p, %p\n", filename, this, stream, sample, module); // printf("%s: %p, %p, %p, %p\n", filename, this, stream, sample, module);
} }
Sound::Sound(char *filename, int type, bool loops){ Sound::Sound(char *filename, int type, bool loops) {
load(filename, type, loops); load(filename, type, loops);
} }
bool endsWith(char *str1, char *str2){ bool endsWith(char *str1, char *str2) {
char *str3 = str1 + strlen(str1) - strlen(str2); char *str3 = str1 + strlen(str1) - strlen(str2);
#ifdef WIN32 #ifdef WIN32
if (stricmp(str3, str2)) return false; if (stricmp(str3, str2))
return false;
#else #else
if (strcasecmp(str3, str2)) return false; if (strcasecmp(str3, str2))
return false;
#endif #endif
else return true; else
return true;
} }
void Sound::load(char *filename, int type, bool loops){ void Sound::load(char *filename, int type, bool loops) {
this->filename = filename; this->filename = filename;
if (type == SOUNDTYPE_AUTODETECT){ if (type == SOUNDTYPE_AUTODETECT) {
if (endsWith(filename, "mp3") || if (endsWith(filename, "mp3") || endsWith(filename, "mp2") ||
endsWith(filename, "mp2") || endsWith(filename, "ogg"))
endsWith(filename, "ogg")) type = SOUNDTYPE_STREAM; type = SOUNDTYPE_STREAM;
if (endsWith(filename, "wav") || if (endsWith(filename, "wav") || endsWith(filename, "raw"))
endsWith(filename, "raw")) type = SOUNDTYPE_SAMPLE; type = SOUNDTYPE_SAMPLE;
if (endsWith(filename, "s3m") || if (endsWith(filename, "s3m") || endsWith(filename, "xm") ||
endsWith(filename, "xm") || endsWith(filename, "it") || endsWith(filename, "mid") ||
endsWith(filename, "it") || endsWith(filename, "rmi") || endsWith(filename, "sgr") ||
endsWith(filename, "mid") || endsWith(filename, "mod"))
endsWith(filename, "rmi") || type = SOUNDTYPE_MODULE;
endsWith(filename, "sgr") ||
endsWith(filename, "mod")) type = SOUNDTYPE_MODULE;
} }
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
sample = NULL; sample = NULL;
module = NULL; module = NULL;
stream = NULL; stream = NULL;
this->type = type; this->type = type;
if (type == SOUNDTYPE_MODULE){ if (type == SOUNDTYPE_MODULE) {
module = FMUSIC_LoadSong(filename); module = FMUSIC_LoadSong(filename);
this->loops = false; this->loops = false;
} else if (type == SOUNDTYPE_SAMPLE){ } else if (type == SOUNDTYPE_SAMPLE) {
if (loops){ if (loops) {
sample = FSOUND_Sample_Load(FSOUND_FREE, filename, FSOUND_LOOP_NORMAL, 0); sample = FSOUND_Sample_Load(FSOUND_FREE, filename, FSOUND_LOOP_NORMAL, 0);
FSOUND_Sample_SetLoopMode(sample, FSOUND_LOOP_NORMAL); FSOUND_Sample_SetLoopMode(sample, FSOUND_LOOP_NORMAL);
} else{ } else {
sample = FSOUND_Sample_Load(FSOUND_FREE, filename, FSOUND_LOOP_OFF, 0); sample = FSOUND_Sample_Load(FSOUND_FREE, filename, FSOUND_LOOP_OFF, 0);
FSOUND_Sample_SetLoopMode(sample, FSOUND_LOOP_OFF); FSOUND_Sample_SetLoopMode(sample, FSOUND_LOOP_OFF);
} }
this->loops = loops; this->loops = loops;
} else if (type == SOUNDTYPE_STREAM){ } else if (type == SOUNDTYPE_STREAM) {
if (loops){ if (loops) {
stream = FSOUND_Stream_OpenFile(filename, FSOUND_LOOP_NORMAL, 0); stream = FSOUND_Stream_OpenFile(filename, FSOUND_LOOP_NORMAL, 0);
} else{ } else {
stream = FSOUND_Stream_OpenFile(filename, FSOUND_LOOP_OFF, 0); stream = FSOUND_Stream_OpenFile(filename, FSOUND_LOOP_OFF, 0);
} }
this->loops = loops; this->loops = loops;
@ -108,138 +104,142 @@ void Sound::load(char *filename, int type, bool loops){
setVolume(1.0); setVolume(1.0);
} }
bool Sound::play() {
bool Sound::play(){ // printf("Playing %s: %p, %p, %p, %p\n", filename, this, stream, sample,
//printf("Playing %s: %p, %p, %p, %p\n", filename, this, stream, sample, module); // module);
if (minduration > 0) return false; if (minduration > 0)
return false;
running = true; running = true;
finished = false; finished = false;
fademode = SOUND_FADENONE; fademode = SOUND_FADENONE;
minduration = 0; minduration = 0;
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
if (type == SOUNDTYPE_MODULE){ if (type == SOUNDTYPE_MODULE) {
FMUSIC_PlaySong(module); FMUSIC_PlaySong(module);
FMUSIC_SetMasterVolume(module, volume*256); FMUSIC_SetMasterVolume(module, volume * 256);
} else if (type == SOUNDTYPE_SAMPLE){ } else if (type == SOUNDTYPE_SAMPLE) {
channel = FSOUND_PlaySound(FSOUND_FREE, sample); channel = FSOUND_PlaySound(FSOUND_FREE, sample);
FSOUND_SetVolume(channel, volume*256); FSOUND_SetVolume(channel, volume * 256);
if (!loops){ if (!loops) {
running = false; running = false;
finished = false; finished = false;
} }
} else if (type == SOUNDTYPE_STREAM){ } else if (type == SOUNDTYPE_STREAM) {
channel = FSOUND_Stream_Play(FSOUND_FREE, stream); channel = FSOUND_Stream_Play(FSOUND_FREE, stream);
FSOUND_SetVolume(channel, volume*256); FSOUND_SetVolume(channel, volume * 256);
} }
#endif #endif
//printf("Done: %f\n", volume); // printf("Done: %f\n", volume);
return true; return true;
} }
void Sound::play(int minduration){ void Sound::play(int minduration) {
if (play()) this->minduration = minduration; if (play())
this->minduration = minduration;
} }
void Sound::stop(){ void Sound::stop() {
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
if (type == SOUNDTYPE_MODULE){ if (type == SOUNDTYPE_MODULE) {
FMUSIC_StopSong(module); FMUSIC_StopSong(module);
} else if (type == SOUNDTYPE_SAMPLE){ } else if (type == SOUNDTYPE_SAMPLE) {
FSOUND_StopSound(channel); FSOUND_StopSound(channel);
} else if (type == SOUNDTYPE_STREAM){ } else if (type == SOUNDTYPE_STREAM) {
FSOUND_Stream_Stop(stream); FSOUND_Stream_Stop(stream);
} }
#endif #endif
} }
void Sound::setVolume(float volume){ void Sound::setVolume(float volume) {
//printf("Volume %s: %f\n", filename, volume); // printf("Volume %s: %f\n", filename, volume);
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
if (type == SOUNDTYPE_MODULE){ if (type == SOUNDTYPE_MODULE) {
FMUSIC_SetMasterVolume(module, volume*256); FMUSIC_SetMasterVolume(module, volume * 256);
} else if (type == SOUNDTYPE_SAMPLE){ } else if (type == SOUNDTYPE_SAMPLE) {
FSOUND_SetVolume(channel, volume*256); FSOUND_SetVolume(channel, volume * 256);
} else if (type == SOUNDTYPE_STREAM){ } else if (type == SOUNDTYPE_STREAM) {
FSOUND_SetVolume(channel, volume*256); FSOUND_SetVolume(channel, volume * 256);
} }
#endif #endif
this->volume = volume; this->volume = volume;
} }
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
signed char streamendcallback(FSOUND_STREAM *stream, void *buff, int len, int param){ signed char streamendcallback(FSOUND_STREAM *stream, void *buff, int len,
int param) {
Sound *sound = (Sound *)param; Sound *sound = (Sound *)param;
sound->setFinished(); sound->setFinished();
return true; return true;
} }
#endif #endif
void Sound::setStopCallback(STOPCALLBACK callback){ void Sound::setStopCallback(STOPCALLBACK callback) {
stopcallback = callback; stopcallback = callback;
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
if (type == SOUNDTYPE_MODULE){ if (type == SOUNDTYPE_MODULE) {
} else if (type == SOUNDTYPE_SAMPLE){ } else if (type == SOUNDTYPE_SAMPLE) {
//NOT SUPPORTED // NOT SUPPORTED
} else if (type == SOUNDTYPE_STREAM){ } else if (type == SOUNDTYPE_STREAM) {
FSOUND_Stream_SetEndCallback(stream, streamendcallback, (int)this); FSOUND_Stream_SetEndCallback(stream, streamendcallback, (int)this);
} }
#endif #endif
} }
void Sound::setFinished(void) { finished = true; }
bool Sound::isFinished(void) {
void Sound::setFinished(void){
finished = true;
}
bool Sound::isFinished(void){
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
if (type == SOUNDTYPE_MODULE){ if (type == SOUNDTYPE_MODULE) {
if (FMUSIC_IsFinished(module)) return true; if (FMUSIC_IsFinished(module))
} else if (type == SOUNDTYPE_SAMPLE){ return true;
//NOT SUPPORTED } else if (type == SOUNDTYPE_SAMPLE) {
} else if (type == SOUNDTYPE_STREAM){ // NOT SUPPORTED
if (finished) return true; } else if (type == SOUNDTYPE_STREAM) {
if (finished)
return true;
} }
#endif #endif
return false; return false;
} }
void Sound::update(void){ void Sound::update(void) {
if (running){ if (running) {
if (isFinished()){ if (isFinished()) {
running = false; running = false;
if (stopcallback != NULL) stopcallback(this); if (stopcallback != NULL)
} else{ stopcallback(this);
if (fademode == SOUND_FADEIN){ } else {
if (fadepos < fadetarget){ if (fademode == SOUND_FADEIN) {
if (fadepos < fadetarget) {
fadepos++; fadepos++;
setVolume((float)fadepos/fadetarget); setVolume((float)fadepos / fadetarget);
} else fademode = SOUND_FADENONE; } else
fademode = SOUND_FADENONE;
} }
if (fademode == SOUND_FADEOUT){ if (fademode == SOUND_FADEOUT) {
if (fadepos < fadetarget){ if (fadepos < fadetarget) {
fadepos++; fadepos++;
setVolume(1.0 - (float)fadepos/fadetarget); setVolume(1.0 - (float)fadepos / fadetarget);
} else{ } else {
fademode = SOUND_FADENONE; fademode = SOUND_FADENONE;
stop(); stop();
} }
} }
} }
} }
if (minduration > 0) minduration--; if (minduration > 0)
minduration--;
} }
void Sound::fadeIn(int length){ void Sound::fadeIn(int length) {
fademode = SOUND_FADEIN; fademode = SOUND_FADEIN;
fadepos = 0; fadepos = 0;
fadetarget = length; fadetarget = length;
} }
void Sound::fadeOut(int length){ void Sound::fadeOut(int length) {
if (fademode == SOUND_FADEIN){ if (fademode == SOUND_FADEIN) {
float percent = 1.0 - (float)fadepos/fadetarget; float percent = 1.0 - (float)fadepos / fadetarget;
fadepos = fadetarget * percent; fadepos = fadetarget * percent;
} }
fadepos = 0; fadepos = 0;
@ -247,22 +247,21 @@ void Sound::fadeOut(int length){
fademode = SOUND_FADEOUT; fademode = SOUND_FADEOUT;
} }
void initAudio(void) {
void initAudio(void){
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
FSOUND_Init(44100, 32, 0); FSOUND_Init(44100, 32, 0);
#endif #endif
} }
void uninitAudio(void){ void uninitAudio(void) {
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
FSOUND_Close(); FSOUND_Close();
#endif #endif
} }
void updateAudio(void){ void updateAudio(void) {
soundlist *node = allsounds; soundlist *node = allsounds;
while (node != NULL){ while (node != NULL) {
Sound *sound = node->sound; Sound *sound = node->sound;
sound->update(); sound->update();
node = node->next; node = node->next;

View file

@ -1,24 +1,22 @@
#ifndef __AUDIO_H_INCLUDED__ #ifndef __AUDIO_H_INCLUDED__
#define __AUDIO_H_INCLUDED__ #define __AUDIO_H_INCLUDED__
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
#include <fmod.h> #include <fmod.h>
#endif #endif
class Sound; class Sound;
typedef void(* STOPCALLBACK)(Sound *sound); typedef void (*STOPCALLBACK)(Sound *sound);
#define SOUNDTYPE_AUTODETECT 0 #define SOUNDTYPE_AUTODETECT 0
#define SOUNDTYPE_MODULE 1 #define SOUNDTYPE_MODULE 1
#define SOUNDTYPE_STREAM 2 #define SOUNDTYPE_STREAM 2
#define SOUNDTYPE_SAMPLE 3 #define SOUNDTYPE_SAMPLE 3
#define BGSONG DATAPATH"boom.mp3" #define BGSONG DATAPATH "boom.mp3"
class Sound{ class Sound {
private: private:
#ifdef AUDIO_FMOD #ifdef AUDIO_FMOD
int type; int type;
@ -50,8 +48,8 @@ public:
void load(char *filename, int type, bool loops); void load(char *filename, int type, bool loops);
bool play(void); bool play(void);
//Plays sound for at least minduration frames until sound // Plays sound for at least minduration frames until sound
//can be played again. Doesn't prevent stopping of the sound // can be played again. Doesn't prevent stopping of the sound
void play(int minduration); void play(int minduration);
void stop(); void stop();
void setStopCallback(STOPCALLBACK callback); void setStopCallback(STOPCALLBACK callback);
@ -59,7 +57,7 @@ public:
void fadeIn(int length); void fadeIn(int length);
void fadeOut(int length); void fadeOut(int length);
//Do not use methods below // Do not use methods below
void setFinished(void); void setFinished(void);
void update(void); void update(void);
}; };
@ -69,4 +67,3 @@ void uninitAudio(void);
void updateAudio(void); void updateAudio(void);
#endif #endif

View file

@ -4,7 +4,7 @@
#include "vector.h" #include "vector.h"
#include "glapi.h" #include "glapi.h"
Camera::Camera(void){ Camera::Camera(void) {
right = &matrix[0]; right = &matrix[0];
up = &matrix[3]; up = &matrix[3];
forward = &matrix[6]; forward = &matrix[6];
@ -16,71 +16,64 @@ Camera::Camera(void){
calculateMatrix(); calculateMatrix();
} }
void Camera::setPosition(float position[3]){ void Camera::setPosition(float position[3]) {
vectorCopy(this->position, position); vectorCopy(this->position, position);
} }
void Camera::setPosition(float x, float y, float z){ void Camera::setPosition(float x, float y, float z) {
this->position[0] = x; this->position[0] = x;
this->position[1] = y; this->position[1] = y;
this->position[2] = z; this->position[2] = z;
} }
void Camera::getPosition(float *position){ void Camera::getPosition(float *position) {
vectorCopy(position, this->position); vectorCopy(position, this->position);
} }
void Camera::setTarget(float target[3]){ void Camera::setTarget(float target[3]) { vectorCopy(this->target, target); }
vectorCopy(this->target, target);
}
void Camera::getTarget(float *target){ void Camera::getTarget(float *target) { vectorCopy(target, this->target); }
vectorCopy(target, this->target);
}
void Camera::setUp(float up[3]){ void Camera::setUp(float up[3]) { vectorCopy(this->up, up); }
vectorCopy(this->up, up);
}
void Camera::getMatrix(float *matrix){ void Camera::getMatrix(float *matrix) {
vectorCopy(&matrix[0], &this->matrix[0]); vectorCopy(&matrix[0], &this->matrix[0]);
vectorCopy(&matrix[3], &this->matrix[3]); vectorCopy(&matrix[3], &this->matrix[3]);
vectorCopy(&matrix[6], &this->matrix[6]); vectorCopy(&matrix[6], &this->matrix[6]);
} }
void Camera::moveRight(float amount){ void Camera::moveRight(float amount) {
float movevector[3]; float movevector[3];
vectorScale(movevector, right, amount); vectorScale(movevector, right, amount);
vectorAdd(position, movevector); vectorAdd(position, movevector);
//vectorAdd(target, movevector); // vectorAdd(target, movevector);
calculateMatrix(); calculateMatrix();
} }
void Camera::moveUp(float amount){ void Camera::moveUp(float amount) {
float movevector[3]; float movevector[3];
vectorScale(movevector, up, amount); vectorScale(movevector, up, amount);
vectorAdd(position, movevector); vectorAdd(position, movevector);
//vectorAdd(target, movevector); // vectorAdd(target, movevector);
calculateMatrix(); calculateMatrix();
} }
void Camera::moveForward(float amount){ void Camera::moveForward(float amount) {
float movevector[3]; float movevector[3];
vectorScale(movevector, forward, amount); vectorScale(movevector, forward, amount);
vectorAdd(position, movevector); vectorAdd(position, movevector);
//vectorAdd(target, movevector); // vectorAdd(target, movevector);
calculateMatrix(); calculateMatrix();
} }
void Camera::glUpdate(void){ void Camera::glUpdate(void) {
//glLoadIdentity(); // glLoadIdentity();
gluLookAt(position[0], position[1], position[2], gluLookAt(position[0], position[1], position[2], target[0], target[1],
target[0], target[1], target[2], target[2], up[0], up[1], up[2]);
up[0], up[1], up[2]);
} }
void Camera::calculateMatrix(void){ void Camera::calculateMatrix(void) {
vectorSub(forward, target, position); vectorSub(forward, target, position);
vectorNormalize(forward); vectorNormalize(forward);
vectorCross(right, forward, up); vectorCross(right, forward, up);

View file

@ -1,7 +1,7 @@
#ifndef __CAMERA_H_INCLUDED__ #ifndef __CAMERA_H_INCLUDED__
#define __CAMERA_H_INCLUDED__ #define __CAMERA_H_INCLUDED__
class Camera{ class Camera {
private: private:
float position[3]; float position[3];
float target[3]; float target[3];
@ -29,4 +29,3 @@ public:
}; };
#endif #endif

View file

@ -9,17 +9,16 @@
#include "world.h" #include "world.h"
#include "audio.h" #include "audio.h"
// objectlist *collisionlists[32];
//objectlist *collisionlists[32];
unsigned int collisionlinks[32]; unsigned int collisionlinks[32];
Contact *contacts; Contact *contacts;
int contactcount; int contactcount;
void initCollisions(void){ void initCollisions(void) {
int i; int i;
for (i = 0; i < 32; i++){ for (i = 0; i < 32; i++) {
//collisionlists[i] = NULL; // collisionlists[i] = NULL;
collisionlinks[i] = 0; collisionlinks[i] = 0;
} }
} }
@ -31,24 +30,27 @@ void initCollisions(void){
collisionlists[group] = node; collisionlists[group] = node;
}*/ }*/
void addCollisionLink(int source, int target){ void addCollisionLink(int source, int target) {
collisionlinks[source] |= (1<<target); collisionlinks[source] |= (1 << target);
if (source != target) collisionlinks[target] |= (1<<source); if (source != target)
collisionlinks[target] |= (1 << source);
} }
void removeCollisionLink(int source, int target){ void removeCollisionLink(int source, int target) {
collisionlinks[source] &= ~(1<<target); collisionlinks[source] &= ~(1 << target);
if (source != target) collisionlinks[target] &= ~(1<<source); if (source != target)
collisionlinks[target] &= ~(1 << source);
} }
bool isCollisionLink(int source, int target){ bool isCollisionLink(int source, int target) {
if (collisionlinks[source] & (1<<target)) return true; if (collisionlinks[source] & (1 << target))
return true;
return false; return false;
} }
void addCollision(Object *source, Object *target, void addCollision(Object *source, Object *target, float *normal,
float *normal, float *contactpoint){ float *contactpoint) {
if (contactcount == MAXCONTACTS){ if (contactcount == MAXCONTACTS) {
printf("Too many contacts!\n"); printf("Too many contacts!\n");
return; return;
} }
@ -61,7 +63,7 @@ void addCollision(Object *source, Object *target,
#define KINETICFRICTION 0.4 #define KINETICFRICTION 0.4
bool handleCollision(Contact *contact){ bool handleCollision(Contact *contact) {
Object *source = contact->object1; Object *source = contact->object1;
Object *target = contact->object2; Object *target = contact->object2;
float *normal = contact->normal; float *normal = contact->normal;
@ -73,10 +75,10 @@ bool handleCollision(Contact *contact){
vectorSub(sourcecontactpoint, contactpoint, source->position); vectorSub(sourcecontactpoint, contactpoint, source->position);
source->getVelocity(sourcevelocity, sourcecontactpoint); source->getVelocity(sourcevelocity, sourcecontactpoint);
if (target == NULL){ if (target == NULL) {
vectorSet(targetcontactpoint, 0, 0, 0); vectorSet(targetcontactpoint, 0, 0, 0);
vectorSet(targetvelocity, 0, 0, 0); vectorSet(targetvelocity, 0, 0, 0);
} else{ } else {
vectorSub(targetcontactpoint, contactpoint, target->position); vectorSub(targetcontactpoint, contactpoint, target->position);
target->getVelocity(targetvelocity, targetcontactpoint); target->getVelocity(targetvelocity, targetcontactpoint);
} }
@ -85,23 +87,25 @@ bool handleCollision(Contact *contact){
vectorSub(deltavelocity, sourcevelocity, targetvelocity); vectorSub(deltavelocity, sourcevelocity, targetvelocity);
float dot = vectorDot(deltavelocity, normal); float dot = vectorDot(deltavelocity, normal);
//if (fabs(dot) < EPSILON) return false; // if (fabs(dot) < EPSILON) return false;
//if (dot > -1.0e-5 && dot < 1.0e-5) return false; // if (dot > -1.0e-5 && dot < 1.0e-5) return false;
//if (dot >= 0) return false; // if (dot >= 0) return false;
if (dot > -1.0e-5) return false; if (dot > -1.0e-5)
return false;
float invmass1; float invmass1;
invmass1 = source->invmass; invmass1 = source->invmass;
float invmass2; float invmass2;
if (target == NULL) invmass2 = 0; if (target == NULL)
else invmass2 = target->invmass; invmass2 = 0;
else
invmass2 = target->invmass;
float t1; float t1;
if (source->invmomentofinertia == 0){ if (source->invmomentofinertia == 0) {
t1 = 0; t1 = 0;
} else{ } else {
float v1[3]; float v1[3];
vectorCross(v1, sourcecontactpoint, normal); vectorCross(v1, sourcecontactpoint, normal);
vectorScale(v1, source->invmomentofinertia); vectorScale(v1, source->invmomentofinertia);
@ -111,9 +115,9 @@ bool handleCollision(Contact *contact){
} }
float t2; float t2;
if (target == NULL || target->invmomentofinertia == 0){ if (target == NULL || target->invmomentofinertia == 0) {
t2 = 0; t2 = 0;
} else{ } else {
float v1[3]; float v1[3];
vectorCross(v1, targetcontactpoint, normal); vectorCross(v1, targetcontactpoint, normal);
vectorScale(v1, target->invmomentofinertia); vectorScale(v1, target->invmomentofinertia);
@ -128,24 +132,23 @@ bool handleCollision(Contact *contact){
float impulsesize = (1 + e) * dot / denominator; float impulsesize = (1 + e) * dot / denominator;
//printf("%f\n", impulsesize); // printf("%f\n", impulsesize);
float impulse[3]; float impulse[3];
vectorScale(impulse, normal, impulsesize); vectorScale(impulse, normal, impulsesize);
float friction[3]; float friction[3];
vectorScale(friction, normal, vectorDot(deltavelocity, normal)); vectorScale(friction, normal, vectorDot(deltavelocity, normal));
vectorAdd(friction, deltavelocity); vectorAdd(friction, deltavelocity);
vectorNormalize(friction); vectorNormalize(friction);
float frictionsize = 10*KINETICFRICTION*dot/denominator; float frictionsize = 10 * KINETICFRICTION * dot / denominator;
float maxfrictionsize = 0.1*vectorLength(deltavelocity); float maxfrictionsize = 0.1 * vectorLength(deltavelocity);
if (frictionsize < -maxfrictionsize) frictionsize = -maxfrictionsize; if (frictionsize < -maxfrictionsize)
frictionsize = -maxfrictionsize;
vectorScale(friction, -frictionsize); vectorScale(friction, -frictionsize);
vectorAdd(impulse, friction); vectorAdd(impulse, friction);
if (target != NULL) {
if (target != NULL){
target->addImpulse(impulse, targetcontactpoint); target->addImpulse(impulse, targetcontactpoint);
target->calculateStateVariables(); target->calculateStateVariables();
} }
@ -153,51 +156,49 @@ bool handleCollision(Contact *contact){
float speed; float speed;
float speed2[3]; float speed2[3];
if (target != NULL && source != NULL){ if (target != NULL && source != NULL) {
//float kvel[3]; // float kvel[3];
//source->getVelocity(kvel); // source->getVelocity(kvel);
float k = vectorLength(sourcevelocity)*0.1; float k = vectorLength(sourcevelocity) * 0.1;
//if (k > 1) k = 1; // if (k > 1) k = 1;
speed = -impulsesize*target->invmass*k; speed = -impulsesize * target->invmass * k;
vectorScale(speed2, impulse, target->invmass*k); vectorScale(speed2, impulse, target->invmass * k);
/*float kvel[3]; /*float kvel[3];
source->getVelocity(kvel); source->getVelocity(kvel);
float k = 0;//vectorDot(speed2, kvel); float k = 0;//vectorDot(speed2, kvel);
if (k < EPSILON) k = 0; if (k < EPSILON) k = 0;
speed *= k; speed *= k;
vectorScale(speed2, k); vectorScale(speed2, k);
if (k > 0) */target->hitForce(speed, speed2, source); if (k > 0) */ target->hitForce(speed, speed2, source);
} }
vectorScale(impulse, -1); vectorScale(impulse, -1);
source->addImpulse(impulse, sourcecontactpoint); source->addImpulse(impulse, sourcecontactpoint);
source->calculateStateVariables(); source->calculateStateVariables();
//vectorScale(speed, source->invmass); // vectorScale(speed, source->invmass);
if (target != NULL && source != NULL){ if (target != NULL && source != NULL) {
//float kvel[3]; // float kvel[3];
//target->getVelocity(kvel); // target->getVelocity(kvel);
float k = vectorLength(targetvelocity)*0.1; float k = vectorLength(targetvelocity) * 0.1;
//if (k > 1) k = 1; // if (k > 1) k = 1;
speed = -impulsesize*source->invmass*k; speed = -impulsesize * source->invmass * k;
vectorScale(speed2, impulse, source->invmass*k); vectorScale(speed2, impulse, source->invmass * k);
/*float kvel[3]; /*float kvel[3];
target->getVelocity(kvel); target->getVelocity(kvel);
float k = 0;//vectorDot(speed2, kvel); float k = 0;//vectorDot(speed2, kvel);
if (k < EPSILON) k = 0; if (k < EPSILON) k = 0;
speed *= k; speed *= k;
vectorScale(speed2, k); vectorScale(speed2, k);
if (k > 0) */source->hitForce(speed, speed2, target); if (k > 0) */ source->hitForce(speed, speed2, target);
} }
return true; return true;
} }
bool handleLink(ObjectLink *link) {
bool handleLink(ObjectLink *link){ if (!link->enabled)
if (!link->enabled) return false; return false;
Object *source = link->object1; Object *source = link->object1;
Object *target = link->object2; Object *target = link->object2;
@ -213,7 +214,8 @@ bool handleLink(ObjectLink *link){
float strength = vectorDot(diff, diff); float strength = vectorDot(diff, diff);
if (strength < 1.0e-5) return false; if (strength < 1.0e-5)
return false;
float sourcevelocity[3], targetvelocity[3]; float sourcevelocity[3], targetvelocity[3];
float sourcecontactpoint[3], targetcontactpoint[3]; float sourcecontactpoint[3], targetcontactpoint[3];
@ -228,19 +230,18 @@ bool handleLink(ObjectLink *link){
vectorSub(deltavelocity, sourcevelocity, targetvelocity); vectorSub(deltavelocity, sourcevelocity, targetvelocity);
float dot = vectorDot(deltavelocity, normal); float dot = vectorDot(deltavelocity, normal);
//if (fabs(dot) < EPSILON) return false; // if (fabs(dot) < EPSILON) return false;
//if (dot > -1.0e-5 && dot < 1.0e-5) return false; // if (dot > -1.0e-5 && dot < 1.0e-5) return false;
//if (dot >= 0) return false; // if (dot >= 0) return false;
//if (dot > -1.0e-5) return false; // if (dot > -1.0e-5) return false;
float invmass1 = source->invmass; float invmass1 = source->invmass;
float invmass2 = target->invmass; float invmass2 = target->invmass;
float t1; float t1;
if (source->invmomentofinertia == 0){ if (source->invmomentofinertia == 0) {
t1 = 0; t1 = 0;
} else{ } else {
float v1[3]; float v1[3];
vectorCross(v1, sourcecontactpoint, normal); vectorCross(v1, sourcecontactpoint, normal);
vectorScale(v1, source->invmomentofinertia); vectorScale(v1, source->invmomentofinertia);
@ -250,9 +251,9 @@ bool handleLink(ObjectLink *link){
} }
float t2; float t2;
if (target->invmomentofinertia == 0){ if (target->invmomentofinertia == 0) {
t2 = 0; t2 = 0;
} else{ } else {
float v1[3]; float v1[3];
vectorCross(v1, targetcontactpoint, normal); vectorCross(v1, targetcontactpoint, normal);
vectorScale(v1, target->invmomentofinertia); vectorScale(v1, target->invmomentofinertia);
@ -263,14 +264,13 @@ bool handleLink(ObjectLink *link){
float denominator = invmass1 + invmass2 + t1 + t2; float denominator = invmass1 + invmass2 + t1 + t2;
float impulsesize = (dot + strength*100) / denominator; float impulsesize = (dot + strength * 100) / denominator;
//printf("%f\n", impulsesize); // printf("%f\n", impulsesize);
float impulse[3]; float impulse[3];
vectorScale(impulse, normal, impulsesize); vectorScale(impulse, normal, impulsesize);
target->addImpulse(impulse, targetcontactpoint); target->addImpulse(impulse, targetcontactpoint);
target->calculateStateVariables(); target->calculateStateVariables();
@ -278,12 +278,11 @@ bool handleLink(ObjectLink *link){
source->addImpulse(impulse, sourcecontactpoint); source->addImpulse(impulse, sourcecontactpoint);
source->calculateStateVariables(); source->calculateStateVariables();
return true; return true;
} }
bool checkCollisions(Object *object, float *contactnormal){ bool checkCollisions(Object *object, float *contactnormal) {
//bool collision = false; // bool collision = false;
int group = object->getCollisionGroup(); int group = object->getCollisionGroup();
int groups = collisionlinks[group]; int groups = collisionlinks[group];
group = 0; group = 0;
@ -311,10 +310,10 @@ bool checkCollisions(Object *object, float *contactnormal){
vectorSub(temp, object->momentum, oldmomentum); vectorSub(temp, object->momentum, oldmomentum);
vectorScale(temp, 1.0/DT); vectorScale(temp, 1.0/DT);
object->addForce(temp);*/ object->addForce(temp);*/
//vectorSub(object-> // vectorSub(object->
//vectorCopy(object->momentum, oldmomentum); // vectorCopy(object->momentum, oldmomentum);
//printf("%i\n", collisions); // printf("%i\n", collisions);
//vectorScale(object->force, 1.0/collisions); // vectorScale(object->force, 1.0/collisions);
/*if (collisions > 0){ /*if (collisions > 0){
vectorScale(object->force, 2.0/vectorLength(object->momentum)); vectorScale(object->force, 2.0/vectorLength(object->momentum));
}*/ }*/
@ -341,8 +340,9 @@ bool checkCollisions(Object *object, float *contactnormal){
} }
}*/ }*/
void collide(Object *source, Object *target, float *normal, float *contactpoint){ void collide(Object *source, Object *target, float *normal,
/* float momentum[3]; float *contactpoint) {
/* float momentum[3];
source->getMomentum(momentum); source->getMomentum(momentum);
float sourcevelocity[3], targetvelocity[3]; float sourcevelocity[3], targetvelocity[3];
@ -378,7 +378,8 @@ void collide(Object *source, Object *target, float *normal, float *contactpoint)
vectorCross(w1, v1, sourcecontactpoint); vectorCross(w1, v1, sourcecontactpoint);
t1 = vectorDot(normal, w1); t1 = vectorDot(normal, w1);
} }
//printf("S: %f, %f, %f\n", sourcecontactpoint[0], source->momentofinertia, v1); //printf("S: %f, %f, %f\n", sourcecontactpoint[0],
source->momentofinertia, v1);
float t2; float t2;
if (target->momentofinertia == 0){ if (target->momentofinertia == 0){
@ -391,19 +392,22 @@ void collide(Object *source, Object *target, float *normal, float *contactpoint)
vectorCross(w2, v2, targetcontactpoint); vectorCross(w2, v2, targetcontactpoint);
t2 = vectorDot(normal, w2); t2 = vectorDot(normal, w2);
} }
//printf("T: %f, %f, %f\n", targetcontactpoint[0], target->momentofinertia, v2); //printf("T: %f, %f, %f\n", targetcontactpoint[0],
target->momentofinertia, v2);
float divisor; float divisor;
divisor = massinverse1 + massinverse2;// + t1 + t2; divisor = massinverse1 + massinverse2;// + t1 + t2;
printf("%f, %f, %f, %f : %f\n", massinverse1, massinverse2, t1, t2, divisor); printf("%f, %f, %f, %f : %f\n", massinverse1, massinverse2, t1, t2,
divisor);
float impulsesize = -dot / divisor; float impulsesize = -dot / divisor;
float impulse[3]; float impulse[3];
vectorScale(impulse, normal, impulsesize); vectorScale(impulse, normal, impulsesize);
//collide(sourcevelocity, targetvelocity, sourcemass, targetmass, normal, impulse); //collide(sourcevelocity, targetvelocity, sourcemass, targetmass, normal,
impulse);
//vectorAdd(source->momentum, impulse); //vectorAdd(source->momentum, impulse);
@ -417,9 +421,8 @@ void collide(Object *source, Object *target, float *normal, float *contactpoint)
//source->addForce(force, sourcecontactpoint);*/ //source->addForce(force, sourcecontactpoint);*/
} }
bool checkSphereMeshCollision(float *sphereposition, float r, Mesh *mesh,
float *normal, float *contactpoint) {
bool checkSphereMeshCollision(float *sphereposition, float r, Mesh *mesh, float *normal, float *contactpoint){
float linenormal[3]; float linenormal[3];
float pointnormal[3]; float pointnormal[3];
float maxdist = 0; float maxdist = 0;
@ -429,20 +432,21 @@ bool checkSphereMeshCollision(float *sphereposition, float r, Mesh *mesh, float
int i, j; int i, j;
for (i = 0; i < mesh->polygoncount; i++){ for (i = 0; i < mesh->polygoncount; i++) {
class Polygon *polygon = &mesh->polygons[i]; class Polygon *polygon = &mesh->polygons[i];
float dist = distanceFromPlane(sphereposition, polygon->planenormal, polygon->planedistance); float dist = distanceFromPlane(sphereposition, polygon->planenormal,
if (dist < r && dist > -r){ polygon->planedistance);
if (dist < r && dist > -r) {
bool directcollision = true; bool directcollision = true;
for (j = 0; j < polygon->vertexcount; j++){ for (j = 0; j < polygon->vertexcount; j++) {
float *p1 = polygon->vertices[j]->position; float *p1 = polygon->vertices[j]->position;
float *p2 = polygon->vertices[(j+1)%polygon->vertexcount]->position; float *p2 = polygon->vertices[(j + 1) % polygon->vertexcount]->position;
float *p3 = polygon->vertices[(j+2)%polygon->vertexcount]->position; float *p3 = polygon->vertices[(j + 2) % polygon->vertexcount]->position;
float v1[3], v2[3]; float v1[3], v2[3];
vectorSub(v1, p2, p1); vectorSub(v1, p2, p1);
//Collision for polygon surface // Collision for polygon surface
vectorSub(v2, p3, p2); vectorSub(v2, p3, p2);
float t1[3]; float t1[3];
vectorProject(t1, v2, v1); vectorProject(t1, v2, v1);
@ -450,39 +454,41 @@ bool checkSphereMeshCollision(float *sphereposition, float r, Mesh *mesh, float
vectorSub(norm, v2, t1); vectorSub(norm, v2, t1);
vectorNormalize(norm); vectorNormalize(norm);
//Collision for polygon edges // Collision for polygon edges
float newpoint[3]; float newpoint[3];
vectorSub(newpoint, sphereposition, p1); vectorSub(newpoint, sphereposition, p1);
float dist2 = vectorDot(newpoint, norm); float dist2 = vectorDot(newpoint, norm);
if (dist2 < 0){ if (dist2 < 0) {
directcollision = false; directcollision = false;
float projloc = vectorDot(newpoint, v1) / vectorDot(v1, v1); float projloc = vectorDot(newpoint, v1) / vectorDot(v1, v1);
if (projloc >= 0 && projloc <= 1){ if (projloc >= 0 && projloc <= 1) {
float proj[3]; float proj[3];
vectorScale(proj, v1, projloc); vectorScale(proj, v1, projloc);
float projorth[3]; float projorth[3];
vectorSub(projorth, newpoint, proj); vectorSub(projorth, newpoint, proj);
float l2 = vectorDot(projorth, projorth); float l2 = vectorDot(projorth, projorth);
if (l2 < r*r){ if (l2 < r * r) {
vectorNormalize(linenormal, projorth); vectorNormalize(linenormal, projorth);
if (dist < 0) vectorScale(linenormal, -1); if (dist < 0)
vectorScale(linenormal, -1);
linecollision = true; linecollision = true;
} }
} }
} }
//Collision for polygon vertices // Collision for polygon vertices
float pointdiff[3]; float pointdiff[3];
vectorSub(pointdiff, sphereposition, p1); vectorSub(pointdiff, sphereposition, p1);
float l3 = vectorDot(pointdiff, pointdiff); float l3 = vectorDot(pointdiff, pointdiff);
if (l3 < r*r){ if (l3 < r * r) {
vectorScale(pointnormal, pointdiff, 1.0 / sqrt(l3)); vectorScale(pointnormal, pointdiff, 1.0 / sqrt(l3));
if (dist < 0) vectorScale(pointnormal, -1); if (dist < 0)
vectorScale(pointnormal, -1);
pointcollision = true; pointcollision = true;
} }
} }
if (directcollision){ if (directcollision) {
if (dist > maxdist || !planecollision){ if (dist > maxdist || !planecollision) {
vectorCopy(normal, polygon->planenormal); vectorCopy(normal, polygon->planenormal);
maxdist = dist; maxdist = dist;
planecollision = true; planecollision = true;
@ -491,39 +497,37 @@ bool checkSphereMeshCollision(float *sphereposition, float r, Mesh *mesh, float
} }
} }
if (planecollision){ if (planecollision) {
vectorScale(contactpoint, normal, -r); vectorScale(contactpoint, normal, -r);
vectorAdd(contactpoint, sphereposition); vectorAdd(contactpoint, sphereposition);
} else if (linecollision){ } else if (linecollision) {
vectorScale(contactpoint, linenormal, -r); vectorScale(contactpoint, linenormal, -r);
vectorAdd(contactpoint, sphereposition); vectorAdd(contactpoint, sphereposition);
vectorCopy(normal, linenormal); vectorCopy(normal, linenormal);
} else if (pointcollision){ } else if (pointcollision) {
vectorScale(contactpoint, pointnormal, -r); vectorScale(contactpoint, pointnormal, -r);
vectorAdd(contactpoint, sphereposition); vectorAdd(contactpoint, sphereposition);
vectorCopy(normal, pointnormal); vectorCopy(normal, pointnormal);
} else{ } else {
return false; return false;
} }
return true; return true;
} }
bool checkPointMeshCollision(float *position, Mesh *mesh, float *normal,
float *contactpoint) {
bool checkPointMeshCollision(float *position, Mesh *mesh, float *normal, float *contactpoint){
float maxdist = 0; float maxdist = 0;
bool planecollision = false; bool planecollision = false;
int i; int i;
for (i = 0; i < mesh->polygoncount; i++){ for (i = 0; i < mesh->polygoncount; i++) {
class Polygon *polygon = &mesh->polygons[i]; class Polygon *polygon = &mesh->polygons[i];
float dist = distanceFromPlane(position, polygon->planenormal, polygon->planedistance); float dist = distanceFromPlane(position, polygon->planenormal,
if (dist < 0){ polygon->planedistance);
if (dist < 0) {
bool directcollision = true; bool directcollision = true;
/*for (j = 0; j < polygon->vertexcount; j++){ /*for (j = 0; j < polygon->vertexcount; j++){
float *p1 = polygon->vertices[j]->position; float *p1 = polygon->vertices[j]->position;
@ -546,21 +550,21 @@ bool checkPointMeshCollision(float *position, Mesh *mesh, float *normal, float *
float dist2 = vectorDot(newpoint, norm); float dist2 = vectorDot(newpoint, norm);
if (dist2 < 0) directcollision = false; if (dist2 < 0) directcollision = false;
}*/ }*/
if (directcollision){ if (directcollision) {
if (dist > maxdist || !planecollision){ if (dist > maxdist || !planecollision) {
vectorCopy(normal, polygon->planenormal); vectorCopy(normal, polygon->planenormal);
maxdist = dist; maxdist = dist;
planecollision = true; planecollision = true;
} }
} }
} else{ } else {
return false; return false;
} }
} }
if (planecollision){ if (planecollision) {
vectorCopy(contactpoint, position); vectorCopy(contactpoint, position);
} else{ } else {
return false; return false;
} }
@ -569,39 +573,43 @@ bool checkPointMeshCollision(float *position, Mesh *mesh, float *normal, float *
#define MAXPOLYGONS 1000 #define MAXPOLYGONS 1000
struct tracehit{ struct tracehit {
float t; float t;
Polygon *polygon; Polygon *polygon;
}; };
bool tracePlane(tracehit *result, float *origin, float *ray, class Polygon *polygon){ bool tracePlane(tracehit *result, float *origin, float *ray,
class Polygon *polygon) {
float *normal = polygon->planenormal; float *normal = polygon->planenormal;
float D = polygon->planedistance; float D = polygon->planedistance;
float denominator = vectorDot(normal, ray); float denominator = vectorDot(normal, ray);
if (denominator == 0){ if (denominator == 0) {
if (vectorDot(normal, origin) > 0) result->t = 1000000; if (vectorDot(normal, origin) > 0)
else result->t = -1000000; result->t = 1000000;
else
result->t = -1000000;
result->polygon = polygon; result->polygon = polygon;
return true; return true;
} }
float t = - (vectorDot(normal, origin) + D) / denominator; float t = -(vectorDot(normal, origin) + D) / denominator;
result->t = t; result->t = t;
result->polygon = polygon; result->polygon = polygon;
//if (t < 0 || t > 1) return false; // if (t < 0 || t > 1) return false;
return true; return true;
} }
Edge *findSharingEdge(class Polygon *p1, class Polygon *p2){ Edge *findSharingEdge(class Polygon *p1, class Polygon *p2) {
//printf("Edges:\n"); // printf("Edges:\n");
int i, j; int i, j;
for (i = 0; i < p1->vertexcount; i++){ for (i = 0; i < p1->vertexcount; i++) {
//printf("%p\n", p1->edges[i]); // printf("%p\n", p1->edges[i]);
for (j = 0; j < p2->vertexcount; j++){ for (j = 0; j < p2->vertexcount; j++) {
if (p1->edges[i] == p2->edges[j]) return p1->edges[i]; if (p1->edges[i] == p2->edges[j])
return p1->edges[i];
} }
} }
return NULL; return NULL;
@ -618,17 +626,20 @@ Edge *findSharingEdge(class Polygon *p1, class Polygon *p2){
} }
return NULL; return NULL;
}*/ }*/
Polygon *findNearestPolygon(class Polygon *polygon, float *point){ Polygon *findNearestPolygon(class Polygon *polygon, float *point) {
int i; int i;
float mindist = 0; float mindist = 0;
Polygon *nearestpolygon = NULL; Polygon *nearestpolygon = NULL;
for (i = 0; i < polygon->edgecount; i++){ for (i = 0; i < polygon->edgecount; i++) {
Edge *edge = polygon->edges[i]; Edge *edge = polygon->edges[i];
Polygon *polygon2 = edge->p1; Polygon *polygon2 = edge->p1;
if (polygon2 == polygon) polygon2 = edge->p2; if (polygon2 == polygon)
float newdist = distanceFromPlane(point, polygon2->planenormal, polygon2->planedistance); polygon2 = edge->p2;
if (newdist > 0) return NULL; float newdist = distanceFromPlane(point, polygon2->planenormal,
if (mindist == 0 || newdist > mindist){ polygon2->planedistance);
if (newdist > 0)
return NULL;
if (mindist == 0 || newdist > mindist) {
mindist = newdist; mindist = newdist;
nearestpolygon = polygon2; nearestpolygon = polygon2;
} }
@ -636,7 +647,8 @@ Polygon *findNearestPolygon(class Polygon *polygon, float *point){
return nearestpolygon; return nearestpolygon;
} }
bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal, float *contactpoint){ bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal,
float *contactpoint) {
float ray[3]; float ray[3];
vectorSub(ray, p2, p1); vectorSub(ray, p2, p1);
@ -648,45 +660,50 @@ bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal, flo
tracehit hits[MAXPOLYGONS]; tracehit hits[MAXPOLYGONS];
int hitcount = 0; int hitcount = 0;
for (i = 0; i < mesh->polygoncount; i++){ for (i = 0; i < mesh->polygoncount; i++) {
class Polygon *polygon = &mesh->polygons[i]; class Polygon *polygon = &mesh->polygons[i];
if (tracePlane(&hits[hitcount], p1, ray, polygon)){ if (tracePlane(&hits[hitcount], p1, ray, polygon)) {
hitcount++; hitcount++;
} }
} }
if (hitcount < 2) return false; if (hitcount < 2)
return false;
for (i = 1; i < hitcount; i++){ for (i = 1; i < hitcount; i++) {
for (j = i; j > 0; j--){ for (j = i; j > 0; j--) {
if (hits[j].t < hits[j-1].t){ if (hits[j].t < hits[j - 1].t) {
float tempt = hits[j].t; float tempt = hits[j].t;
hits[j].t = hits[j-1].t; hits[j].t = hits[j - 1].t;
hits[j-1].t = tempt; hits[j - 1].t = tempt;
class Polygon *tempp = hits[j].polygon; class Polygon *tempp = hits[j].polygon;
hits[j].polygon = hits[j-1].polygon; hits[j].polygon = hits[j - 1].polygon;
hits[j-1].polygon = tempp; hits[j - 1].polygon = tempp;
} else break; } else
break;
} }
} }
int negative = -1, positive = -1; int negative = -1, positive = -1;
for (i = 0; i < hitcount; i++) {
for (i = 0; i < hitcount; i++){
float t = hits[i].t; float t = hits[i].t;
class Polygon *polygon = hits[i].polygon; class Polygon *polygon = hits[i].polygon;
float dot = vectorDot(ray, polygon->planenormal); float dot = vectorDot(ray, polygon->planenormal);
if (dot > 0 && positive == -1) positive = i; if (dot > 0 && positive == -1)
if (dot < 0) negative = i; positive = i;
if (dot < 0)
negative = i;
if (dot < 0 && positive != -1) return false; if (dot < 0 && positive != -1)
return false;
} }
if (negative == -1 || positive == -1) return false; if (negative == -1 || positive == -1)
return false;
/*for (i = 0; i < hitcount; i++){ /*for (i = 0; i < hitcount; i++){
float t = hits[i].t; float t = hits[i].t;
@ -698,18 +715,19 @@ bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal, flo
} }
printf("\n");*/ printf("\n");*/
if (hits[negative].t < 0 || hits[positive].t > 1) return false; if (hits[negative].t < 0 || hits[positive].t > 1)
return false;
Edge *edge2 = findSharingEdge(hits[negative].polygon, hits[positive].polygon); Edge *edge2 = findSharingEdge(hits[negative].polygon, hits[positive].polygon);
//fflush(stdout); // fflush(stdout);
float cp1[3], cp2[3]; float cp1[3], cp2[3];
vectorScale(cp1, ray, hits[negative].t); vectorScale(cp1, ray, hits[negative].t);
vectorAdd(cp1, p1); vectorAdd(cp1, p1);
vectorScale(cp2, ray, hits[positive].t); vectorScale(cp2, ray, hits[positive].t);
vectorAdd(cp2, p1); vectorAdd(cp2, p1);
if (edge2 != NULL){ if (edge2 != NULL) {
/*float ev1[3]; /*float ev1[3];
vectorSub(ev1, edge2->v2->position, edge2->v1->position); vectorSub(ev1, edge2->v2->position, edge2->v1->position);
@ -724,20 +742,20 @@ bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal, flo
float dot1 = fabs(vectorDot(ray, hits[negative].polygon->planenormal)); float dot1 = fabs(vectorDot(ray, hits[negative].polygon->planenormal));
float dot2 = fabs(vectorDot(ray, hits[positive].polygon->planenormal)); float dot2 = fabs(vectorDot(ray, hits[positive].polygon->planenormal));
if (dot1 > dot2){ if (dot1 > dot2) {
//vectorScale(contactpoint, ray, hits[negative].t); // vectorScale(contactpoint, ray, hits[negative].t);
//vectorAdd(contactpoint, p1); // vectorAdd(contactpoint, p1);
vectorCopy(contactpoint, cp1); vectorCopy(contactpoint, cp1);
vectorCopy(normal, hits[positive].polygon->planenormal); vectorCopy(normal, hits[positive].polygon->planenormal);
} else{ } else {
//vectorScale(contactpoint, ray, hits[positive].t); // vectorScale(contactpoint, ray, hits[positive].t);
//vectorAdd(contactpoint, p1); // vectorAdd(contactpoint, p1);
vectorCopy(contactpoint, cp2); vectorCopy(contactpoint, cp2);
vectorCopy(normal, hits[negative].polygon->planenormal); vectorCopy(normal, hits[negative].polygon->planenormal);
} }
} else{ } else {
Polygon *polygon = findNearestPolygon(hits[negative].polygon, cp1); Polygon *polygon = findNearestPolygon(hits[negative].polygon, cp1);
if (polygon != NULL){ if (polygon != NULL) {
/*vectorCopy(contactpoint, cp1); /*vectorCopy(contactpoint, cp1);
vectorAdd(contactpoint, cp2); vectorAdd(contactpoint, cp2);
vectorScale(contactpoint, 0.5);*/ vectorScale(contactpoint, 0.5);*/
@ -746,12 +764,11 @@ bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal, flo
vectorAdd(contactpoint, p1); vectorAdd(contactpoint, p1);
vectorCopy(normal, polygon->planenormal); vectorCopy(normal, polygon->planenormal);
} else{ } else {
return false; return false;
} }
} }
// shotsound->play();
//shotsound->play();
return true; return true;
} }

View file

@ -16,12 +16,12 @@ class ObjectLink;
#define COLLISIONFRICTION 0.9 #define COLLISIONFRICTION 0.9
void initCollisions(void); void initCollisions(void);
//void addCollisionObject(Object *object, int group); // void addCollisionObject(Object *object, int group);
void addCollisionLink(int source, int target); void addCollisionLink(int source, int target);
void removeCollisionLink(int source, int target); void removeCollisionLink(int source, int target);
bool isCollisionLink(int source, int target); bool isCollisionLink(int source, int target);
class Contact{ class Contact {
public: public:
Object *object1, *object2; Object *object1, *object2;
float normal[3]; float normal[3];
@ -31,17 +31,18 @@ public:
extern Contact *contacts; extern Contact *contacts;
extern int contactcount; extern int contactcount;
// Contact point is world-relative and must be transformed
//Contact point is world-relative and must be transformed // into coordinate system of both objects
//into coordinate system of both objects void addCollision(Object *source, Object *target, float *normal,
void addCollision(Object *source, Object *target, float *contactpoint);
float *normal, float *contactpoint);
bool handleCollision(Contact *contact); bool handleCollision(Contact *contact);
bool handleLink(ObjectLink *link); bool handleLink(ObjectLink *link);
bool checkSphereMeshCollision(float *sphereposition, float r, Mesh *mesh, float *normal, float *contactpoint); bool checkSphereMeshCollision(float *sphereposition, float r, Mesh *mesh,
bool checkPointMeshCollision(float *position, Mesh *mesh, float *normal, float *contactpoint); float *normal, float *contactpoint);
bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal, float *contactpoint); bool checkPointMeshCollision(float *position, Mesh *mesh, float *normal,
float *contactpoint);
bool checkEdgeMeshCollision(float *p1, float *p2, Mesh *mesh, float *normal,
float *contactpoint);
#endif #endif

View file

@ -27,13 +27,13 @@
Camera endcamera; Camera endcamera;
Light endlight, endlight2; Light endlight, endlight2;
//BasicBlockAppearance *endfloor = new BasicBlockAppearance(100, 1, 100); // BasicBlockAppearance *endfloor = new BasicBlockAppearance(100, 1, 100);
BasicBlock *endfloor;// = new BasicBlock(20, 1, 15); BasicBlock *endfloor; // = new BasicBlock(20, 1, 15);
void initEnd(void){ void initEnd(void) {
endlight.setColor(1, 1, 1); endlight.setColor(1, 1, 1);
endlight.setSpecular(1, 1, 1); endlight.setSpecular(1, 1, 1);
endlight.setPosition(-0.5, BLOCKHEIGHT*16, 0.5); endlight.setPosition(-0.5, BLOCKHEIGHT * 16, 0.5);
endlight.setAttenuation(0, 0.0, 0.005); endlight.setAttenuation(0, 0.0, 0.005);
endlight2.setColor(1, 1, 1); endlight2.setColor(1, 1, 1);
@ -41,21 +41,21 @@ void initEnd(void){
endlight2.setAttenuation(1.0, 0.0, 0.0); endlight2.setAttenuation(1.0, 0.0, 0.0);
endfloor = new BasicBlock(30, 1, 20); endfloor = new BasicBlock(30, 1, 20);
//endfloor->material.setColor(0, 1, 0, 1); // endfloor->material.setColor(0, 1, 0, 1);
endfloor->setColor(0, 1, 0); endfloor->setColor(0, 1, 0);
endfloor->setPosition(-10, -BLOCKHEIGHT*0.5, 0); endfloor->setPosition(-10, -BLOCKHEIGHT * 0.5, 0);
endfloor->prepare(); endfloor->prepare();
} }
int endingcounter; int endingcounter;
void endRestart(void){ void endRestart(void) {
endingcounter = 0; endingcounter = 0;
//initEnd(); // initEnd();
//endfloor->prepare(); // endfloor->prepare();
} }
void stopEnding(void){ void stopEnding(void) {
endlight.setEnabled(false); endlight.setEnabled(false);
changeGameMode(MENUMODE); changeGameMode(MENUMODE);
fightmusic->fadeOut(300); fightmusic->fadeOut(300);
@ -64,31 +64,35 @@ void stopEnding(void){
float endfade; float endfade;
void calculateEnd(int framecount){ void calculateEnd(int framecount) {
endfade = -1; endfade = -1;
if (endingcounter < 200){ if (endingcounter < 200) {
endfade = 1-(float)endingcounter/200; endfade = 1 - (float)endingcounter / 200;
} }
endingcounter++; endingcounter++;
endlight.setEnabled(true); endlight.setEnabled(true);
//endlight2.setEnabled(true); // endlight2.setEnabled(true);
float target[3] = {0, 13, 0}; float target[3] = {0, 13, 0};
endcamera.setTarget(target); endcamera.setTarget(target);
endcamera.setPosition(10+sin(framecount*0.002)*2, 20+sin(framecount*0.0017)*2, 25+cos(framecount*0.002)*2); endcamera.setPosition(10 + sin(framecount * 0.002) * 2,
//endcamera.setPosition(sin(framecount*0.01)*25, sin(framecount*0.007)*6+20, cos(framecount*0.01)*25); 20 + sin(framecount * 0.0017) * 2,
25 + cos(framecount * 0.002) * 2);
// endcamera.setPosition(sin(framecount*0.01)*25, sin(framecount*0.007)*6+20,
// cos(framecount*0.01)*25);
//endlight.setPosition(40, 20, 0); // endlight.setPosition(40, 20, 0);
endlight.setPosition(-sin(framecount*0.007)*10, 15, cos(framecount*0.007)*2+22); endlight.setPosition(-sin(framecount * 0.007) * 10, 15,
cos(framecount * 0.007) * 2 + 22);
if (keys[SDLK_ESCAPE]){ if (keys[SDLK_ESCAPE]) {
stopEnding(); stopEnding();
} }
} }
void drawEnd(int framecount){ void drawEnd(int framecount) {
glLoadIdentity(); glLoadIdentity();
glTranslatef(10, 0, 0); glTranslatef(10, 0, 0);
@ -108,7 +112,7 @@ void drawEnd(int framecount){
drawTrophy(); drawTrophy();
glRotatef(270, 0, 1, 0); glRotatef(270, 0, 1, 0);
glTranslatef(2-BLOCKHEIGHT*0.5, 0, 15-BLOCKHEIGHT*0.5); glTranslatef(2 - BLOCKHEIGHT * 0.5, 0, 15 - BLOCKHEIGHT * 0.5);
glScalef(3, 3, 3); glScalef(3, 3, 3);
winner->head->draw(); winner->head->draw();
@ -119,16 +123,16 @@ void drawEnd(int framecount){
winner->leftleg->draw(); winner->leftleg->draw();
winner->rightleg->draw(); winner->rightleg->draw();
enable2D(); enable2D();
glColor3f(1, 1, 1); glColor3f(1, 1, 1);
if (winner->side == PLAYER1) print(0.05, 0.05, "Player 1 is\nthe winner", 0.09); if (winner->side == PLAYER1)
if (winner->side == PLAYER2) print(0.05, 0.05, "Player 2 is\nthe winner", 0.09); print(0.05, 0.05, "Player 1 is\nthe winner", 0.09);
if (winner->side == PLAYER2)
print(0.05, 0.05, "Player 2 is\nthe winner", 0.09);
if (endfade != -1) {
if (endfade != -1){
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0, 0, 0, endfade); glColor4f(0, 0, 0, endfade);

View file

@ -6,11 +6,9 @@
#include "texture.h" #include "texture.h"
#include "audio.h" #include "audio.h"
void initEnd(void); void initEnd(void);
void endRestart(void); void endRestart(void);
void calculateEnd(int framecount); void calculateEnd(int framecount);
void drawEnd(int framecount); void drawEnd(int framecount);
#endif #endif

View file

@ -46,212 +46,216 @@ int points1, points2;
bool fightinitialized = false; bool fightinitialized = false;
void initFight(void){ void initFight(void) {
if (!fightinitialized){ if (!fightinitialized) {
initCollisions(); initCollisions();
addCollisionLink(COLLISIONGROUP_ARENA, COLLISIONGROUP_PARTICLE); addCollisionLink(COLLISIONGROUP_ARENA, COLLISIONGROUP_PARTICLE);
//addCollisionLink(COLLISIONGROUP_PARTICLE, COLLISIONGROUP_PARTICLE); // addCollisionLink(COLLISIONGROUP_PARTICLE, COLLISIONGROUP_PARTICLE);
addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_ARENA); addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_ARENA);
//addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_PARTICLE); // addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_PARTICLE);
addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_MAN1); addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_MAN1);
addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_ARENA); addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_ARENA);
//addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_PARTICLE); // addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_PARTICLE);
addCollisionLink(COLLISIONGROUP_MAN2, COLLISIONGROUP_ARENA); addCollisionLink(COLLISIONGROUP_MAN2, COLLISIONGROUP_ARENA);
//addCollisionLink(COLLISIONGROUP_MAN2, COLLISIONGROUP_PARTICLE); // addCollisionLink(COLLISIONGROUP_MAN2, COLLISIONGROUP_PARTICLE);
addCollisionLink(COLLISIONGROUP_MAN2, COLLISIONGROUP_MAN2); addCollisionLink(COLLISIONGROUP_MAN2, COLLISIONGROUP_MAN2);
addCollisionLink(COLLISIONGROUP_MAN2HAND, COLLISIONGROUP_ARENA); addCollisionLink(COLLISIONGROUP_MAN2HAND, COLLISIONGROUP_ARENA);
//addCollisionLink(COLLISIONGROUP_MAN2HAND, COLLISIONGROUP_PARTICLE); // addCollisionLink(COLLISIONGROUP_MAN2HAND, COLLISIONGROUP_PARTICLE);
addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_MAN2); addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_MAN2);
addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_MAN2HAND); addCollisionLink(COLLISIONGROUP_MAN1, COLLISIONGROUP_MAN2HAND);
addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_MAN2); addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_MAN2);
addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_MAN2HAND); addCollisionLink(COLLISIONGROUP_MAN1HAND, COLLISIONGROUP_MAN2HAND);
//Sound* backgroundsong = new Sound("mixdown.mp3"); // Sound* backgroundsong = new Sound("mixdown.mp3");
Sound* backgroundsong = new Sound(BGSONG, true); Sound *backgroundsong = new Sound(BGSONG, true);
camera.setPosition(-5, 8, 18); camera.setPosition(-5, 8, 18);
arenaworld = new World(); arenaworld = new World();
// arenalight.setEnabled(true);
//arenalight.setEnabled(true);
/*arenalight.setPosition(0, 10, 0); /*arenalight.setPosition(0, 10, 0);
Object *lamp = new Object(); Object *lamp = new Object();
lamp->appearance = new LampAppearance(); lamp->appearance = new LampAppearance();
lamp->setPosition(0, 10, 0); lamp->setPosition(0, 10, 0);
arenaworld->addChild(lamp);*/ arenaworld->addChild(lamp);*/
} }
light1.setColor(1, 1, 1); light1.setColor(1, 1, 1);
light1.setSpecular(1, 1, 1); light1.setSpecular(1, 1, 1);
light1.setPosition(-ARENASIZE+0.5, 5, -ARENASIZE+0.5); light1.setPosition(-ARENASIZE + 0.5, 5, -ARENASIZE + 0.5);
light1.setAttenuation(0.2, 0.0, 0.02); light1.setAttenuation(0.2, 0.0, 0.02);
light2.setColor(1, 1, 1); light2.setColor(1, 1, 1);
light2.setSpecular(1, 1, 1); light2.setSpecular(1, 1, 1);
light2.setPosition(ARENASIZE-0.5, 5, -ARENASIZE+0.5); light2.setPosition(ARENASIZE - 0.5, 5, -ARENASIZE + 0.5);
light2.setAttenuation(0.2, 0.0, 0.02); light2.setAttenuation(0.2, 0.0, 0.02);
light3.setColor(1, 1, 1); light3.setColor(1, 1, 1);
light3.setSpecular(1, 1, 1); light3.setSpecular(1, 1, 1);
light3.setPosition(-ARENASIZE+0.5, 5, ARENASIZE-0.5); light3.setPosition(-ARENASIZE + 0.5, 5, ARENASIZE - 0.5);
light3.setAttenuation(0.2, 0.0, 0.02); light3.setAttenuation(0.2, 0.0, 0.02);
light4.setColor(1, 1, 1); light4.setColor(1, 1, 1);
light4.setSpecular(1, 1, 1); light4.setSpecular(1, 1, 1);
light4.setPosition(ARENASIZE-0.5, 5, ARENASIZE-0.5); light4.setPosition(ARENASIZE - 0.5, 5, ARENASIZE - 0.5);
light4.setAttenuation(0.2, 0.0, 0.02); light4.setAttenuation(0.2, 0.0, 0.02);
if (!fightinitialized) {
if (!fightinitialized){
Object *lamp; Object *lamp;
lamp = new Object(); lamp = new Object();
lamp->appearance = new LampAppearance(); lamp->appearance = new LampAppearance();
lamp->setPosition(-ARENASIZE+0.5, (ARENAHEIGHT+0.5)*BLOCKHEIGHT, -ARENASIZE+0.5); lamp->setPosition(-ARENASIZE + 0.5, (ARENAHEIGHT + 0.5) * BLOCKHEIGHT,
-ARENASIZE + 0.5);
arenaworld->addChild(lamp); arenaworld->addChild(lamp);
lamp = new Object(); lamp = new Object();
lamp->appearance = new LampAppearance(); lamp->appearance = new LampAppearance();
lamp->setPosition(ARENASIZE-0.5, (ARENAHEIGHT+0.5)*BLOCKHEIGHT, -ARENASIZE+0.5); lamp->setPosition(ARENASIZE - 0.5, (ARENAHEIGHT + 0.5) * BLOCKHEIGHT,
-ARENASIZE + 0.5);
arenaworld->addChild(lamp); arenaworld->addChild(lamp);
lamp = new Object(); lamp = new Object();
lamp->appearance = new LampAppearance(); lamp->appearance = new LampAppearance();
lamp->setPosition(-ARENASIZE+0.5, (ARENAHEIGHT+0.5)*BLOCKHEIGHT, ARENASIZE-0.5); lamp->setPosition(-ARENASIZE + 0.5, (ARENAHEIGHT + 0.5) * BLOCKHEIGHT,
ARENASIZE - 0.5);
arenaworld->addChild(lamp); arenaworld->addChild(lamp);
lamp = new Object(); lamp = new Object();
lamp->appearance = new LampAppearance(); lamp->appearance = new LampAppearance();
lamp->setPosition(ARENASIZE-0.5, (ARENAHEIGHT+0.5)*BLOCKHEIGHT, ARENASIZE-0.5); lamp->setPosition(ARENASIZE - 0.5, (ARENAHEIGHT + 0.5) * BLOCKHEIGHT,
ARENASIZE - 0.5);
arenaworld->addChild(lamp); arenaworld->addChild(lamp);
// Floor
//Floor
BasicBlock *floorblock; BasicBlock *floorblock;
floorblock = new BasicBlock(ARENASIZE*2, 3, ARENASIZE*2); floorblock = new BasicBlock(ARENASIZE * 2, 3, ARENASIZE * 2);
floorblock->setPosition(0, -BLOCKHEIGHT*3/2.0, 0); floorblock->setPosition(0, -BLOCKHEIGHT * 3 / 2.0, 0);
floorblock->setColor(0, 1, 0); floorblock->setColor(0, 1, 0);
floorblock->setCollisionGroup(COLLISIONGROUP_ARENA); floorblock->setCollisionGroup(COLLISIONGROUP_ARENA);
arenaworld->addChild(floorblock); arenaworld->addChild(floorblock);
// Corners
//Corners
BasicBlock *arenacorner; BasicBlock *arenacorner;
arenacorner = new BasicBlock(1, ARENAHEIGHT, 1); arenacorner = new BasicBlock(1, ARENAHEIGHT, 1);
arenacorner->setColor(1, 0, 0); arenacorner->setColor(1, 0, 0);
//arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA); // arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA);
arenacorner->setPosition(ARENASIZE-0.5, BLOCKHEIGHT*ARENAHEIGHT/2.0, ARENASIZE-0.5); arenacorner->setPosition(ARENASIZE - 0.5, BLOCKHEIGHT * ARENAHEIGHT / 2.0,
ARENASIZE - 0.5);
arenaworld->addChild(arenacorner); arenaworld->addChild(arenacorner);
arenacorner = new BasicBlock(1, ARENAHEIGHT, 1); arenacorner = new BasicBlock(1, ARENAHEIGHT, 1);
arenacorner->setColor(1, 0, 0); arenacorner->setColor(1, 0, 0);
//arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA); // arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA);
arenacorner->setPosition(-ARENASIZE+0.5, BLOCKHEIGHT*ARENAHEIGHT/2.0, ARENASIZE-0.5); arenacorner->setPosition(-ARENASIZE + 0.5, BLOCKHEIGHT * ARENAHEIGHT / 2.0,
ARENASIZE - 0.5);
arenaworld->addChild(arenacorner); arenaworld->addChild(arenacorner);
arenacorner = new BasicBlock(1, ARENAHEIGHT, 1); arenacorner = new BasicBlock(1, ARENAHEIGHT, 1);
arenacorner->setColor(1, 0, 0); arenacorner->setColor(1, 0, 0);
//arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA); // arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA);
arenacorner->setPosition(ARENASIZE-0.5, BLOCKHEIGHT*ARENAHEIGHT/2.0, -ARENASIZE+0.5); arenacorner->setPosition(ARENASIZE - 0.5, BLOCKHEIGHT * ARENAHEIGHT / 2.0,
-ARENASIZE + 0.5);
arenaworld->addChild(arenacorner); arenaworld->addChild(arenacorner);
arenacorner = new BasicBlock(1, ARENAHEIGHT, 1); arenacorner = new BasicBlock(1, ARENAHEIGHT, 1);
arenacorner->setColor(1, 0, 0); arenacorner->setColor(1, 0, 0);
//arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA); // arenacorner->setCollisionGroup(COLLISIONGROUP_ARENA);
arenacorner->setPosition(-ARENASIZE+0.5, BLOCKHEIGHT*ARENAHEIGHT/2.0, -ARENASIZE+0.5); arenacorner->setPosition(-ARENASIZE + 0.5, BLOCKHEIGHT * ARENAHEIGHT / 2.0,
-ARENASIZE + 0.5);
arenaworld->addChild(arenacorner); arenaworld->addChild(arenacorner);
//"Ropes" //"Ropes"
MeshObject *arenaline; MeshObject *arenaline;
Mesh *linegeometry; Mesh *linegeometry;
MultiAppearance *lineappearance; MultiAppearance *lineappearance;
BasicBlockAppearance *line; BasicBlockAppearance *line;
int geometryheight = BLOCKHEIGHT*ARENAHEIGHT; int geometryheight = BLOCKHEIGHT * ARENAHEIGHT;
linegeometry = createBox(-0.5, 0.5, -geometryheight/2, geometryheight/2-BLOCKHEIGHT, -ARENASIZE, ARENASIZE); linegeometry =
createBox(-0.5, 0.5, -geometryheight / 2,
geometryheight / 2 - BLOCKHEIGHT, -ARENASIZE, ARENASIZE);
arenaline = new MeshObject(linegeometry); arenaline = new MeshObject(linegeometry);
lineappearance = new MultiAppearance(); lineappearance = new MultiAppearance();
line = new BasicBlockAppearance(1, 1, ARENASIZE*2); line = new BasicBlockAppearance(1, 1, ARENASIZE * 2);
vectorSet(line->displacement, 0, -BLOCKHEIGHT*2.5, 0); vectorSet(line->displacement, 0, -BLOCKHEIGHT * 2.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(1, 1, ARENASIZE*2); line = new BasicBlockAppearance(1, 1, ARENASIZE * 2);
vectorSet(line->displacement, 0, BLOCKHEIGHT*0.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 0.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(1, 1, ARENASIZE*2); line = new BasicBlockAppearance(1, 1, ARENASIZE * 2);
vectorSet(line->displacement, 0, BLOCKHEIGHT*3.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 3.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line), arenaline->appearance = lineappearance;
arenaline->appearance = lineappearance;
arenaline->setCollisionGroup(COLLISIONGROUP_ARENA); arenaline->setCollisionGroup(COLLISIONGROUP_ARENA);
arenaline->setPosition(-ARENASIZE+0.5, geometryheight/2, 0); arenaline->setPosition(-ARENASIZE + 0.5, geometryheight / 2, 0);
arenaworld->addChild(arenaline); arenaworld->addChild(arenaline);
linegeometry = createBox(-0.5, 0.5, -geometryheight/2, geometryheight/2-BLOCKHEIGHT, -ARENASIZE, ARENASIZE); linegeometry =
createBox(-0.5, 0.5, -geometryheight / 2,
geometryheight / 2 - BLOCKHEIGHT, -ARENASIZE, ARENASIZE);
arenaline = new MeshObject(linegeometry); arenaline = new MeshObject(linegeometry);
lineappearance = new MultiAppearance(); lineappearance = new MultiAppearance();
line = new BasicBlockAppearance(1, 1, ARENASIZE*2); line = new BasicBlockAppearance(1, 1, ARENASIZE * 2);
vectorSet(line->displacement, 0, -BLOCKHEIGHT*2.5, 0); vectorSet(line->displacement, 0, -BLOCKHEIGHT * 2.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(1, 1, ARENASIZE*2); line = new BasicBlockAppearance(1, 1, ARENASIZE * 2);
vectorSet(line->displacement, 0, BLOCKHEIGHT*0.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 0.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(1, 1, ARENASIZE*2); line = new BasicBlockAppearance(1, 1, ARENASIZE * 2);
vectorSet(line->displacement, 0, BLOCKHEIGHT*3.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 3.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line), arenaline->appearance = lineappearance;
arenaline->appearance = lineappearance;
arenaline->setCollisionGroup(COLLISIONGROUP_ARENA); arenaline->setCollisionGroup(COLLISIONGROUP_ARENA);
arenaline->setPosition(ARENASIZE-0.5, geometryheight/2, 0); arenaline->setPosition(ARENASIZE - 0.5, geometryheight / 2, 0);
arenaworld->addChild(arenaline); arenaworld->addChild(arenaline);
linegeometry = createBox(-ARENASIZE, ARENASIZE, -geometryheight/2, geometryheight/2-BLOCKHEIGHT, -0.5, 0.5); linegeometry = createBox(-ARENASIZE, ARENASIZE, -geometryheight / 2,
geometryheight / 2 - BLOCKHEIGHT, -0.5, 0.5);
arenaline = new MeshObject(linegeometry); arenaline = new MeshObject(linegeometry);
lineappearance = new MultiAppearance(); lineappearance = new MultiAppearance();
line = new BasicBlockAppearance(ARENASIZE*2, 1, 1); line = new BasicBlockAppearance(ARENASIZE * 2, 1, 1);
vectorSet(line->displacement, 0, -BLOCKHEIGHT*2.5, 0); vectorSet(line->displacement, 0, -BLOCKHEIGHT * 2.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(ARENASIZE*2, 1, 1); line = new BasicBlockAppearance(ARENASIZE * 2, 1, 1);
vectorSet(line->displacement, 0, BLOCKHEIGHT*0.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 0.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(ARENASIZE*2, 1, 1); line = new BasicBlockAppearance(ARENASIZE * 2, 1, 1);
vectorSet(line->displacement, 0, BLOCKHEIGHT*3.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 3.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line), arenaline->appearance = lineappearance;
arenaline->appearance = lineappearance;
arenaline->setCollisionGroup(COLLISIONGROUP_ARENA); arenaline->setCollisionGroup(COLLISIONGROUP_ARENA);
arenaline->setPosition(0, geometryheight/2, -ARENASIZE+0.5); arenaline->setPosition(0, geometryheight / 2, -ARENASIZE + 0.5);
arenaworld->addChild(arenaline); arenaworld->addChild(arenaline);
linegeometry = createBox(-ARENASIZE, ARENASIZE, -geometryheight/2, geometryheight/2-BLOCKHEIGHT, -0.5, 0.5); linegeometry = createBox(-ARENASIZE, ARENASIZE, -geometryheight / 2,
geometryheight / 2 - BLOCKHEIGHT, -0.5, 0.5);
arenaline = new MeshObject(linegeometry); arenaline = new MeshObject(linegeometry);
lineappearance = new MultiAppearance(); lineappearance = new MultiAppearance();
line = new BasicBlockAppearance(ARENASIZE*2, 1, 1); line = new BasicBlockAppearance(ARENASIZE * 2, 1, 1);
vectorSet(line->displacement, 0, -BLOCKHEIGHT*2.5, 0); vectorSet(line->displacement, 0, -BLOCKHEIGHT * 2.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(ARENASIZE*2, 1, 1); line = new BasicBlockAppearance(ARENASIZE * 2, 1, 1);
vectorSet(line->displacement, 0, BLOCKHEIGHT*0.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 0.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line),
line = new BasicBlockAppearance(ARENASIZE*2, 1, 1); line = new BasicBlockAppearance(ARENASIZE * 2, 1, 1);
vectorSet(line->displacement, 0, BLOCKHEIGHT*3.5, 0); vectorSet(line->displacement, 0, BLOCKHEIGHT * 3.5, 0);
line->material.setColor(1, 0, 0, 1); line->material.setColor(1, 0, 0, 1);
lineappearance->addAppearance(line), lineappearance->addAppearance(line), arenaline->appearance = lineappearance;
arenaline->appearance = lineappearance;
arenaline->setCollisionGroup(COLLISIONGROUP_ARENA); arenaline->setCollisionGroup(COLLISIONGROUP_ARENA);
arenaline->setPosition(0, geometryheight/2, ARENASIZE-0.5); arenaline->setPosition(0, geometryheight / 2, ARENASIZE - 0.5);
arenaworld->addChild(arenaline); arenaworld->addChild(arenaline);
float movement[3]; float movement[3];
@ -271,20 +275,18 @@ void initFight(void){
man1->addOpponent(man2); man1->addOpponent(man2);
man2->addOpponent(man1); man2->addOpponent(man1);
initBloods(arenaworld); initBloods(arenaworld);
hitsound1 = new Sound(DATAPATH "hit1.wav");
softhitsound1 = new Sound(DATAPATH "hitsoft1.wav");
softhitsound2 = new Sound(DATAPATH "hitsoft2.wav");
jumpsound = new Sound(DATAPATH "jump.wav");
fallsound1 = new Sound(DATAPATH "fall1.wav");
fallsound2 = new Sound(DATAPATH "fall2.wav");
fightsound = new Sound(DATAPATH "fight.wav");
victorysound = new Sound(DATAPATH "victory.wav");
hitsound1 = new Sound(DATAPATH"hit1.wav"); fightmusic = new Sound(DATAPATH "fight.mp3", true);
softhitsound1 = new Sound(DATAPATH"hitsoft1.wav");
softhitsound2 = new Sound(DATAPATH"hitsoft2.wav");
jumpsound = new Sound(DATAPATH"jump.wav");
fallsound1 = new Sound(DATAPATH"fall1.wav");
fallsound2 = new Sound(DATAPATH"fall2.wav");
fightsound = new Sound(DATAPATH"fight.wav");
victorysound = new Sound(DATAPATH"victory.wav");
fightmusic = new Sound(DATAPATH"fight.mp3", true);
} }
float cameraTarget[3] = {0, 6, 0}; float cameraTarget[3] = {0, 6, 0};
@ -301,7 +303,7 @@ void initFight(void){
int trophycounter = -1; int trophycounter = -1;
void resetFight(void){ void resetFight(void) {
float movement[3]; float movement[3];
man1->heal(); man1->heal();
man2->heal(); man2->heal();
@ -323,13 +325,13 @@ bool dead;
Legoman *winner; Legoman *winner;
void gameOver(Legoman *loser){ void gameOver(Legoman *loser) {
endcounter = 0; endcounter = 0;
dead = true; dead = true;
winner = loser->getOpponent(); winner = loser->getOpponent();
} }
void startFight(void){ void startFight(void) {
resetFight(); resetFight();
fightmusic->setVolume(0); fightmusic->setVolume(0);
fightmusic->play(); fightmusic->play();
@ -356,8 +358,7 @@ SDLKey player2backward = SDLK_s;
SDLKey player2jump = SDLK_LSHIFT; SDLKey player2jump = SDLK_LSHIFT;
SDLKey player2hit = SDLK_LCTRL; SDLKey player2hit = SDLK_LCTRL;
void stopGame(void) {
void stopGame(void){
light1.setEnabled(false); light1.setEnabled(false);
light2.setEnabled(false); light2.setEnabled(false);
light3.setEnabled(false); light3.setEnabled(false);
@ -367,11 +368,9 @@ void stopGame(void){
menuRestart(); menuRestart();
} }
void endGame(void){ void endGame(void) { trophycounter = 0; }
trophycounter = 0;
}
void endGame2(void){ void endGame2(void) {
light1.setEnabled(false); light1.setEnabled(false);
light2.setEnabled(false); light2.setEnabled(false);
light3.setEnabled(false); light3.setEnabled(false);
@ -390,39 +389,43 @@ void endGame2(void){
#define TROPHYFADE 400 #define TROPHYFADE 400
void calculateFight(int framecount){ void calculateFight(int framecount) {
fightfade = -1; fightfade = -1;
if (startcounter < 200){ if (startcounter < 200) {
fightfade = (200-startcounter)/200.0; fightfade = (200 - startcounter) / 200.0;
} }
if (startcounter == FIGHT - 30){ if (startcounter == FIGHT - 30) {
fightsound->play(); fightsound->play();
} }
startcounter++; startcounter++;
if (endcounter == VICTORY){ if (endcounter == VICTORY) {
victorysound->play(); victorysound->play();
if (winner == man1) points1++; if (winner == man1)
if (winner == man2) points2++; points1++;
if (winner == man2)
points2++;
} }
if (endcounter >= ENDFADE && endcounter <= STARTOVER){ if (endcounter >= ENDFADE && endcounter <= STARTOVER) {
fightfade = (endcounter - ENDFADE)/(STARTOVER-ENDFADE); fightfade = (endcounter - ENDFADE) / (STARTOVER - ENDFADE);
} }
if (endcounter == STARTOVER){ if (endcounter == STARTOVER) {
if (points1 == MAXSCORE || points2 == MAXSCORE){ if (points1 == MAXSCORE || points2 == MAXSCORE) {
endGame(); endGame();
} else{ } else {
startcounter = 0; startcounter = 0;
resetFight(); resetFight();
dead = false; dead = false;
endcounter = 0; endcounter = 0;
} }
} }
if (dead) endcounter++; if (dead)
if (trophycounter != -1){ endcounter++;
fightfade = (float)trophycounter/TROPHYFADE; if (trophycounter != -1) {
fightfade = (float)trophycounter / TROPHYFADE;
trophycounter++; trophycounter++;
if (trophycounter == TROPHYFADE) endGame2(); if (trophycounter == TROPHYFADE)
endGame2();
} }
/*if (framecount % 10 == 0){ /*if (framecount % 10 == 0){
@ -430,13 +433,15 @@ void calculateFight(int framecount){
float vel[3] = {randomf(2)-1, randomf(2)-1, randomf(2)-1}; float vel[3] = {randomf(2)-1, randomf(2)-1, randomf(2)-1};
createBlood(pos, vel); createBlood(pos, vel);
}*/ }*/
//arenalight.setPosition(sin(framecount*0.01)*6, 3, cos(framecount*0.01)*4); // arenalight.setPosition(sin(framecount*0.01)*6, 3, cos(framecount*0.01)*4);
//light2.setPosition(sin(framecount*0.017)*6, 2, cos(framecount*0.027)*5); // light2.setPosition(sin(framecount*0.017)*6, 2, cos(framecount*0.027)*5);
//light3.setPosition(sin(framecount*0.023)*3, 4, cos(framecount*0.013)*3); // light3.setPosition(sin(framecount*0.023)*3, 4, cos(framecount*0.013)*3);
camera.setPosition(sin(framecount*0.0005)*20, sin(framecount*0.0013)*5+15, cos(framecount*0.0005)*20); camera.setPosition(sin(framecount * 0.0005) * 20,
sin(framecount * 0.0013) * 5 + 15,
cos(framecount * 0.0005) * 20);
//camera.setPosition(8, 5, 5); // camera.setPosition(8, 5, 5);
float upmovement[3] = {0, 0.001, 0}; float upmovement[3] = {0, 0.001, 0};
man1->move(upmovement); man1->move(upmovement);
@ -444,56 +449,65 @@ void calculateFight(int framecount){
man1->update(); man1->update();
man2->update(); man2->update();
if (startcounter >= FIGHT){ if (startcounter >= FIGHT) {
if (man1->isAlive()){ if (man1->isAlive()) {
if (keys[player1left]) man1->turn(5); if (keys[player1left])
if (keys[player1right]) man1->turn(-5); man1->turn(5);
if (keys[player1forward]) man1->walk(0.03); if (keys[player1right])
if (keys[player1backward]) man1->walk(-0.03); man1->turn(-5);
if (keys[player1jump]) man1->jump(); if (keys[player1forward])
if (keys[player1hit]) man1->hit(); man1->walk(0.03);
if (keys[player1backward])
man1->walk(-0.03);
if (keys[player1jump])
man1->jump();
if (keys[player1hit])
man1->hit();
} }
if (man2->isAlive()){ if (man2->isAlive()) {
if (keys[player2left]) man2->turn(5); if (keys[player2left])
if (keys[player2right]) man2->turn(-5); man2->turn(5);
if (keys[player2forward]) man2->walk(0.03); if (keys[player2right])
if (keys[player2backward]) man2->walk(-0.03); man2->turn(-5);
if (keys[player2jump]) man2->jump(); if (keys[player2forward])
if (keys[player2hit]) man2->hit(); man2->walk(0.03);
if (keys[player2backward])
man2->walk(-0.03);
if (keys[player2jump])
man2->jump();
if (keys[player2hit])
man2->hit();
} }
} }
if (keys[SDLK_ESCAPE]) {
if (keys[SDLK_ESCAPE]){
stopGame(); stopGame();
} }
arenaworld->move(); arenaworld->move();
} }
void drawDamageMeters(void){ void drawDamageMeters(void) {
enable2D(); enable2D();
glEnable(GL_BLEND); glEnable(GL_BLEND);
glPushMatrix(); glPushMatrix();
glTranslatef(0.925, 0.22-0.025, 0); glTranslatef(0.925, 0.22 - 0.025, 0);
glScalef(0.08*3/4, 0.08, 0.1); glScalef(0.08 * 3 / 4, 0.08, 0.1);
man1->drawVisuals(); man1->drawVisuals();
glPopMatrix(); glPopMatrix();
glPushMatrix(); glPushMatrix();
glTranslatef(0.075, 0.22-0.025, 0); glTranslatef(0.075, 0.22 - 0.025, 0);
glScalef(0.08*3/4, 0.08, 0.1); glScalef(0.08 * 3 / 4, 0.08, 0.1);
man2->drawVisuals(); man2->drawVisuals();
glPopMatrix(); glPopMatrix();
glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glColor3f(1, 1, 0); glColor3f(1, 1, 0);
char pointstring[5]; char pointstring[5];
@ -506,16 +520,15 @@ void drawDamageMeters(void){
disable2D(); disable2D();
} }
void drawFight(int framecount){ void drawFight(int framecount) {
glLoadIdentity(); glLoadIdentity();
camera.glUpdate(); camera.glUpdate();
//float position[3]; // float position[3];
//camera.getPosition((float*)position); // camera.getPosition((float*)position);
//createSkyBox(position[0], position[1], position[2], 50, 20, 50); // createSkyBox(position[0], position[1], position[2], 50, 20, 50);
createSkyBox(0, 10, 0, 50, 20, 50); createSkyBox(0, 10, 0, 50, 20, 50);
light1.setEnabled(true); light1.setEnabled(true);
light2.setEnabled(true); light2.setEnabled(true);
light3.setEnabled(true); light3.setEnabled(true);
@ -527,7 +540,6 @@ void drawFight(int framecount){
drawDamageMeters(); drawDamageMeters();
flaretexture->enable(); flaretexture->enable();
light1.createFlare(); light1.createFlare();
light2.createFlare(); light2.createFlare();
@ -535,10 +547,9 @@ void drawFight(int framecount){
light4.createFlare(); light4.createFlare();
flaretexture->disable(); flaretexture->disable();
enable2D(); enable2D();
if (fightfade != -1){ if (fightfade != -1) {
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0, 0, 0, fightfade); glColor4f(0, 0, 0, fightfade);
@ -550,22 +561,22 @@ void drawFight(int framecount){
glEnd(); glEnd();
} }
if (startcounter >= READY && startcounter < FIGHT){ if (startcounter >= READY && startcounter < FIGHT) {
float size = 0.2 - (startcounter - READY)*0.0001; float size = 0.2 - (startcounter - READY) * 0.0001;
float alpha = 1 - (float)(startcounter - READY)/(FIGHT - READY); float alpha = 1 - (float)(startcounter - READY) / (FIGHT - READY);
float x = 0.5 - size*1.5; float x = 0.5 - size * 1.5;
float y = 0.5 - size*0.5; float y = 0.5 - size * 0.5;
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(alpha, 0, 0, alpha); glColor4f(alpha, 0, 0, alpha);
print(x, y, "Ready", size); print(x, y, "Ready", size);
} }
if (startcounter >= FIGHT && startcounter < FIGHT+200){ if (startcounter >= FIGHT && startcounter < FIGHT + 200) {
float size = 0.2 + (startcounter - FIGHT)*0.0005; float size = 0.2 + (startcounter - FIGHT) * 0.0005;
float alpha = 1 - (float)(startcounter - FIGHT)/200; float alpha = 1 - (float)(startcounter - FIGHT) / 200;
float x = 0.5 - size*1.4; float x = 0.5 - size * 1.4;
float y = 0.5 - size*0.5; float y = 0.5 - size * 0.5;
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
@ -573,14 +584,14 @@ void drawFight(int framecount){
print(x, y, "Fight!", size); print(x, y, "Fight!", size);
} }
if (dead){ if (dead) {
if (endcounter >= VICTORY && endcounter < VICTORYEND){ if (endcounter >= VICTORY && endcounter < VICTORYEND) {
float size = 0.18 + (endcounter - VICTORY)*0.0001; float size = 0.18 + (endcounter - VICTORY) * 0.0001;
float alpha = (float)(endcounter - VICTORY)/(VICTORYEND-VICTORY); float alpha = (float)(endcounter - VICTORY) / (VICTORYEND - VICTORY);
alpha = 1-4*(alpha-0.5)*(alpha-0.5); alpha = 1 - 4 * (alpha - 0.5) * (alpha - 0.5);
alpha = pow(alpha, 0.5); alpha = pow(alpha, 0.5);
float x = 0.5 - size*1.9; float x = 0.5 - size * 1.9;
float y = 0.3 - size*0.5; float y = 0.3 - size * 0.5;
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
@ -591,7 +602,6 @@ void drawFight(int framecount){
disable2D(); disable2D();
glDisable(GL_BLEND); glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
} }

View file

@ -25,4 +25,3 @@ void handleKeydownFight(SDLKey key);
void addGraphicsVector(float *p1, float *p2, float size); void addGraphicsVector(float *p1, float *p2, float size);
#endif #endif

View file

@ -5,29 +5,29 @@
Texture *fonttexture; Texture *fonttexture;
void drawChar(float x, float y, char ch, float size){ void drawChar(float x, float y, char ch, float size) {
fonttexture->enable(); fonttexture->enable();
int tx = (ch&15)*64; int tx = (ch & 15) * 64;
int ty = (ch>>4)*64; int ty = (ch >> 4) * 64;
float w = size, h = size*4/3; float w = size, h = size * 4 / 3;
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
glBegin(GL_QUADS); glBegin(GL_QUADS);
glTexCoord2f((tx)/1024.0, (ty)/1024.0); glTexCoord2f((tx) / 1024.0, (ty) / 1024.0);
glVertex2f(x, y); glVertex2f(x, y);
glTexCoord2f((tx)/1024.0, (ty+64)/1024.0); glTexCoord2f((tx) / 1024.0, (ty + 64) / 1024.0);
glVertex2f(x, y+h); glVertex2f(x, y + h);
glTexCoord2f((tx+64)/1024.0, (ty+64)/1024.0); glTexCoord2f((tx + 64) / 1024.0, (ty + 64) / 1024.0);
glVertex2f(x+w, y+h); glVertex2f(x + w, y + h);
glTexCoord2f((tx+64)/1024.0, (ty)/1024.0); glTexCoord2f((tx + 64) / 1024.0, (ty) / 1024.0);
glVertex2f(x+w, y); glVertex2f(x + w, y);
glEnd(); glEnd();
@ -35,39 +35,40 @@ void drawChar(float x, float y, char ch, float size){
} }
float letterwidth[256] = { float letterwidth[256] = {
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
0.5, 0.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.45, 0.2, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 0.2, 1.0, 1.0, 1.0, 1.0, 1.0,
0.6, 0.5, 0.6, 0.6, 0.65, 0.65, 0.6, 0.65, 0.6, 0.6, 0.2, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.45, 0.2, 0.5, 0.6, 0.5, 0.6, 0.6,
1.0, 0.7, 0.6, 0.7, 0.7, 0.65, 0.6, 0.7, 0.8, 0.6, 0.7, 0.7, 0.6, 0.9, 0.85, 0.8, 0.65, 0.65, 0.6, 0.65, 0.6, 0.6, 0.2, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0,
0.6, 0.9, 0.7, 0.7, 0.7, 0.7, 0.7, 1.0, 0.8, 0.7, 0.8, 1.0, 1.0, 1.0, 1.0, 1.0, 0.7, 0.6, 0.7, 0.7, 0.65, 0.6, 0.7, 0.8, 0.6, 0.7, 0.7, 0.6, 0.9,
1.0, 0.6, 0.6, 0.6, 0.6, 0.6, 0.5, 0.6, 0.6, 0.2, 0.4, 0.6, 0.2, 0.8, 0.5, 0.55, 0.85, 0.8, 0.6, 0.9, 0.7, 0.7, 0.7, 0.7, 0.7, 1.0, 0.8, 0.7, 0.8,
0.55, 0.55, 0.5, 0.55, 0.55, 0.55, 0.6, 0.8, 0.6, 0.6, 0.6, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.6, 0.6, 0.6, 0.6, 0.6, 0.5, 0.6,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.6, 0.2, 0.4, 0.6, 0.2, 0.8, 0.5, 0.55, 0.55, 0.55, 0.5, 0.55, 0.55,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.55, 0.6, 0.8, 0.6, 0.6, 0.6, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
}; 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
void print(float x, float y, char *text, float size){ void print(float x, float y, char *text, float size) {
int i; int i;
int textlength = strlen(text); int textlength = strlen(text);
float px = x; float px = x;
float py = y; float py = y;
for (i = 0; i < textlength; i++){ for (i = 0; i < textlength; i++) {
char ch = text[i]; char ch = text[i];
if (ch == '\n'){ if (ch == '\n') {
px = x; px = x;
py += size*1.2; py += size * 1.2;
} else{ } else {
drawChar(px, py, ch, size); drawChar(px, py, ch, size);
px += size*letterwidth[ch]; px += size * letterwidth[ch];
} }
} }
} }

View file

@ -5,9 +5,8 @@
extern Texture *fonttexture; extern Texture *fonttexture;
//Top left = 0.0 , 0.0 Bottom right = 1.0 , 1.0 // Top left = 0.0 , 0.0 Bottom right = 1.0 , 1.0
void drawChar(float x, float y, char ch, float size = 0.05); void drawChar(float x, float y, char ch, float size = 0.05);
void print(float x, float y, char *text, float size = 0.05); void print(float x, float y, char *text, float size = 0.05);
#endif #endif

View file

@ -2,9 +2,9 @@
#include "glapi.h" #include "glapi.h"
void setupOpengl(int width, int height){ void setupOpengl(int width, int height) {
//float ratio = (float)width/height; // float ratio = (float)width/height;
float ratio = 4.0/3.0; float ratio = 4.0 / 3.0;
glShadeModel(GL_SMOOTH); glShadeModel(GL_SMOOTH);
@ -20,11 +20,12 @@ void setupOpengl(int width, int height){
glEnable(GL_COLOR_MATERIAL); glEnable(GL_COLOR_MATERIAL);
//Enables lighting with zero initial lights. Lights are created with Light-class // Enables lighting with zero initial lights. Lights are created with
// Light-class
glEnable(GL_LIGHTING); glEnable(GL_LIGHTING);
glDisable(GL_LIGHT0); glDisable(GL_LIGHT0);
float ambient[4]= {0.1, 0.1, 0.1, 1}; float ambient[4] = {0.1, 0.1, 0.1, 1};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
@ -33,20 +34,18 @@ void setupOpengl(int width, int height){
GLfloat zero[4] = {0, 0, 0, 1}; GLfloat zero[4] = {0, 0, 0, 1};
GLfloat one[4] = {1, 1, 1, 1}; GLfloat one[4] = {1, 1, 1, 1};
//Default frontface lighting // Default frontface lighting
glMaterialfv(GL_FRONT, GL_AMBIENT, one); glMaterialfv(GL_FRONT, GL_AMBIENT, one);
glMaterialfv(GL_FRONT, GL_DIFFUSE, one); glMaterialfv(GL_FRONT, GL_DIFFUSE, one);
GLfloat specular[4] = {2, 2, 2, 1}; GLfloat specular[4] = {2, 2, 2, 1};
glMaterialfv(GL_FRONT, GL_SPECULAR, specular); glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
glMaterialf(GL_FRONT, GL_SHININESS, 120); glMaterialf(GL_FRONT, GL_SHININESS, 120);
//Never any backface lighting, except ambient // Never any backface lighting, except ambient
glMaterialfv(GL_BACK, GL_AMBIENT, one); glMaterialfv(GL_BACK, GL_AMBIENT, one);
glMaterialfv(GL_BACK, GL_DIFFUSE, zero); glMaterialfv(GL_BACK, GL_DIFFUSE, zero);
glMaterialfv(GL_BACK, GL_SPECULAR, zero); glMaterialfv(GL_BACK, GL_SPECULAR, zero);
glViewport(0, 0, width, height); glViewport(0, 0, width, height);
glDepthFunc(GL_LEQUAL); glDepthFunc(GL_LEQUAL);
@ -59,6 +58,5 @@ void setupOpengl(int width, int height){
gluPerspective(60.0, ratio, 1.0, 1024.0); gluPerspective(60.0, ratio, 1.0, 1024.0);
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} }

View file

@ -6,5 +6,3 @@
void setupOpengl(int width, int height); void setupOpengl(int width, int height);
#endif #endif

View file

@ -3,26 +3,23 @@
GraphicsDruid *GraphicsDruid::instance = 0; GraphicsDruid *GraphicsDruid::instance = 0;
GraphicsDruid::GraphicsDruid(void){ GraphicsDruid::GraphicsDruid(void) { this->reserved = 0; }
this->reserved = 0;
}
GraphicsDruid::~GraphicsDruid(void){ GraphicsDruid::~GraphicsDruid(void) {}
}
void GraphicsDruid::init(void){ void GraphicsDruid::init(void) {
instance->textureCount = 0; instance->textureCount = 0;
instance->reserved = ID_ARRAY_INIT_SIZE; instance->reserved = ID_ARRAY_INIT_SIZE;
instance->idArray = (int*) calloc(ID_ARRAY_INIT_SIZE, sizeof(int)); instance->idArray = (int *)calloc(ID_ARRAY_INIT_SIZE, sizeof(int));
for (int i=0; i < instance->reserved; i++){ for (int i = 0; i < instance->reserved; i++) {
instance->idArray[i] = -1; instance->idArray[i] = -1;
} }
} }
void GraphicsDruid::destroy(void){ void GraphicsDruid::destroy(void) {
if (instance->textureCount > 0){ if (instance->textureCount > 0) {
glDeleteTextures(GL_TEXTURE_2D, (const unsigned int*)instance->idArray); glDeleteTextures(GL_TEXTURE_2D, (const unsigned int *)instance->idArray);
} }
free(instance->idArray); free(instance->idArray);
instance->idArray = 0; instance->idArray = 0;
@ -30,35 +27,37 @@ void GraphicsDruid::destroy(void){
instance = 0; instance = 0;
} }
GraphicsDruid &GraphicsDruid::getInstance(void){ GraphicsDruid &GraphicsDruid::getInstance(void) {
if (!instance){ if (!instance) {
instance = new GraphicsDruid; instance = new GraphicsDruid;
init(); init();
} }
return *instance; return *instance;
} }
int GraphicsDruid::loadTexture(SDL_Surface *texture, int id, int format){ int GraphicsDruid::loadTexture(SDL_Surface *texture, int id, int format) {
int textureID = id == -1 ? getNewTextureID(id) : id; int textureID = id == -1 ? getNewTextureID(id) : id;
// register texture in OpenGL // register texture in OpenGL
glBindTexture (GL_TEXTURE_2D, textureID); glBindTexture(GL_TEXTURE_2D, textureID);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);//_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL_LINEAR); //_MIPMAP_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
//printf("w: %i, h: %i, format: %i, RGBA: %i, pixels: %p\n", // printf("w: %i, h: %i, format: %i, RGBA: %i, pixels: %p\n",
// texture->w, texture->h, format, GL_RGBA, texture->pixels); // texture->w, texture->h, format, GL_RGBA, texture->pixels);
//printf("Pitch: %i, Bpp: %i\n", texture->pitch, texture->format->BytesPerPixel); // printf("Pitch: %i, Bpp: %i\n", texture->pitch,
// texture->format->BytesPerPixel);
/*gluBuild2DMipmaps(GL_TEXTURE_2D, /*gluBuild2DMipmaps(GL_TEXTURE_2D,
4, 4,
@ -82,68 +81,73 @@ int GraphicsDruid::loadTexture(SDL_Surface *texture, int id, int format){
} }
h = 1; h = 1;
for (;i > 1; i--) h <<= 1;*/ for (;i > 1; i--) h <<= 1;*/
//glTexImage2D(GL_TEXTURE_2D, 0, texture->format->BytesPerPixel, w, h, 0, format, GL_UNSIGNED_BYTE, texture->pixels); // glTexImage2D(GL_TEXTURE_2D, 0, texture->format->BytesPerPixel, w, h, 0,
if (texture->format->BytesPerPixel == 3){ // format, GL_UNSIGNED_BYTE, texture->pixels);
glTexImage2D(GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->pixels); if (texture->format->BytesPerPixel == 3) {
} else if (texture->format->BytesPerPixel == 4){ glTexImage2D(GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE,
glTexImage2D(GL_TEXTURE_2D, 0, 4, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture->pixels); texture->pixels);
} else if (texture->format->BytesPerPixel == 4) {
glTexImage2D(GL_TEXTURE_2D, 0, 4, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE,
texture->pixels);
} }
//SDL_FreeSurface(texture); // SDL_FreeSurface(texture);
//SDL_FreeSurface(alphaSurface); // SDL_FreeSurface(alphaSurface);
return textureID; return textureID;
} }
int GraphicsDruid::loadTexture(char* path, int id){ int GraphicsDruid::loadTexture(char *path, int id) {
SDL_Surface* texture; SDL_Surface *texture;
texture = IMG_Load(path); texture = IMG_Load(path);
if (!texture){ if (!texture) {
#ifdef _DEBUG #ifdef _DEBUG
printf ("Error while loading image: %s\n", SDL_GetError()); printf("Error while loading image: %s\n", SDL_GetError());
#endif #endif
return -1; return -1;
} }
int textureID = getNewTextureID(id); int textureID = getNewTextureID(id);
// register texture in OpenGL // register texture in OpenGL
glBindTexture (GL_TEXTURE_2D, textureID); glBindTexture(GL_TEXTURE_2D, textureID);
//glPixelStorei (GL_UNPACK_ALIGNMENT, 1); // glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
// NOTE : Making some assumptions about texture parameters // NOTE : Making some assumptions about texture parameters
//glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); // glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
//printf("w: %i, h: %i, RGBA: %i, pixels: %p\n", // printf("w: %i, h: %i, RGBA: %i, pixels: %p\n",
// texture->w, texture->h, GL_RGBA, texture->pixels); // texture->w, texture->h, GL_RGBA, texture->pixels);
//printf("Pitch: %i, Bpp: %i\n", texture->pitch, texture->format->BytesPerPixel); // printf("Pitch: %i, Bpp: %i\n", texture->pitch,
// texture->format->BytesPerPixel);
if (texture->format->BytesPerPixel == 3){ if (texture->format->BytesPerPixel == 3) {
/*gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, /*gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB,
texture->w, texture->w,
texture->h, texture->h,
GL_RGB, GL_UNSIGNED_BYTE, GL_RGB, GL_UNSIGNED_BYTE,
texture->pixels);*/ texture->pixels);*/
glTexImage2D(GL_TEXTURE_2D, 0, 3, texture->w, texture->h, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->pixels); glTexImage2D(GL_TEXTURE_2D, 0, 3, texture->w, texture->h, 0, GL_RGB,
} GL_UNSIGNED_BYTE, texture->pixels);
else if (texture->format->BytesPerPixel == 4){ } else if (texture->format->BytesPerPixel == 4) {
/*gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, /*gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA,
texture->w, texture->w,
texture->h, texture->h,
GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA, GL_UNSIGNED_BYTE,
texture->pixels);*/ texture->pixels);*/
glTexImage2D(GL_TEXTURE_2D, 0, 4, texture->w, texture->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture->pixels); glTexImage2D(GL_TEXTURE_2D, 0, 4, texture->w, texture->h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, texture->pixels);
} }
/* /*
gluBuild2DMipmaps(GL_TEXTURE_2D, gluBuild2DMipmaps(GL_TEXTURE_2D,
@ -158,37 +162,35 @@ int GraphicsDruid::loadTexture(char* path, int id){
return textureID; return textureID;
} }
int GraphicsDruid::loadTranspTexture(char* path, float* transpColor, int id){ int GraphicsDruid::loadTranspTexture(char *path, float *transpColor, int id) {
SDL_Surface* texture; SDL_Surface *texture;
texture = IMG_Load(path); texture = IMG_Load(path);
if (!texture){ if (!texture) {
#ifdef _DEBUG #ifdef _DEBUG
printf ("Error while loading image: %s\n", SDL_GetError()); printf("Error while loading image: %s\n", SDL_GetError());
#endif #endif
return -1; return -1;
} }
Uint32 colorKey =
Uint32 colorKey = SDL_MapRGB(texture->format, SDL_MapRGB(texture->format, (Uint8)(transpColor[0] * 255),
(Uint8)(transpColor[0] * 255), (Uint8)(transpColor[1] * 255), (Uint8)(transpColor[2] * 255));
(Uint8)(transpColor[1] * 255), // SDL_SetAlpha(texture, 0, SDL_ALPHA_OPAQUE);
(Uint8)(transpColor[2] * 255));
//SDL_SetAlpha(texture, 0, SDL_ALPHA_OPAQUE);
SDL_SetColorKey(texture, SDL_SRCCOLORKEY, colorKey); SDL_SetColorKey(texture, SDL_SRCCOLORKEY, colorKey);
//SDL_Surface* alphaSurface = SDL_DisplayFormatAlpha(texture); // SDL_Surface* alphaSurface = SDL_DisplayFormatAlpha(texture);
texture = SDL_DisplayFormatAlpha(texture); texture = SDL_DisplayFormatAlpha(texture);
return loadTexture(texture); return loadTexture(texture);
} }
int GraphicsDruid::getNewTextureID(int id){ int GraphicsDruid::getNewTextureID(int id) {
if (id != -1){ if (id != -1) {
for (int i = 0; i < instance->reserved; i++){ for (int i = 0; i < instance->reserved; i++) {
if (instance->idArray[i] == id){ if (instance->idArray[i] == id) {
freeTexture(id); freeTexture(id);
instance->textureCount--; instance->textureCount--;
break; break;
@ -198,39 +200,37 @@ int GraphicsDruid::getNewTextureID(int id){
GLuint newId; GLuint newId;
if (id == -1){ if (id == -1) {
glGenTextures (1, &newId); glGenTextures(1, &newId);
} } else
else
newId = id; newId = id;
int index = 0; int index = 0;
while (instance->idArray[index] != -1 && index < instance->reserved){ while (instance->idArray[index] != -1 && index < instance->reserved) {
index++; index++;
} }
// out of space, make more // out of space, make more
if (index >= instance->reserved){ if (index >= instance->reserved) {
instance->idArray = (int*) realloc(instance->idArray, (instance->reserved + ID_ARRAY_GROW)*sizeof(int)); instance->idArray = (int *)realloc(
instance->idArray, (instance->reserved + ID_ARRAY_GROW) * sizeof(int));
for (int i = instance->reserved + 1; i < instance->reserved + ID_ARRAY_GROW; i++) for (int i = instance->reserved + 1; i < instance->reserved + ID_ARRAY_GROW;
i++)
instance->idArray[i] = -1; instance->idArray[i] = -1;
instance->reserved += ID_ARRAY_GROW; instance->reserved += ID_ARRAY_GROW;
} } else
else
instance->idArray[index] = newId; instance->idArray[index] = newId;
instance->textureCount++; instance->textureCount++;
return newId; return newId;
} }
void GraphicsDruid::freeTexture(int id){ void GraphicsDruid::freeTexture(int id) {
if (id > -1 && id < instance->reserved){ if (id > -1 && id < instance->reserved) {
instance->idArray[id] = -1; instance->idArray[id] = -1;
const unsigned int helpInt = id; const unsigned int helpInt = id;
glDeleteTextures(1, &helpInt); glDeleteTextures(1, &helpInt);
} }
} }

View file

@ -2,7 +2,7 @@
#define __GRAPHICS_H_INCLUDED__ #define __GRAPHICS_H_INCLUDED__
#ifdef WIN32 #ifdef WIN32
#pragma warning ( disable : 4700 ) #pragma warning(disable : 4700)
#endif #endif
#include "main.h" #include "main.h"
@ -15,20 +15,17 @@ const int ID_ARRAY_GROW = 8;
#define DRUID GraphicsDruid::getInstance() #define DRUID GraphicsDruid::getInstance()
#define DIE_DRUID_DIE GraphicsDruid::destroy() #define DIE_DRUID_DIE GraphicsDruid::destroy()
typedef unsigned char byte; typedef unsigned char byte;
typedef struct jpeg_pixel{ typedef struct jpeg_pixel {
Uint8 red; Uint8 red;
Uint8 green; Uint8 green;
Uint8 blue; Uint8 blue;
}jpeg_pixel; } jpeg_pixel;
class GraphicsDruid {
class GraphicsDruid{
private: private:
static GraphicsDruid *instance;
static GraphicsDruid* instance; int *idArray;
int* idArray;
int textureCount; int textureCount;
int reserved; int reserved;
@ -39,16 +36,13 @@ private:
static void destroy(void); static void destroy(void);
public: public:
static GraphicsDruid &getInstance(void); static GraphicsDruid &getInstance(void);
int loadTexture(SDL_Surface *texture, int id = -1, int format = GL_RGB); int loadTexture(SDL_Surface *texture, int id = -1, int format = GL_RGB);
int loadTexture(char* path, int id = -1); int loadTexture(char *path, int id = -1);
int loadTranspTexture(char* path, float* transpColor, int id = -1); int loadTranspTexture(char *path, float *transpColor, int id = -1);
void freeTexture(int id); void freeTexture(int id);
void freeAll(void); void freeAll(void);
int getNewTextureID(int id); int getNewTextureID(int id);
}; };
#endif #endif

View file

@ -9,18 +9,19 @@
#include "vector.h" #include "vector.h"
#include "glapi.h" #include "glapi.h"
BasicBlock::BasicBlock(int width, int height, int depth) : MeshObject(createBox(-width/2.0, width/2.0, -height/2.0*BLOCKHEIGHT, BLOCKHEIGHT*height/2.0, -depth/2.0, depth/2.0)){ BasicBlock::BasicBlock(int width, int height, int depth)
: MeshObject(
createBox(-width / 2.0, width / 2.0, -height / 2.0 * BLOCKHEIGHT,
BLOCKHEIGHT * height / 2.0, -depth / 2.0, depth / 2.0)) {
appearance = new BasicBlockAppearance(width, height, depth); appearance = new BasicBlockAppearance(width, height, depth);
//geometry = new MeshShape(this); // geometry = new MeshShape(this);
} }
void BasicBlock::setColor(float red, float green, float blue){ void BasicBlock::setColor(float red, float green, float blue) {
appearance->getMaterial()->setColor(red, green, blue, 1); appearance->getMaterial()->setColor(red, green, blue, 1);
} }
BasicBlockAppearance::BasicBlockAppearance(int width, int height, int depth) {
BasicBlockAppearance::BasicBlockAppearance(int width, int height, int depth){
this->width = width; this->width = width;
this->height = height; this->height = height;
this->depth = depth; this->depth = depth;
@ -29,97 +30,99 @@ BasicBlockAppearance::BasicBlockAppearance(int width, int height, int depth){
usematerial = true; usematerial = true;
} }
void BasicBlockAppearance::prepare(){ void BasicBlockAppearance::prepare() {
glNewList(gllist, GL_COMPILE); glNewList(gllist, GL_COMPILE);
float width = this->width; float width = this->width;
float height = this->height * BLOCKHEIGHT; float height = this->height * BLOCKHEIGHT;
if (usematerial) material.enable(); if (usematerial)
{//Block material.enable();
//Front Face { // Block
// Front Face
glPushMatrix(); glPushMatrix();
glTranslatef(-width/2.0, -height/2.0, depth/2.0); glTranslatef(-width / 2.0, -height / 2.0, depth / 2.0);
drawDetailRectangle(width, height); drawDetailRectangle(width, height);
glPopMatrix(); glPopMatrix();
// Back Face // Back Face
glPushMatrix(); glPushMatrix();
glTranslatef(width/2.0, -height/2.0, -depth/2.0); glTranslatef(width / 2.0, -height / 2.0, -depth / 2.0);
glRotatef(180, 0, 1, 0); glRotatef(180, 0, 1, 0);
drawDetailRectangle(width, height); drawDetailRectangle(width, height);
glPopMatrix(); glPopMatrix();
// Top Face // Top Face
glPushMatrix(); glPushMatrix();
glTranslatef(-width/2.0, height/2.0, depth/2.0); glTranslatef(-width / 2.0, height / 2.0, depth / 2.0);
glRotatef(-90, 1, 0, 0); glRotatef(-90, 1, 0, 0);
drawDetailRectangle(width, depth); drawDetailRectangle(width, depth);
glPopMatrix(); glPopMatrix();
// Bottom Face // Bottom Face
glPushMatrix(); glPushMatrix();
glTranslatef(-width/2.0, -height/2.0, -depth/2.0); glTranslatef(-width / 2.0, -height / 2.0, -depth / 2.0);
glRotatef(90, 1, 0, 0); glRotatef(90, 1, 0, 0);
drawDetailRectangle(width, depth); drawDetailRectangle(width, depth);
glPopMatrix(); glPopMatrix();
// Right face // Right face
glPushMatrix(); glPushMatrix();
glTranslatef(width/2.0, -height/2.0, depth/2.0); glTranslatef(width / 2.0, -height / 2.0, depth / 2.0);
glRotatef(90, 0, 1, 0); glRotatef(90, 0, 1, 0);
drawDetailRectangle(depth, height); drawDetailRectangle(depth, height);
glPopMatrix(); glPopMatrix();
// Left Face // Left Face
glPushMatrix(); glPushMatrix();
glTranslatef(-width/2.0, -height/2.0, -depth/2.0); glTranslatef(-width / 2.0, -height / 2.0, -depth / 2.0);
glRotatef(-90, 0, 1, 0); glRotatef(-90, 0, 1, 0);
drawDetailRectangle(depth, height); drawDetailRectangle(depth, height);
glPopMatrix(); glPopMatrix();
} }
glPushMatrix(); glPushMatrix();
glTranslatef(0.5 - width/2.0, height - height/2.0, 0.5 - depth/2.0); glTranslatef(0.5 - width / 2.0, height - height / 2.0, 0.5 - depth / 2.0);
int x, z; int x, z;
for (x = 0; x < width; x++){ for (x = 0; x < width; x++) {
//glPushMatrix(); // glPushMatrix();
for (z = 0; z < depth; z++){ for (z = 0; z < depth; z++) {
createKnob(); createKnob();
glTranslatef(0, 0, 1); glTranslatef(0, 0, 1);
} }
glTranslatef(1, 0, -depth); glTranslatef(1, 0, -depth);
//glPopMatrix(); // glPopMatrix();
} }
glPopMatrix(); glPopMatrix();
if (usematerial) material.disable(); if (usematerial)
material.disable();
glEndList(); glEndList();
} }
void BasicBlockAppearance::draw(){ void BasicBlockAppearance::draw() {
glPushMatrix(); glPushMatrix();
glTranslatef(displacement[0], displacement[1], displacement[2]); glTranslatef(displacement[0], displacement[1], displacement[2]);
glCallList(gllist); glCallList(gllist);
glPopMatrix(); glPopMatrix();
//prepare(); // prepare();
} }
#define BLOCKDETAILGRID 1 #define BLOCKDETAILGRID 1
void drawDetailRectangle(float width, float height){ void drawDetailRectangle(float width, float height) {
glBegin(GL_QUADS); glBegin(GL_QUADS);
float x, y, x2, y2; float x, y, x2, y2;
glNormal3f(0, 0, 1); glNormal3f(0, 0, 1);
for (y = 0; y < height; y += BLOCKDETAILGRID){ for (y = 0; y < height; y += BLOCKDETAILGRID) {
y2 = y + BLOCKDETAILGRID; y2 = y + BLOCKDETAILGRID;
if (y2 > height) y2 = height; if (y2 > height)
for (x = 0; x < width; x += BLOCKDETAILGRID){ y2 = height;
for (x = 0; x < width; x += BLOCKDETAILGRID) {
x2 = x + BLOCKDETAILGRID; x2 = x + BLOCKDETAILGRID;
if (x2 > width) x2 = width; if (x2 > width)
x2 = width;
glTexCoord2f(x / width, y / height); glTexCoord2f(x / width, y / height);
glVertex3f(x, y, 0); glVertex3f(x, y, 0);
@ -142,16 +145,16 @@ void drawDetailRectangle(float width, float height){
int knobgllist; int knobgllist;
int knobdetail; int knobdetail;
void renderKnob(int knobsegments){ void renderKnob(int knobsegments) {
point2d knobpoints[4]; point2d knobpoints[4];
knobpoints[0].x = 0.3; knobpoints[0].x = 0.3;
knobpoints[0].y = 0; knobpoints[0].y = 0;
knobpoints[1].x = 0.3; knobpoints[1].x = 0.3;
knobpoints[1].y = BLOCKHEIGHT*0.5 - KNOBROUNDNESS; knobpoints[1].y = BLOCKHEIGHT * 0.5 - KNOBROUNDNESS;
knobpoints[2].x = 0.3 - KNOBROUNDNESS; knobpoints[2].x = 0.3 - KNOBROUNDNESS;
knobpoints[2].y = BLOCKHEIGHT*0.5; knobpoints[2].y = BLOCKHEIGHT * 0.5;
knobpoints[3].x = 0; knobpoints[3].x = 0;
knobpoints[3].y = BLOCKHEIGHT*0.5; knobpoints[3].y = BLOCKHEIGHT * 0.5;
point2d knobderivates[4]; point2d knobderivates[4];
knobderivates[0].x = 0; knobderivates[0].x = 0;
@ -166,7 +169,7 @@ void renderKnob(int knobsegments){
createLathedSurface(knobpoints, knobderivates, 4, knobsegments, 4); createLathedSurface(knobpoints, knobderivates, 4, knobsegments, 4);
} }
void initKnob(void){ void initKnob(void) {
glNewList(knobgllist, GL_COMPILE); glNewList(knobgllist, GL_COMPILE);
renderKnob(knobdetail); renderKnob(knobdetail);
@ -174,26 +177,20 @@ void initKnob(void){
glEndList(); glEndList();
} }
void createKnob(int knobsegments){ void createKnob(int knobsegments) {
if (knobsegments != -1){ if (knobsegments != -1) {
renderKnob(knobsegments); renderKnob(knobsegments);
return; return;
} }
glCallList(knobgllist); glCallList(knobgllist);
} }
float knobroundness = 0.05;
float pillarroundness = 0.03;
HeadAppearance::HeadAppearance(void) { gllist = glGenLists(1); }
void HeadAppearance::prepare(void) {
float knobroundness=0.05;
float pillarroundness=0.03;
HeadAppearance::HeadAppearance(void){
gllist = glGenLists(1);
}
void HeadAppearance::prepare(void){
glNewList(gllist, GL_COMPILE); glNewList(gllist, GL_COMPILE);
glPushMatrix(); glPushMatrix();
@ -202,31 +199,45 @@ void HeadAppearance::prepare(void){
point2d headpoints[14]; point2d headpoints[14];
headpoints[0].x=0.0; headpoints[0].y=BLOCKHEIGHT*(0); headpoints[0].x = 0.0;
headpoints[1].x=0.4; headpoints[1].y=BLOCKHEIGHT*(0); headpoints[0].y = BLOCKHEIGHT * (0);
headpoints[2].x=0.45; headpoints[2].y=BLOCKHEIGHT*(0.35); headpoints[1].x = 0.4;
headpoints[3].x=0.55; headpoints[3].y=BLOCKHEIGHT*(0.5); headpoints[1].y = BLOCKHEIGHT * (0);
headpoints[4].x=0.62*1.0; headpoints[4].y=BLOCKHEIGHT*(0.65); headpoints[2].x = 0.45;
headpoints[5].x=0.65*1.0; headpoints[5].y=BLOCKHEIGHT*(1); headpoints[2].y = BLOCKHEIGHT * (0.35);
headpoints[6].x=0.65*1.0; headpoints[6].y=BLOCKHEIGHT*(1.75); headpoints[3].x = 0.55;
headpoints[7].x=0.65*1.0; headpoints[7].y=BLOCKHEIGHT*(2.35); headpoints[3].y = BLOCKHEIGHT * (0.5);
headpoints[8].x=0.62*1.0; headpoints[8].y=BLOCKHEIGHT*(2.60); headpoints[4].x = 0.62 * 1.0;
headpoints[9].x=0.55*1.0; headpoints[9].y=BLOCKHEIGHT*(2.80); headpoints[4].y = BLOCKHEIGHT * (0.65);
headpoints[10].x=0.4; headpoints[10].y=BLOCKHEIGHT*(2.95); headpoints[5].x = 0.65 * 1.0;
headpoints[11].x=0.3; headpoints[11].y=BLOCKHEIGHT*3.5-pillarroundness; headpoints[5].y = BLOCKHEIGHT * (1);
headpoints[12].x=0.3-pillarroundness; headpoints[12].y=BLOCKHEIGHT*3.5; headpoints[6].x = 0.65 * 1.0;
headpoints[13].x=0; headpoints[13].y=BLOCKHEIGHT*3.5; headpoints[6].y = BLOCKHEIGHT * (1.75);
headpoints[11].x=0; headpoints[11].y=BLOCKHEIGHT*3.0; headpoints[7].x = 0.65 * 1.0;
headpoints[7].y = BLOCKHEIGHT * (2.35);
glColor4f(0.8,0.8,0.0,1.0); headpoints[8].x = 0.62 * 1.0;
headpoints[8].y = BLOCKHEIGHT * (2.60);
headpoints[9].x = 0.55 * 1.0;
headpoints[9].y = BLOCKHEIGHT * (2.80);
headpoints[10].x = 0.4;
headpoints[10].y = BLOCKHEIGHT * (2.95);
headpoints[11].x = 0.3;
headpoints[11].y = BLOCKHEIGHT * 3.5 - pillarroundness;
headpoints[12].x = 0.3 - pillarroundness;
headpoints[12].y = BLOCKHEIGHT * 3.5;
headpoints[13].x = 0;
headpoints[13].y = BLOCKHEIGHT * 3.5;
headpoints[11].x = 0;
headpoints[11].y = BLOCKHEIGHT * 3.0;
glColor4f(0.8, 0.8, 0.0, 1.0);
faceTexture->enable(); faceTexture->enable();
glBlendFunc(GL_ONE, GL_SRC_ALPHA); glBlendFunc(GL_ONE, GL_SRC_ALPHA);
createLathedSurface(headpoints,NULL,12,16,24); createLathedSurface(headpoints, NULL, 12, 16, 24);
faceTexture->disable(); faceTexture->disable();
glTranslatef(0, BLOCKHEIGHT*3-0.05, 0); glTranslatef(0, BLOCKHEIGHT * 3 - 0.05, 0);
createKnob(16); createKnob(16);
@ -235,106 +246,121 @@ void HeadAppearance::prepare(void){
glEndList(); glEndList();
} }
void HeadAppearance::draw(void){ void HeadAppearance::draw(void) { glCallList(gllist); }
glCallList(gllist);
}
FlowerAppearance::FlowerAppearance(int color1, int color2, int color3) {
FlowerAppearance::FlowerAppearance(int color1, int color2, int color3){
gllist = glGenLists(1); gllist = glGenLists(1);
this->color1 = color1; this->color1 = color1;
this->color2 = color2; this->color2 = color2;
this->color3 = color3; this->color3 = color3;
} }
void FlowerAppearance::prepare(void){ void FlowerAppearance::prepare(void) {
glNewList(gllist, GL_COMPILE); glNewList(gllist, GL_COMPILE);
glPushMatrix(); glPushMatrix();
int colors[] = {color1, color2, color3};
int colors[]={color1,color2,color3}; glColor3f(0.0, 0.6, 0.0);
glColor3f(0.0,0.6,0.0);
point2d basepoints[8]; point2d basepoints[8];
basepoints[0].x=0.4; basepoints[0].y=0; basepoints[0].x = 0.4;
basepoints[1].x=0.4; basepoints[1].y=BLOCKHEIGHT*1.5-pillarroundness; basepoints[0].y = 0;
basepoints[2].x=0.4-pillarroundness; basepoints[2].y=BLOCKHEIGHT*1.5; basepoints[1].x = 0.4;
basepoints[3].x=0.3+pillarroundness; basepoints[3].y=BLOCKHEIGHT*1.5; basepoints[1].y = BLOCKHEIGHT * 1.5 - pillarroundness;
basepoints[4].x=0.3; basepoints[4].y=BLOCKHEIGHT*1.5+pillarroundness; basepoints[2].x = 0.4 - pillarroundness;
basepoints[5].x=0.3; basepoints[5].y=BLOCKHEIGHT*2.0-pillarroundness; basepoints[2].y = BLOCKHEIGHT * 1.5;
basepoints[6].x=0.3-pillarroundness; basepoints[6].y=BLOCKHEIGHT*2.0; basepoints[3].x = 0.3 + pillarroundness;
basepoints[7].x=0; basepoints[7].y=BLOCKHEIGHT*2.0; basepoints[3].y = BLOCKHEIGHT * 1.5;
basepoints[4].x = 0.3;
basepoints[4].y = BLOCKHEIGHT * 1.5 + pillarroundness;
basepoints[5].x = 0.3;
basepoints[5].y = BLOCKHEIGHT * 2.0 - pillarroundness;
basepoints[6].x = 0.3 - pillarroundness;
basepoints[6].y = BLOCKHEIGHT * 2.0;
basepoints[7].x = 0;
basepoints[7].y = BLOCKHEIGHT * 2.0;
point2d basederivates[8]; point2d basederivates[8];
basederivates[0].x=0; basederivates[0].y=basepoints[1].y-basepoints[0].y; basederivates[0].x = 0;
basederivates[1].x=0; basederivates[1].y=basepoints[2].y-basepoints[1].y; basederivates[0].y = basepoints[1].y - basepoints[0].y;
basederivates[2].x=basepoints[2].x-basepoints[1].x; basederivates[2].y=0; basederivates[1].x = 0;
basederivates[3].x=basepoints[4].x-basepoints[3].x; basederivates[3].y=0; basederivates[1].y = basepoints[2].y - basepoints[1].y;
basederivates[4].x=0; basederivates[4].y=basepoints[4].y-basepoints[3].y; basederivates[2].x = basepoints[2].x - basepoints[1].x;
basederivates[5].x=0; basederivates[5].y=basepoints[6].y-basepoints[5].y; basederivates[2].y = 0;
basederivates[6].x=basepoints[6].x-basepoints[5].x; basederivates[6].y=0; basederivates[3].x = basepoints[4].x - basepoints[3].x;
basederivates[7].x=basepoints[7].x-basepoints[6].x; basederivates[7].y=0; basederivates[3].y = 0;
basederivates[4].x = 0;
basederivates[4].y = basepoints[4].y - basepoints[3].y;
basederivates[5].x = 0;
basederivates[5].y = basepoints[6].y - basepoints[5].y;
basederivates[6].x = basepoints[6].x - basepoints[5].x;
basederivates[6].y = 0;
basederivates[7].x = basepoints[7].x - basepoints[6].x;
basederivates[7].y = 0;
createLathedSurface(basepoints,basederivates,8,8,8); createLathedSurface(basepoints, basederivates, 8, 8, 8);
int i,j; int i, j;
for (i=0;i<3;i++){ for (i = 0; i < 3; i++) {
glColor3f(0.0,0.6,0.0); glColor3f(0.0, 0.6, 0.0);
glPushMatrix(); glPushMatrix();
glTranslatef(0,BLOCKHEIGHT,0.4); glTranslatef(0, BLOCKHEIGHT, 0.4);
glRotatef(20-90,1,0,0); glRotatef(20 - 90, 1, 0, 0);
gluCylinder(gluNewQuadric(),0.1,0.1,BLOCKHEIGHT*(3+i*0.7),4,1); gluCylinder(gluNewQuadric(), 0.1, 0.1, BLOCKHEIGHT * (3 + i * 0.7), 4, 1);
glRotatef(90,1,0,0); glRotatef(90, 1, 0, 0);
glTranslatef(0,BLOCKHEIGHT*(3+i*0.7),0); glTranslatef(0, BLOCKHEIGHT * (3 + i * 0.7), 0);
float r,g,b; float r, g, b;
switch(colors[i]){ switch (colors[i]) {
case FLOWER_RED: case FLOWER_RED:
r=1.0; g=0.0; b=0.0; r = 1.0;
g = 0.0;
b = 0.0;
break; break;
case FLOWER_YELLOW: case FLOWER_YELLOW:
r=1.0; g=1.0; b=0.0; r = 1.0;
g = 1.0;
b = 0.0;
break; break;
case FLOWER_WHITE: case FLOWER_WHITE:
r=1.0; g=1.0; b=1.0; r = 1.0;
g = 1.0;
b = 1.0;
break; break;
} }
glDisable(GL_CULL_FACE); glDisable(GL_CULL_FACE);
glColor3f(r,g,b); glColor3f(r, g, b);
createKnob(); createKnob();
/* Terälehdet tehdään triangle-fanilla */ /* Terälehdet tehdään triangle-fanilla */
glBegin(GL_TRIANGLE_FAN); glBegin(GL_TRIANGLE_FAN);
glNormal3f(0.0,1.0,0.0); glNormal3f(0.0, 1.0, 0.0);
glVertex3f(0.0,0.0,0.0); glVertex3f(0.0, 0.0, 0.0);
float x,z; float x, z;
for (j=0;j<24;j+=4){ for (j = 0; j < 24; j += 4) {
x=sin((j+0)*2*PI/24)*0.4; x = sin((j + 0) * 2 * PI / 24) * 0.4;
z=cos((j+0)*2*PI/24)*0.4; z = cos((j + 0) * 2 * PI / 24) * 0.4;
glVertex3f(x,0.0,z); glVertex3f(x, 0.0, z);
x=sin((j+1)*2*PI/24)*0.55; x = sin((j + 1) * 2 * PI / 24) * 0.55;
z=cos((j+1)*2*PI/24)*0.55; z = cos((j + 1) * 2 * PI / 24) * 0.55;
glVertex3f(x,0.0,z); glVertex3f(x, 0.0, z);
x=sin((j+2)*2*PI/24)*0.6; x = sin((j + 2) * 2 * PI / 24) * 0.6;
z=cos((j+2)*2*PI/24)*0.6; z = cos((j + 2) * 2 * PI / 24) * 0.6;
glVertex3f(x,0.0,z); glVertex3f(x, 0.0, z);
x=sin((j+3)*2*PI/24)*0.55; x = sin((j + 3) * 2 * PI / 24) * 0.55;
z=cos((j+3)*2*PI/24)*0.55; z = cos((j + 3) * 2 * PI / 24) * 0.55;
glVertex3f(x,0.0,z); glVertex3f(x, 0.0, z);
} }
glVertex3f(0,0.0,0.4); glVertex3f(0, 0.0, 0.4);
glEnd(); glEnd();
glEnable(GL_CULL_FACE); glEnable(GL_CULL_FACE);
glPopMatrix(); glPopMatrix();
glRotatef(120,0,1,0); glRotatef(120, 0, 1, 0);
} }
glPopMatrix(); glPopMatrix();
@ -342,46 +368,49 @@ void FlowerAppearance::prepare(void){
glEndList(); glEndList();
} }
void FlowerAppearance::draw(void){ void FlowerAppearance::draw(void) { glCallList(gllist); }
glCallList(gllist);
}
LampAppearance::LampAppearance(void) { gllist = glGenLists(1); }
void LampAppearance::prepare(void) {
LampAppearance::LampAppearance(void){
gllist = glGenLists(1);
}
void LampAppearance::prepare(void){
glNewList(gllist, GL_COMPILE); glNewList(gllist, GL_COMPILE);
glPushMatrix(); glPushMatrix();
//glTranslatef(0, -1, 0); // glTranslatef(0, -1, 0);
//glRotatef(180, 1, 0, 0); // glRotatef(180, 1, 0, 0);
glDisable(GL_LIGHTING); glDisable(GL_LIGHTING);
point2d lightpoints[11]; point2d lightpoints[11];
lightpoints[0].x=0.4; lightpoints[0].y=BLOCKHEIGHT*(0); lightpoints[0].x = 0.4;
lightpoints[1].x=0.55; lightpoints[1].y=BLOCKHEIGHT*(0); lightpoints[0].y = BLOCKHEIGHT * (0);
lightpoints[2].x=0.62; lightpoints[2].y=BLOCKHEIGHT*(0+0.15); lightpoints[1].x = 0.55;
lightpoints[3].x=0.65; lightpoints[3].y=BLOCKHEIGHT*(0+0.5); lightpoints[1].y = BLOCKHEIGHT * (0);
lightpoints[4].x=0.68; lightpoints[4].y=BLOCKHEIGHT*(0+1.25); lightpoints[2].x = 0.62;
lightpoints[5].x=0.65; lightpoints[5].y=BLOCKHEIGHT*(0+2); lightpoints[2].y = BLOCKHEIGHT * (0 + 0.15);
lightpoints[6].x=0.62; lightpoints[6].y=BLOCKHEIGHT*(0+2.35); lightpoints[3].x = 0.65;
lightpoints[7].x=0.55; lightpoints[7].y=BLOCKHEIGHT*(0+2.5); lightpoints[3].y = BLOCKHEIGHT * (0 + 0.5);
lightpoints[8].x=0.4; lightpoints[8].y=BLOCKHEIGHT*(0+2.5); lightpoints[4].x = 0.68;
lightpoints[9].x=0.4; lightpoints[9].y=BLOCKHEIGHT*(0+3); lightpoints[4].y = BLOCKHEIGHT * (0 + 1.25);
lightpoints[10].x=0.0; lightpoints[10].y=BLOCKHEIGHT*(0+3); lightpoints[5].x = 0.65;
glColor4f(0.8,0.8,0.8,0.5); lightpoints[5].y = BLOCKHEIGHT * (0 + 2);
lightpoints[6].x = 0.62;
lightpoints[6].y = BLOCKHEIGHT * (0 + 2.35);
lightpoints[7].x = 0.55;
lightpoints[7].y = BLOCKHEIGHT * (0 + 2.5);
lightpoints[8].x = 0.4;
lightpoints[8].y = BLOCKHEIGHT * (0 + 2.5);
lightpoints[9].x = 0.4;
lightpoints[9].y = BLOCKHEIGHT * (0 + 3);
lightpoints[10].x = 0.0;
lightpoints[10].y = BLOCKHEIGHT * (0 + 3);
glColor4f(0.8, 0.8, 0.8, 0.5);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
createLathedSurface(lightpoints,NULL,11,8,11); createLathedSurface(lightpoints, NULL, 11, 8, 11);
glEnable(GL_LIGHTING); glEnable(GL_LIGHTING);
@ -392,7 +421,6 @@ void LampAppearance::prepare(void){
glVertex3f(0, -100, 0); glVertex3f(0, -100, 0);
glEnd();*/ glEnd();*/
/*float screencoords[3] /*float screencoords[3]
getPointCoordinates(0,lighty,0); getPointCoordinates(0,lighty,0);
@ -438,13 +466,9 @@ void LampAppearance::prepare(void){
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity();*/ glLoadIdentity();*/
glPopMatrix(); glPopMatrix();
glEndList(); glEndList();
} }
void LampAppearance::draw(void){ void LampAppearance::draw(void) { glCallList(gllist); }
glCallList(gllist);
}

View file

@ -8,7 +8,7 @@
#define BLOCKHEIGHT 0.4 #define BLOCKHEIGHT 0.4
class BasicBlock : public MeshObject{ class BasicBlock : public MeshObject {
private: private:
int width, height, depth; int width, height, depth;
@ -18,8 +18,7 @@ public:
void setColor(float red, float green, float blue); void setColor(float red, float green, float blue);
}; };
class BasicBlockAppearance : public Appearance {
class BasicBlockAppearance : public Appearance{
private: private:
int width, height, depth; int width, height, depth;
int gllist; int gllist;
@ -43,9 +42,7 @@ extern int knobdetail;
void initKnob(void); void initKnob(void);
void createKnob(int knobsegments = -1); void createKnob(int knobsegments = -1);
class HeadAppearance : public Appearance {
class HeadAppearance : public Appearance{
private: private:
int gllist; int gllist;
@ -56,13 +53,11 @@ public:
void draw(void); void draw(void);
}; };
#define FLOWER_RED 1 #define FLOWER_RED 1
#define FLOWER_YELLOW 2 #define FLOWER_YELLOW 2
#define FLOWER_WHITE 3 #define FLOWER_WHITE 3
class FlowerAppearance : public Appearance{ class FlowerAppearance : public Appearance {
private: private:
int gllist; int gllist;
int color1, color2, color3; int color1, color2, color3;
@ -74,9 +69,7 @@ public:
void draw(void); void draw(void);
}; };
class LampAppearance : public Appearance {
class LampAppearance : public Appearance{
private: private:
int gllist; int gllist;
@ -87,5 +80,4 @@ public:
void draw(void); void draw(void);
}; };
#endif #endif

File diff suppressed because it is too large Load diff

View file

@ -23,22 +23,19 @@ class DamageVisual;
#define LEFTHAND 4 #define LEFTHAND 4
#define RIGHTHAND 8 #define RIGHTHAND 8
const char LEFTLEGASC[] = DATAPATH "blockolegscaled.asc";
const char LEFTLEGASC[] = DATAPATH"blockolegscaled.asc"; const char RIGHTLEGASC[] = DATAPATH "blockolegscaled.asc";
const char RIGHTLEGASC[] = DATAPATH"blockolegscaled.asc"; const char WAISTASC[] = DATAPATH "blockowaistscaled.asc";
const char WAISTASC[] = DATAPATH"blockowaistscaled.asc"; const char TORSOASC[] = DATAPATH "blockotorsoscaled.asc";
const char TORSOASC[] = DATAPATH"blockotorsoscaled.asc"; const char LEFTARMASC[] = DATAPATH "leftarm.asc";
const char LEFTARMASC[] = DATAPATH"leftarm.asc"; const char RIGHTARMASC[] = DATAPATH "rightarm.asc";
const char RIGHTARMASC[] = DATAPATH"rightarm.asc"; const char LEFTPALMASC[] = DATAPATH "leftpalm.asc";
const char LEFTPALMASC[] = DATAPATH"leftpalm.asc"; const char RIGHTPALMASC[] = DATAPATH "rightpalm.asc";
const char RIGHTPALMASC[] = DATAPATH"rightpalm.asc";
#define MODELSCALE 0.12 #define MODELSCALE 0.12
#define TORSOSCALE 0.115 #define TORSOSCALE 0.115
class BodyPart : public Object {
class BodyPart : public Object{
private: private:
float energy; float energy;
float strength; float strength;
@ -63,7 +60,7 @@ public:
friend class Legoman; friend class Legoman;
}; };
class Sensor{ class Sensor {
private: private:
float relativeposition[3]; float relativeposition[3];
Object *object; Object *object;
@ -84,7 +81,7 @@ public:
void getAcceleration(float *target); void getAcceleration(float *target);
}; };
class Legoman{ class Legoman {
private: private:
int side; int side;
@ -145,15 +142,15 @@ public:
void addOpponent(Legoman *opponent); void addOpponent(Legoman *opponent);
//Call once per frame // Call once per frame
void update(void); void update(void);
//Lock both legs at the same time by calling // Lock both legs at the same time by calling
//lockLeg(LEFTLEG | RIGHTLEG); // lockLeg(LEFTLEG | RIGHTLEG);
void lockPart(int part); void lockPart(int part);
void unlockPart(int part); void unlockPart(int part);
//Relative movement // Relative movement
void move(float *movement); void move(float *movement);
void turn(float amount); void turn(float amount);
@ -171,15 +168,12 @@ public:
friend void drawEnd(int framecount); friend void drawEnd(int framecount);
}; };
extern Texture *damageHead; extern Texture *damageHead;
extern Texture *damageTorso; extern Texture *damageTorso;
extern Texture *damageHand; extern Texture *damageHand;
extern Texture *damageLeg; extern Texture *damageLeg;
class DamageVisual {
class DamageVisual{
private: private:
BodyPart *object; BodyPart *object;
float x1, y1, x2, y2; float x1, y1, x2, y2;
@ -187,11 +181,10 @@ private:
Texture *texture; Texture *texture;
public: public:
DamageVisual(BodyPart *object, Texture *texture, bool mirror, DamageVisual(BodyPart *object, Texture *texture, bool mirror, float x1,
float x1, float y1, float x2, float y2); float y1, float x2, float y2);
void draw(void); void draw(void);
}; };
#endif #endif

View file

@ -9,7 +9,7 @@ static int glnextlightnum = 0;
static Light *lights[GL_MAX_LIGHTS]; static Light *lights[GL_MAX_LIGHTS];
Light::Light(void){ Light::Light(void) {
setPosition(0, 0, 0); setPosition(0, 0, 0);
setColor(1, 1, 1); setColor(1, 1, 1);
setSpecular(0, 0, 0); setSpecular(0, 0, 0);
@ -20,21 +20,21 @@ Light::Light(void){
glnextlightnum++; glnextlightnum++;
} }
void Light::setPosition(float x, float y, float z){ void Light::setPosition(float x, float y, float z) {
position[0] = x; position[0] = x;
position[1] = y; position[1] = y;
position[2] = z; position[2] = z;
position[3] = 1; position[3] = 1;
} }
void Light::setDirection(float x, float y, float z){ void Light::setDirection(float x, float y, float z) {
position[0] = -x; position[0] = -x;
position[1] = -y; position[1] = -y;
position[2] = -z; position[2] = -z;
position[3] = 0; position[3] = 0;
} }
void Light::setColor(float red, float green, float blue){ void Light::setColor(float red, float green, float blue) {
diffuse[0] = red; diffuse[0] = red;
diffuse[1] = green; diffuse[1] = green;
diffuse[2] = blue; diffuse[2] = blue;
@ -42,7 +42,7 @@ void Light::setColor(float red, float green, float blue){
glLightfv(glnum, GL_DIFFUSE, diffuse); glLightfv(glnum, GL_DIFFUSE, diffuse);
} }
void Light::setSpecular(float red, float green, float blue){ void Light::setSpecular(float red, float green, float blue) {
specular[0] = red; specular[0] = red;
specular[1] = green; specular[1] = green;
specular[2] = blue; specular[2] = blue;
@ -50,7 +50,7 @@ void Light::setSpecular(float red, float green, float blue){
glLightfv(glnum, GL_SPECULAR, specular); glLightfv(glnum, GL_SPECULAR, specular);
} }
void Light::setAttenuation(float constant, float linear, float quadratic){ void Light::setAttenuation(float constant, float linear, float quadratic) {
attenuation[0] = constant; attenuation[0] = constant;
attenuation[1] = linear; attenuation[1] = linear;
attenuation[2] = quadratic; attenuation[2] = quadratic;
@ -59,20 +59,19 @@ void Light::setAttenuation(float constant, float linear, float quadratic){
glLightf(glnum, GL_QUADRATIC_ATTENUATION, attenuation[2]); glLightf(glnum, GL_QUADRATIC_ATTENUATION, attenuation[2]);
} }
void Light::setEnabled(bool enabled){ void Light::setEnabled(bool enabled) {
this->enabled = enabled; this->enabled = enabled;
if (enabled) glEnable(glnum); if (enabled)
else glDisable(glnum); glEnable(glnum);
else
glDisable(glnum);
} }
void Light::glUpdate(void){ void Light::glUpdate(void) { glLightfv(glnum, GL_POSITION, position); }
glLightfv(glnum, GL_POSITION, position);
}
extern Camera camera; extern Camera camera;
void Light::createFlare(void) {
void Light::createFlare(void){
glPushMatrix(); glPushMatrix();
GLint viewport[4]; GLint viewport[4];
@ -109,30 +108,29 @@ void Light::createFlare(void){
float zd=(staticlightpositions[lightnumber].z-cameraposition.z)*cz; float zd=(staticlightpositions[lightnumber].z-cameraposition.z)*cz;
float distance=xd+yd+zd;*/ float distance=xd+yd+zd;*/
float screencoords[3]; float screencoords[3];
/*GLint viewport[4]; /*GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport); glGetIntegerv(GL_VIEWPORT, viewport);
int width=viewport[2]; int width=viewport[2];
int height=viewport[3];*/ int height=viewport[3];*/
GLdouble modelviewm[16], projectionm[16]; GLdouble modelviewm[16], projectionm[16];
glGetDoublev(GL_MODELVIEW_MATRIX, modelviewm); glGetDoublev(GL_MODELVIEW_MATRIX, modelviewm);
glGetDoublev(GL_PROJECTION_MATRIX, projectionm); glGetDoublev(GL_PROJECTION_MATRIX, projectionm);
GLdouble wx,wy,wz; GLdouble wx, wy, wz;
if (gluProject(0, 0, 0, modelviewm, projectionm, viewport, &wx, &wy, &wz) == GL_FALSE){ if (gluProject(0, 0, 0, modelviewm, projectionm, viewport, &wx, &wy, &wz) ==
GL_FALSE) {
printf("Failure\n"); printf("Failure\n");
} }
screencoords[0] = (float)(2*wx-width)/width; screencoords[0] = (float)(2 * wx - width) / width;
screencoords[1] = (float)(2*wy-height)/height; screencoords[1] = (float)(2 * wy - height) / height;
screencoords[2] = wz; screencoords[2] = wz;
// getPointCoordinates(screencoords);
//getPointCoordinates(screencoords); // point3d screencoords = getPointCoordinates(0, 0, 0);
//point3d screencoords = getPointCoordinates(0, 0, 0);
glLoadIdentity(); glLoadIdentity();
glTranslatef(screencoords[0], screencoords[1], 0); glTranslatef(screencoords[0], screencoords[1], 0);
@ -140,36 +138,37 @@ void Light::createFlare(void){
glEnable(GL_CULL_FACE); glEnable(GL_CULL_FACE);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_ONE,GL_ONE); glBlendFunc(GL_ONE, GL_ONE);
//glEnable(GL_TEXTURE_2D); // glEnable(GL_TEXTURE_2D);
//glBindTexture(GL_TEXTURE_2D, flaretexture->getId()); // glBindTexture(GL_TEXTURE_2D, flaretexture->getId());
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glPushMatrix(); glPushMatrix();
glLoadIdentity(); glLoadIdentity();
float sizey = 6.0/distance * 1.0;//staticlightflarebrightnesses[lightnumber]; float sizey =
float sizex = sizey * height/width; 6.0 / distance * 1.0; // staticlightflarebrightnesses[lightnumber];
float sizex = sizey * height / width;
if (distance>0.5){ if (distance > 0.5) {
glBegin(GL_QUADS); glBegin(GL_QUADS);
//glColor3f(staticlightflarebrightnesses[lightnumber],staticlightflarebrightnesses[lightnumber],staticlightflarebrightnesses[lightnumber]); // glColor3f(staticlightflarebrightnesses[lightnumber],staticlightflarebrightnesses[lightnumber],staticlightflarebrightnesses[lightnumber]);
glColor3fv(diffuse); glColor3fv(diffuse);
glTexCoord2f(0.0, 0.0); glTexCoord2f(0.0, 0.0);
glVertex2f(-sizex,sizey); glVertex2f(-sizex, sizey);
glTexCoord2f(0.0, 1.0); glTexCoord2f(0.0, 1.0);
glVertex2f(-sizex,-sizey); glVertex2f(-sizex, -sizey);
glTexCoord2f(1.0, 1.0); glTexCoord2f(1.0, 1.0);
glVertex2f( sizex,-sizey); glVertex2f(sizex, -sizey);
glTexCoord2f(1.0, 0.0); glTexCoord2f(1.0, 0.0);
glVertex2f( sizex,sizey); glVertex2f(sizex, sizey);
glEnd(); glEnd();
} }
//glDisable(GL_TEXTURE_2D); // glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND); glDisable(GL_BLEND);
@ -177,15 +176,16 @@ void Light::createFlare(void){
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); glLoadIdentity();
if (lightingenabled) glEnable(GL_LIGHTING); if (lightingenabled)
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glPopMatrix(); glPopMatrix();
} }
void updateLights(void){ void updateLights(void) {
int i; int i;
for (i = 0; i < glnextlightnum; i++){ for (i = 0; i < glnextlightnum; i++) {
Light *light = lights[i]; Light *light = lights[i];
light->glUpdate(); light->glUpdate();
} }

View file

@ -1,7 +1,7 @@
#ifndef __LIGHT_H_INCLUDED__ #ifndef __LIGHT_H_INCLUDED__
#define __LIGHT_H_INCLUDED__ #define __LIGHT_H_INCLUDED__
class Light{ class Light {
private: private:
float position[4]; float position[4];
float diffuse[4]; float diffuse[4];
@ -11,7 +11,7 @@ private:
int glnum; int glnum;
public: public:
//Creates DISABLED light // Creates DISABLED light
Light(void); Light(void);
void setPosition(float x, float y, float z); void setPosition(float x, float y, float z);
@ -27,4 +27,3 @@ public:
void updateLights(void); void updateLights(void);
#endif #endif

View file

@ -16,21 +16,23 @@
#include "glapi.h" #include "glapi.h"
int screenwidth=1024; int screenwidth = 1024;
int screenheight=768; int screenheight = 768;
int screenbpp; int screenbpp;
void exitProgram(int code){ void exitProgram(int code) {
SDL_Quit(); SDL_Quit();
//uninitAudio(); // uninitAudio();
exit(code); exit(code);
} }
void changeResolution(int width, int height, bool fullscreen){ void changeResolution(int width, int height, bool fullscreen) {
int mode = SDL_OPENGL; int mode = SDL_OPENGL;
if (fullscreen) mode |= SDL_FULLSCREEN; if (fullscreen)
if (!SDL_SetVideoMode(width, height, screenbpp, mode)){ mode |= SDL_FULLSCREEN;
fprintf(stderr,"Couldn't set %i*%i*%i opengl video mode: %s\n",screenwidth,screenheight,screenbpp,SDL_GetError()); if (!SDL_SetVideoMode(width, height, screenbpp, mode)) {
fprintf(stderr, "Couldn't set %i*%i*%i opengl video mode: %s\n",
screenwidth, screenheight, screenbpp, SDL_GetError());
exitProgram(-1); exitProgram(-1);
} }
@ -39,28 +41,24 @@ void changeResolution(int width, int height, bool fullscreen){
screenwidth = width; screenwidth = width;
screenheight = height; screenheight = height;
if (fullscreen) SDL_ShowCursor(SDL_DISABLE); if (fullscreen)
else SDL_ShowCursor(SDL_ENABLE); SDL_ShowCursor(SDL_DISABLE);
else
SDL_ShowCursor(SDL_ENABLE);
initScenes(); initScenes();
} }
bool keys[SDLK_LAST] = {false}; bool keys[SDLK_LAST] = {false};
void handleKeydown(SDL_keysym *keysym){ void handleKeydown(SDL_keysym *keysym) { keys[keysym->sym] = true; }
keys[keysym->sym] = true;
}
void handleKeyup(SDL_keysym *keysym) { keys[keysym->sym] = false; }
void handleKeyup(SDL_keysym *keysym){ void processEvents(void) {
keys[keysym->sym] = false;
}
void processEvents(void){
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)){ while (SDL_PollEvent(&event)) {
switch (event.type){ switch (event.type) {
case SDL_KEYDOWN: case SDL_KEYDOWN:
handleKeydown(&event.key.keysym); handleKeydown(&event.key.keysym);
break; break;
@ -68,9 +66,9 @@ void processEvents(void){
handleKeyup(&event.key.keysym); handleKeyup(&event.key.keysym);
break; break;
case SDL_VIDEORESIZE: case SDL_VIDEORESIZE:
screenwidth=event.resize.w; screenwidth = event.resize.w;
screenheight=event.resize.h; screenheight = event.resize.h;
setupOpengl(screenwidth,screenheight); setupOpengl(screenwidth, screenheight);
break; break;
case SDL_QUIT: case SDL_QUIT:
exitProgram(0); exitProgram(0);
@ -79,7 +77,7 @@ void processEvents(void){
} }
} }
int getTime(void){ int getTime(void) {
#ifdef WIN32 #ifdef WIN32
return timeGetTime(); return timeGetTime();
#else #else
@ -87,56 +85,53 @@ int getTime(void){
#endif #endif
} }
int main(int argc, char *argv[]){ int main(int argc, char *argv[]) {
//printf("Initializing SDL.\n"); // printf("Initializing SDL.\n");
if ((SDL_Init(SDL_INIT_VIDEO)==-1)){ if ((SDL_Init(SDL_INIT_VIDEO) == -1)) {
printf("Could not initialize SDL: %s.\n",SDL_GetError()); printf("Could not initialize SDL: %s.\n", SDL_GetError());
exitProgram(-1); exitProgram(-1);
} }
const SDL_VideoInfo *info=SDL_GetVideoInfo(); const SDL_VideoInfo *info = SDL_GetVideoInfo();
if (!info){ if (!info) {
printf("Could not get video info with SDL: %s.\n",SDL_GetError()); printf("Could not get video info with SDL: %s.\n", SDL_GetError());
exitProgram(-1); exitProgram(-1);
} }
screenbpp=info->vfmt->BitsPerPixel; screenbpp = info->vfmt->BitsPerPixel;
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
atexit(SDL_Quit); atexit(SDL_Quit);
SDL_WM_SetCaption("BlockoFighter 2",NULL); SDL_WM_SetCaption("BlockoFighter 2", NULL);
initAudio(); initAudio();
changeResolution(screenwidth, screenheight, false); changeResolution(screenwidth, screenheight, false);
//printf("SDL initialized.\n"); // printf("SDL initialized.\n");
double calculatefps = 200.0; double calculatefps = 200.0;
int framecounter, oldframecounter = 0; int framecounter, oldframecounter = 0;
int currenttime; int currenttime;
int framesdrawn=0; int framesdrawn = 0;
int skipframes; int skipframes;
int starttime = getTime(); int starttime = getTime();
while (1){ while (1) {
do{ do {
currenttime = getTime()-starttime; currenttime = getTime() - starttime;
framecounter = calculatefps*currenttime/1000.0; framecounter = calculatefps * currenttime / 1000.0;
} while (oldframecounter == framecounter); } while (oldframecounter == framecounter);
skipframes = framecounter - oldframecounter; skipframes = framecounter - oldframecounter;
for (; skipframes > 0; skipframes--){ for (; skipframes > 0; skipframes--) {
calculateFrame(++oldframecounter); calculateFrame(++oldframecounter);
} }
//calculateFrame(oldframecounter++); // calculateFrame(oldframecounter++);
processEvents(); processEvents();
drawFrame(framecounter); drawFrame(framecounter);
framesdrawn++; framesdrawn++;

View file

@ -1,10 +1,11 @@
#ifndef __MAIN_H_INCLUDED__ #ifndef __MAIN_H_INCLUDED__
#define __MAIN_H_INCLUDED__ #define __MAIN_H_INCLUDED__
#ifdef WIN32 #ifdef WIN32
#pragma warning(disable:4244) //Disable: conversion from 'double' to 'double', possible loss of data #pragma warning(disable : 4244) // Disable: conversion from 'double' to
#pragma warning(disable:4305) //Disable: truncation from 'const double' to 'double' // 'double', possible loss of data
#pragma warning( \
disable : 4305) // Disable: truncation from 'const double' to 'double'
#endif #endif
#include <SDL.h> #include <SDL.h>
@ -18,10 +19,10 @@ extern int screenwidth, screenheight;
extern int debugcounter; extern int debugcounter;
#ifdef DEBUG #ifdef DEBUG
#define DP printf("%s: %i (Debug counter: %i)\n",__FILE__,__LINE__,debugcounter++); #define DP \
printf("%s: %i (Debug counter: %i)\n", __FILE__, __LINE__, debugcounter++);
#else #else
#define DP #define DP
#endif #endif
#endif #endif

View file

@ -4,57 +4,49 @@
#include "glapi.h" #include "glapi.h"
#include "graphics.h" #include "graphics.h"
Material::Material(void){ Material::Material(void) {
setColor(1, 1, 1, 1); setColor(1, 1, 1, 1);
this->texture = new Texture; this->texture = new Texture;
} }
bool Material::loadTexture(char *path){ bool Material::loadTexture(char *path) {
if (!this->texture){ if (!this->texture) {
this->texture = new Texture; this->texture = new Texture;
} }
if (this->texture->loadImage(path)){ if (this->texture->loadImage(path)) {
setColor(1, 1, 1, 1); setColor(1, 1, 1, 1);
return true; return true;
} }
return false; return false;
} }
void Material::freeTexture(void){ void Material::freeTexture(void) { this->texture->~Texture(); }
this->texture->~Texture();
}
void Material::setColor(float red, float green, float blue, float alpha){ void Material::setColor(float red, float green, float blue, float alpha) {
color[0] = red; color[0] = red;
color[1] = green; color[1] = green;
color[2] = blue; color[2] = blue;
color[3] = alpha; color[3] = alpha;
} }
const float* Material::getColor(void){ const float *Material::getColor(void) { return color; }
return color;
}
void Material::enable(void){ void Material::enable(void) {
enabled = true; enabled = true;
glColor4fv(color); glColor4fv(color);
this->texture->enable(); this->texture->enable();
} }
void Material::disable(void){ void Material::disable(void) {
enabled = false; enabled = false;
this->texture->disable(); this->texture->disable();
} }
bool Material::isEnabled(void){ bool Material::isEnabled(void) { return enabled; }
return enabled;
}
Texture* Material::getTexture(void){ Texture *Material::getTexture(void) { return this->texture; }
return this->texture;
}
void Material::setTexture(Texture* tex){ void Material::setTexture(Texture *tex) {
//this->texture->~Texture; // this->texture->~Texture;
this->texture = tex; this->texture = tex;
} }

View file

@ -4,9 +4,9 @@
#include <SDL_image.h> #include <SDL_image.h>
#include "texture.h" #include "texture.h"
class Material{ class Material {
private: private:
Texture* texture; Texture *texture;
float color[4]; float color[4];
bool enabled; bool enabled;
@ -16,14 +16,12 @@ public:
void freeTexture(void); void freeTexture(void);
void setColor(float red, float green, float blue, float alpha); void setColor(float red, float green, float blue, float alpha);
const float* getColor(void); const float *getColor(void);
void enable(void); void enable(void);
void disable(void); void disable(void);
bool isEnabled(void); bool isEnabled(void);
Texture* getTexture(void); Texture *getTexture(void);
void setTexture(Texture* tex); void setTexture(Texture *tex);
}; };
#endif #endif

View file

@ -34,53 +34,50 @@ Sound *menumusic;
bool menuinitialized = false; bool menuinitialized = false;
void initMenu(void){ void initMenu(void) {
if (!menuinitialized){ if (!menuinitialized) {
titleworld = new World(); titleworld = new World();
} }
titlelight.setColor(1, 1, 1); titlelight.setColor(1, 1, 1);
titlelight.setSpecular(1, 1, 1); titlelight.setSpecular(1, 1, 1);
titlelight.setPosition(-0.5, BLOCKHEIGHT*16, 0.5); titlelight.setPosition(-0.5, BLOCKHEIGHT * 16, 0.5);
titlelight.setAttenuation(0.0, 0.0, 0.01); titlelight.setAttenuation(0.0, 0.0, 0.01);
if (!menuinitialized){ if (!menuinitialized) {
Object *lamp; Object *lamp;
lamp = new Object(); lamp = new Object();
lamp->appearance = new LampAppearance(); lamp->appearance = new LampAppearance();
lamp->setPosition(-0.5, BLOCKHEIGHT*15.5, 0.5); lamp->setPosition(-0.5, BLOCKHEIGHT * 15.5, 0.5);
titleworld->addChild(lamp); titleworld->addChild(lamp);
// Floor
//Floor
BasicBlock *floorblock; BasicBlock *floorblock;
floorblock = new BasicBlock(33, 1, 5); floorblock = new BasicBlock(33, 1, 5);
floorblock->setPosition(-0.5, -BLOCKHEIGHT/2.0 + BLOCKHEIGHT*(4*3+1), 0.5-5); floorblock->setPosition(
-0.5, -BLOCKHEIGHT / 2.0 + BLOCKHEIGHT * (4 * 3 + 1), 0.5 - 5);
floorblock->setColor(0, 1, 0); floorblock->setColor(0, 1, 0);
titleworld->addChild(floorblock); titleworld->addChild(floorblock);
floorblock = new BasicBlock(41, 1, 10); floorblock = new BasicBlock(41, 1, 10);
floorblock->setPosition(8.5-5, -BLOCKHEIGHT/2.0, 0.5-2.5); floorblock->setPosition(8.5 - 5, -BLOCKHEIGHT / 2.0, 0.5 - 2.5);
floorblock->setColor(0, 1, 0); floorblock->setColor(0, 1, 0);
titleworld->addChild(floorblock); titleworld->addChild(floorblock);
floorblock = new BasicBlock(1, 4*3, 1); floorblock = new BasicBlock(1, 4 * 3, 1);
floorblock->setPosition(-14.5, BLOCKHEIGHT*4*3/2.0, 0.5-5); floorblock->setPosition(-14.5, BLOCKHEIGHT * 4 * 3 / 2.0, 0.5 - 5);
floorblock->setColor(1, 0, 0); floorblock->setColor(1, 0, 0);
titleworld->addChild(floorblock); titleworld->addChild(floorblock);
floorblock = new BasicBlock(1, 4*3, 1); floorblock = new BasicBlock(1, 4 * 3, 1);
floorblock->setPosition(13.5, BLOCKHEIGHT*4*3/2.0, 0.5-5); floorblock->setPosition(13.5, BLOCKHEIGHT * 4 * 3 / 2.0, 0.5 - 5);
floorblock->setColor(1, 0, 0); floorblock->setColor(1, 0, 0);
titleworld->addChild(floorblock); titleworld->addChild(floorblock);
// Letters
// B
//Letters
//B
/*int Bsize = 8; /*int Bsize = 8;
int Bwidth = 5; int Bwidth = 5;
int Bletter[8][4] = { int Bletter[8][4] = {
@ -96,8 +93,7 @@ void initMenu(void){
{4, 6, 1, 3}};*/ {4, 6, 1, 3}};*/
int Bsize = 10; int Bsize = 10;
int Bwidth = 5; int Bwidth = 5;
int Bletter[10][4] = { int Bletter[10][4] = {{0, 0, 4, 1},
{0, 0, 4, 1},
{0, 4, 4, 1}, {0, 4, 4, 1},
{0, 8, 4, 1}, {0, 8, 4, 1},
{0, 1, 1, 7}, {0, 1, 1, 7},
@ -108,42 +104,32 @@ void initMenu(void){
{4, 2, 1, 1}, {4, 2, 1, 1},
{4, 6, 1, 1}}; {4, 6, 1, 1}};
//l // l
int lsize = 2; int lsize = 2;
int lwidth = 4; int lwidth = 4;
int lletter[2][4] = { int lletter[2][4] = {{0, 0, 4, 1}, {0, 1, 1, 4}};
{0, 0, 4, 1},
{0, 1, 1, 4}};
//o // o
int osize = 4; int osize = 4;
int owidth = 4; int owidth = 4;
int oletter[4][4] = { int oletter[4][4] = {
{0, 0, 4, 1}, {0, 0, 4, 1}, {0, 4, 4, 1}, {0, 1, 1, 3}, {3, 1, 1, 3}};
{0, 4, 4, 1},
{0, 1, 1, 3},
{3, 1, 1, 3}};
//c // c
int csize = 5; int csize = 5;
int cwidth = 4; int cwidth = 4;
int cletter[5][4] = { int cletter[5][4] = {
{0, 0, 4, 1}, {0, 0, 4, 1}, {0, 4, 4, 1}, {0, 1, 1, 3}, {3, 1, 1, 1}, {3, 3, 1, 1}};
{0, 4, 4, 1},
{0, 1, 1, 3},
{3, 1, 1, 1},
{3, 3, 1, 1}};
/* {1, 0, 2, 1}, /* {1, 0, 2, 1},
{1, 4, 2, 1}, {1, 4, 2, 1},
{0, 1, 1, 3}, {0, 1, 1, 3},
{3, 1, 1, 1}, {3, 1, 1, 1},
{3, 3, 1, 1}};*/ {3, 3, 1, 1}};*/
//k // k
int ksize = 6; int ksize = 6;
int kwidth = 4; int kwidth = 4;
int kletter[6][4] = { int kletter[6][4] = {{0, 0, 1, 5},
{0, 0, 1, 5},
{1, 2, 2, 1}, {1, 2, 2, 1},
{2, 1, 2, 1}, {2, 1, 2, 1},
{2, 3, 2, 1}, {2, 3, 2, 1},
@ -156,145 +142,91 @@ void initMenu(void){
{3, 0, 1, 1}, {3, 0, 1, 1},
{3, 4, 1, 1}};*/ {3, 4, 1, 1}};*/
//F // F
int Fsize = 3; int Fsize = 3;
int Fwidth = 3; int Fwidth = 3;
int Fletter[3][4] = { int Fletter[3][4] = {{0, 0, 1, 7}, {0, 4, 3, 1}, {0, 7, 6, 1}};
{0, 0, 1, 7},
{0, 4, 3, 1},
{0, 7, 6, 1}};
//i // i
int isize = 1; int isize = 1;
int iwidth = 1; int iwidth = 1;
int iletter[1][4] = { int iletter[1][4] = {{0, 0, 1, 4}};
{0, 0, 1, 4}};
//g // g
int gsize = 5; int gsize = 5;
int gwidth = 4; int gwidth = 4;
int gletter[5][4] = { int gletter[5][4] = {
{0, 0, 4, 1}, {0, 0, 4, 1}, {0, 4, 4, 1}, {0, 1, 1, 3}, {3, 1, 1, 1}, {2, 2, 2, 1}};
{0, 4, 4, 1},
{0, 1, 1, 3},
{3, 1, 1, 1},
{2, 2, 2, 1}};
//h // h
int hsize = 3; int hsize = 3;
int hwidth = 1; int hwidth = 1;
int hletter[3][4] = { int hletter[3][4] = {{0, 0, 1, 5}, {3, 0, 1, 5}, {0, 2, 4, 1}};
{0, 0, 1, 5},
{3, 0, 1, 5},
{0, 2, 4, 1}};
//t // t
int tsize = 2; int tsize = 2;
int twidth = 4; int twidth = 4;
int tletter[2][4] = { int tletter[2][4] = {{3, 0, 1, 6}, {0, 6, 7, 1}};
{3, 0, 1, 6},
{0, 6, 7, 1}};
//e // e
int esize = 5; int esize = 5;
int ewidth = 4; int ewidth = 4;
int eletter[5][4] = { int eletter[5][4] = {
{0, 0, 4, 1}, {0, 0, 4, 1}, {0, 4, 4, 1}, {0, 2, 3, 1}, {0, 1, 1, 1}, {0, 3, 1, 1}};
{0, 4, 4, 1},
{0, 2, 3, 1},
{0, 1, 1, 1},
{0, 3, 1, 1}};
//r // r
int rsize = 6; int rsize = 6;
int rwidth = 4; int rwidth = 4;
int rletter[6][4] = { int rletter[6][4] = {{0, 0, 1, 5},
{0, 0, 1, 5},
{0, 2, 3, 1}, {0, 2, 3, 1},
{0, 4, 3, 1}, {0, 4, 3, 1},
{2, 1, 2, 1}, {2, 1, 2, 1},
{3, 0, 1, 1}, {3, 0, 1, 1},
{2, 3, 2, 1}}; {2, 3, 2, 1}};
/*int rsize = 5; /*int rsize = 5;
int rwidth = 4; int rwidth = 4;
int rletter[5][4] = { int rletter[5][4] = {
{0, 0, 1, 5}, {0, 0, 1, 5},
{0, 2, 3, 1}, {0, 2, 3, 1},
{0, 4, 3, 1}, {0, 4, 3, 1},
{3, 0, 1, 2}, {3, 0, 1, 2},
{3, 3, 1, 1}};*/ {3, 3, 1, 1}};*/
#define LETTERCOUNT 6 #define LETTERCOUNT 6
int lettersizes[LETTERCOUNT] = { int lettersizes[LETTERCOUNT] = {Bsize, lsize, osize, csize, ksize, osize};
Bsize, int letterwidths[LETTERCOUNT] = {Bwidth, lwidth, owidth,
lsize, cwidth, kwidth, owidth};
osize, int *letters[LETTERCOUNT] = {&Bletter[0][0], &lletter[0][0],
csize, &oletter[0][0], &cletter[0][0],
ksize, &kletter[0][0], &oletter[0][0]};
osize
};
int letterwidths[LETTERCOUNT] = {
Bwidth,
lwidth,
owidth,
cwidth,
kwidth,
owidth
};
int *letters[LETTERCOUNT] = {
&Bletter[0][0],
&lletter[0][0],
&oletter[0][0],
&cletter[0][0],
&kletter[0][0],
&oletter[0][0]
};
#define LETTERCOUNT2 7 #define LETTERCOUNT2 7
int lettersizes2[LETTERCOUNT2] = { int lettersizes2[LETTERCOUNT2] = {Fsize, isize, gsize, hsize,
Fsize, tsize, esize, rsize};
isize, int letterwidths2[LETTERCOUNT2] = {Fwidth, iwidth, gwidth, hwidth,
gsize, twidth, ewidth, rwidth};
hsize,
tsize,
esize,
rsize
};
int letterwidths2[LETTERCOUNT2] = {
Fwidth,
iwidth,
gwidth,
hwidth,
twidth,
ewidth,
rwidth
};
int *letters2[LETTERCOUNT2] = { int *letters2[LETTERCOUNT2] = {
&Fletter[0][0], &Fletter[0][0], &iletter[0][0], &gletter[0][0], &hletter[0][0],
&iletter[0][0], &tletter[0][0], &eletter[0][0], &rletter[0][0]};
&gletter[0][0],
&hletter[0][0],
&tletter[0][0],
&eletter[0][0],
&rletter[0][0]
};
BasicBlock *letterblock; BasicBlock *letterblock;
float z = 0.5; float z = 0.5;
int i, j; int i, j;
int dx = -15; int dx = -15;
int dy = BLOCKHEIGHT*(4*3+1); int dy = BLOCKHEIGHT * (4 * 3 + 1);
int dz = -5; int dz = -5;
for (i = 0; i < LETTERCOUNT; i++){ for (i = 0; i < LETTERCOUNT; i++) {
int size = lettersizes[i]; int size = lettersizes[i];
int width = letterwidths[i]; int width = letterwidths[i];
for (j = 0; j < size; j++){ for (j = 0; j < size; j++) {
int x = letters[i][j*4+0]; int x = letters[i][j * 4 + 0];
int y = letters[i][j*4+1]*3; int y = letters[i][j * 4 + 1] * 3;
int w = letters[i][j*4+2]; int w = letters[i][j * 4 + 2];
int h = letters[i][j*4+3]*3; int h = letters[i][j * 4 + 3] * 3;
letterblock = new BasicBlock(w, h, 1); letterblock = new BasicBlock(w, h, 1);
letterblock->setPosition(dx+x+w/2.0, dy+BLOCKHEIGHT*(y+h/2.0), dz+z + randomf(0.1)); letterblock->setPosition(dx + x + w / 2.0,
dy + BLOCKHEIGHT * (y + h / 2.0),
dz + z + randomf(0.1));
letterblock->setColor(1, 0.5, 1); letterblock->setColor(1, 0.5, 1);
titleworld->addChild(letterblock); titleworld->addChild(letterblock);
} }
@ -303,48 +235,49 @@ void initMenu(void){
dx = -5; dx = -5;
dy = 0; dy = 0;
dz = 0; dz = 0;
for (i = 0; i < LETTERCOUNT2; i++){ for (i = 0; i < LETTERCOUNT2; i++) {
int size = lettersizes2[i]; int size = lettersizes2[i];
int width = letterwidths2[i]; int width = letterwidths2[i];
for (j = 0; j < size; j++){ for (j = 0; j < size; j++) {
int x = letters2[i][j*4+0]; int x = letters2[i][j * 4 + 0];
int y = letters2[i][j*4+1]*3; int y = letters2[i][j * 4 + 1] * 3;
int w = letters2[i][j*4+2]; int w = letters2[i][j * 4 + 2];
int h = letters2[i][j*4+3]*3; int h = letters2[i][j * 4 + 3] * 3;
letterblock = new BasicBlock(w, h, 1); letterblock = new BasicBlock(w, h, 1);
letterblock->setPosition(dx+x+w/2.0, dy+BLOCKHEIGHT*(y+h/2.0), dz+z + randomf(0.1)); letterblock->setPosition(dx + x + w / 2.0,
//float rotate[3] = {0, randomf(0.1), 0}; dy + BLOCKHEIGHT * (y + h / 2.0),
//matrixCreateRotation(letterblock->rotation, rotate); dz + z + randomf(0.1));
// float rotate[3] = {0, randomf(0.1), 0};
// matrixCreateRotation(letterblock->rotation, rotate);
letterblock->setColor(1, 0.5, 1); letterblock->setColor(1, 0.5, 1);
titleworld->addChild(letterblock); titleworld->addChild(letterblock);
} }
dx += width + 1; dx += width + 1;
} }
Object *flower; Object *flower;
flower = new Object(); flower = new Object();
flower->appearance = new FlowerAppearance(FLOWER_RED, FLOWER_WHITE, FLOWER_YELLOW); flower->appearance =
new FlowerAppearance(FLOWER_RED, FLOWER_WHITE, FLOWER_YELLOW);
flower->setPosition(-7.5, 0, 1.5); flower->setPosition(-7.5, 0, 1.5);
titleworld->addChild(flower); titleworld->addChild(flower);
flower = new Object(); flower = new Object();
flower->appearance = new FlowerAppearance(FLOWER_YELLOW, FLOWER_RED, FLOWER_YELLOW); flower->appearance =
new FlowerAppearance(FLOWER_YELLOW, FLOWER_RED, FLOWER_YELLOW);
flower->setPosition(-11.5, 0, -2.5); flower->setPosition(-11.5, 0, -2.5);
titleworld->addChild(flower); titleworld->addChild(flower);
flower = new Object(); flower = new Object();
flower->appearance = new FlowerAppearance(FLOWER_WHITE, FLOWER_WHITE, FLOWER_RED); flower->appearance =
new FlowerAppearance(FLOWER_WHITE, FLOWER_WHITE, FLOWER_RED);
flower->setPosition(-14.5, 0, 0.5); flower->setPosition(-14.5, 0, 0.5);
titleworld->addChild(flower); titleworld->addChild(flower);
changesound = new Sound(DATAPATH "menuchange.wav");
selectsound = new Sound(DATAPATH "menuselect.wav");
changesound = new Sound(DATAPATH"menuchange.wav"); menumusic = new Sound(DATAPATH "menu.mp3", true);
selectsound = new Sound(DATAPATH"menuselect.wav");
menumusic = new Sound(DATAPATH"menu.mp3", true);
} }
titleworld->prepare(); titleworld->prepare();
@ -381,25 +314,21 @@ int olddetail;
int detail = 2; int detail = 2;
#define RESOLUTIONCOUNT 6 #define RESOLUTIONCOUNT 6
int resolutions[RESOLUTIONCOUNT][2] = { int resolutions[RESOLUTIONCOUNT][2] = {{640, 480},
{640, 480},
{800, 600}, {800, 600},
{1024, 768}, {1024, 768},
{1280, 960}, {1280, 960},
{1280, 1024}, {1280, 1024},
{1600, 1200} {1600, 1200}};
};
#define DETAILCOUNT 4 #define DETAILCOUNT 4
char *details[DETAILCOUNT] = {"Off", "Low", "Medium", "High"}; char *details[DETAILCOUNT] = {"Off", "Low", "Medium", "High"};
int menurestartcounter = -1; int menurestartcounter = -1;
void menuRestart(void){ void menuRestart(void) { menurestartcounter = 0; }
menurestartcounter = 0;
}
void menuMain(void){ void menuMain(void) {
interpolator = 0.0; interpolator = 0.0;
menumode = MODEMAIN; menumode = MODEMAIN;
menuoption = MAINOPTIONS; menuoption = MAINOPTIONS;
@ -415,20 +344,20 @@ int gamestart = 0;
bool loading = true; bool loading = true;
void menuStartGame(void){ void menuStartGame(void) {
menumusic->fadeOut(300); menumusic->fadeOut(300);
gamestart = 200; gamestart = 200;
menurestartcounter = -1; menurestartcounter = -1;
} }
void menuStartGame2(void){ void menuStartGame2(void) {
titlelight.setEnabled(false); titlelight.setEnabled(false);
changeGameMode(FIGHTMODE); changeGameMode(FIGHTMODE);
startFight(); startFight();
menurestartcounter = -1; menurestartcounter = -1;
} }
void menuOptions(void){ void menuOptions(void) {
interpolator = 0.0; interpolator = 0.0;
menumode = MODEOPTIONS; menumode = MODEOPTIONS;
menuoption = OPTIONSRESOLUTION; menuoption = OPTIONSRESOLUTION;
@ -442,67 +371,68 @@ void menuOptions(void){
int quitcounter = -1; int quitcounter = -1;
void menuEscPressed(void){ void menuEscPressed(void) {
menurestartcounter = -1; menurestartcounter = -1;
//menumusic->stop(); // menumusic->stop();
menumusic->fadeOut(200); menumusic->fadeOut(200);
quitcounter = 0; quitcounter = 0;
} }
void menuQuit(void){ void menuQuit(void) { exitProgram(0); }
exitProgram(0);
}
void menuResolution(int dir) {
void menuResolution(int dir){
resolution += dir; resolution += dir;
if (resolution < 0) resolution = 0; if (resolution < 0)
if (resolution >= RESOLUTIONCOUNT) resolution = RESOLUTIONCOUNT-1; resolution = 0;
//resolution = (resolution + RESOLUTIONCOUNT) % RESOLUTIONCOUNT; if (resolution >= RESOLUTIONCOUNT)
resolution = RESOLUTIONCOUNT - 1;
// resolution = (resolution + RESOLUTIONCOUNT) % RESOLUTIONCOUNT;
} }
void calculateMenu(int framecount){ void calculateMenu(int framecount) {
if (framecount == 1){ if (framecount == 1) {
menumusic->setVolume(0); menumusic->setVolume(0);
menumusic->play(); menumusic->play();
menumusic->fadeIn(300); menumusic->fadeIn(300);
} }
if (menurestartcounter != -1){ if (menurestartcounter != -1) {
menurestartcounter++; menurestartcounter++;
if (menurestartcounter == 300){ if (menurestartcounter == 300) {
menumusic->play(); menumusic->play();
menumusic->fadeIn(100); menumusic->fadeIn(100);
menurestartcounter = -1; menurestartcounter = -1;
} }
} }
menufade = -1; menufade = -1;
titlelight.setEnabled(true); titlelight.setEnabled(true);
if (framecount < 200){ if (framecount < 200) {
menufade = 1-framecount/200.0; menufade = 1 - framecount / 200.0;
} else{ } else {
loading = false; loading = false;
} }
if (gamestart > 0){ if (gamestart > 0) {
gamestart--; gamestart--;
if (gamestart == 0){ if (gamestart == 0) {
menuStartGame2(); menuStartGame2();
} }
menufade = (200-gamestart)/200.0; menufade = (200 - gamestart) / 200.0;
} }
if (quitcounter != -1){ if (quitcounter != -1) {
menufade = quitcounter/200.0; menufade = quitcounter / 200.0;
quitcounter++; quitcounter++;
if (quitcounter == 200) menuQuit(); if (quitcounter == 200)
menuQuit();
} }
float cameratarget[3] = {0, 0, 0}; float cameratarget[3] = {0, 0, 0};
titlecamera.setPosition(sin(framecount*0.001)*2-8, sin(framecount*0.0033)*2+15, cos(framecount*0.001)*2+25); titlecamera.setPosition(sin(framecount * 0.001) * 2 - 8,
sin(framecount * 0.0033) * 2 + 15,
cos(framecount * 0.001) * 2 + 25);
titlecamera.setTarget(cameratarget); titlecamera.setTarget(cameratarget);
titleworld->move(); titleworld->move();
@ -510,7 +440,7 @@ void calculateMenu(int framecount){
xres = resolutions[resolution][0]; xres = resolutions[resolution][0];
yres = resolutions[resolution][1]; yres = resolutions[resolution][1];
switch(menumode){ switch (menumode) {
case MODEMAIN: case MODEMAIN:
maxoption = 2; maxoption = 2;
@ -530,41 +460,42 @@ void calculateMenu(int framecount){
break; break;
} }
if (interpolator < 1.0){ if (interpolator < 1.0) {
interpolator += 0.02; interpolator += 0.02;
} else{ } else {
interpolator = 1.0; interpolator = 1.0;
if (menufade == -1){ if (menufade == -1) {
if (keys[SDLK_DOWN]){ if (keys[SDLK_DOWN]) {
if (!pressed){ if (!pressed) {
/*if (menuoption < maxoption){ /*if (menuoption < maxoption){
menuoption++; menuoption++;
changesound->play(); changesound->play();
}*/ }*/
menuoption = (menuoption + 1)%(maxoption+1); menuoption = (menuoption + 1) % (maxoption + 1);
changesound->play(); changesound->play();
pressed = true; pressed = true;
} }
} else if (keys[SDLK_UP]){ } else if (keys[SDLK_UP]) {
if (!pressed){ if (!pressed) {
/*if (menuoption > 0){ /*if (menuoption > 0){
menuoption--; menuoption--;
changesound->play(); changesound->play();
}*/ }*/
menuoption = (menuoption + maxoption)%(maxoption+1); menuoption = (menuoption + maxoption) % (maxoption + 1);
changesound->play(); changesound->play();
pressed = true; pressed = true;
} }
} else if (keys[SDLK_LEFT]){ } else if (keys[SDLK_LEFT]) {
if (!pressed){ if (!pressed) {
switch(menumode){ switch (menumode) {
case MODEOPTIONS: case MODEOPTIONS:
switch(menuoption){ switch (menuoption) {
case OPTIONSRESOLUTION: case OPTIONSRESOLUTION:
menuResolution(-1); menuResolution(-1);
break; break;
case OPTIONSDETAIL: case OPTIONSDETAIL:
if (detail > 0) detail--; if (detail > 0)
detail--;
break; break;
} }
break; break;
@ -572,16 +503,17 @@ void calculateMenu(int framecount){
selectsound->play(); selectsound->play();
pressed = true; pressed = true;
} }
} else if (keys[SDLK_RIGHT]){ } else if (keys[SDLK_RIGHT]) {
if (!pressed){ if (!pressed) {
switch(menumode){ switch (menumode) {
case MODEOPTIONS: case MODEOPTIONS:
switch(menuoption){ switch (menuoption) {
case OPTIONSRESOLUTION: case OPTIONSRESOLUTION:
menuResolution(1); menuResolution(1);
break; break;
case OPTIONSDETAIL: case OPTIONSDETAIL:
if (detail < DETAILCOUNT-1) detail++; if (detail < DETAILCOUNT - 1)
detail++;
break; break;
} }
break; break;
@ -589,15 +521,15 @@ void calculateMenu(int framecount){
selectsound->play(); selectsound->play();
pressed = true; pressed = true;
} }
} else if (keys[SDLK_ESCAPE]){ } else if (keys[SDLK_ESCAPE]) {
if (!pressed){ if (!pressed) {
switch(menumode){ switch (menumode) {
case MODEMAIN: case MODEMAIN:
if (menuoption != MAINQUIT){ if (menuoption != MAINQUIT) {
menuoption = MAINQUIT; menuoption = MAINQUIT;
changesound->play(); changesound->play();
} } else
else menuEscPressed(); menuEscPressed();
break; break;
case MODEOPTIONS: case MODEOPTIONS:
selectsound->play(); selectsound->play();
@ -608,11 +540,11 @@ void calculateMenu(int framecount){
} }
pressed = true; pressed = true;
} }
} else if (keys[SDLK_RETURN]){ } else if (keys[SDLK_RETURN]) {
if (!pressed){ if (!pressed) {
switch(menumode){ switch (menumode) {
case MODEMAIN: case MODEMAIN:
switch(menuoption){ switch (menuoption) {
case MAINSTART: case MAINSTART:
menuStartGame(); menuStartGame();
break; break;
@ -625,9 +557,10 @@ void calculateMenu(int framecount){
} }
break; break;
case MODEOPTIONS: case MODEOPTIONS:
switch(menuoption){ switch (menuoption) {
case OPTIONSRESOLUTION: case OPTIONSRESOLUTION:
if (resolution != oldresolution) changeResolution(xres, yres, fullscreen); if (resolution != oldresolution)
changeResolution(xres, yres, fullscreen);
oldresolution = resolution; oldresolution = resolution;
break; break;
case OPTIONSFULLSCREEN: case OPTIONSFULLSCREEN:
@ -639,11 +572,11 @@ void calculateMenu(int framecount){
olddetail = detail; olddetail = detail;
break; break;
case OPTIONSRETURN: case OPTIONSRETURN:
if (resolution != oldresolution){ if (resolution != oldresolution) {
changeResolution(xres, yres, fullscreen); changeResolution(xres, yres, fullscreen);
oldresolution = resolution; oldresolution = resolution;
} }
if (detail != olddetail){ if (detail != olddetail) {
setDetail(detail); setDetail(detail);
olddetail = detail; olddetail = detail;
} }
@ -655,29 +588,26 @@ void calculateMenu(int framecount){
selectsound->play(); selectsound->play();
pressed = true; pressed = true;
} }
} else pressed = false; } else
pressed = false;
} }
} }
} }
void drawMenu(int framecount){ void drawMenu(int framecount) {
//createSkyBox(0, -20, 0, 400, 200, 400); // createSkyBox(0, -20, 0, 400, 200, 400);
createSkyBox(-200, -200, -200, 400, 400, 400); createSkyBox(-200, -200, -200, 400, 400, 400);
glLoadIdentity(); glLoadIdentity();
titlecamera.glUpdate(); titlecamera.glUpdate();
updateLights(); updateLights();
titleworld->draw(); titleworld->draw();
flaretexture->enable(); flaretexture->enable();
titlelight.createFlare(); titlelight.createFlare();
flaretexture->disable(); flaretexture->disable();
/*//2D-view /*//2D-view
glDisable(GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE); glDisable(GL_CULL_FACE);
@ -692,18 +622,17 @@ void drawMenu(int framecount){
enable2D(); enable2D();
glColor3f(1, 1, 1); glColor3f(1, 1, 1);
print(0.73, 0.55, print(0.73, 0.55, "Programming:\n"
"Programming:\n" \ " Miika Sell\n"
" Miika Sell\n" \ " Juha Kaarlas\n"
" Juha Kaarlas\n" \ "\n"
"\n" \ "Graphics:\n"
"Graphics:\n" \ " Miika Sell\n"
" Miika Sell\n" \ " Juha Kaarlas\n"
" Juha Kaarlas\n" \ "\n"
"\n" \ "Musics:\n"
"Musics:\n" \ " Osmand",
" Osmand" 0.03);
, 0.03);
print(0.35, 0.965, "http://blockofighter.kicks-ass.net/", 0.02); print(0.35, 0.965, "http://blockofighter.kicks-ass.net/", 0.02);
@ -716,35 +645,34 @@ void drawMenu(int framecount){
float tuxx = 0.9; float tuxx = 0.9;
float tuxy = 0.02; float tuxy = 0.02;
float tuxw = 0.1*3/4; float tuxw = 0.1 * 3 / 4;
float tuxh = 0.1; float tuxh = 0.1;
glBegin(GL_QUADS); glBegin(GL_QUADS);
glTexCoord2f(0, 0); glTexCoord2f(0, 0);
glVertex2f(tuxx, tuxy); glVertex2f(tuxx, tuxy);
glTexCoord2f(1, 0); glTexCoord2f(1, 0);
glVertex2f(tuxx+tuxw, tuxy); glVertex2f(tuxx + tuxw, tuxy);
glTexCoord2f(1, 1); glTexCoord2f(1, 1);
glVertex2f(tuxx+tuxw, tuxy+tuxh); glVertex2f(tuxx + tuxw, tuxy + tuxh);
glTexCoord2f(0, 1); glTexCoord2f(0, 1);
glVertex2f(tuxx, tuxy+tuxh); glVertex2f(tuxx, tuxy + tuxh);
glEnd(); glEnd();
tuxtexture->disable(); tuxtexture->disable();
glColor3f(1, 1, 1); glColor3f(1, 1, 1);
print(0.88, 0.12, "supported", 0.02); print(0.88, 0.12, "supported", 0.02);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0, 0, 0, 0.5); glColor4f(0, 0, 0, 0.5);
float x1, y1, x2, y2; float x1, y1, x2, y2;
x1 = (1-interpolator)*obx1 + interpolator*bx1; x1 = (1 - interpolator) * obx1 + interpolator * bx1;
y1 = (1-interpolator)*oby1 + interpolator*by1; y1 = (1 - interpolator) * oby1 + interpolator * by1;
x2 = (1-interpolator)*obx2 + interpolator*bx2; x2 = (1 - interpolator) * obx2 + interpolator * bx2;
y2 = (1-interpolator)*oby2 + interpolator*by2; y2 = (1 - interpolator) * oby2 + interpolator * by2;
glBegin(GL_QUADS); glBegin(GL_QUADS);
glVertex2f(x1, y1); glVertex2f(x1, y1);
glVertex2f(x2, y1); glVertex2f(x2, y1);
@ -752,8 +680,8 @@ void drawMenu(int framecount){
glVertex2f(x1, y2); glVertex2f(x1, y2);
glEnd(); glEnd();
if (interpolator == 1.0){ if (interpolator == 1.0) {
switch(menumode){ switch (menumode) {
case MODEMAIN: case MODEMAIN:
glColor3f(1, 1, 1); glColor3f(1, 1, 1);
print(0.05, 0.5, "Start game", 0.1); print(0.05, 0.5, "Start game", 0.1);
@ -762,7 +690,7 @@ void drawMenu(int framecount){
x1 = 0.04; x1 = 0.04;
x2 = 0.67; x2 = 0.67;
switch(menuoption){ switch (menuoption) {
case 0: case 0:
y1 = 0.5; y1 = 0.5;
y2 = 0.65; y2 = 0.65;
@ -790,7 +718,7 @@ void drawMenu(int framecount){
x1 = 0.11; x1 = 0.11;
x2 = 0.89; x2 = 0.89;
switch(menuoption){ switch (menuoption) {
case 0: case 0:
y1 = 0.32; y1 = 0.32;
y2 = 0.42; y2 = 0.42;
@ -813,7 +741,9 @@ void drawMenu(int framecount){
glLineWidth(2); glLineWidth(2);
glColor4f(sin(framecount*0.04)*0.4+0.6, sin(framecount*0.04)*0.4+0.6, sin(framecount*0.04)*0.4+0.6, 0.5); glColor4f(sin(framecount * 0.04) * 0.4 + 0.6,
sin(framecount * 0.04) * 0.4 + 0.6,
sin(framecount * 0.04) * 0.4 + 0.6, 0.5);
glBegin(GL_LINE_LOOP); glBegin(GL_LINE_LOOP);
glVertex2f(x1, y1); glVertex2f(x1, y1);
glVertex2f(x2, y1); glVertex2f(x2, y1);
@ -822,8 +752,7 @@ void drawMenu(int framecount){
glEnd(); glEnd();
} }
if (menufade != -1) {
if (menufade != -1){
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0, 0, 0, menufade); glColor4f(0, 0, 0, menufade);
glBegin(GL_QUADS); glBegin(GL_QUADS);
@ -832,7 +761,7 @@ void drawMenu(int framecount){
glVertex2f(1, 1); glVertex2f(1, 1);
glVertex2f(0, 1); glVertex2f(0, 1);
glEnd(); glEnd();
if (loading){ if (loading) {
glColor4f(menufade, menufade, menufade, menufade); glColor4f(menufade, menufade, menufade, menufade);
print(0.08, 0.4, "Loading...", 0.2); print(0.08, 0.4, "Loading...", 0.2);
} }

View file

@ -16,4 +16,3 @@ void drawMenu(int framecount);
void menuRestart(void); void menuRestart(void);
#endif #endif

View file

@ -10,52 +10,50 @@
#include "glapi.h" #include "glapi.h"
Vertex::Vertex(void){ Vertex::Vertex(void) {
vectorSet(position, 0, 0, 0); vectorSet(position, 0, 0, 0);
vectorSet(normal, 0, 0, 0); vectorSet(normal, 0, 0, 0);
} }
Vertex::Vertex(float x, float y, float z){ Vertex::Vertex(float x, float y, float z) {
vectorSet(position, x, y, z); vectorSet(position, x, y, z);
vectorSet(normal, x, y, z); vectorSet(normal, x, y, z);
vectorNormalize(normal); vectorNormalize(normal);
} }
Vertex::Vertex(float x, float y, float z, float nx, float ny, float nz){ Vertex::Vertex(float x, float y, float z, float nx, float ny, float nz) {
vectorSet(position, x, y, z); vectorSet(position, x, y, z);
vectorSet(normal, nx, ny, nz); vectorSet(normal, nx, ny, nz);
} }
void Vertex::setTexCoords(float u, float v){ void Vertex::setTexCoords(float u, float v) {
this->texcoords[0] = u; this->texcoords[0] = u;
this->texcoords[1] = v; this->texcoords[1] = v;
} }
Polygon::Polygon(void){ Polygon::Polygon(void) {
vertexcount = 0; vertexcount = 0;
edgecount = 0; edgecount = 0;
smooth = false; smooth = false;
realsmooth = false; realsmooth = false;
} }
Mesh::Mesh(void) {
Mesh::Mesh(void){
vertexcount = 0; vertexcount = 0;
polygoncount = 0; polygoncount = 0;
edgecount = 0; edgecount = 0;
} }
Mesh::~Mesh(void){ Mesh::~Mesh(void) {
delete [] polygons; delete[] polygons;
delete [] vertices; delete[] vertices;
} }
void Mesh::createPlanes(void){ void Mesh::createPlanes(void) {
int i; int i;
for (i = 0; i < polygoncount; i++){ for (i = 0; i < polygoncount; i++) {
class Polygon *polygon = &this->polygons[i]; class Polygon *polygon = &this->polygons[i];
if (polygon->vertexcount >= 3){ if (polygon->vertexcount >= 3) {
float v1[3], v2[3]; float v1[3], v2[3];
vectorSub(v1, polygon->vertices[1]->position, vectorSub(v1, polygon->vertices[1]->position,
polygon->vertices[0]->position); polygon->vertices[0]->position);
@ -64,45 +62,47 @@ void Mesh::createPlanes(void){
vectorCross(polygon->planenormal, v1, v2); vectorCross(polygon->planenormal, v1, v2);
vectorNormalize(polygon->planenormal); vectorNormalize(polygon->planenormal);
polygon->planedistance = -vectorDot(polygon->vertices[0]->position, polygon->planenormal); polygon->planedistance =
-vectorDot(polygon->vertices[0]->position, polygon->planenormal);
} }
} }
} }
void Mesh::createVertexnormals(void){ void Mesh::createVertexnormals(void) {
int i, j, ii; int i, j, ii;
bool connect; bool connect;
float normal[3]; float normal[3];
for (i = 0; i < vertexcount; i++){ for (i = 0; i < vertexcount; i++) {
bool found = false; bool found = false;
vectorSet(normal, 0, 0, 0); vectorSet(normal, 0, 0, 0);
for (j = 0; j < polygoncount; j++){ for (j = 0; j < polygoncount; j++) {
connect = false; connect = false;
class Polygon *polygon = &polygons[j]; class Polygon *polygon = &polygons[j];
for (ii = 0;ii < polygon->vertexcount; ii++){ for (ii = 0; ii < polygon->vertexcount; ii++) {
if (polygons[j].vertices[ii] == &(vertices[i])){ if (polygons[j].vertices[ii] == &(vertices[i])) {
connect = true; connect = true;
} }
} }
if (connect){ if (connect) {
vectorAdd(normal, polygon->planenormal); vectorAdd(normal, polygon->planenormal);
found = true; found = true;
} }
} }
if (found){ if (found) {
vectorNormalize(vertices[i].normal, normal); vectorNormalize(vertices[i].normal, normal);
} }
} }
for (j = 0; j < polygoncount; j++){ for (j = 0; j < polygoncount; j++) {
class Polygon *polygon = &polygons[j]; class Polygon *polygon = &polygons[j];
if (!polygon->realsmooth) polygon->smooth = true; if (!polygon->realsmooth)
polygon->smooth = true;
} }
} }
void Mesh::createEdges(void){ void Mesh::createEdges(void) {
int maxedgecount = 0; int maxedgecount = 0;
int i; int i;
for (i = 0; i < polygoncount; i++){ for (i = 0; i < polygoncount; i++) {
class Polygon *polygon = &polygons[i]; class Polygon *polygon = &polygons[i];
maxedgecount += polygon->vertexcount; maxedgecount += polygon->vertexcount;
} }
@ -110,23 +110,23 @@ void Mesh::createEdges(void){
edgecount = 0; edgecount = 0;
int j, k; int j, k;
Edge *edges = new Edge[maxedgecount]; Edge *edges = new Edge[maxedgecount];
for (i = 0; i < polygoncount; i++){ for (i = 0; i < polygoncount; i++) {
class Polygon *polygon = &polygons[i]; class Polygon *polygon = &polygons[i];
polygon->edges = new Edge *[polygon->vertexcount]; polygon->edges = new Edge *[polygon->vertexcount];
for (j = 1; j <= polygon->vertexcount; j++){ for (j = 1; j <= polygon->vertexcount; j++) {
Vertex *v1 = polygon->vertices[j-1]; Vertex *v1 = polygon->vertices[j - 1];
Vertex *v2 = polygon->vertices[j%polygon->vertexcount]; Vertex *v2 = polygon->vertices[j % polygon->vertexcount];
bool found = false; bool found = false;
for (k = 0; k < edgecount; k++){ for (k = 0; k < edgecount; k++) {
if (edges[k].v2 == v1 && edges[k].v1 == v2){ if (edges[k].v2 == v1 && edges[k].v1 == v2) {
found = true; found = true;
edges[k].p2 = polygon; edges[k].p2 = polygon;
break; break;
} }
} }
if (!found){ if (!found) {
edges[edgecount].v1 = v1; edges[edgecount].v1 = v1;
edges[edgecount].v2 = v2; edges[edgecount].v2 = v2;
edges[edgecount].p1 = polygon; edges[edgecount].p1 = polygon;
@ -137,8 +137,8 @@ void Mesh::createEdges(void){
} }
this->edges = new Edge[edgecount]; this->edges = new Edge[edgecount];
//printf("%i\n", edgecount); // printf("%i\n", edgecount);
for (i = 0; i < edgecount; i++){ for (i = 0; i < edgecount; i++) {
this->edges[i].v1 = edges[i].v1; this->edges[i].v1 = edges[i].v1;
this->edges[i].v2 = edges[i].v2; this->edges[i].v2 = edges[i].v2;
this->edges[i].p1 = edges[i].p1; this->edges[i].p1 = edges[i].p1;
@ -149,23 +149,22 @@ void Mesh::createEdges(void){
p->edges[p->edgecount++] = &this->edges[i]; p->edges[p->edgecount++] = &this->edges[i];
p = edges[i].p2; p = edges[i].p2;
p->edges[p->edgecount++] = &this->edges[i]; p->edges[p->edgecount++] = &this->edges[i];
//printf("%p, %p\n", edges[i].p1, edges[i].p2); // printf("%p, %p\n", edges[i].p1, edges[i].p2);
} }
delete[] edges; delete[] edges;
} }
float Mesh::calculateScale(float targetLength, int axis) {
float Mesh::calculateScale(float targetLength, int axis){
float min = 0.0; float min = 0.0;
float max = 0.0; float max = 0.0;
for (int i=0; i < this->vertexcount; i++){ for (int i = 0; i < this->vertexcount; i++) {
if (this->vertices->position[axis] > max){ if (this->vertices->position[axis] > max) {
max = this->vertices->position[axis]; max = this->vertices->position[axis];
} }
if (this->vertices->position[axis] < min){ if (this->vertices->position[axis] < min) {
min = this->vertices->position[axis]; min = this->vertices->position[axis];
} }
} }
@ -173,14 +172,14 @@ float Mesh::calculateScale(float targetLength, int axis){
} }
/* ei toimi kunnolla kaikille objekteille (kädet ok, jalat ja torso ei) */ /* ei toimi kunnolla kaikille objekteille (kädet ok, jalat ja torso ei) */
void Mesh::scale(float targetLength, int axis){ void Mesh::scale(float targetLength, int axis) {
float newscale = this->calculateScale(targetLength, axis); float newscale = this->calculateScale(targetLength, axis);
this->scale(newscale); this->scale(newscale);
} }
/* ei toimi kunnolla kaikille objekteille (kädet ok, jalat ja torso ei)*/ /* ei toimi kunnolla kaikille objekteille (kädet ok, jalat ja torso ei)*/
void Mesh::scale(float scale){ void Mesh::scale(float scale) {
for (int i=0; i < this->vertexcount; i++){ for (int i = 0; i < this->vertexcount; i++) {
this->vertices->position[0] *= scale; this->vertices->position[0] *= scale;
this->vertices->position[1] *= scale; this->vertices->position[1] *= scale;
this->vertices->position[2] *= scale; this->vertices->position[2] *= scale;
@ -189,52 +188,45 @@ void Mesh::scale(float scale){
this->createPlanes(); this->createPlanes();
} }
MeshObject::MeshObject(Mesh *mesh){ MeshObject::MeshObject(Mesh *mesh) {
this->mesh = mesh; this->mesh = mesh;
this->appearance = new MeshAppearance(mesh); this->appearance = new MeshAppearance(mesh);
this->geometry = new MeshShape(this); this->geometry = new MeshShape(this);
} }
MeshAppearance::MeshAppearance(Mesh *mesh) { this->mesh = mesh; }
void MeshAppearance::draw(void) {
MeshAppearance::MeshAppearance(Mesh *mesh){ // glDisable(GL_CULL_FACE);
this->mesh = mesh;
}
void MeshAppearance::draw(void){
//glDisable(GL_CULL_FACE);
glColor4fv(this->material.getColor()); glColor4fv(this->material.getColor());
this->material.enable(); this->material.enable();
int i, j; int i, j;
for (i = 0; i < mesh->polygoncount; i++){ for (i = 0; i < mesh->polygoncount; i++) {
class Polygon *polygon = &mesh->polygons[i]; class Polygon *polygon = &mesh->polygons[i];
glBegin(GL_TRIANGLE_FAN); glBegin(GL_TRIANGLE_FAN);
if (!polygon->smooth) glNormal3fv(polygon->planenormal); if (!polygon->smooth)
glNormal3fv(polygon->planenormal);
for (j = 0; j < polygon->vertexcount; j++){ for (j = 0; j < polygon->vertexcount; j++) {
Vertex *vertex = polygon->vertices[j]; Vertex *vertex = polygon->vertices[j];
if (polygon->smooth) glNormal3fv(vertex->normal); if (polygon->smooth)
glNormal3fv(vertex->normal);
glVertex3fv(vertex->position); glVertex3fv(vertex->position);
} }
glEnd(); glEnd();
} }
glDisable(GL_DEPTH); glDisable(GL_DEPTH);
glDisable(GL_LIGHTING); glDisable(GL_LIGHTING);
glLineWidth(5.0); glLineWidth(5.0);
glBegin(GL_LINES); glBegin(GL_LINES);
for (i = 0; i < mesh->edgecount; i++){ for (i = 0; i < mesh->edgecount; i++) {
glColor3f(0, 0, 0); glColor3f(0, 0, 0);
glVertex3fv(mesh->edges[i].v1->position); glVertex3fv(mesh->edges[i].v1->position);
glVertex3fv(mesh->edges[i].v2->position); glVertex3fv(mesh->edges[i].v2->position);
@ -244,44 +236,39 @@ void MeshAppearance::draw(void){
glEnable(GL_LIGHTING); glEnable(GL_LIGHTING);
glEnable(GL_DEPTH); glEnable(GL_DEPTH);
this->material.disable(); this->material.disable();
//glEnable(GL_CULL_FACE); // glEnable(GL_CULL_FACE);
} }
MeshShape::MeshShape(MeshObject *object) : Shape(object) {
MeshShape::MeshShape(MeshObject *object) : Shape(object){
mesh = object->mesh; mesh = object->mesh;
} }
MeshShape::MeshShape(Object *object, Mesh *mesh) : Shape(object){ MeshShape::MeshShape(Object *object, Mesh *mesh) : Shape(object) {
this->mesh = mesh; this->mesh = mesh;
} }
bool MeshShape::checkCollision(Object *target){ bool MeshShape::checkCollision(Object *target) {
return target->geometry->checkCollisionPeer(this); return target->geometry->checkCollisionPeer(this);
} }
float MeshShape::calculateMomentOfInertia(float *rotationvector){ float MeshShape::calculateMomentOfInertia(float *rotationvector) {
if (vectorDot(rotationvector, rotationvector) < EPSILON) return 0; if (vectorDot(rotationvector, rotationvector) < EPSILON)
return 0;
int i; int i;
float j = 0; float j = 0;
for (i = 0; i < mesh->vertexcount; i++){ for (i = 0; i < mesh->vertexcount; i++) {
float proj[3]; float proj[3];
vectorProject(proj, mesh->vertices[i].position, rotationvector); vectorProject(proj, mesh->vertices[i].position, rotationvector);
vectorSub(proj, mesh->vertices[i].position, proj); vectorSub(proj, mesh->vertices[i].position, proj);
//float r = vectorLength(proj); // float r = vectorLength(proj);
float r2 = vectorDot(proj, proj); float r2 = vectorDot(proj, proj);
j += r2; j += r2;
} }
return j / i; return j / i;
} }
bool MeshShape::checkCollisionPeer(SphereShape *target){ bool MeshShape::checkCollisionPeer(SphereShape *target) {
float position[3] = {0, 0, 0}; float position[3] = {0, 0, 0};
target->object->transformPoint(position, position); target->object->transformPoint(position, position);
object->unTransformPoint(position, position); object->unTransformPoint(position, position);
@ -290,14 +277,14 @@ bool MeshShape::checkCollisionPeer(SphereShape *target){
float contactpoint[3]; float contactpoint[3];
float r = target->getRadius(); float r = target->getRadius();
if (checkSphereMeshCollision(position, r, mesh, normal, contactpoint)){ if (checkSphereMeshCollision(position, r, mesh, normal, contactpoint)) {
vectorScale(normal, -1); vectorScale(normal, -1);
object->transformVector(normal, normal); object->transformVector(normal, normal);
object->transformPoint(contactpoint, contactpoint); object->transformPoint(contactpoint, contactpoint);
addCollision(object, target->object, normal, contactpoint); addCollision(object, target->object, normal, contactpoint);
//vectorAdd(contactnormal, normal); // vectorAdd(contactnormal, normal);
return true; return true;
} }
@ -305,9 +292,9 @@ bool MeshShape::checkCollisionPeer(SphereShape *target){
return false; return false;
} }
//extern Sound *shotsound; // extern Sound *shotsound;
bool MeshShape::checkCollisionPeer(MeshShape *target){ bool MeshShape::checkCollisionPeer(MeshShape *target) {
float normal[3]; float normal[3];
float contactpoint[3]; float contactpoint[3];
@ -319,17 +306,18 @@ bool MeshShape::checkCollisionPeer(MeshShape *target){
sourcemesh = this->mesh; sourcemesh = this->mesh;
targetmesh = target->mesh; targetmesh = target->mesh;
for (i = 0; i < sourcemesh->vertexcount; i++){ for (i = 0; i < sourcemesh->vertexcount; i++) {
Vertex *vertex = &sourcemesh->vertices[i]; Vertex *vertex = &sourcemesh->vertices[i];
float vertexposition[3]; float vertexposition[3];
object->transformPoint(vertexposition, vertex->position); object->transformPoint(vertexposition, vertex->position);
target->object->unTransformPoint(vertexposition, vertexposition); target->object->unTransformPoint(vertexposition, vertexposition);
if (checkPointMeshCollision(vertexposition, targetmesh, normal, contactpoint)){ if (checkPointMeshCollision(vertexposition, targetmesh, normal,
contactpoint)) {
target->object->transformVector(normal, normal); target->object->transformVector(normal, normal);
target->object->transformPoint(contactpoint, contactpoint); target->object->transformPoint(contactpoint, contactpoint);
if (vectorIsZero(contactpoint)){ if (vectorIsZero(contactpoint)) {
vectorSet(contactpoint, 0, 0, 0); vectorSet(contactpoint, 0, 0, 0);
} }
addCollision(object, target->object, normal, contactpoint); addCollision(object, target->object, normal, contactpoint);
@ -339,13 +327,14 @@ bool MeshShape::checkCollisionPeer(MeshShape *target){
sourcemesh = target->mesh; sourcemesh = target->mesh;
targetmesh = this->mesh; targetmesh = this->mesh;
for (i = 0; i < sourcemesh->vertexcount; i++){ for (i = 0; i < sourcemesh->vertexcount; i++) {
Vertex *vertex = &sourcemesh->vertices[i]; Vertex *vertex = &sourcemesh->vertices[i];
float vertexposition[3]; float vertexposition[3];
target->object->transformPoint(vertexposition, vertex->position); target->object->transformPoint(vertexposition, vertex->position);
object->unTransformPoint(vertexposition, vertexposition); object->unTransformPoint(vertexposition, vertexposition);
if (checkPointMeshCollision(vertexposition, targetmesh, normal, contactpoint)){ if (checkPointMeshCollision(vertexposition, targetmesh, normal,
contactpoint)) {
object->transformVector(normal, normal); object->transformVector(normal, normal);
object->transformPoint(contactpoint, contactpoint); object->transformPoint(contactpoint, contactpoint);
@ -356,7 +345,7 @@ bool MeshShape::checkCollisionPeer(MeshShape *target){
sourcemesh = this->mesh; sourcemesh = this->mesh;
targetmesh = target->mesh; targetmesh = target->mesh;
for (i = 0; i < sourcemesh->edgecount; i++){ for (i = 0; i < sourcemesh->edgecount; i++) {
Edge *edge = &sourcemesh->edges[i]; Edge *edge = &sourcemesh->edges[i];
float v1[3], v2[3]; float v1[3], v2[3];
object->transformPoint(v1, edge->v1->position); object->transformPoint(v1, edge->v1->position);
@ -365,7 +354,7 @@ bool MeshShape::checkCollisionPeer(MeshShape *target){
object->transformPoint(v2, edge->v2->position); object->transformPoint(v2, edge->v2->position);
target->object->unTransformPoint(v2, v2); target->object->unTransformPoint(v2, v2);
if (checkEdgeMeshCollision(v1, v2, targetmesh, normal, contactpoint)){ if (checkEdgeMeshCollision(v1, v2, targetmesh, normal, contactpoint)) {
target->object->transformVector(normal, normal); target->object->transformVector(normal, normal);
target->object->transformPoint(contactpoint, contactpoint); target->object->transformPoint(contactpoint, contactpoint);
@ -376,4 +365,3 @@ bool MeshShape::checkCollisionPeer(MeshShape *target){
return collided; return collided;
} }

View file

@ -3,13 +3,11 @@
#include "object.h" #include "object.h"
#define X_AXIS 0 #define X_AXIS 0
#define Y_AXIS 1 #define Y_AXIS 1
#define Z_AXIS 2 #define Z_AXIS 2
class Vertex {
class Vertex{
public: public:
float position[3]; float position[3];
float oldposition[3]; float oldposition[3];
@ -23,10 +21,9 @@ public:
void setTexCoords(float u, float v); void setTexCoords(float u, float v);
}; };
class Edge; class Edge;
class Polygon{ class Polygon {
public: public:
float planenormal[3]; float planenormal[3];
float planedistance; float planedistance;
@ -41,17 +38,13 @@ public:
Polygon(void); Polygon(void);
}; };
class Edge {
class Edge{
public: public:
Vertex *v1, *v2; Vertex *v1, *v2;
class Polygon *p1, *p2; class Polygon *p1, *p2;
}; };
class Mesh {
class Mesh{
public: public:
int vertexcount; int vertexcount;
Vertex *vertices; Vertex *vertices;
@ -62,7 +55,6 @@ public:
Edge *edges; Edge *edges;
int edgecount; int edgecount;
Mesh(void); Mesh(void);
~Mesh(void); ~Mesh(void);
@ -74,18 +66,14 @@ public:
void scale(float scale); void scale(float scale);
}; };
class MeshObject : public Object {
class MeshObject : public Object{
public: public:
Mesh *mesh; Mesh *mesh;
MeshObject(Mesh *mesh); MeshObject(Mesh *mesh);
}; };
class MeshAppearance : public Appearance {
class MeshAppearance : public Appearance{
private: private:
Mesh *mesh; Mesh *mesh;
@ -95,11 +83,9 @@ public:
void draw(void); void draw(void);
}; };
// Geometry of sphere
class MeshShape : public Shape {
//Geometry of sphere
class MeshShape : public Shape{
private: private:
Mesh *mesh; Mesh *mesh;
@ -118,4 +104,3 @@ public:
}; };
#endif #endif

View file

@ -9,7 +9,7 @@
#include "fight.h" #include "fight.h"
#include "glapi.h" #include "glapi.h"
Object::Object(void){ Object::Object(void) {
appearance = NULL; appearance = NULL;
geometry = NULL; geometry = NULL;
invmass = 0.0; invmass = 0.0;
@ -24,33 +24,33 @@ Object::Object(void){
gravity = false; gravity = false;
} }
void Object::prepare(void){ void Object::prepare(void) {
if (appearance != NULL) appearance->prepare(); if (appearance != NULL)
appearance->prepare();
} }
#define DT 0.01 #define DT 0.01
void Object::move(void){ void Object::move(void) { moveStep(DT); }
moveStep(DT);
}
void Object::moveStep(float dt){ void Object::moveStep(float dt) {
if (invmass == 0) return; if (invmass == 0)
return;
if (vectorDot(momentum, momentum) > 1.0e+5)
if (vectorDot(momentum, momentum) > 1.0e+5) vectorSet(momentum, 0, 0, 0); vectorSet(momentum, 0, 0, 0);
if (vectorDot(angularmomentum, angularmomentum) > 1.0e+5) vectorSet(angularmomentum, 0, 0, 0); if (vectorDot(angularmomentum, angularmomentum) > 1.0e+5)
vectorSet(angularmomentum, 0, 0, 0);
calculateStateVariables(); calculateStateVariables();
float velocitydt[3]; float velocitydt[3];
vectorScale(velocitydt, velocity, dt); vectorScale(velocitydt, velocity, dt);
vectorAdd(position, velocitydt); vectorAdd(position, velocitydt);
float rotationdt[9]; float rotationdt[9];
if (vectorIsZero(angularmomentum)){ if (vectorIsZero(angularmomentum)) {
matrixIdentity(rotationdt); matrixIdentity(rotationdt);
} else{ } else {
float angularvelocitydt[3]; float angularvelocitydt[3];
vectorScale(angularvelocitydt, angularvelocity, dt); vectorScale(angularvelocitydt, angularvelocity, dt);
matrixCreateRotation(rotationdt, angularvelocitydt); matrixCreateRotation(rotationdt, angularvelocitydt);
@ -60,45 +60,46 @@ void Object::moveStep(float dt){
vectorScale(angularmomentum, 0.99); vectorScale(angularmomentum, 0.99);
} }
void Object::calculateStateVariables(void){ void Object::calculateStateVariables(void) {
getVelocity(velocity); getVelocity(velocity);
if (vectorIsZero(angularmomentum)){ if (vectorIsZero(angularmomentum)) {
invmomentofinertia = 0; invmomentofinertia = 0;
} else{ } else {
invmomentofinertia = invmass * 1.0 / geometry->calculateMomentOfInertia(angularmomentum); invmomentofinertia =
invmass * 1.0 / geometry->calculateMomentOfInertia(angularmomentum);
} }
vectorScale(angularvelocity, angularmomentum, invmomentofinertia); vectorScale(angularvelocity, angularmomentum, invmomentofinertia);
} }
void Object::setPosition(float x, float y, float z){ void Object::setPosition(float x, float y, float z) {
position[0] = x; position[0] = x;
position[1] = y; position[1] = y;
position[2] = z; position[2] = z;
} }
void Object::getPosition(float *position){ void Object::getPosition(float *position) {
vectorCopy(position, this->position); vectorCopy(position, this->position);
} }
void Object::getVelocity(float *velocity){ void Object::getVelocity(float *velocity) {
vectorCopy(velocity, momentum); vectorCopy(velocity, momentum);
vectorScale(velocity, invmass); vectorScale(velocity, invmass);
} }
void Object::getVelocity(float *velocity, float *point){ void Object::getVelocity(float *velocity, float *point) {
getVelocity(velocity); getVelocity(velocity);
float tangentialvelocity[3]; float tangentialvelocity[3];
getTangentialVelocity(tangentialvelocity, point); getTangentialVelocity(tangentialvelocity, point);
//float tv[3]; // float tv[3];
//transformVector(tv, tangentialvelocity); // transformVector(tv, tangentialvelocity);
vectorAdd(velocity, tangentialvelocity); vectorAdd(velocity, tangentialvelocity);
} }
void Object::getTangentialVelocity(float *target, float *point){ void Object::getTangentialVelocity(float *target, float *point) {
if (vectorIsZero(angularmomentum)){ if (vectorIsZero(angularmomentum)) {
vectorSet(target, 0, 0, 0); vectorSet(target, 0, 0, 0);
return; return;
} }
@ -107,30 +108,30 @@ void Object::getTangentialVelocity(float *target, float *point){
vectorScale(target, invmomentofinertia); vectorScale(target, invmomentofinertia);
} }
void Object::getMomentum(float *momentum){ void Object::getMomentum(float *momentum) {
vectorCopy(momentum, this->momentum); vectorCopy(momentum, this->momentum);
} }
void Object::setMass(float mass){ void Object::setMass(float mass) {
if (mass == 0) this->invmass = 0; if (mass == 0)
else this->invmass = 1.0 / mass; this->invmass = 0;
else
this->invmass = 1.0 / mass;
} }
float Object::getMass(void){ float Object::getMass(void) {
if (invmass == 0) return 0; if (invmass == 0)
return 0;
return 1.0 / invmass; return 1.0 / invmass;
} }
void Object::setCollisionGroup(int group){ void Object::setCollisionGroup(int group) { this->collisiongroup = group; }
this->collisiongroup = group;
}
int Object::getCollisionGroup(void){ int Object::getCollisionGroup(void) { return collisiongroup; }
return collisiongroup;
}
void Object::addImpulse(float *impulse, float *contactpoint){ void Object::addImpulse(float *impulse, float *contactpoint) {
if (invmass == 0) return; if (invmass == 0)
return;
float angularimpulse[3]; float angularimpulse[3];
vectorCross(angularimpulse, contactpoint, impulse); vectorCross(angularimpulse, contactpoint, impulse);
vectorAdd(angularmomentum, angularimpulse); vectorAdd(angularmomentum, angularimpulse);
@ -142,10 +143,10 @@ void Object::addImpulse(float *impulse, float *contactpoint){
vectorNormalize(t2, impulse); vectorNormalize(t2, impulse);
vectorAdd(t2, t1); vectorAdd(t2, t1);
//addGraphicsVector(t1, t2, vectorLength(impulse)); // addGraphicsVector(t1, t2, vectorLength(impulse));
} }
void Object::addExternalForce(float *force){ void Object::addExternalForce(float *force) {
float impulse[3]; float impulse[3];
vectorScale(impulse, force, DT); vectorScale(impulse, force, DT);
@ -153,61 +154,58 @@ void Object::addExternalForce(float *force){
this->addImpulse(impulse, contact); this->addImpulse(impulse, contact);
} }
void Object::transformPoint(float *newpoint, float *oldpoint){ void Object::transformPoint(float *newpoint, float *oldpoint) {
vectorMatrixMultiply(newpoint, oldpoint, rotation); vectorMatrixMultiply(newpoint, oldpoint, rotation);
vectorAdd(newpoint, position); vectorAdd(newpoint, position);
} }
void Object::unTransformPoint(float *newpoint, float *oldpoint){ void Object::unTransformPoint(float *newpoint, float *oldpoint) {
vectorSub(newpoint, oldpoint, position); vectorSub(newpoint, oldpoint, position);
float rotmat[9]; float rotmat[9];
matrixTranspose(rotmat, rotation); matrixTranspose(rotmat, rotation);
vectorMatrixMultiply(newpoint, newpoint, rotmat); vectorMatrixMultiply(newpoint, newpoint, rotmat);
} }
void Object::transformVector(float *newvector, float *oldvector){ void Object::transformVector(float *newvector, float *oldvector) {
vectorMatrixMultiply(newvector, oldvector, rotation); vectorMatrixMultiply(newvector, oldvector, rotation);
} }
void Object::unTransformVector(float *newvector, float *oldvector){ void Object::unTransformVector(float *newvector, float *oldvector) {
float rotmat[9]; float rotmat[9];
matrixTranspose(rotmat, rotation); matrixTranspose(rotmat, rotation);
vectorMatrixMultiply(newvector, oldvector, rotmat); vectorMatrixMultiply(newvector, oldvector, rotmat);
} }
void Object::hitForce(float speed, float *speed2, Object *source) {
void Object::hitForce(float speed, float *speed2, Object *source){
float tolerance = 1.0; float tolerance = 1.0;
if (speed > tolerance){ if (speed > tolerance) {
Sound *sound; Sound *sound;
if (rand()&1) sound = softhitsound1; if (rand() & 1)
else sound = softhitsound2; sound = softhitsound1;
float volume = (speed-tolerance)*2; else
if (volume > 1) volume = 1; sound = softhitsound2;
float volume = (speed - tolerance) * 2;
if (volume > 1)
volume = 1;
sound->setVolume(volume); sound->setVolume(volume);
sound->play(30 + random(70)); sound->play(30 + random(70));
} }
} }
void Object::setGravity(bool enabled) { gravity = enabled; }
void Object::draw(void) {
void Object::setGravity(bool enabled){
gravity = enabled;
}
void Object::draw(void){
glPushMatrix(); glPushMatrix();
glTranslatef(position[0], position[1], position[2]); glTranslatef(position[0], position[1], position[2]);
GLfloat glmatrix[16] = { GLfloat glmatrix[16] = {rotation[0], rotation[1], rotation[2], 0,
rotation[0], rotation[1], rotation[2], 0,
rotation[3], rotation[4], rotation[5], 0, rotation[3], rotation[4], rotation[5], 0,
rotation[6], rotation[7], rotation[8], 0, rotation[6], rotation[7], rotation[8], 0,
0 , 0 , 0 , 1}; 0, 0, 0, 1};
glMultMatrixf(glmatrix); glMultMatrixf(glmatrix);
if (appearance != NULL) appearance->draw(); if (appearance != NULL)
appearance->draw();
glPopMatrix(); glPopMatrix();
} }

View file

@ -10,12 +10,12 @@ class Object;
#include "shape.h" #include "shape.h"
#include "appearance.h" #include "appearance.h"
struct objectlist{ struct objectlist {
Object *object; Object *object;
objectlist *next; objectlist *next;
}; };
class Object{ class Object {
public: public:
float invmass; float invmass;
@ -32,14 +32,13 @@ public:
*/ */
float position[3]; float position[3];
//derivative: velocity = momentum / mass // derivative: velocity = momentum / mass
float momentum[3];//, oldmomentum[3]; float momentum[3]; //, oldmomentum[3];
//derivative: force // derivative: force
//float force[3]; //Temporary properties
//float externalforce[3];
// float force[3]; //Temporary properties
// float externalforce[3];
/* Angular movement: /* Angular movement:
* rotation <-> orientaatio (R) * rotation <-> orientaatio (R)
@ -58,17 +57,16 @@ public:
float invmomentofinertia; float invmomentofinertia;
float rotation[9]; float rotation[9];
//derivative: StarOperation(angularvelocity) * rotation // derivative: StarOperation(angularvelocity) * rotation
float angularmomentum[3]; float angularmomentum[3];
//angular momentum = angular velocity * moment of inertia // angular momentum = angular velocity * moment of inertia
//derivative: torque = angular acceleration * moment of inertia // derivative: torque = angular acceleration * moment of inertia
//float torque[3]; //Temporary property
// float torque[3]; //Temporary property
void moveStep(float dt); void moveStep(float dt);
//void applyForces(float dt); // void applyForces(float dt);
void calculateStateVariables(void); void calculateStateVariables(void);
@ -81,8 +79,6 @@ public:
bool gravity; bool gravity;
Object(void); Object(void);
virtual void prepare(void); virtual void prepare(void);
@ -92,17 +88,17 @@ public:
void setPosition(float x, float y, float z); void setPosition(float x, float y, float z);
void getPosition(float *position); void getPosition(float *position);
//Gets velocity from object and return it in "velocity" // Gets velocity from object and return it in "velocity"
void getVelocity(float *velocity); void getVelocity(float *velocity);
//Gets velocity from object for point "point" with // Gets velocity from object for point "point" with
//tangential speed and return it in "velocity" // tangential speed and return it in "velocity"
void getVelocity(float *velocity, float *point); void getVelocity(float *velocity, float *point);
void getTangentialVelocity(float *target, float *point); void getTangentialVelocity(float *target, float *point);
void getMomentum(float *momentum); void getMomentum(float *momentum);
//void getForce(float *force); // void getForce(float *force);
void setMass(float mass); void setMass(float mass);
float getMass(void); float getMass(void);
void setCollisionGroup(int group); void setCollisionGroup(int group);
@ -117,30 +113,16 @@ public:
void setGravity(bool enabled); void setGravity(bool enabled);
virtual void hitForce(float speed, float *speed2, Object *source); virtual void hitForce(float speed, float *speed2, Object *source);
friend class ObjectLink; friend class ObjectLink;
//friend void collide(Object *source, Object *target, float *normal, float *contactpoint); // friend void collide(Object *source, Object *target, float *normal, float
// *contactpoint);
friend bool checkCollisions(Object *object, float *contactnormal); friend bool checkCollisions(Object *object, float *contactnormal);
// Temporary state variables
//Temporary state variables
float velocity[3]; float velocity[3];
float angularvelocity[3]; float angularvelocity[3];
}; };
#endif #endif

View file

@ -12,8 +12,7 @@
#include "objectfactory.h" #include "objectfactory.h"
#include "glapi.h" #include "glapi.h"
MeshObject *createPyramid(float width, float height) {
MeshObject *createPyramid(float width, float height){
Mesh *mesh = new Mesh(); Mesh *mesh = new Mesh();
mesh->vertexcount = 5; mesh->vertexcount = 5;
mesh->vertices = new Vertex[5]; mesh->vertices = new Vertex[5];
@ -74,39 +73,40 @@ MeshObject *createPyramid(float width, float height){
return object; return object;
} }
MeshObject *createSpherePool(float width, float height){ MeshObject *createSpherePool(float width, float height) {
int grid = 16; int grid = 16;
Mesh *mesh = new Mesh(); Mesh *mesh = new Mesh();
mesh->vertexcount = (grid+1)*(grid+1); mesh->vertexcount = (grid + 1) * (grid + 1);
mesh->vertices = new Vertex[mesh->vertexcount]; mesh->vertices = new Vertex[mesh->vertexcount];
int x, z; int x, z;
for (z = 0; z < grid; z++){ for (z = 0; z < grid; z++) {
float pz = (2.0*z/(grid-1) - 1)*width; float pz = (2.0 * z / (grid - 1) - 1) * width;
for (x = 0; x < grid; x++){ for (x = 0; x < grid; x++) {
float px = (2.0*x/(grid-1) - 1)*width; float px = (2.0 * x / (grid - 1) - 1) * width;
//float py = randomf(1); // float py = randomf(1);
float l = sqrt(pz*pz + px*px)*1; float l = sqrt(pz * pz + px * px) * 1;
if (l > width) l = width; if (l > width)
l = l/width; l = width;
//l = l*l; l = l / width;
float py = height*(sin(PI*(1.5+l*2))+1)/2; // l = l*l;
float py = height * (sin(PI * (1.5 + l * 2)) + 1) / 2;
vectorSet(mesh->vertices[z * grid + x].position, px, py, pz); vectorSet(mesh->vertices[z * grid + x].position, px, py, pz);
} }
} }
mesh->polygoncount = (grid-1)*(grid-1); mesh->polygoncount = (grid - 1) * (grid - 1);
mesh->polygons = new class Polygon[mesh->polygoncount]; mesh->polygons = new class Polygon[mesh->polygoncount];
for (z = 0; z < grid-1; z++){ for (z = 0; z < grid - 1; z++) {
for (x = 0; x < grid-1; x++){ for (x = 0; x < grid - 1; x++) {
class Polygon *poly = &mesh->polygons[z * (grid-1) + x]; class Polygon *poly = &mesh->polygons[z * (grid - 1) + x];
poly->vertexcount = 4; poly->vertexcount = 4;
poly->vertices = new Vertex *[4]; poly->vertices = new Vertex *[4];
poly->vertices[0] = &mesh->vertices[z * grid + x + 1]; poly->vertices[0] = &mesh->vertices[z * grid + x + 1];
poly->vertices[1] = &mesh->vertices[z * grid + x ]; poly->vertices[1] = &mesh->vertices[z * grid + x];
poly->vertices[2] = &mesh->vertices[(z + 1) * grid + x]; poly->vertices[2] = &mesh->vertices[(z + 1) * grid + x];
poly->vertices[3] = &mesh->vertices[(z + 1) * grid + x + 1]; poly->vertices[3] = &mesh->vertices[(z + 1) * grid + x + 1];
@ -114,7 +114,6 @@ MeshObject *createSpherePool(float width, float height){
} }
} }
mesh->createPlanes(); mesh->createPlanes();
mesh->createVertexnormals(); mesh->createVertexnormals();
@ -122,7 +121,7 @@ MeshObject *createSpherePool(float width, float height){
return object; return object;
} }
Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2) {
Mesh *mesh = new Mesh(); Mesh *mesh = new Mesh();
mesh->vertexcount = 8; mesh->vertexcount = 8;
mesh->vertices = new Vertex[8]; mesh->vertices = new Vertex[8];
@ -138,7 +137,7 @@ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){
mesh->polygoncount = 6; mesh->polygoncount = 6;
mesh->polygons = new class Polygon[6]; mesh->polygons = new class Polygon[6];
//Back // Back
mesh->polygons[0].vertexcount = 4; mesh->polygons[0].vertexcount = 4;
mesh->polygons[0].vertices = new Vertex *[4]; mesh->polygons[0].vertices = new Vertex *[4];
mesh->polygons[0].vertices[0] = &mesh->vertices[0]; mesh->polygons[0].vertices[0] = &mesh->vertices[0];
@ -146,7 +145,7 @@ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){
mesh->polygons[0].vertices[2] = &mesh->vertices[3]; mesh->polygons[0].vertices[2] = &mesh->vertices[3];
mesh->polygons[0].vertices[3] = &mesh->vertices[1]; mesh->polygons[0].vertices[3] = &mesh->vertices[1];
//Front // Front
mesh->polygons[1].vertexcount = 4; mesh->polygons[1].vertexcount = 4;
mesh->polygons[1].vertices = new Vertex *[4]; mesh->polygons[1].vertices = new Vertex *[4];
mesh->polygons[1].vertices[0] = &mesh->vertices[4]; mesh->polygons[1].vertices[0] = &mesh->vertices[4];
@ -154,7 +153,7 @@ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){
mesh->polygons[1].vertices[2] = &mesh->vertices[7]; mesh->polygons[1].vertices[2] = &mesh->vertices[7];
mesh->polygons[1].vertices[3] = &mesh->vertices[6]; mesh->polygons[1].vertices[3] = &mesh->vertices[6];
//Left // Left
mesh->polygons[2].vertexcount = 4; mesh->polygons[2].vertexcount = 4;
mesh->polygons[2].vertices = new Vertex *[4]; mesh->polygons[2].vertices = new Vertex *[4];
mesh->polygons[2].vertices[0] = &mesh->vertices[0]; mesh->polygons[2].vertices[0] = &mesh->vertices[0];
@ -162,7 +161,7 @@ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){
mesh->polygons[2].vertices[2] = &mesh->vertices[6]; mesh->polygons[2].vertices[2] = &mesh->vertices[6];
mesh->polygons[2].vertices[3] = &mesh->vertices[2]; mesh->polygons[2].vertices[3] = &mesh->vertices[2];
//Right // Right
mesh->polygons[3].vertexcount = 4; mesh->polygons[3].vertexcount = 4;
mesh->polygons[3].vertices = new Vertex *[4]; mesh->polygons[3].vertices = new Vertex *[4];
mesh->polygons[3].vertices[0] = &mesh->vertices[1]; mesh->polygons[3].vertices[0] = &mesh->vertices[1];
@ -170,7 +169,7 @@ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){
mesh->polygons[3].vertices[2] = &mesh->vertices[7]; mesh->polygons[3].vertices[2] = &mesh->vertices[7];
mesh->polygons[3].vertices[3] = &mesh->vertices[5]; mesh->polygons[3].vertices[3] = &mesh->vertices[5];
//Top // Top
mesh->polygons[4].vertexcount = 4; mesh->polygons[4].vertexcount = 4;
mesh->polygons[4].vertices = new Vertex *[4]; mesh->polygons[4].vertices = new Vertex *[4];
mesh->polygons[4].vertices[0] = &mesh->vertices[2]; mesh->polygons[4].vertices[0] = &mesh->vertices[2];
@ -178,7 +177,7 @@ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){
mesh->polygons[4].vertices[2] = &mesh->vertices[7]; mesh->polygons[4].vertices[2] = &mesh->vertices[7];
mesh->polygons[4].vertices[3] = &mesh->vertices[3]; mesh->polygons[4].vertices[3] = &mesh->vertices[3];
//Bottom // Bottom
mesh->polygons[5].vertexcount = 4; mesh->polygons[5].vertexcount = 4;
mesh->polygons[5].vertices = new Vertex *[4]; mesh->polygons[5].vertices = new Vertex *[4];
mesh->polygons[5].vertices[0] = &mesh->vertices[0]; mesh->polygons[5].vertices[0] = &mesh->vertices[0];
@ -188,74 +187,74 @@ Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2){
mesh->createPlanes(); mesh->createPlanes();
mesh->createEdges(); mesh->createEdges();
//mesh->createVertexnormals(); // mesh->createVertexnormals();
return mesh; return mesh;
} }
float getValueFromString(char *data) {
float getValueFromString(char* data){ while (*data == ' ')
while(*data==' ') data++; data++;
char* enddata=data; char *enddata = data;
//char oldchar; // char oldchar;
do{ do {
enddata++; enddata++;
if ((*enddata<'0' || *enddata>'9') && (*enddata!='.')) *enddata=0; if ((*enddata < '0' || *enddata > '9') && (*enddata != '.'))
} while(*enddata!=0); *enddata = 0;
float ret=atof(data); } while (*enddata != 0);
*enddata=' '; float ret = atof(data);
*enddata = ' ';
return ret; return ret;
} }
char* findStringEnd(char* data, char* findstring){ char *findStringEnd(char *data, char *findstring) {
return strstr(data,findstring)+strlen(findstring); return strstr(data, findstring) + strlen(findstring);
} }
Mesh* loadAscModel(char *filename, float scale){ Mesh *loadAscModel(char *filename, float scale) {
float zeroOffset[3] = {0.0, 0.0, 0.0}; float zeroOffset[3] = {0.0, 0.0, 0.0};
return loadAscModel(filename, scale, (float*)zeroOffset); return loadAscModel(filename, scale, (float *)zeroOffset);
} }
Mesh* loadAscModel(char *filename, float scale, float* offset){ Mesh *loadAscModel(char *filename, float scale, float *offset) {
Mesh* target = new Mesh(); Mesh *target = new Mesh();
FILE *file;
FILE* file;
float x, y, z; float x, y, z;
if ((file=fopen(filename,"rt"))==NULL){ if ((file = fopen(filename, "rt")) == NULL) {
printf("Unable to open file %s\n",filename); printf("Unable to open file %s\n", filename);
return NULL; return NULL;
} }
fseek(file,0,SEEK_END); fseek(file, 0, SEEK_END);
int size=ftell(file); int size = ftell(file);
fseek(file,0,SEEK_SET); fseek(file, 0, SEEK_SET);
char* data=(char*)malloc(size*sizeof(char)); char *data = (char *)malloc(size * sizeof(char));
fread(data,size,1,file); fread(data, size, 1, file);
fclose(file); fclose(file);
char* vert=findStringEnd(data,"Vertices:"); char *vert = findStringEnd(data, "Vertices:");
target->vertexcount=getValueFromString(vert); target->vertexcount = getValueFromString(vert);
char* face=findStringEnd(data,"Faces:"); char *face = findStringEnd(data, "Faces:");
target->polygoncount=getValueFromString(face); target->polygoncount = getValueFromString(face);
target->vertices = new Vertex[target->vertexcount]; target->vertices = new Vertex[target->vertexcount];
target->polygons = new class Polygon[target->polygoncount]; target->polygons = new class Polygon[target->polygoncount];
int i; int i;
vert=findStringEnd(data,"Vertex list:"); vert = findStringEnd(data, "Vertex list:");
for (i=0;i<target->vertexcount;i++){ for (i = 0; i < target->vertexcount; i++) {
vert=findStringEnd(vert,"Vertex"); vert = findStringEnd(vert, "Vertex");
vert=findStringEnd(vert,"X:"); vert = findStringEnd(vert, "X:");
x = getValueFromString(vert)*scale; x = getValueFromString(vert) * scale;
vert=findStringEnd(vert,"Y:"); vert = findStringEnd(vert, "Y:");
y = getValueFromString(vert)*scale; y = getValueFromString(vert) * scale;
vert=findStringEnd(vert,"Z:"); vert = findStringEnd(vert, "Z:");
z = getValueFromString(vert)*scale; z = getValueFromString(vert) * scale;
vectorSet(target->vertices[i].position, x + offset[0], y + offset[1] , z + offset[2]); vectorSet(target->vertices[i].position, x + offset[0], y + offset[1],
//recycle variables for texture coordinates z + offset[2]);
// recycle variables for texture coordinates
vert = findStringEnd(vert, "U:"); vert = findStringEnd(vert, "U:");
x = getValueFromString(vert); x = getValueFromString(vert);
vert = findStringEnd(vert, "V:"); vert = findStringEnd(vert, "V:");
@ -263,62 +262,93 @@ Mesh* loadAscModel(char *filename, float scale, float* offset){
target->vertices[i].setTexCoords(x, y); target->vertices[i].setTexCoords(x, y);
} }
int vnum; int vnum;
face=findStringEnd(data,"Face list:"); face = findStringEnd(data, "Face list:");
for (i = 0; i < target->polygoncount; i++) {
for (i=0;i<target->polygoncount;i++){ face = findStringEnd(face, "Face");
face=findStringEnd(face,"Face"); face = findStringEnd(face, "A:");
face=findStringEnd(face,"A:"); vnum = getValueFromString(face);
vnum=getValueFromString(face);
target->polygons[i].vertexcount = 3; target->polygons[i].vertexcount = 3;
target->polygons[i].vertices = new Vertex *[3]; target->polygons[i].vertices = new Vertex *[3];
target->polygons[i].vertices[0]=&(target->vertices[vnum]); target->polygons[i].vertices[0] = &(target->vertices[vnum]);
target->polygons[i].vertices[0]->setTexCoords(target->vertices[vnum].texcoords[0], target->polygons[i].vertices[0]->setTexCoords(
target->vertices[vnum].texcoords[0],
target->vertices[vnum].texcoords[1]); target->vertices[vnum].texcoords[1]);
face=findStringEnd(face,"B:"); face = findStringEnd(face, "B:");
vnum=getValueFromString(face); vnum = getValueFromString(face);
target->polygons[i].vertices[1]=&(target->vertices[vnum]); target->polygons[i].vertices[1] = &(target->vertices[vnum]);
target->polygons[i].vertices[1]->setTexCoords(target->vertices[vnum].texcoords[0], target->polygons[i].vertices[1]->setTexCoords(
target->vertices[vnum].texcoords[0],
target->vertices[vnum].texcoords[1]); target->vertices[vnum].texcoords[1]);
face=findStringEnd(face,"C:"); face = findStringEnd(face, "C:");
vnum=getValueFromString(face); vnum = getValueFromString(face);
target->polygons[i].vertices[2]=&(target->vertices[vnum]); target->polygons[i].vertices[2] = &(target->vertices[vnum]);
target->polygons[i].vertices[2]->setTexCoords(target->vertices[vnum].texcoords[0], target->polygons[i].vertices[2]->setTexCoords(
target->vertices[vnum].texcoords[0],
target->vertices[vnum].texcoords[1]); target->vertices[vnum].texcoords[1]);
char *face2=findStringEnd(face,"Nosmooth"); char *face2 = findStringEnd(face, "Nosmooth");
char *face3=findStringEnd(face,"Smoothing"); char *face3 = findStringEnd(face, "Smoothing");
if (face2 > face && face2 < face3) target->polygons[i].realsmooth = true; if (face2 > face && face2 < face3)
target->polygons[i].realsmooth = true;
} }
free(data); free(data);
data = NULL; data = NULL;
//target->createEdges(); // target->createEdges();
target->createPlanes(); target->createPlanes();
target->createVertexnormals(); target->createVertexnormals();
//return new MeshObject(target); // return new MeshObject(target);
return target; return target;
} }
void drawTrophy(void){ void drawTrophy(void) {
point2d points[14]; point2d points[14];
int width = 3; int width = 3;
int i = 0; int i = 0;
points[i].x = 0.0; points[i].y = 0.0; i++; points[i].x = 0.0;
points[i].x = width; points[i].y = 0.0; i++; points[i].y = 0.0;
points[i].x = width-2; points[i].y = 2.0; i++; i++;
points[i].x = width-2; points[i].y = 3.0; i++; points[i].x = width;
points[i].x = width-1; points[i].y = 4.0; i++; points[i].y = 0.0;
points[i].x = width-2; points[i].y = 5.0; i++; i++;
points[i].x = width-2; points[i].y = 6.0; i++; points[i].x = width - 2;
points[i].x = width-1; points[i].y = 8.0; i++; points[i].y = 2.0;
points[i].x = width; points[i].y = 9.0; i++; i++;
points[i].x = width+1; points[i].y = 11.0; i++; points[i].x = width - 2;
points[i].x = width+2; points[i].y = 15.0; i++; points[i].y = 3.0;
points[i].x = width+3; points[i].y = 21.0; i++; i++;
points[i].x = width+2; points[i].y = 21.0; i++; points[i].x = width - 1;
points[i].x = 0.0; points[i].y = 8.0; i++; points[i].y = 4.0;
i++;
points[i].x = width - 2;
points[i].y = 5.0;
i++;
points[i].x = width - 2;
points[i].y = 6.0;
i++;
points[i].x = width - 1;
points[i].y = 8.0;
i++;
points[i].x = width;
points[i].y = 9.0;
i++;
points[i].x = width + 1;
points[i].y = 11.0;
i++;
points[i].x = width + 2;
points[i].y = 15.0;
i++;
points[i].x = width + 3;
points[i].y = 21.0;
i++;
points[i].x = width + 2;
points[i].y = 21.0;
i++;
points[i].x = 0.0;
points[i].y = 8.0;
i++;
createLathedSurface(points, NULL, i, i*5, i*10); createLathedSurface(points, NULL, i, i * 5, i * 10);
} }

View file

@ -3,14 +3,12 @@
#include "mesh.h" #include "mesh.h"
MeshObject* createPyramid(float width, float height); MeshObject *createPyramid(float width, float height);
MeshObject* createSpherePool(float width, float height); MeshObject *createSpherePool(float width, float height);
Mesh *createBox(float x1, float x2, float y1, float y2, float z1, float z2);
Mesh* createBox(float x1, float x2, float y1, float y2, float z1, float z2); Mesh *loadAscModel(char *filename, float scale, float *offset);
Mesh* loadAscModel(char* filename, float scale, float* offset); Mesh *loadAscModel(char *filename, float scale);
Mesh* loadAscModel(char* filename, float scale);
void drawTrophy(void); void drawTrophy(void);
#endif #endif

View file

@ -10,8 +10,7 @@
#include "collision.h" #include "collision.h"
#include "glapi.h" #include "glapi.h"
Particle::Particle(World *world, Mesh *mesh) : MeshObject(mesh) {
Particle::Particle(World *world, Mesh *mesh) : MeshObject(mesh){
this->world = world; this->world = world;
} }
@ -19,7 +18,7 @@ Contact *contact = new Contact();
int bloodcount; int bloodcount;
void Particle::move(void){ void Particle::move(void) {
/*if (position[1] + momentum[1] < 0.5){ /*if (position[1] + momentum[1] < 0.5){
currentparticle->velocity.x*=0.8; currentparticle->velocity.x*=0.8;
currentparticle->velocity.y=fabs(currentparticle->velocity.y)*0.8; currentparticle->velocity.y=fabs(currentparticle->velocity.y)*0.8;
@ -39,10 +38,10 @@ void Particle::move(void){
vectorSet(contact->normal, 0, 1, 0); vectorSet(contact->normal, 0, 1, 0);
contact->object2 = NULL; contact->object2 = NULL;
bool die = false; bool die = false;
for (i = 0; i < mesh->vertexcount; i++){ for (i = 0; i < mesh->vertexcount; i++) {
float point[3]; float point[3];
transformPoint(point, mesh->vertices[i].position); transformPoint(point, mesh->vertices[i].position);
if (point[1] < 0){ if (point[1] < 0) {
contact->object1 = this; contact->object1 = this;
vectorCopy(contact->position, point); vectorCopy(contact->position, point);
handleCollision(contact); handleCollision(contact);
@ -62,48 +61,48 @@ void Particle::move(void){
lifetime++; lifetime++;
Object::move(); Object::move();
if (lifetime > 300) removeBlood(id); if (lifetime > 300)
removeBlood(id);
} }
void Particle::hitForce(float speed, Object *source){ void Particle::hitForce(float speed, Object *source) {
/*bounces++; /*bounces++;
if (bounces == 2){ if (bounces == 2){
removeBlood(id); removeBlood(id);
}*/ }*/
} }
void Particle::create(float *position, float *velocity){ void Particle::create(float *position, float *velocity) {
vectorCopy(this->position, position); vectorCopy(this->position, position);
vectorCopy(this->momentum, velocity); vectorCopy(this->momentum, velocity);
float rotate[3] = {randomf(2)-1, randomf(2)-1, randomf(2)-1}; float rotate[3] = {randomf(2) - 1, randomf(2) - 1, randomf(2) - 1};
vectorCopy(this->angularmomentum, rotate); vectorCopy(this->angularmomentum, rotate);
bounces = 0; bounces = 0;
lifetime = 0; lifetime = 0;
world->addParticle(this); world->addParticle(this);
} }
void Particle::destroy(void){ void Particle::destroy(void) { world->removeParticle(this); }
world->removeParticle(this);
}
Particle **bloodparticles; Particle **bloodparticles;
BloodAppearance::BloodAppearance(int *lifetime) : BasicBlockAppearance(1, 1, 1){ BloodAppearance::BloodAppearance(int *lifetime)
: BasicBlockAppearance(1, 1, 1) {
this->lifetime = lifetime; this->lifetime = lifetime;
usematerial = false; usematerial = false;
} }
void BloodAppearance::draw(void){ void BloodAppearance::draw(void) {
glPushMatrix(); glPushMatrix();
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
float alpha = 1-*lifetime*0.003; float alpha = 1 - *lifetime * 0.003;
if (alpha < 0) alpha = 0; if (alpha < 0)
alpha = 0;
glColor4f(1, 0, 0, alpha);//1.0/(1+*lifetime*0.004)); glColor4f(1, 0, 0, alpha); // 1.0/(1+*lifetime*0.004));
glScalef(0.5, 0.5, 0.5); glScalef(0.5, 0.5, 0.5);
BasicBlockAppearance::draw(); BasicBlockAppearance::draw();
@ -115,25 +114,27 @@ void BloodAppearance::draw(void){
World *bloodworld; World *bloodworld;
void initBloods(World *world){ void initBloods(World *world) {
bloodcount = 0; bloodcount = 0;
bloodparticles = new Particle *[MAXBLOOD]; bloodparticles = new Particle *[MAXBLOOD];
int i; int i;
Mesh *bloodmesh = createBox(-0.5, 0.5, -0.5*BLOCKHEIGHT, 0.5*BLOCKHEIGHT, -0.5, 0.5); Mesh *bloodmesh =
for (i = 0; i < MAXBLOOD; i++){ createBox(-0.5, 0.5, -0.5 * BLOCKHEIGHT, 0.5 * BLOCKHEIGHT, -0.5, 0.5);
for (i = 0; i < MAXBLOOD; i++) {
bloodparticles[i] = new Particle(world, bloodmesh); bloodparticles[i] = new Particle(world, bloodmesh);
bloodparticles[i]->appearance = new BloodAppearance(&(bloodparticles[i]->lifetime)); bloodparticles[i]->appearance =
new BloodAppearance(&(bloodparticles[i]->lifetime));
bloodparticles[i]->setMass(1); bloodparticles[i]->setMass(1);
bloodparticles[i]->prepare(); bloodparticles[i]->prepare();
//bloodparticles[i]->setGravity(true); // bloodparticles[i]->setGravity(true);
//bloodparticles[i]->setCollisionGroup(COLLISIONGROUP_PARTICLE); // bloodparticles[i]->setCollisionGroup(COLLISIONGROUP_PARTICLE);
//bloodparticles[i]->id = i; // bloodparticles[i]->id = i;
} }
bloodworld = world; bloodworld = world;
} }
void createBlood(float *position, float *velocity){ void createBlood(float *position, float *velocity) {
if (bloodcount < MAXBLOOD){ if (bloodcount < MAXBLOOD) {
Particle *currentparticle = bloodparticles[bloodcount]; Particle *currentparticle = bloodparticles[bloodcount];
currentparticle->create(position, velocity); currentparticle->create(position, velocity);
currentparticle->id = bloodcount; currentparticle->id = bloodcount;
@ -141,11 +142,11 @@ void createBlood(float *position, float *velocity){
} }
} }
void removeBlood(int id){ void removeBlood(int id) {
Particle *particle = bloodparticles[id]; Particle *particle = bloodparticles[id];
particle->destroy(); particle->destroy();
bloodparticles[id] = bloodparticles[bloodcount-1]; bloodparticles[id] = bloodparticles[bloodcount - 1];
bloodparticles[id]->id = id; bloodparticles[id]->id = id;
bloodparticles[bloodcount-1] = particle; bloodparticles[bloodcount - 1] = particle;
bloodcount--; bloodcount--;
} }

View file

@ -8,7 +8,7 @@ class BloodAppearance;
#include "legoblocks.h" #include "legoblocks.h"
#include "world.h" #include "world.h"
class Particle : public MeshObject{ class Particle : public MeshObject {
private: private:
int bounces; int bounces;
bool enabled; bool enabled;
@ -27,18 +27,13 @@ public:
void hitForce(float speed, Object *source); void hitForce(float speed, Object *source);
void create(float *position, float *velocity); void create(float *position, float *velocity);
void destroy(void); void destroy(void);
}; };
#define MAXBLOOD 500 #define MAXBLOOD 500
class BloodAppearance : public BasicBlockAppearance {
class BloodAppearance : public BasicBlockAppearance{
private: private:
int *lifetime; int *lifetime;
@ -53,4 +48,3 @@ void createBlood(float *position, float *velocity);
void removeBlood(int id); void removeBlood(int id);
#endif #endif

View file

@ -21,12 +21,11 @@ bool gameinitialized = false;
void initFontTexture(void); void initFontTexture(void);
void initScenes(void){ void initScenes(void) {
knobgllist = glGenLists(1); knobgllist = glGenLists(1);
setDetail(detail); setDetail(detail);
// Simple loading-screen
//Simple loading-screen
enable2D(); enable2D();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@ -40,25 +39,23 @@ void initScenes(void){
disable2D(); disable2D();
SKYBOX = -1; SKYBOX = -1;
initTextures(); initTextures();
initFight(); initFight();
initMenu(); initMenu();
initEnd(); initEnd();
changeGameMode(MENUMODE); changeGameMode(MENUMODE);
//changeGameMode(ENDMODE); // changeGameMode(ENDMODE);
gameinitialized = true; gameinitialized = true;
} }
void changeGameMode(int newmode){ void changeGameMode(int newmode) {
gamemode = newmode; gamemode = newmode;
changed = true; changed = true;
} }
void calculateFrame(int framecount){ void calculateFrame(int framecount) {
switch(gamemode){ switch (gamemode) {
case MENUMODE: case MENUMODE:
calculateMenu(framecount); calculateMenu(framecount);
break; break;
@ -73,14 +70,15 @@ void calculateFrame(int framecount){
changed = false; changed = false;
} }
void drawFrame(int framecount){ void drawFrame(int framecount) {
if (changed) calculateFrame(framecount); if (changed)
calculateFrame(framecount);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
switch(gamemode){ switch (gamemode) {
case MENUMODE: case MENUMODE:
drawMenu(framecount); drawMenu(framecount);
break; break;
@ -118,17 +116,17 @@ Texture *damageLeg;
Texture *tuxtexture; Texture *tuxtexture;
Texture *faceTexture; Texture *faceTexture;
void initFontTexture(void){ void initFontTexture(void) {
if (!texturesloaded){ if (!texturesloaded) {
float trans[3] = {1, 0, 0}; float trans[3] = {1, 0, 0};
fonttexture = new Texture(); fonttexture = new Texture();
fonttexture->loadImage(DATAPATH"font.png", trans); fonttexture->loadImage(DATAPATH "font.png", trans);
} else{ } else {
fonttexture->reload(); fonttexture->reload();
} }
} }
void initTextures(void){ void initTextures(void) {
/*SKY_FRONT_ID = DRUID.loadTexture(SKYFRONT); /*SKY_FRONT_ID = DRUID.loadTexture(SKYFRONT);
SKY_BACK_ID = DRUID.loadTexture(SKYBACK); SKY_BACK_ID = DRUID.loadTexture(SKYBACK);
SKY_LEFT_ID = DRUID.loadTexture(SKYLEFT); SKY_LEFT_ID = DRUID.loadTexture(SKYLEFT);
@ -136,7 +134,7 @@ void initTextures(void){
SKY_TOP_ID = DRUID.loadTexture(SKYTOP); SKY_TOP_ID = DRUID.loadTexture(SKYTOP);
SKY_BOTTOM_ID = DRUID.loadTexture(SKYBOTTOM);*/ SKY_BOTTOM_ID = DRUID.loadTexture(SKYBOTTOM);*/
if (!texturesloaded){ if (!texturesloaded) {
skyfronttexture = new Texture(); skyfronttexture = new Texture();
skyfronttexture->loadImage(SKYFRONT); skyfronttexture->loadImage(SKYFRONT);
skybacktexture = new Texture(); skybacktexture = new Texture();
@ -150,7 +148,6 @@ void initTextures(void){
skybottomtexture = new Texture(); skybottomtexture = new Texture();
skybottomtexture->loadImage(SKYBOTTOM); skybottomtexture->loadImage(SKYBOTTOM);
float something[3] = {1, 0, 0.5}; float something[3] = {1, 0, 0.5};
damageHead = new Texture(); damageHead = new Texture();
damageHead->loadImage(DAMAGEHEAD, something); damageHead->loadImage(DAMAGEHEAD, something);
@ -166,13 +163,12 @@ void initTextures(void){
float zeros[3] = {0, 0, 0}; float zeros[3] = {0, 0, 0};
flaretexture = new Texture(); flaretexture = new Texture();
flaretexture->loadImage(DATAPATH"flare.png", zeros); flaretexture->loadImage(DATAPATH "flare.png", zeros);
float pink[3] = {1, 0, 1}; float pink[3] = {1, 0, 1};
tuxtexture = new Texture(); tuxtexture = new Texture();
tuxtexture->loadImage(DATAPATH"tux.png", pink); tuxtexture->loadImage(DATAPATH "tux.png", pink);
} else{ } else {
skyfronttexture->reload(); skyfronttexture->reload();
skybacktexture->reload(); skybacktexture->reload();
skylefttexture->reload(); skylefttexture->reload();
@ -192,8 +188,8 @@ void initTextures(void){
texturesloaded = true; texturesloaded = true;
} }
void setDetail(int detail){ void setDetail(int detail) {
switch(detail){ switch (detail) {
case 0: case 0:
knobdetail = 0; knobdetail = 0;
break; break;
@ -209,5 +205,3 @@ void setDetail(int detail){
} }
initKnob(); initKnob();
} }

View file

@ -13,4 +13,3 @@ void initTextures(void);
void setDetail(int detail); void setDetail(int detail);
#endif #endif

View file

@ -1,18 +1,8 @@
#include "shape.h" #include "shape.h"
Shape::Shape(Object *object){ Shape::Shape(Object *object) { this->object = object; }
this->object = object;
}
bool Shape::checkCollision(Object *target){ bool Shape::checkCollision(Object *target) { return false; }
return false; bool Shape::checkCollisionPeer(Shape *target) { return false; }
} bool Shape::checkCollisionPeer(SphereShape *target) { return false; }
bool Shape::checkCollisionPeer(Shape *target){ bool Shape::checkCollisionPeer(MeshShape *target) { return false; }
return false;
}
bool Shape::checkCollisionPeer(SphereShape *target){
return false;
}
bool Shape::checkCollisionPeer(MeshShape *target){
return false;
}

View file

@ -10,14 +10,13 @@ class MeshShape;
/* /*
* Abstract class for object geometry * Abstract class for object geometry
*/ */
class Shape{ class Shape {
protected: protected:
Object *object; Object *object;
public: public:
Shape(Object *object); Shape(Object *object);
virtual float calculateMomentOfInertia(float *rotationvector) = 0; virtual float calculateMomentOfInertia(float *rotationvector) = 0;
virtual bool checkCollision(Object *target); virtual bool checkCollision(Object *target);
@ -28,4 +27,3 @@ public:
}; };
#endif #endif

View file

@ -10,60 +10,50 @@
#include "collision.h" #include "collision.h"
#include "glapi.h" #include "glapi.h"
Sphere::Sphere(void) {
Sphere::Sphere(void){
appearance = new SphereAppearance(); appearance = new SphereAppearance();
Object::appearance = appearance; Object::appearance = appearance;
geometry = new SphereShape(this); geometry = new SphereShape(this);
Object::geometry = geometry; Object::geometry = geometry;
} }
void Sphere::setRadius(float r){ void Sphere::setRadius(float r) {
if (r < 0) r = -r; if (r < 0)
r = -r;
this->r = r; this->r = r;
appearance->setRadius(r); appearance->setRadius(r);
geometry->setRadius(r); geometry->setRadius(r);
} }
SphereAppearance::SphereAppearance(void){ SphereAppearance::SphereAppearance(void) { setRadius(1); }
setRadius(1);
}
void SphereAppearance::setRadius(float r){ void SphereAppearance::setRadius(float r) {
if (r < 0) r = -r; if (r < 0)
r = -r;
this->r = r; this->r = r;
} }
void Sphere::setColor(float red, float green, float blue){ void Sphere::setColor(float red, float green, float blue) {
appearance->getMaterial()->setColor(red, green, blue, 1); appearance->getMaterial()->setColor(red, green, blue, 1);
} }
void SphereAppearance::draw(void){ void SphereAppearance::draw(void) {
material.enable(); material.enable();
createSphere(r); createSphere(r);
} }
SphereShape::SphereShape(Object *sphere) : Shape(sphere) { setRadius(1); }
void SphereShape::setRadius(float r) { this->r = r; }
float SphereShape::getRadius(void) { return r; }
SphereShape::SphereShape(Object *sphere) : Shape(sphere){ bool SphereShape::checkCollision(Object *target) {
setRadius(1);
}
void SphereShape::setRadius(float r){
this->r = r;
}
float SphereShape::getRadius(void){
return r;
}
bool SphereShape::checkCollision(Object *target){
return target->geometry->checkCollisionPeer(this); return target->geometry->checkCollisionPeer(this);
} }
float SphereShape::calculateMomentOfInertia(float *rotationvector){ float SphereShape::calculateMomentOfInertia(float *rotationvector) {
return 2.0/3.0*r*r; return 2.0 / 3.0 * r * r;
} }
/*bool SphereShape::checkCollisionPeer(PlaneShape *target){ /*bool SphereShape::checkCollisionPeer(PlaneShape *target){
@ -84,7 +74,7 @@ float SphereShape::calculateMomentOfInertia(float *rotationvector){
return false; return false;
}*/ }*/
bool SphereShape::checkCollisionPeer(SphereShape *target){ bool SphereShape::checkCollisionPeer(SphereShape *target) {
/*float sourceposition[3], targetposition[3]; /*float sourceposition[3], targetposition[3];
object->getPosition(sourceposition); object->getPosition(sourceposition);
target->object->getPosition(targetposition); target->object->getPosition(targetposition);
@ -95,7 +85,7 @@ bool SphereShape::checkCollisionPeer(SphereShape *target){
target->object->unTransformPoint(impact, impact); target->object->unTransformPoint(impact, impact);
float distance2 = vectorDot(impact, impact); float distance2 = vectorDot(impact, impact);
if (distance2 < (r + target->r)*(r + target->r)){ if (distance2 < (r + target->r) * (r + target->r)) {
/*float temp[3], temp2[3], temp3[3]; /*float temp[3], temp2[3], temp3[3];
object->getMomentum(temp2); object->getMomentum(temp2);
target->object->getMomentum(temp3); target->object->getMomentum(temp3);
@ -113,7 +103,7 @@ bool SphereShape::checkCollisionPeer(SphereShape *target){
addCollision(object, target->object, normal, contactpoint); addCollision(object, target->object, normal, contactpoint);
//vectorAdd(contactnormal, normal); // vectorAdd(contactnormal, normal);
return true; return true;
} }
@ -121,8 +111,9 @@ bool SphereShape::checkCollisionPeer(SphereShape *target){
return false; return false;
} }
bool between(float x, float x1, float x2){ bool between(float x, float x1, float x2) {
if ((x >= x1 && x <=x2) || (x >= x2 && x <=x1)) return true; if ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))
return true;
return false; return false;
} }
@ -238,9 +229,7 @@ bool between(float x, float x1, float x2){
return false; return false;
}*/ }*/
bool SphereShape::checkCollisionPeer(MeshShape *target) {
bool SphereShape::checkCollisionPeer(MeshShape *target){
float position[3] = {0, 0, 0}; float position[3] = {0, 0, 0};
object->transformPoint(position, position); object->transformPoint(position, position);
target->object->unTransformPoint(position, position); target->object->unTransformPoint(position, position);
@ -249,13 +238,13 @@ bool SphereShape::checkCollisionPeer(MeshShape *target){
float normal[3]; float normal[3];
float contactpoint[3]; float contactpoint[3];
if (checkSphereMeshCollision(position, r, mesh, normal, contactpoint)){ if (checkSphereMeshCollision(position, r, mesh, normal, contactpoint)) {
target->object->transformVector(normal, normal); target->object->transformVector(normal, normal);
target->object->transformPoint(contactpoint, contactpoint); target->object->transformPoint(contactpoint, contactpoint);
addCollision(object, target->object, normal, contactpoint); addCollision(object, target->object, normal, contactpoint);
//vectorAdd(contactnormal, normal); // vectorAdd(contactnormal, normal);
return true; return true;
} }

View file

@ -5,12 +5,11 @@
#include "material.h" #include "material.h"
#include "mesh.h" #include "mesh.h"
class SphereAppearance; class SphereAppearance;
//Object for sphere // Object for sphere
class Sphere : public Object{ class Sphere : public Object {
private: private:
float r; float r;
SphereAppearance *appearance; SphereAppearance *appearance;
@ -23,11 +22,9 @@ public:
void setColor(float red, float green, float blue); void setColor(float red, float green, float blue);
}; };
// Appearance of sphere
class SphereAppearance : public Appearance {
//Appearance of sphere
class SphereAppearance : public Appearance{
private: private:
float r; float r;
@ -38,11 +35,9 @@ public:
void draw(void); void draw(void);
}; };
// Geometry of sphere
class SphereShape : public Shape {
//Geometry of sphere
class SphereShape : public Shape{
private: private:
float r; float r;
@ -64,4 +59,3 @@ public:
}; };
#endif #endif

View file

@ -1,57 +1,55 @@
#include "texture.h" #include "texture.h"
#include "graphics.h" #include "graphics.h"
Texture::Texture(void){ Texture::Texture(void) {
this->textureId = -1; this->textureId = -1;
this->enabled = false; this->enabled = false;
} }
Texture::~Texture(void){ Texture::~Texture(void) {
if (textureId != -1){ if (textureId != -1) {
DRUID.freeTexture(textureId); DRUID.freeTexture(textureId);
textureId = -1; textureId = -1;
enabled = false; enabled = false;
} }
} }
Texture::Texture(int id){ Texture::Texture(int id) {
if (id > -1){ if (id > -1) {
this->textureId = id; this->textureId = id;
this->enabled = false; this->enabled = false;
} } else {
else{
this->textureId = -1; this->textureId = -1;
this->enabled = false; this->enabled = false;
} }
} }
bool Texture::loadImage(char* path){ bool Texture::loadImage(char *path) {
format = GL_RGB; format = GL_RGB;
texture = IMG_Load(path); texture = IMG_Load(path);
//texture = SDL_DisplayFormatAlpha(texture); // texture = SDL_DisplayFormatAlpha(texture);
this->textureId = DRUID.loadTexture(texture, -1); this->textureId = DRUID.loadTexture(texture, -1);
//this->textureId = DRUID.loadTexture(path, -1); // this->textureId = DRUID.loadTexture(path, -1);
this->enable(); this->enable();
return this->isValidId(); return this->isValidId();
} }
bool Texture::loadImage(char* path, float *trans){ bool Texture::loadImage(char *path, float *trans) {
format = GL_RGBA; format = GL_RGBA;
texture = IMG_Load(path); texture = IMG_Load(path);
Uint32 colorKey = SDL_MapRGB(texture->format, Uint32 colorKey =
(Uint8)(trans[0] * 255), SDL_MapRGB(texture->format, (Uint8)(trans[0] * 255),
(Uint8)(trans[1] * 255), (Uint8)(trans[1] * 255), (Uint8)(trans[2] * 255));
(Uint8)(trans[2] * 255)); // SDL_SetAlpha(texture, 0, SDL_ALPHA_OPAQUE);
//SDL_SetAlpha(texture, 0, SDL_ALPHA_OPAQUE);
SDL_SetColorKey(texture, SDL_SRCCOLORKEY, colorKey); SDL_SetColorKey(texture, SDL_SRCCOLORKEY, colorKey);
//SDL_Surface* alphaSurface = SDL_DisplayFormatAlpha(texture); // SDL_Surface* alphaSurface = SDL_DisplayFormatAlpha(texture);
texture = SDL_DisplayFormatAlpha(texture); texture = SDL_DisplayFormatAlpha(texture);
this->textureId = DRUID.loadTexture(texture, -1, format); this->textureId = DRUID.loadTexture(texture, -1, format);
@ -59,39 +57,33 @@ bool Texture::loadImage(char* path, float *trans){
return this->isValidId(); return this->isValidId();
} }
void Texture::reload(void){ void Texture::reload(void) {
this->textureId = DRUID.loadTexture(texture, -1, format); this->textureId = DRUID.loadTexture(texture, -1, format);
this->enable(); this->enable();
} }
void Texture::disable(void){ void Texture::disable(void) {
this->enabled = false; this->enabled = false;
glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
} }
void Texture::enable(void){ void Texture::enable(void) {
if (textureId > -1){ if (textureId > -1) {
this->enabled = true; this->enabled = true;
glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureId); glBindTexture(GL_TEXTURE_2D, textureId);
} }
} }
bool Texture::isEnabled(void){ bool Texture::isEnabled(void) { return this->enabled; }
return this->enabled;
}
int Texture::getId(void){ int Texture::getId(void) { return this->textureId; }
return this->textureId;
}
void Texture::setId(int id){ void Texture::setId(int id) {
if (id > -1){ if (id > -1) {
this->textureId = id; this->textureId = id;
this->enable(); this->enable();
} }
} }
bool Texture::isValidId(void){ bool Texture::isValidId(void) { return (this->textureId > -1); }
return (this->textureId > -1);
}

View file

@ -3,16 +3,15 @@
#include <SDL_image.h> #include <SDL_image.h>
#include "main.h" #include "main.h"
class Texture{ class Texture {
public: public:
Texture(void); Texture(void);
Texture(int id); Texture(int id);
~Texture(void); ~Texture(void);
bool loadImage(char* path); bool loadImage(char *path);
bool loadImage(char* path, float *trans); bool loadImage(char *path, float *trans);
void enable(void); void enable(void);
void disable(void); void disable(void);
bool isEnabled(void); bool isEnabled(void);
@ -21,13 +20,12 @@ public:
bool isValidId(void); bool isValidId(void);
void reload(void); void reload(void);
//int* getOGLTexture(void); // int* getOGLTexture(void);
//int* getModifiableOGLTexture(void); // int* getModifiableOGLTexture(void);
private: private:
int textureId; int textureId;
//int* modTexture; // int* modTexture;
bool enabled; bool enabled;
SDL_Surface *texture; SDL_Surface *texture;
@ -35,4 +33,3 @@ private:
}; };
#endif #endif

View file

@ -1,39 +1,37 @@
#include <stdlib.h> #include <stdlib.h>
void swapInt(int *a, int *b){ void swapInt(int *a, int *b) {
int temp = *a; int temp = *a;
*a = *b; *a = *b;
*b = temp; *b = temp;
} }
void swapFloat(float *a, float *b){ void swapFloat(float *a, float *b) {
float temp = *a; float temp = *a;
*a = *b; *a = *b;
*b = temp; *b = temp;
} }
int random(int x){ int random(int x) { return rand() * x / RAND_MAX; }
return rand() * x / RAND_MAX;
float randomf(float x) { return rand() * x / RAND_MAX; }
int smod(int val, int mod) {
if (val >= 0)
return val % mod;
int temp = -val / mod + 1;
return (val + temp * mod) % mod;
} }
float randomf(float x){ double sdes(double val) {
return rand() * x / RAND_MAX; if (val >= 0)
return val - (int)(val);
return val - (int)(val) + 1;
} }
int smod(int val, int mod){ double sfmod(double val, double mod) {
if (val>=0) return val%mod; val -= (int)(val / mod) * mod;
int temp=-val/mod+1; if (val < 0)
return (val+temp*mod)%mod; val += mod;
}
double sdes(double val){
if (val>=0) return val-(int)(val);
return val-(int)(val)+1;
}
double sfmod(double val, double mod){
val-=(int)(val/mod)*mod;
if (val<0) val+=mod;
return val; return val;
} }

View file

@ -1,7 +1,6 @@
#ifndef __UTILS_H_INCLUDED__ #ifndef __UTILS_H_INCLUDED__
#define __UTILS_H_INCLUDED__ #define __UTILS_H_INCLUDED__
#define PI 3.14159265358979323846 #define PI 3.14159265358979323846
void swapInt(int *a, int *b); void swapInt(int *a, int *b);
@ -13,4 +12,3 @@ double sdes(double val);
double sfmod(double val, double mod); double sfmod(double val, double mod);
#endif #endif

View file

@ -4,146 +4,145 @@
#include "vector.h" #include "vector.h"
#include "utils.h" #include "utils.h"
void vectorSet(float *target, float x, float y, float z){ void vectorSet(float *target, float x, float y, float z) {
target[0] = x; target[0] = x;
target[1] = y; target[1] = y;
target[2] = z; target[2] = z;
} }
void vectorCopy(float *target, float *source){ void vectorCopy(float *target, float *source) {
target[0] = source[0]; target[0] = source[0];
target[1] = source[1]; target[1] = source[1];
target[2] = source[2]; target[2] = source[2];
} }
void vectorAdd(float *target, float *source1, float *source2){ void vectorAdd(float *target, float *source1, float *source2) {
target[0] = source1[0] + source2[0]; target[0] = source1[0] + source2[0];
target[1] = source1[1] + source2[1]; target[1] = source1[1] + source2[1];
target[2] = source1[2] + source2[2]; target[2] = source1[2] + source2[2];
} }
void vectorAdd(float *target, float *source){ void vectorAdd(float *target, float *source) {
target[0] += source[0]; target[0] += source[0];
target[1] += source[1]; target[1] += source[1];
target[2] += source[2]; target[2] += source[2];
} }
void vectorSub(float *target, float *source1, float *source2){ void vectorSub(float *target, float *source1, float *source2) {
target[0] = source1[0] - source2[0]; target[0] = source1[0] - source2[0];
target[1] = source1[1] - source2[1]; target[1] = source1[1] - source2[1];
target[2] = source1[2] - source2[2]; target[2] = source1[2] - source2[2];
} }
void vectorSub(float *target, float *source){ void vectorSub(float *target, float *source) {
target[0] -= source[0]; target[0] -= source[0];
target[1] -= source[1]; target[1] -= source[1];
target[2] -= source[2]; target[2] -= source[2];
} }
void vectorNegative(float *target, float *source){ void vectorNegative(float *target, float *source) {
target[0] = -source[0]; target[0] = -source[0];
target[1] = -source[1]; target[1] = -source[1];
target[2] = -source[2]; target[2] = -source[2];
} }
void vectorNegative(float *target){ void vectorNegative(float *target) {
target[0] = -target[0]; target[0] = -target[0];
target[1] = -target[1]; target[1] = -target[1];
target[2] = -target[2]; target[2] = -target[2];
} }
void vectorScale(float *target, float *source, float scale){ void vectorScale(float *target, float *source, float scale) {
target[0] = source[0] * scale; target[0] = source[0] * scale;
target[1] = source[1] * scale; target[1] = source[1] * scale;
target[2] = source[2] * scale; target[2] = source[2] * scale;
} }
void vectorScale(float *target, float scale){ void vectorScale(float *target, float scale) {
target[0] *= scale; target[0] *= scale;
target[1] *= scale; target[1] *= scale;
target[2] *= scale; target[2] *= scale;
} }
float vectorDot(float *source1, float *source2){ float vectorDot(float *source1, float *source2) {
return source1[0]*source2[0] + source1[1]*source2[1] + source1[2]*source2[2]; return source1[0] * source2[0] + source1[1] * source2[1] +
source1[2] * source2[2];
} }
float vectorNormalizedDot(float *source1, float *source2){ float vectorNormalizedDot(float *source1, float *source2) {
return vectorDot(source1, source2) / (vectorLength(source1) * vectorLength(source2)); return vectorDot(source1, source2) /
(vectorLength(source1) * vectorLength(source2));
} }
float vectorLength(float *source){ float vectorLength(float *source) { return sqrtf(vectorDot(source, source)); }
return sqrtf(vectorDot(source, source));
void vectorCross(float *target, float *source1, float *source2) {
target[0] = source1[1] * source2[2] - source1[2] * source2[1];
target[1] = source1[2] * source2[0] - source1[0] * source2[2];
target[2] = source1[0] * source2[1] - source1[1] * source2[0];
} }
void vectorCross(float *target, float *source1, float *source2){ void vectorNormalize(float *target, float *source) {
target[0] = source1[1]*source2[2] - source1[2]*source2[1]; vectorScale(target, source, 1.0 / vectorLength(source));
target[1] = source1[2]*source2[0] - source1[0]*source2[2];
target[2] = source1[0]*source2[1] - source1[1]*source2[0];
} }
void vectorNormalize(float *target, float *source){ void vectorNormalize(float *target) {
vectorScale(target, source, 1.0/vectorLength(source)); vectorScale(target, 1.0 / vectorLength(target));
} }
void vectorNormalize(float *target){ void vectorReflect(float *target, float *source, float *normal) {
vectorScale(target, 1.0/vectorLength(target));
}
void vectorReflect(float *target, float *source, float *normal){
vectorCopy(target, normal); vectorCopy(target, normal);
vectorScale(target, -vectorDot(source, normal)*2); vectorScale(target, -vectorDot(source, normal) * 2);
vectorAdd(target, source); vectorAdd(target, source);
} }
void vectorProject(float *target, float *source1, float *source2){ void vectorProject(float *target, float *source1, float *source2) {
vectorScale(target, source2, vectorDot(source1, source2) / vectorDot(source2, source2)); vectorScale(target, source2,
vectorDot(source1, source2) / vectorDot(source2, source2));
} }
bool vectorIsZero(float *vector){ bool vectorIsZero(float *vector) {
if (vector[0] == 0 && vector[1] == 0 && vector[2] == 0) return true; if (vector[0] == 0 && vector[1] == 0 && vector[2] == 0)
//if (vectorDot(vector, vector) < 0.00001) return true; return true;
else return false; // if (vectorDot(vector, vector) < 0.00001) return true;
else
return false;
} }
void vectorSaturate(float *target, float *source, float min, float max){ void vectorSaturate(float *target, float *source, float min, float max) {
float len = vectorLength(source); float len = vectorLength(source);
if (len < min){ if (len < min) {
len = min; len = min;
} else if (len > max){ } else if (len > max) {
len = max; len = max;
} else{ } else {
if (target != source) vectorCopy(target, source); if (target != source)
vectorCopy(target, source);
return; return;
} }
vectorNormalize(target, source); vectorNormalize(target, source);
vectorScale(target, len); vectorScale(target, len);
} }
void vectorSaturate(float *vector, float min, float max){ void vectorSaturate(float *vector, float min, float max) {
vectorSaturate(vector, vector, min, max); vectorSaturate(vector, vector, min, max);
} }
void vectorMatrixMultiply(float *target, float *source, float *matrix){ void vectorMatrixMultiply(float *target, float *source, float *matrix) {
float source2[3]; float source2[3];
if (source == target){ if (source == target) {
vectorCopy(source2, source); vectorCopy(source2, source);
source = source2; source = source2;
} }
int x; int x;
for (x = 0; x < 3; x++){ for (x = 0; x < 3; x++) {
target[x] = source[0]*matrix[0+x] + target[x] = source[0] * matrix[0 + x] + source[1] * matrix[3 + x] +
source[1]*matrix[3+x] + source[2] * matrix[6 + x];
source[2]*matrix[6+x];
} }
} }
void matrixSet(float *matrix, float x1, float y1, float z1, float x2, float y2,
float z2, float x3, float y3, float z3) {
void matrixSet(float *matrix,
float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3){
matrix[0] = x1; matrix[0] = x1;
matrix[1] = y1; matrix[1] = y1;
matrix[2] = z1; matrix[2] = z1;
@ -155,13 +154,13 @@ void matrixSet(float *matrix,
matrix[8] = z3; matrix[8] = z3;
} }
void matrixSet(float *matrix, float *r1, float *r2, float *r3){ void matrixSet(float *matrix, float *r1, float *r2, float *r3) {
vectorCopy(&matrix[0], r1); vectorCopy(&matrix[0], r1);
vectorCopy(&matrix[3], r2); vectorCopy(&matrix[3], r2);
vectorCopy(&matrix[6], r3); vectorCopy(&matrix[6], r3);
} }
void matrixCopy(float *target, float *source){ void matrixCopy(float *target, float *source) {
target[0] = source[0]; target[0] = source[0];
target[1] = source[1]; target[1] = source[1];
target[2] = source[2]; target[2] = source[2];
@ -173,11 +172,11 @@ void matrixCopy(float *target, float *source){
target[8] = source[8]; target[8] = source[8];
} }
void matrixIdentity(float *matrix){ void matrixIdentity(float *matrix) {
matrixSet(matrix, 1, 0, 0, 0, 1, 0, 0, 0, 1); matrixSet(matrix, 1, 0, 0, 0, 1, 0, 0, 0, 1);
} }
void matrixAdd(float *target, float *source1, float *source2){ void matrixAdd(float *target, float *source1, float *source2) {
target[0] = source1[0] + source2[0]; target[0] = source1[0] + source2[0];
target[1] = source1[1] + source2[1]; target[1] = source1[1] + source2[1];
target[2] = source1[2] + source2[2]; target[2] = source1[2] + source2[2];
@ -189,7 +188,7 @@ void matrixAdd(float *target, float *source1, float *source2){
target[8] = source1[8] + source2[8]; target[8] = source1[8] + source2[8];
} }
void matrixAdd(float *target, float *source){ void matrixAdd(float *target, float *source) {
target[0] += source[0]; target[0] += source[0];
target[1] += source[1]; target[1] += source[1];
target[2] += source[2]; target[2] += source[2];
@ -201,24 +200,24 @@ void matrixAdd(float *target, float *source){
target[8] += source[8]; target[8] += source[8];
} }
void matrixMultiply(float *target, float *source1, float *source2){ void matrixMultiply(float *target, float *source1, float *source2) {
float target2[9]; float target2[9];
float *oldtarget = target; float *oldtarget = target;
bool copy = false; bool copy = false;
if (source1 == target || source2 == target){ if (source1 == target || source2 == target) {
copy = true; copy = true;
target = target2; target = target2;
} }
int x, y; int x, y;
for (y = 0; y < 3; y++){ for (y = 0; y < 3; y++) {
for (x = 0; x < 3; x++){ for (x = 0; x < 3; x++) {
*target = source1[y*3+0]*source2[x] + *target = source1[y * 3 + 0] * source2[x] +
source1[y*3+1]*source2[3+x] + source1[y * 3 + 1] * source2[3 + x] +
source1[y*3+2]*source2[6+x]; source1[y * 3 + 2] * source2[6 + x];
target++; target++;
} }
} }
if (copy){ if (copy) {
matrixCopy(oldtarget, target2); matrixCopy(oldtarget, target2);
} }
} }
@ -233,7 +232,7 @@ void matrixMultiply(float *target, float *source1, float *source2){
matrixMultiply(matrix, matrix, rotmat); matrixMultiply(matrix, matrix, rotmat);
}*/ }*/
void matrixCreateRotation(float *matrix, float *vector){ void matrixCreateRotation(float *matrix, float *vector) {
float angle = vectorLength(vector); float angle = vectorLength(vector);
float n[3]; float n[3];
vectorNormalize(n, vector); vectorNormalize(n, vector);
@ -246,20 +245,23 @@ void matrixCreateRotation(float *matrix, float *vector){
float y = n[1]; float y = n[1];
float z = n[2]; float z = n[2];
matrixSet(matrix, matrixSet(matrix, t * x * x + c, t * y * x + s * z, t * z * x - s * y,
t*x*x + c, t*y*x + s*z, t*z*x - s*y, t * x * y - s * z, t * y * y + c, t * z * y + s * x,
t*x*y - s*z, t*y*y + c, t*z*y + s*x, t * x * z + s * y, t * y * z - s * x, t * z * z + c);
t*x*z + s*y, t*y*z - s*x, t*z*z + c);
} }
void matrixTranspose(float *target, float *source){ void matrixTranspose(float *target, float *source) {
target[0] = source[0]; target[1] = source[3]; target[2] = source[6]; target[0] = source[0];
target[3] = source[1]; target[4] = source[4]; target[5] = source[7]; target[1] = source[3];
target[6] = source[2]; target[7] = source[5]; target[8] = source[8]; target[2] = source[6];
target[3] = source[1];
target[4] = source[4];
target[5] = source[7];
target[6] = source[2];
target[7] = source[5];
target[8] = source[8];
} }
/*void rotatePointAroundVector(float *target, float *point, float *vector){ /*void rotatePointAroundVector(float *target, float *point, float *vector){
float angle = vectorLength(vector); float angle = vectorLength(vector);
float n[3]; float n[3];
@ -271,4 +273,3 @@ void matrixTranspose(float *target, float *source){
//r' = r*c + n*(n . r)*t + (r x n)*s //r' = r*c + n*(n . r)*t + (r x n)*s
}*/ }*/

View file

@ -24,27 +24,22 @@ bool vectorIsZero(float *vector);
void vectorSaturate(float *target, float *source, float min, float max); void vectorSaturate(float *target, float *source, float min, float max);
void vectorSaturate(float *vector, float min, float max); void vectorSaturate(float *vector, float min, float max);
//Projects vector source1 onto vector source2 // Projects vector source1 onto vector source2
void vectorProject(float *target, float *source1, float *source2); void vectorProject(float *target, float *source1, float *source2);
void vectorMatrixMultiply(float *target, float *source, float *matrix); void vectorMatrixMultiply(float *target, float *source, float *matrix);
void matrixSet(float *matrix, float x1, float y1, float z1, float x2, float y2,
float z2, float x3, float y3, float z3);
void matrixSet(float *matrix,
float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3);
void matrixSet(float *matrix, float *r1, float *r2, float *r3); void matrixSet(float *matrix, float *r1, float *r2, float *r3);
void matrixCopy(float *target, float *source); void matrixCopy(float *target, float *source);
void matrixIdentity(float *matrix); void matrixIdentity(float *matrix);
void matrixAdd(float *target, float *source1, float *source2); void matrixAdd(float *target, float *source1, float *source2);
void matrixAdd(float *target, float *source); void matrixAdd(float *target, float *source);
void matrixMultiply(float *target, float *source1, float *source2); void matrixMultiply(float *target, float *source1, float *source2);
//void matrixMultiply(float *target, float *source); // void matrixMultiply(float *target, float *source);
void matrixRotate(float *matrix, float *vector); void matrixRotate(float *matrix, float *vector);
void matrixCreateRotation(float *matrix, float *vector); void matrixCreateRotation(float *matrix, float *vector);
void matrixTranspose(float *target, float *source); void matrixTranspose(float *target, float *source);
#endif #endif

View file

@ -4,7 +4,7 @@
#include "collision.h" #include "collision.h"
#include "vector.h" #include "vector.h"
World::World(void){ World::World(void) {
childlist = NULL; childlist = NULL;
linklist = NULL; linklist = NULL;
maxparticles = 500; maxparticles = 500;
@ -12,10 +12,10 @@ World::World(void){
particlecount = 0; particlecount = 0;
} }
void World::prepare(void){ void World::prepare(void) {
objectlist *node = childlist; objectlist *node = childlist;
childcount = 0; childcount = 0;
while (node != NULL){ while (node != NULL) {
Object *child = node->object; Object *child = node->object;
child->prepare(); child->prepare();
node = node->next; node = node->next;
@ -25,30 +25,29 @@ void World::prepare(void){
childs = new Object *[childcount]; childs = new Object *[childcount];
node = childlist; node = childlist;
int i = 0; int i = 0;
while (node != NULL){ while (node != NULL) {
Object *child = node->object; Object *child = node->object;
childs[i] = child; childs[i] = child;
node = node->next; node = node->next;
i++; i++;
} }
contacts = new Contact[MAXCONTACTS];//childcount*childcount]; contacts = new Contact[MAXCONTACTS]; // childcount*childcount];
} }
#define GRAVITY 9.81 #define GRAVITY 9.81
//#define GRAVITY 15 //#define GRAVITY 15
void World::move(void){ void World::move(void) {
int i, j; int i, j;
// Gravity
//Gravity
float gravity[3]; float gravity[3];
vectorSet(gravity, 0, 0, 0); vectorSet(gravity, 0, 0, 0);
for (i = 0; i < childcount; i++){ for (i = 0; i < childcount; i++) {
Object *object = childs[i]; Object *object = childs[i];
if (object->gravity){ if (object->gravity) {
gravity[1] = -object->getMass()*GRAVITY; gravity[1] = -object->getMass() * GRAVITY;
object->addExternalForce(gravity); object->addExternalForce(gravity);
} }
} }
@ -61,18 +60,17 @@ void World::move(void){
} }
}*/ }*/
// Collisions
//Collisions
contactcount = 0; contactcount = 0;
for (i = 0; i < childcount; i++){ for (i = 0; i < childcount; i++) {
Object *object1 = childs[i]; Object *object1 = childs[i];
int group1 = object1->getCollisionGroup(); int group1 = object1->getCollisionGroup();
for (j = i+1; j < childcount; j++){ for (j = i + 1; j < childcount; j++) {
Object *object2 = childs[j]; Object *object2 = childs[j];
int group2 = object2->getCollisionGroup(); int group2 = object2->getCollisionGroup();
if (isCollisionLink(group1, group2)){ if (isCollisionLink(group1, group2)) {
object2->geometry->checkCollision(object1); object2->geometry->checkCollision(object1);
} }
} }
@ -91,27 +89,28 @@ void World::move(void){
} }
}*/ }*/
//printf("Contacts: %i\n", contactcount); // printf("Contacts: %i\n", contactcount);
bool contactresponse; bool contactresponse;
j = 0; j = 0;
do{ do {
contactresponse = false; contactresponse = false;
//Links between objects // Links between objects
objectlinklist *node = linklist; objectlinklist *node = linklist;
while (node != NULL){ while (node != NULL) {
ObjectLink *link = node->link; ObjectLink *link = node->link;
if (handleLink(link)) contactresponse = true; if (handleLink(link))
contactresponse = true;
node = node->next; node = node->next;
} }
//Collision contact // Collision contact
for (i = 0; i < contactcount; i++){ for (i = 0; i < contactcount; i++) {
Contact *contact = &contacts[i]; Contact *contact = &contacts[i];
if (handleCollision(contact)) contactresponse = true; if (handleCollision(contact))
contactresponse = true;
} }
j++; j++;
@ -145,54 +144,55 @@ void World::move(void){
j++; j++;
} while (contactresponse && j < 3);*/ } while (contactresponse && j < 3);*/
for (i = 0; i < childcount; i++) {
for (i = 0; i < childcount; i++){
childs[i]->move(); childs[i]->move();
} }
for (i = 0; i < particlecount; i++){ for (i = 0; i < particlecount; i++) {
particles[i]->move(); particles[i]->move();
} }
} }
void World::draw(void){ void World::draw(void) {
int i; int i;
for (i = 0; i < childcount; i++) childs[i]->draw(); for (i = 0; i < childcount; i++)
for (i = 0; i < particlecount; i++) particles[i]->draw(); childs[i]->draw();
for (i = 0; i < particlecount; i++)
particles[i]->draw();
} }
void World::addChild(Object *child){ void World::addChild(Object *child) {
objectlist *node = new objectlist; objectlist *node = new objectlist;
node->object = child; node->object = child;
node->next = childlist; node->next = childlist;
childlist = node; childlist = node;
} }
void World::addParticle(Particle *particle){ void World::addParticle(Particle *particle) {
if (particlecount < maxparticles){ if (particlecount < maxparticles) {
particles[particlecount++] = particle; particles[particlecount++] = particle;
} }
} }
void World::removeParticle(Particle *particle){ void World::removeParticle(Particle *particle) {
int i; int i;
for (i = 0; i < particlecount; i++){ for (i = 0; i < particlecount; i++) {
if (particles[i] == particle){ if (particles[i] == particle) {
particles[i] = particles[particlecount-1]; particles[i] = particles[particlecount - 1];
particlecount--; particlecount--;
break; break;
} }
} }
} }
ObjectLink *World::addLink(Object *object1, Object *object2, float *point){ ObjectLink *World::addLink(Object *object1, Object *object2, float *point) {
ObjectLink *link = new ObjectLink(); ObjectLink *link = new ObjectLink();
link->object1 = object1; link->object1 = object1;
link->object2 = object2; link->object2 = object2;
if (point != NULL){ if (point != NULL) {
object1->unTransformPoint(link->point1, point); object1->unTransformPoint(link->point1, point);
object2->unTransformPoint(link->point2, point); object2->unTransformPoint(link->point2, point);
link->enabled = true; link->enabled = true;
} else{ } else {
link->enabled = false; link->enabled = false;
} }
objectlinklist *node = new objectlinklist; objectlinklist *node = new objectlinklist;
@ -202,10 +202,8 @@ ObjectLink *World::addLink(Object *object1, Object *object2, float *point){
return link; return link;
} }
void World::renewLink(ObjectLink *link, float *point){ void World::renewLink(ObjectLink *link, float *point) {
link->object1->unTransformPoint(link->point1, point); link->object1->unTransformPoint(link->point1, point);
link->object2->unTransformPoint(link->point2, point); link->object2->unTransformPoint(link->point2, point);
link->enabled = true; link->enabled = true;
} }

View file

@ -7,34 +7,33 @@ class ObjectLink;
#include "object.h" #include "object.h"
#include "particle.h" #include "particle.h"
class ObjectLink{ class ObjectLink {
public: public:
Object *object1, *object2; Object *object1, *object2;
float point1[3], point2[3]; float point1[3], point2[3];
bool enabled; bool enabled;
}; };
struct objectlinklist{ struct objectlinklist {
ObjectLink *link; ObjectLink *link;
objectlinklist *next; objectlinklist *next;
}; };
#define MAXCONTACTS 100 #define MAXCONTACTS 100
class World{ class World {
private: private:
objectlist *childlist; objectlist *childlist;
int childcount; int childcount;
Object **childs; Object **childs;
int particlecount; int particlecount;
int maxparticles; int maxparticles;
Particle **particles; Particle **particles;
objectlinklist *linklist; objectlinklist *linklist;
public: public:
World(void); World(void);
@ -47,10 +46,9 @@ public:
void addParticle(Particle *particle); void addParticle(Particle *particle);
void removeParticle(Particle *particle); void removeParticle(Particle *particle);
//Point is world-relative // Point is world-relative
ObjectLink *addLink(Object *object1, Object *object2, float *point); ObjectLink *addLink(Object *object1, Object *object2, float *point);
void renewLink(ObjectLink *link, float *point); void renewLink(ObjectLink *link, float *point);
}; };
#endif #endif