Exemple #1
0
objReader::objReader(const std::string &file, GLuint texture)
{
    loadObj(file);

    m_textures.push_back(texture);

}
Exemple #2
0
bool load(const Path &path, std::vector<Vertex> &verts, std::vector<TriangleI> &tris)
{
    if (path.testExtension("wo3"))
        return loadWo3(path, verts, tris);
    else if (path.testExtension("obj"))
        return loadObj(path, verts, tris);
    return false;
}
StaticObject::StaticObject(char* url,vec3 position,vec3 rotation,vec3 scale){
	mat4 t_normalizeMatrix =  loadObj(url);
	this->speed = vec3(0);
	this->position = position;
	this->rotation = rotation;
	this->scale = scale;
	calculateModelMatrix();
}
	Direct3D10Mesh* loadObj(ID3D10Device& device, const std::string& fileName, const D3DXCOLOR& color, float scale)
	{
		vector<Vertex> vertices;

		loadObj(fileName, color, scale, vertices, 0, 0, 0, 0);

		return new Direct3D10Mesh(device, vertices);
	}
Exemple #5
0
int main(int argc, char **argv) {
  
  if (argc < 2) {
    fprintf(stderr, "usage: %s objfilename[s]\n", argv[0]);
    return -1;
  }

  XYZ minP, maxP;

  int i;
  for (i = 1; i < argc; i++) {
    OBJ_STRUCT *obj; // = loadObj(argv[argc -i], "null", 1, 1, 1, 1);
    char *ext = argv[argc-i] + strlen(argv[argc-i]) - 3;
    if (!strncmp(ext, "obj", 3)) {
      obj = loadObj(argv[argc-i], "null", 1,1,1,1);
    } else if (!strncmp(ext, "stl", 3)) {
      obj = loadObjFromSTL(argv[argc-i], "null", 1,1,1,1);
    } else {
      fprintf(stderr, "Cannot load file '%s'.\n", argv[argc-i]);
      exit(-1);
    }
    if (i == 1) {
      minP = obj->minP;
      maxP = obj->maxP;
    } else {
      if (obj->minP.x < minP.x) {
	minP.x = obj->minP.x;
      }
      if (obj->minP.y < minP.y) {
	minP.y = obj->minP.y;
      }
      if (obj->minP.z < minP.z) {
	minP.z = obj->minP.z;
      }

      if (obj->maxP.x > maxP.x) {
	maxP.x = obj->maxP.x;
      }
      if (obj->maxP.y > maxP.y) {
	maxP.y = obj->maxP.y;
      }
      if (obj->maxP.z > maxP.z) {
	maxP.z = obj->maxP.z;
      }
      
    }
  }

  // offset all model parts
  XYZ mid = VectorAdd(minP, maxP);
  mid = VectorMul(mid, 0.5);
  fprintf(stderr, "OBJ vertex range: (%f,%f,%f) -> (%f,%f,%f)\n", minP.x, minP.y, minP.z,
	  maxP.x, maxP.y, maxP.z);
  fprintf(stderr, "OBJ vertex midpoint: (%f,%f,%f)\n", mid.x, mid.y, mid.z);

  return 0;
}
Exemple #6
0
int main(void) {
  char* fname="data/teddy.obj";
  int vertices = count('v',fname);
  int faces = count('f',fname);
  printf("%d %d",vertices,faces);
  GLfloat vertex_buffer_data[vertices*3];
  GLfloat color_buffer_data[vertices*3];
  GLushort index_buffer_data[faces*3];
  loadObj(vertex_buffer_data, color_buffer_data, index_buffer_data, vertices, faces, fname);
}
Exemple #7
0
static PyObject* pyLoadObj(PyObject *self, PyObject *args) {
	char* filename;	
	if(!PyArg_ParseTuple(args, "s", &filename))
      return NULL;

	// Load obj & print info
	int id = createObj();
	loadObj(filename, id);
	printf("Loaded: %i\n", id);
	return Py_BuildValue("i", id);
}
Exemple #8
0
int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(1280, 720);
    glutInitWindowPosition(20, 20);
    glutCreateWindow("ObjLoader");
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    loadObj("Bugatti-Veyron.obj");
    glutMainLoop();
    return 0;
}
Exemple #9
0
Mesh::Mesh(char *fileName, Material material)
{
    m_fileName = fileName;
    m_material = material;

    if (loadObj() != 0)
    {
        std::cerr << "Mesh: Error loading " << m_fileName << std::endl;
        std::exit(1);
    }

    std::cout << "Mesh: " << m_fileName << " has been loaded succesfully." << std::endl;
}
Exemple #10
0
void init() {

    camera.position[2] = 15;

    libpng_version();

    light0.slot = GL_LIGHT0;
    light0.setDiffuse(1.0, 1.0, 1.0, 1.0);
    light0.setPosition(0.0, 0.0, 1.0, 0.0);
    light0.load();
    light0.enable();

    glewInit();

    loadObj((char*) "models/350z.obj", &mesh);
    VBOfromMesh(vbo, mesh);

    vbo.generate();

    int w, h;
    test_texture = texture_bank.findOrReg((char*) "textures/350z/vinyls.png");
    //test_texture = PNG_load((const char*) "textures/vinyls.png", &w, &h);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, test_texture);

    programID = loadShaders("shaders/vertex.glsl", "shaders/fragment.glsl");
    glUseProgram(programID);

    uTex = glGetUniformLocation(programID, "texDiff");
    glUniform1i(uTex, 0);

    uProjection = glGetUniformLocation(programID, "projection");
    uView = glGetUniformLocation(programID, "view");
    uModel = glGetUniformLocation(programID, "model");

    uLightPos = glGetUniformLocation(programID, "lightPos");
    uLightDiff = glGetUniformLocation(programID, "lightDiff");
    uLightSpec = glGetUniformLocation(programID, "lightSpec");

    uCameraPosition = glGetUniformLocation(programID, "cameraPosition");

    glEnable(GL_LIGHTING);
    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_ALPHA_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

    glEnable(GL_DEPTH_TEST);
}
Exemple #11
0
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(800,450);
glutInitWindowPosition(20,20);
glutCreateWindow("ObjLoader");
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(display);
loadObj("untitled.obj");//replace porsche.obj with radar.obj or any other .obj to display it
glutMainLoop();
return 0;
}
/* function main()
* Description:
*  - this is the main function
*  - does initialization and then calls glutMainLoop() to start the event handler
*/
int main(int argc, char **argv)
{
	/* initialize the window and OpenGL properly */
	glutInit(&argc, argv);
	glutInitWindowSize(windowWidth, windowHeight);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
	glutCreateWindow("Supercool dope title game");

	/* set up our function callbacks */
	glutDisplayFunc(DisplayCallbackFunction);
	glutKeyboardFunc(KeyboardCallbackFunction);
	glutKeyboardUpFunc(KeyboardUpCallbackFunction);
	glutReshapeFunc(WindowReshapeCallbackFunction);
	glutMouseFunc(MouseClickCallbackFunction);
	glutMotionFunc(MouseMotionCallbackFunction);
	glutPassiveMotionFunc(MousePassiveMotionCallbackFunction);
	glutTimerFunc(1, TimerCallbackFunction, 0);

	/* Call some OpenGL parameters */
	glEnable(GL_CULL_FACE);
	//glFrontFace(GL_CCW);
	//glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);

	/* Turn on the lights! */
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_COLOR_MATERIAL);
	glShadeModel(GL_SMOOTH);
	///glShademodel(GL_SMOOTH);

	/* Init Image Library */
	glEnable(GL_TEXTURE_2D);
	//replace the parameters in loadObj with what you want to load
	loadObj("C:\\Users\\100550931\\Documents\\intro to graphics tutorials\\Tutorial3Package\\Tutorial3Package\\Tutorial1IntroGraphics\\obj.txt");
	ilInit();
	iluInit();
	ilutRenderer(ILUT_OPENGL);

	/* Load a texture */
	textureHandle = ilutGLLoadImage("..//img//win.png");
	glBindTexture(GL_TEXTURE_2D, textureHandle);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glBindTexture(GL_TEXTURE_2D, NULL);

	/* start the event handler */
	glutMainLoop();
	return 0;
}
Exemple #13
0
void init(void)
{
	srand(static_cast <unsigned> (time(NULL)));
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    
    loadObj();

//    findBoundingBox();
    
    initLighting();
    
	glEnable(GL_TEXTURE_2D);
    glDepthRange(0.0, 1.0);  /* The default z mapping */
}
Exemple #14
0
objReader::objReader(const std::string &file, const char* texture)
: m_vertices(), m_normals(), m_texCoord(), m_faces(), m_textures()
{
    loadObj(file);

    //computeNormals();

    if (texture) {
        m_textures.push_back(TextureManager::loadTexture(texture, texture));
    }

    std::cout<<"Read "<<m_vertices.size()<<" vertices, "<<m_texCoord.size()
        <<" texcoord, "<<m_normals.size()<<" normals, "<<m_faces.size()<<" faces.\n"
        <<m_textures.size()<<" textures files were loaded\n";
}
Exemple #15
0
bool loadObj(Geometry &geom, const std::string &filename, float scale, int flags)
{
    std::vector<Geometry> geomList;
    loadObj(geomList,filename,scale,flags);

    geom.clear();

    // Pack all Geometry into one.
    for(unsigned int i=0; i<geomList.size(); ++i)
    {
        geom.addGeometry(geomList[i]);
    }

    return 0;
}
// initilize scene
// load obj files, set lights, camera
void initScene(const std::string& textureName)
{
	// for loading triangle mesh
	Matrix4x4 matrix;
	loadObj(objName.c_str(), vertices, normals, texcoord, mesh);
	matrix.m[2][3] = -9.f;
	matrix.m[1][3] = 0.f;

	Transform* tr = new Transform(matrix);
	trfList.push_back(tr);
	Mesh* newmesh = new Mesh(tr, &vertices, &normals, &mesh);
	objList.push_back(newmesh);

	// object initialize, for sphere
	/*Matrix4x4 mat;
	mat.m[2][3] = -16.f;
	Transform* tr2 = new Transform(mat);
	trfList.push_back(tr2);
	Sphere *sphere1 = new Sphere(tr2, 6.f);
	objList.push_back(sphere1);*/

	// initialize image plane
	intensity = new float[WINX * WINY * 3];
	memset(intensity, 0, WINX*WINY * 3 * sizeof(float));

	// set up the camera
	Point camCenter, camLookAt(0.f, 0.f, -1.f);
	Vector camUp(0.f, 1.f, 0.f);
	float fovy = 60.f;
	camera = new PerspectiveCamera(camCenter, camLookAt, camUp, fovy);

	// set up the projectionLight
	Point e(-1.5f, 3.f, 15.f), gaze(-1.2f, 1.3f, 0.f);
	Vector up(0.f, 0.9f, 0.43589f);
	/* For sphere ray tracing test */
	/*Point e(0.f, 0.f, 7.f), gaze(.0f, 0.f, -1.f);
	Vector up(0.f, 1.f, 0.f);*/
	Transform light2world = LookAt(e, gaze, up);
	
	//string texname("grid.jpg");
	float projFovy = 20.0;
	ProjectionLight *projector = new ProjectionLight(Inverse(light2world), textureName, projFovy);

	// set up the sampler
	sampler = new SimpleSampler(WINX, WINY);

	scene = new Scene(sampler, camera, &objList, projector, WINX, WINY);
}
struct Model * loadModel(char * directory,char * modelname)
{
  struct Model * mod = ( struct Model * ) malloc(sizeof(struct Model));
  if ( mod == 0 )  { fprintf(stderr,"Could not allocate enough space for model %s \n",modelname);  return 0; }
  memset(mod , 0 , sizeof(struct Model));

  if ( strstr(modelname,".obj") != 0 )
    {
      mod->type = OBJMODEL;
      mod->model = (struct  OBJ_Model * ) loadObj(directory,modelname);
    }

  if (mod->model ==0 ) { free(mod); return 0 ;}

  return mod;
}
Exemple #18
0
bool
TriangleMesh::load(char* file, const Matrix4x4& ctm)
{
    FILE *fp = fopen(file, "rb");
    if (!fp)
    {
        error("Cannot open \"%s\" for reading\n",file);
        return false;
    }
    debug("Loading \"%s\"...\n", file);

    loadObj(fp, ctm);
    debug("Loaded \"%s\" with %d triangles\n",file,m_numTris);
    fclose(fp);

    return true;
}
Exemple #19
0
Model::Model(const QString &filePath)
    : m_fileName(QFileInfo(filePath).fileName())
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly))
        return;

    if (filePath.endsWith(".stl", Qt::CaseInsensitive)) {
        loadStl(file);
    } else if (filePath.endsWith(".obj", Qt::CaseInsensitive)) {
        loadObj(file);
    } else if (filePath.endsWith(".gcode", Qt::CaseInsensitive)) {
        loadGCode(filePath.toStdString());
    }

    m_transform.setToIdentity();
}
dpBinary* dpLoader::load(const char *path)
{
    size_t len = strlen(path);
    if(len>=4) {
        if     (_stricmp(&path[len-4], ".obj")==0) {
            return loadObj(path);
        }
        else if(_stricmp(&path[len-4], ".lib")==0) {
            return loadLib(path);
        }
        else if(_stricmp(&path[len-4], ".dll")==0 || _stricmp(&path[len-4], ".exe")==0) {
            return loadDll(path);
        }
    }
    dpPrintError("unrecognized file %s\n", path);
    return nullptr;
}
Exemple #21
0
void Model::load()
{
    loadObj( model_path, vertices, normals );

    glGenBuffers( 2, vbo );
    glGenVertexArrays( 1, vao );

    glBindBuffer( GL_ARRAY_BUFFER, vbo[ 0 ] );
    glBufferData( GL_ARRAY_BUFFER, vertices.size() * sizeof( glm::vec3 ), &vertices[ 0 ], GL_STATIC_DRAW );
    glBindVertexArray( vao[ 0 ] );
    glEnableVertexAttribArray( 0 );
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof( glm::vec3 ), (const GLvoid*) 0 );

    glBindBuffer( GL_ARRAY_BUFFER, vbo[ 1 ] );
    glBufferData( GL_ARRAY_BUFFER, normals.size() * sizeof( glm::vec3 ), &normals[ 0 ], GL_STATIC_DRAW );
    glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, sizeof( glm::vec3 ), (const GLvoid*) 0 );
    glEnableVertexAttribArray( 1 );
}
Exemple #22
0
int main(int argc, char* argv[])
{
    int timestoload = 1;

    if(argc == 1)
    {
        printf("usage testobjloader filename.obj 5\n");
        return 0;
    }

    if(argc == 3)
    {
        sscanf(argv[2], "%20i", &timestoload);
    }

    printf("starting to load %s %i times\n", argv[1], timestoload);
    timespec start, stop;
    clock_gettime(CLOCK_REALTIME, &start);
    double calltime;

    for(int i = 0; i < timestoload; i++)
    {
        obj* testmesh = loadObj(argv[1]);
        for(int j=0;j<testmesh->numfaces;j++)
        {

            fprintf(stdout,"%i %i %i\n",testmesh->faces[j].verts[0],testmesh->faces[j].verts[1],testmesh->faces[j].verts[2]);
        }
        obj* testmesh2 = ObjMakeUniqueFullVerts(testmesh);
        for(int j=0;j<testmesh2->numfaces;j++)
        {

            fprintf(stdout,"%i %i %i\n",testmesh2->faces[j].verts[0],testmesh2->faces[j].verts[1],testmesh2->faces[j].verts[2]);
        }
        delete testmesh;
        delete testmesh2;
    }

    clock_gettime(CLOCK_REALTIME, &stop);
    calltime = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec) / 1000000000.0;
    printf("done loading file %lfseconds\n", calltime / timestoload);

    return 0;
}
MeshManager :: MeshManager(ofVec3f s, int d, bool hf, char* fname){
	hasfile = hf;
	current = 0;
	depth = d;
	limit_depth = d;
	filename = fname;
	scale.set(1.,1.,1.);


	if(hasfile) meshes.push_back(loadObj());
	else meshes.push_back(loadMesh());


	vector<Delta*> changes;
	for(int i = 1; i < depth; i++) meshes.push_back(new Mesh(i, meshes.back(), changes));



}
Exemple #24
0
Mesh::Mesh(string filename, bool ccw):
    mRot(0,0,0),
    mPos(0,0,0),
    mAABB(BVL_SIZE(BVL)),
    mAABBTriangles(BVL_SIZE(BVL)),
    mSphere(BVL_SIZE(BVL)),
    mSphereTriangles(BVL_SIZE(BVL))
{
    clock_t t = clock();
    loadObj(filename, mVertices, mTriangles, ccw);
    createTriangleLists();
    createBoundingVolHierarchy();
    centerAlign();
    createNormals();
    calculateVolume();
    printf ("Mesh loading took:\t%4.2f sec | %d triangles \n", ((float)clock()-t)/CLOCKS_PER_SEC, mTriangles.size());
    for (int blevel=0; blevel<=BVL; blevel++)
        printf("Coverage Level %d: AABB %4.2f%%, Sphere %4.2f%% \n", blevel, 100*AABBCover[blevel], 100*sphereCover[blevel]);

}
int main(int argc, char *argv[]) {
  if (argc != 2) {
    std::cout << "usage: ./ObjLoader.out <Target Object Path>\n";
    exit(1);
  }

  if (!loadObj(std::string(argv[1]), mesh))
    std::cout << "Could not load obj\n";

  mesh.print();
  mesh.movetoCenter();
  mesh.fittoUnitSphere();

  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
  glutInitWindowPosition(50, 25);
  glutInitWindowSize(900, 620); // w h
  glutCreateWindow("OpenGL Window");
  glClearColor(.9, .9, .9, 0.0);

  initializeGL();

  // GLUT Display Function
  glutDisplayFunc(renderScene);
  glutReshapeFunc(resize);

  // Keyboard handlers
  glutKeyboardFunc(keyboardDown);

  // Mouse handlers
  glutMouseFunc(mouseClick);
  glutMotionFunc(mouseMotion);

  // GLUT Main Lopp
  glutMainLoop();

  return 0;
}
Exemple #26
0
    //--------------------------------------------------------------------
    Status MeshManager::mLoad(std::shared_ptr<Mesh> mesh, const std::string& sid) const {
        //try to load from the cache
        if (mesh->hasCache()) {
            return mLoad(mesh, sid,
                         mesh->positions,
                         mesh->uvs,
                         mesh->flatNormals,
                         mesh->vertexIndices);
        }

        //otherwise load from the file

        // stores elements as they comes from .obj
        std::vector<glm::vec3> positions;
        std::vector<glm::vec2> uvs;
        std::vector<glm::vec3> flatNormals;
        // map one UV & one p per vertex object
        std::vector<VertexIndices> vertexIndices;

        //filename, deduced from SID
        std::string path = mLocalDir + sid + ".obj";

        //load positions uvs and their indices from the obj file
        if (loadObj(path, positions, uvs, flatNormals, vertexIndices) != STATUS_OK) {
            Log::error(TAG, "Unable to load obj %s", path.c_str());
            return STATUS_KO;
        }

        //update the cache if any
        mesh->positions = positions;
        mesh->uvs = uvs;
        mesh->flatNormals = flatNormals;
        mesh->vertexIndices = vertexIndices;

        return mLoad(mesh, sid, positions, uvs, flatNormals, vertexIndices);
    }
	Direct3D10Mesh* loadObj(ID3D10Device& device, const string& fileName, const D3DXCOLOR& color)
	{
		return loadObj(device, fileName, color, 1.0f);
	}
int main()
{

    lightDir.x=0.5;
    lightDir.y=.7;
    lightDir.z=-0.5;
    kmVec3Normalize(&lightDir,&lightDir);

    // creates a window and GLES context
    // create a window and GLES context
	if (!glfwInit())
		exit(EXIT_FAILURE);

	window = glfwCreateWindow(width, height, "I N V A D E R S ! ! !", NULL, NULL);
	if (!window) {
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwSetWindowSizeCallback(window,window_size_callback);	
	glfwMakeContextCurrent(window);



    // all the shaders have at least texture unit 0 active so
    // activate it now and leave it active
    glActiveTexture(GL_TEXTURE0);

    // The obj shapes and their textures are loaded
    cubeTex = loadPNG("resources/textures/dice.png");
    loadObj(&cubeObj, "resources/models/cube.gbo",
            "resources/shaders/textured.vert", "resources/shaders/textured.frag");


    shipTex = loadPNG("resources/textures/shipv2.png");
    loadObjCopyShader(&shipObj,"resources/models/ship.gbo",&cubeObj);

    alienTex = loadPNG("resources/textures/alien.png");
    loadObjCopyShader(&alienObj, "resources/models/alien.gbo", &cubeObj);

    shotTex = loadPNG("resources/textures/shot.png");
    loadObjCopyShader(&shotObj, "resources/models/shot.gbo", &cubeObj);

    expTex = loadPNG("resources/textures/explosion.png");


    playerPos.x = 0;
    playerPos.y = 0;
    playerPos.z = 0;

    kmMat4Identity(&view);

    pEye.x = 0;
    pEye.y = 2;
    pEye.z = 4;
    pCenter.x = 0;
    pCenter.y = 0;
    pCenter.z = -5;
    pUp.x = 0;
    pUp.y = 1;
    pUp.z = 0;

    kmMat4LookAt(&view, &pEye, &pCenter, &pUp);

    // projection matrix, as distance increases
    // the way the model is drawn is effected
    kmMat4Identity(&projection);
    kmMat4PerspectiveProjection(&projection, 45,
                                (float)width/ height, 0.1, 1000);

    glViewport(0, 0, width,height);

    // these two matrices are pre combined for use with each model render
    kmMat4Assign(&vp, &projection);
    kmMat4Multiply(&vp, &vp, &view);

    // initialises glprint's matrix shader and texture
    initGlPrint(width,height);

	font1=createFont("resources/textures/font.png",0,256,16,16,16);
	font2=createFont("resources/textures/bigfont.png",32,512,9.5,32,48);

    glCullFace(GL_BACK);
    glEnable(GL_CULL_FACE);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_BLEND);	// only used by glprintf
    glEnable(GL_DEPTH_TEST);


    int num_frames = 0;

    bool quit = false;

    resetAliens();

    for (int n = 0; n < MAX_PLAYER_SHOTS; n++) {
        playerShots[n].alive = false;
    }


    initPointClouds("resources/shaders/particle.vert",
                    "resources/shaders/particle.frag",(float)width/24.0);



    for (int n = 0; n < MAX_ALIENS; n++) {
        aliens[n].explosion=createPointCloud(40);
        resetExposion(aliens[n].explosion); // sets initials positions
    }

	glClearColor(0, .5, 1, 1);

    while (!quit) {		// the main loop

        clock_gettime(0,&ts);  // note the time BEFORE we start to render the current frame
		glfwPollEvents();


        if (glfwGetKey(window,GLFW_KEY_ESCAPE)==GLFW_PRESS || glfwWindowShouldClose(window))
            quit = true;

        float rad;		// radians rotation based on frame counter

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        frame++;
        rad = frame * (0.0175f * 2);

        //kmMat4Identity(&model);
        kmMat4Translation(&model, playerPos.x, playerPos.y, playerPos.z);
        playerCroll +=
            (PIDcal(playerRoll, playerCroll, &playerPre_error, &playerIntegral)
             / 2);
//        kmMat4RotationPitchYawRoll(&model, 0, 3.1416, playerCroll * 3);	//
		kmMat4RotationYawPitchRoll(&rot,0,3.1416,-playerCroll*3);
        kmMat4Multiply(&model, &model, &rot);
        
        kmMat4Assign(&mvp, &vp);
        kmMat4Multiply(&mvp, &mvp, &model);

        kmMat4Assign(&mv, &view);
        kmMat4Multiply(&mv, &mv, &model);

        glBindTexture(GL_TEXTURE_2D, shipTex);
        drawObj(&shipObj, &mvp, &mv, lightDir, viewDir);

        glPrintf(50 + sinf(rad) * 16, 240 + cosf(rad) * 16,
                 font2,"frame=%i", frame);

        kmVec3 tmp;

        playerFireCount--;

        if (glfwGetKey(window,GLFW_KEY_LEFT_CONTROL)==GLFW_PRESS && playerFireCount < 0) {

            struct playerShot_t *freeShot;
            freeShot = getFreeShot();
            if (freeShot != 0) {
                playerFireCount = 15;
                freeShot->alive = true;
                kmVec3Assign(&freeShot->pos, &playerPos);
            }
        }

        for (int n = 0; n < MAX_PLAYER_SHOTS; n++) {
            if (playerShots[n].alive) {
                playerShots[n].pos.z -= .08;
                if (playerShots[n].pos.z < -10)
                    playerShots[n].alive = false;

                //kmMat4Identity(&model);
                kmMat4Translation(&model, playerShots[n].pos.x,
                                  playerShots[n].pos.y,
                                  playerShots[n].pos.z);
                //kmMat4RotationPitchYawRoll(&model, rad * 4, 0,
                //                           -rad * 4);
				kmMat4RotationYawPitchRoll(&rot,rad*4,0,-rad*4);
				kmMat4Multiply(&model,&model,&rot);
                kmMat4Assign(&mvp, &vp);
                kmMat4Multiply(&mvp, &mvp, &model);

                kmMat4Assign(&mv, &view);
                kmMat4Multiply(&mv, &mv, &model);

                glBindTexture(GL_TEXTURE_2D, shotTex);
                drawObj(&shotObj, &mvp, &mv, lightDir, viewDir);
            }
        }

        playerRoll = 0;
        if (glfwGetKey(window,GLFW_KEY_LEFT)==GLFW_PRESS && playerPos.x > -10) {
            playerPos.x -= 0.1;
            playerRoll = .2;
        }
        if (glfwGetKey(window,GLFW_KEY_RIGHT)==GLFW_PRESS && playerPos.x < 10) {
            playerPos.x += 0.1;
            playerRoll = -.2;
        }
        pEye.x = playerPos.x * 1.25;

        pCenter.x = playerPos.x;
        pCenter.y = playerPos.y + 1;
        pCenter.z = playerPos.z;

        int deadAliens;

        deadAliens = 0;

        for (int n = 0; n < MAX_ALIENS; n++) {
            if (aliens[n].alive == true) {

                //kmMat4Identity(&model);
                kmMat4Translation(&model, aliens[n].pos.x,
                                  aliens[n].pos.y, aliens[n].pos.z);
                //kmMat4RotationPitchYawRoll(&model, -.4, 0, 0);
				kmMat4RotationYawPitchRoll(&rot,.2,0,0);
				kmMat4Multiply(&model,&model,&rot);

                kmMat4Assign(&mvp, &vp);
                kmMat4Multiply(&mvp, &mvp, &model);

                kmMat4Assign(&mv, &view);
                kmMat4Multiply(&mv, &mv, &model);

                glBindTexture(GL_TEXTURE_2D, alienTex);
                drawObj(&alienObj, &mvp, &mv, lightDir, viewDir);

                kmVec3 d;
                for (int i = 0; i < MAX_PLAYER_SHOTS; i++) {
                    kmVec3Subtract(&d, &aliens[n].pos,
                                   &playerShots[i].pos);
                    if (kmVec3Length(&d) < .7
                            && playerShots[i].alive) {
                        aliens[n].alive = false;
                        playerShots[i].alive = false;
                        aliens[n].exploding = true;
                        resetExposion(aliens[n].explosion);
                    }
                }
            } 

            if (aliens[n].alive != true && aliens[n].exploding != true) {
                    deadAliens++;
                
            }
        }

        if (deadAliens == MAX_ALIENS) {
            resetAliens();
        }

		// draw explosions after ALL aliens
        for (int n = 0; n < MAX_ALIENS; n++) {
			if (aliens[n].exploding==true) {
				kmMat4Identity(&model);
				kmMat4Translation(&model, aliens[n].pos.x,
								  aliens[n].pos.y, aliens[n].pos.z);

				kmMat4Assign(&mvp, &vp);
				kmMat4Multiply(&mvp, &mvp, &model);
				glBindTexture(GL_TEXTURE_2D, expTex);
				drawPointCloud(aliens[n].explosion, &mvp);
				aliens[n].explosion->tick=aliens[n].explosion->tick+0.05;
				if (aliens[n].explosion->tick>1.25) {
					aliens[n].exploding=false;                   	
				} else {
					// update the explosion
					
					for (int i=0; i<aliens[n].explosion->totalPoints; i++) {
				
						float t;
						t=aliens[n].explosion->tick;
						if (i>aliens[n].explosion->totalPoints/2) t=t/2.0;
						aliens[n].explosion->pos[i*3]=aliens[n].explosion->vel[i*3] * t;
						aliens[n].explosion->pos[i*3+1]=aliens[n].explosion->vel[i*3+1] * t;
						aliens[n].explosion->pos[i*3+2]=aliens[n].explosion->vel[i*3+2] * t;
				
					}
				}
			}
		}

        // move camera
        kmMat4LookAt(&view, &pEye, &pCenter, &pUp);

        kmMat4Assign(&vp, &projection);
        kmMat4Multiply(&vp, &vp, &view);

        kmVec3Subtract(&viewDir,&pEye,&pCenter);
        kmVec3Normalize(&viewDir,&viewDir);

        // dump values
        glPrintf(100, 280, font1,"eye    %3.2f %3.2f %3.2f ", pEye.x, pEye.y, pEye.z);
        glPrintf(100, 296, font1,"centre %3.2f %3.2f %3.2f ", pCenter.x, pCenter.y,
                 pCenter.z);
        glPrintf(100, 340, font1,"frame %i %i ", frame, frame % 20);



        glfwSwapBuffers(window);

        ts.tv_nsec+=20000000;  // 1000000000 / 50 = 50hz less time to render the frame
        //thrd_sleep(&ts,NULL); // tinycthread
        usleep(20000); // while I work out why tinycthread that was working isnt.... :/

    }

	glfwDestroyWindow(window);
	glfwTerminate();

    return 0;
}
Exemple #29
0
void loadModels() {
	model=loadObj(AUTO_MODEL_DIR, AUTO_MATERIAL_DIR);
	loaded=loadObj(TRACK_MODEL_DIR, TRACK_MATERIAL_DIR);
}
Exemple #30
0
		Polyline* loadPolyline(const std::string& filename){
			unsigned int vbo, ibo, vao, count;
			loadObj(filename, vao, vbo, ibo, count);
			Polyline *p = new Polyline(vbo, ibo, vao, count);
			return p;
		}