-
Notifications
You must be signed in to change notification settings - Fork 3
/
world.py
341 lines (263 loc) · 9.48 KB
/
world.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
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
import itertools
import json
import panda3d.core as core
from direct.showbase.MessengerGlobal import messenger
from direct.directnotify.DirectNotifyGlobal import directNotify
DIRECTIONS = {
'up': (0, 0, 1),
'down': (0, 0, -1),
'front': (0, 1, 0),
'back': (0, -1, 0),
'left': (-1, 0, 0),
'right': (1, 0, 0)
}
def load_forms():
models = loader.loadModel('media/models/forms.egg')
yield Form('Void', [], [])
for geomnode in models.findAllMatches('**/+GeomNode'):
_, name = geomnode.getName().split(':')
vertices = []
indices = []
geom = geomnode.node().getGeom(0)
vdata = geom.getVertexData()
vertex = core.GeomVertexReader(vdata, 'vertex')
tex = core.GeomVertexReader(vdata, 'texcoord')
normal = core.GeomVertexReader(vdata, 'normal')
while not vertex.isAtEnd():
v = vertex.getData3f()
n = normal.getData3f()
t = tex.getData2f()
vertices.append((v, n, t))
for prim in range(geom.getNumPrimitives()):
primitive = geom.getPrimitive(prim).decompose()
for p in range(primitive.getNumPrimitives()):
for i in range(primitive.getPrimitiveStart(p), primitive.getPrimitiveEnd(p)):
vi = primitive.getVertex(i)
indices.append(vi)
yield Form(name, vertices, indices)
class Form(object):
def __init__(self, name, vertices, indices):
self.name = name
self.vertices = vertices
self.indices = indices
self.num_vertices = len(vertices)
def hides(self, direction):
if self.name == 'Block':
return True
if self.name.startswith('Ramp') and direction == (0, 0, 1):
return True
return False
class Substance(object):
AIR = 0
DIRT = 1
STONE = 2
class Block(object):
__slots__ = ('form', 'substance', 'hidden', 'x', 'y', 'z', 'world')
FORMS = None
def __init__(self, form, substance, hidden, pos, world):
self.form = form
self.substance = substance
self.hidden = hidden
self.x, self.y, self.z = pos
self.world = world
@property
def passable(self):
return self.form.name == 'Void'
@property
def is_block(self):
return self.form.name == 'Block'
@property
def is_void(self):
return self.form.name == 'Void'
@property
def is_ramp(self):
return self.form.name.startswith('Ramp')
@property
def up(self):
return self.world.get_block(self.x, self.y, self.z + 1)
@property
def down(self):
return self.world.get_block(self.x, self.y, self.z - 1)
@property
def right(self):
return self.world.get_block(self.x + 1, self.y, self.z)
@property
def left(self):
return self.world.get_block(self.x - 1, self.y, self.z)
@property
def front(self):
return self.world.get_block(self.x, self.y + 1, self.z)
@property
def back(self):
return self.world.get_block(self.x, self.y - 1, self.z)
def hides(self, direction):
return self.form.hides(direction)
def __str__(self):
return '{}/{}/{}'.format(self.form.name, self.substance, self.hidden)
def __repr__(self):
return str(self)
class NullBlock(Block):
@property
def is_block(self):
return False
@property
def is_ramp(self):
return False
@property
def is_void(self):
return False
@property
def passable(self):
return False
def hides(self, direction):
return True
def __str__(self):
return 'no block'
class World(object):
def __init__(self, width, height, depth):
self.forms = {f.name: f for f in load_forms()}
Block.FORMS = self.forms
self.width = width
self.height = height
self.depth = depth
self.size = core.Point3(self.width, self.height, self.depth)
self.midpoint = core.Point3(self.width // 2, self.height // 2, self.depth // 2)
self.blocks = {coords: None for coords in self.grid()}
self.notify = directNotify.newCategory('world')
messenger.accept('console-command', self, self.command)
def __contains__(self, item):
x, y, z = item
return (
(0 <= x < self.width) and
(0 <= y < self.height) and
(0 <= z < self.depth)
)
def get_raw(self, x, y, z):
return self.blocks[(x, y, z)]
def get_block(self, x, y, z):
p = (x, y, z)
if p not in self:
return NullBlock(None, None, False, p, self)
b = self.get_raw(x, y, z)
return Block(b[0], b[1], b[2], p, self)
def set_block(self, x, y, z, form, substance, hidden, update_hidden=True):
if (x, y, z) not in self:
return False
old = self.blocks[(x, y, z)]
new = (form, substance, hidden)
if old != new:
self.blocks[(x, y, z)] = new
messenger.send('block-update', [(x, y, z)])
if update_hidden:
for dx, dy, dz in DIRECTIONS.values():
self.update_hidden(x + dx, y + dy, z + dz)
def update_hidden(self, x, y, z):
b = self.get_block(x, y, z)
if all(f.hides(d) for d, (f, s, h) in self.neighborhood(x, y, z)):
b.hidden = True
else:
b.hidden = False
self.set_block(x, y, z, b.form, b.substance, b.hidden, False)
def grid(self):
return itertools.product(range(self.width), range(self.height), range(self.depth))
def all(self):
for x, y, z in self.grid():
b = self.get_block(x, y, z)
yield x, y, z, b
def slice(self, z):
for x, y in self.columns():
yield x, y, self.get_block(x, y, z)
def columns(self):
for x, y in itertools.product(range(self.width), range(self.height)):
yield x, y
def zlevels(self):
return range(self.depth)
def neighborhood(self, x, y, z):
for dx, dy, dz in DIRECTIONS.values():
rx, ry, rz = x + dx, y + dy, z + dz
if (rx, ry, rz) in self:
yield (dx, dy, dz), self.get_raw(rx, ry, rz)
def make_ramp(self, x, y, z, update_hidden=True):
b = self.get_block(x, y, z)
if b.left.is_block and b.front.is_block:
f, s = 'RampWN', b.left.substance
elif b.front.is_block and b.right.is_block:
f, s = 'RampNE', b.front.substance
elif b.right.is_block and b.back.is_block:
f, s = 'RampES', b.right.substance
elif b.back.is_block and b.left.is_block:
f, s = 'RampSW', b.back.substance
elif b.left.is_block:
f, s = 'RampW', b.left.substance
elif b.right.is_block:
f, s = 'RampE', b.right.substance
elif b.back.is_block:
f, s = 'RampS', b.back.substance
elif b.front.is_block:
f, s = 'RampN', b.front.substance
else:
return False
self.set_block(x, y, z, self.forms[f], s, False, update_hidden)
return True
def generate(self):
self.notify.info('Generation started')
fbm = core.StackedPerlinNoise2(100, 100, 5, 2.01, 0.65)
for x, y in self.columns():
h = fbm.noise(x, y) * 20 + self.midpoint.z
h2 = fbm.noise(x, y) * 7 + self.midpoint.z
for z in range(self.depth):
i = (x, y, z)
if z > max(h, h2):
self.blocks[i] = (self.forms['Void'], Substance.AIR, False)
elif h < z < h2:
self.blocks[i] = (self.forms['Block'], Substance.DIRT, True)
else:
self.blocks[i] = (self.forms['Block'], Substance.STONE, True)
self.notify.info('Making ramps')
for x, y, z in self.grid():
if z > 0:
f = self.get_raw(x, y, z)[0]
fd, sd, _ = self.get_raw(x, y, z - 1)
if f.name == 'Void':
if fd.name == 'Block':
if not self.make_ramp(x, y, z, False):
if sd == Substance.DIRT:
self.set_block(x, y, z, self.forms['Floor'], sd, False, False)
self.notify.info('Updating hidden blocks')
for x, y, z in self.grid():
f, s, h = self.get_raw(x, y, z)
if f.name == 'Block':
self.update_hidden(x, y, z)
continue
self.notify.info('Generation complete')
def command(self, args):
args = list(args)
cmd = args.pop(0)
if cmd == 'save':
fn = args.pop(0)
self.save(fn)
@staticmethod
def load(fn):
with open(fn) as f:
data = json.load(f)
w = World(*data['extents'])
f = data['forms']
for (x, y, z, b), datum in zip(w.all(), data['data']):
i = (x, y, z)
form, substance, hidden = datum
w.blocks[i] = (w.forms[f[form]], substance, hidden)
return w
def save(self, fn):
forms = self.forms.keys()
formmap = {f: i for i, f in enumerate(forms)}
x, y, z = self.size
data = {
'extents': [int(x), int(y), int(z)],
'forms': forms,
'data': [
(formmap[b.form.name], b.substance, int(b.hidden))
for x, y, z, b in self.all()
]
}
with open(fn, 'w') as f:
json.dump(data, f)