Пример #1
0
unsigned char *loadImage( String path,int *width,int *height,int *depth ){
	FILE *f=fopenFile( path,"rb" );
	if( !f ) return 0;
	unsigned char *data=stbi_load_from_file( f,width,height,depth,0 );
	fclose( f );
	return data;
}
Пример #2
0
void Texture::loadImage(const string& filePath){
	FILE *file = fopen(filePath.c_str(), "rb");
	if(!file)
		throw runtime_error("texture image file cannot be opened");
	//or give option to replace with default.png?

	data = stbi_load_from_file(file, &width, &height, &channel, 0);
	fclose(file);
}
Пример #3
0
		/*
		Constructor
		shader = shader to use for drawing
		filenames = locations of the 6 textures
		cubemapVertices = (36) vertices of the cubemap
		Author: Bas Rops - 22-05-2014
		Last edit: <name> - dd-mm-yyyy
		*/
		Cubemap::Cubemap(ShaderProgram* shader, std::string filenames[6], const std::vector<glm::vec3> &cubemapVertices)
		{
			if (shader != NULL)
				this->shader = shader;
			else
				std::cout << "Error initializing Cubemap: Shader == NULL" << std::endl;

			//Generate 1 texture
			glGenTextures(1, &texid);
			//Bind the texture as a cubemap texture
			glBindTexture(GL_TEXTURE_CUBE_MAP, texid);
			//Set cubemap parameters
			glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
			glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
			glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

			//Load all 6 textures for the cubemap
			for (int i = 0; i < 6; i++)
			{
				std::string* filename = &filenames[i];

				//Open the file
				FILE* pFile = fopen(filename->c_str(), "rb");
				if (pFile)
				{
					//Get the data from the texture
					BYTE* data = stbi_load_from_file(pFile, &width, &height, &components, 4);
					//Close the file
					fclose(pFile);

					glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

					//Data no longer required, since it has been copied into a texture
					delete data;
				}
				else
					std::cout << "Error while loading cubemap texture: " << *filename << " does not exist." << std::endl;
			}

			//Add all vertices of the cubemap to a VBO
			std::vector<VertexPosition> vertices;

			for(const glm::vec3 &vertex : cubemapVertices)
			{
				vertices.push_back(VertexPosition(vertex));
			}

			vbo = new VBO<VertexPosition>();

			vbo->bind();
			vbo->setData(vertices.size(), &vertices[0], GL_DYNAMIC_DRAW);
			vertices.clear();
		}
Пример #4
0
void Texture::initFail(GLenum type, std::string fname, std::vector<std::array<GLenum, 2> > params)
{
    std::cout << "InitFail " << fname;
    
    try
    {
        FILE *file = fopen(fname.c_str(), "rb");
        
        if (!file)
            return ;

        int width, height, comp;
        unsigned char* imgdata = stbi_load_from_file(file, &width, &height, &comp, 0);
        fclose(file);
    
    
        //png::image<png::rgba_pixel> image (fname);
        //GLubyte* imgdata = extractData(image, false, false);
        
        glGenTextures(1, &textureID);
        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, type, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, imgdata);
        
        std::cout << comp << " " << textureID << " " << GL_RGB << " " << type << " " << width << " " << height << std::endl;
        
        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_T, GL_CLAMP_TO_EDGE);

        
        for(int i=0; i<params.size(); i++)
        {
            glTexParameteri(GL_TEXTURE_2D, params[i][0], params[i][1]);
        }
        
        glBindTexture(GL_TEXTURE_2D, 0);
        
        stbi_image_free(imgdata);
        
        inited = true;
        
        std::cout << " - success" << std::endl;
        
    }
    catch(png::std_error& e)
    {
        std::cout << " - fail" << std::endl;
    }

    
    
    
    
}
Пример #5
0
void Texture::LoadFromFile()
{
	FILE* file = fopen(this->filename, "rb");
	imgData = stbi_load_from_file(file, &width, &height, &components, 4);
	fclose(file);
	glGenTextures(1, &glID);
	glBindTexture(GL_TEXTURE_2D, glID);
	gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, imgData);
	stbi_image_free(imgData);
	glBindTexture(GL_TEXTURE_2D, 0);
}
Пример #6
0
unsigned char *BBWin8Game::LoadImageData( String path,int *width,int *height,int *format ){

	FILE *f=OpenFile( path,"rb" );
	if( !f ) return 0;
	
	unsigned char *data=stbi_load_from_file( f,width,height,format,0 );
	fclose( f );
	
	
	gc_force_sweep=true;

	return data;
}
Пример #7
0
unsigned char* loadImage(const char* filename, int* imageWidth, int* imageHeight, int* comp) {
	int req_comp=0;

	FILE *file = fopen(filename, "rb");
	if (!file) {
		cerr << "TextureManager.cpp line 11: image file not found" << endl;
		return 0;
	}

	unsigned char* image = stbi_load_from_file(file, imageWidth, imageHeight,
			comp, req_comp);

	return image;
}
Пример #8
0
Texture::Texture(std::string fileName, int reqComponents)
{
   FILE * file = fopen(fileName.c_str(), "r");
   if(file)
   {
      buffer = stbi_load_from_file(file,&width,&height,&nComps,reqComponents);
      loaded = true;
      fclose(file);
   }
   else
   {
      throw ParseException(fileName, "Unrecognized File: " + fileName);
   }
}
Пример #9
0
    int SImgX_STB::LoadFromFile( LPCWSTR pszFileName )
    {
        if(m_pImg) delete m_pImg;
        m_pImg = NULL;

        FILE *f=_wfopen(pszFileName,L"rb");
        if(!f) return 0;
        int w=0,h=0;
        unsigned char *data = stbi_load_from_file(f,&w,&h,NULL,4);
        fclose(f);
        if(!data)
        {
            return 0;
        }
        _DoPromultiply(data,w,h);
        m_pImg = new SImgFrame_STB(data,w,h);
        return 1;
    }
Пример #10
0
//===Load the "iNum" numbers of texture file
void Texture::LoadTex(const char * texture_file_path)
{
	//===Load the texture file 
	GLint iChannel=0;
	FILE* pFile=fopen(texture_file_path,"rb");
	const unsigned char* pImageData=stbi_load_from_file(pFile,&m_iTexWidth,&m_iTexHeight,&iChannel,0);

	//====//check the texture picture 
	if (pImageData==NULL)
	{
		fprintf(stderr,"The %s texture picture is null.Please check.\n",texture_file_path);
		getchar();
		return ;
	}

	//Generate the texture id
	glGenTextures(1,&m_iTexture);
	glBindTexture(GL_TEXTURE_2D,m_iTexture);
	//====//
	glPixelStorei(GL_UNPACK_ALIGNMENT,1);

	//===//check the texture id
	if (glIsTexture(m_iTexture)==GL_FALSE)
	{
		fprintf(stderr,"Is not currently the name of texture.Or some error occurs.Please check.\n");
		getchar();
		return ;
	}

	//Generate the texture
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,m_iTexWidth,m_iTexHeight,0,GL_RGB,GL_UNSIGNED_BYTE,pImageData);
	//Release the texture picture buffer
	free((void *)pImageData);
	pImageData=NULL;
	//Set the texture parameters
	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_CLAMP_TO_EDGE);
 	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
}
Пример #11
0
sdl_surface load_image(std::string filename, bool alpha, bool convert)
{
    int width, height, depth;
    unsigned char * data = stbi_load_from_file(get_resource_file(filename.c_str()), &width, &height, &depth, 0);
    if(data == 0)
        throw std::logic_error("sdlw error: couldn't load file " + filename + " because: " + stbi_failure_reason());

    // Note the order of creation and destruction here. First create an SDL_Surface from
    // the stb image data. This only references the stb image data, it does not copy it.
    // This SDL_Surface has to be released before the stb image data can be free'd.
    SDL_Surface * raw = SDL_CreateRGBSurfaceFrom(data, width, height, depth*8, (width*depth),
                                                 0xFF, 0xFF00, 0xFF0000, alpha ? 0xFF000000 : 0);
    if(raw == 0)
        throw std::logic_error("sdlw error: could not create surface from file " + filename);

    sdl_surface res;

    if(convert)
    {
        // Convert the raw surface to an sdl_surface that has the display pixel format. We now
        // have a copy of the image data.
        res = sdl_surface(alpha ? SDL_DisplayFormatAlpha(raw) : SDL_DisplayFormat(raw));

        // Release the unconverted SDL_Surface.
        SDL_FreeSurface(raw);
    }
    else
    {
        // Just take ownership of the raw surface
        res = sdl_surface(raw);
    }

    // Free the stb image data.
    stbi_image_free(data);

    return res;

}
Пример #12
0
ReplayCreateStatus IMG_CreateReplayDevice(const char *logfile, IReplayDriver **driver)
{
	FILE *f = FileIO::fopen(logfile, "rb");

	if(!f)
		return eReplayCreate_FileIOFailed;
		
	FetchTexture texDetails;

	ResourceFormat rgba8_unorm;
	rgba8_unorm.compByteWidth = 1;
	rgba8_unorm.compCount = 4;
	rgba8_unorm.compType = eCompType_UNorm;
	rgba8_unorm.special = false;

	ResourceFormat rgba32_float = rgba8_unorm;
	rgba32_float.compByteWidth = 4;
	rgba32_float.compType = eCompType_Float;

	texDetails.creationFlags = eTextureCreate_SwapBuffer|eTextureCreate_RTV;
	texDetails.cubemap = false;
	texDetails.customName = true;
	texDetails.name = logfile;
	texDetails.ID = ResourceId();
	texDetails.byteSize = 0;
	texDetails.msQual = 0;
	texDetails.msSamp = 1;

	// reasonable defaults for everything but dds
	texDetails.numSubresources = 1;
	texDetails.dimension = 2;
	texDetails.arraysize = 1;
	texDetails.depth = 1;
	texDetails.mips = 1;

	byte *data = NULL;
	size_t datasize = 0;

	bool dds = false;

	if(is_exr_file(f))
	{
		texDetails.format = rgba32_float;
		
		FileIO::fseek64(f, 0, SEEK_SET);

		const char *err = NULL;

		int ret = LoadEXRFP((float **)&data, (int *)&texDetails.width, (int *)&texDetails.height, f, &err);
		datasize = texDetails.width*texDetails.height*4*sizeof(float);

		// could be an unsupported form of EXR, like deep image or other
		if(ret != 0)
		{
			if(data) free(data);
			RDCERR("EXR file detected, but couldn't load with LoadEXR %d: '%s'", ret, err);
			return eReplayCreate_APIUnsupported;
		}
	}
	else if(stbi_is_hdr_from_file(f))
	{
		texDetails.format = rgba32_float;

		FileIO::fseek64(f, 0, SEEK_SET);

		int ignore = 0;
		data = (byte *)stbi_loadf_from_file(f, (int *)&texDetails.width, (int *)&texDetails.height, &ignore, 4);
		datasize = texDetails.width*texDetails.height*4*sizeof(float);
	}
	else if(is_dds_file(f))
	{
		dds = true;
	}
	else
	{
		int ignore = 0;
		int ret = stbi_info_from_file(f, (int *)&texDetails.width, (int *)&texDetails.height, &ignore);

		// just in case (we shouldn't have come in here if this weren't true), make sure
		// the format is supported
		if(ret == 0 ||
			 texDetails.width == 0 || texDetails.width == ~0U ||
			 texDetails.height == 0 || texDetails.height == ~0U)
		{
			return eReplayCreate_APIUnsupported;
		}

		texDetails.format = rgba8_unorm;

		data = stbi_load_from_file(f, (int *)&texDetails.width, (int *)&texDetails.height, &ignore, 4);
		datasize = texDetails.width*texDetails.height*4*sizeof(byte);
	}
	
	// if we don't have data at this point (and we're not a dds file) then the
	// file was corrupted and we failed to load it
	if(!dds && data == NULL)
	{
		return eReplayCreate_FileCorrupted;
	}
	
	IReplayDriver *proxy = NULL;
	auto status = RenderDoc::Inst().CreateReplayDriver(RDC_Unknown, NULL, &proxy);
	
	if(status != eReplayCreate_Success || !proxy)
	{
		if(proxy) proxy->Shutdown();
		return status;
	}

	ResourceId id;

	if(!dds)
	{
		id = proxy->CreateProxyTexture(texDetails);

		proxy->SetProxyTextureData(id, 0, 0, data, datasize);
		free(data);
	}
	else
	{
		FileIO::fseek64(f, 0, SEEK_SET);
		dds_data read_data = load_dds_from_file(f);
		
		if(read_data.subdata == NULL)
		{
			proxy->Shutdown();
			return eReplayCreate_FileCorrupted;
		}

		texDetails.cubemap = read_data.cubemap;
		texDetails.arraysize = read_data.slices;
		texDetails.width = read_data.width;
		texDetails.height = read_data.height;
		texDetails.depth = read_data.depth;
		texDetails.mips = read_data.mips;
		texDetails.numSubresources = texDetails.arraysize*texDetails.mips;
		texDetails.format = read_data.format;
		                         texDetails.dimension = 1;
		if(texDetails.width > 1) texDetails.dimension = 2;
		if(texDetails.depth > 1) texDetails.dimension = 3;

		id = proxy->CreateProxyTexture(texDetails);

		for(uint32_t i=0; i < texDetails.numSubresources; i++)
		{
			proxy->SetProxyTextureData(id, i/texDetails.mips, i%texDetails.mips, read_data.subdata[i], (size_t)read_data.subsizes[i]);

			delete[] read_data.subdata[i];
		}

		delete[] read_data.subdata;
		delete[] read_data.subsizes;
	}

	*driver = new ImageViewer(proxy, logfile, id);

	FileIO::fclose(f);

	return eReplayCreate_Success;
}
Пример #13
0
int main( int argc, char** argv )
{

    std::cout << "Starting..\n";
    std::vector<std::string> file_names;
    parse_args(argc, argv, file_names);
    file_names.push_back(std::string("b0e0.hgt"));
    InitGraphics();

    glfwSetWindowTitle( "p7" );

    // Ensure we can capture the escape key being pressed below
    glfwEnable( GLFW_STICKY_KEYS );

    // Dark blue background
    glClearColor(0.7f, 0.7f, 0.7f, 0.0f);

    // Enable depth test
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    // Accept fragment if it closer to the camera than the former one
    glDepthFunc(GL_LESS);
//  glFrontFace(GL_CCW);

    // Create and compile our GLSL program from the shaders
    GLuint programIDs[2] = { LoadShaders( "tvs.vertexshader", "cfs.fragmentshader" ), LoadShaders( "tvs2.vertexshader", "cfs.fragmentshader" )};
    std::cout << "Linked shaders..\n";
    // Get a handle for our "MVP" uniform
    GLuint MatrixIDs[2] = {glGetUniformLocation(programIDs[0], "MVP"), glGetUniformLocation(programIDs[1], "MVP")};
    GLuint EdgexIDs[2] = {glGetUniformLocation(programIDs[0], "Edgex"), glGetUniformLocation(programIDs[1], "Edgex")};
    GLuint EdgeyIDs[2] = {glGetUniformLocation(programIDs[0], "Edgey"), glGetUniformLocation(programIDs[1], "Edgey")};
    GLuint HeightIDs[2] = {glGetUniformLocation(programIDs[0], "height"), glGetUniformLocation(programIDs[1], "height")};
    GLuint TextureIDs[2] = {glGetUniformLocation(programIDs[0], "tex2d"), glGetUniformLocation(programIDs[1], "tex2d")};
    GLuint TimeIDs[2] = {glGetUniformLocation(programIDs[0], "time"), glGetUniformLocation(programIDs[1], "time")};
    GLuint AlphaIDs[2] = {glGetUniformLocation(programIDs[0], "alpha"), glGetUniformLocation(programIDs[1], "alpha")};
    std::cout << "Got uniforms..\n";
    std::cout << glGetString(GL_VERSION) << std::endl;

    std::cout << "Loadin textures...\n";

    char texName[] = "texture3.jpg";
    std::cout << texName << std::endl;
    int t1x,t1y,t1comp;
    FILE* t1f = fopen(texName, "rb");
    unsigned char* tex1data = stbi_load_from_file(t1f, &t1x, &t1y, &t1comp,0);
    unsigned int tex_2d;
    glGenTextures(1, &tex_2d);
    glBindTexture(GL_TEXTURE_2D, tex_2d);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, t1x, t1y, 0, GL_RGB, GL_UNSIGNED_BYTE, tex1data);
    /*
      char texNameCl[] = "textureClouds3.png";
      std::cout << texNameCl << std::endl;
      int t2x,t2y,t2comp;
      FILE* t2f = fopen(texNameCl, "rb");
      unsigned char* tex2data = stbi_load_from_file  (t2f, &t2x, &t2y, &t2comp,0);
      unsigned int tex_cl;
      glGenTextures(1, &tex_cl);
      glBindTexture(GL_TEXTURE_2D, tex_cl);
      //-->
      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, t2x, t2y, 0, GL_RGB, GL_UNSIGNED_BYTE, tex2data);
    */
    std::cout << "Done!\n";

    const int side(1201);
    const int vBOsize(file_names.size());


    //Vertices:
    short piece_map[360][181];
    for(int i=0; i<360; i++)
        for(int y=0; y<=180; y++)
            piece_map[i][y] = -1;
    unsigned int numberOfVertices=side*side;
    GLuint vaoObjects[vBOsize+1], vertexBufferObject, vBOs[vBOsize+1];
    std::vector<std::pair<int, int> > edges(vBOsize+1);
    // -->
    std::cout << "Generating arrays...\n";
    glGenVertexArrays(vBOsize, vaoObjects);
    std::cout << "Done\n";
    glGenBuffers(vBOsize, vBOs);
    int height;
    // <---
    for(short i=0; i< vBOsize; i++)
    {
        std::vector< int > vertexPositionsVec(3*numberOfVertices);
        int* vertexPositions = &vertexPositionsVec[0];
        loadVertices(file_names[i], vertexPositionsVec, true, side, edges[i], height);
        glBindVertexArray(vaoObjects[i]);
        glBindBuffer(GL_ARRAY_BUFFER, vBOs[i]);
        glVertexAttribPointer(
            0,                  // attribute. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_INT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );
        glBufferData(GL_ARRAY_BUFFER, sizeof(int)*3*numberOfVertices, vertexPositions, GL_STATIC_DRAW);
        if(i<vBOsize-1)
        {
            piece_map[edges[i].second+180][edges[i].first+90]=i;
            std::cout << edges[i].second+180 << " " << edges[i].first+90 << std::endl;
        }
    }

    //Indices::
    GLuint indexBufferObject, iBOs[maxLoD], numberOfIndices;
    std::vector<GLuint> nOIs(maxLoD);
    glGenBuffers(maxLoD, iBOs);
    for(unsigned int density=1, i=0; i<maxLoD; i++, density*=2)
    {
        std::cout << "Entering for with i: " << i << "\n";
        nOIs[i]=(side-1)/density;
        if((side-1)%density!=0)
            nOIs[i]+=1;
        nOIs[i]=6*(nOIs[i]*(nOIs[i]));
        std::cout << "Allocating memory...\n";
        GLuint* indices = new GLuint [nOIs[i]];
        std::cout << "Done.\n";
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iBOs[i]);
        std::cout << "Density: " << density << " Number of indices: " << nOIs[i] << std::endl;
        genIndices(indices, side, density);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*nOIs[i], indices, GL_STATIC_DRAW);
        std::cout << "Leaving for with i: " << i << "\n";
    }

    // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
    glm::mat4 Projection =
        // glm::mat4(1.0f);
        glm::perspective(45.0f, 4.0f / 3.0f, 100.f, 30000.0f);
    // Camera matrix
//  int xVw = edges[0].first*side, yVw = edges[0].second*side;
    int xVw = 6000, yVw = -6000;
    height = 3000;
    glm::mat4 View       = glm::lookAt(
                               glm::vec3(xVw,yVw,2*height), // Camera is at (4,3,-3), in World Space
                               glm::vec3(xVw,yVw,0), // and looks at the origin
                               glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                           );
    // Model matrix : an identity matrix (model will be at the origin)
    glm::mat4 Model      = glm::mat4(1.0f);
    // Our ModelViewProjection : multiplication of our 3 matrices

    glm::mat4 MVP        = Projection * View * Model; // Remember, matrix multiplication is the other way around

    std::cout << "Init done.\n";

    glfwSetKeyCallback(Key_Callback);

    double last_time = glfwGetTime(), last_reset=last_time;
    int FPScounter=0;

    x = edges[0].second*12010;
    startx=x;
    y = edges[0].first*12010;
    starty=y;
    std::cout << edges[0].first << " " << edges[0].second << std::endl;
    do {
        int ex = x/12010+180;
        int ey = y/12010+90;
        //time statistics:
        FPScounter++;
        double cur_time = glfwGetTime();
        if(cur_time-last_reset>=2)
        {
            double FPS = (float)FPScounter/(cur_time-last_reset);
            std::cout << "FPS: " << FPS << " lod: " << iBOindex << std::endl;
            std::cout << ex << " " << ey << " " << alpha <<  std::endl;
            if(autolod && abs(FPS-optfps)>4)
            {
                if(FPS<optfps && iBOindex<maxLoD)
                    iBOindex++;
                if(FPS>4*optfps && iBOindex > 0)
                    iBOindex--;
            }
            FPScounter=0;
            last_reset=cur_time;
        }
        last_time=cur_time;

        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use our shader
        glUseProgram(programIDs[ball]);
        glm::mat4 Vw;
        // Send our transformation to the currently bound shader,
        // in the "MVP" uniform
        Vw=MVP * glm::translate( mat4(1.0),vec3((-x + 6000)*ball,(-y - 6000)*ball,(z - 12000)*ball))
           * glm::rotate(mat4(1.0), oz, glm::vec3(0,1,0))
           * glm::rotate(mat4(1.0), ox, glm::vec3(1,0,0))
           * glm::rotate(mat4(1.0), oy, glm::vec3(0,0,1))
           * glm::translate( mat4(1.0), vec3(-x*(1-ball), -y*(1-ball), z*(1-ball)));
        glUniformMatrix4fv(MatrixIDs[ball], 1, GL_FALSE, &Vw[0][0]);

        glUniform1i(HeightIDs[ball], 0);

        glUniform1f(TimeIDs[ball], glfwGetTime());
        glUniform1f(AlphaIDs[ball], (float)alpha*0.1);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, tex_2d);
        glUniform1i(TextureIDs[ball], /*GL_TEXTURE0+*/0);

        indexBufferObject=iBOs[iBOindex];
        numberOfIndices=nOIs[iBOindex];

//   std::cout << ex << " " << ey << std::endl;
        if(ball==0)
        {
            glCullFace(GL_FRONT);
            for(int i = max(ex-3,0); i<= min(ex+3,360) ; i++)
                for(int j=max(ey-3,0); j<= min(ey+3,180); j++)
                {
                    glUniform1i(EdgexIDs[ball], (i-180));
                    glUniform1i(EdgeyIDs[ball], (j-90));
                    int point;
                    if(piece_map[i][j]==-1)
                    {
                        point=vBOsize-1;
                        draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                    }
                    else
                    {
                        point = piece_map[i][j];
                        draw(vaoObjects[point], vBOs[point], indexBufferObject, numberOfIndices);
                    }
                    //         std::cout << "Drawing " << file_names[point] << "with mods " << i-180 << " " << j-90 << std::endl
                    //           << i << " "  << ex << " " << j << " " << ey << std::endl;

                }
        }
        else
        {
            glCullFace(GL_FRONT);
            for(int i=/*edges[0].second+180+*/0; i</*edges[0].second+18*/360; i++)
                for(int j=/*edges[0].first+90+*/0; j<=/*edges[0].first+90*/180; j++)
                {

                    glUniform1i(EdgexIDs[ball], (i-180));
                    glUniform1i(EdgeyIDs[ball], (j-90));

                    int point;
                    if(piece_map[i][j]==-1)
                    {
                        point=vBOsize-1;
                        draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                    }
                    else
                    {
                        point = piece_map[i][j];
                        draw(vaoObjects[point], vBOs[point], indexBufferObject, numberOfIndices);
                    }
                }
        }


        //CLOUDS
        /*
            Vw=MVP * glm::translate( mat4(1.0),vec3((-x + 6000)*ball,(-y - 6000)*ball,(z - 12000)*ball))
                             * glm::rotate(mat4(1.0), oz+(float)glfwGetTime(), glm::vec3(0,1,0))
                             * glm::rotate(mat4(1.0), ox, glm::vec3(1,0,0))
                             * glm::rotate(mat4(1.0), oy, glm::vec3(0,0,1))
                             * glm::translate( mat4(1.0), vec3(-x*(1-ball), -y*(1-ball), z*(1-ball)));
            glUniformMatrix4fv(MatrixIDs[ball], 1, GL_FALSE, &Vw[0][0]);

            glUniform1i(HeightIDs[ball], 100);

            glUniform1f(TimeIDs[ball], glfwGetTime());
            glUniform1f(AlphaIDs[ball], 0.25);

            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, tex_cl);
            glUniform1i(TextureIDs[ball], 0);

            indexBufferObject=iBOs[iBOindex];
            numberOfIndices=nOIs[iBOindex];

         //   std::cout << ex << " " << ey << std::endl;
            if(ball==0)
            {
                glCullFace(GL_FRONT);
              for(int i = max(ex-3,0); i<= min(ex+3,360) ;i++)
                for(int j=max(ey-3,0); j<= min(ey+3,180); j++)
                {
                  glUniform1i(EdgexIDs[ball], (i-180));
                  glUniform1i(EdgeyIDs[ball], (j-90));
                  int point;
                  {
                    point=vBOsize-1;
                    draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                  }

                }
            }
            else
            {
                glCullFace(GL_FRONT);
              for(int i=0; i<360;i++)
                for(int j=0; j<=180;j++)
                {

                  glUniform1i(EdgexIDs[ball], (i-180));
                  glUniform1i(EdgeyIDs[ball], (j-90));

                  int point;
                  {
                    point=vBOsize-1;
                    draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                  }
                }
            }*/
        // Swap buffers
        glfwSwapBuffers();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS &&
            glfwGetWindowParam( GLFW_OPENED ) );

    // Cleanup VBO and shader
    glDeleteProgram(programIDs[0]);
    glDeleteProgram(programIDs[1]);
//  CleanVBOs(vaoObjects, vBOs, vBOsize+1, iBOs, tex_2d);

    std::cout << "Cleaning done, terminating..\n";
    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
Пример #14
0
Файл: cam.c Проект: saitoha/cam
static int deal(FILE *fp, char *filename, int pipemode)
{
  color *image;
  void (*outputcolor)();
  int width, height, comp, i, j, istep, jstep, ch, scale, scalew, scaleh,
      offset, imagewidth, imageheight,
      margintopbottom, marginleftright, marginleft, margintop,
      paddingtopbottom, paddingleftright, paddingleft, paddingright,
      paddingtop, paddingbottom,
      ipaddingleftright, ipaddingleft, ipaddingright;

  image = stbi_load_from_file(fp, &width, &height, &comp, 0);

  /* error handling */
  if (image == NULL) {
    if ((!qflag) && (stbi_failure_reason() != NULL))
      warnx("%s: %s", filename, stbi_failure_reason());
    goto ERR_DEAL;
  }
  if (width <= 0 || height <= 0) {
    if (!qflag)
      warnx("%s %s (width: %d, height: %d)", filename,
          "is an invalid image", width, height);
    goto ERR_DEAL;
  }
  /* ok, it is surely a valid image */

  /* get terminal size before processing each image */
  terminalsize();

  /* set scale parameters */
  scale = 1;
  if (Sflag) {
    if (cflag) outputcolor = outputcolor_3;
    else       outputcolor = outputcolor_1;
    scale = (int)Sval; /* TODO */
    istep = 2 * (jstep = scale);
    imageheight = (int)ceil((double)height / (double)istep);
    imagewidth = (int)ceil((double)width / (double)jstep);
  } else if (2 * width <= outputwidth && height <= outputheight) {
    if (cflag) outputcolor = outputcolor_4;
    else       outputcolor = outputcolor_2;
    istep = jstep = 1;
    imagewidth = width * 2;
    imageheight = height;
  } else {
    if (cflag) outputcolor = outputcolor_3;
    else       outputcolor = outputcolor_1;
    scalew = (int)ceil((double)width / (double)outputwidth);
    scaleh = (int)ceil((double)height / 2.0 / (double)outputheight);
    if (Hval == 0 && hval == 0 && (wval > 0 || Wval > 0))      scale = scalew;
    else if ((hval > 0 || Hval > 0) && wval == 0 && Wval == 0) scale = scaleh;
    else                             scale = ((scalew) > (scaleh) ? (scalew) : (scaleh));
    istep = 2 * (jstep = scale);
    imageheight = (int)ceil((double)height / (double)istep);
    imagewidth = (int)ceil((double)width / (double)jstep);
  }
  if (istep * jstep >= INT_MAX / 256 || width * height >= INT_MAX / 3) {
    if (!qflag)
      warnx("%s %s (width: %d, height: %d)",
          filename, "is too large", width, height);
    goto ERR_DEAL;
  }

  /* setting parameters */
  margintopbottom = terminalheight - outputheight - iflag;
  marginleftright = terminalwidth - outputwidth;
  paddingtopbottom = outputheight - imageheight;
  paddingleftright = outputwidth - imagewidth;

  if (Rflag && !Lflag) {
    marginleft = marginleftright;
  } else if (Lflag && !Rflag) {
    marginleft = 0;
  } else if ((Lflag && Rflag) || Cflag || Tflag || Bflag) {
    marginleft = marginleftright / 2;
  } else {
    marginleft = 0;
  }

  if (PRflag && !PLflag) {
    paddingleft = paddingleftright;
  } else if (PLflag && !PRflag) {
    paddingleft = 0;
  } else if ((PLflag && PRflag) || PCflag || PTflag || PBflag) {
    paddingleft = paddingleftright / 2;
  } else if (Rflag && !Lflag) {
    paddingleft = paddingleftright;
  } else if (Lflag && !Rflag) {
    paddingleft = 0;
  } else if ((Lflag && Rflag) || Cflag || Tflag || Bflag) {
    paddingleft = paddingleftright / 2;
  } else {
    paddingleft = 0;
  }

  if (Bflag) {
    margintop = margintopbottom;
  } else if (Tflag) {
    margintop = 0;
  } else if (Cflag) {
    margintop = margintopbottom / 2;
  } else {
    margintop = 0;
  }

  if (PBflag) {
    paddingtop = paddingtopbottom;
  } else if (PTflag) {
    paddingtop = 0;
  } else if (PCflag) {
    paddingtop = paddingtopbottom / 2;
  } else if (Bflag) {
    paddingtop = paddingtopbottom;
  } else if (Tflag) {
    paddingtop = 0;
  } else if (Cflag) {
    paddingtop = paddingtopbottom / 2;
  } else {
    paddingtop = 0;
  }

  paddingright = paddingleftright - paddingleft;
  paddingbottom = paddingtopbottom - paddingtop;

  /* start up */
  setdefaultcolor();
  if (uflag) {
    cursorhide();
    cursorsave();
  }

  /* main process */
  if (Eflag && filecount == 0) erasescreen();
  if (Cflag || Tflag || Bflag) {
    if (!eflag) {
      if (margintop >= 0) cursormove(margintop + 1, 1);
      for (i = 0; i < paddingtop; i++) {
        if (marginleft > 0) cursorforward(marginleft);
        replicatespace(outputwidth);
        cursordown_cursorhorizontalabsolute();
      }
    }
    if (margintop + paddingtop >= 0) cursormove(margintop + paddingtop + 1, 1);
  }
  if (iflag) {
    ipaddingleftright = outputwidth - strlen(filename);
    if (PRflag && !PLflag) {
      ipaddingleft = ipaddingleftright;
    } else if (PLflag && !PRflag) {
      ipaddingleft = 0;
    } else if ((PLflag && PRflag) || PCflag || PTflag || PBflag) {
      ipaddingleft = ipaddingleftright / 2;
    } else if (Rflag && !Lflag) {
      ipaddingleft = ipaddingleftright;
    } else if (Lflag && !Rflag) {
      ipaddingleft = 0;
    } else if ((Lflag && Rflag) || Cflag || Tflag || Bflag) {
      ipaddingleft = ipaddingleftright / 2;
    } else {
      ipaddingleft = 0;
    }
    ipaddingright = ipaddingleftright - ipaddingleft;
    if (Cflag || Lflag || Rflag || Tflag || Bflag ||
        PCflag || PLflag || PRflag || PTflag || PBflag) {
      if (marginleft > 0) cursorforward(marginleft);
      if (ipaddingleft > 0) {
        if (eflag) {
          cursorforward(ipaddingleft);
        } else {
          replicatespace(ipaddingleft);
        }
      } else if (ipaddingleftright < 0) {
        filename[outputwidth] = '\0';
      }
    }
    printf("%s", filename);
    if (Cflag || Tflag || Bflag || PCflag || PTflag || PBflag) {
      if (ipaddingright > 0) {
        if (!eflag) {
          replicatespace(ipaddingright);
        }
      }
      if (Cflag || Tflag || Bflag) {
        cursordown_cursorhorizontalabsolute();
      } else {
        newline();
      }
    } else {
      newline();
    }
  }
  for (i = 0; i < height; i += istep) {
    if (Cflag || Lflag || Rflag || Tflag || Bflag ||
        PCflag || PLflag || PRflag || PTflag || PBflag) {
      if (marginleft > 0) cursorforward(marginleft);
      if (paddingleft > 0) {
        if (eflag) {
          cursorforward(paddingleft);
        } else {
          replicatespace(paddingleft);
        }
      }
    }
    for (j = 0; j < width; j += jstep) {
      offset = (i * width + j) * comp;
      outputcolor(image, height, width, offset, i, j,
          (i + istep > height ? height - i : istep),
          (j + jstep > width ? width - j : jstep), comp);
    }
    setdefaultcolor();
    if (Cflag || Tflag || Bflag || PCflag || PTflag || PBflag) {
      if (paddingright > 0) {
        if (!eflag) {
          replicatespace(paddingright);
        }
      }
      if (Cflag || Tflag || Bflag) {
        cursordown_cursorhorizontalabsolute();
      } else {
        newline();
      }
    } else {
      newline();
    }
  }
  if (Cflag || Tflag) {
    if (!eflag) {
      for (i = 0; i < paddingbottom; i++) {
        if (marginleft > 0) cursorforward(marginleft);
        if (outputwidth > 0) replicatespace(outputwidth);
        cursordown_cursorhorizontalabsolute();
      }
    }
  }

  /* clean up */
  setdefaultcolor();
  if (uflag) {
    cursorunsave();
    cursorshow();
  }
  fflush(stdout);
  stbi_image_free(image);
  ++filecount;

  /* debug mode */
  if (dflag) {
    cursorsave();
    cursormove(1, 1);
    printf(PACKAGE);
    if (iflag) printf(" -i");
    if (qflag) printf(" -q");
    if (sflag) printf(" -s %lf", sval);
    if (rflag) printf(" -r %ld", rval);
    if (Lflag) printf(" -L");
    if (Rflag) printf(" -R");
    if (Cflag) printf(" -C");
    if (Tflag) printf(" -T");
    if (Bflag) printf(" -B");
    if (Eflag) printf(" -E");
    if (hflag) printf(" -h %ld", hval);
    if (Hflag) printf(" -H %ld", Hval);
    if (wflag) printf(" -w %ld", wval);
    if (Wflag) printf(" -W %ld", Wval);
    printf(" %s\n", filename);
    printf("terminalwidth: %d\n", terminalwidth);
    printf("terminalheight: %d\n", terminalheight);
    printf("outputwidth: %d\n", outputwidth);
    printf("outputheight: %d\n", outputheight);
    printf("imagewidth: %d\n", imagewidth);
    printf("imageheight: %d\n", imageheight);
    printf("margintop: %d\n", margintop);
    printf("marginleft: %d\n", marginleft);
    printf("paddingtop: %d\n", paddingtop);
    printf("paddingleft: %d\n", paddingleft);
    printf("paddingbottom: %d\n", paddingbottom);
    printf("paddingright: %d\n", paddingright);
    fflush(stdout);
    cursorunsave();
  }

  /* check next file if pipe or fifo */
  if (pipemode) {
    ch = getc(fp);
    if (ch != EOF) {
      if (ch != '\0' && ch != '\n') {
        ungetc(ch, fp);
      } else if ((ch = getc(fp)) != '\0' && ch != '\n') {
        ungetc(ch, fp);
      } else if ((ch = getc(fp)) != '\0' && ch != '\n') {
        ungetc(ch, fp);
      }
      if (ch != EOF) {
        if (sflag && sval > 0) {
          usleep(sval * 1e6);
        }
        deal(fp, filename, pipemode);
      }
    }
  }

  return 0;

ERR_DEAL:
  return 1;
}
Пример #15
0
Файл: image.cpp Проект: beru/siv
void Image::load(FILE* f)
{
	data = stbi_load_from_file(f, &width, &height, &ncomponents, 0);
}
Пример #16
0
ReplayCreateStatus IMG_CreateReplayDevice(const char *logfile, IReplayDriver **driver)
{
  FILE *f = FileIO::fopen(logfile, "rb");

  if(!f)
    return eReplayCreate_FileIOFailed;

  // make sure the file is a type we recognise before going further
  if(is_exr_file(f))
  {
    const char *err = NULL;

    FileIO::fseek64(f, 0, SEEK_END);
    uint64_t size = FileIO::ftell64(f);
    FileIO::fseek64(f, 0, SEEK_SET);

    std::vector<byte> buffer;
    buffer.resize((size_t)size);

    FileIO::fread(&buffer[0], 1, buffer.size(), f);

    EXRImage exrImage;
    InitEXRImage(&exrImage);

    int ret = ParseMultiChannelEXRHeaderFromMemory(&exrImage, &buffer[0], &err);

    FreeEXRImage(&exrImage);

    // could be an unsupported form of EXR, like deep image or other
    if(ret != 0)
    {
      FileIO::fclose(f);

      RDCERR(
          "EXR file detected, but couldn't load with ParseMultiChannelEXRHeaderFromMemory %d: '%s'",
          ret, err);
      return eReplayCreate_APIUnsupported;
    }
  }
  else if(stbi_is_hdr_from_file(f))
  {
    FileIO::fseek64(f, 0, SEEK_SET);

    int ignore = 0;
    float *data = stbi_loadf_from_file(f, &ignore, &ignore, &ignore, 4);

    if(!data)
    {
      FileIO::fclose(f);
      RDCERR("HDR file recognised, but couldn't load with stbi_loadf_from_file");
      return eReplayCreate_FileCorrupted;
    }

    free(data);
  }
  else if(is_dds_file(f))
  {
    FileIO::fseek64(f, 0, SEEK_SET);
    dds_data read_data = load_dds_from_file(f);

    if(read_data.subdata == NULL)
    {
      FileIO::fclose(f);
      RDCERR("DDS file recognised, but couldn't load");
      return eReplayCreate_FileCorrupted;
    }

    for(int i = 0; i < read_data.slices * read_data.mips; i++)
      delete[] read_data.subdata[i];

    delete[] read_data.subdata;
    delete[] read_data.subsizes;
  }
  else
  {
    int width = 0, height = 0;
    int ignore = 0;
    int ret = stbi_info_from_file(f, &width, &height, &ignore);

    // just in case (we shouldn't have come in here if this weren't true), make sure
    // the format is supported
    if(ret == 0 || width == 0 || width == ~0U || height == 0 || height == ~0U)
    {
      FileIO::fclose(f);
      return eReplayCreate_APIUnsupported;
    }

    byte *data = stbi_load_from_file(f, &ignore, &ignore, &ignore, 4);

    if(!data)
    {
      FileIO::fclose(f);
      RDCERR("File recognised, but couldn't load with stbi_load_from_file");
      return eReplayCreate_FileCorrupted;
    }

    free(data);
  }

  FileIO::fclose(f);

  IReplayDriver *proxy = NULL;
  auto status = RenderDoc::Inst().CreateReplayDriver(RDC_Unknown, NULL, &proxy);

  if(status != eReplayCreate_Success || !proxy)
  {
    if(proxy)
      proxy->Shutdown();
    return status;
  }

  *driver = new ImageViewer(proxy, logfile);

  return eReplayCreate_Success;
}
Пример #17
0
void 
ASCGLES2Texture::Load()
{
	#ifdef __OBJC__
		stbi_convert_iphone_png_to_rgb(1);
	#endif

	//Open the texture file
	FILE* pFile = NULL; 
#ifdef ASC_IOS
	pFile = fopen(m_strTextureName.c_str(), "rb");
#else
	fopen_s(&pFile, m_strTextureName.c_str(), "rb");
#endif
	if(NULL == pFile)
	{
		assert_nowex("Guts, failed to load texture file: ", m_strTextureName);
		m_bLoaded = false;
		return;
	}
	
	UINT32 uForceChannels = 0;
	SINT32 iChannels;
	SINT32 iWidth;
	SINT32 iHeight;

	//Load in the texture data
	UINT8* pImg = stbi_load_from_file(pFile, &iWidth, &iHeight, &iChannels, uForceChannels);

	//Close the texture file
	fclose( pFile );

	if(NULL == pImg)
	{
		assert_nowex("Guts, failed to load texture because: ", stbi_failure_reason());
		m_bLoaded = false;
		return;
	}

	if( ( uForceChannels >= 1 ) && ( uForceChannels <= 4 ) )
	{
		iChannels = SC_SINT(uForceChannels);
	}
	
	m_uiWidth = iWidth;
	m_uiHeight = iHeight;

	//Generate the texture
	glGenTextures(1, &m_uTextureID);

	//Bind the texture
	glBindTexture( GL_TEXTURE_2D, m_uTextureID );

	UINT32 uTextureFormat = ( iChannels == 3 ) ? GL_RGB : GL_RGBA;

	if(uTextureFormat != GL_RGBA)
	{
		//assert_now("Guts, Texture is not RGBA, dont realy want this");
	}

	glTexImage2D( GL_TEXTURE_2D, 0, uTextureFormat, m_uiWidth, m_uiHeight, 0, uTextureFormat, GL_UNSIGNED_BYTE, pImg);
	
	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_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
	
	glBindTexture( GL_TEXTURE_2D, 0 );

	ASCMemoryManagement::ReleaseMemory(pImg, false);
	m_bLoaded = true;
}
Пример #18
0


	/* --- private --- */
	void Texture2D::loadTextureData(const char* textureFile)
	{
		FILE* file = NULL;
		file = fopen( textureFile, "rb");

		if(file == NULL)
		{
			BREAKPOINT(Texture could not be loaded!);
			return;
		}

		int x; 
		int y; 
		int numComponents;

		m_textureData = stbi_load_from_file( file, &x, &y, &numComponents, 0);

		fclose(file);

		m_width = x;
		m_height = y;
		m_numComponents = numComponents;
		m_componentSizeInBytes = 1;
		m_isLocalDataAvailable = true;
	}

}
Пример #19
0
void ImageViewer::RefreshFile()
{
  FILE *f = NULL;

  for(int attempt = 0; attempt < 10 && f == NULL; attempt++)
  {
    f = FileIO::fopen(m_Filename.c_str(), "rb");
    if(f)
      break;
    Threading::Sleep(40);
  }

  if(!f)
  {
    RDCERR("Couldn't open %s! Exclusive lock elsewhere?", m_Filename.c_str());
    return;
  }

  FetchTexture texDetails;

  ResourceFormat rgba8_unorm;
  rgba8_unorm.compByteWidth = 1;
  rgba8_unorm.compCount = 4;
  rgba8_unorm.compType = eCompType_UNorm;
  rgba8_unorm.special = false;

  ResourceFormat rgba32_float = rgba8_unorm;
  rgba32_float.compByteWidth = 4;
  rgba32_float.compType = eCompType_Float;

  texDetails.creationFlags = eTextureCreate_SwapBuffer | eTextureCreate_RTV;
  texDetails.cubemap = false;
  texDetails.customName = true;
  texDetails.name = m_Filename;
  texDetails.ID = m_TextureID;
  texDetails.byteSize = 0;
  texDetails.msQual = 0;
  texDetails.msSamp = 1;
  texDetails.format = rgba8_unorm;

  // reasonable defaults
  texDetails.numSubresources = 1;
  texDetails.dimension = 2;
  texDetails.arraysize = 1;
  texDetails.width = 1;
  texDetails.height = 1;
  texDetails.depth = 1;
  texDetails.mips = 1;

  byte *data = NULL;
  size_t datasize = 0;

  bool dds = false;

  if(is_exr_file(f))
  {
    texDetails.format = rgba32_float;

    FileIO::fseek64(f, 0, SEEK_END);
    uint64_t size = FileIO::ftell64(f);
    FileIO::fseek64(f, 0, SEEK_SET);

    std::vector<byte> buffer;
    buffer.resize((size_t)size);

    FileIO::fread(&buffer[0], 1, buffer.size(), f);

    FileIO::fclose(f);

    EXRImage exrImage;
    InitEXRImage(&exrImage);

    const char *err = NULL;

    int ret = ParseMultiChannelEXRHeaderFromMemory(&exrImage, &buffer[0], &err);

    if(ret != 0)
    {
      RDCERR(
          "EXR file detected, but couldn't load with ParseMultiChannelEXRHeaderFromMemory %d: '%s'",
          ret, err);
      return;
    }

    texDetails.width = exrImage.width;
    texDetails.height = exrImage.height;

    datasize = texDetails.width * texDetails.height * 4 * sizeof(float);
    data = (byte *)malloc(datasize);

    for(int i = 0; i < exrImage.num_channels; i++)
      exrImage.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;

    ret = LoadMultiChannelEXRFromMemory(&exrImage, &buffer[0], &err);

    int channels[4] = {-1, -1, -1, -1};
    for(int i = 0; i < exrImage.num_channels; i++)
    {
      switch(exrImage.channel_names[i][0])
      {
        case 'R': channels[0] = i; break;
        case 'G': channels[1] = i; break;
        case 'B': channels[2] = i; break;
        case 'A': channels[3] = i; break;
      }
    }

    float *rgba = (float *)data;
    float **src = (float **)exrImage.images;

    for(uint32_t i = 0; i < texDetails.width * texDetails.height; i++)
    {
      for(int c = 0; c < 4; c++)
      {
        if(channels[c] >= 0)
          rgba[i * 4 + c] = src[channels[c]][i];
        else if(c < 3)    // RGB channels default to 0
          rgba[i * 4 + c] = 0.0f;
        else    // alpha defaults to 1
          rgba[i * 4 + c] = 1.0f;
      }
    }

    FreeEXRImage(&exrImage);

    // shouldn't get here but let's be safe
    if(ret != 0)
    {
      free(data);
      RDCERR("EXR file detected, but couldn't load with LoadEXRFromMemory %d: '%s'", ret, err);
      return;
    }
  }
  else if(stbi_is_hdr_from_file(f))
  {
    texDetails.format = rgba32_float;

    FileIO::fseek64(f, 0, SEEK_SET);

    int ignore = 0;
    data = (byte *)stbi_loadf_from_file(f, (int *)&texDetails.width, (int *)&texDetails.height,
                                        &ignore, 4);
    datasize = texDetails.width * texDetails.height * 4 * sizeof(float);
  }
  else if(is_dds_file(f))
  {
    dds = true;
  }
  else
  {
    int ignore = 0;
    int ret = stbi_info_from_file(f, (int *)&texDetails.width, (int *)&texDetails.height, &ignore);

    // just in case (we shouldn't have come in here if this weren't true), make sure
    // the format is supported
    if(ret == 0 || texDetails.width == 0 || texDetails.width == ~0U || texDetails.height == 0 ||
       texDetails.height == ~0U)
    {
      FileIO::fclose(f);
      return;
    }

    texDetails.format = rgba8_unorm;

    data = stbi_load_from_file(f, (int *)&texDetails.width, (int *)&texDetails.height, &ignore, 4);
    datasize = texDetails.width * texDetails.height * 4 * sizeof(byte);
  }

  // if we don't have data at this point (and we're not a dds file) then the
  // file was corrupted and we failed to load it
  if(!dds && data == NULL)
  {
    FileIO::fclose(f);
    return;
  }

  m_FrameRecord.frameInfo.initDataSize = 0;
  m_FrameRecord.frameInfo.persistentSize = 0;
  m_FrameRecord.frameInfo.fileSize = datasize;

  dds_data read_data = {0};

  if(dds)
  {
    FileIO::fseek64(f, 0, SEEK_SET);
    read_data = load_dds_from_file(f);

    if(read_data.subdata == NULL)
    {
      FileIO::fclose(f);
      return;
    }

    texDetails.cubemap = read_data.cubemap;
    texDetails.arraysize = read_data.slices;
    texDetails.width = read_data.width;
    texDetails.height = read_data.height;
    texDetails.depth = read_data.depth;
    texDetails.mips = read_data.mips;
    texDetails.numSubresources = texDetails.arraysize * texDetails.mips;
    texDetails.format = read_data.format;
    texDetails.dimension = 1;
    if(texDetails.width > 1)
      texDetails.dimension = 2;
    if(texDetails.depth > 1)
      texDetails.dimension = 3;

    m_FrameRecord.frameInfo.fileSize = 0;
    for(uint32_t i = 0; i < texDetails.numSubresources; i++)
      m_FrameRecord.frameInfo.fileSize += read_data.subsizes[i];
  }

  // recreate proxy texture if necessary.
  // we rewrite the texture IDs so that the
  // outside world doesn't need to know about this
  // (we only ever have one texture in the image
  // viewer so we can just set all texture IDs
  // used to that).
  if(m_TextureID != ResourceId())
  {
    if(m_TexDetails.width != texDetails.width || m_TexDetails.height != texDetails.height ||
       m_TexDetails.depth != texDetails.depth || m_TexDetails.cubemap != texDetails.cubemap ||
       m_TexDetails.mips != texDetails.mips || m_TexDetails.arraysize != texDetails.arraysize ||
       m_TexDetails.width != texDetails.width || m_TexDetails.format != texDetails.format)
    {
      m_TextureID = ResourceId();
    }
  }

  if(m_TextureID == ResourceId())
    m_TextureID = m_Proxy->CreateProxyTexture(texDetails);

  if(!dds)
  {
    m_Proxy->SetProxyTextureData(m_TextureID, 0, 0, data, datasize);
    free(data);
  }
  else
  {
    for(uint32_t i = 0; i < texDetails.numSubresources; i++)
    {
      m_Proxy->SetProxyTextureData(m_TextureID, i / texDetails.mips, i % texDetails.mips,
                                   read_data.subdata[i], (size_t)read_data.subsizes[i]);

      delete[] read_data.subdata[i];
    }

    delete[] read_data.subdata;
    delete[] read_data.subsizes;
  }

  FileIO::fclose(f);
}
Пример #20
0
void DGTexture::load() {
    FILE* fh;
    char magic[10]; // Used to identity file types
    GLint format = 0, internalFormat = 0;
    
    if (_isLoaded)
        return;
    
    if (!_hasResource) {
        log->error(DGModTexture, "%s: %s", DGMsg210004, this->name());
        
        return;
    }
    
    fh = fopen(_resource, "rb");	
    
    if (fh != NULL) {
        if (fread(&magic, sizeof(magic), 1, fh) == 0) {
            // Couldn't read magic number
            log->error(DGModTexture, "%s: %s", DGMsg210002, _resource);
        }
        
        if (memcmp(TEXIdent, &magic, 7) == 0) {
            short numTextures = 0;
            
            TEXMainHeader header;
            TEXSubHeader subheader;
            GLint compressed, size;
            
            fseek(fh, 8, SEEK_SET); // Skip identifier
            if (!fread(&header, 1, sizeof(header), fh))
                return;
            numTextures = header.numTextures;
            _width = (GLuint)header.width;
            _height = (GLuint)header.height;
            
            // Skip subheaders based on the index
            if (_indexInBundle) {
                unsigned int i;
                
                for (i = 0; i < _indexInBundle; i++) {
                    if (!fread(&subheader, 1, sizeof(subheader), fh))
                        return;
                    fseek(fh, sizeof(char) * subheader.size, SEEK_CUR);
                }
            }
            
            if (!fread(&subheader, 1, sizeof(subheader), fh))
                return;
            
            _depth = (GLuint)subheader.depth;
            size = (GLint)subheader.size;
            internalFormat = (GLint)subheader.format;
            
            _bitmap = (GLubyte*)malloc(size * sizeof(GLubyte)); 
            if (!fread(_bitmap, 1, sizeof(GLubyte) * size, fh))
                return;
            
            glGenTextures(1, &_ident);
            glBindTexture(GL_TEXTURE_2D, _ident);
            
            if (header.compressionLevel) {
                glCompressedTexImage2D(GL_TEXTURE_2D, 0, internalFormat, _width, _height, 
                                       0, size, _bitmap);
                glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPRESSED, &compressed);
                
                if (compressed == GL_TRUE)
                    _isLoaded = true;
                else
                    log->error(DGModTexture, "%s: %s", DGMsg210002, fh);
            }
            else {
                glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, _width, _height, 0, GL_RGB, GL_UNSIGNED_BYTE, _bitmap); // Only RGB is supported
                _isLoaded = true;
            }
            
            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_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
            
            free(_bitmap);
        }
        else {
            int x, y, comp;
            
            fseek(fh, 0, SEEK_SET);
            _bitmap = (GLubyte*)stbi_load_from_file(fh, &x, &y, &comp, STBI_default);
            
            if (_bitmap) {
                _width = x;
                _height = y;
                _depth = comp;
                
                switch (comp) {
                    case STBI_grey:
                        format = GL_LUMINANCE;				
                        if (_compressionLevel)							
                            internalFormat = GL_COMPRESSED_LUMINANCE;						
                        else						
                            internalFormat = GL_LUMINANCE;
                        break;
                    case STBI_grey_alpha:
                        format = GL_LUMINANCE_ALPHA;					
                        if (_compressionLevel)
                            internalFormat = GL_COMPRESSED_LUMINANCE_ALPHA;							
                        else						
                            internalFormat = GL_LUMINANCE_ALPHA;
                        break;
                    case STBI_rgb:
                        format = GL_RGB;					
                        if (_compressionLevel)					
                            internalFormat = GL_COMPRESSED_RGB;							
                        else						
                            internalFormat = GL_RGB;
                        break;
                    case STBI_rgb_alpha:
                        format = GL_RGBA;						
                        if (_compressionLevel)						
                            internalFormat = GL_COMPRESSED_RGBA;						
                        else						
                            internalFormat = GL_RGBA;
                        break;
                    default:
                        log->warning(DGModTexture, "%s: (%s) %d", DGMsg210003, _resource, comp);
                        break;
                }
                
                glGenTextures(1, &_ident);
                glBindTexture(GL_TEXTURE_2D, _ident);
                
                glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, _width, _height,
                             0, format, GL_UNSIGNED_BYTE, _bitmap);
                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_WRAP_S, GL_CLAMP_TO_EDGE);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
                
                free(_bitmap);
                
                _isLoaded = true;
            }
            else {
                // Nothing loaded
                log->error(DGModTexture, "%s: (%s) %s", DGMsg210001, _resource, stbi_failure_reason());
            }
        }
        
        fclose(fh);
    }
    else {
        // File not found
        log->error(DGModTexture, "%s: %s", DGMsg210000, _resource);
    }    
}