aboutsummaryrefslogtreecommitdiff
path: root/src/libjin/Graphics/Bitmap.cpp
blob: 93ea1a96bcba271af5dffdc5c16053eb565210f6 (plain)
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
#include "Bitmap.h"
#include "../3rdparty/stb/stb_image.h"
#include "../Math/math.h"

using namespace jin::math;

namespace jin
{
namespace graphics
{

    /*static*/ Bitmap* Bitmap::createBitmap(const void* imgData, size_t size)
    {
        if (imgData == nullptr)
            return nullptr; 
        int w, h;
        void* data = stbi_load_from_memory((unsigned char *)imgData, size, &w, &h, NULL, STBI_rgb_alpha);
        if (data == nullptr)
            return nullptr;
        Bitmap* bitmap = new Bitmap();
        bitmap->pixels = (Color*)data; 
        bitmap->width = w; 
        bitmap->height = h;
        return bitmap;
    }

    /*static*/ Bitmap* Bitmap::createBitmap(int w, int h)
    {
        Bitmap* bitmap = new Bitmap(w, h);
        return bitmap;
    }

    Bitmap::Bitmap()
        : width(0)
        , height(0)
        , pixels(nullptr)
    {
    }

    Bitmap::Bitmap(int w, int h)
    {
        width = w; 
        height = h; 
        pixels = (Color*)calloc(1, w*h*sizeof(Color));
    }

    Bitmap::~Bitmap()
    {
        stbi_image_free(pixels);
    }

    void Bitmap::bindPixels(Color* p, int w, int h)
    {
        if (pixels != nullptr)
            delete[] pixels;
        pixels = p;
        width = w; 
        height = h;
    }

    void Bitmap::setPixels(Color* p, int w, int h)
    {
        if (pixels != nullptr)
            delete[] pixels; 
        size_t s = w * h * sizeof(Color);
        pixels = (Color*)calloc(1, s);
        memcpy(pixels, p, s);
        width = w; 
        height = h;
    }

    void Bitmap::setPixel(const Color& pixel, int x, int y)
    {
        if (pixels == nullptr)
            return;
        if (without<int>(x, 0, width - 1) || without<int>(y, 0, height - 1))
            return;
        pixels[x + y * width] = pixel;
    }
    
    Color Bitmap::getPixel(int x, int y)
    {
        if (pixels == nullptr)
            return Color::BLACK;
        if (without<int>(x, 0, width - 1) || without<int>(y, 0, height - 1))
            return Color::BLACK;
        return pixels[x + y * width];
    }
    
    const Color* Bitmap::getPixels()
    {
        return pixels;
    }

}
}