TextureDataLoadStore.cc 26.1 KB
Newer Older
1
2
3
4
5
/***********************************************************************
 * Copyright 2011-2012 Computer Graphics Group RWTH Aachen University. *
 * All rights reserved.                                                *
 * Distributed under the terms of the MIT License (see LICENSE.TXT).   *
 **********************************************************************/
6

Robert Menzel's avatar
Robert Menzel committed
7
#include <ACGL/OpenGL/Data/TextureDataLoadStore.hh>
8
#include <ACGL/OpenGL/Tools.hh>
9
10
#include <ACGL/Utils/FileHelpers.hh>
#include <ACGL/Utils/StringHelpers.hh>
Robert Menzel's avatar
Robert Menzel committed
11
#include <ACGL/Utils/Memory.hh>
12
13
14
15
16

// for the screenshot function:
#include <ACGL/OpenGL/Objects/FrameBufferObject.hh>
#include <cstdio>
#include <ctime>
17

18
#include <stdexcept>
19
#include <fstream>
Robert Menzel's avatar
Robert Menzel committed
20
#include "lodepng/lodepng.h"
21
#include "rgbe/rgbe.hh"
22

23
24
25
#ifdef ACGL_COMPILE_WITH_QT
#include <QImage>
#include <QGLWidget>
Robert Menzel's avatar
Robert Menzel committed
26
27
#include <QByteArray>
#include <QImageWriter>
28
29
30
31
32
#elif ACGL_COMPILE_WITH_QT5
#include <QImage>
#include <QtOpenGL/QGLWidget>
#include <QByteArray>
#include <QImageWriter>
33
34
#endif

35
36
37
38
39
40
41
42
43
//
// OpenEXR:
// Only compile with OpenEXR support if explicitly wanted so.
// Note that the application has to be linked to libIlmImf and libIex and the include path has to be set.
// (in your CMakeLists.txt add:
//   ADD_DEFINITIONS(-DACGL_BUILD_WITH_EXR)
//   ADD_DEFINITIONS(-I"/usr/include/OpenEXR/")
//   SET(LIBRARIES ${LIBRARIES} "-lIlmImf -lIex")
//
44
45
46
47
48
49
50
#ifdef ACGL_BUILD_WITH_EXR
//#include <ImfInputFile.h>
#include <ImfRgbaFile.h>
using namespace Imf;
using namespace Imath;
#endif

51
52
53
using namespace ACGL;
using namespace ACGL::OpenGL;
using namespace ACGL::Utils;
54
using namespace ACGL::Utils::StringHelpers;
55

Robert Menzel's avatar
Robert Menzel committed
56
57
58
namespace ACGL{
namespace OpenGL{

59
60
61
///////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                               generic load/save
///////////////////////////////////////////////////////////////////////////////////////////////////
62

63
64
65
66
std::map<std::string,TextureLoadFuncPtr> textureLoadFunctions = std::map<std::string,TextureLoadFuncPtr>();

void registerTextureLoadFunction(std::vector<std::string> _endings, TextureLoadFuncPtr _function)
{
Robert Menzel's avatar
Robert Menzel committed
67
    if(_function != NULL)
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    {
        std::vector<std::string>::iterator n = _endings.end();
        for(std::vector<std::string>::iterator i = _endings.begin() ; i != n ; i++ )
        {
            textureLoadFunctions.insert( std::pair<std::string,TextureLoadFuncPtr>(*i ,_function) );
        }
    }
}

void unregisterTextureLoadFunction(TextureLoadFuncPtr _function)
{
    std::map<std::string,TextureLoadFuncPtr>::iterator n = textureLoadFunctions.end();
    for(std::map<std::string,TextureLoadFuncPtr>::iterator i = textureLoadFunctions.begin() ; i != n ; i++)
    {

        if(i->second == _function)
            textureLoadFunctions.erase(i);
    }
}

88
SharedTextureData loadTextureData(const std::string &_filename, ColorSpace _colorSpace)
89
90
{
    // lower case file ending:
91
    std::string fileEnding = getFileEnding( _filename );
92

93
94
95
    SharedTextureData textureData;

    if(textureLoadFunctions.find(fileEnding) != textureLoadFunctions.end()) {
96
        textureData = textureLoadFunctions[fileEnding](_filename, _colorSpace);
97
    } else if (fileEnding == "png") {
98
        textureData = loadTextureDataFromLodepng( _filename, _colorSpace );
99
    } else if (fileEnding == "hdr") {
100
        textureData = loadTextureDataFromRGBE( _filename, _colorSpace );
101
    } else if (fileEnding == "exr") {
102
        textureData = loadTextureDataFromEXR( _filename, _colorSpace );
103
    } else if (fileEnding == "ppm") {
104
        textureData = loadTextureDataFromPNM( _filename, _colorSpace );
105
106
107
108
109
110
    }
#ifdef ACGL_COMPILE_WITH_QT
    else if (   fileEnding == "bmp" || fileEnding == "jpg" || fileEnding == "jpeg"
             || fileEnding == "png" || fileEnding == "pbm" || fileEnding == "ppm"
             || fileEnding == "tif" || fileEnding == "tiff"|| fileEnding == "xbm"
             || fileEnding == "xpm" || fileEnding == "pgm") {
111
        textureData = loadTextureDataFromQT( _filename, _colorSpace );
112
113
114
    }
#endif
    else {
115
        error() << "texture file format of " << _filename << " not supported" << std::endl;
116
117
    }

118
    return textureData;
119
}
120

121
122
123
bool saveTextureData(const SharedTextureData &_textureData, const std::string &_filename)
{
    // lower case file ending:
124
    std::string fileEnding = getFileEnding( _filename );
125

126
127
    if (fileEnding == "png") {
        return saveTextureDataToLodepng( _textureData, _filename );
128
    }
129
130
131
132
133
134
135
136
137
138
#ifdef ACGL_COMPILE_WITH_QT
    else if (   fileEnding == "bmp" || fileEnding == "jpg" || fileEnding == "jpeg"
             || fileEnding == "png" || fileEnding == "ppm"
             || fileEnding == "tif" || fileEnding == "tiff"|| fileEnding == "xbm"
             || fileEnding == "xpm") {
        return saveTextureDataToQT( _textureData, _filename );
    }
#endif
    else if (fileEnding == "ppm") {
        return saveTextureDataToPPM( _textureData, _filename );
139
140
    } else if (fileEnding == "raw") {
        return saveTextureDataToRAW( _textureData, _filename );
141
    } else {
142
        error() << "texture file format of " << _filename << " not supported" << std::endl;
143
144
    }

145
146
    return false;
}
147

148
149
150
151
152
153
bool saveScreenshot(const std::string& _fileName)
{
    ACGL::OpenGL::SharedTextureData screenShot = FrameBufferObject::getImageData();
    bool success = ACGL::OpenGL::saveTextureData( screenShot, _fileName );
    return success;
}
154

155
156

bool saveScreenshotWithDate(const std::string& _prefix, const std::string& _fileEnding )
157
158
159
{
    time_t rawtime;
    time( &rawtime );
160

161
162
163
    char timestring[30];
    strftime( timestring, 30, "_%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) );

Robert Menzel's avatar
Robert Menzel committed
164
165
166
    static int i = 0;
    i++;

167
    std::string filename = _prefix + timestring + "_" + ACGL::Utils::StringHelpers::toString(i) + "." + _fileEnding;
Robert Menzel's avatar
Robert Menzel committed
168

169
    return saveScreenshot(filename);
170
}
Robert Menzel's avatar
Robert Menzel committed
171

172
173
174
///////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                           library specific load
///////////////////////////////////////////////////////////////////////////////////////////////////
Robert Menzel's avatar
Robert Menzel committed
175

176
177
178
179
180
181
182
183
184
185
struct LodepngFile
{
public:
    LodepngFile(const std::string& _filename)
    {
        unsigned int errorCode = lodepng_load_file(&mData, &mSize, _filename.c_str());
        if(errorCode)
        {
            std::stringstream errorMsg;
            errorMsg << "LodePNG error while loading file " << _filename << " - " << errorCode << ": " << lodepng_error_text(errorCode);
Robert Menzel's avatar
Robert Menzel committed
186
            mData = NULL;
187
188
189
190
191
192
193
194
195
196
197
198
199
            throw std::runtime_error(errorMsg.str());
        }
    }

    ~LodepngFile()
    {
        free(mData);
    }

    unsigned char* mData;
    size_t mSize;
};

200
SharedTextureData loadTextureDataFromLodepng(const std::string &_filename, ColorSpace _colorSpace)
Robert Menzel's avatar
Robert Menzel committed
201
202
203
204
205
206
207
208
209
210
{
    SharedTextureData data;

    unsigned int errorCode;
    unsigned int width, height;
    LodePNGState state;

    // Load the PNG file from disk
    lodepng_state_init(&state);

211
    try
Robert Menzel's avatar
Robert Menzel committed
212
    {
213
        LodepngFile lodepngFile(_filename);
Robert Menzel's avatar
Robert Menzel committed
214

215
216
217
218
219
220
221
222
        // Extract metadata (bit depth, color type)
        errorCode = lodepng_inspect(&width, &height, &state, lodepngFile.mData, lodepngFile.mSize);
        if(errorCode)
        {
            std::stringstream errorMsg;
            errorMsg << "LodePNG error " << errorCode << ": " << lodepng_error_text(errorCode);
            throw std::runtime_error(errorMsg.str());
        }
Robert Menzel's avatar
Robert Menzel committed
223

224
225
        unsigned int bitdepth = state.info_png.color.bitdepth;
        LodePNGColorType colorType = state.info_png.color.colortype;
Robert Menzel's avatar
Robert Menzel committed
226

227
228
        unsigned int channels = 0;
        GLenum glFormat = 0;
Robert Menzel's avatar
Robert Menzel committed
229

230
231
232
233
234
        if(colorType == LCT_GREY)       { channels = 1; glFormat = GL_RED;  }
        if(colorType == LCT_GREY_ALPHA) { channels = 2; glFormat = GL_RG;   }
        if(colorType == LCT_RGB)        { channels = 3; glFormat = GL_RGB;  }
        if(colorType == LCT_RGBA)       { channels = 4; glFormat = GL_RGBA; }
        if(colorType == LCT_PALETTE)    { channels = 4; glFormat = GL_RGBA; colorType = LCT_RGBA; } // force LodePNG to convert paletted data to RGBA
Robert Menzel's avatar
Robert Menzel committed
235

236
237
238
        GLenum glType = 0;
        if(bitdepth ==  8) glType = GL_UNSIGNED_BYTE;
        if(bitdepth == 16) glType = GL_UNSIGNED_SHORT;
Robert Menzel's avatar
Robert Menzel committed
239

240
241
242
243
244
245
        if(channels == 0 || glFormat == 0 || glType == 0)
        {
            std::stringstream errorMsg;
            errorMsg << "Could not load " << _filename << ": " << "unsupported bit depth or format";
            throw std::runtime_error(errorMsg.str());
        }
Robert Menzel's avatar
Robert Menzel committed
246

247
        // Decode the image
248
249
        unsigned char* lodepngImage;
        errorCode = lodepng_decode_memory(&lodepngImage, &width, &height, lodepngFile.mData, lodepngFile.mSize, colorType, bitdepth);
250
251
252
253
254
255
        if(errorCode)
        {
            std::stringstream errorMsg;
            errorMsg << "LodePNG error while decoding file " << _filename << " - " << errorCode << ": " << lodepng_error_text(errorCode);
            throw std::runtime_error(errorMsg.str());
        }
256
257
258
259
260
261
        // HOTFIX: TextureData destroys its pointer using delete[], but lodepng uses malloc().
        // As a hotfix, copy lodepngImage data to a memory location allocated using new[].
        unsigned int dataSize = width * height * channels * bitdepth / 8;
        unsigned char* image = new unsigned char[dataSize];
        memcpy(image, lodepngImage, dataSize);
        free(lodepngImage);
Robert Menzel's avatar
Robert Menzel committed
262

263
264
265
        // LodePNG decodes 16 bit PNGs in big endian format ==> Convert
#ifndef ACGL_BIG_ENDIAN
        if(bitdepth == 16)
266
            for(unsigned int i = 0; i < (width * height * channels * 2); i += 2)
267
268
                std::swap(image[i], image[i+1]);
#endif
Robert Menzel's avatar
Robert Menzel committed
269

270
271
272
273
274
275
276
        // Wrap the data in a TextureData object
        data = SharedTextureData(new TextureData());
        data->setData((GLubyte*)image);
        data->setWidth(width);
        data->setHeight(height);
        data->setType(glType);
        data->setFormat(glFormat);
277
        data->setPadding(0); // LodePNG data has no padding
278
        data->setColorSpace(_colorSpace); // no auto-detection
279
280
281
282
283

        // Flip
        data->flipVertically();
    }
    catch(std::runtime_error& error)
Robert Menzel's avatar
Robert Menzel committed
284
    {
285
        ACGL::Utils::error() << error.what() << std::endl;
Robert Menzel's avatar
Robert Menzel committed
286
287
288
289
290
    }

    return data;
}

291
292
293

#ifdef ACGL_COMPILE_WITH_QT
//! loads from the QT library
294
SharedTextureData loadTextureDataFromQT(const std::string& _filename, ColorSpace _colorSpace)
Robert Menzel's avatar
Robert Menzel committed
295
{
Robert Menzel's avatar
Robert Menzel committed
296
    SharedTextureData data = SharedTextureData( new TextureData() );
Robert Menzel's avatar
Robert Menzel committed
297

298
    QImage image = QImage( QString(_filename.c_str()) );
Robert Menzel's avatar
Robert Menzel committed
299

300
301
302
303
304
    if (image.isNull())
    {
        ACGL::Utils::error() << "Loading image " << _filename << " has failed!" << std::endl;
        return data;
    }
Robert Menzel's avatar
Robert Menzel committed
305

306
307
308
309
310
311
    image = QGLWidget::convertToGLFormat(image);
    GLubyte *pImageData = new GLubyte[image.byteCount()];
    memcpy(pImageData, image.bits(), image.byteCount());
    data->setData(   pImageData     );
    data->setWidth(  image.width()  );
    data->setHeight( image.height() );
312
    data->setColorSpace(_colorSpace); // no auto-detection
Robert Menzel's avatar
Robert Menzel committed
313

314
315
316
317
    return data;
}
#endif

318
SharedTextureData loadTextureDataFromRGBE(const std::string& _filename, ColorSpace _colorSpace)
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
{
    SharedTextureData data = SharedTextureData( new TextureData() );

    FILE* f = fopen(_filename.c_str(), "rb");

    int texWidth, texHeight;
    RGBE_ReadHeader(f, &texWidth, &texHeight, NULL);
    GLubyte* tempdata = new GLubyte[ sizeof(GL_FLOAT) * 3 * texWidth * texHeight];
    RGBE_ReadPixels_RLE(f, (float*)tempdata, texWidth, texHeight);
    fclose(f);

    data->setData(   tempdata  );
    data->setHeight( texHeight );
    data->setWidth(  texWidth  );
    data->setFormat( GL_RGB );
    data->setType(   GL_FLOAT  );
335
    data->setColorSpace(_colorSpace); // no auto-detection
336
337
338
339

    return data;
}

340
SharedTextureData loadTextureDataFromEXR(const std::string& _filename, ColorSpace _colorSpace)
341
342
{
#ifndef ACGL_BUILD_WITH_EXR
343
    error() << "can't load EXR file " << _filename << " ACGL was not build with EXR support" << std::endl;
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    return SharedTextureData();
#else
    SharedTextureData data = SharedTextureData( new TextureData() );
    try {
        // see GPU gems 1:
        Imf::RgbaInputFile in( _filename.c_str() );

        Imath::Box2i window = in.dataWindow();

        Imath::V2i dimension( window.max.x - window.min.x +1,
                              window.max.y - window.min.y +1);

        unsigned char *buffer = (unsigned char *) new Imf::Rgba[ dimension.x*dimension.y ];

        int dx = window.min.x;
        int dy = window.min.y;

        in.setFrameBuffer( (Imf::Rgba*)buffer-dx-dy*dimension.x, 1, dimension.x );
        in.readPixels( window.min.y, window.max.y );

        data->setData(   buffer  );
        data->setHeight( dimension.y );
        data->setWidth(  dimension.x  );
        data->setFormat( GL_RGBA );
        data->setType(   GL_HALF_FLOAT  );
369
        data->setColorSpace(_colorSpace); // no auto-detection
370
371
372
373
374
375
376
377
378
    } catch(Iex::BaseExc &e) {
        error() << "EXR loading failed: " << e.what() << std::endl;
        return SharedTextureData();
    }

    return data;
#endif
}

379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
enum loadTextureDataFromPNM_InputDataFormat
{
    PLAIN_TEXT_BITMAP,  // used by P1
    PLAIN_TEXT_DECIMAL, // used by P2 and P3
    BINARY_PACKED,      // used by P4
    BINARY_BYTES,       // used by P5 and P6
    BINARY_WORDS        // used by P5 and P6
};

void loadTextureDataFromPNM_skipWhitespace(std::istream& _in, uint_t _max = std::numeric_limits<std::streamsize>::max())
{
    uint_t skipped = 0;
    while(isspace(_in.peek()) && skipped < _max)
    {
        _in.ignore(1);
        skipped++;
    }
}

std::istream& loadTextureDataFromPNM_filterPNMComments(std::istream& _in)
{
    loadTextureDataFromPNM_skipWhitespace(_in);

    // When the stream starts with a #, throw away all following characters until the next newline
    // TODO: this does not entirely conform to the PNM specs, where # characters may appear anywhere, not just at the beginning of fields
    while(_in.peek() == '#')
    {
        _in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        loadTextureDataFromPNM_skipWhitespace(_in);
    }
    return _in;
}

412
SharedTextureData loadTextureDataFromPNM(const std::string& _filename, ColorSpace _colorSpace)
413
{
Robert Menzel's avatar
Robert Menzel committed
414
    std::ifstream fileStream( _filename.c_str() );
415
416
417
418
419
420

    if (!fileStream.good()) {
        error() << "could not open file " << _filename << std::endl;
        return SharedTextureData();
    }

421
    SharedTextureData textureData = SharedTextureData( new TextureData() );
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535

    // Read the PNM header
    std::string header;
    loadTextureDataFromPNM_filterPNMComments(fileStream) >> header;

    // The header version determines the format of the data
    loadTextureDataFromPNM_InputDataFormat inputDataFormat = BINARY_BYTES; // set it to something to prevent 'may be uninitialized' warnings (which can't occur here)
    uint_t components;
    if     (header == "P1") { components = 1; inputDataFormat = PLAIN_TEXT_BITMAP; }
    else if(header == "P2") { components = 1; inputDataFormat = PLAIN_TEXT_DECIMAL; }
    else if(header == "P3") { components = 3; inputDataFormat = PLAIN_TEXT_DECIMAL; }
    else if(header == "P4") { components = 1; inputDataFormat = BINARY_PACKED; }
    else if(header == "P5") { components = 1; /* the data format will be determined later */ }
    else if(header == "P6") { components = 3; /* the data format will be determined later */ }
    else
    {
        error() << "could not load " << _filename << ": invalid header" << std::endl;
        fileStream.close();
        return SharedTextureData();
    }

    // Read the width and height of the image
    uint_t width, height;
    loadTextureDataFromPNM_filterPNMComments(fileStream) >> width;
    loadTextureDataFromPNM_filterPNMComments(fileStream) >> height;
    if(!fileStream.good() || width == 0 || height == 0)
    {
        error() << "could not load " << _filename << ": invalid image size" << std::endl;
        fileStream.close();
        return SharedTextureData();
    }

    // The max value is only present in the P2, P3, P5, P6 versions of the PNM format
    uint_t maxValue = 1;
    if(header == "P2" || header == "P3" || header == "P5" || header == "P6")
    {
        loadTextureDataFromPNM_filterPNMComments(fileStream) >> maxValue;

        if(!fileStream.good() || maxValue == 0)
        {
            error() << "could not load " << _filename << ": invalid value range" << std::endl;
            fileStream.close();
            return SharedTextureData();
        }
    }

    // The binary formats P5 and P6 use either bytes or words of data for each element, depending on the maxValue
    if(header == "P5" || header == "P6")
    {
        if     (maxValue <   256) { inputDataFormat = BINARY_BYTES; }
        else if(maxValue < 65536) { inputDataFormat = BINARY_WORDS; }
        else
        {
            error() << "could not load " << _filename << ": max value out of bounds" << std::endl;
            fileStream.close();
            return SharedTextureData();
        }
    }

    // If the image data has maxValue of 255 or 1, we return a GL_UNSIGNED_BYTE texture,
    // otherwise the values are normalized and returned as a GL_FLOAT texture
    GLenum outputDataType = GL_FLOAT;
    if(maxValue == 255 || maxValue == 1)
        outputDataType = GL_UNSIGNED_BYTE;

    // The data section is separated by a single whitespace
    loadTextureDataFromPNM_skipWhitespace(fileStream, 1);

    // Now, read in the data
    // No comments (#) are expected during this section
    unsigned char* data = new unsigned char[width * height * components * getGLTypeSize(outputDataType)];
    uint_t elementsRead = 0;
    while (fileStream.good() && elementsRead < (width * height * components))
    {
        // Read in one element
        // The exact procedure is based on the input data format

        uint_t elem;
        if(inputDataFormat == PLAIN_TEXT_DECIMAL)
        {
            fileStream >> elem;
        }
        else if(inputDataFormat == BINARY_BYTES)
        {
            uint8_t byte;
            fileStream.read((char*)&byte, 1);
            elem = byte;
        }
        else if(inputDataFormat == BINARY_WORDS)
        {
            uint8_t word;
            fileStream.read((char*)&word, 2);
            elem = word;
        }
        else if(inputDataFormat == PLAIN_TEXT_BITMAP)
        {
            loadTextureDataFromPNM_skipWhitespace(fileStream);
            char c;
            fileStream.read(&c, 1);
            if     (c == '0') elem = 0;
            else if(c == '1') elem = 1;
            else              break;
        }
        else if(inputDataFormat == BINARY_PACKED)
        {
            uint_t offset = elementsRead % 8;
            uint8_t byte = fileStream.peek();

            if(byte & 1<<(7-offset)) elem = 1;
            else                     elem = 0;

            if(offset == 7)
                fileStream.ignore(1);
        }
536
		else elem = 0;
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563

        if(!fileStream.good()) break;

        // Store the element in the data array
        if(outputDataType == GL_UNSIGNED_BYTE)
        {
            if(maxValue == 1) elem *= 255; // Bitmap values are normalized to 0..255
            data[elementsRead * getGLTypeSize(outputDataType)] = (GLubyte)elem;
        }
        else if(outputDataType == GL_FLOAT)
        {
            // Float values are normalized to 0..1
            GLfloat normalized = (GLfloat)elem / (GLfloat)maxValue;
            GLfloat* position = (GLfloat*)&data[elementsRead * getGLTypeSize(outputDataType)];
            *position = normalized;
        }

        elementsRead++;
    }
    fileStream.close();

    if(elementsRead != width * height * components)
    {
        error() << "could not load " << _filename << ": unexpected EOF" << std::endl;
        return SharedTextureData();
    }

564
565
566
567
    textureData->setData(data); // data will get deleted by the TextureData destructor!
    textureData->setDepth(1);   // 2D so, depth is 1
    textureData->setHeight(height);
    textureData->setWidth(width);
568
569
570
#ifdef ACGL_OPENGL_ES
    texture->setFormat(GL_RGB);
#else
571
    textureData->setFormat(components == 3 ? GL_RGB : GL_RED);
572
#endif
573
574
    textureData->setType(outputDataType);
    textureData->setColorSpace(_colorSpace); // no auto-detection
575

576
    return textureData;
577
578
}

579
580
581
582
///////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                           library specific save
///////////////////////////////////////////////////////////////////////////////////////////////////

583
584
585
586
587
588
589
590
591
592
593
594
595
596
bool saveTextureDataToRAW( const SharedTextureData &_data, const std::string &_filename )
{
    std::ofstream outFileStream(_filename.c_str(), std::ios_base::out | std::ios_base::binary);

    if(!outFileStream.good())
    {
        error() << "saveTextureDataToRAW: Could not open file " << _filename << std::endl;
        return false;
    }

    outFileStream.write( (char*)_data->getData(), _data->getSizeInBytes() );
    return true;
}

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
bool saveTextureDataToPPM(const SharedTextureData& _textureData, const std::string &_filename)
{
    std::ofstream outFileStream(_filename.c_str(), std::ios_base::out | std::ios_base::binary);

    if(!outFileStream.good())
    {
        error() << "saveTextureDataToPPM: Could not open file " << _filename << std::endl;
        return false;
    }

    // Use the binary-encoded RGB texture format
    outFileStream << "P6" << std::endl;

    // Width and height
    outFileStream << _textureData->getWidth() << " " << _textureData->getHeight() << std::endl;

    // Maximum value
    uint_t maxValue;
    if(_textureData->getType() == GL_UNSIGNED_BYTE)
    {
        maxValue = 255;
    }
    else
    {
        error() << "saveTextureDataToPPM: Unsupported texture type, must be GL_UNSIGNED_BYTE" << std::endl;
        return false;
    }
    outFileStream << maxValue;

    // Single whitespace as a delimiter
    outFileStream << "\n";

Robert Menzel's avatar
Robert Menzel committed
629
630
    GLsizei channelCount = _textureData->getNumberOfChannels();

631
632
633
634
635
    // Now, write the image data in binary format
    for(GLsizei y = 0; y < _textureData->getHeight(); ++y)
    {
        for(GLsizei x = 0; x < _textureData->getWidth(); ++x)
        {
Robert Menzel's avatar
Robert Menzel committed
636
637
            GLsizei row = _textureData->getHeight() - y - 1; // from bottom to the top to mirror the image
            GLsizei i = channelCount * (row * _textureData->getWidth() + x) + (row * _textureData->getPadding());
638

Robert Menzel's avatar
Robert Menzel committed
639
640
641
642
643
644
645
646
            unsigned char r =                     _textureData->getData()[(i + 0)];
            unsigned char g = (channelCount > 1)? _textureData->getData()[(i + 1)] : 0;
            unsigned char b = (channelCount > 2)? _textureData->getData()[(i + 2)] : 0;

            outFileStream.put( r );
            outFileStream.put( g );
            outFileStream.put( b );
            // ignore alpha if there is an alpha
647
        }
Robert Menzel's avatar
Robert Menzel committed
648
649
    }

650
651
    outFileStream.close();
    return true;
Robert Menzel's avatar
Robert Menzel committed
652
653
}

654
bool saveTextureDataToLodepng( const SharedTextureData &_data, const std::string &_filename )
Robert Menzel's avatar
Robert Menzel committed
655
{
Robert Menzel's avatar
Robert Menzel committed
656
657
658
659
    if (_data->getPadding() != 0) {
        error() << "png saving via lodepng does not support padding per row" << std::endl;
        return false;
    }
Robert Menzel's avatar
Robert Menzel committed
660
    GLenum channelDataType    = _data->getType();
Robert Menzel's avatar
Robert Menzel committed
661
    unsigned int channelCount = _data->getNumberOfChannels();
Robert Menzel's avatar
Robert Menzel committed
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692

    int channelBitCount = 0;
    if (channelDataType == GL_BYTE  || channelDataType == GL_UNSIGNED_BYTE)  channelBitCount = 8;
    if (channelDataType == GL_SHORT || channelDataType == GL_UNSIGNED_SHORT) channelBitCount = 16;
    if (channelDataType == GL_INT   || channelDataType == GL_UNSIGNED_INT)   channelBitCount = 32;

    unsigned char *processedData;
    if ( channelBitCount == 8 ) {
       processedData = preProcess<unsigned char>( _data );
    } else if ( channelBitCount == 16 ) {
        processedData = preProcess<unsigned short>( _data );
    } else if ( channelBitCount == 32 ) {
        processedData = preProcess<unsigned int>( _data );

        // no 32 bit save support -> reduce to 16 bit
        uint32_t *original = (uint32_t*) processedData;
        uint16_t *processedData16 = new uint16_t[ channelCount*_data->getWidth() * _data->getHeight() ];

        for (unsigned int i = 0; i < channelCount*_data->getWidth() * _data->getHeight(); ++i) {
            processedData16[i] = (uint16_t) original[i];
        }
        channelBitCount = 16;
        processedData = (unsigned char*) processedData16;

        delete[] original;

    } else {
        error() << "savePNG does not support this data type (yet), could not write " << _filename << std::endl;
        return false;
    }

693
694
695
696
697
698
    // LodePNG expects 16 bit image data in big endian format ==> convert
#ifndef ACGL_BIG_ENDIAN
        if(channelBitCount == 16)
            for(int i = 0; i < _data->getWidth() * _data->getHeight() * _data->getNumberOfChannels() * 2; i += 2)
                std::swap(processedData[i], processedData[i+1]);
#endif
Robert Menzel's avatar
Robert Menzel committed
699
700
701

    LodePNGColorType colorType;
    if (channelCount == 1) colorType = LCT_GREY;
702
703
704
705
    else if (channelCount == 2) colorType = LCT_GREY_ALPHA;
	else if (channelCount == 3) colorType = LCT_RGB;
	else if (channelCount == 4) colorType = LCT_RGBA;
	else colorType = LCT_RGBA;
Robert Menzel's avatar
Robert Menzel committed
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721

    unsigned int errorCode = lodepng_encode_file(_filename.c_str(),
                                    processedData, _data->getWidth(), _data->getHeight(),
                                    colorType, channelBitCount );

    delete[] processedData;

    //if there's an error, display it
    if (errorCode) {
        error() << "encoder error " << errorCode << ": "<< lodepng_error_text(errorCode) << std::endl;
        return false;
    }

    return true;
}

722
723
724
#ifdef ACGL_COMPILE_WITH_QT
bool saveTextureDataToQT( const SharedTextureData &_data, const std::string &_filename )
{
Robert Menzel's avatar
Robert Menzel committed
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    QImage::Format format = QImage::Format_ARGB32;

    if ( pointerAlignment( (void*)_data->getData() ) < 4 ) {
        error() << "image data is not 32bit aligned, QT will not be able to handle that" << std::endl;
        return false;
    }

    GLenum glFormat = _data->getFormat();
    if (glFormat == GL_RGB) {
        format = QImage::Format_RGB888;
        if (_data->getPackAlignment() < 4 ) {
            error() << "scan lines of image data are not 32bit aligned, QT will not be able to handle that" << std::endl;
            return false;
        }
739
    } else if (glFormat == GL_RGBA || glFormat == GL_BGRA) {
Robert Menzel's avatar
Robert Menzel committed
740
741
742
743
744
745
746
        format = QImage::Format_ARGB32;
    } else {
        error() << "unsupported OpenGL format" << std::endl;
    }

    QImage image = QImage( _data->getData(), _data->getWidth(), _data->getHeight(), format );
    return image.save( QString( _filename.c_str() ) );
747
748
}
#endif
Robert Menzel's avatar
Robert Menzel committed
749
750
751

} // OpenGL
} // ACGL