-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtexture.c
143 lines (112 loc) · 2.95 KB
/
texture.c
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
#include <stdio.h>
#include <stdlib.h>
#include "texture.h"
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef struct
{
uchar magic; // 0x0a
uchar version;
uchar encoding; // 0x01
uchar bitsperpixel;
ushort xmin;
ushort ymin;
ushort xmax;
ushort ymax;
ushort hres;
ushort vres;
uchar palette[48];
uchar reserved;
uchar numofplanes;
ushort bytesperline;
ushort palettetype;
ushort hsize;
ushort vsize;
uchar filler[54];
} pcxhead_t;
void unload_bitmap(bitmap_t* bitmap)
{
if (bitmap->data) {
free(bitmap->data);
if (bitmap->palette) {
free(bitmap->palette);
}
}
}
void read_compressed_data(FILE* fp, int size, unsigned char* data)
{
int i = 0;
unsigned char j, b;
fseek(fp, 128, SEEK_SET);
while (i != size) {
b = fgetc(fp);
if (b >= 192) {
j = b - 192;
b = fgetc(fp);
while (j-- > 0) {
data[i++] = b;
}
} else {
data[i++] = b;
}
}
}
void read_palette(FILE* fp, unsigned char* palette)
{
int i;
fseek(fp, -768L, SEEK_END);
for (i = 0; i < 768; i++) {
palette[i] = fgetc(fp) >> 2;
}
}
int load_bitmap(bitmap_t* bitmap, const char* filename)
{
pcxhead_t header;
FILE* fp;
int i, is_success = 0;
fp = fopen(filename, "r+b");
if (fp) {
fread(&header, sizeof(pcxhead_t), 1, fp);
if (header.magic == 0x0a && header.bitsperpixel == 8) {
bitmap->width = header.xmax - header.xmin + 1;
bitmap->height = header.ymax - header.ymin + 1;
if (bitmap->width * bitmap->height < 0xffff) {
bitmap->data = (unsigned char *)malloc(bitmap->width * bitmap->height * sizeof(unsigned char));
if (bitmap->data) {
bitmap->palette = (unsigned char *)malloc(768 * sizeof(unsigned char));
if (bitmap->palette) {
read_compressed_data(fp, bitmap->width * bitmap->height, bitmap->data);
read_palette(fp, bitmap->palette);
is_success = 1;
}
}
}
}
fclose(fp);
}
if (!is_success) {
unload_bitmap(bitmap);
}
return is_success;
}
int load_texture(texture_t* texture, const char* filename)
{
int is_success;
is_success = load_bitmap(&texture->bitmap, filename);
if (is_success) {
texture->texturetype = TEXTURE_SOFT;
printf("Loaded texture: %s\n", filename);
}
return is_success;
}
void unload_texture(texture_t* texture)
{
unload_bitmap(&texture->bitmap);
}
void copy_texture(texture_t* dest, texture_t* src)
{
// shallow copy is good enough
dest->bitmap.data = src->bitmap.data;
dest->bitmap.palette = src->bitmap.palette;
dest->texturetype = src->texturetype;
}