-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathngschm.py
540 lines (520 loc) · 20.8 KB
/
ngschm.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
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#!/usr/bin/env python
import os,sys
import time
import random
from io import BytesIO
from struct import pack, unpack
import array, math
import glob
from collections import Counter
import numpy as np
from operator import itemgetter
# local module
try:
import nbt
except ImportError:
# nbt not in search path. Let's see if it can be found in the parent folder
extrasearchpath = os.path.realpath(os.path.join(__file__,os.pardir,os.pardir))
if not os.path.exists(os.path.join(extrasearchpath,'nbt')):
raise
sys.path.append(extrasearchpath)
from nbt.nbt import NBTFile, TAG_Short, TAG_Int, TAG_String, TAG_List, TAG_Byte, TAG_Byte_Array, TAG_Compound
"""'
methodology:
MCEdit(Minecraft World) -> NBTExplorer(.schematic) -> txt2nbok(numpy block array) -> source
(source||random) -> child book
child book -> MCEdit(.schematic) -> Minecraft World
nbtexplorer can export .schematic block array as text which was
coverted to a book(base91 string) representing the 3D block array
NOW it is converted to a numpy array which is printed in binary
genetic algortihm natively generates random individuals for its starting popupulation,
this requires many generations to get anywhere (even after 10 gens, it is effectively random}
quilting can be used to grow individuals from a source
No transcription will be done
evolve: breeding cross over chunk by chunk
"""
verbose =10
class foo():
id = 10
def printv(*args, sep=' ', end='\n', file=None, level=1,flush=False):
if verbose>=level:
print(*args, sep=sep, end=end, file=file,flush=flush)
def probability(a,d):
"""return index of random element based on probability"""
c = np.sum(a)
b = np.random.random()
while b > c:
b = np.random.random()
for p in range(len(a)):
#print(b,[p],a[p])
if a[p] >= b:
#print("win")
return p
else:
b -= a[p]
if b == 0:
#print("fail")
return 0#default block
return 197
def individual(length):
'Create a member of the population.'
printv("random individual")
return np.random.randint(91, size=length).reshape(256,128,128)
def quilt(length,s ='',legacy=False):
#fault = 0
#mod = 32
printv("quilted individual v2")
if s == '':
sys.exit(1)
try:
relam = np.fromfile(glob.glob('books/*.rlay')[0]).reshape(198,2,198)
except:
relam = np.zeros((198,2,198))
#create relay
for x in range(256):
for y in range(512):
for z in range(512):
if z==511 and y==511:
continue
elif z==511:
relam[s[x,y,z],1,s[x,y+1,z]] += 1
elif y==511:
relam[s[x,y,z],0,s[x,y,z+1]] += 1
else:
relam[s[x,y,z],0,s[x,y,z+1]] += 1
relam[s[x,y,z],1,s[x,y+1,z]] += 1
relam = relam/(len(s.flatten()))
print(len(s.flatten()))
relam.tofile('books/0.rlay')
res = np.zeros((256,128,128),dtype=np.uint8) - 1
if legacy == False:
b = np.random.randint(384)
c = np.random.randint(384)
for x in range(256):
for y in range(128):
for z in range(128):
if (z%32)<16 and (y%32)<16:
res[x,y,z] = s[x,y+b,z+b]
elif z>=16 and y<16:
res[x,y,z] = probability(relam[res[x,y,z-1],0],res[x,y,z-1])
if x-5 >= 0:####REMOVE BLOCKS IN THE AIR
if res[x-5,y,z] == 0:
res[x,y,z] = 0
elif z<16 and y>=16:
res[x,y,z] = probability(relam[res[x,y-1,z],1],res[x,y-1,z])
if x-5 >= 0:####REMOVE BLOCKS IN THE AIR
if res[x-5,y,z] == 0:
res[x,y,z] = 0
elif (z%32)>=16 and (y%32)>=16:
res[x,y,z] = s[x,y+c,z+c]
else:
res[x,y,z] = probability(relam[res[x,y-1,z],1],res[x,y-1,z])
if x-5 >= 0:####REMOVE BLOCKS IN THE AIR
if res[x-5,y,z] == 0:
res[x,y,z] = 0
elif legacy == 512 and False:
try:
nst = np.load(glob.glob('books/*.npz')[0])
except:
#relam = np.zeros(256,512,512)
#create relay
nst = [[] for x in range(197)]
ss = s.flatten()
for n in range(256*512*512):
nst[ss[n]].append(n)
for m in range(197):
nst[m] = np.array(nst[m], dtype=np.uint32)
np.savez("books/0",*nst)
b = np.random.randint(384)
c = np.random.randint(384)
#access = (0,0,0)
#print(nst.files)
i = 0
es = s.flatten()
for x in range(256):
print((i/256)*100,'%',sep='')
i+=1
for y in range(128):
#sys.stdout.write('.')
#sys.stdout.flush()
for z in range(128):
#if z == 0:
#print('***[',x,y-1,z,']','{',res[x,y-1,z],'}')
if (z%32)<16 and (y%32)<16:
res[x,y,z] = s[x,y+b,z+b]
elif z>=16 and y<16:
res[x,y,z] = es[np.random.choice(nst['arr_'+str(res[x,y,z-1])])+1]
#print('[',x,y,z,']','{',res[x,y,z],'}')
"""print()
ok = np.random.choice(nst['arr_'+str(res[x,y,z-1])]+1)
access = np.unravel_index(ok,[256,512,512])
#access = (access[0],access[1], access[2] + 1)
#print(ok,access,'[',x,y,z-1,']','{',res[x,y,z-1],'}')
res[x,y,z] = s[access]#"""
if x-5 >= 0:####REMOVE BLOCKS IN THE AIR
if res[x-5,y,z] == 0:
res[x,y,z] = 0
elif z<16 and y>=16:
res[x,y,z] = es[np.random.choice(nst['arr_'+str(res[x,y-1,z])])+1]
#print('[',x,y,z,']','{',res[x,y,z],'}')
"""print('[',x,y,z-1,']','{',res[x,y,z-1],'}')
ok = np.random.choice(nst['arr_'+str(res[x,y-1,z])]+1)
access = np.unravel_index(ok,[256,512,512])
#access = (access[0],access[1], access[2] + 1)
#print(ok,access,'[',x,y,z-1,']','{',res[x,y,z-1],'}')
res[x,y,z] = s[access]#"""
if x-5 >= 0:####REMOVE BLOCKS IN THE AIR
if res[x-5,y,z] == 0:
res[x,y,z] = 0
elif (z%32)>=16 and (y%32)>=16:
res[x,y,z] = s[x,y+c,z+c]
else:
res[x,y,z] = es[np.random.choice(nst['arr_'+str(res[x,y,z-1])])+1]
#print('[',x,y,z,']','{',res[x,y,z],'}')
"""print('[',x,y,z-1,']','{',res[x,y,z-1],'}')
ok = np.random.choice(nst['arr_'+str(res[x,y,z-1])])+1
access = np.unravel_index(ok,[256,512,512])
#access = (access[0],access[1], access[2] + 1)
#print(ok,access,'[',x,y,z-1,']','{',res[x,y,z-1],'}')
res[x,y,z] = s[access]#"""
if x-5 >= 0:####REMOVE BLOCKS IN THE AIR
if res[x-5,y,z] == 0:
res[x,y,z] = 0
else:#older version
b = np.random.randint(384)
c = np.random.randint(384)
for x in range(256):
for y in range(128):
for z in range(128):
if z<16 and z<16:
res[x,y,z] = s[x,y+b,z+b]
elif z>=16 and y<16:
res[x,y,z] = probability(relam[res[x,y,z-1],0],res[x,y,z-1])
elif z<16 and y>=16:
res[x,y,z] = probability(relam[res[x,y-1,z],1],res[x,y-1,z])
elif z>=16 and y>=16:
res[x,y,z] = probability(relam[res[x,y-1,z-1],1],res[x,y-1,z-1])
else:
res[x,y,z] = probability(relam[res[x,y-1,z],1],res[x,y-1,z])
print(res)
return res
def population(s='',count=20, ran=False,org=False,length=4194304,leg=1):
"""Create a number of individuals (i.e. a population).
count: the number of individuals in the population
length: the number of values per individual
min: the minimum possible value in an individual's list of values
max: the maximum possible value in an individual's list of values
"""
printv("REAL POPULATION")
if ran:
c = np.array([individual(length) for x in range(count)],dtype=np.uint8)
else:
c = np.array([quilt(length,s,leg) for x in range(count)],dtype=np.uint8)
if org:
for u in range(count):
_ = c[u].flatten()
l = "books/"+org+"ORG/"
m = "schema/"+org+"ORG/"
if not os.path.exists(l):
os.makedirs(l)
if not os.path.exists(m):
os.makedirs(m)
_.tofile(l+str(u)+'.nbok')
mine = _schema(blst=_.tolist())
mine.write_file("schema/"+org+"ORG/"+str(u)+'.schematic')
return c
def artpop(exist=False, count=20, length=4194304):
"""create artificial population, non random individuals or existing individuals"""
printv("FICTIONAL POPULATION")
if exist:#exist == foldername of individuals, which must have numbered names
#use ready made nboks, can be used to add more evolutions, or make a new evolutionary path
numobk = len(glob.glob("books/"+exist+"/*.nbok"))
c = np.array([np.fromfile("books/"+exist+"/"+str(x%numobk)+".nbok",dtype=np.uint8).reshape(256,128,128) for x in range(count)],dtype=np.uint8)
else:
c = np.array([[x%90]*length for x in range(count)],dtype=np.uint8).reshape(count,256,128,128)
return c
def fitness(individual, s='', target=0):
"""
Determine the fitness of an individual. Higher is better.
individual: the individual to evaluate
target: the target number individuals are aiming for
"""
#return np.random.randint(0,50000)
try:
srccn = np.fromfile(glob.glob('books/*.cont')[0])
except:
srccn = np.zeros(197)
scntt = Counter(s)
for x in range(197):
srccn[x] = scntt[x]
srccn.tofile('books/0.cont')
stats = np.zeros(197)
stcnt = Counter(individual.flatten())
for x in range(197):
stats[x] = stcnt[x]
return 1000000 - np.sum(np.fabs(stats - (srccn/len(individual))))
def grade(pop, s='',target=0):
'Find average fitness for a population.'
arr = np.array([fitness(x, s, target) for x in pop])
printv(arr)
summed = np.sum(arr)
return summed / (len(pop) * 1.0)
def evolve(pop, end=False, s='', length=4194304, target=0, retain=0.25, random_select=0.05, mutate=0.01):
#printv("start evolve")
graded = np.array([x[1] for x in sorted([(fitness(x, target), x) for x in pop],key=itemgetter(0),reverse=True)],dtype=np.uint8)
retain_length = int(len(graded)*retain)
parents = graded[:retain_length]
# randomly add other individuals to promote genetic diversity
for individual in graded[retain_length:]:
if random_select > random.random():
np.append(parents,individual)
# mutate some individuals
for individual in parents:
if mutate > np.random.random():
for x in range(int(length*0.01)):
#mutate 1% of the positions of an individual
pos_to_mutate = np.random.randint(0, len(individual))
individual = individual.flatten()
individual[pos_to_mutate] = np.random.choice(s.flatten())
individual.reshape(256,128,128)
# crossover parents to create children
parents_length = len(parents)
desired_length = len(pop) - parents_length
children = []
iuo = 0
while len(children) < desired_length:
male = np.random.randint(0, parents_length-1)
female = np.random.randint(0, parents_length-1)
if male != female:
male = parents[male].flatten()
female = parents[female].flatten()
#chunk select: (x%128)<16 and (x%16384)<2048
child = np.zeros(128*128*256, dtype=np.uint8)
printv("C"+str(iuo)+",",end="",flush=True)
for k in range(4194304):
if ((k%128)%32)<16 and ((k%16384)%4096)<2048:
child[k] = male[k]
elif ((k%128)%32)>=16 and ((k%16384)%4096)>=2048:
child[k] = male[k]
else:
child[k] = female[k]#reversed of female (adds genetic diversity)
children.append(child)
iuo = iuo+1
children = np.array(children,dtype=np.uint8)
children = children.reshape(desired_length,256,128,128)
#print("shape", parents.shape, children.shape)
parents = np.concatenate((parents,children))
if end:
parents = np.array([x[1] for x in sorted([(fitness(x, target), x) for x in parents],key=itemgetter(0),reverse=True)],dtype=np.uint8)
return parents
def _schema(blst=[0]*4194304,h=256,l=128,w=128):
if len(blst) < 4194304:
#pad
blst = blst + [0]*(4194304-len(blst))
elif len(blst) > 4194304:
#truncate
blst = blst[:4194304]
result = NBTFile() #Blank NBT
result.name = "Schematic"
result.tags.extend([
TAG_Short(name="Height", value=h),
TAG_Short(name="Length", value=l),
TAG_Short(name="Width", value=w),
TAG_Byte_Array("Biomes",gbba([0]*16384,True)),
TAG_Byte_Array("Blocks", gbba(blst,True)),
TAG_Byte_Array("Data",gbba([0]*4194304,True)),
TAG_String(name="Materials", value="Alpha"),
TAG_List(type=foo(),name="Entities"),
TAG_List(type=foo(),name="TileEntities"),
TAG_List(type=foo(),name="TileTicks")
])
return result
def gbba(blocksList, buffer=False):
"""Return a list of all blocks in this chunk."""
if buffer:
length = len(blocksList)
return BytesIO(pack(">i", length)+gbba(blocksList))
else:
return array.array('B', blocksList).tostring()
def main(gue=True,fake=False,fold='Moe'):
gui = """#########################################################
Intelligent Procedural Level Generation #5.00
using Minecraft, MCEdit, NBTExplorer, numpy, #threading#
source: {}
cmd: select source - 0, generate schematic - 1, test schematic - 2, exit - 3
"""
while True:
if(gue==False):
sourcename = glob.glob('books/*.nsorce')[0]
source = np.fromfile(sourcename, dtype=np.uint8).reshape(256,512,512)
cmd = 1
else:
try:
print(gui.format(sourcename))
except:
try:
sourcename = glob.glob('books/*.nsorce')[0]
source = np.fromfile(sourcename, dtype=np.uint8).reshape(256,512,512)
continue
except:
printv('<SOURCE REQUIRED>')
printv('add .nsorce to book dir and')
input('press enter')
continue
try:
cmd = int(input('c: '))
except:
printv("command must be integer")
continue
if cmd == 0:#select source
directory = glob.glob('books/*.nsorce')
printv(directory)
wid = input('Select Source ID: ')
try:
sourcename = directory[int(wid)]
except:
continue
source = np.fromfile(sourcename, dtype=np.uint8).reshape(256,512,512)
elif cmd == 1:#generate schematics
if (gue==False):
name = fold
psize = 20
gennm = 10
org = 1
exister = "qtORG"
#auto
#name = '3t'
#psize = 1
gennm = 0
else:
name = input('Book Folder name: ')
try:
fake = int(input('Quilt - 0 or Solid - 1 or Random - 2\nQuilt[NO GEN] - 3 or Existing - 4 or Quilt V2 - 5 or Legacy Quilt(Slow) - 6\n'))
except:
fake = 1
try:
psize = int(math.fabs(int(input('Pop Size: '))))
except:
psize = 20
try:
gennm = int(math.fabs(int(input('Number of Generations: '))))
except:
gennm = 10
try:
org = int(input('save intial 1 or discard intial 0\n'))
except:
org = 0
if fake==4:
exister = input('Directory of Existing Nboks?\n')
if name == "":
continue
j = "schema/"+name+"/"
k = "books/"+name+"/"
if not os.path.exists(j):
os.makedirs(j)
if not os.path.exists(k):
os.makedirs(k)
if fake==1:
p = artpop()
elif fake==2:
p = population(source,psize,True)
elif fake==3:
#by default saves initial
gennm = 0
p = population(source,psize)
elif fake==4:
p = artpop(exister)
elif fake==5:
if org:
p = population(source,psize,org=name,leg=1)
else:
p = population(source,psize,leg=1)
elif fake==6:
if org:
p = population(source,psize,org=name,leg=2)
else:
p = population(source,psize,leg=2)
else:
if org:
p = population(source,psize,org=name)
else:
p = population(source,psize)
fitness_history = np.zeros(gennm+1)
printv("Int Grade")
fitness_history[0] = grade(p,s=source)
printv("generation INTIAL")
printv(fitness_history[0])
for i in range(gennm):
printv("generation "+str(i+1))
if i==gennm-1:
p = evolve(p,True,source)#last p, returns reverse sorted list
else:
p = evolve(p,s=source)
fitness_history[i+1] = grade(p)
printv(fitness_history[i+1])
jkl = 0
for _ in p:
_ = _.flatten()
_.tofile(k+str(jkl)+'.nbok')
mine = _schema(blst=_.tolist())
mine.write_file(j+str(jkl)+'.schematic')
jkl = jkl+1
if gue==False:
break
elif cmd == 3:#exit
break
elif cmd == 2:#test schematic
name = input('Schematic Name:')
try:
typ = input('Type? B - Blank, R - Random, L - Random Legal, S - Source(nbok), Q - Quilt\n: ').lower()
except:
typ ='b'
if name == "":
continue
if typ == 'b':
mine = _schema()
elif typ == 'r':
mp = np.random.randint(197, size=4194304)
mp.tofile('books/'+typ.upper()+name+".nbok")
mine = _schema(mp.tolist())
elif typ == 'l':
mp = np.random.randint(91, size=4194304)
mp.tofile('books/'+typ.upper()+name+".nbok")
mine = _schema(mp.tolist())
elif typ == 'q':
mp = quilt(4194304,source).flatten()
mp.tofile('books/'+typ.upper()+name+".nbok")
mine = _schema(mp.tolist())
elif typ == 's':
mp = np.fromfile("books/"+name+".nbok", dtype=np.uint8)
mine = _schema(mp.tolist())
else:
typ = 'b'
mine = _schema()
printv(mine.pretty_tree())
mine.write_file("schema/"+typ.upper()+name+".schematic")
else:
printv("Command {} is not found".format(cmd))
return 0
if __name__ == '__main__':
g = False
f = False
if len(sys.argv) >= 2:
try:
sys.argv.index("-g")
g = True
except:
pass
try:
sys.argv.index("-f")
f = True
except:
pass
if g and f:
sys.exit(main(g,f))
elif g:
sys.exit(main(g))
elif f:
sys.exit(main(fake=f))
else:
sys.exit(main())