Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Мультимедия, OpenGL/DirectX > glutSoliSphere texture


Автор: kostay 14.9.2008, 22:56
вот так загружаем текстуру
Код

GLuint _textureId;

GLuint loadTexture(Image* image) {
    GLuint textureId;
    glGenTextures(1, &textureId); //Make room for our texture
    glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
    //Map the image to the texture
    glTexImage2D(GL_TEXTURE_2D,                //Always GL_TEXTURE_2D
                 0,                            //0 for now
                 GL_RGB,                       //Format OpenGL uses for image
                 image->width, image->height,  //Width and height
                 0,                            //The border of the image
                 GL_RGB, //GL_RGB, because pixels are stored in RGB format
                 GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
                                   //as unsigned numbers
                 image->pixels);               //The actual pixel data
    return textureId; //Returns the id of the texture
}

Код

#include <assert.h>
#include <fstream>

#include "Image.h"

using namespace std;

Image::Image(char* ps, int w, int h) : pixels(ps), width(w), height(h) {
    
}

Image::~Image() {
    delete[] pixels;
}

namespace {
    //Converts a four-character array to an integer, using little-endian form
    int toInt(const char* bytes) {
        return (int)(((unsigned char)bytes[3] << 24) |
                     ((unsigned char)bytes[2] << 16) |
                     ((unsigned char)bytes[1] << 8) |
                     (unsigned char)bytes[0]);
    }
    
    //Converts a two-character array to a short, using little-endian form
    short toShort(const char* bytes) {
        return (short)(((unsigned char)bytes[1] << 8) |
                       (unsigned char)bytes[0]);
    }
    
    //Reads the next four bytes as an integer, using little-endian form
    int readInt(ifstream &input) {
        char buffer[4];
        input.read(buffer, 4);
        return toInt(buffer);
    }
    
    //Reads the next two bytes as a short, using little-endian form
    short readShort(ifstream &input) {
        char buffer[2];
        input.read(buffer, 2);
        return toShort(buffer);
    }
    
    //Just like auto_ptr, but for arrays
    template<class T>
    class auto_array {
        private:
            T* array;
            mutable bool isReleased;
        public:
            explicit auto_array(T* array_ = NULL) :
                array(array_), isReleased(false) {
            }
            
            auto_array(const auto_array<T> &aarray) {
                array = aarray.array;
                isReleased = aarray.isReleased;
                aarray.isReleased = true;
            }
            
            ~auto_array() {
                if (!isReleased && array != NULL) {
                    delete[] array;
                }
            }
            
            T* get() const {
                return array;
            }
            
            T &operator*() const {
                return *array;
            }
            
            void operator=(const auto_array<T> &aarray) {
                if (!isReleased && array != NULL) {
                    delete[] array;
                }
                array = aarray.array;
                isReleased = aarray.isReleased;
                aarray.isReleased = true;
            }
            
            T* operator->() const {
                return array;
            }
            
            T* release() {
                isReleased = true;
                return array;
            }
            
            void reset(T* array_ = NULL) {
                if (!isReleased && array != NULL) {
                    delete[] array;
                }
                array = array_;
            }
            
            T* operator+(int i) {
                return array + i;
            }
            
            T &operator[](int i) {
                return array[i];
            }
    };
}

Image* loadBMP(const char* filename) {
    ifstream input;
    input.open(filename, ifstream::binary);
    assert(!input.fail() || !"Could not find file");
    char buffer[2];
    input.read(buffer, 2);
    assert(buffer[0] == 'B' && buffer[1] == 'M' || !"Not a bitmap file");
    input.ignore(8);
    int dataOffset = readInt(input);
    
    //Read the header
    int headerSize = readInt(input);
    int width;
    int height;
    switch(headerSize) {
        case 40:
            //V3
            width = readInt(input);
            height = readInt(input);
            input.ignore(2);
            assert(readShort(input) == 24 || !"Image is not 24 bits per pixel");
            assert(readShort(input) == 0 || !"Image is compressed");
            break;
        case 12:
            //OS/2 V1
            width = readShort(input);
            height = readShort(input);
            input.ignore(2);
            assert(readShort(input) == 24 || !"Image is not 24 bits per pixel");
            break;
        case 64:
            //OS/2 V2
            assert(!"Can't load OS/2 V2 bitmaps");
            break;
        case 108:
            //Windows V4
            assert(!"Can't load Windows V4 bitmaps");
            break;
        case 124:
            //Windows V5
            assert(!"Can't load Windows V5 bitmaps");
            break;
        default:
            assert(!"Unknown bitmap format");
    }
    
    //Read the data
    int bytesPerRow = ((width * 3 + 3) / 4) * 4 - (width * 3 % 4);
    int size = bytesPerRow * height;
    auto_array<char> pixels(new char[size]);
    input.seekg(dataOffset, ios_base::beg);
    input.read(pixels.get(), size);
    
    //Get the data into the right format
    auto_array<char> pixels2(new char[width * height * 3]);
    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x++) {
            for(int c = 0; c < 3; c++) {
                pixels2[3 * (width * y + x) + c] =
                    pixels[bytesPerRow * y + 3 * x + (2 - c)];
            }
        }
    }
    
    input.close();
    return new Image(pixels2.release(), width, height);
}


вот так ставлю её, ставится из бмп только левый нижний пиксел растягивается на весь шар... в 4ом дело?
Код

Image* image = loadBMP("vtr.bmp");
    _textureId = loadTexture(image);
    delete image;

glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, _textureId);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glPushMatrix();
    glTranslated(x,y,0);
    glutSolidSphere (10, 30, 30);
    glPopMatrix();
    glDisable(GL_TEXTURE_2D);

Автор: Rickert 15.9.2008, 01:04
kostay, скрин в студию.

Автор: kostay 15.9.2008, 08:29
да 4то... обы4ный шар, с цветом одного пикселя из бмп файла, сдаётся мне 4то надо както указать размер текстуры

Автор: Rickert 16.9.2008, 03:37
Да мне не шар нужен тот якобы последний пиксель, который растягивается.

Автор: kostay 16.9.2008, 20:39
http://ipicture.ru/Gallery/Viewfull/6891109.html

Автор: Rickert 18.9.2008, 06:39
kostay, вы издеваетесь или ведёте настолько секретную разработку шарика, что не можете нормальный полный скрин окна дать? smile 

Автор: kostay 19.9.2008, 13:07
за4ем... меняю в фотошопе у текстуры левий нижний пихел другим цветом и шар меняется другим цветом... шар обы4ний шар...

вобше помоему мой код полний бред, надо ведь по вершинам указывать как растягивается текстура... вот как ето с glutsloidsphere сделать

Автор: Rickert 20.9.2008, 20:15
kostay, советую самому писать работу с сферой, а не использоватьглут. Там всё зашито - хрен знает что да как.

Автор: bugs 21.9.2008, 09:36
Файл texture.cpp
Код

#include "texture.h"
 
// Конструктор
CTexture::CTexture()
{
    // В конструкторе инициализируем библиотеки IL и ILU.
    // Если этого не сделать, программа будет вываливатся с ошибкой.
    ilInit();
    iluInit();
}
 
// Деструктор
CTexture::~CTexture()
{
}
 
// Функция, непосредственно загружающая текстуру в переданную структуру.
// В функцию передается тип файла, имя файла и указатель на текстуру.
void CTexture::LoadTexture(ILenum FileType, char *filename, TextureImage *texture)
{
    // Просим DevIL загрузить файл
    ilLoad(FileType, filename);
 
    // Проверяем, нет ли ошибок при открытии файла
    int err=ilGetError();
    if(err!=IL_NO_ERROR)
    {
        const char* strError = iluErrorString(err);
        MessageBox(NULL, strError, "Ошибка при загрузке!", MB_OK);
        exit(1);
    }
 
    // Получаем данные текстуры
    texture->width = ilGetInteger(IL_IMAGE_WIDTH);            // Ширина
    texture->height = ilGetInteger(IL_IMAGE_HEIGHT);        // Высота
    texture->bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);        // Байт на пиксель
 
    // Загружаем данные в нашу текстуру
    texture->imageData = ilGetData();
 
    ilEnable(IL_CONV_PAL);
 
    // Тип данных изображения
    unsigned int type = ilGetInteger(IL_IMAGE_FORMAT);
 
    // Генерируем текстуру
    glGenTextures(1, &texture->texID);
 
    // Привязываем данные текстуры к ID
    glBindTexture(GL_TEXTURE_2D,texture->texID);
 
    // биндим мип-мапы
    gluBuild2DMipmaps(GL_TEXTURE_2D, texture->bpp, texture->width,
        texture->height, type, GL_UNSIGNED_BYTE, texture->imageData);
 
    // Устанавливаем качество текстур
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
 
void CTexture::FreeTexture(TextureImage *texture)
{
 
}



Файл texture.h
Код

#ifndef __TEXTURE_H
#define __TEXTURE_H
 
//#include "main.h"
// Хидеры библиотеки DevIL
#include <devil\il.h>
#include <devil\ilu.h>
 
// Создадим структуру TextureImage для хранения данных текстуры.
typedef struct TextureImage
{
    GLubyte *imageData;        // Данные текстуры
    GLuint    bpp;            // Байт на пиксел
    GLuint width,height;        // Высота и ширина
    GLuint texID;            // ID текстуры
}TextureImage;
 
 
// Класс текстур. Загрузка и высвобождение.
class CTexture{
public:
 
    CTexture();
    ~CTexture();
 
    // Собственно, класс наш делает немного - в нём только 2 функции - 
    // загрузка и освобождение текстур =)
    void LoadTexture(ILenum FileType, char *filename, TextureImage *texture);
    void FreeTexture(TextureImage *texture);
};
 
 
#endif



Загрузка текстуры:
Код

void TForm1::LoadGLTextures()                                                                        // загрузить изображения и преобразовать в текстуры
{
        //DevIL
        Texture[0] = new CTexture();
        Texture[0]->LoadTexture(IL_JPG, "t_001.jpg", &Textures[0]);
        

}



Объявление текстуры:
Код

CTexture *Texture[3];
TextureImage Textures[3];


Рисуем сферу и накладываем текстуру:
Код

GLUquadricObj *obj;
                        glBindTexture(GL_TEXTURE_2D, Textures[1].texID);
                        obj=gluNewQuadric();
                        gluQuadricTexture(obj, GL_TRUE);
                 gluQuadricDrawStyle(obj, GLU_FILL);
                 glPushMatrix();
                                glRotatef(-90,1.0f,0.0f,0.0f);
                                glRotatef(23,0.0f,1.0f,0.0f);
                                glRotatef(xrot,0.0f,0.0f,1.0f);
                     gluSphere(obj, radius, 26, 26);
                     gluDeleteQuadric(obj);
                     glColor3ub(0, 0, 0);
                 glPopMatrix(); 



В данном примере для загрузки рисунка я использовал  библиотеки http://openil.sourceforge.net/.

Добавлено через 10 минут и 39 секунд
Забыл: smile 

Подключение
Код

#include <DevIL\il.h>
#include "texture.h"
#include "texture.cpp"

 

а также
Код

#pragma comment(lib, "devil.lib")
#pragma comment(lib, "ilu.lib")
#pragma comment(lib, "ilut.lib")


Вот вроде всё!

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)