-
Notifications
You must be signed in to change notification settings - Fork 1
/
LevelBuilder.py
1456 lines (1298 loc) · 71.8 KB
/
LevelBuilder.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# eventually: separate out different pieces of the addon into modules
# https://b3d.interplanety.org/en/creating-multifile-add-on-for-blender/
# moduleNames = ['customUI', 'addActor', 'fileTemplates', 'meshData', 'iconData']
# create new python files for adding a new actor to these modules
# ------------------------------------------------------------------------
# Addon Info
# ------------------------------------------------------------------------
bl_info = {
"name": "OpenGOAL Custom Level Builder",
"description": "modified from https://gist.github.com/p2or/2947b1aa89141caae182526a8fc2bc5a and https://github.com/blender/blender/blob/master/release/scripts/templates_py/addon_add_object.py",
"author": "himham",
"version": (1, 2, 0),
"blender": (2, 92, 0),
"location": "3D View > Level Info",
"warning": "",
"category": "Development"
}
# ------------------------------------------------------------------------
# Includes
# ------------------------------------------------------------------------
import bpy, bmesh, os, re, shutil, math, fileinput, socket, struct, sys, json
from bpy.app.handlers import persistent
from bpy.props import (StringProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
EnumProperty,
PointerProperty,
)
from bpy.types import (Panel,
Menu,
Operator,
PropertyGroup,
)
from bpy.utils import previews
from bpy_extras.object_utils import AddObjectHelper, object_data_add
from mathutils import Vector
# this config file is not on a per level basis, it's the config for the addon itself so you don't have to enter everything again
if os.path.exists("blender_goal_config.json"):
with open("blender_goal_config.json", "r") as f:
json_data = json.loads(f.read())
else:
with open("blender_goal_config.json", "w") as f:
f.write('{"Custom Levels Path": ""}')
# ------------------------------------------------------------------------
# Scene Properties
# ------------------------------------------------------------------------
class MyProperties(PropertyGroup):
level_title: StringProperty(
name="Level Title",
description="The name of your custom level.\nOnly letters and dashes are allowed, case will be ignored.\nDefault: my-level",
default="my-level",
maxlen=1024,
)
level_nickname: StringProperty(
name="Level Nickname",
description="The nickname of your custom level.\nThree letters, case will be ignored.\nDefault: lvl",
default="lvl",
maxlen=3,
)
anchor: StringProperty(
name="Anchor",
description="The Parent of all your level geometry. The anchor itself will not export.\nSuggestion: Create a new empty, Parent all your geometry to it. Select the empty here.",
maxlen=1024,
)
spawn_location: FloatVectorProperty(
name = "Spawn Location",
description="The location in 3d space to place Jak.\nDefault: 0,0,0",
default=(0.0, 0.0, 0.0),
)
level_rotation: FloatVectorProperty(
name = "Level Rotation",
description="The quaternion rotation in 3d space to place your custom level.\nDefault: 0,0,0,1",
default=(0.0, 0.0, 0.0), # Blender doesn't want me to make a 4d vector
min= 0.0,
max = 1.0
)
custom_levels_path: StringProperty(
name = "Custom Levels Path",
description="The path to /custom_levels/ in the OpenGOAL distribution",
default=json_data["Custom Levels Path"],
maxlen=1024,
subtype='DIR_PATH'
)
should_export_level_info: BoolProperty(
name="Level Info",
description="Check if you'd like the level info to be included when you export",
default = True
)
should_export_actor_info: BoolProperty(
name="Actor Info",
description="Check if you'd like the actor info to be included when you export",
default = True
)
should_export_geometry: BoolProperty(
name="Level Geometry",
description="Check if you'd like the level geometry to be included when you export",
default = True
)
should_playtest_level: BoolProperty(
name="Playtest Level",
description="Check if you'd like to launch the level immediately after export",
default = True
)
actor_name: StringProperty(
name="Actor Name",
description="The name of your object (actor).\nOnly lowercase letters and dashes are allowed.\nDefault: my-level",
default="my-actor",
maxlen=1024,
)
actor_type: EnumProperty(
name="Actor Type",
description="Apply Data to attribute.",
items=[ ('collectable', '', ''),
('eco-collectable', '', ''),
('eco', '', ''),
('eco-yellow', 'Yellow Eco', ''),
('eco-red', 'Red Eco', ''),
('eco-blue', 'Blue Eco', ''),
('health', 'Green Eco', ''),
('eco-pill', 'Green Eco Pill', ''),
('money', 'Precursor Orb', ''),
('fuel-cell', 'Power Cell', ''),
('buzzer', 'Scout Fly', ''),
('ecovalve', 'Eco Valve', ''),
('vent', '', ''),
('ventyellow', 'Yellow Eco Vent', ''),
('ventred', 'Red Eco Vent', ''),
('ventblue', 'Blue Eco Vent', ''),
('ecovent', 'Eco Vent', ''),
('vent-wait-for-touch', '', ''),
('vent-pickup', '', ''),
('vent-standard-event-handler', '', ''),
('vent-blocked', '', ''),
('ecovalve-init-by-other', '', ''),
('*ecovalve-sg*', '', ''),
('ecovalve-idle', '', ''),
('*eco-pill-count*', '', ''),
('birth-pickup-at-point', '', ''),
('*buzzer-sg*', '', ''),
('fuel-cell-pick-anim', '', ''),
('fuel-cell-clone-anim', '', ''),
('*fuel-cell-tune-pos*', '', ''),
('*fuel-cell-sg*', '', ''),
('othercam-init-by-other', '', ''),
('fuel-cell-animate', '', ''),
('*money-sg*', '', ''),
('add-blue-motion', '', ''),
('check-blue-suck', '', ''),
('initialize-eco-by-other', '', ''),
('add-blue-shake', '', ''),
('money-init-by-other', '', ''),
('money-init-by-other-no-bob', '', ''),
('fuel-cell-init-by-other', '', ''),
('fuel-cell-init-as-clone', '', ''),
('buzzer-init-by-other', '', ''),
('crate-post', '', ''),
('*crate-iron-sg*', '', ''),
('*crate-steel-sg*', '', ''),
('*crate-darkeco-sg*', '', ''),
('*crate-barrel-sg*', '', ''),
('*crate-bucket-sg*', '', ''),
('*crate-wood-sg*', '', ''),
('*CRATE-bank*', '', ''),
('crate-standard-event-handler', '', ''),
('crate-init-by-other', '', ''),
('crate-bank', '', ''),
('crate', '', ''), # eco-info [item,quantity] item: 1=yellow 2=red 3=green 4=cell 5=orb 6=blue 7=pill 8=fly 9+=empty, enames=crate/iron,steel,bucket,barrel
('barrel', '', ''),
('bucket', '', ''),
('crate-buzzer', 'Scout Fly Box', ''),
('pickup-spawner', '', ''),
('double-lurker', 'Double Lurker', ''),
('evilbro', 'Gol', ''),
('evilsis', 'Maya', ''),
('explorer', 'Explorer', ''),
('farmer', 'Farmer', ''),
('balloon', 'Balloon', ''),
('spike', 'Spike', ''),
('crate-darkeco-cluster', 'Cluster of Dark Eco Crates', ''),
('flutflut', 'Flut Flut', ''),
('geologist', 'Geologist', ''),
('hopper', 'Hopper', ''),
('junglesnake', 'Jungle Snake', ''),
('kermit', 'Kermit', ''),
('lurkercrab', 'Lurker Crab', ''),
('lurkerpuppy', 'Lurker Puppy', ''),
('lurkerworm', 'Lurker Worm', ''),
('mother-spider', 'Mother Spider', ''),
('muse', 'Muse', ''),
('swamp-rat', 'Swamp Rat', ''),
('yeti', 'Yeti', ''),
('yakow', 'Yakow', ''),
('orbit-plat', 'Orbiting Platform', ''),
('steam-cap', 'Steam Cap Platform', ''),
('citb-plat', 'Citadel B Platform', ''),
('citb-button', 'Citadel B Button', ''),
('citb-drop-plat', 'Citadel B Drop Platform', ''),
('wall-plat', 'Wall Platform', ''),
('wedge-plat', 'Wedge Platform', ''),
('wedge-plat-outer', 'Wedge Platform Outer', ''),
('puffer', 'Puffer', ''),
('babak', 'Gorilla', ''),
('babak-with-cannon', 'Gorilla with Cannon', ''),
('seaweed', 'Seaweed', ''),
('ropebridge', 'Rope Bridge', ''),
]
)
actor_location: FloatVectorProperty(
name = "Actor Location",
description="The location in 3d space to place your object (actor).\nDefault: -21.6238,20.0496,17.1191",
default=(-21.6238, 20.0496, 17.1191),
min= 0.0,
max = 25.0
)
actor_rotation: FloatVectorProperty(
name = "Actor Rotation",
description="The quaternion rotation in 3d space to place your object (actor.\nDefault: 0,0,0,1",
default=(0.0, 0.0, 0.0), # Blender doesn't want me to make a 4d vector
min= 0.0,
max = 1.0
)
# unused properties
my_bool: BoolProperty(
name="Boolean",
description="A bool property",
default = False
)
my_float: FloatProperty(
name = "Float Value",
description = "A float property",
default = 23.7,
min = 0.01,
max = 30.0
)
# ------------------------------------------------------------------------
# Operators
# ------------------------------------------------------------------------
class WM_OT_World_Ref(Operator):
bl_label = "Create World Reference*"
bl_idname = "wm.create_world_reference"
bl_description = "Imports the game's level models so that you can position your level within the world."
def execute(self, context):
scene = context.scene
mytool = scene.my_tool
# check that debug_out folder is populated with objs
# run batch import
# put the location to the folder where the objs are located here in this fashion
path_to_obj_dir = os.path.dirname(os.path.dirname(mytool.custom_levels_path))+"\\debug_out\\"
# get list of all files in directory
file_list = sorted(os.listdir(path_to_obj_dir))
# get a list of files ending in 'obj'
obj_list = [item for item in file_list if item.endswith('.obj')]
# check if it's empty and throw an error
if obj_list == []:
show_message("You don't seem to have extracted the level geometry from the game. Try turning on the levels_convert_to_obj option in the decompiler config and extracting from your iso again.","Error","ERROR")
return {'CANCELLED'}
# create an anchor for the world geometry
bpy.ops.object.empty_add(type='PLAIN_AXES', location=(0, 0, 0))
anchor = bpy.context.object
anchor.name = "World Geometry"
# loop through the strings in obj_list and add the files to the scene
for item in obj_list:
path_to_file = os.path.join(path_to_obj_dir, item)
bpy.ops.import_scene.obj(filepath = path_to_file)
bpy.context.scene.objects[item[:-4]].parent = anchor # parent them to the anchor
# scale up by 16
anchor.scale=(16,16,16)
return {'FINISHED'}
class WM_OT_Export(Operator):
bl_label = "Export"
bl_idname = "wm.export"
bl_description = "Exports the Level Info, Level Geometry, and Actor Info.\nAfter exporting, be sure to read the README"
def execute(self, context):
scene = context.scene
mytool = scene.my_tool
# validate level info inputs
# eventually want validation to live update while you're typing
if not bool(re.match("^[A-Za-z-]*$", mytool.level_title)): # should have only letters and dashes
show_message("Level Title can only contain letters and dashes","Error","ERROR")
return {'CANCELLED'}
if not bool(re.match("^[A-Za-z]*$", mytool.level_nickname)): # should have only letters
show_message("Level Nickname can only contain letters","Error","ERROR")
return {'CANCELLED'}
if (mytool.anchor == "") & mytool.should_export_geometry:
show_message("Anchor cannot be empty if exporting geometry","Error","ERROR")
return {'CANCELLED'}
if mytool.custom_levels_path == "": # can't be empty
show_message("Custom Levels Path cannot be empty","Error","ERROR")
return {'CANCELLED'}
if not os.path.dirname(mytool.custom_levels_path)[-19:] == "\data\custom_levels": # check dir and parent dir are correct
show_message("Custom Levels Path seems incorrect","Error","ERROR")
return {'CANCELLED'}
# create values needed to make files
longtitle = mytool.level_title.lower()
title = re.sub(r'[^\w\s]', '', mytool.level_title)[0:8] # create 8 digit alpha-only short title
nick = mytool.level_nickname.lower()
newpath = mytool.custom_levels_path+longtitle+"\\"
# be extra
print("\n ---Beginning Export Process---\n")
# keep track of what task we're on
task_count = (mytool.should_export_level_info or mytool.should_export_actor_info)+mytool.should_export_geometry+mytool.should_playtest_level
current_task = 1
# update level info and actor info if needed
current_task = update_files(task_count, current_task, mytool.should_export_level_info, mytool.should_export_actor_info, newpath, nick, longtitle, title, mytool.spawn_location)
# export the geometry
# may need to update renderer to cycles before exporting, just in case. make sure to notify user.
if mytool.should_export_geometry:
print("Task ("+str(current_task)+"/"+str(task_count)+")")
current_task += 1
export_geometry(context, mytool.anchor, newpath, longtitle)
# open the level in game
if mytool.should_playtest_level:
print("Task ("+str(current_task)+"/"+str(task_count)+")")
current_task += 1
playtest_level(longtitle, newpath)
return {'FINISHED'}
# ------------------------------------------------------------------------
# Functions
# ------------------------------------------------------------------------
def show_message(message, title = "Message", icon = "INFO"):
def draw(self, context):
self.layout.label(text = message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
def return_actor_block(actor_name, actor_type, actor_location, actor_rotation, game_task, bsphere_radius):
return [
' {\n',
' "trans": [',
str(actor_location[0]),
', ',
str(actor_location[2]),
', ',
str(actor_location[1]),
'],\n',
' "etype": "',
actor_type,
'",\n',
' "game_task": ',
str(game_task),
',\n',
' "quat" : [',
str(actor_rotation[0]),
', ',
str(actor_rotation[1]),
', ',
str(actor_rotation[2]),
', ',
str(actor_rotation[3]),
'],\n',
' "bsphere": [',
str(actor_location[0]),
', ',
str(actor_location[2]),
', ',
str(actor_location[1]),
', ',
str(bsphere_radius),
'],\n',
' "lump": {\n',
' "name":"',
actor_name,
'"\n',
' }\n',
' }',
]
def update_files(task_count, current_task, should_export_level_info, should_export_actor_info, newpath, nick, longtitle, title, spawn):
if not should_export_level_info:
return current_task
print("Task ("+str(current_task)+"/"+str(task_count)+")")
current_task += 1
print("Updating the necessary files.\n")
# make the new folder
if not os.path.exists(newpath):
os.mkdir(newpath)
print("\tDirectory created.")
# save the custom levels path so it doesn't have to be retyped
with open("blender_goal_config.json", "r+") as f:
file = f.read()
json_data = json.loads(file)
json_data["Custom Levels Path"]=os.path.dirname(os.path.dirname(newpath))+"\\"
f.seek(0)
f.truncate()
json.dump(json_data, f)
# save the blend file
bpy.ops.wm.save_as_mainfile(filepath=newpath+longtitle+'.blend')
# make paths for game.gp and level-info.gc
gppath = os.path.dirname(os.path.dirname(os.path.dirname(newpath)))+"\\goal_src\\jak1\\"
gcpath = gppath+"engine\\level\\"
gd = [
'("',
nick,
'.DGO"\n',
' ("static-screen.o" "static-screen")\n',
' ("',
longtitle,
'.go" "',
longtitle,
'")\n',
' )'
]
jsonc = [
'{\n',
' "long_name": "',
longtitle,
'",\n',
' "iso_name": "',
title.upper(),
'",\n',
' "nickname": "',
nick.upper(),
'", // 3 char name, all uppercase\n\n',
' "gltf_file": "custom_levels/',
longtitle,
'/',
longtitle,
'.glb",\n',
' "automatic_wall_detection": true,\n',
' "automatic_wall_angle": 45.0,\n',
' "actors" : [\n'
]
jsonc_end = [
' ]\n',
'}'
]
readme = [
"test line 1\n",
"test line 2\n",
"test line 3"
]
gc = [
"\n\n(define ",
longtitle,
" (new 'static 'level-load-info\n",
" :index 26\n",
" :name '",
longtitle,
"\n :visname '",
longtitle,
"-vis ;; name + -vis\n",
" :nickname '",
nick,
"\n :packages '()\n",
" :sound-banks '()\n",
" :music-bank #f\n",
" :ambient-sounds '()\n",
" :mood '*default-mood*\n",
" :mood-func 'update-mood-default\n",
" :ocean #f\n",
" :sky #t\n",
" :continues '((new 'static 'continue-point\n",
" :name \"",
longtitle,
"-start\"\n",
" :level '",
longtitle,
"\n :trans (new 'static 'vector :x (meters ",
str(spawn[0]),
") :y (meters ",
str(spawn[2]+5),
") :z (meters ",
str(spawn[1]),
",) :w 1.0)\n",
" :quat (new 'static 'quaternion :w 1.0)\n",
" :camera-trans (new 'static 'vector :x 0.0 :y 4096.0 :z 0.0 :w 1.0)\n",
" :camera-rot (new 'static 'array float 9 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0)\n",
" :load-commands '()\n",
" :vis-nick 'none\n",
" :lev0 '",
longtitle,
"\n :disp0 'display\n",
" :lev1 'village1\n",
" :disp1 'display\n",
" ))\n",
" :tasks '()\n",
" :priority 100\n",
" :load-commands '()\n",
" :alt-load-commands '()\n",
" :bsp-mask #xffffffffffffffff\n",
" :bsphere (new 'static 'sphere :w 167772160000.0)\n",
" :bottom-height (meters -20)\n",
" :run-packages '()\n",
" :wait-for-load #t\n",
" )\n",
" )\n\n",
"(cons! *level-load-list* '",
longtitle,
")"
]
gp = '\n(build-custom-level "'+longtitle+'")\n'+'(custom-level-cgo "'+nick.upper()+'.DGO" "'+longtitle+'/'+title+'.gd")\n'
# create gd
path = newpath
filename = title+".gd"
contents = gd
if not os.path.exists(path+filename):
f = open(path+filename, 'w', encoding="utf-8")
# write the contents
f.writelines(contents)
# close the file
f.close()
print("\t"+filename+" created.")
else:
print("\t"+filename+" already exists, creation skipped.")
# create jsonc
path = newpath
filename = longtitle+".jsonc"
contents = jsonc
if not os.path.exists(path+filename):
f = open(path+filename, 'w', encoding="utf-8")
# write the contents
f.writelines(contents)
contents = []
commas = len(bpy.data.collections['actor_collection'].all_objects)
for actor in bpy.data.collections['actor_collection'].all_objects:
contents+=return_actor_block(actor.name, actor["Actor Type"], actor.location, actor.rotation_quaternion, actor["Game Task"], actor["Bounding Sphere Radius"])
if commas>1:
contents+=",\n\n"
commas-=1
else:
contents+="\n\n"
f.writelines(contents)
contents = jsonc_end
f.writelines(contents)
# close the file
f.close()
print("\t"+filename+" created.")
else:
print("\t"+filename+" already exists, creation skipped.")
# create readme
path = newpath
filename = "README.MD"
contents = readme
if not os.path.exists(path+filename):
f = open(path+filename, 'w', encoding="utf-8")
# write the contents
f.writelines(contents)
# close the file
f.close()
print("\t"+filename+" created.")
else:
print("\t"+filename+" already exists, creation skipped.")
# create a backup and append new level to level-info.gc
path = gcpath
filename = "level-info.gc"
backupname = "level-info.bak"
contents = gc
needs_update = True
# check level-info.gc for the level before adding it
f = open(path+filename, 'r', encoding="utf-8")
for line in f:
if longtitle in line:
needs_update = False
# close the file
f.close()
if needs_update:
shutil.copyfile(path+filename,path+backupname)
print("\tBackup of level-info.gc created")
f = open(path+filename, 'a', encoding="utf-8")
# write the contents
f.writelines(contents)
# close the file
f.close()
print("\t"+filename+" updated.")
else:
print("\t"+filename+" already contains the level, modification skipped.")
# create a backup and append new level to game.gp
path = gppath
filename = "game.gp"
backupname = "game.bak"
contents = gp
needs_update = True
# check level-info.gc for the level before adding it
f = open(path+filename, 'r', encoding="utf-8")
for line in f:
if longtitle in line:
needs_update = False
# close the file
f.close()
if needs_update:
shutil.copyfile(path+filename,path+backupname)
print("\tBackup of game.gp created")
match_string = "testzone.gd\")"
with open(path+filename, 'r+') as f:
current = f.readlines()
if match_string in current[-1]: # this will fail if the levels have to be in order
current.append(contents)
else:
for index, line in enumerate(current):
if match_string in line and contents not in current[index + 1]:
current.insert(index + 1, contents)
break
f.seek(0)
f.writelines(current)
print("\t"+filename+" updated.")
else:
print("\t"+filename+" already contains the level, modification skipped.")
print("\nDone.\n")
return current_task
def export_geometry(context, anchor, newpath, longtitle):
print("Exporting geometry.\n")
if not os.path.exists(newpath+longtitle+".glb"):
bpy.ops.object.select_all(action='DESELECT') # deselect everything, probably not necessary
bpy.context.scene.objects[anchor].select_set(True) # select the anchor
bpy.ops.object.select_grouped(type='CHILDREN_RECURSIVE') # select the anchor's children
bpy.ops.export_scene.gltf( # actually export
filepath=newpath+longtitle+".glb",
use_selection=True # export only the selection
)
print("\t"+longtitle+".glb created.\n")
else:
print("\t"+longtitle+".glb already exists, creation skipped.\n")
print("Done.\n")
def playtest_level(longtitle,newpath):
print("Beginning playtest.\n")
opengoalpath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(newpath))))
#print(opengoalpath)
#os.system('''start cmd @cmd /c "cd ..\Games\opengoal-v0.1.19-windows && gk -boot -fakeiso -debug" ''') # open the game in debug mode
#os.system('''start cmd @cmd /k "cd ..\Games\opengoal-v0.1.19-windows && goalc --startup-cmd "(mi) (lt)"" ''') # open the repl, rebuild, and link to game
#os.system('''start cmd @cmd /c "cd '''+opengoalpath+''' && gk -boot -fakeiso -debug" ''') # open the game in debug mode
#os.system('''start cmd @cmd /k "cd '''+opengoalpath+''' && goalc --startup-cmd "(mi) (lt) (r) (bg-custom \''''+longtitle+'''-vis)"" ''') # open the repl, rebuild, and link to game
#keyboard.write("Python is an amazing programming language.")
# run (bg-custom 'longtitle-vis) in the repl
#print("Message: Sorry, for now you'll have to run (bg-custom '"+longtitle+"-vis) in goalc manually.\n")
# create a socket
try:
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
except socket.error as e:
print("Error creating socket: %s" % e)
return 0
# establish a socket connection with the repl
# if no repl is open, try to open one and connect to it
try:
clientSocket.connect(("127.0.0.1", 8181)) # "127.0.0.1", 8181 for repl by default
except socket.gaierror as e:
print("Address-related error connecting to server: %s" % e)
except socket.error as e:
print("Connection error: %s")
#print(e)
print("\tWe didn't find an open instance of goalc.")
print("\tAttempting to open one for you.")
os.system('''start cmd @cmd /k "cd '''+ opengoalpath +''' && goalc''') # open the repl
try:
clientSocket.connect(("127.0.0.1", 8181)) # "127.0.0.1", 8181 for repl by default
except socket.gaierror as e:
print("Address-related error connecting to server: %s" % e)
except socket.error as e:
print("Connection error: %s")
#print(e)
print("\tWe didn't find an open instance of goalc. Exiting.")
return 0
try:
data = clientSocket.recv(33) # connection confirmation message is 33 symbols
print("\t"+data.decode())
form = "(bg-custom \'"+ longtitle +"-vis)"
header = struct.pack('<II', len(form), 10)
clientSocket.sendall(header + form.encode())
print("\tLevel sent to goalc. If it fails to open, make sure you have the game connected.")
except socket.error as e:
print ("Error sending data: %s" % e)
print("Done.\n")
#delete
class WM_OT_PrintActors(Operator):
bl_label = "Print"
bl_idname = "wm.print"
def execute(self, context):
#bpy.context.object["MyOwnProperty"] = 7
#print(bpy.context.object)
#print(bpy.context.object["MyOwnProperty"])
return {'FINISHED'}
# ------------------------------------------------------------------------
# Panel in Object Mode
# ------------------------------------------------------------------------
class OBJECT_PT_LevelInfoPanel(Panel):
bl_label = "Level Info"
bl_idname = "OBJECT_PT_level_info_panel"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Level Editing"
bl_context = "objectmode"
@classmethod
def poll(self,context):
return context.object is not None
def draw(self, context):
layout = self.layout
scene = context.scene
mytool = scene.my_tool
# live input validation
title = layout.row()
if not (bool(re.match("^[A-Za-z-]*$", mytool.level_title)) and mytool.level_title):
title.alert = True
nick = layout.row()
if not (bool(re.match("^[A-Za-z]*$", mytool.level_nickname)) and mytool.level_nickname):
nick.alert = True
anch = layout.row()
if (mytool.should_export_geometry and not mytool.anchor): # live input validation fails, no idea why
anch.alert = True
trans = layout.column()
if not mytool.anchor:
trans.active = False
path = layout.row()
if not mytool.custom_levels_path:
path.alert = True
if not os.path.dirname(mytool.custom_levels_path)[-19:] == "\data\custom_levels":
path.alert = True
# set these properties manually
title.prop(mytool, "level_title", icon="TEXT") # validate not in list? "training","village1","beach","jungle","jungleb","misty","firecanyon","village2","sunken","sunkenb","swamp","rolling","ogre","village3","snow","maincave","darkcave","robocave","lavatube","citadel","finalboss","intro","demo","title","halfpipe","default-level"
nick.prop(mytool, "level_nickname", icon="TEXT")
anch.prop_search(mytool, "anchor", scene, "objects", icon="EMPTY_AXIS")
trans.prop(mytool, "spawn_location", text="Spawn Location*")
trans.prop(bpy.context.scene.objects[mytool.anchor], "location", text = "Anchor Location*") # breaks when no anchor is selected
#trans.prop(mytool, "level_rotation", text="Level Rotation*")
anch.operator("wm.create_world_reference")
path.prop(mytool, "custom_levels_path")
layout.prop(mytool, "should_export_level_info")
layout.prop(mytool, "should_export_actor_info", text="Actor Info*")
layout.prop(mytool, "should_export_geometry", )
layout.prop(mytool, "should_playtest_level")
layout.operator("wm.export")
layout.label(text="Options with * do not currently export/function.", icon="ERROR")
layout.separator()
class OBJECT_PT_ActorInfoPanel(Panel):
bl_label = "Actor Info*"
bl_idname = "OBJECT_PT_actor_info_panel"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Level Editing"
bl_context = "objectmode"
@classmethod
def poll(self,context):
return context.object is not None
def draw(self, context):
layout = self.layout
scene = context.scene
mytool = scene.my_tool
if (bpy.context.object.data is not None) and ("Game Task" in bpy.context.object.data.keys()): # only check for custom properties on actors, not other objects
layout.prop(context.active_object, "name", text = "Actor Name")
layout.prop(mytool, "actor_type") # dummy
layout.prop(context.active_object, "type")
# these properties auto populate
layout.prop(context.active_object, "location", text = "Actor Location")
layout.prop(context.active_object, "rotation_quaternion", text = "Actor Rotation") # this won't display properly unless the object is in quaternion mode, so I force all actors into quat mode when added
# set these properties manually in the panel
layout.prop(bpy.data.objects[bpy.context.object.data.name], '["Actor Type"]')
layout.prop(bpy.data.objects[bpy.context.object.data.name], '["Game Task"]')
layout.prop(bpy.data.objects[bpy.context.object.data.name], '["Bounding Sphere Radius"]')
#layout.operator("wm.print") # this is a debug button to print all the current actors and their attributes before exporting
else:
layout.label(text="Select an actor to see its properties.", icon="ERROR")
layout.separator()
# ------------------------------------------------------------------------
# Panel in Mesh Edit Mode # At the moment, i don't really use this
# ------------------------------------------------------------------------
class EDIT_PT_LevelInfoPanel(Panel):
bl_label = "Level Info"
bl_idname = "EDIT_PT_level_info_panel"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Level Editing"
bl_context = "mesh_edit"
@classmethod
def poll(self,context):
return context.object is not None
def draw(self, context):
layout = self.layout
scene = context.scene
mytool = scene.my_tool
# set these properties manually
layout.prop(mytool, "level_title", icon="TEXT") # validate not in list? "training","village1","beach","jungle","jungleb","misty","firecanyon","village2","sunken","sunkenb","swamp","rolling","ogre","village3","snow","maincave","darkcave","robocave","lavatube","citadel","finalboss","intro","demo","title","halfpipe","default-level"
layout.prop(mytool, "level_nickname", icon="TEXT")
layout.prop_search(mytool, "anchor", scene, "objects", icon="EMPTY_AXIS")
layout.prop(mytool, "level_location", text="Level Location*")
layout.prop(mytool, "level_rotation", text="Level Rotation*")
layout.prop(mytool, "custom_levels_path")
layout.prop(mytool, "should_export_level_info")
layout.prop(mytool, "should_export_actor_info", text="Actor Info*")
layout.prop(mytool, "should_export_geometry", )
layout.prop(mytool, "should_playtest_level")
layout.label(text="Switch to Object Mode to export.", icon="ERROR")
layout.label(text="Options with * do not currently export.", icon="ERROR")
layout.separator()
class EDIT_PT_ActorInfoPanel(Panel):
bl_label = "Actor Info*"
bl_idname = "EDIT_PT_actor_info_panel"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Level Editing"
bl_context = "mesh_edit"
@classmethod
def poll(self,context):
return context.object is not None
def draw(self, context):
layout = self.layout
scene = context.scene
mytool = scene.my_tool
if "Game Task" in bpy.data.objects[bpy.context.object.data.name].keys(): # only check for custom properties on actors, not other objects
layout.prop(context.active_object, "name", text = "Actor Name")
layout.prop(mytool, "actor_type") # dummy
layout.prop(context.active_object, "type")
# these properties auto populate
layout.prop(context.active_object, "location", text = "Actor Location")
layout.prop(context.active_object, "rotation_quaternion", text = "Actor Rotation") # this won't display properly unless the object is in quaternion mode, so I force all actors into quat mode when added
# set these properties manually in the panel
layout.prop(bpy.data.objects[bpy.context.object.data.name], '["Actor Type"]')
layout.prop(bpy.data.objects[bpy.context.object.data.name], '["Game Task"]')
layout.prop(bpy.data.objects[bpy.context.object.data.name], '["Bounding Sphere"]')
#layout.operator("wm.print") # this is a debug button to print all the current actors and their attributes before exporting
else:
layout.label(text="Select an actor to see its properties.", icon="ERROR")
layout.separator()
# ------------------------------------------------------------------------
# New Mesh Initialization # This will be cleaned up with the verts,edges,faces in a separate file for each actor model
# ------------------------------------------------------------------------
actor_types = [
["Precursor Orb","money"],
["Power Cell","fuel-cell"],
["Green Eco","greeneco"],
["Blue Eco","blueeco"],
["Yellow Eco","yelloweco"],
["Red Eco","redeco"],
]
def add_object(self, context, actor_type):
verts = [
Vector((0.0849609375,0.0234375,0.06640625)),
Vector((0.1220703125,0.025390625,-0.064453125)),
Vector((0.12109375,0.025390625,0.068359375)),
Vector((0.1220703125,0.025390625,-0.064453125)),
Vector((0.1240234375,0.0537109375,0.068359375)),
Vector((0.1240234375,0.0537109375,-0.06640625)),
Vector((0.08984375,0.052734375,0.099609375)),
Vector((-0.0888671875,0.0537109375,0.1005859375)),
Vector((0.0869140625,0.0244140625,0.1015625)),
Vector((-0.0859375,0.0244140625,0.1005859375)),
Vector((0.087890625,0.17578125,0.0947265625)),
Vector((-0.087890625,0.17578125,0.0947265625)),
Vector((0.087890625,0.14453125,0.09375)),
Vector((-0.087890625,0.14453125,0.09375)),
Vector((0.087890625,0.140625,-0.0966796875)),
Vector((-0.0869140625,0.14453125,-0.0966796875)),
Vector((0.0869140625,0.1796875,-0.09765625)),
Vector((-0.0869140625,0.177734375,-0.09765625)),
Vector((0.0869140625,0.0244140625,-0.099609375)),
Vector((-0.091796875,0.0234375,-0.1044921875)),
Vector((0.08984375,0.052734375,-0.0986328125)),
Vector((-0.0947265625,0.052734375,-0.103515625)),
Vector((0.0859375,0.0234375,-0.0634765625)),
Vector((-0.0908203125,0.0234375,-0.0673828125)),
Vector((0.0869140625,0.0244140625,-0.099609375)),
Vector((-0.091796875,0.0234375,-0.1044921875)),
Vector((0.0869140625,0.0244140625,0.1015625)),
Vector((-0.0859375,0.0244140625,0.1005859375)),
Vector((-0.083984375,0.0234375,0.0654296875)),
Vector((0.126953125,0.1787109375,-0.0634765625)),
Vector((0.126953125,0.14453125,-0.064453125)),
Vector((0.12109375,0.1787109375,0.0029296875)),
Vector((0.126953125,0.146484375,0.064453125)),
Vector((0.126953125,0.177734375,0.064453125)),
Vector((0.1279296875,0.1416015625,-0.103515625)),
Vector((0.125,0.0537109375,-0.099609375)),
Vector((0.125,0.0537109375,-0.099609375)),
Vector((0.126953125,0.14453125,-0.064453125)),
Vector((0.1279296875,0.1416015625,-0.103515625)),
Vector((0.126953125,0.0546875,0.103515625)),
Vector((0.1298828125,0.142578125,0.099609375)),
Vector((0.138671875,0.1474609375,-0.015625)),
Vector((0.1357421875,0.1552734375,-0.0146484375)),
Vector((0.1328125,0.1435546875,-0.0283203125)),
Vector((0.1220703125,0.1533203125,-0.0146484375)),
Vector((0.126953125,0.140625,-0.01953125)),
Vector((0.138671875,0.1474609375,0.0224609375)),