-
Notifications
You must be signed in to change notification settings - Fork 0
/
LvdSpec.py
1444 lines (1252 loc) · 52 KB
/
LvdSpec.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
import os
import os.path
from os import listdir
from pathlib import Path
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import fileinput
import shutil
import subprocess
import sys
import webbrowser
import xml.etree.ElementTree as ET
import yaml
import configparser
import re
reAlpha='[^0-9,.-]'
def GetStringAsNumber(value):
value = re.sub(reAlpha, '', value)
#If empty, return
if (value==""): return -1,False
try:
value=float(value)
return value,True
except:
return -1,False
import math
#create ui for program
root = Tk()
root.programName="LVD Spec"
root.title(root.programName)
icon = os.getcwd() +"/icon.ico"
if os.path.isfile(icon):
root.iconbitmap(icon)
root.withdraw()
root.UnsavedChanges=False
#Check for prcxmls
sample = os.path.isfile(os.getcwd() + "/sample.yaml")
groundconfig = os.path.isfile(os.getcwd() + "/groundconfig.yaml")
if not (sample or groundconfig):
messagebox.showerror(root.programName,"Sample.yaml and groundconfig.yaml are missing in this directory!")
root.destroy()
sys.exit("User does not have .prcxmls")
# Check if yaml is installed
package_name = 'yaml'
import importlib.util
spec = importlib.util.find_spec(package_name)
if spec is None:
print(package_name +" is not installed")
#subcall = ["pip install"+package_name]
#with open('output.txt', 'w+') as stdout_file:
# process_output = subprocess.run(subcall, stdout=stdout_file, stderr=stdout_file, text=True)
# print(process_output.__dict__)
#spec = importlib.util.find_spec(package_name)
#if spec is None:
messagebox.showerror(root.programName,"Please install "+package_name+" to use this program!")
root.destroy()
sys.exit("User does not have "+package_name)
#truncate strings for labels
def truncate(string,direciton=W,limit=20,ellipsis=True):
if (len(string) < 3):
return string
text = ""
addEllipsis = "..." if (ellipsis and (len(string)>limit)) else ""
if direciton == W:
text = addEllipsis+string[len(string)-limit:len(string)]
else:
text = string[0:limit]+addEllipsis
return text
#Why isn't this built in?
def clamp(val, minval, maxval):
if val < minval: return minval
if val > maxval: return maxval
return val
config = configparser.ConfigParser()
defaultConfig = configparser.ConfigParser()
defaultConfig['DEFAULT'] = {
'parcelDir' : "",
'arcDir' : "",
'yamlvd' : "",
'stageParamsLocation' : "",
'levelFile' : ""
}
def CreateConfig():
print("creating valid config")
with open('config.ini', 'w+') as configfile:
defaultConfig.write(configfile)
config.read('config.ini')
#create a config if necessary
if (not os.path.isfile(os.getcwd() + r"\config.ini")):
CreateConfig()
config.read('config.ini')
def UpdateTitle(newtitle=""):
prefix="*" if root.UnsavedChanges else ""
workspace= os.path.basename(root.workspace)
if (workspace.lower()=="workspace"):
workspace=""
else:
workspace = "("+workspace+")"
if (newtitle!=""):
newtitle = " - "+newtitle
root.title(prefix+root.programName+workspace+newtitle)
def UpdateTitleAuto():
filename = os.path.basename(root.levelFile)
newtitle = root.stageName+": "+filename
UpdateTitle(newtitle)
root.arcDir = config["DEFAULT"].get("arcDir","")
root.stageParamsFolderShortcut = r"/stage/common/shared/param/"
#make sure that it is a validated parcel folder, otherwise quit
def IsValidParcel():
#Is this the directory with Parcel.exe?
return (os.path.exists(root.parcelDir + r"/parcel.exe"))
def SetParcel():
messagebox.showinfo(root.programName,"Set Parcel directory")
root.parcelDir = filedialog.askdirectory(title = "Select your Parcel directory")
if (root.parcelDir == ""):
root.destroy()
sys.exit("Invalid folder")
if (IsValidParcel() == False):
messagebox.showerror(root.programName,"Please select the root of your Parcel folder")
root.destroy()
sys.exit("Invalid Folder")
#make sure that it is a validated arc folder, otherwise quit
def IsValidArc():
#Is this the directory with ArcExplorer.exe?
if (os.path.exists(root.arcDir + r"/ArcExplorer.exe")):
#Has stageParams been extracted?
if (os.path.exists(root.arcDir + r"/export" + root.stageParamsFolderShortcut + "groundconfig.prc")):
return True
else:
messagebox.showerror(root.programName,"Please extra the folder stage/common/shared/param")
root.destroy()
sys.exit("Needs Param Folder")
return False
#Get Stage Params folder from Valid Arc
def SetStageParams():
#First, check to see if ArcExplorer Exists
messagebox.showinfo(root.programName,"Set ArcExplorer directory")
root.arcDir = filedialog.askdirectory(title = "Select your ArcExplorer directory")
if (root.arcDir == ""):
root.destroy()
sys.exit("Invalid folder")
if (IsValidArc() == False):
messagebox.showerror(root.programName,"Please select the root of your ArcExplorer folder")
root.destroy()
sys.exit("Invalid Folder")
root.stageParams = root.arcDir + r"/export"+ root.stageParamsFolderShortcut
#Copy prc for our working file
shutil.copy(root.stageParams + "groundconfig.prc", root.workspace+"/groundconfig.prc")
def SetYamlvd():
messagebox.showinfo(root.programName,"Set Yamlvd directory")
root.yamlvd = filedialog.askdirectory(title = "Select your Yamlvd directory")
if (root.yamlvd == ""):
root.destroy()
sys.exit("Invalid folder")
root.yamlvd = root.yamlvd + r"/yamlvd.exe"
if (os.path.exists(root.yamlvd) == False):
messagebox.showerror(root.programName,"Please select the root of your Yamlvd folder")
root.destroy()
sys.exit("Invalid Folder")
#make sure that it is a validated destination folder, otherwise quit
def IsValidModFolder():
root.modDirName = os.path.basename(root.modDir)
if (root.modDirName == "stage"):
return False
else:
subfolders = [f.path for f in os.scandir(root.modDir) if f.is_dir()]
for dirname in list(subfolders):
if (os.path.basename(dirname) == "stage"):
return True
return False
#open folder dialogue
def SetWorkspace():
quitOnFail=False
newWorkspace = filedialog.askdirectory(title = "Select your workspace folder")
if (newWorkspace == ""):
return
root.workspace = newWorkspace
if (not os.path.exists(root.workspace+"/groundconfig.prc")):
if (IsValidArc() == False):
messagebox.showerror(root.programName,"FATAL: groundconfig.prc missing from StageParams")
root.destroy()
sys.exit("Invalid Folder")
shutil.copy(root.stageParams + "groundconfig.prc", root.workspace+"/groundconfig.prc")
UpdateTitleAuto()
config.set("DEFAULT","workspace",root.workspace)
with open('config.ini', 'w+') as configfile:
config.write(configfile)
#Get or Set workspace
root.workspace = config["DEFAULT"].get("workspace","")
if (root.workspace == ""):
print("no workspace")
root.workspace = os.getcwd() +"/workspace"
if (not os.path.exists(root.workspace)):
os.makedirs(root.workspace)
#Set Parcel Directory if needed
root.parcelDir = config["DEFAULT"].get("parcelDir","")
if (not os.path.isdir(root.parcelDir)):
root.parcelDir = ""
#Get or Set root.parcelDir
if (root.parcelDir == ""):
print("no parcel")
SetParcel()
#Set Arc Directory and StageParams if needed
root.stageParams = config["DEFAULT"].get("stageParamsLocation","")
if (not os.path.isdir(root.stageParams)):
root.stageParams = ""
if (not os.path.exists(root.workspace + "/groundconfig.prc")):
root.stageParams=""
#Get or Set root.stageParams
if (root.stageParams == ""):
print("no arc")
SetStageParams()
config.set("DEFAULT","parcelDir",root.parcelDir)
config.set("DEFAULT","arcDir",root.arcDir)
config.set("DEFAULT","stageParamsLocation",root.stageParams)
config.set("DEFAULT","workspace",root.workspace)
with open('config.ini', 'w+') as configfile:
config.write(configfile)
root.stageName = ""
root.stageLocation = ""
root.steveTable={
"Steve_Label":"Steve LVD Settings",
"Steve_material":"soil",
"Steve_origin_x":0,
"Steve_origin_y":0,
"Steve_cell_sensitivity":0,
"Steve_line_offset":0,
"Steve_cell_minilen_side":0,
"Steve_cell_minilen_top":0,
"Steve_cell_minilen_bottom":0
}
root.steveMaterials=[
"soil",
"wool",
"sand",
"ice",
]
root.collisions=[]
root.maxCollisionsTag="Canvas_Collisions To Show"
#root.maxCollisions=50
root.stageLimit=125
root.stageDefaults ={
"Camera_Label":"Camera Boundaries",
"Camera_Left":-170,
"Camera_Right":170,
"Camera_Top":130,
"Camera_Bottom":-80,
"Camera_CenterX":0,
"Camera_CenterY":0,
"Blast_Label":"Blastzone Boundaries",
"Blast_Left":-240,
"Blast_Right":240,
"Blast_Top":192,
"Blast_Bottom":-140,
"Stage_Label":"Stage Data",
"Stage_Radius":80,
"Stage_Top":47,
"Stage_Bottom":-40,
"Stage_FloorY":0,
"Stage_OriginX":0,
"Stage_OriginY":0,
"Canvas_Label":"Canvas Settings",
""+root.maxCollisionsTag:50
}
root.stageDataTable = root.stageDefaults.copy()
def ConvertSteveTag(data):
data = (data.lower()).replace("steve_","Steve_")
if ("top" in data):
data = "Steve_cell_minilen_top"
elif ("side" in data):
data = "Steve_cell_minilen_side"
elif ("bottom" in data):
data = "Steve_cell_minilen_bottom"
return data
def GetData(data):
if ("Steve" in data):
data = ConvertSteveTag(data)
return root.steveTable[data]
elif (data in root.stageDataTable):
return root.stageDataTable[data]
else:
return
def SetData(data,value):
if ("Steve" in data):
data = ConvertSteveTag(data)
root.steveTable[data] = value
elif (data in root.stageDataTable):
root.stageDataTable[data] = value
if ("Camera" in data):
root.stageDataTable["Camera_CenterX"] = (GetData("Camera_Left")+GetData("Camera_Right"))/2
root.stageDataTable["Camera_CenterY"] = (GetData("Camera_Top")+GetData("Camera_Bottom"))/2
else:
print("Error: "+data+" key not found")
root.levelFile = ""
root.modParams = ""
root.popup = None
root.popupOptions = {}
root.FirstLoad=True
root.Loading=True
#Deprecated
def SetStageFromRoot():
print("Open Stage from root:"+root.modDir)
if (root.modDir==""):
SetYaml(False)
return
SetStage(root.modDir+ "/stage/")
def SetStageFromLVD():
stageKey="/stage/"
normalKey="/normal/"
#We need to find whatever is in between stageKey and normalKey
root.stageLocation = root.levelFile[:root.levelFile.index(normalKey)]
root.stageName = root.stageLocation[root.stageLocation.index(stageKey)+len(stageKey):]
print("Stage:"+root.stageName)
if (root.stageName == ""):
messagebox.showerror(root.programName,"There is no valid stage within that stage folder!")
return
root.modParams = root.stageLocation+"/normal/param/"
root.modDir = root.levelFile[:root.levelFile.index(stageKey)]
print("Stage Loaded, stage params should be at "+root.modParams)
def SetStage(stageDir):
print("Find stage at "+stageDir)
root.stageName = None
subfolders = [s.path for s in os.scandir(stageDir) if s.is_dir()]
for dirname in list(subfolders):
if (dirname != "common"):
root.stageName = os.path.basename(dirname)
if (root.stageName == None):
messagebox.showerror(root.programName,"There is no valid stage within that stage folder!")
return
#root.destroy()
#sys.exit("Not a stage folder")
def FinishedCreateYaml():
#create yaml by copying our sample
#root.levelFile = root.modParams+root.stageName+"_spec.yaml"
shutil.copy(os.getcwd() + "/sample.yaml", root.levelFile)
# Replace all tagged values
with open(root.levelFile, 'r') as file :
filedata = file.read()
for option in root.popupOptions:
filedata = filedata.replace(option, root.popupOptions[option].get())
filedata = filedata.replace("RingL", "-"+root.popupOptions["StageRadius"].get())
filedata = filedata.replace("RingR", root.popupOptions["StageRadius"].get())
# Write to the copy
with open(root.levelFile, 'w') as file:
file.write(filedata)
#Destroy popup, and return to main
root.popup.destroy()
root.deiconify()
LoadYaml()
def ClosedCreateYaml():
root.levelFile=""
root.popup.destroy()
root.deiconify()
LoadYaml()
def CreateYaml():
print(root.levelFile)
if (root.levelFile==""):
messagebox.showinfo(root.programName,"Set directory to save yaml to")
root.modParams = filedialog.askdirectory(title = "Select your yaml directory")
if (root.modParams == ""):
return
root.levelFile = root.modParams
SetStageFromLVD()
print("Create Stage:"+root.stageName)
root.levelFile=root.modParams+root.stageName+"_spec.yaml"
root.popup = Toplevel()
root.popup.title("Create Yaml")
root.fr_Options = Frame(root.popup)
root.fr_Options.pack(fill = BOTH,expand=1,anchor=N)
root.popupOptions = {}
stageOptions = {
"Label1":"Camera Settings",
"CameraLeft":root.stageDefaults["Camera_Left"],"CameraRight":root.stageDefaults["Camera_Right"],
"CameraTop":root.stageDefaults["Camera_Top"],"CameraBottom":root.stageDefaults["Camera_Bottom"],
"Label2":"Blastzone Settings",
"BlastLeft":root.stageDefaults["Blast_Left"],"BlastRight":root.stageDefaults["Blast_Right"],
"BlastTop":root.stageDefaults["Blast_Top"],"BlastBottom":root.stageDefaults["Blast_Bottom"],
"Label3":"Stage Settings",
"StageRadius":root.stageDefaults["Stage_Radius"],"StageFloorY":root.stageDefaults["Stage_FloorY"],
"StageTop":root.stageDefaults["Stage_Top"],"StageBottom":root.stageDefaults["Stage_Bottom"]}
for option in stageOptions:
if ("Label" in option):
optionFrame = Frame(root.fr_Options)
optionFrame.pack(fill = X,expand=1)
optionName = Label(optionFrame,text=stageOptions[option])
optionName.pack(fill = BOTH)
continue
optionData = stageOptions[option]
optionFrame = Frame(root.fr_Options)
optionFrame.pack(fill = X,expand=1)
optionName = Entry(optionFrame,width=15)
optionName.insert(0,option)
optionName.configure(state ='disabled')
optionName.pack(side = LEFT, fill = BOTH,anchor=E)
optionValue = Entry(optionFrame,width=15)
optionValue.insert(0,optionData)
optionValue.pack(side = RIGHT, fill = BOTH,expand=1)
root.popupOptions.update({option:optionValue})
button = Button(root.popup, text="Create Yaml", command=FinishedCreateYaml,width = 10).pack(side=BOTTOM)
root.popup.protocol("WM_DELETE_WINDOW", ClosedCreateYaml)
root.withdraw();
def LoadLastYaml():
root.levelFile = config["DEFAULT"]["levelFile"]
if (not os.path.exists(root.levelFile)):
root.levelFile = ""
else:
SetStageFromLVD()
Main()
def SetYaml(automatic=False):
SetData(root.maxCollisionsTag,root.stageDefaults[root.maxCollisionsTag])
originalYaml = root.levelFile
root.levelFile=""
#Attempt to find automatically first, if valid directory file exists
if (automatic and os.path.isdir(root.modParams)):
if (root.levelFile == ""):
#Automatically comb through modParams to find the first yaml file
paramfiles = [f for f in listdir(root.modParams) if os.path.exists(os.path.join(root.modParams, f))]
root.yaml = {}
for f in list(paramfiles):
filename = os.path.splitext(os.path.basename(f))[0]
extension = os.path.splitext(os.path.basename(f))[1]
if (extension == ".yaml"):
#if (root.stageName in filename): #this checks if the filename contains the stage name, which might not always be the case
root.levelFile = root.modParams +f
break
if (root.levelFile != ""):
print(os.path.basename(root.levelFile)+" was automatically retrieved")
elif (root.levelFile == "" or not automatic):
#SetYaml manually. First select an lvd/yaml file
#messagebox.showinfo(root.programName,"Select your stage collision file (usually found in stage/normal/params)")
filetypes = (
('All File Types', '*.yaml *lvd'),
('Yaml File', '*.yaml'),
('LVD File', '*lvd')
)
desiredFile = filedialog.askopenfilename(title = "Load Level File",filetypes=filetypes,initialdir = root.modParams)
if (desiredFile == ""):
print("No lvd selected")
#enter manually if rejected, and no current file
if (root.levelFile == "" and originalYaml==""):
messagebox.showwarning(root.programName,"Let's manually create a yaml file then!")
CreateYaml()
#otherwise close window?
else:
root.levelFile=originalYaml
return
#If accidentally selected the Yaml version instead of the lvd verison, select yaml instead
possibleYaml = desiredFile.replace(".lvd",".yaml")
if (os.path.exists(possibleYaml) and ".lvd" in desiredFile):
res = messagebox.askquestion(root.programName,"A .yaml version exists of "+os.path.basename(desiredFile)+". If you select the lvd, this yaml will be overwritten."+
"\nSelect .lvd and overwrite its .yaml?")
if res != 'yes':
desiredFile=possibleYaml
desiredFileName = os.path.basename(desiredFile)
extension = os.path.splitext(desiredFileName)[1]
#If it's a yaml file, continue to the main program
if (extension == ".yaml"):
root.levelFile = desiredFile
#else yamlvd it
elif (extension == ".lvd"):
print("Use yamlvd")
#Get or Set Yamlvd
root.yamlvd = config["DEFAULT"]["yamlvd"]
if (not os.path.exists(root.yamlvd)):
root.yamlvd = ""
if (root.yamlvd == ""):
print("no yamlvd")
SetYamlvd()
config.set("DEFAULT","yamlvd",root.yamlvd)
with open('config.ini', 'w+') as configfile:
config.write(configfile)
#run yamlvd on the lvd file
root.levelFile = desiredFile.replace(".lvd",".yaml")
subcall = [root.yamlvd,desiredFile,root.levelFile]
with open('output.txt', 'a+') as stdout_file:
process_output = subprocess.run(subcall, stdout=stdout_file, stderr=stdout_file, text=True)
print(process_output.__dict__)
#if yamlvd doesn't work with this stage, enter values manually
if (not os.path.exists(root.levelFile)):
#enter manually
messagebox.showwarning(root.programName,"Yamlvd not compatible with this stage! Let's create a yaml file!")
CreateYaml()
return
LoadYaml()
def LoadYaml():
root.Loading=True
root.collisions=[]
print("")
print("Loaded New Yaml")
if (root.levelFile != ""):
SetStageFromLVD()
Main()
def GetConfigFromYaml():
toReturn = root.modDir + root.stageParamsFolderShortcut + r"groundconfig_"
toReturn = toReturn+os.path.basename(root.levelFile).replace(".yaml",".prcxml")
return toReturn
def ParseSteve(ParseFromWorkspace=True):
if (root.stageName == ""):
return
tree = None
treeRoot = None
sourceGroundInfo = os.getcwd() + r"\groundconfig.prcxml"
if (not os.path.exists(sourceGroundInfo)):
messagebox.showerror(root.programName,"Source Groundconfig missing from this folder")
return
workingGroundInfo=""
if (ParseFromWorkspace):
workingGroundInfo = root.workspace+"/groundconfig_"+os.path.basename(root.levelFile).replace(".yaml",".prcxml")
#if (not os.path.exists(workingGroundInfo)):
# messagebox.showerror(root.programName,"No data for "+os.path.basename(root.levelFile)+" found in workspace")
# return
SetData("Steve_Side", 0)
SetData("Steve_Top",0)
SetData("Steve_Bottom", 0)
if (ParseFromWorkspace):
if (not os.path.exists(workingGroundInfo)):
ParseFromWorkspace=False
else:
#Make sure the mod has our desired stage
hasStage = False
while hasStage == False:
with open(workingGroundInfo, 'rb') as file:
parser = ET.XMLParser(encoding ='utf-8')
tree = ET.parse(file,parser)
treeRoot = tree.getroot()
for type_tag in treeRoot.findall('struct'):
nodeName = type_tag.get('hash')
if (nodeName == root.stageName):
hasStage=True
break
ParseFromWorkspace = hasStage
print("Current mod's groundconfig excludes the desired stage, using source instead")
root.TempGroundInfo = os.getcwd() + r"\tempconfig.prcxml"
f = open(root.TempGroundInfo, "w")
f.close()
GroundInfo = workingGroundInfo if ParseFromWorkspace else sourceGroundInfo
print("Parsing Steve Data...")
#Parse Steve data from main groundconfig file and place it in a temporary file
with open(GroundInfo, 'rb') as file:
parser = ET.XMLParser(encoding ='utf-8')
tree = ET.parse(file,parser)
treeRoot = tree.getroot()
#remove cell_size
for type_tag in treeRoot.findall('float'):
treeRoot.remove(type_tag)
#remove material_tabel
for type_tag in treeRoot.findall('list'):
treeRoot.remove(type_tag)
#remove everything that isn't this stage
for type_tag in treeRoot.findall('struct'):
nodeName = type_tag.get('hash')
if (nodeName != root.stageName):
treeRoot.remove(type_tag)
else:
for child in type_tag:
childName = "Steve_"+child.get("hash")
if (childName in list(root.steveTable.keys())):
print(childName+":"+child.text)
if (childName!="Steve_material"):
root.steveTable.update({childName:float(child.text)})
else:
root.steveTable.update({childName:child.text})
tree.write(root.TempGroundInfo)
print("")
def SaveGroundInfoChanges():
tree = None
treeRoot = None
#Write our changes to TempGroundInfo
with open(root.TempGroundInfo, 'rb') as file:
parser = ET.XMLParser(encoding ='utf-8')
tree = ET.parse(file,parser)
treeRoot = tree.getroot()
for type_tag in treeRoot.findall('struct'):
nodeName = type_tag.get('hash')
if (nodeName != root.stageName):
treeRoot.remove(type_tag)
else:
for child in type_tag:
childName = "Steve_"+child.get("hash")
if (childName in list(root.steveTable.keys())):
value = GetData(childName)
print("Write:"+childName+":"+str(value))
child.text = str(value)
tree.write(root.TempGroundInfo)
targetFile = GetConfigFromYaml()
targetFile = root.workspace + "/"+os.path.basename(targetFile)
#Copy the temp prcxml to our workspace
shutil.copy(root.TempGroundInfo,targetFile)
root.UnsavedChanges=False
UpdateTitleAuto()
#def ReadPrcxml(file):
def PatchWorkspace():
workspacePrcxml = root.workspace+"/groundconfig.prcxml"
f = open(workspacePrcxml, "w")
f.close()
mainTree = None
mainTreeRoot = None
patchCreated=False
#For each PRCXML in the workspace (that isnt groundconfig), add it to the mainTree
with open(workspacePrcxml, 'rb') as file:
mainParser = ET.XMLParser(encoding ='utf-8')
mainTreeRoot = ET.Element("struct")
mainTree = ET.ElementTree(mainTreeRoot)
prcxmls = [f.path for f in os.scandir(root.workspace) if f.is_file()]
stages=[]
for file in list(prcxmls):
fileName = os.path.basename(file)
fileName = os.path.basename(os.path.splitext(file)[0])
fileExt = os.path.splitext(file)[1]
if (fileName != "groundconfig" and fileExt == ".prcxml"):
with open(file, 'rb') as prcxml:
parser = ET.XMLParser(encoding ='utf-8')
tree = ET.parse(prcxml,parser)
treeRoot = tree.getroot()
if (len(treeRoot)>0):
patchCreated=True
stageName = treeRoot[0].get('hash')
print(stageName)
isNewEntry = True
if (stageName in stages):
messagebox.showwarning(root.programName,"Multiple files in workspace use stage '"+stageName+"'!"+
"\nValues will be overwritten, it is recommended that each stage has only one file in a workspace!")
for type_tag in mainTreeRoot.findall("struct"):
nodeName = type_tag.get('hash')
if (nodeName==stageName):
mainTreeRoot.remove(type_tag)
mainTreeRoot.append(treeRoot[0])
stages.append(stageName)
#Write XML
mainTree.write(workspacePrcxml, encoding="utf-8", xml_declaration=True)
if (not patchCreated):
messagebox.showwarning(root.programName,"No files to patch")
return
parcel = root.parcelDir + r"/parcel.exe"
#Patch the source file with our workspacePrcxml, and create a clone as our workspaces' prc
sourcePrc = root.stageParams + "groundconfig.prc"
workspacePrc = workspacePrcxml.replace(".prcxml",".prc")
subcall = [parcel,"patch",sourcePrc,workspacePrcxml,workspacePrc]
with open('output.txt', 'a+') as stdout_file:
process_output = subprocess.run(subcall, stdout=stdout_file, stderr=stdout_file, text=True)
print(process_output.__dict__)
print("Prc created!")
#Create Prcx for mod
targetFile = workspacePrcxml.replace(".prcxml",".prcx")
subcall = [parcel,"diff",sourcePrc,workspacePrc,targetFile]
with open('output.txt', 'a+') as stdout_file:
process_output = subprocess.run(subcall, stdout=stdout_file, stderr=stdout_file, text=True)
print(process_output.__dict__)
print("Prcx created!")
messagebox.showinfo(root.programName,"Workspace patch file and prc created!")
webbrowser.open(root.workspace)
def exportGroundInfo():
tempPrc = os.getcwd() +"/temp.prc"
sourcePrc = root.stageParams + "groundconfig.prc"
parcel = root.parcelDir + r"/parcel.exe"
if (not os.path.exists(sourcePrc)):
messagebox.showerror(root.programName,"Cannot export without ArcExplorer's groundconfig.prc")
return
if (not os.path.exists(parcel)):
messagebox.showerror(root.programName,"Cannot export without Parcel")
return
#Changes must be saved before exporting
SaveGroundInfoChanges()
#Patch the source file with our edited values, and create a clone as TempPRC
subcall = [parcel,"patch",sourcePrc,root.TempGroundInfo,tempPrc]
with open('output.txt', 'a+') as stdout_file:
process_output = subprocess.run(subcall, stdout=stdout_file, stderr=stdout_file, text=True)
print(process_output.__dict__)
print("Temp prc created!")
#Patch our workspace's prc, as well
workingPrc = root.workspace + "/groundconfig.prc"
if (os.path.exists(workingPrc)):
subcall = [parcel,"patch",workingPrc,root.TempGroundInfo,workingPrc]
with open('output.txt', 'a+') as stdout_file:
process_output = subprocess.run(subcall, stdout=stdout_file, stderr=stdout_file, text=True)
print(process_output.__dict__)
print("Working prc patched!")
#Run parcel with the original and the patch to receive a prcx
else:
messagebox.showwarning(root.programName,"groundconfig.prc missing from LvdSpec")
#Create Prcx for mod
targetLocation = root.modDir + root.stageParamsFolderShortcut
if (not os.path.exists(targetLocation)):
os.makedirs(targetLocation)
targetFile = targetLocation+"groundconfig.prcx"
subcall = [parcel,"diff",sourcePrc,tempPrc,targetFile.replace(".prcxml",".prcx")]
with open('output.txt', 'a+') as stdout_file:
process_output = subprocess.run(subcall, stdout=stdout_file, stderr=stdout_file, text=True)
print(process_output.__dict__)
print("Prcx created!")
#Copy the temp prcxml to the destination
#shutil.copy(root.TempGroundInfo,targetFile)
#Final part: remove temp and navigate to new folder
os.remove(tempPrc)
messagebox.showinfo(root.programName,"Exported steve parameters as "+os.path.basename(targetFile)+"!"
"\nMake sure you rename the file to 'groundconfig' in your mod file"
"\n"
"\nLVDSpec's groundconfig.prc has also been updated!")
webbrowser.open(targetLocation)
def OpenReadMe():
webbrowser.open('https://github.com/CSharpM7/LVDSpec')
def OpenWiki():
webbrowser.open('https://github.com/CSharpM7/LVDSpec/wiki')
root.string_vars = {}
def OnSteveSliderUpdate(variable):
if (root.Loading):
return
value = root.stageData[variable].get()
value=float(value)
print("Updated "+variable+" with "+str(value))
root.steveTable.update({variable:value})
#Until we know what sensitivity and offset do, we can't update the steve block
#DrawSteveBlock()
def OnOriginXSliderUpdate(event):
variable = "Steve_origin_x"
OnSteveSliderUpdate(variable)
def OnOriginYSliderUpdate(event):
variable = "Steve_origin_y"
OnSteveSliderUpdate(variable)
def OnLineSliderUpdate(event):
variable = "Steve_line_offset"
OnSteveSliderUpdate(variable)
def OnSensitivitySliderUpdate(event):
variable = "Steve_cell_sensitivity"
OnSteveSliderUpdate(variable)
def OnSettingUpdated(variable):
#Get Value, only take #s,- and .
value = root.string_vars[variable].get()
value,isValidValue = GetStringAsNumber(value)
if (not isValidValue): return
value=float(value)
#Convert Collisions to int
if (variable==root.maxCollisionsTag and value != ""):
value=int(value)
#Clamp Radius
elif ("Radius" in variable):
value=min(value,root.stageLimit)
#Clamp Steve Origins
elif ("Steve_origin" in variable):
value=clamp(value,-10,10)
SetData(variable,value)
#print("Updated "+variable+" with "+str(value))
if ("Canvas" in variable):
DrawCollisions()
else:
if ("Stage" in variable):
DrawBoundaries()
elif ("Steve" in variable):
if (not root.UnsavedChanges):
root.UnsavedChanges=True
UpdateTitleAuto()
DrawSteveBlock()
DrawGrid()
def OnSteveSettingUpdated(*args):
if (root.Loading):
return
variable = "Steve_"+args[0]
OnSettingUpdated(variable)
def OnStageSettingUpdated(*args):
if (root.Loading):
return
variable = "Stage_"+args[0]
OnSettingUpdated(variable)
def OnCanvasSettingUpdated(*args):
if (root.Loading):
return
variable = "Canvas_"+args[0]
OnSettingUpdated(variable)
def LoadLevel():
if (root.UnsavedChanges):
res = messagebox.askquestion(root.programName,"There are unsaved changes! Are you sure you want to load a new file?"
,icon = "warning")
if res != 'yes':
return
SetYaml()
root.canvasWidth = 576
root.canvasHeight = 480
#This should really only run once, maybe I should split this up but idk
def CreateCanvas():
#Define window stuff
root.geometry("1080x512")
root.deiconify()
root.mainFrame = Frame(root)
root.mainFrame.pack(fill = X,expand=1)
root.my_canvas = Canvas(root.mainFrame,width=root.canvasWidth,height=root.canvasHeight,bg="white")
root.my_canvas.pack(padx=20,pady=20,side=LEFT)
#Rectangle variables for later
root.steveArea = root.my_canvas.create_rectangle(-10,-10,-10,-10,fill = "lime green",tag="steve")
root.cameraArea = root.my_canvas.create_rectangle(-10,-10,-10,-10,outline = "blue",tag="camera")
root.blastArea = root.my_canvas.create_rectangle(-10,-10,-10,-10,outline = "red",tag = "blast")
#File menu
root.menubar = Menu(root)
root.filemenu = Menu(root.menubar, tearoff=0)
root.filemenu.add_command(label="Load Stage Collision File", command=LoadLevel)
root.filemenu.add_command(label="Save To Workspace", command=SaveGroundInfoChanges)
root.filemenu.add_separator()
root.filemenu.add_command(label="Export Patch File To Mod", command=exportGroundInfo)
root.filemenu.add_command(label="Create Workspace Patch", command=PatchWorkspace)
root.filemenu.add_separator()
root.filemenu.add_command(label="Exit", command=quit)
root.menubar.add_cascade(label="File", menu=root.filemenu)
root.settingsmenu = Menu(root.menubar, tearoff=0)
root.settingsmenu.add_command(label="Set Workspace", command=SetWorkspace)
root.menubar.add_cascade(label="Settings", menu=root.settingsmenu)
root.helpmenu = Menu(root.menubar, tearoff=0)
root.helpmenu.add_command(label="About", command=OpenReadMe)
root.helpmenu.add_command(label="Wiki", command=OpenWiki)
root.menubar.add_cascade(label="Help", menu=root.helpmenu)
root.config(menu=root.menubar)
#Settings displayed on the side,
root.fr_Settings = Frame(root.mainFrame)
root.fr_Settings.pack(pady=20,expand=1,fill=BOTH,side=RIGHT)
root.fr_SteveSettings = Frame(root.fr_Settings)
root.fr_SteveSettings.pack(padx=10,side=LEFT,anchor=N)
root.fr_StageSettings = Frame(root.fr_Settings)
root.fr_StageSettings.pack(padx=10,side=LEFT,anchor=N)
root.stageData = {}
dataTable = {}
dataTable.update(root.steveTable)
dataTable.update(root.stageDataTable)
for data in dataTable:
frame = root.fr_StageSettings
if ("Steve" in data):
frame = root.fr_SteveSettings
#For labels, don't use Entries
if ("Label" in data):
dataFrame = Frame(frame)
dataFrame.pack(fill = X,expand=1)
dataName = Label(dataFrame,text=dataTable[data])
dataName.pack(fill = BOTH)
continue
dataText=re.sub(r'[^a-zA-Z _]', '', data)
dataText=dataText[dataText.index("_")+1:]
dataDefault = str(dataTable[data])
dataFrame = Frame(frame)
dataFrame.pack(fill = X,expand=1)
dataName = Entry(dataFrame)
dataName.insert(0,dataText)
dataName.configure(state ='disabled')
dataName.pack(side = LEFT, fill = BOTH,anchor=E)
dataEntry=None
#For Steve Entries, trace any updates
if ("Steve" in data or "Stage" in data or "Canvas" in data):
#Sensitivity is a slider
if ("sensitivity" in data):
dataEntry = Scale(dataFrame, from_=0, to=1,orient=HORIZONTAL,resolution=0.01)
dataEntry.bind("<ButtonRelease-1>",OnSensitivitySliderUpdate)
dataEntry.set(dataDefault)
elif ("line" in data):
dataEntry = Scale(dataFrame, from_=0, to=10,orient=HORIZONTAL,resolution=0.01)
dataEntry.bind("<ButtonRelease-1>",OnLineSliderUpdate)
dataEntry.set(dataDefault)
#Origin is now using textEntry
elif ("Xorigin" in data):
dataEntry = Scale(dataFrame, from_=-10, to=10,orient=HORIZONTAL,resolution=0.01)
dataEntry.set(dataDefault)
if ("_x" in data):
dataEntry.bind("<ButtonRelease-1>",OnOriginXSliderUpdate)
elif ("_y" in data):
dataEntry.bind("<ButtonRelease-1>",OnOriginYSliderUpdate)