summaryrefslogtreecommitdiff
path: root/src/resources/atlas/atlasmanager.cpp
blob: 90b72b4d61ba5df3080327793b1fbe596f10d9e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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
369
370
371
372
373
374
375
376
377
378
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
412
413
414
415
416
417
418
419
420
421
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
/*
 *  The ManaPlus Client
 *  Copyright (C) 2012-2017  The ManaPlus Developers
 *
 *  This file is part of The ManaPlus Client.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef USE_OPENGL

#include "resources/atlas/atlasmanager.h"

#include "settings.h"

#ifdef DEBUG_IMAGES
#include "logger.h"
#endif  // DEBUG_IMAGES

#include "utils/mathutils.h"
#include "utils/physfscheckutils.h"
#include "utils/physfsrwops.h"
#include "utils/sdlcheckutils.h"

#include "resources/openglimagehelper.h"

#include "resources/atlas/atlasresource.h"
#include "resources/atlas/textureatlas.h"

#include "resources/dye/dye.h"

#include "resources/resourcemanager/resourcemanager.h"

#ifndef SDL_BIG_ENDIAN
#include <SDL_endian.h>
#endif  // SDL_BYTEORDER

#include "utils/checkutils.h"

#include "debug.h"

AtlasManager::AtlasManager()
{
}

AtlasResource *AtlasManager::loadTextureAtlas(const std::string &name,
                                              const StringVect &files)
{
    BLOCK_START("AtlasManager::loadTextureAtlas")
    std::vector<TextureAtlas*> atlases;
    std::vector<Image*> images;
    AtlasResource *resource = new AtlasResource;

    loadImages(files, images);
    int maxSize = OpenGLImageHelper::getTextureSize();
#if !defined(ANDROID) && !defined(__APPLE__)
    int sz = settings.textureSize;
    if (maxSize > sz)
        maxSize = sz;
#endif  // !defined(ANDROID) && !defined(__APPLE__)

    // sorting images on atlases.
    simpleSort(name, atlases, images, maxSize);

    FOR_EACH (std::vector<TextureAtlas*>::iterator, it, atlases)
    {
        TextureAtlas *const atlas = *it;
        if (!atlas)
            continue;

        createSDLAtlas(atlas);
        if (atlas->atlasImage == nullptr)
            continue;
        convertAtlas(atlas);
        resource->atlases.push_back(atlas);
    }

    BLOCK_END("AtlasManager::loadTextureAtlas")
    return resource;
}

AtlasResource *AtlasManager::loadEmptyAtlas(const std::string &name,
                                            const StringVect &files)
{
    std::vector<TextureAtlas*> atlases;
    std::vector<Image*> images;
    AtlasResource *resource = new AtlasResource;

    loadEmptyImages(files, images);
    int maxSize = OpenGLImageHelper::getTextureSize();

    // sorting images on atlases.
    simpleSort(name, atlases, images, maxSize);

    FOR_EACH (std::vector<TextureAtlas*>::iterator, it, atlases)
    {
        TextureAtlas *const atlas = *it;
        if (!atlas)
            continue;

        atlas->atlasImage = new Image(0,
            8192, 8192,
            8192, 8192);
        // convert SDL images to OpenGL
        convertAtlas(atlas);

        resource->atlases.push_back(atlas);
    }

    BLOCK_END("AtlasManager::loadTextureAtlas")
    return resource;
}

void AtlasManager::loadImages(const StringVect &files,
                              std::vector<Image*> &images)
{
    BLOCK_START("AtlasManager::loadImages")

    FOR_EACH (StringVectCIter, it, files)
    {
        const std::string str = *it;
        // check is image with same name already in cache
        // and if yes, move it to deleted set
        Resource *const res = resourceManager->getTempResource(str);
        if (res)
        {
            // increase counter because in moveToDeleted it will be decreased.
            res->incRef();
            resourceManager->moveToDeleted(res);
        }

        std::string path = str;
        const size_t p = path.find('|');
        Dye *d = nullptr;
        if (p != std::string::npos)
        {
            d = new Dye(path.substr(p + 1));
            path = path.substr(0, p);
        }

        SDL_RWops *const rw = MPHYSFSRWOPS_openRead(path.c_str());
        if (rw)
        {
            Image *const image = d ? surfaceImageHelper->load(rw, *d)
                : surfaceImageHelper->load(rw);

            if (image)
            {
                image->mIdPath = str;
#ifdef DEBUG_IMAGES
                logger->log("set name %p, %s", static_cast<void*>(image),
                    image->mIdPath.c_str());
#endif  // DEBUG_IMAGES

                images.push_back(image);
            }
        }
        else
        {
            reportAlways("Physfs error: %s", PhysFs::getLastError());
        }
        delete d;
    }
    BLOCK_END("AtlasManager::loadImages")
}

void AtlasManager::loadEmptyImages(const StringVect &files,
                                   std::vector<Image*> &images)
{
    BLOCK_START("AtlasManager::loadEmptyImages")

    FOR_EACH (StringVectCIter, it, files)
    {
        const std::string str = *it;
        // check is image with same name already in cache
        // and if yes, move it to deleted set
        Resource *const res = resourceManager->getTempResource(str);
        if (res)
        {
            // increase counter because in moveToDeleted it will be decreased.
            res->incRef();
            resourceManager->moveToDeleted(res);
        }

        Image *const image = new Image(0,
            2048, 2048,
            2048, 2048);
        image->mIdPath = str;
        images.push_back(image);
    }
    BLOCK_END("AtlasManager::loadEmptyImages")
}

void AtlasManager::simpleSort(const std::string &restrict name,
                              std::vector<TextureAtlas*> &restrict atlases,
                              const std::vector<Image*> &restrict images,
                              int size)
{
    BLOCK_START("AtlasManager::simpleSort")
    int x = 0;
    int y = 0;
    int tempHeight = 0;
    TextureAtlas *atlas = new TextureAtlas();
    std::vector<Image*>::const_iterator it = images.begin();
    const std::vector<Image*>::const_iterator it_end = images.end();
    for (it = images.begin(); it != it_end; ++ it)
    {
        const Image *const img = *it;
        if (img)
        {
            atlas->name = std::string("atlas_").append(name).append(
                "_").append(img->getIdPath());
            break;
        }
    }

    for (it = images.begin(); it != it_end; ++ it)
    {
        Image *const img = *it;
        if (img)
        {
            AtlasItem *const item = new AtlasItem(img);
            item->name = img->getIdPath();
            // start next line
            if (x + img->mBounds.w > size)
            {
                x = 0;
                y += tempHeight;
                tempHeight = 0;
            }

            // can't put image with this height
            if (y + img->mBounds.h > size)
            {
                x = 0;
                y = 0;
                atlases.push_back(atlas);
                atlas = new TextureAtlas();
                atlas->name = std::string("atlas_").append(name).append(
                    "_").append(img->getIdPath());
            }

            if (img->mBounds.h > tempHeight)
                tempHeight = img->mBounds.h;

            item->x = x;
            item->y = y;
            atlas->items.push_back(item);

            // continue put textures in line
            x += img->mBounds.w;
            if (x > atlas->width)
                atlas->width = x;
            if (y + img->mBounds.h > atlas->height)
                atlas->height = y + img->mBounds.h;
        }
    }
    if (!atlas->items.empty())
        atlases.push_back(atlas);
    else
        delete atlas;
    BLOCK_END("AtlasManager::simpleSort")
}

void AtlasManager::createSDLAtlas(TextureAtlas *const atlas)
{
    BLOCK_START("AtlasManager::createSDLAtlas")
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    const unsigned int rmask = 0xff000000;
    const unsigned int gmask = 0x00ff0000;
    const unsigned int bmask = 0x0000ff00;
    const unsigned int amask = 0x000000ff;
#else  // SDL_BYTEORDER == SDL_BIG_ENDIAN

    const unsigned int rmask = 0x000000ff;
    const unsigned int gmask = 0x0000ff00;
    const unsigned int bmask = 0x00ff0000;
    const unsigned int amask = 0xff000000;
#endif  // SDL_BYTEORDER == SDL_BIG_ENDIAN

    // do not create atlas based on only one image
    if (atlas->items.size() == 1)
    {
        logger->log("Skip atlas creation because only one image in atlas.");
        BLOCK_END("AtlasManager::createSDLAtlas")
        return;
    }

    // using only power of two sizes.
    atlas->width = powerOfTwo(atlas->width);
    atlas->height = powerOfTwo(atlas->height);

    const int width = atlas->width;
    const int height = atlas->height;
    BLOCK_START("AtlasManager::createSDLAtlas create surface")
    // temp SDL surface for atlas
    SDL_Surface *const surface = MSDL_CreateRGBSurface(SDL_SWSURFACE,
        width, height, 32U, rmask, gmask, bmask, amask);
    if (!surface)
    {
        reportAlways("Error creating surface for atlas. Size: %dx%d",
            width,
            height);
        BLOCK_END("AtlasManager::createSDLAtlas")
        return;
    }
    BLOCK_END("AtlasManager::createSDLAtlas create surface")

    Image *image = imageHelper->loadSurface(surface);
    // free SDL atlas surface
    MSDL_FreeSurface(surface);
    if (image == nullptr)
    {
        reportAlways("Error converting surface to texture. Size: %dx%d",
            width,
            height);
        return;
    }

    // drawing SDL images to surface
    FOR_EACH (std::vector<AtlasItem*>::iterator, it, atlas->items)
    {
        AtlasItem *const item = *it;
        imageHelper->copySurfaceToImage(image, item->x, item->y,
            item->image->mSDLSurface);
    }
    atlas->atlasImage = image;
    BLOCK_END("AtlasManager::createSDLAtlas")
}

void AtlasManager::convertAtlas(TextureAtlas *const atlas)
{
    // no check for null pointer in atlas because it was in caller
    // convert surface to OpemGL image
    Image *const oldImage = atlas->atlasImage;

    if (oldImage->mSDLSurface)
    {
        atlas->atlasImage = imageHelper->loadSurface(
            atlas->atlasImage->mSDLSurface);
        oldImage->decRef();
    }

    Image *const image = atlas->atlasImage;
    if (!image)
        return;

    image->mIdPath = atlas->name;
#ifdef DEBUG_IMAGES
    logger->log("set name %p, %s", static_cast<void*>(image),
        image->mIdPath.c_str());
#endif  // DEBUG_IMAGES

    image->incRef();

    FOR_EACH (std::vector<AtlasItem*>::iterator, it, atlas->items)
    {
        AtlasItem *const item = *it;
        // delete SDL Image
        delete item->image;
        // store OpenGL image
        item->image = image->getSubImage(item->x, item->y,
            item->width, item->height);
        Image *const image2 = item->image;
        if (image2)
        {
            image2->mIdPath = item->name;
#ifdef DEBUG_IMAGES
            logger->log("set name %p, %s", static_cast<void*>(image2),
                image2->mIdPath.c_str());
#endif  // DEBUG_IMAGES

            image2->incRef();
        }
    }
}

void AtlasManager::injectToResources(const AtlasResource *const resource)
{
    if (!resource)
        return;
    FOR_EACH (std::vector<TextureAtlas*>::const_iterator,
              it, resource->atlases)
    {
        // add each atlas image to resources
        TextureAtlas *const atlas = *it;
        if (atlas)
        {
            Image *const image = atlas->atlasImage;
            if (image)
                resourceManager->addResource(atlas->name, image);
            FOR_EACH (std::vector<AtlasItem*>::iterator, it2, atlas->items)
            {
                AtlasItem *const item = *it2;
                if (!item)
                    continue;
                // add each atlas sub image to resources
                resourceManager->addResource(item->name, item->image);
            }
        }
    }
}

void AtlasManager::moveToDeleted(AtlasResource *const resource)
{
    if (!resource)
        return;
    FOR_EACH (std::vector<TextureAtlas*>::iterator, it, resource->atlases)
    {
        // move each atlas image to deleted
        TextureAtlas *const atlas = *it;
        if (atlas)
        {
            Image *const image = atlas->atlasImage;
            if (image)
            {
                // move each atlas image to deleted
                resourceManager->moveToDeleted(image);
            }
            FOR_EACH (std::vector<AtlasItem*>::iterator, it2, atlas->items)
            {
                AtlasItem *const item = *it2;
                if (item)
                {
                    Image *const image2 = item->image;
                    if (image2)
                    {
                        // move each atlas sub image to deleted
                        resourceManager->moveToDeleted(image2);
                    }
                }
            }
        }
    }
}

#endif  // USE_OPENGL