Beispiel #1
7
bool Texture::loadFromFile(const std::string &filename) {
	int width;
	int height;
	int comp;
	stbi_uc *pixels = stbi_load(filename.c_str(), &width, &height, &comp, 4);

	if (pixels == NULL) {
		// TODO: Log this..
		return false;
	}

	glBindTexture(GL_TEXTURE_2D, mName);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

	stbi_image_free(pixels);

	mWidth = width;
	mHeight = height;

	return true;
}
Beispiel #2
3
image load_image_stb(char *filename, int channels)
{
    int w, h, c;
    unsigned char *data = stbi_load(filename, &w, &h, &c, channels);
    if (!data) {
        fprintf(stderr, "Cannot load file image %s\nSTB Reason: %s\n", filename, stbi_failure_reason());
        exit(0);
    }
    if(channels) c = channels;
    int i,j,k;
    image im = make_image(w, h, c);
    for(k = 0; k < c; ++k){
        for(j = 0; j < h; ++j){
            for(i = 0; i < w; ++i){
                int dst_index = i + w*j + w*h*k;
                int src_index = k + c*i + c*w*j;
                im.data[dst_index] = (float)data[src_index]/255.;
            }
        }
    }
    free(data);
    return im;
}
int scene::loadMap(string mapid)
{
	int id = atoi(mapid.c_str());
	if(id!=maps.size()){
		cout << "ERROR: MATERIAL ID does not match expected number of materials" << endl;
		return -1;
	}else{
		cout << "Loading Map " << id << "..." << endl;
		Map newMap;
	
		//load static properties
	
			string line;
			getline(fp_in,line);
			vector<string> tokens = utilityCore::tokenizeString(line);
			if(strcmp(tokens[0].c_str(), "FILE")==0){
				newMap.mapptr = stbi_load(tokens[1].c_str(),&newMap.width, &newMap.height,&newMap.depth,0);
			}					  
			
		maps.push_back(newMap);
		return 1;
	}
}
Beispiel #4
2
TextureMap::TextureMap(const GLchar* path)
{
	glGenTextures(1, &textureID);
	int width, height,bpp;
	//unsigned char* image = SOIL_load_image(path, &width, &height, 0, SOIL_LOAD_RGB);
	unsigned char* image = stbi_load(path, &width, &height, &bpp, 3);
	mWidth = width;
	mHeight = height;
	glBindTexture(GL_TEXTURE_2D, textureID);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
	glGenerateMipmap(GL_TEXTURE_2D);

	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);
	float aniso = 0.0f;
	glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &aniso);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso);
	glBindTexture(GL_TEXTURE_2D, 0);

	stbi_image_free(image);
}
Beispiel #5
0
bool NormalMap::load(float scale)
{
    int actual_components = 0;
    int requested_components = 1;
    components = requested_components;
    image = stbi_load(filename, &width, &height, &actual_components, requested_components);
    if (image) {
        assert(width > 0);
        assert(height > 0);
        assert(actual_components > 0);
        if (actual_components != requested_components) {
            if (verbose) {
                printf("warning: %d component normal map treated as gray scale height map\n",
                    actual_components);
            }
        }
        normal_image = new GLubyte[width*height*3];
        assert(normal_image);
        GLubyte* p = normal_image;
        for (int y=0; y<height; y++) {
            for (int x=0; x<width; x++) {
                float3 normal = computeNormal(x,y, scale);
                PackedNormal packed_normal(normal);
                p[0] = packed_normal.n[0];
                p[1] = packed_normal.n[1];
                p[2] = packed_normal.n[2];
                p += 3;
            }
        }
        assert(p == normal_image+(width*height*3));
        // success
        return true;
    } else {
        printf("%s: failed to load image %s\n", program_name, filename);
        return false;
    }
}
Beispiel #6
0
Enco3D::Rendering::TextureCubeMap::TextureCubeMap(const std::string *filenames, unsigned int filter, unsigned int wrap)
{
	glGenTextures(1, &m_id);
	glBindTexture(GL_TEXTURE_CUBE_MAP, m_id);

	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, filter);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, filter);

	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, wrap);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, wrap);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, wrap);

	for (unsigned int i = 0; i < 6; i++)
	{
		int w, h, bytesPerPixel;
		unsigned char *data = stbi_load(filenames[i].c_str(), &w, &h, &bytesPerPixel, 4);

		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

		if (data == nullptr)
		{
			Core::DebugLogger::log("[ERROR] Unable to load texture: " + filenames[i]);
			return;
		}
		else
			Core::DebugLogger::log("Successfully loaded texture " + filenames[i]);

		m_width = (unsigned int)w;
		m_height = (unsigned int)h;

		stbi_image_free(data);
	}

	glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

	Core::DebugLogger::log("[OPEN_GL] Created texture cube map with id " + std::to_string(m_id));
}
void DialogControlsModels::createTextureBuffer(std::string imageFile, GLuint* vboBuffer, int* width, int* height) {
    if (!boost::filesystem::exists(imageFile))
        imageFile = Settings::Instance()->currentFolder + "/" + imageFile;
    int tChannels;
    unsigned char* tPixels = stbi_load(imageFile.c_str(), width, height, &tChannels, 0);
    if (!tPixels)
        Settings::Instance()->funcDoLog("Can't load texture image - " + imageFile + " with error - " + std::string(stbi_failure_reason()));
    else {
        glGenTextures(1, vboBuffer);
        glBindTexture(GL_TEXTURE_2D, *vboBuffer);
        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_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        GLenum textureFormat = 0;
        switch (tChannels) {
            case 1:
                textureFormat = GL_LUMINANCE;
                break;
            case 2:
                textureFormat = GL_LUMINANCE_ALPHA;
                break;
            case 3:
                textureFormat = GL_RGB;
                break;
            case 4:
                textureFormat = GL_RGBA;
                break;
            default:
                textureFormat = GL_RGB;
                break;
        }
        glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(textureFormat), *width, *height, 0, textureFormat, GL_UNSIGNED_BYTE, (GLvoid*)tPixels);
        glGenerateMipmap(GL_TEXTURE_2D);
        stbi_image_free(tPixels);
    }
}
Beispiel #8
0
Texture::Texture(const char* filename, std::initializer_list<float> texcoords) : 
   	Component(EComponentType::TEXTURE),	
	uv(texcoords) {
	
	// Load pixeldata, width, height, and components from file
	unsigned char* pixels = stbi_load(filename, &width, &height, &components, 0);

	// Allocate a new texture in OpenGL
	glGenTextures(1, &GLtex);

	glActiveTexture(GL_TEXTURE0);
	
	// Set active texture id
	glBindTexture(GL_TEXTURE_2D, GLtex);


	if (components == 4 ) {
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
	} else {
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

	// cleanup
	stbi_image_free(pixels);

	// unbind texture for cleanliness
	glBindTexture(GL_TEXTURE_2D, 0);

	for (int i = 0; i < uv.size(); i++) {
		uv[i] = uv[i] / width;
		uv[i+1] = uv[i+1] / height;
		i++;
	}
}
Beispiel #9
0
Texture::Texture( const char *filename, bool png )
{
	int h, w, comp;
	uchar *img = stbi_load( filename, &w, &h, &comp, 4 );
	if ( img == NULL )
	{
		printf( "%sが読み込めません\n", filename );
		return;
	}
	width = w;
	height = h;
	aspect = (double)width/height;

	//glEnable( GL_TEXTURE_2D );

	glGenTextures( 1, &id );

	glBindTexture( GL_TEXTURE_2D, id );

	gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, width, height,
		GL_RGBA, GL_UNSIGNED_BYTE, img );

	stbi_image_free( img );
}
Beispiel #10
0
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        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);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}
Beispiel #11
0
Image * 
Image::loadPNG(const std::string &filename) 
{
    assert(!filename.empty());

    int w, h, n;
    unsigned char *buffer = stbi_load(filename.c_str(), &w, &h, &n, 0);
    assert(buffer != NULL);
    assert(n == 3);

    Image *image = new Image(w, h);

    // flip y so that (0,0) is bottom left corner
    for (int c = 0, p = 0, y = h - 1; y >= 0; y--) {
        for (int x = 0; x < w; x++, ++p) {
            Vector3f &pixel = image->_data[p];
            pixel[0] = buffer[c++] / 255.0f;
            pixel[1] = buffer[c++] / 255.0f;
            pixel[2] = buffer[c++] / 255.0f;
        }
    }

    return image;
}
Beispiel #12
0
LDRImage loadImage(const std::string& filename, int convertToChannels)
{



    int width=0,height=0,channels=0;

    auto pixels = stbi_load(filename.c_str(),&width,&height,&channels, convertToChannels);

    if(!pixels)
    {
        throw std::runtime_error(std::string("LDRImage load error: \nFile")+filename+"\nReason:"+stbi_failure_reason());

    }

     std::array<std::size_t ,3> arr= {{(std::size_t)channels,(std::size_t)width,(std::size_t)height}};
    return MultidimensionalArray<unsigned char, 3>(std::shared_ptr<unsigned char>(pixels,StbiDeleter<unsigned char>()),

                                                   // {(std::size_t)channels,(std::size_t)width,(std::size_t)height}
                                                   arr

                                                    );//

}
Resource* ResourceManager::LoadTexture2D(std::string filepath)
{
	Image image;
	int width, height, components;
	image.data = stbi_load(filepath.c_str(), &width, &height, &components, 0);
	image.width = width;
	image.height = height;
	image.components = components;

	// This may not work as intended
	if (image.data == NULL)
	{
#ifdef DEBUG
		Debug::LogError("[ResourceManager] Texture2D could not be loaded.");
#endif
		return 0;
	}

	Texture2D* texture = new Texture2D(image);

	texture->IncreaseReferenceCount();
	resourceCollection[filepath] = texture;
	return dynamic_cast<Resource*>(texture);
}
Beispiel #14
0
Texture::Texture(const char * path)
{
	id = 0;
	int width, height, nrChannels;//R"(D:\Projects\C++\KatEngine\Pukman\winter.jpg)"
	unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0);
	if (!data)
		fatal_error("Couldn't load texture image");
	this->width = width;
	this->height = height;
	glGenTextures(1, &id);
	//glActiveTexture(GL_TEXTURE0);//????
	glBindTexture(GL_TEXTURE_2D, id);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
	glGenerateMipmap(GL_TEXTURE_2D);

	stbi_image_free(data);

	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_NEAREST_MIPMAP_LINEAR);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
std::vector<GLuint> Texture::LoadTexture(const std::vector<std::string>& textures)
{
	std::vector<GLuint> texture;
	int size = textures.size();
	GLuint* tex = new GLuint[size];
	glGenTextures(size, tex);
	for (unsigned int i = 0; i < size; ++i)
	{
		int width, height, numComponents;
		unsigned char* data = stbi_load(textures[i].c_str(), &width, &height, &numComponents, STBI_rgb_alpha);
		if (data == nullptr)
			std::cerr << "unable load texture " << textures[i] << "\n";
		glBindTexture(GL_TEXTURE_2D, tex[i]);
		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_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
	}
	for (int i = 0; i < size; ++i)
		texture.push_back(tex[i]);
	delete tex;
	return texture;
}
Texture2D::Texture2D(const char* filename) {
	glGenTextures(1, &texID);
	glBindTexture(GL_TEXTURE_2D, texID);

	// Load texture from file.
	int components;
	unsigned char* data = stbi_load(filename, &width, &height, &components, 0);

	if (data == NULL)
        Log() << "Couldn't load image " << filename << "\n";

	// Give the image to OpenGL.
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, Format(components), GL_UNSIGNED_BYTE, data);

	stbi_image_free(data);

	// When MAGnifying the image (no bigger mipmap available), use LINEAR filtering.
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// When MINifying the image, use a LINEAR blend of two mipmaps, each filtered LINEARLY too.
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

	// Repeat texture when texture coordinates outside 0.0-1.0.
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	// Generate mipmaps, by the way.
	glGenerateMipmap(GL_TEXTURE_2D);
    
    // For rendering.
    rectangle = Resources().CreateRectangle();
    
    vertexShader = Resources().CreateShader(DEFAULT2D_VERT, DEFAULT2D_VERT_LENGTH, GL_VERTEX_SHADER);
    fragmentShader = Resources().CreateShader(TEXTURE2D_FRAG, TEXTURE2D_FRAG_LENGTH, GL_FRAGMENT_SHADER);
    shaderProgram = Resources().CreateShaderProgram({ vertexShader, fragmentShader });
}
Beispiel #17
0
Texture::Texture(const std::string& fileName) {
	int width, height, numComponents; //returned by the stb loader

	unsigned char* imageData = stbi_load(fileName.c_str(), &width, &height, &numComponents, 4);

	if (imageData == NULL)
		std::cerr << "Texture loading failed for texture: " << fileName << std::endl;

	glGenTextures(1, &m_texture); //generate space for 1 texture and store it in m_texture
	glBindTexture(GL_TEXTURE_2D, m_texture);

	//wrapping if the mesh has more pixels than the texture, repeat makes the texture repeat in this case
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	//for interpolation
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	//send the texture to the GPU
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

	stbi_image_free(imageData);//free the image data from the CPU once we dont need it anymore
}
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat 
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}
Beispiel #19
0
Image::Image(const string &name) {
	_isCompressed = false;

	int w;
	int h;
	int ch;
	if (upToLow(name).find(".pvr") == string::npos) {
		unsigned char * buff = stbi_load(name.c_str(), &w, &h, &ch, 0);
		if (!buff)
			throw std::runtime_error("stbi_load failed");

		int original_texture_format;

		switch( ch )
		{
		case 1:
			original_texture_format = GL_LUMINANCE;
			break;
		case 2:
			original_texture_format = GL_LUMINANCE_ALPHA;
			break;
		case 3:
			original_texture_format = GL_RGB;
			break;
		case 4:
			original_texture_format = GL_RGBA;
			break;
		}
		init(name, w, h, 8, original_texture_format, ch, buff, true);
	} else {
		_isCompressed = true;
		pvrImage = new PVRImage(name);
		ch = 4;
		init(name, pvrImage->getWidth(), pvrImage->getHeight(), pvrImage->getNumOfMipmaps(), pvrImage->getInternalFormat(), ch, pvrImage->getImageData(0), true);
	}
}
Beispiel #20
0
int main( int argCount, char* args[] )
{
    if (argCount != 3)
    {
        std::cout << "Usage: SDF_Generator font.png font_sdf.tga" << std::endl;
        return 1;
    }

    int width, height, components;
    unsigned char* imageData = stbi_load( args[1], &width, &height, &components, 1 );

    if (imageData == nullptr)
    {
        std::cerr << "Failed to load " << args[ 1 ] << ". Reason: " << stbi_failure_reason() << std::endl;
        return 1;
    }

    CreateDistanceMap( imageData, width, height );
    ScaleDistanceMap( width, height, 4 );
    WriteScaledMapIntoTGAFile( "sdf.tga", scaledWidth, scaledHeight );

    stbi_image_free( imageData );
    return 0;
}
Beispiel #21
0
int main(int argc, char *argv[])
{
	uint32_t width = 1920, height = 1080;
	LoadOpenGLESWindow(width, height);
    
	// initial opengl state
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	glDisable(GL_CULL_FACE);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	
	// load textures
	GLfloat max_anisotropy;
	glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &max_anisotropy);
	GLuint textures[TEXTURES_NUM];
	glGenTextures(TEXTURES_NUM, textures);
	int i;
	for (i = 0; i < TEXTURES_NUM; i++)
	{
		int x, y, n;
		unsigned char *data = stbi_load(texture_files[i], &x, &y, &n, 3);
		if (data == NULL)
		{
			fprintf(stderr, "Could not load file: %s", texture_files[i]);
			exit(-1);
		}
		
		glBindTexture(GL_TEXTURE_2D, textures[i]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
		glGenerateMipmap(GL_TEXTURE_2D);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY, max_anisotropy);
		
		stbi_image_free(data);
	}
	
	// load program
	GLuint programObject = LoadProgram(vertex_shader, fragment_shader);
	glUseProgram(programObject);
	glUniform1i(glGetUniformLocation(programObject, "tex"), 0);
	GLint colorUniformLocation = glGetUniformLocation(programObject, "color");
	GLint transformUniformLocation = glGetUniformLocation(programObject, "transform");
	
	// load quad data
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, quad_vertices);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, quad_texcoord);
	glEnableVertexAttribArray(1);

    unsigned int frames = 0;
    while(1)
    {
		glViewport(0, 0, width, height);
		
		// animation params
		double t = (frames++) * 0.02f;
		float a = 0.5f + 0.5f * sinf(t * 13.0f);
		float x = 0.2f * sinf(32.0f * t) * sinf(3.5f * t);
		float y = 0.1f * sinf(23.0f * t) * sinf(3.5f * t);
		
		// camera config
		mat4_t proj = mat4_perspective(50.0f, (float)width / (float)height, 0.1f, 1000.0f);
		mat4_t view = mat4_mul(//mat4_mul(
			mat4_translation(vec3(x, y, -3.0f)), // positioning
			mat4_rotation(-90.0f, vec3(0.0f, 0.0f, 1.0f)));//, // beamer rotation
			//mat4_rotation(180.0f, vec3(0.0f, 1.0f, 0.0f))); // horizontal "flip"
		mat4_t vp = mat4_mul(proj, view);
		
		// color
		glUniform3f(colorUniformLocation, 
			a * (0.5f + 0.5f * sinf(t)),
			a * (0.5f + 0.5f * sinf(1.3f * t)),
			a * (0.5f + 0.5f * sinf(1.7f * t)));
			
		// draw radials
		int i;
		for (i = 0; i < 3; i++)
		{
			mat4_t mvp = mat4_mul(vp, mat4_rotation(20.0f * cos(t * 2.0f), vec3(0.0f, 1.0f, 0.0f)));
			mvp = mat4_mul(mvp, mat4_translation(vec3(0.0f, 0.8f, 0.0f)));
			mvp = mat4_mul(mvp, mat4_rotation(t * 32.0f * (0.5f + (i - 1)), vec3(0.0f, 0.0f, 1.0f)));
			glUniformMatrix4fv(transformUniformLocation, 1, GL_FALSE, mvp.m);
			glBindTexture(GL_TEXTURE_2D, textures[RADIAL0 + i]);
			glDrawArrays(GL_TRIANGLES, 0, 6);
		}

		// draw text
		mat4_t mvp = mat4_mul(vp, mat4_rotation(60.0f * sin(t), vec3(0.0f, 1.0f, 0.0f)));
		mvp = mat4_mul(mvp, mat4_translation(vec3(0.0f, -0.8f, 0.0f)));
		glUniformMatrix4fv(transformUniformLocation, 1, GL_FALSE, mvp.m);
		glBindTexture(GL_TEXTURE_2D, textures[TEXT]);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		
		// present
		eglSwapBuffers(display, surface);
    }
}
Beispiel #22
0
    Tutorial(GUIHelperInterface* guiHelper, int tutorialIndex)
    :m_app(guiHelper->getAppInterface()),
	m_guiHelper(guiHelper),
	m_tutorialIndex(tutorialIndex),
	m_stage(0),
	m_counter(0),
	m_timeSeriesCanvas0(0),
	m_timeSeriesCanvas1(0)
    {
		int numBodies = 1;
		
		m_app->setUpAxis(1);
		m_app->m_renderer->enableBlend(true);
		
		switch (m_tutorialIndex)
		{
			case TUT_VELOCITY:
			{
				numBodies=10;
				m_timeSeriesCanvas0 = new TimeSeriesCanvas(m_app->m_2dCanvasInterface,512,256,"Constant Velocity");
				
				m_timeSeriesCanvas0 ->setupTimeSeries(2,60, 0);
				m_timeSeriesCanvas0->addDataSource("X position (m)", 255,0,0);
				m_timeSeriesCanvas0->addDataSource("X velocity (m/s)", 0,0,255);
				m_timeSeriesCanvas0->addDataSource("dX/dt (m/s)", 0,0,0);
				break;
			}
			case TUT_ACCELERATION:
			{
				numBodies=10;
				m_timeSeriesCanvas1 = new TimeSeriesCanvas(m_app->m_2dCanvasInterface,256,512,"Constant Acceleration");
				
				m_timeSeriesCanvas1 ->setupTimeSeries(50,60, 0);
				m_timeSeriesCanvas1->addDataSource("Y position (m)", 255,0,0);
				m_timeSeriesCanvas1->addDataSource("Y velocity (m/s)", 0,0,255);
				m_timeSeriesCanvas1->addDataSource("dY/dt (m/s)", 0,0,0);
				break;
			}
			case TUT_COLLISION:
			{
				numBodies=2;
				m_timeSeriesCanvas1 = new TimeSeriesCanvas(m_app->m_2dCanvasInterface,512,200,"Distance");
				m_timeSeriesCanvas1 ->setupTimeSeries(1.5,60, 0);
				m_timeSeriesCanvas1->addDataSource("distance", 255,0,0);
				break;
			}
			
			case TUT_SOLVE_CONTACT_CONSTRAINT:
			{
				numBodies=2;
				m_timeSeriesCanvas1 = new TimeSeriesCanvas(m_app->m_2dCanvasInterface,512,200,"Collision Impulse");
				m_timeSeriesCanvas1 ->setupTimeSeries(1.5,60, 0);
				m_timeSeriesCanvas1->addDataSource("Distance", 0,0,255);
				m_timeSeriesCanvas1->addDataSource("Impulse magnutide", 255,0,0);
				
				{
					SliderParams slider("Restitution",&gRestitution);
					slider.m_minVal=0;
					slider.m_maxVal=1;
					m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
				}
				{
					SliderParams slider("Mass A",&gMassA);
					slider.m_minVal=0;
					slider.m_maxVal=100;
					m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
				}
				
				{
					SliderParams slider("Mass B",&gMassB);
					slider.m_minVal=0;
					slider.m_maxVal=100;
					m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider);
				}
				
				
				
				break;
			}
				
			default:
			{
				
				m_timeSeriesCanvas0 = new TimeSeriesCanvas(m_app->m_2dCanvasInterface,512,256,"Unknown");
				m_timeSeriesCanvas0 ->setupTimeSeries(1,60, 0);
				
			}
		};

		
		
		if (m_tutorialIndex==TUT_VELOCITY)
		{

		 int boxId = m_app->registerCubeShape(100,1,100);
            b3Vector3 pos = b3MakeVector3(0,-3.5,0);
            b3Quaternion orn(0,0,0,1);
            b3Vector4 color = b3MakeVector4(1,1,1,1);
            b3Vector3 scaling = b3MakeVector3(1,1,1);
            m_app->m_renderer->registerGraphicsInstance(boxId,pos,orn,color,scaling);
		}

		for (int i=0;i<numBodies;i++)
		{
			m_bodies.push_back(new LWRigidBody());
		}
		for (int i=0;i<m_bodies.size();i++)
		{
			m_bodies[i]->m_worldPose.m_position.setValue((i/4)*5,3,(i&3)*5);
		}
		{
			int textureIndex = -1;
			
			if (1)
			{
				int width,height,n;
				
				const char* filename = "data/cube.png";
				const unsigned char* image=0;
				
				const char* prefix[]={"./","../","../../","../../../","../../../../"};
				int numprefix = sizeof(prefix)/sizeof(const char*);
				
				for (int i=0;!image && i<numprefix;i++)
				{
					char relativeFileName[1024];
					sprintf(relativeFileName,"%s%s",prefix[i],filename);
					image = stbi_load(relativeFileName, &width, &height, &n, 0);
				}
				
				b3Assert(image);
				if (image)
				{
					textureIndex = m_app->m_renderer->registerTexture(image,width,height);
				}
			}
			
			//            int boxId = m_app->registerCubeShape(1,1,1,textureIndex);
			int boxId = m_app->registerGraphicsUnitSphereShape(SPHERE_LOD_HIGH, textureIndex);
			b3Vector4 color = b3MakeVector4(1,1,1,0.8);
			b3Vector3 scaling = b3MakeVector3(SPHERE_RADIUS,SPHERE_RADIUS,SPHERE_RADIUS);
			for (int i=0;i<m_bodies.size();i++)
			{
				m_bodies[i]->m_collisionShape.m_sphere.m_radius = SPHERE_RADIUS;
				m_bodies[i]->m_collisionShape.m_type = LW_SPHERE_TYPE;
				
				m_bodies[i]->m_graphicsIndex = m_app->m_renderer->registerGraphicsInstance(boxId,m_bodies[i]->m_worldPose.m_position, m_bodies[i]->m_worldPose.m_orientation,color,scaling);
				m_app->m_renderer->writeSingleInstanceTransformToCPU(m_bodies[i]->m_worldPose.m_position, m_bodies[i]->m_worldPose.m_orientation, m_bodies[i]->m_graphicsIndex);
			}
		}

		
		if (m_tutorialIndex == TUT_SOLVE_CONTACT_CONSTRAINT)
		{
			m_bodies[0]->m_invMass = gMassA? 1./gMassA : 0;
			m_bodies[0]->m_collisionShape.m_sphere.computeLocalInertia(gMassA,m_bodies[0]->m_localInertia);
			
			m_bodies[1]->m_invMass =gMassB? 1./gMassB : 0;
			m_bodies[1]->m_collisionShape.m_sphere.computeLocalInertia(gMassB,m_bodies[1]->m_localInertia);

			if (gMassA)
				m_bodies[0]->m_linearVelocity.setValue(0,0,1);
			if (gMassB)
				m_bodies[1]->m_linearVelocity.setValue(0,0,-1);

		}
		

			
		 m_app->m_renderer->writeTransforms();
    }
Beispiel #23
0
////////////////////////////////////////////////////////////////////////
// Material: encapsulates surface properties
void Material::setTexture(const std::string path)
{
    int width, height, n;
    stbi_set_flip_vertically_on_load(true);
    unsigned char* image = stbi_load(path.c_str(), &width, &height, &n, 0);
}
Beispiel #24
0
std::string processMaterial(unsigned idx, aiMaterial *material)
{
	aiString path;

	if(material->GetTexture(aiTextureType_DIFFUSE, 0, &path) == AI_SUCCESS)
	{
		// Some file formats store absolute paths, we just need the filename and
		// pick the correct texture from a directory ourselves
		std::string filename = extractFilename(path);

		std::string dir = "C:/Documents and Settings/Jasper/My Documents/School/062187/Graduation/Raw/Level/";
		std::string input = dir + filename;
		std::string newfilename = stripFileExtension(filename);
		std::string imagefilename = outdir + "/Images/" + newfilename;
		std::string texturefilename = outdir + "/Textures/" + newfilename;
		std::string materialfilename = outdir + "/Materials/" + newfilename;

		if(!textures[filename])
		{
			outputJsonMaterialFile(texturefilename, materialfilename);
			outputJsonTextureFile(imagefilename, texturefilename);

			int x, y, comp;
			unsigned char *buffer = stbi_load(input.c_str(), &x, &y, &comp, 4);

			if(buffer)
			{
				int flags = squish::kDxt1 | squish::kColourRangeFit;

				unsigned size = squish::GetStorageRequirements(x, y, flags);
				unsigned char *blocks = new unsigned char[size];

				Bitstream s(scratchpad, g_Endianness, g_supportHalfFloat);

				s.WriteULong(2); // version
				s.WriteULong(TextureType2D); // type
				s.WriteULong(TextureFormatDxt1); // format
				s.WriteULong(FilterLinear);
				s.WriteULong(FilterLinear);
				s.WriteULong(x); // width
				s.WriteULong(y); // height
				s.WriteULong(0); // depth
				s.WriteULong(1); // mipmaps

				squish::CompressImage(buffer, x, y, blocks, flags);

				FILE *f = fopen((imagefilename + ".btx").c_str(), "wb");
				fwrite(s.GetBuffer(), s.BytesWritten(), 1, f);
				fwrite(blocks, size, 1, f);
				fclose(f);

				printf("Done writing texture '%s'\n", filename.c_str());

				delete[] blocks;

				textures[filename] = blocks;
				stbi_image_free(buffer);
			}
		}

		return materialfilename;
	}

	return "material_not_found";
}
    CollisionTutorialBullet2(GUIHelperInterface* guiHelper, int tutorialIndex)
    :m_app(guiHelper->getAppInterface()),
	m_guiHelper(guiHelper),
	m_tutorialIndex(tutorialIndex),
	m_collisionSdkHandle(0),
	m_collisionWorldHandle(0),
	m_stage(0),
	m_counter(0),
	m_timeSeriesCanvas0(0)
    {
		
		gTotalPoints = 0;
		m_app->setUpAxis(1);
		m_app->m_renderer->enableBlend(true);
		
		switch (m_tutorialIndex)
		{
			case TUT_SPHERE_PLANE_RTB3:
			case TUT_SPHERE_PLANE_BULLET2:
			{
				
				if (m_tutorialIndex==TUT_SPHERE_PLANE_BULLET2)
				{
					m_collisionSdkHandle = plCreateBullet2CollisionSdk();
				} else
				{
#ifndef DISABLE_REAL_TIME_BULLET3_COLLISION_SDK
					m_collisionSdkHandle = plCreateRealTimeBullet3CollisionSdk();
#endif //DISABLE_REAL_TIME_BULLET3_COLLISION_SDK
				}
				if (m_collisionSdkHandle)
				{
					int maxNumObjsCapacity=1024;
					int maxNumShapesCapacity=1024;
					int maxNumPairsCapacity=16384;
					btAlignedObjectArray<plCollisionObjectHandle> colliders;
					m_collisionWorldHandle = plCreateCollisionWorld(m_collisionSdkHandle,maxNumObjsCapacity,maxNumShapesCapacity,maxNumPairsCapacity);
					//create objects, do query etc
					{
						float radius = 1.f;

						void* userPointer = 0;
						{
							for (int j=0;j<sNumCompounds;j++)
							{
								plCollisionShapeHandle compoundShape =  plCreateCompoundShape(m_collisionSdkHandle,m_collisionWorldHandle);

								for (int i=0;i<sNumSpheres;i++)
								{
									btVector3 childPos(i*1.5,0,0);
									btQuaternion childOrn(0,0,0,1);
								
									btVector3 scaling(radius,radius,radius);
						
									plCollisionShapeHandle childShape = plCreateSphereShape(m_collisionSdkHandle, m_collisionWorldHandle,radius);
									plAddChildShape(m_collisionSdkHandle,m_collisionWorldHandle,compoundShape, childShape,childPos,childOrn);
						
								
									//m_guiHelper->createCollisionObjectGraphicsObject(colObj,color);
								
								}
								if (m_tutorialIndex==TUT_SPHERE_PLANE_BULLET2)
								{
									btCollisionShape* colShape = (btCollisionShape*) compoundShape;
									m_guiHelper->createCollisionShapeGraphicsObject(colShape);
								} else
								{
								}
							
								{
									btVector3 pos(j*sNumSpheres*1.5,-2.4,0);
									btQuaternion orn(0,0,0,1);
									plCollisionObjectHandle colObjHandle = plCreateCollisionObject(m_collisionSdkHandle,m_collisionWorldHandle,userPointer, -1,compoundShape,pos,orn);
									if (m_tutorialIndex==TUT_SPHERE_PLANE_BULLET2)
									{
										btCollisionObject* colObj = (btCollisionObject*) colObjHandle;
										btVector4 color=sColors[j&3];
										m_guiHelper->createCollisionObjectGraphicsObject(colObj,color);
										colliders.push_back(colObjHandle);
										plAddCollisionObject(m_collisionSdkHandle, m_collisionWorldHandle,colObjHandle);
									}
								}
							}
						}
					}

					{
						plCollisionShapeHandle colShape = plCreatePlaneShape(m_collisionSdkHandle, m_collisionWorldHandle,0,1,0,-3.5);
						btVector3 pos(0,0,0);
						btQuaternion orn(0,0,0,1);
						void* userPointer = 0;
						plCollisionObjectHandle colObj = plCreateCollisionObject(m_collisionSdkHandle,m_collisionWorldHandle,userPointer, 0,colShape,pos,orn);
						colliders.push_back(colObj);
						plAddCollisionObject(m_collisionSdkHandle, m_collisionWorldHandle,colObj);
					}

                    int numContacts = plCollide(m_collisionSdkHandle,m_collisionWorldHandle,colliders[0],colliders[1],pointsOut,sPointCapacity);
                    printf("numContacts = %d\n", numContacts);
                    void* myUserPtr = 0;
                    
                    plWorldCollide(m_collisionSdkHandle,m_collisionWorldHandle,myNearCallback, myUserPtr);
                    printf("total points=%d\n",gTotalPoints);
                    
                    //plRemoveCollisionObject(m_collisionSdkHandle,m_collisionWorldHandle,colObj);
					//plDeleteCollisionObject(m_collisionSdkHandle,colObj);
					//plDeleteShape(m_collisionSdkHandle,colShape);
				}
				

				/*
				m_timeSeriesCanvas0 = new TimeSeriesCanvas(m_app->m_2dCanvasInterface,512,256,"Constant Velocity");
				
				m_timeSeriesCanvas0 ->setupTimeSeries(2,60, 0);
				m_timeSeriesCanvas0->addDataSource("X position (m)", 255,0,0);
				m_timeSeriesCanvas0->addDataSource("X velocity (m/s)", 0,0,255);
				m_timeSeriesCanvas0->addDataSource("dX/dt (m/s)", 0,0,0);
				 */
				break;
			}
			
			
			default:
			{
				
				m_timeSeriesCanvas0 = new TimeSeriesCanvas(m_app->m_2dCanvasInterface,512,256,"Unknown");
				m_timeSeriesCanvas0 ->setupTimeSeries(1,60, 0);
				
			}
		};

		
		
		{

		 int boxId = m_app->registerCubeShape(100,0.01,100);
            b3Vector3 pos = b3MakeVector3(0,-3.5,0);
            b3Quaternion orn(0,0,0,1);
            b3Vector4 color = b3MakeVector4(1,1,1,1);
            b3Vector3 scaling = b3MakeVector3(1,1,1);
            m_app->m_renderer->registerGraphicsInstance(boxId,pos,orn,color,scaling);
		}

		
		{
			int textureIndex = -1;
			
			if (1)
			{
				int width,height,n;
				
				const char* filename = "data/cube.png";
				const unsigned char* image=0;
				
				const char* prefix[]={"./","../","../../","../../../","../../../../"};
				int numprefix = sizeof(prefix)/sizeof(const char*);
				
				for (int i=0;!image && i<numprefix;i++)
				{
					char relativeFileName[1024];
					sprintf(relativeFileName,"%s%s",prefix[i],filename);
					image = stbi_load(relativeFileName, &width, &height, &n, 3);
				}
				
				b3Assert(image);
				if (image)
				{
					textureIndex = m_app->m_renderer->registerTexture(image,width,height);
				}
			}
			
		}
		
		m_app->m_renderer->writeTransforms();
    }
Beispiel #26
0
GLTexture::GLTexture(const char *file_name, int flags, float *color)
{
	int img_width = 0;
	int img_height = 0;
	int img_bpp = 0;
    unsigned char* img_data = stbi_load(file_name, &img_width, &img_height, &img_bpp, 4);

    if (img_data)
    {
        GLenum type = (img_bpp == 4) ? GL_RGBA : GL_RGB;
        _width = img_width;
        _height = img_height;
        _bpp = img_bpp;
		_fileName = (char*)malloc(strlen(file_name) + 1);
		strcpy(_fileName, file_name);

		//only 32bit images (for now)
		type = GL_RGBA;
		_bpp = 4;

        glGenTextures(1, &_textureId);
        glBindTexture(GL_TEXTURE_2D, _textureId);

        //edge
        if (flags & GLPLUS_TEXTURE_EDGE)
        {
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        }
        else if (flags & GLPLUS_TEXTURE_BORDER)
        {
            float c[4] = {1,1,1,1};
            glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, c);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
        }

        //filter
        if (flags & GLPLUS_TEXTURE_NEAREST)
        {
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        }
        else if (flags & GLPLUS_TEXTURE_LINEAR)
        {
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        }
        else
        {
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        }

        //color key
		#if 0
        if (flags & GLPLUS_TEXTURE_COLORKEY)
        {
            img->replacePixels(ckey, Color::Transparent);
        }
		#endif

        //mipmaps
        if (flags & GLPLUS_TEXTURE_NOMIPMAPS)
        {
            glTexImage2D(GL_TEXTURE_2D, 0, _bpp, _width, _height, 0,
                         type, GL_UNSIGNED_BYTE, img_data);
        }
        else
        {
            gluBuild2DMipmaps(GL_TEXTURE_2D, _bpp, _width, _height,
                              type, GL_UNSIGNED_BYTE, img_data);
        }
    }
	else
	{
		_textureId = 0;
		_width = 0;
		_height = 0;
		_bpp = 0;
		_fileName = NULL;
        printf("%s:%d: error: Loading texture '%s'\n", __FILE__, __LINE__, file_name);
	}
}
Beispiel #27
0
void initShadersVAOS(){

	// White color
	glClearColor(0.0, 0.0, 0.0, 0.0);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);

	/* Initialize the vertex shader (generate, load, compile and check errors) */
		loadFile("vertex.glsl", vertexShaderCode);
		const char* vertexSource = vertexShaderCode.c_str();
		vertexShader = glCreateShader(GL_VERTEX_SHADER);
		glShaderSource(vertexShader, 1, &vertexSource, NULL);
		glCompileShader(vertexShader);
		GLint status = 0;
		glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
		if(status != GL_TRUE)
		{
			char buffer[512];
			glGetShaderInfoLog(vertexShader, 512, NULL, buffer);
			std::cout << "Error while compiling the vertex shader: " << std::endl << buffer << std::endl;
		}

		/* Initialize the fragment shader (generate, load, compile and check errors) */
		loadFile("fragment.glsl", fragmentShaderCode);
		const char* fragmentSource = fragmentShaderCode.c_str();
		fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
		glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
		glCompileShader(fragmentShader);
		status = 0;
		glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
		if(status != GL_TRUE)
		{
			char buffer[512];
			glGetShaderInfoLog(fragmentShader, 512, NULL, buffer);
			std::cout << "Error while compiling the fragment shader: " << std::endl << buffer << std::endl;
		}

		/****************************************** Perlin Data VAO*********************************************/

//		glGenBuffers(1, &perlinVbo);
//		glBindBuffer(GL_ARRAY_BUFFER, perlinVbo);
//		glBufferData(GL_ARRAY_BUFFER, sizeof(double) * 3 * IslandWidth * IslandHeight, perlinArray, GL_STATIC_DRAW);
//
//		/* Initialize the Vertex Buffer Object for the colors of the vertices */
//		glGenBuffers(1, &perlinColorsVbo);
//		glBindBuffer(GL_ARRAY_BUFFER, perlinColorsVbo);
//		glBufferData(GL_ARRAY_BUFFER, sizeof(perlinColors), perlinColors, GL_STATIC_DRAW);
//
//		/* Define the Vertex Array Object for the points */
//		glGenVertexArrays(1, &perlinVao);
//		glBindVertexArray(perlinVao);
//		glBindBuffer(GL_ARRAY_BUFFER, perlinVbo);
//		glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
//		glBindBuffer(GL_ARRAY_BUFFER, perlinColorsVbo);
//		glVertexAttribPointer(1, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
//		glEnableVertexAttribArray(0);
//		glEnableVertexAttribArray(1);

		/******************************************Points Data VAO*********************************************/
//		glGenBuffers(1, &pointsVbo);
//		glBindBuffer(GL_ARRAY_BUFFER, pointsVbo);
//		glBufferData(GL_ARRAY_BUFFER, numberofPoints * 3 * sizeof(double), setPoints, GL_STATIC_DRAW);
//
//		/* Initialize the Vertex Buffer Object for the colors of the vertices */
//		glGenBuffers(1, &pointsColorsVbo);
//		glBindBuffer(GL_ARRAY_BUFFER, pointsColorsVbo);
//		glBufferData(GL_ARRAY_BUFFER, sizeof(setPointsColors), setPointsColors, GL_STATIC_DRAW);
//
//		/* Define the Vertex Array Object for the points */
//		glGenVertexArrays(1, &pointsVao);
//		glBindVertexArray(pointsVao);
//		glBindBuffer(GL_ARRAY_BUFFER, pointsVbo);
//		glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
//		glBindBuffer(GL_ARRAY_BUFFER, pointsColorsVbo);
//		glVertexAttribPointer(1, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
//		glEnableVertexAttribArray(0);
//		glEnableVertexAttribArray(1);


		/******************************************Circle Data VAO*********************************************/
//		/* Initialize the Vertex Buffer Object for the location of the vertices */
//		glGenBuffers(1, &vertexVbo);
//		glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
//		glBufferData(GL_ARRAY_BUFFER, sizeof(double) * circlePointCt * 3, circleVertices, GL_STATIC_DRAW);
//
//		/* Initialize the Vertex Buffer Object for the colors of the vertices */
//		glGenBuffers(1, &colorVbo);
//		glBindBuffer(GL_ARRAY_BUFFER, colorVbo);
//		glBufferData(GL_ARRAY_BUFFER, sizeof(double) * circlePointCt * 3, NULL, GL_STATIC_DRAW);
//
//		/* Define the Vertex Array Object for the circles */
//		glGenVertexArrays(1, &circlesVao);
//		glBindVertexArray(circlesVao);
//		glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
//		glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
//		glBindBuffer(GL_ARRAY_BUFFER, colorVbo);
//		glVertexAttribPointer(1, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
//		glEnableVertexAttribArray(0);
//		glEnableVertexAttribArray(1);


		/******************************************Voronoi Data VAO*********************************************/
		glGenBuffers(1, &voronoiVbo);
		glBindBuffer(GL_ARRAY_BUFFER, voronoiVbo);
//		glBufferData(GL_ARRAY_BUFFER, sizeof(voronoiPoints), voronoiPoints, GL_STATIC_DRAW);
		glBufferData(GL_ARRAY_BUFFER, sizeof(double) * idx, voronoiVertices, GL_STATIC_DRAW);

		/* Initialize the Vertex Buffer Object for the colors of the vertices */
		glGenBuffers(1, &voronoiColorsVbo);
		glBindBuffer(GL_ARRAY_BUFFER, voronoiColorsVbo);
//		glBufferData(GL_ARRAY_BUFFER, sizeof(voronoiColors), voronoiColors, GL_STATIC_DRAW);
		glBufferData(GL_ARRAY_BUFFER, sizeof(double) * idx, voronoiColors, GL_STATIC_DRAW);

		/* Define the Vertex Array Object for the voronoi */
		glGenVertexArrays(1, &voronoiVao);
		glBindVertexArray(voronoiVao);
		glBindBuffer(GL_ARRAY_BUFFER, voronoiVbo);
		glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
		glBindBuffer(GL_ARRAY_BUFFER, voronoiColorsVbo);
		glVertexAttribPointer(1, 3, GL_DOUBLE, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray(0);
		glEnableVertexAttribArray(1);



		/****************************************** Load textures ********************************************/

		// texture coordinates
		glGenBuffers(1, &coordsVbo);
		glBindBuffer(GL_ARRAY_BUFFER, coordsVbo);
		glBufferData(GL_ARRAY_BUFFER, sizeof(double) * (idx / 3) * 2, voronoiCoords, GL_STATIC_DRAW);

//		/* Initialize the Vertex Buffer Object for the normal vectors */
		glGenBuffers(1, &normalsVbo);
		glBindBuffer(GL_ARRAY_BUFFER, normalsVbo);
		glBufferData(GL_ARRAY_BUFFER, sizeof(double) * idx * 3, voronoiNormals, GL_STATIC_DRAW);


		/* Set the texture of the model */
		textureData = stbi_load(textureFile, &textureWidth, &textureHeight, &textureComp, STBI_rgb);
		GLuint texture;
		glGenTextures(1, &texture);
		glBindTexture(GL_TEXTURE_2D, texture);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

		/* Set the normal map of the model */
		normalData = stbi_load(normalFile, &normalWidth, &normalHeight, &normalComp, STBI_rgb);
		GLuint normal;
		glGenTextures(1, &normal);
		glBindTexture(GL_TEXTURE_2D, normal);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, normalWidth, normalHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, normalData);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);


		glBindBuffer(GL_ARRAY_BUFFER, coordsVbo);
		glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, NULL);
		glBindBuffer(GL_ARRAY_BUFFER, normalsVbo);
		glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray(2);
		glEnableVertexAttribArray(3);

		/* Initialize the shader program */
		shaderProgram = glCreateProgram();
		glAttachShader(shaderProgram, vertexShader);
		glAttachShader(shaderProgram, fragmentShader);
		glBindAttribLocation(shaderProgram, 0, "inPoint");
		glBindAttribLocation(shaderProgram, 1, "inColor");
		glBindAttribLocation(shaderProgram, 2, "inCoords");
		glBindAttribLocation(shaderProgram, 3, "inNormal");
		glLinkProgram(shaderProgram);

		// Send texture
		/* Set information for the texture locations */
		glUniform1i(textureDataLocation, 0);
		glUniform1i(normalDataLocation, 1);

		/* Bind textures */
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texture);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, normal);

		// MVP Matrices
		/* Get the location of the uniform variables */
		modelMatrixLocation = glGetUniformLocation(shaderProgram, "modelMatrix");
		viewMatrixLocation = glGetUniformLocation(shaderProgram, "viewMatrix");
		projMatrixLocation = glGetUniformLocation(shaderProgram, "projMatrix");
		perlinLocation = glGetUniformLocation(shaderProgram, "perlinData");
		textureDataLocation = glGetUniformLocation(shaderProgram, "textureData");
		normalDataLocation = glGetUniformLocation(shaderProgram, "normalData");


//		glMatrixMode(GL_PROJECTION);
//		glLoadIdentity();
//		gluOrtho2D(0.0, IslandWidth, IslandHeight, 0.0);

}
Beispiel #28
0
int main(int arg_c, char *ppArgs[])
{
    printf("jpge/jpgd example app\n");

    // Parse command line.
    bool run_exhausive_test = false;
    bool test_memory_compression = false;
    int subsampling = -1;
    bool use_jpgd = true;

    int arg_index = 1;
    while ((arg_index < arg_c) && (ppArgs[arg_index][0] == '-')) {
        switch (tolower(ppArgs[arg_index][1])) {
        case 'g':
            strcpy_s(s_log_filename, sizeof(s_log_filename), &ppArgs[arg_index][2]);
            break;
        case 'x':
            run_exhausive_test = true;
            break;
        case 'm':
            test_memory_compression = true;
            break;
        case 'o': // dropped option
            break;
        case 'l':
            if (strcasecmp(&ppArgs[arg_index][1], "luma") == 0)
                subsampling = jpge::Y_ONLY;
            else {
                log_printf("Unrecognized option: %s\n", ppArgs[arg_index]);
                return EXIT_FAILURE;
            }
            break;
        case 'h':
            if (strcasecmp(&ppArgs[arg_index][1], "h1v1") == 0)
                subsampling = jpge::H1V1;
            else if (strcasecmp(&ppArgs[arg_index][1], "h2v1") == 0)
                subsampling = jpge::H2V1;
            else if (strcasecmp(&ppArgs[arg_index][1], "h2v2") == 0)
                subsampling = jpge::H2V2;
            else {
                log_printf("Unrecognized subsampling: %s\n", ppArgs[arg_index]);
                return EXIT_FAILURE;
            }
            break;
        case 's': {
            use_jpgd = false;
            break;
        }
        default:
            log_printf("Unrecognized option: %s\n", ppArgs[arg_index]);
            return EXIT_FAILURE;
        }
        arg_index++;
    }

    if (run_exhausive_test) {
        if ((arg_c - arg_index) < 1) {
            log_printf("Not enough parameters (expected source file)\n");
            return print_usage();
        }

        const char *pSrc_filename = ppArgs[arg_index++];
        return exhausive_compression_test(pSrc_filename, use_jpgd);
    }

    // Test jpge
    if ((arg_c - arg_index) < 3) {
        log_printf("Not enough parameters (expected source file, dest file, quality factor to follow options)\n");
        return print_usage();
    }

    const char *pSrc_filename = ppArgs[arg_index++];
    const char *pDst_filename = ppArgs[arg_index++];

    float quality_factor = atof(ppArgs[arg_index++]);
    if ((quality_factor < 1) || (quality_factor > 100)) {
        log_printf("Quality factor must range from 1-100!\n");
        return EXIT_FAILURE;
    }

    // Load the source image.
    const int req_comps = 3; // request RGB image
    int width = 0, height = 0, actual_comps = 0;
    uint8 *pImage_data = stbi_load(pSrc_filename, &width, &height, &actual_comps, req_comps);
    if (!pImage_data) {
        log_printf("Failed loading file \"%s\"!\n", pSrc_filename);
        return EXIT_FAILURE;
    }

    log_printf("Source file: \"%s\", image resolution: %ix%i, actual comps: %i\n", pSrc_filename, width, height, actual_comps);

    // Fill in the compression parameter structure.
    jpge::params params;
    params.m_quality = quality_factor;
    params.m_subsampling = (subsampling < 0) ? ((actual_comps == 1) ? jpge::Y_ONLY : jpge::H2V2) : static_cast<jpge::subsampling_t>(subsampling);

    // Now create the JPEG file.
    if (test_memory_compression) {
        int buf_size = width * height * 3; // allocate a buffer that's hopefully big enough (this is way overkill for jpeg)
        if (buf_size < 1024) buf_size = 1024;
        void *pBuf = malloc(buf_size);
        printf("jpge subsampling: %d", (int)params.m_subsampling);

        if (!jpge::compress_image_to_jpeg_file_in_memory(pBuf, buf_size, width, height, req_comps, pImage_data, params)) {
            log_printf("Failed creating JPEG data!\n");
            return EXIT_FAILURE;
        }

        FILE *pFile = fopen(pDst_filename, "wb");
        if (!pFile) {
            log_printf("Failed creating file \"%s\"!\n", pDst_filename);
            return EXIT_FAILURE;
        }

        if (fwrite(pBuf, buf_size, 1, pFile) != 1) {
            log_printf("Failed writing to output file!\n");
            return EXIT_FAILURE;
        }

        if (fclose(pFile) == EOF) {
            log_printf("Failed writing to output file!\n");
            return EXIT_FAILURE;
        }
    } else {

        if (!jpge::compress_image_to_jpeg_file(pDst_filename, width, height, req_comps, pImage_data, params)) {
            log_printf("Failed writing to output file!\n");
            return EXIT_FAILURE;
        }
    }

    const long comp_file_size = get_file_size(pDst_filename);
    const uint total_pixels = width * height;
    log_printf("Compressed file size: %u, bits/pixel: %3.3f\n", comp_file_size, (comp_file_size * 8.0f) / total_pixels);

    // Now try loading the JPEG file using jpgd or stbi_image's JPEG decompressor.
    int uncomp_width = 0, uncomp_height = 0, uncomp_actual_comps = 0, uncomp_req_comps = 3;

    uint8 *pUncomp_image_data;
    if (use_jpgd)
        pUncomp_image_data = jpgd::decompress_jpeg_image_from_file(pDst_filename, &uncomp_width, &uncomp_height, &uncomp_actual_comps, uncomp_req_comps);
    else
        pUncomp_image_data = stbi_load(pDst_filename, &uncomp_width, &uncomp_height, &uncomp_actual_comps, uncomp_req_comps);

    if (!pUncomp_image_data) {
        log_printf("Failed loading compressed image file \"%s\"!\n", pDst_filename);
        return EXIT_FAILURE;
    }

    if ((uncomp_width != width) || (uncomp_height != height)) {
        log_printf("Loaded JPEG file has a different resolution than the original file!\n");
        return EXIT_FAILURE;
    }

    // Diff the original and compressed images.
    image_compare_results results;
    image_compare(results, width, height, pImage_data, req_comps, pUncomp_image_data, uncomp_req_comps, (params.m_subsampling == jpge::Y_ONLY) || (actual_comps == 1) || (uncomp_actual_comps == 1));
    log_printf("Error Max: %f, Mean: %f, Mean^2: %f, RMSE: %f, PSNR: %f\n", results.max_err, results.mean, results.mean_squared, results.root_mean_squared, results.peak_snr);

    if (results.root_mean_squared > 40) {
        return EXIT_FAILURE;
    }
    log_printf("Success.\n");

    return EXIT_SUCCESS;
}
Beispiel #29
0
// Simple exhaustive test. Tries compressing/decompressing image using all supported quality, subsampling, and Huffman optimization settings.
static int exhausive_compression_test(const char *pSrc_filename, bool use_jpgd)
{
    int status = EXIT_SUCCESS;

    // Load the source image.
    const int req_comps = 3; // request RGB image
    int width = 0, height = 0, actual_comps = 0;
    uint8 *pImage_data = stbi_load(pSrc_filename, &width, &height, &actual_comps, req_comps);
    if (!pImage_data) {
        log_printf("Failed loading file \"%s\"!\n", pSrc_filename);
        return EXIT_FAILURE;
    }

    log_printf("Source file: \"%s\" Image resolution: %ix%i Actual comps: %i\n", pSrc_filename, width, height, actual_comps);

    int orig_buf_size = width * height * 3; // allocate a buffer that's hopefully big enough (this is way overkill for jpeg)
    if (orig_buf_size < 1024) orig_buf_size = 1024;
    void *pBuf = malloc(orig_buf_size);

    uint8 *pUncomp_image_data = NULL;

    double max_err = 0, bpq_sum=0; int bpq_num=0;
    double lowest_psnr = 9e+9;
    double threshold_psnr = 9e+9;
    double threshold_max_err = 0.0f;

    image_compare_results prev_results;

    for (uint quality_factor = 12; quality_factor <= 100; quality_factor+=11) {
        for (uint subsampling = 0; subsampling <= jpge::H2V2; subsampling++) {
                // Fill in the compression parameter structure.
                jpge::params params;
                params.m_quality = quality_factor;
                params.m_subsampling = static_cast<jpge::subsampling_t>(subsampling);

                int comp_size = orig_buf_size;
                if (!jpge::compress_image_to_jpeg_file_in_memory(pBuf, comp_size, width, height, req_comps, pImage_data, params)) {
                    status = EXIT_FAILURE;
                    goto failure;
                }

                int uncomp_width = 0, uncomp_height = 0, uncomp_actual_comps = 0, uncomp_req_comps = 3;
                free(pUncomp_image_data);
                if (use_jpgd)
                    pUncomp_image_data = jpgd::decompress_jpeg_image_from_memory((const stbi_uc *)pBuf, comp_size, &uncomp_width, &uncomp_height, &uncomp_actual_comps, uncomp_req_comps);
                else
                    pUncomp_image_data = stbi_load_from_memory((const stbi_uc *)pBuf, comp_size, &uncomp_width, &uncomp_height, &uncomp_actual_comps, uncomp_req_comps);
                if (!pUncomp_image_data) {
                    status = EXIT_FAILURE;
                    goto failure;
                }

                if ((uncomp_width != width) || (uncomp_height != height)) {
                    status = EXIT_FAILURE;
                    goto failure;
                }

                image_compare_results results;
                image_compare(results, width, height, pImage_data, req_comps, pUncomp_image_data, uncomp_req_comps, (params.m_subsampling == jpge::Y_ONLY) || (actual_comps == 1) || (uncomp_actual_comps == 1));
                double bpq = comp_size*results.mean/results.peak_snr/100;
                log_printf("Q: %3u, S%u, Size: %7u, Error Max:% 5.0f, Mean:% 6.2f, RMSE:%6.2f, PSNR:%7.3f, BPQ:%6.0f\n",
                           quality_factor, subsampling, comp_size, results.max_err, results.mean, results.root_mean_squared, results.peak_snr, bpq);
                if (results.max_err > max_err) max_err = results.max_err;
                if (results.peak_snr < lowest_psnr) lowest_psnr = results.peak_snr;
                if (quality_factor < 99 && quality_factor > 35) {
                    bpq_sum += bpq;
                    bpq_num++;
                }

                if (quality_factor == 12) {
                    if (results.peak_snr < threshold_psnr)
                        threshold_psnr = results.peak_snr;
                    if (results.max_err > threshold_max_err)
                        threshold_max_err = results.max_err;
                } else {
                    // Couple empirically determined tests - worked OK on my test data set.
                    if ((results.peak_snr < (threshold_psnr - 3.0f)) || (results.peak_snr < 6.0f)) {
                        status = EXIT_FAILURE;
                        goto failure;
                    }
                }

                prev_results = results;
        }
    }

    log_printf("Max error: %.0f Lowest PSNR: %.3f, BPQ: %.0f\n", max_err, lowest_psnr, bpq_sum/bpq_num);

failure:
    free(pImage_data);
    free(pBuf);
    free(pUncomp_image_data);

    log_printf((status == EXIT_SUCCESS) ? "Success.\n" : "Exhaustive test failed!\n");
    return status;
}
Beispiel #30
-1
bool ImageLoader::loadImageFromFile(const std::string& filename, std::vector<Uint8>& pixels, Vector2u& size)
{
    // Clear the array (just in case)
    pixels.clear();

    // Load the image and get a pointer to the pixels in memory
    int width = 0;
    int height = 0;
    int channels = 0;
    unsigned char* ptr = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);

    if (ptr)
    {
        // Assign the image properties
        size.x = width;
        size.y = height;

        if (width && height)
        {
            // Copy the loaded pixels to the pixel buffer
            pixels.resize(width * height * 4);
            memcpy(&pixels[0], ptr, pixels.size());
        }

        // Free the loaded pixels (they are now in our own pixel buffer)
        stbi_image_free(ptr);

        return true;
    }
    else
    {
        // Error, failed to load the image
        err() << "Failed to load image \"" << filename << "\". Reason: " << stbi_failure_reason() << std::endl;

        return false;
    }
}