This repository has been archived by the owner on Jun 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
1805 lines (1566 loc) · 61.7 KB
/
main.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 sys
import os
import subprocess
import shutil
import struct
import configparser
import locale
import fsb5
# PySide bindings
import PySide
from PySide.QtGui import *
from PySide.QtCore import *
from PySide.QtOpenGL import *
from PySide.QtMultimedia import *
from OpenGL.GL import *
import res_rc
langs = [
"en_US",
"ru_RU"
]
developers = [
"aspadm",
"volfin",
"Sir Kane",
"erik945",
"Vindis",
"Simon Pinfold"
]
version = "1.1 (17.09.2017)"
ext_preview = [
"pc_weightedprim",
"pc_tex",
"pc_prim",
"pc_linkedprim",
]
ext_non_preview = [
"pc_hair",
"pc_apex",
"pc_swf",
"pc_fsb"
]
all_types = [
"pc_animation", "pc_animationrig", "pc_animset", "pc_apex", "pc_binkvid",
"pc_bonerig", "pc_chartype", "pc_coll", "pc_collisionlayers",
"pc_coverdata", "pc_curvetex", "pc_decalpreset", "pc_entityblueprint",
"pc_entityresource", "pc_entitytemplate", "pc_entitytype", "pc_facefx",
"pc_fontdef", "pc_fsb", "pc_fsbm", "pc_hair", "pc_ies", "pc_irv",
"pc_kitsystem", "pc_linkedprim", "pc_localized-fontdef",
"pc_localized-swf", "pc_localized-textlist", "pc_localized-wavebank",
"pc_mate", "pc_mi", "pc_musiccomp", "pc_navmesh", "pc_platformspecific",
"pc_prim", "pc_rawentityblueprint", "pc_rawentitytype", "pc_rbs",
"pc_resourceidx", "pc_resourcelist", "pc_rigdataresource", "pc_rtet",
"pc_sdefs", "pc_socialresource", "pc_staticvisibility", "pc_swf", "pc_tex",
"pc_textline", "pc_textlist", "pc_umbra", "pc_volumetricnavgraph",
"pc_wavebank", "pc_wavebankfx", "pc_weightedprim"
]
ext_types = []
if os.path.isfile("unpack_ext.txt"):
for i in open("unpack_ext.txt", "r"):
if len(i) > 0:
if i[-1] == "\n":
i = i[:-1]
if i in all_types:
ext_types.append(i)
if ext_types == []:
ext_types = ext_preview[:] + ext_non_preview[:]
types_3d = [
"prim",
"weightedprim",
"linkedprim",
"staticscenecollisiondef",
"apx"
]
types_tex = [
"tex"
]
types_audio = [
"wavebank"
]
save_filter = [
"OBJ - Wavefront Object (*.obj);;\
FBX - Autodesc Filmbox (*.fbx);;\
3DS - 3D Studio Graphics (*.3ds);;\
STL - Stereolithography Interface Format (*.stl);;\
PRIM - DEMD native model (*.bin)",
"PNG - Portable Network Graphics (*.png);;\
TGA - Targa bitmap (*.tga);;\
JPG - JPEG (*.jpg);;\
TIF - Tagged Image Format File (*.tif);;\
DDS - Direct Draw Surface (*.dds);;\
TXET - DEMD native texture (*.tex)"
]
save_ext_tex = [
"png", "tga",
"jpg", "tif",
"dds", "tex"
]
save_ext_3d = [
"obj", "fbx",
"3ds", "stl",
"bin"
]
tree_list = [] # List of files by levels
folder_tree = {} # Pairs of filename: dirname
path = ""
lpath = os.getcwd() + "\\"
tpath = lpath+"temp_files\\"
last_dir = ""
last_filter = ["", ""]
# Toolset
dds_converter = ""
tex_converter = ""
unpacker = ""
blender = ""
# Fast export
epath = ""
ext_textures = ""
ext_models = ""
# Current element
file_name = ""
file_parent = ""
cur_hash = ""
cur_item = QTreeWidgetItem()
lang_name = ""
first_launch = False
icons = {"prim": ":/3d.png",
"tex": ":/tex.png",
"platform-tex": ":/tex.png",
"linkedprim": ":/3da.png",
"weightedprim": ":/3db.png",
"apx": ":/apx.png",
"hair": ":/hair.png",
"wavebank": ":/mus.png"}
#
##### 3D viewer class
class GLWidget(QGLWidget):
def __init__(self, parent=None, shareWidget=None):
super(GLWidget, self).__init__(parent, shareWidget)
self.clearColor = Qt.white
self.zoom_scale = 0.001 # wheel step
self.angle = 15 # arrows angle step
self.angle_scale = 1.0 # mouse rotation
self.move_scale = 0.001 # mouse position
self.size_scale = 0.02 # mouse scaling
self.size_hint = 0.7 # avoid clipping
# Model rotation
self.xRot = -90
self.yRot = 0
self.zRot = 180
# Model screen position and scale
self.xOff = 0.0
self.yOff = -0.5
self.zOff = 0.9
# Last mouse pos
self.lastPos = QPoint()
self.v_list = []
self.n_list = []
self.v_count = 0
self.can_show = False
def add_vertex(self, vertex):
vertex[0][0] *= -1
vertex[1][0] *= -1
vertex[2][0] *= -1
for i in range(3):
for j in range(3):
self.size_hint = max(self.size_hint, vertex[i][j])
for v in vertex[2]:
self.v_list.append(v)
for v in vertex[1]:
self.v_list.append(v)
for v in vertex[0]:
self.v_list.append(v)
Ux = vertex[1][0] - vertex[2][0]
Uy = vertex[1][1] - vertex[2][1]
Uz = vertex[1][2] - vertex[2][2]
Vx = vertex[0][0] - vertex[2][0]
Vy = vertex[0][1] - vertex[2][1]
Vz = vertex[0][2] - vertex[2][2]
normal = [Uy*Vz - Uz*Vy, Uz*Vx - Ux*Vz, Ux*Vy - Uy*Vx]
for k in range(3):
for v in normal:
self.n_list.append(v)
def read_model(self, name):
self.v_list = []
self.n_list = []
try:
model = open(name, "rb")
except:
return 1
vert_buf = [1, 1, 1]
model.read(80)
count = struct.unpack("I", model.read(4))[0]
for i in range(count):
model.read(12)
for j in range(3):
buf = model.read(12)
vert_buf[j] = list(struct.unpack("3f", buf))[:]
model.read(2)
self.add_vertex(vert_buf)
model.close()
self.v_count = count * 3
return 0
def load_model(self, name):
self.reset_view()
self.read_model(name)
self.size_hint = 1/self.size_hint
self.size_hint = max(min(0.7, self.size_hint), 0.0001)
self.initializeGL()
def unload_model(self):
self.can_show = False
posAttrib = glGetAttribLocation(self.shaderProgram, b"position")
glDisableVertexAttribArray(posAttrib)
glDeleteBuffers(1, [self.vbo])
glDeleteVertexArrays(1, [self.vao])
def initializeGL(self):
#glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glShadeModel(GL_FLAT)
glEnable(GL_DEPTH_TEST)
#glEnable(GL_CULL_FACE)
# get Vertex Array Object name
self.vao = glGenVertexArrays(1)
# set this new VAO to the active one
glBindVertexArray(self.vao)
# vertex data for one triangle
triangle_vertices = self.v_list[:] + self.n_list[:]
# convert to ctypes c_float array
triangle_array = ((ctypes.c_float * len(triangle_vertices))
(*triangle_vertices))
# get a VBO name from the graphics card
self.vbo = glGenBuffers(1)
# bind our vbo name to the GL_ARRAY_BUFFER target
glBindBuffer(GL_ARRAY_BUFFER, self.vbo)
# move the vertex data to a new data store associated with our vbo
glBufferData(GL_ARRAY_BUFFER, ctypes.sizeof(triangle_array),
triangle_array, GL_STATIC_DRAW)
# vertex shader
vertexShaderProgram = r"""#version 130
in vec3 position;
in vec3 normal;
varying vec4 t_color;
uniform float scale_z;
void main() {
mat4 scale_m = mat4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, scale_z, 0.0,
0.0, 0.0, 0.0, 1.0);
mat4 mvmatrix = scale_m * gl_ModelViewMatrix;
gl_Position = mvmatrix * vec4 (position, 1.0);
const vec3 l = vec3(0.0, 0.0, 1.0);
vec3 n = normalize(gl_NormalMatrix * normal);
float snormal = dot(n, l);
vec4 color;
if (snormal < 0.0)
color = vec4 (-0.55, -0.55, -0.55, 1.0) * snormal;
else
color = vec4 (0.25, 0.22, 0.0, 1.0) * snormal;
vec4 spec = vec4(0.6, 0.5, 0.0, 1.0) * pow(max(dot(n, normalize(vec3(0.0, 1.1, -1.0))), 0.0), 20.0);
vec4 spec2 = vec4(0.5, 0.4, 0.0, 0.0) * pow(max(dot(n, normalize(vec3(0.0, -1.2, -1.0))), 0.0), 15.0);
t_color = color + spec + spec2;
}"""
vertexShader = glCreateShader(GL_VERTEX_SHADER)
glShaderSource(vertexShader, vertexShaderProgram)
glCompileShader(vertexShader)
# fragment shader
fragmentShaderProgram = r"""#version 130
varying vec4 t_color;
out vec4 outColor;
void main() {
outColor = t_color;
}"""
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER)
glShaderSource(fragmentShader, fragmentShaderProgram)
glCompileShader(fragmentShader)
# shader program
self.shaderProgram = glCreateProgram()
glAttachShader(self.shaderProgram, vertexShader)
glAttachShader(self.shaderProgram, fragmentShader)
# color output buffer assignment
glBindFragDataLocation(self.shaderProgram, 0, b"outColor")
# link the program
glLinkProgram(self.shaderProgram)
# validate the program
glValidateProgram(self.shaderProgram)
# activate the program
glUseProgram(self.shaderProgram)
self.can_show = True
self.setupViewport(self.width(), self.height())
def mousePressEvent(self, event):
self.lastPos = event.pos()
def wheelEvent(self, event):
self.zOff += self.zoom_scale * event.delta()
if self.zOff <= 0:
self.zOff = 0.00001
self.updateGL()
def reload_model(self, name):
self.unload_model()
self.load_model(name)
self.updateGL()
def reset_view(self):
self.xOff = 0.0
self.yOff = -0.5
self.zOff = 0.9
self.setXRotation(-90)
self.setYRotation(0)
self.setZRotation(180)
self.updateGL()
def mouseDoubleClickEvent(self, event):
if event.buttons() & Qt.MiddleButton:
self.reset_view()
def keyPressEvent(self, event):
if event.key() == Qt.Key_Up:
self.setXRotation(self.xRot - self.angle)
self.updateGL()
if event.key() == Qt.Key_Down:
self.setXRotation(self.xRot + self.angle)
self.updateGL()
if event.key() == Qt.Key_Right:
self.setZRotation(self.zRot + self.angle)
self.updateGL()
if event.key() == Qt.Key_Left:
self.setZRotation(self.zRot - self.angle)
self.updateGL()
def mouseMoveEvent(self, event):
dx = event.x() - self.lastPos.x()
dy = event.y() - self.lastPos.y()
if event.buttons() & Qt.LeftButton:
self.xOff += self.move_scale * dx
self.yOff -= self.move_scale * dy
elif event.buttons() & Qt.RightButton:
self.setXRotation(self.xRot - self.angle_scale * dy)
self.setZRotation(self.zRot - self.angle_scale * dx)
elif event.buttons() & Qt.MiddleButton:
self.zOff += self.size_scale * dy
if self.zOff <= 0:
self.zOff = 0.00001
self.lastPos = event.pos()
self.updateGL()
def normalizeAngle(self, angle):
if angle < 0:
angle = 360 + angle % 360
elif angle > 359:
angle = angle % 360
return angle
def resizeGL(self, width, height):
self.setupViewport(width, height)
def setupViewport(self, width, height):
side = max(width, height)
glViewport((width - side) // 2, (height - side) // 2, side, side)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
glDisable(GL_CLIP_PLANE0)
glMatrixMode(GL_MODELVIEW)
def paintGL(self):
self.qglClearColor(self.clearColor)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
# Change scroll offset
#glScalef(self.zOff, self.zOff, self.zOff)
glTranslatef(self.xOff, self.yOff, 0.0)
glScalef(self.zOff, self.zOff, self.zOff)
glRotatef(self.xRot, 1.0, 0.0, 0.0)
glRotatef(self.yRot, 0.0, 1.0, 0.0)
glRotatef(self.zRot, 0.0, 0.0, 1.0)
loc = glGetUniformLocation(self.shaderProgram, b"scale_z")
glUniform1f(loc, self.size_hint/self.zOff);
if self.can_show:
# Choose buffer; triangles
posAttrib = glGetAttribLocation(self.shaderProgram, b"position")
glEnableVertexAttribArray(posAttrib)
glVertexAttribPointer(posAttrib,
3,
GL_FLOAT,
False,
0,
ctypes.c_voidp(0))
nAttrib = glGetAttribLocation(self.shaderProgram, b"normal")
glEnableVertexAttribArray(nAttrib)
glVertexAttribPointer(nAttrib,
3,
GL_FLOAT,
False,
0,
ctypes.c_voidp(
self.v_count * 3 * sizeof(ctypes.c_float)))
# Draw triangles
glDrawArrays(GL_TRIANGLES, 0, self.v_count)
# Floor
glBegin(GL_LINES)
for i in range(21):
glVertex3f(-1.0 + 0.1 * i, -1.0, 0.0)
glVertex3f(-1.0 + 0.1 * i, +1.0, 0.0)
glVertex3f(-1.0, -1.0 + 0.1 * i, 0.0)
glVertex3f(+1.0, -1.0 + 0.1 * i, 0.0)
glEnd()
def setXRotation(self, angle):
angle = self.normalizeAngle(angle)
if angle != self.xRot:
self.xRot = angle
def setYRotation(self, angle):
angle = self.normalizeAngle(angle)
if angle != self.yRot:
self.yRot = angle
def setZRotation(self, angle):
angle = self.normalizeAngle(angle)
if angle != self.zRot:
self.zRot = angle
# End of 3D widget
def create_blank_config():
config = configparser.ConfigParser()
config.add_section("Main")
config.add_section("Tools")
config.add_section("Export")
config.set("Main", "last_base", "")
config.set("Main", "language", detect_locale())
if os.path.isdir(lpath+"tools\\Blender"):
bpath = lpath+"tools\\Blender"
elif os.path.isdir("C:\\Program Files (x86)\\Blender Foundation\\Blender"):
bpath = "C:\\Program Files (x86)\\Blender Foundation\\Blender"
else:
bpath = "C:\\Program Files\\Blender Foundation\\Blender"
config.set("Tools", "blender", bpath + "\\blender.exe")
config.set("Tools", "unpacker",
lpath+"tools\\BD_extract\\DXMDExtract.exe")
config.set("Tools", "tex_converter",
lpath+"tools\\texture_converter\\TXET2DDS.exe")
config.set("Tools", "dds_converter",
lpath+"tools\\texture_converter\\sctexconv_1.3.exe")
config.set("Export", "directory", "")
config.set("Export", "texture_format", "")
config.set("Export", "model_format", "")
with open("config.txt", "w") as config_file:
config.write(config_file)
def read_config():
global path
global dds_converter
global tex_converter
global unpacker
global blender
global epath
global ext_textures
global ext_models
global lang_name
global last_dir
config = configparser.ConfigParser()
config.read(lpath+"config.txt")
path = config.get("Main", "last_base")
lang_name = detect_locale(config.get("Main", "language"))
blender = config.get("Tools", "blender")
unpacker = config.get("Tools", "unpacker")
tex_converter = config.get("Tools", "tex_converter")
dds_converter = config.get("Tools", "dds_converter")
epath = config.get("Export", "directory")
if len(epath) > 0 and epath[-1] != "\\":
epath += "\\"
if last_dir == "" and len(epath) > 0: last_dir = epath[:-1]
ext_textures = config.get("Export", "texture_format")
ext_models = config.get("Export", "model_format")
def write_config():
config = configparser.ConfigParser()
config.add_section("Main")
config.add_section("Tools")
config.add_section("Export")
config.set("Main", "last_base", path)
config.set("Main", "language", lang_name)
config.set("Tools", "blender", blender)
config.set("Tools", "unpacker", unpacker)
config.set("Tools", "tex_converter", tex_converter)
config.set("Tools", "dds_converter", dds_converter)
config.set("Export", "directory", epath)
config.set("Export", "texture_format", ext_textures)
config.set("Export", "model_format", ext_models)
with open("config.txt", "w") as config_file:
config.write(config_file)
# Locale set
def detect_locale(lang_name=None):
if lang_name == None:
if os.name == "nt":
lang_name = locale.windows_locale[ctypes.windll.kernel32.\
GetUserDefaultUILanguage()]
else:
lang_name = locale.getdefaultlocale()[0]
if lang_name not in langs:
lang_name = langs[0]
return lang_name
def create_blender_script():
with open(lpath + "tools/blender_script.py", "w") as blender_script:
blender_script.write(r"""import os
import bpy
import sys
# Names of folder and files
args = sys.argv
source_file = args[-2]
convert_file = args[-1]
save_type = convert_file.split(".")[-1]
# Deleting all objects
for scene in bpy.data.scenes:
for obj in scene.objects:
scene.objects.unlink(obj)
for bpy_data_iter in (
bpy.data.objects,
bpy.data.meshes,
bpy.data.lamps,
bpy.data.cameras,
):
for id_data in bpy_data_iter:
bpy_data_iter.remove(id_data)
bpy.ops.object.select_by_type(type = "MESH")
bpy.ops.object.delete(use_global=False)
for item in bpy.data.meshes:
for scene in bpy.data.scenes:
for obj in scene.objects:
scene.objects.unlink(obj)
item.user_clear()
bpy.data.meshes.remove(item)
print("Scene cleared")
# Open model and save
try:
try:
print("Try to use plugin...")
bpy.ops.import_scene.deusexmd(filepath=source_file)
print("Success")
except:
try:
print("Fail")
print("Try to use outer script...")
try:
import import_DeusExMD
except:
print("Fail to import")
exit(2)
print("Successful module import; try to open model...")
import_DeusExMD.import_DeusExMD(source_file, #filepath
bpy.context, #context
False, #randomize_colors
True, #import_vertcolors
False, #skip_blank
False, #use_layers
1.0) #mesh_scale
print("Success")
except:
print("Fail")
exit(1)
print("\nModel opened\n")
if save_type == "obj":
bpy.ops.export_scene.obj(filepath=convert_file)
elif save_type == "fbx":
bpy.ops.export_scene.fbx(filepath=convert_file)
elif save_type == "3ds":
bpy.ops.export_scene.autodesk_3ds(filepath=convert_file)
elif save_type == "stl":
bpy.ops.export_mesh.stl(filepath=convert_file,
check_existing=False,
ascii=False)
else:
print("Incorrect save format")
print("\nConvertions done!")
exit(0)
# In case of error
except Exception:
print("\nSome errors here")
exit(1)
""")
def init_folders():
is_first_launch = 0
if not os.path.isfile(lpath+"config.txt"):
create_blank_config()
is_first_launch += 3
if not os.path.isdir(tpath):
os.mkdir(tpath)
is_first_launch += 1
if not os.path.isdir(lpath + "tools"):
os.mkdir(lpath + "tools")
is_first_launch += 2
if not os.path.isdir(lpath + "tools/BD_extract"):
os.mkdir(lpath + "tools/BD_extract")
is_first_launch += 1
if not os.path.isdir(lpath + "tools/texture_converter"):
os.mkdir(lpath + "tools/texture_converter")
is_first_launch += 1
if not os.path.isdir(lpath + "tools/texture_converter"):
os.mkdir(lpath + "tools/Models")
is_first_launch += 1
if not os.path.isfile(lpath + "tools/blender_script.py"):
is_first_launch += 1
create_blender_script()
read_config()
if not os.path.isfile(blender) or not os.path.isfile(unpacker) or\
not os.path.isfile(tex_converter) or not os.path.isfile(dds_converter):
is_first_launch += 3
else:
is_first_launch -= 1
if is_first_launch > 3:
global first_launch
first_launch = True
def shift(arr):
offset = 0
for element in arr:
if type(element) == int:
offset += element
return offset
# Load folders
def load_folders(path):
global folder_tree
if path == "" or not os.path.isdir(path) or\
not os.path.isfile(path+"NameMap.txt"):
return
else:
folder_tree = {}
for line in os.listdir(path):
if os.path.isdir(path+line):
for file in os.listdir(path+line):
folder_tree.update({file: line})
# Load base
def load_base(base_file):
global tree_list
base = open(base_file, "r")
for line in base.readlines():
if len(line) > 3:
tree_list.append([])
buf = line.split(";")[:-1]
for el in buf:
la = el.split(":")
l1 = int(la[1])
if l1 != -1:
l2 = int(la[2])
else:
l2 = la[2]
tree_list[-1].append([la[0], l1, l2])
base.close()
# Return branch with leaves; x, y - branch node
def add_leaf(x, y):
if tree_list[y][x][1] == -1: # Add file
leaf = QTreeWidgetItem(None, [tree_list[y][x][0], tree_list[y][x][2]])
leaf.setIcon(0, QIcon(icons.get(tree_list[y][x][0].split(".")[-1], None)))
return leaf
else:
arr = [] # Add list of children
for i in range(tree_list[y][x][1],
tree_list[y][x][1] + tree_list[y][x][2]):
arr.append(add_leaf(i, y + 1))
branch = QTreeWidgetItem(None, [tree_list[y][x][0],
str(tree_list[y][x][2])])
branch.addChildren(arr)
return branch
# Build a tree widget ierarchy
def build_tree():
global tree_list
global cur_item
cur_item = QTreeWidgetItem()
tree.clear()
widget.statusBar().showMessage(app.translate("BuildTree",
"Build a file tree"))
load_base(path+"converted_base.txt")
if len(tree_list) == 0:
error_window = QMessageBox.critical(None, "Empty base",
"Converted base is empty")
return
for i in range(len(tree_list[0])):
tree.addTopLevelItem(add_leaf(i, 0))
tree.sortItems(0, Qt.AscendingOrder)
tree_list = []
def convert_base():
base = open(path+"NameMap.txt", "r")
tree_list = []
lc = len(base.readlines())
base.seek(0)
pj = 1
convertWindow = QWidget()
convertWindow.setWindowTitle(app.translate("ConvertTitle", "Convert names"))
convertWindow.resize(350, 100)
convertWindow.setWindowFlags(Qt.ToolTip)
convertLayout = QVBoxLayout(convertWindow)
convertProgress = QProgressBar(parent = convertWindow)
convertProgress.setMaximum(lc)
convertLabel = QLabel(app.translate("ConvertText", "Please wait: file tree's creation is going (only at the first launch)"),
parent = convertWindow)
convertLabel.setWordWrap(True)
convertLabel.setAlignment(Qt.AlignCenter)
convertLayout.addWidget(convertLabel)
convertLayout.addWidget(convertProgress)
convertWindow.show()
for line in base.readlines():
convertProgress.setValue(pj)
pj += 1
ext = line.split(".")[-1][:-1]
#or ext not in ext_types
if ext not in ext_types or\
line.count("[", 38) != 1 or line[39:48] != "assembly:":
continue
leaf = line[21:37] # File hash (name)
if leaf+".bin" not in folder_tree:
#print("Not a real file", line)
continue
line = line[48:line.rindex("]")]
line = line.replace("?", "") # del ? sign
#line += "?" + ext
buf = line.split("/")[1:] # Folders
buf[-1], leaf = leaf, buf[-1]
length = len(buf)
# Scale up base
if length*2 > len(tree_list):
for i in range(length*2 - len(tree_list)):
tree_list.append([])
index = 0
for i in range(length):
if i == 0: # Top level folders
if buf[0] not in tree_list[0]: # Add new
index = len(tree_list[0]) # Remember it's index
tree_list[0].append(buf[0]) # Add it's name
tree_list[1].append(0) # Add count of it's children
else:
index = tree_list[0].index(buf[0]) # Remember it's index
else:
lb = shift(tree_list[i*2 - 1][:index]) # Number of elements before
if type(tree_list[i*2 - 1][index]) == str:
#print("BAD LEAF!", buf[i], tree_list[i*2][index])
break
rb = lb + tree_list[i*2 - 1][index] # add elements of this folder
if buf[i] in tree_list[i*2][lb:rb]: # If we have this element
index = tree_list[i*2].index(buf[i], lb, rb) # Remember it's index
else:
tree_list[i*2-1][index] += 1 # Increase parent counter
index = lb # Index of new element
if i == length - 1: # If file
tree_list[i*2 + 1].insert(index, leaf) # Store it's hash
else:
tree_list[i*2 + 1].insert(index, 0) # Init parent counter
tree_list[i*2].insert(index, buf[i]) # Store name
base.close()
base = open(path+"converted_base.txt", "w")
for i in range(len(tree_list)//2):
offset = 0
for j in range(len(tree_list[i*2])):
if type(tree_list[i*2+1][j]) == str:
base.write("{:}:{:}:{:};".format(tree_list[i*2+1][j],
-1, tree_list[i*2][j]))
else:
base.write("{:}:{:}:{:};".format(tree_list[i*2][j], offset,
tree_list[i*2+1][j]))
offset = offset + tree_list[i*2+1][j]
base.write("\n")
base.close()
convertWindow.close()
def open_base():
global path
if not os.path.isfile(path+"NameMap.txt"):
fileName = QFileDialog.getOpenFileName(
caption=app.translate("OpenBase", "Open converted base"),
dir = "", filter="DEMD namemap (NameMap.txt)")
if fileName[0] == "":
return
path = os.path.dirname(fileName[0])+"/"
load_folders(path)
if not os.path.isfile(path+"converted_base.txt"):
widget.statusBar().showMessage(app.translate("BaseConvert",
"Convert base"))
convert_base()
write_config()
build_tree()
widget.statusBar().showMessage(app.translate("Ready", "Ready"))
def convert_DEMD_base():
global path
demd_dir = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Deus Ex \
Mankind Divided\\runtime"
if not os.path.isdir(demd_dir):
demd_dir = "C:\\Program Files\\Steam\\steamapps\\common\\Deus Ex \
Mankind Divided\\runtime"
if not os.path.isdir(demd_dir):
demd_dir = "C:\\"
game_folder = QFileDialog.getExistingDirectory(
caption=app.translate("OpenGameFolder", "Open DEMD runtime folder"),
dir = demd_dir)
if game_folder == "":
return
path = QFileDialog.getExistingDirectory(
caption=app.translate("OpenBaseSaveFolder",
"Where to unpack base (need about 23gb of free space)"))
if path == "":
return
res = subprocess.call([unpacker, game_folder, path], shell=False)
if res != 0 or not os.path.isfile(path+"NameMap.txt"):
error_mess = QMessageBox.critical(
None, app.translate("ConvertError", "Convertion error"),
app.translate("ConvertErrorText",
"Looks like base convertion failed.\nCheck your actions and/or read help."))
def change_lang():
global app
global translation
translation = QTranslator()
if os.path.isfile("lang_"+lang_name) or\
os.path.isfile("lang_"+lang_name.split("_")[0]):
translation.load("lang_"+lang_name)
else:
translation.load(":lang_"+lang_name)
app.installTranslator(translation)
# Open settings
init_folders()
# Enable translation
#translation = QTranslator()
#translation.load("lang_"+lang_name)
app = QApplication(sys.argv)
#app.installTranslator(translation)
change_lang()
# App icon
app.setWindowIcon(QIcon(":/ico.png"))
# Main widget
widget = QMainWindow()
widget.setMinimumSize(350, 350)
widget.resize(640, 350)
widget.setWindowTitle(app.translate("AppTitle", "DEMD database"))
widget.statusBar().showMessage(app.translate("Ready", "Ready"))
# Central widget
centre = QSplitter(Qt.Horizontal)
widget.setCentralWidget(centre)
# Tree widget
tree = QTreeWidget(parent=centre)
tree.setColumnCount(2)
tree.setFrameStyle(QFrame.Box | QFrame.Sunken)
tree.header().setStretchLastSection(False)
tree.header().setResizeMode(0, QHeaderView.Stretch)
tree.header().close()
tree.setColumnHidden(1, True)
# Viewport widget
viewport = QLabel(parent=centre)
viewport.setFrameStyle(QFrame.Panel | QFrame.Sunken)
viewport.setMinimumSize(300, 300)
vp3D = GLWidget(parent=viewport)
vpTopLayout = QVBoxLayout(viewport)
vpLayout = QStackedLayout(viewport)
class ImageView(QLabel):
def __init__(self, parent=None):
super(ImageView, self).__init__(parent,)
# Model screen position and scale
self.xOff = 0.0
self.yOff = 0.0
self.scaleImage = 1.0
self.move_scale = 1.0
self.zoom_scale = 0.001
self.size_scale = 0.002
# Last mouse pos
self.lastPos = QPoint()
def wheelEvent(self, event):
self.scaleImage += self.zoom_scale * event.delta()
if self.scaleImage < 0:
self.scaleImage = 0.0
self.resize_image()
def reset_view(self):
self.xOff = 0.0
self.yOff = 0.0
self.scaleImage = 1.0
self.resize_image()
def mouseDoubleClickEvent(self, event):
if event.buttons() & Qt.MiddleButton:
self.reset_view()
def mouseMove(self, event):
dx = event.x() - self.lastPos.x()
dy = event.y() - self.lastPos.y()
if event.buttons() & Qt.LeftButton:
self.xOff += self.move_scale * dx
self.yOff += self.move_scale * dy
elif event.buttons() & Qt.MiddleButton:
self.scaleImage += self.size_scale * dy
if self.scaleImage < 0:
self.scaleImage = 0.0