VPN termux about China.net

Saturday 7 September 2024

SDL2 openGl load obj

 #include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <jni.h>
#include <errno.h>
#include <math.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include "SDL2/SDL.h"
//#include<GL/gl.h>
//#include<GL/glxext.h>
//#include<GL/glu.h>
#include "SDL_test_common.h"
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include "SDL_image.h"
#include <stdio.h>
#include <string.h>
#include <SDL_image.h>
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#define PATH "/storage/emulated/0/img.jpg"
SDL_Surface* surface;
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define SCREEN_BPP 255
#define FALSE 0
#define TRUE 1
GLuint texture[1];
SDLTest_CommonState *state;
SDL_Event *event;
SDL_GLContext *context; // No need to have this as a pointer
struct mouse_handle {
    int x = 1;
    int y = 1;
} mouse;
struct Vertex {
    float x, y, z;
};
struct Normal {
    float nx, ny, nz;
};
struct TexCoord {
    float u, v;
};
std::vector<Vertex>* vertices = nullptr;
std::vector<Normal>* normals = nullptr;
std::vector<TexCoord>* texCoords = nullptr;
void loadObj(const char *filename) {
    vertices = new std::vector<Vertex>();
    normals = new std::vector<Normal>();
    texCoords = new std::vector<TexCoord>();
    std::ifstream objFile(filename);
    if (!objFile) {
        std::cerr << "Unable to open file: " << filename << std::endl;
        exit(1);
    }
    std::vector<Vertex> tempVertices;
    std::vector<Normal> tempNormals;
    std::vector<TexCoord> tempTexCoords;
    std::string line;
    while (std::getline(objFile, line)) {
        std::istringstream iss(line);
        std::string prefix;
        iss >> prefix;
        if (prefix == "v") {
            Vertex vertex;
            iss >> vertex.x >> vertex.y >> vertex.z;
            tempVertices.push_back(vertex);
        } else if (prefix == "vn") {
            Normal normal;
            iss >> normal.nx >> normal.ny >> normal.nz;
            tempNormals.push_back(normal);
        } else if (prefix == "vt") {
            TexCoord texCoord;
            iss >> texCoord.u >> texCoord.v;
            tempTexCoords.push_back(texCoord);
        } else if (prefix == "f") {
            std::vector<int> vIndices, tIndices, nIndices;
            std::string vertexData;
            while (iss >> vertexData) {
                std::replace(vertexData.begin(), vertexData.end(), '/', ' ');
                std::istringstream vertexStream(vertexData);
                int vIndex, tIndex = 0, nIndex = 0;
                vertexStream >> vIndex;
                if (vertexStream.peek() == ' ') { vertexStream >> tIndex; }
                if (vertexStream.peek() == ' ') { vertexStream >> nIndex; }
                vIndices.push_back(vIndex);
                tIndices.push_back(tIndex);
                nIndices.push_back(nIndex);
            }
            // Tworzenie trójkątów
            for (size_t i = 1; i < vIndices.size() - 1; i++) {
                vertices->push_back(tempVertices[vIndices[0] - 1]);
                vertices->push_back(tempVertices[vIndices[i] - 1]);
                vertices->push_back(tempVertices[vIndices[i + 1] - 1]);
                normals->push_back(tempNormals[nIndices[0] - 1]);
                normals->push_back(tempNormals[nIndices[i] - 1]);
                normals->push_back(tempNormals[nIndices[i + 1] - 1]);
                // Dodanie współrzędnych tekstury, jeśli są dostępne
                if (!tempTexCoords.empty()) {
                    texCoords->push_back(tempTexCoords[tIndices[0] - 1]);
                    texCoords->push_back(tempTexCoords[tIndices[i] - 1]);
                    texCoords->push_back(tempTexCoords[tIndices[i + 1] - 1]);
                }
            }
        }
    }
    objFile.close();
}
int LoadGLTextures() {
    SDL_Surface *TextureImage = IMG_Load("elo.bmp");
    if (!TextureImage) {
        std::cerr << "Unable to load texture: " << IMG_GetError() << std::endl;
        return 0;
    }
    glGenTextures(1, &texture[0]);  // Poprawka: indeks tekstury powinien być texture[0], nie [1]
    glBindTexture(GL_TEXTURE_2D, texture[0]);
    int mode = (TextureImage->format->BytesPerPixel == 4) ? GL_RGBA : GL_RGB;
    glTexImage2D(GL_TEXTURE_2D, 0, mode, TextureImage->w, TextureImage->h, 0, mode, GL_UNSIGNED_BYTE, TextureImage->pixels);
           glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
        glGenerateMipmapOES(GL_TEXTURE_2D);  // OpenGL ES 2.0: zmieniono z glGenerateMipmapOES na glGenerateMipmap
    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_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    SDL_FreeSurface(TextureImage);  // Zwalnianie pamięci po załadowaniu tekstury
    return 1;
}



void setPerspective(float fov, float aspect, float znear, float zfar) {
    float ymax = znear * tanf(fov * M_PI / 360.0f);
    float ymin = -ymax;
    float xmin = ymin * aspect;
    float xmax = ymax * aspect;
    glFrustumf(xmin, xmax, ymin, ymax, znear, zfar);
}
void cleanup() {
    delete vertices;
    delete normals;
    delete texCoords;
}
void renderScene() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    setPerspective(60.0f, 1.0f, 0.1f, 80.0f);  // Adjusted FOV and aspect ratio
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    // Apply transformations
    glTranslatef(0.0f, 0.0f, -5.0f);  // Move the object back
    glScalef(1.0f, 1.0f, 1.0f);  // Scale the object
    glRotatef(mouse.x % 360, 0.0f, 1.0f, 0.0f);  // Rotate around Y-axis
    glRotatef(mouse.y % 360, 1.0f, 0.0f, 0.0f);  // Rotate around X-axis
    // Lighting setup
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    GLfloat light_position[] = {0.0f, 1.0f, 1.0f, 0.0f};
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);
       glEnable(GL_TEXTURE_2D);
   glShadeModel( GL_SMOOTH );
    // Enable and set vertex arrays
      glShadeModel( GL_SMOOTH );
//    glClearDepthx( 1.0f );                                                        // specify the clear value for the depth buffer
    glEnable( GL_DEPTH_TEST );
    glDepthFunc( GL_LEQUAL );
    glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );                        // specify implementation-specific hints
    GLfloat amb_light[] = { 0.1, 0.1, 0.1, 1.0 };
    GLfloat diffuse[] = { 0.6, 0.6, 0.6, 1 };
    GLfloat specular[] = { 0.7, 0.7, 0.3, 1 };
    glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light );
    glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
    glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
    glEnable( GL_LIGHT0 );
    glEnable( GL_COLOR_MATERIAL );
    glShadeModel( GL_SMOOTH );
  //  glLightModelx( GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE );
    glDepthFunc( GL_LEQUAL );
    glEnable( GL_DEPTH_TEST );
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glClearColor(0.0, 0.0, 0.0, 1.0); glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(3, GL_FLOAT, sizeof(Vertex), vertices->data());
    // Enable and set normal arrays
    glEnableClientState(GL_NORMAL_ARRAY);
    glNormalPointer(GL_FLOAT, sizeof(Normal), normals->data());
    // Enable and set texture coordinates arrays
    if (!texCoords->empty()) {
     glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glTexCoordPointer(2, GL_FLOAT, sizeof(TexCoord), texCoords->data());
        glBindTexture(GL_TEXTURE_2D, texture[0]);
    }
    //gluLookAt( 4,2,0, 0,0,0, 0,1,0);   
    
//GLUquadricObj *sphere=NULL;
//  sphere = gluNewQuadric();
  //gluQuadricDrawStyle(sphere, GLU_FILL);
  //gluQuadricTexture(sphere, TRUE);
//  gluQuadricNormals(sphere, GLU_SMOOTH);
glBindTexture( GL_TEXTURE_2D,texture[0] );
    // Draw the object
    glDrawArrays(GL_TRIANGLES, 0, vertices->size());
    // Disable client states
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    if (!texCoords->empty()) {
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    }
    // Swap buffers to display the scene
    SDL_GL_SwapWindow(state->windows[0]);
}


int main(int argc, char *argv[]) {
if (!(IMG_Init(IMG_INIT_JPG) & IMG_INIT_JPG)) {
    std::cerr << "IMG_Init failed: " << IMG_GetError() << std::endl;
    return 0;
}
    SDL_DisplayMode mode;
    state = SDLTest_CommonCreateState(argv, SDL_INIT_EVERYTHING);
    SDLTest_CommonInit(state);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
    bool sdlmainloop = true;
    bool running = true;
LoadGLTextures(); 
  
    loadObj("/sdcard/cubec.obj");  // Wczytanie pliku OBJ na początku
SDL_GL_CreateContext(*state->windows);
    
    while (running) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = false;
            }
            if (event.type == SDL_MOUSEMOTION) {
                mouse.x = event.motion.x;
                mouse.y = event.motion.y;
            }
            // 
            // Render the scene
          //  SDL_GL_SwapWindow(state->windows[0]);
            renderScene();
             //  SDL_GL_SwapWindow(*state->windows);
        }
    }
cleanup();
    // Cleanup
    SDL_GL_DeleteContext(context);
    SDLTest_CommonQuit(state);
    return 0;
}

No comments:

Post a Comment