forked from fogleman/Minecraft
-
Notifications
You must be signed in to change notification settings - Fork 33
/
utils.py
289 lines (227 loc) · 7.52 KB
/
utils.py
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
# Imports, sorted alphabetically.
# Python packages
import os
import struct
from typing import Tuple, List
from ctypes import byref
# Third-party packages
import pyglet
from pyglet.gl import *
# Modules from this project
import globals as G
from custom_types import iVector, fVector
__all__ = (
'load_image', 'image_sprite', 'hidden_image_sprite', 'vec', 'FastRandom',
'init_resources', 'init_font', 'get_block_icon',
'FACES', 'FACES_WITH_DIAGONALS', 'normalize_float', 'normalize',
'sectorize', 'TextureGroup', 'make_nbt_from_dict', 'extract_nbt'
)
def load_image(*args):
path = os.path.join(*args)
return pyglet.image.load(os.path.join(*args)) if os.path.isfile(
path) else None
def image_sprite(image, batch, group, x: int = 0, y: int = 0, width: int = None, height: int = None):
if image is None or batch is None or group is None:
return None
width = width or image.width
height = height or image.height
if isinstance(group, int):
group = pyglet.graphics.OrderedGroup(group)
return pyglet.sprite.Sprite(image.get_region(x, y, width, height),
batch=batch, group=group)
def hidden_image_sprite(*args, **kwargs):
sprite = image_sprite(*args, **kwargs)
if sprite:
sprite.visible = False
return sprite
def vec(*args):
"""Creates GLfloat arrays of floats"""
return (GLfloat * len(args))(*args)
# fast math algorithms
class FastRandom:
seed: int
def __init__(self, seed):
self.seed = seed
def randint(self) -> int:
self.seed = (214013 * self.seed + 2531011)
return (self.seed >> 16) & 0x7FFF
def init_resources():
init_font('resources/fonts/Chunkfive.ttf', 'ChunkFive Roman')
init_font('resources/fonts/slkscr.ttf', 'Silkscreen Normal')
def init_font(filename, fontname):
pyglet.font.add_file(filename)
pyglet.font.load(fontname)
_block_icon_fbo = None
def get_block_icon(block, icon_size, world):
global _block_icon_fbo
print(block.id.filename())
block_icon = G.texture_pack_list.selected_texture_pack.load_texture(block.id.filename()) \
or (block.group or world.group).texture.get_region(
int(block.texture_data[2 * 8] * G.TILESET_SIZE) * icon_size,
int(block.texture_data[2 * 8 + 1] * G.TILESET_SIZE) * icon_size,
icon_size,
icon_size)
if block.id.is_item():
return block_icon
# create 3d icon for blocks
if _block_icon_fbo is None:
_block_icon_fbo = GLuint(0)
glGenFramebuffers(1, byref(_block_icon_fbo))
glBindFramebuffer(GL_FRAMEBUFFER, _block_icon_fbo)
icon_texture = pyglet.image.Texture.create(icon_size, icon_size, GL_RGBA)
glBindTexture(GL_TEXTURE_2D, icon_texture.id)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, icon_size, icon_size, 0, GL_RGBA, GL_FLOAT, None)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, icon_texture.id, 0)
viewport = (GLint * 4)()
glGetIntegerv(GL_VIEWPORT, viewport)
glViewport(0, 0, icon_size, icon_size)
glClearColor(1.0, 1.0, 1.0, 0.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(-1.5, 1.5, -1.5, 1.5, -10, 10)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
glColor4f(1.0, 1.0, 1.0, 1.0)
glRotatef(-45.0, 0.0, 1.0, 0.0)
glRotatef(-30.0, -1.0, 0.0, 1.0)
glScalef(1.5, 1.5, 1.5)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
vertex_data = block.get_vertices(0, 0, 0)
texture_data = block.texture_data
count = len(texture_data) // 2
batch = pyglet.graphics.Batch()
batch.add(count, GL_QUADS, (block.group or world.group),
('v3f/static', vertex_data),
('t2f/static', texture_data))
batch.draw()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
glBindFramebuffer(GL_FRAMEBUFFER, 0)
glViewport(*viewport)
glClearColor(0.0, 0.0, 0.0, 1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
return icon_texture.get_image_data()
FACES: Tuple[iVector, ...] = (
( 0, 1, 0),
( 0, -1, 0),
(-1, 0, 0),
( 1, 0, 0),
( 0, 0, 1),
( 0, 0, -1),
)
FACES_WITH_DIAGONALS: Tuple[iVector, ...] = FACES + (
(-1, -1, 0),
(-1, 0, -1),
( 0, -1, -1),
( 1, 1, 0),
( 1, 0, 1),
( 0, 1, 1),
( 1, -1, 0),
( 1, 0, -1),
( 0, 1, -1),
(-1, 1, 0),
(-1, 0, 1),
( 0, -1, 1),
)
def normalize_float(f: float) -> int:
"""
This is faster than int(round(f)). Nearly two times faster.
Since it is run at least 500,000 times during map generation,
and also in game logic, it has a major impact on performance.
>>> normalize_float(0.2)
0
>>> normalize_float(-0.4)
0
>>> normalize_float(0.5)
1
>>> normalize_float(-0.5)
-1
>>> normalize_float(0.0)
0
"""
int_f = int(f)
if f > 0:
if f - int_f < 0.5:
return int_f
return int_f + 1
if f - int_f > -0.5:
return int_f
return int_f - 1
def normalize(position: fVector) -> fVector:
x, y, z = position
return normalize_float(x), normalize_float(y), normalize_float(z)
def sectorize(position: iVector) -> iVector:
x, y, z = normalize(position)
x, y, z = (x // G.SECTOR_SIZE,
y // G.SECTOR_SIZE,
z // G.SECTOR_SIZE)
return x, y, z
class TextureGroup(pyglet.graphics.Group):
def __init__(self, path):
super(TextureGroup, self).__init__()
self.texture = pyglet.image.load(path).get_texture()
def set_state(self):
glBindTexture(self.texture.target, self.texture.id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glEnable(self.texture.target)
def unset_state(self):
glDisable(self.texture.target)
# Named Binary Tag
def make_int_packet(i: int) -> bytes:
return struct.pack('i', i)
def extract_int_packet(packet: bytes):
"""
:rtype: (bytes, int)
"""
return packet[4:], struct.unpack('i', packet[:4])[0]
def make_string_packet(s: str) -> bytes:
return struct.pack('i', len(s)) + s.encode('utf-8')
def extract_string_packet(packet: bytes):
"""
:rtype: (bytes, str)
"""
strlen = struct.unpack('i', packet[:4])[0]
packet = packet[4:]
s = packet[:strlen].decode('utf-8')
packet = packet[strlen:]
return packet, s
def make_packet(obj) -> bytes:
if type(obj) == int:
return make_int_packet(obj)
elif type(obj) == str:
return make_string_packet(obj)
else:
print(('make_packet: unsupported type: ' + str(type(obj))))
return None
def extract_packet(packet):
tag, packet = struct.unpack('B', packet[:1])[0], packet[1:]
if tag == 0:
return extract_int_packet(packet)
elif tag == 1:
return extract_string_packet(packet)
def type_tag(t) -> bytes:
tag = 0
if t == int:
tag = 0
elif t == str:
tag = 1
return struct.pack('B', tag)
def make_nbt_from_dict(d: dict) -> bytes:
packet = b''
for key in list(d.keys()):
packet += make_string_packet(key) + type_tag(type(d[key])) + make_packet(d[key])
return packet
def extract_nbt(nbt):
result = {}
while len(nbt) > 0:
nbt, key = extract_string_packet(nbt)
nbt, value = extract_packet(nbt)
result[key] = value
return result