-
Notifications
You must be signed in to change notification settings - Fork 0
/
HLSLToFlatOut2Shader.py
1560 lines (1266 loc) · 63.2 KB
/
HLSLToFlatOut2Shader.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
# Zack's HLSL to FlatOut SHA
version = "v2.5"
# Am I particularly proud of this code? uhh
try:
from tkinter import filedialog
except:
from Tkinter import filedialog
import time
import os
import re
filename = ""
author = ""
authors = "" # I accidentally made a typo in the original settings file so it's a feature now
loop = ""
is24Hour = False
isPixelShader = True
noOptimizations = False
includeComments = True
vertexConstants = 32
class HVar:
def __init__(self, name, register, value, tyype):
# The HLSL keyword it's associated with
self.name = name
# The assembly keyword it's associated with, could be "r0", "t0", or "oPos.yyy"
self.register = register
# Reserved for constants, this what came after the =, for example "float4(0.0f, 0.0f, 0.0f, 0.0f)"
self.value = value
# The first letter of the type, followed by the number of components, from 1-4. a float4 would be an f4 while an int3 would be an i3. Matrices start with m
self.type = tyype
# When packing multiple constants into a single register, the offset makes them reference the correct components
self.offset = 0
def __eq__(self, other):
return self.name == other
def __str__(self):
return "[" + ", ".join([self.name, self.register, self.value, self.type]) +"]"
def __repr__(self):
return "[" + ", ".join([self.name, self.register, self.value, self.type]) +"]"
class HStruct:
def __init__(self, name, properties):
self.name = name
self.properties = properties
def __eq__(self, other):
return self.name == other
def __str__(self):
return self.name
class HFunc:
def __init__(self, name, code):
self.name = name
self.code = code
linenum = 1
# I originally included the column number as well, but because it reads per-statement, the column will always be the semi-colon at the end of the line.
col = 0
scope = "global"
typeOfExpr = ""
constants = 3
startC = 3
def Error(message):
print("Error in", scope, "line", str(linenum), "(" + typeOfExpr + "):", message)
def every(string1, string2):
return all([(char in string2) for char in string1])
# dhvars is default hvars, it acts as the global namespace to return to after exiting a function
# the %split% marks where the user-defined default hvars begin
dhvars = [HVar("SHADOW", "c2", "", "f4"), HVar("AMBIENT", "v0", "", "f3"), HVar("FRESNEL", "v0.a", "", "f1"), HVar("BLEND", "v1.a", "", "f1"), HVar("%split%", "", "", "")]
hvars = []
fvars = []
hfuncs = [HFunc("dot", "dp3\t%0, %1, %2"), HFunc("lerp", "lrp\t%0, %3, %1, %2"), HFunc("mad", "mad\t%0, %1, %2, %3")]
def ResetDHVars(isPS=isPixelShader):
global dhvars
dhvars = dhvars[dhvars.index("%split%"):]
dhvars = ([HVar("SHADOW", "c2", "", "f4"), HVar("AMBIENT", "v0", "", "f3"), HVar("FRESNEL", "v0.a", "", "f1"), HVar("BLEND", "v1.a", "", "f1"), HVar("EXTRA", "v1", "", "f3")] if isPS else [HVar("FRESNEL", "oD0.a", "", "f1"), HVar("AMBIENT", "oD0.xyz", "", "f3"), HVar("BLEND", "oD1.a", "", "f1"), HVar("EXTRA", "oD1.xyz", "", "f3"), HVar("CAMERA", "c8", "", "f3"), HVar("PLANEX", "c17", "", "f4"), HVar("PLANEY", "c18", "", "f4"), HVar("PLANEZ", "c19", "", "f4")]) + dhvars
def PSTexToVSTex():
for dhvar in dhvars:
if dhvar.register:
if dhvar.register[0] == "t":
dhvar.register = "oT" + dhvar.register[1:]
def ResetAVars(isPS=isPixelShader):
global hfuncs
hfuncs = [HFunc("dot", "dp%tn1\t%0, %1, %2"), HFunc("lerp", "lrp\t%0, %3, %2, %1"), HFunc("mad", "mad\t%0, %1, %2, %3")] if isPS else [HFunc("dot", "dp%tn1\t%0, %1, %2"), HFunc("dot3", "dp3\t%0, %1, %2"), HFunc("dot4", "dp4\t%0, %1, %2"), HFunc("mad", "mad\t%0, %1, %2, %3"), HFunc("exp2", "expp\t%0, %1"), HFunc("exp2_full", "exp\t%0, %1"), HFunc("frac", "frc\t%0, %1"), HFunc("max", "max\t%0, %1, %2"), HFunc("min", "min\t%0, %1, %2"), HFunc("log2", "logp\t%0, %1"), HFunc("log2_full", "log\t%0, %1"), HFunc("rcp", "rcp\t%0, %1"), HFunc("rsqrt", "rsq\t%0, %1"), HFunc("rdistance", "sub\t%z, %1, %2\ndp3\t%z.w, %z, %z\nrsq\t%z.w, %z.w"), HFunc("distance", "sub\t%z, %1, %2\ndp3\t%z.w, %z, %z\nrsq\t%z.w, %z.w\nrcp\t%0, %z.w"), HFunc("dst", "dst\t%0, %1"), HFunc("abs", "max\t%0, %1, -%1"), HFunc("degrees", "rcp\t%z.x, c95.x\nmul\t%0, %z.x, %1"), HFunc("step", "sge\t%0, %1, %2"), HFunc("floor", "frc\t%z.w, %1\nsub\t%0, %1, %z.w"), HFunc("radians", "mul\t%0, c95.x, %1"), HFunc("lit", "mov\t%z.x, %1\nmov\t%z.y, %2\nmov\t%z.w, %3\nlit\t%0, %z"), HFunc("fresnel", "dp3\t%z.x, %1, %2\nmax\t%z.x, -%z.x, %z.x\nsub\t%z.x, c95.y, %z.x\nmul\t%z.x, %z.x, %z.x\nmul\t%z.x, %z.x, %z.x\nmul\t%0, %z.x, %z.x"), HFunc("reflect", "dp3\t%z.x, %1, %2\nadd\t%z.x, %z.x, %z.x\nmul\t%z, %z.x, %2\nsub\t%0, %1, %z"), HFunc("normalize", "dp3\t%z.a, %1, %1\nrsq\t%z.a, %z.a\nmul\t%0, %1, %z.a"), HFunc("lerp", "sub\t%z, %2, %1\nmad\t%0, %z, %3, %1"), HFunc("rlength", "dp3\t%z.a, %1, %1\nrsq\t%z.a, %z.a"), HFunc("length", "dp3\t%z.a, %1, %1\nrsq\t%z.a, %z.a\nrcp\t%0, %z.a"), HFunc("clamp", "min\t%z, %1, %3\nmax\t%0, %z, %2"), HFunc("sqrt", "rsq\t%z, %1\nrcp\t%0, %z"), HFunc("RotateToWorld", "m3x%tn0\t%0, %1, c4"), HFunc("LocalToWorld", "m4x%tn0\t%0, %1, c4"), HFunc("LocalToScreen", "m4x%tn0\t%0, %1, c0"), HFunc("mul", "m%tn2x%tn0\t%0, %1, %2")]
# Finds the item in list1 and retrieves the corrosponding item in list2
def Translate(list1, list2, item):
return list2[list1.index(item)]
def Count(string, thing):
return len(string.split(thing)) - 1
def HVarRegisterToVar(register):
for v in hvars + dhvars:
if v.register == register:
return v
return False
def StrToFloat(x):
x = x.strip()
if x[0] == "%" or x.isalpha(): return "0.0f"
if x[-1] == "f":
x = x[:-1]
return str(float(x)) + "f"
def OperatorPriority(char):
return "/*+-".find(char)
def AddConstant(name, value, valtype="f", pack=True, swizzle=True):
global constants
if constants >= maxC:
Error("Too many constants defined, there can only be " + str(maxC - startC) + ", since the game reserves " + str(startC) + " of them")
return ""
if "(" in value:
value = value[value.index("(") + 1:value.index(")")]
vals = [item.strip() for item in value.split(",")]
dimensions = len(vals)
allDimensions = 0
numConsts = 0
# Checking for pre-existing constant
valstring = ",".join([StrToFloat(item) for item in vals])
for hv in hvars + dhvars:
if hv.type and hv.value:
if hv.type[0] == valtype:
if hv.value != "debug":
existingvalues = ','.join([StrToFloat(item) for item in hv.value[hv.value.index("(") + 1:hv.value.index(")")].split(",")])
if valstring in existingvalues:
offset = Count(existingvalues[:existingvalues.index(valstring)], ",")
newRegister = ""
if "." in hv.register or not swizzle:
newRegister = hv.register
else:
newRegister = hv.register + "." + "xyzw"[offset:offset + dimensions]
if "constant_" not in name:
hvars.append(HVar(name, newRegister, "", valtype + str(dimensions)))
return newRegister
while len(vals) < 4:
vals.append("%x")
newHVar = HVar(name, "", "", valtype + str(dimensions))
suffix = ""
chart = "xyzw"
if dimensions < 4 and pack:
for c in range(startC, constants):
allDimensions = 0
numConsts = 0
firstConst = False
for hv in hvars + dhvars:
if hv.type:
if hv.type[0] == valtype:
if hv.register == "c" + str(c):
numConsts += 1
if not firstConst: firstConst = hv
allDimensions += len(hv.value.split("%x")) - 1
break
if firstConst:
if allDimensions >= dimensions:
if isPixelShader:
if dimensions == 1 and numConsts == 1 and ("%x" in firstConst.value):
newHVar.register = "c" + str(c)
newHVar.offset = 3
firstConst.value = firstConst.value[:firstConst.value.rfind("%x")] + vals[0] + firstConst.value[firstConst.value.rfind("%x") + 2:]
hvars.append(newHVar)
return newHVar.register + ".a"
else:
continue
newHVar.register = "c" + str(c)
newHVar.offset = 4 - allDimensions
for i in range(dimensions):
firstConst.value = firstConst.value.replace("%x", vals[i], 1)
hvars.append(newHVar)
return newHVar.register + (OffsetProperty("." + chart[:dimensions], newHVar.offset) if ("." not in newHVar.register) else "")
if swizzle:
suffix = OffsetProperty("." + chart[:dimensions], newHVar.offset)
newHVar.register = "c" + str(constants)
constants += 1
if isPixelShader and dimensions == 1:
vals = vals[1:] + [vals[0]]
newHVar.register += ".a"
suffix = ""
newHVar.value = Translate("fib", ["float", "int", "bool"], valtype)
newHVar.value += "4(" + ", ".join(vals) + ")"
hvars.append(newHVar)
return newHVar.register + suffix
def IsType(string):
if string:
types = ["float", "int", "bool", "void"]
for t in types:
if string.split(" ")[0] in ([t + str(i) for i in range(2, 5)] + [t]):
return True
return False
def IsConst(line):
if line:
if line.split(" ")[0] == "const":
return True
arg = line
'''
if "=" in line:
arg = line[line.index("=") + 1:].strip()
else:
arg = line
'''
if arg:
if arg[0] in "01234567890." or arg in ["true", "false"]:
if arg[:2] not in ["1-", "1/"]:
return True
for i in range(2, 5):
for t in ["float", "int", "bool"]:
if t + str(i) + "(" in arg:
return True
return False
def BreakdownMath(line):
tokes = [""]
symbols = "+-*" if isPixelShader else "+-*/"
mode = 0
bString = False
for char in line:
if char in ")]}":
mode -= 1
if char in "([{":
mode += 1
if char == "\"":
mode += -1 if bString else 1
bString = not bString
if not mode:
if char in symbols:
tokes[-1] = tokes[-1].strip()
if tokes[-1]:
if tokes[-1] not in "+-*":
if tokes[-1][-1] not in "(,":
tokes.append(char)
tokes.append("")
continue
tokes[-1] += char
tokes = [item.strip() for item in tokes]
if isPixelShader:
i = 0
while True:
try:
i = tokes.index("*", i)
except ValueError:
break
if tokes[i + 1] in ["2", "4"]:
tokes[i - 1] = tokes[i - 1] + tokes[i] + tokes[i + 1]
tokes = tokes[:i] + tokes[i + 2:]
i += 1
i = 0
while i < len(tokes):
token = tokes[i]
if isPixelShader:
if token == "1":
if i < (len(tokes) - 1):
if tokes[i + 1] == "-":
tokes[i] = "\"1-" + HVarNameToRegister(tokes[i + 2]) + "\""
tokes = tokes[:i + 1] + tokes[i + 3:]
continue
if IsConst(token):
if i < (len(tokes) - 1):
if token + tokes[i + 1] == "1/":
i += 1
continue
tokes[i] = "\"" + AddConstant("constant_" + str(constants), token, swizzle=True) + "\""
i += 1
return tokes
scopeSnapshot = []
psSnapshot = []
# Just so that you can fill texture data with texture.uv =
def HandleProperty(prop):
return prop.replace("u", "x").replace("v", "y")
def OffsetProperty(prop, offset):
chart = "xyzwrgba"
output = ""
for char in prop:
if char == ".":
output += char
else:
if char in chart:
output += chart[chart.index(char) + offset]
return output
def HandleString(string):
if string[0] == string[-1]:
return string[1:-1]
prefix = string[1:].split("\"")
ext = prefix[1]
prefix = prefix[0]
if "." in prefix:
return prefix[:prefix.index(".")] + ext
return prefix + ext
def TypeIdFromName(name):
if name in ["float", "int", "bool"]:
return Translate(["float", "int", "bool"], "fib", name) + "1"
return Translate(["float", "int", "bool"], "fib", name[:-1]) + name[-1]
def HVarNameToRegister(name, swizzle=True):
allhvars = dhvars + hvars
exptype = ""
if name[0] == "(":
exptype = TypeIdFromName(name[1:name.index(")")])
name = name[name.index(")") + 1:]
ext = ""
prefix = ""
if name:
if name[0] == "\"":
return HandleString(name)
if "." in name:
ext = "." + HandleProperty(name.split(".")[1].strip())
name = name.split(".")[0].strip()
if "-" in name:
prefix = name[:name.index("-") + 1]
name = name[name.index("-") + 1:]
if name in allhvars:
hv = Translate(allhvars, allhvars, name)
if not exptype:
exptype = hv.type
if (hv.offset or int(exptype[1:]) != 4) and (not ext) and ("." not in hv.register) and (hv.register[0] != "v") and (not isPixelShader) and swizzle:
ext = "." + "xyzw"[hv.offset:hv.offset + int(exptype[1:])]
return prefix + hv.register + OffsetProperty(ext, hv.offset)
Error("HVarNameToRegister(): Unknown Variable [" + name + "]")
return ""
def HVarRegisterToName(register):
allhvars = dhvars + hvars
for hv in allhvars:
if hv.register == register:
return hv.name
return ""
def HVarNameToVar(name):
allhvars = dhvars + hvars
for hv in allhvars:
if hv.name == name:
return hv
return False
def GetFVar(name):
return fvars[fvars.index(name)]
def IsDef(line):
if line.split(" ")[0] == "const":
line = line[6:].strip()
types = ["float", "int", "bool", "void", "auto"]
for t in types:
if line.split(" ")[0] in ([t + str(i) for i in range(2, 5)] + [t]):
return t[0]
return False
def IsFunc(line):
return "(" in line
def IsOp(text):
return "+" in text or "-" in text or "*" in text or ""
def IsCall(text):
return "(" in text
def CarefulIn(haystack, needle):
spaces = "\n\t +-*/=(){}[],.;"
for i in spaces:
for j in spaces:
if (i + needle + j) in haystack:
return True
return False
# Only replaces when there's space around the subject, makes absolutely sure it's not part of some other word
def CarefulReplace(text, replacer, replacee):
# Doing something with it to make sure it's a copy
script = text.replace("\n", "\n")
if script[:len(replacer)] == replacer:
script = replacee + script[len(replacer):]
if script[-len(replacer):] == replacer:
script = script[:-len(replacer)] + replacee
spaces = "\n\t +-*/=(){}[],.;"
for i in spaces:
for j in spaces:
script = script.replace(i + replacer + j, i + replacee + j)
return script
# returns the ) to the ( that you give it in a string, basically it skips nested parenthasis
def GetParEnd(string, index, par="()"):
layer = 0
while index < len(string):
if string[index] == par[1]:
if not layer: break
layer -= 1
if string[index] == par[0]:
layer += 1
index += 1
return index
# Returns the first unused register
# The offset allows for multiple unused registers to be allocated
def AllocateRegister(offset=0):
try:
return "r" + str(rStatus.index(False) + offset)
except ValueError:
Error("Ran out of registers to hold results, too much is being done in a single line")
return "r" + str(len(rStatus) - 1)
def GetOperands(string, dex):
s = string.find(" ", dex)
return [ string[max(string.rfind(" ", dex), 0):dex] , string[dex + 1:(s if s != -1 else len(string))]]
modifs = [("saturate", "sat"), ("half", "d2"), ("double", "x2"), ("quad", "x4"), ("d2", "d2"), ("x2", "x2"), ("x4", "x4")]
def GetFirstModif(string):
result = ""
dex = 999999999999
for m in modifs:
if m[0] + "(" in string:
if string.index(m[0] + "(") < dex:
result = m
dex = string.index(m[0] + "(")
return result
def ResetModifs(isPS=isPixelShader):
global modifs
modifs = [("saturate", "sat"), ("half", "d2"), ("double", "x2"), ("quad", "x4"), ("d2", "d2"), ("x2", "x2"), ("x4", "x4")] if isPS else []
def CompileOperand(string, ext="", dst="", components=4):
CompilePartial = CompileOperand_Partial
# Technically the name of this variable isn't right, but I didn't want to type out usedunusedRegisters every time
unusedRegisters = 0
if dst == "":
dst = AllocateRegister(0)
unusedRegisters = 1
fullsembly = ""
tokens = BreakdownMath(string)
while len(tokens) > 1:
for i in [0, 2]:
if "(" in tokens[i]:
this = CompilePartial(tokens[i], "", AllocateRegister(unusedRegisters), 4)
unusedRegisters += 1
fullsembly += this[1]
tokens[i] = "\"" + this[0] + "\""
if "[" in tokens[i]:
index = tokens[i][tokens[i].index("[") + 1:tokens[i].index("]")].strip()
if any([(char in index) for char in "*+-/("]):
that = CompileOperand(index, "", AllocateRegister(unusedRegisters) + ".x", 1)
unusedRegisters += 1
fullsembly += that[1]
fullsembly += "mov" + ext + "\ta0.x, " + that[0] + "\n"
else:
fullsembly += CompilePartial(index, "", "a0.x", 1)[1]
tokens[i] = "\"c[a0.x + " + HVarNameToRegister(tokens[i][:tokens[i].index("[")].strip())[1:] + "]\""
that = CompilePartial(" ".join(tokens[:3]), ext, dst, components)
tokens = ["\"" + that[0] + "\""] + tokens[3:]
fullsembly += that[1]
if tokens:
if "[" in tokens[0]:
index = tokens[0][tokens[0].index("[") + 1:tokens[0].index("]")].strip()
if any([(char in index) for char in "*+-/("]):
that = CompileOperand(index, "", AllocateRegister(unusedRegisters) + ".x", 1)
unusedRegisters += 1
fullsembly += that[1]
fullsembly += "mov" + ext + "\ta0.x, " + that[0] + "\n"
else:
fullsembly += CompilePartial(index, "", "a0.x", 1)[1]
tokens[0] = "\"c[a0.x + " + HVarNameToRegister(tokens[0][:tokens[0].index("[")].strip())[1:] + "]\""
fullsembly += CompilePartial(tokens[0], ext, dst, components)[1]
return [dst, fullsembly]
def GetRegisterType(register):
register = register.strip()
if "." in register:
return "f" + str(len(register[register.index(".") + 1:]))
return "f4"
# Skips strings, parenthasis, and brackets
def IndexOfSafe(string, item):
i = 0
for index, char in enumerate(string):
if char in "[(":
i += 1
if char in "])":
i -= 1
if not i:
if char == item:
if char == "-":
if index:
if string[index - 1] != "1":
return index
else:
return index
return -1
# Returns a list where the first item is the destination that contains the result of the code, and the second item is the code.
def CompileOperand_Partial(string, ext="", dst="", components=4):
string = string.strip()
sembly = ""
ops = ["*mul", "+add", "-sub"]
mathed = False
reg = 0
if dst == "":
dst = AllocateRegister()
reg += 1
CompilePartial = CompileOperand_PartialPS if isPixelShader else CompileOperand_PartialVS
secondOpinion = CompilePartial(string, ext, dst, components)
if secondOpinion:
return secondOpinion
if "(" in string:
if string[0] == "(" and string[-1] == ")":
return [dst, CompileOperand(string[1:-1], ext, AllocateRegister(), 4)[1]]
for av in hfuncs:
if string[:string.index("(")].strip() == av.name:
dex = string.index(av.name + "(") + len(av.name) + 1
end = GetParEnd(string, dex)
inner = [item.strip() for item in ArraySplit(string[dex:end])]
end = av.code
# When calling a function that reads from the destination, it checks if you gave it a write-only register and will use an unused variable register if that's the case.
if ("%z" in end and dst[0] != 'r') or "%z." in end:
newDst = "r" + str(rStatus.index(False))
end = end.replace("%z", newDst)
else:
end = end.replace("%z", dst)
end = end.replace("%0", dst)
if len(end.split("\t")) > 2:
end = end[:end.rfind("\t")] + ext + "\t" + end[end.rfind("\t") + 1:]
else:
end = end.replace("\t", ext + "\t")
end = end.replace("%tn0", str(components) if "." not in dst else str(len(dst[dst.index(".") + 1:])))
prepend = ""
for dex, item in enumerate(inner):
if not item: continue
if any([IndexOfSafe(item, char) != -1 for char in "+-*/"] + ["(" in item]):
if not (item == "-" and inner[dex - 1] == "1"):
that = CompileOperand(item, ext, AllocateRegister(reg), components)
reg += 1
prepend += that[1]
inner[dex] = "\"" + that[0] + "\""
item = "\"" + that[0] + "\""
if item[0] in "0123456789":
if item[:2] != "1-":
item = "\"" + AddConstant("constant_" + str(constants), item, "f" if item[-1] == "f" else "i") + "\""
if "." in item:
item = item.split(".")
item.append(len(item[1]))
else:
item = [item, ""]
if item[0] in hvars:
item[-1] = hvars[hvars.index(item[0])].type[1:]
elif item[0] in dhvars:
item[-1] = dhvars[dhvars.index(item[0])].type[1:]
else:
if not isPixelShader:
item[-1] = "m4" if (item[0] == "c0") else "m3" if (item[0] == "c4") else "4"
else:
item[-1] = "4"
end = end.replace("%tn" + str(dex + 1), str(item[-1]))
name = '.'.join(item[:-1]).strip()
hv = HVarNameToVar(name)
if hv:
# I don't know much about regular expressions
matches = re.findall("%" + str(dex + 1) + "\\.[xyzwrgba]+", end)
for m in matches:
end = end.replace(m, hv.register + OffsetProperty(m[m.index("."):], hv.offset))
register = hv.register
else:
register = HVarNameToRegister(name)
if "." in register:
end = end.replace("%" + str(dex + 1) + ".", register[:register.index(".") + 1])
end = end.replace("%" + str(dex + 1), register)
return [dst, prepend + end + "\n"]
for op in ops:
if op[0] in string:
dex = IndexOfSafe(string, op[0])
if dex != -1:
these = [string[:dex], string[dex + 1:]]
if isPixelShader and (op[0] == "-" and these[0].strip() in ["", "1"]): continue
sembly += op[1:] + ext + "\t" + dst + ", " + HVarNameToRegister(these[0].strip()) + ", " + HVarNameToRegister(these[1].strip()) + "\n"
mathed = True
break
if not mathed:
val = HVarNameToRegister(string)
if val != dst:
return [dst, "mov" + ext + "\t" + dst + ", " + val + "\n"]
return [dst, ""]
return [dst, sembly]
def CompileOperand_PartialPS(string, ext="", dst="", components=4):
mathed = False
m = GetFirstModif(string)
if m:
dex = string.index(m[0] + "(") + len(m[0]) + 1
end = GetParEnd(string, dex)
inner = string[dex:end]
return CompileOperand(inner, "_" + m[1] + ext, dst)
if "?" in string:
symbols = [">=", "<"]
symbolMeanings = [", %0, %1", ", %1, %0"]
for dex, symbol in enumerate(symbols):
if symbol in string:
splt = string[:string.index("?")].strip()
if splt[0] == "(" and splt[-1] == ")":
splt = splt[1:-1]
splt = [item.strip() for item in splt.split(symbol)]
flip = False
if not splt[0].isalpha():
flip = float(splt[0]) == 0.0
src0 = splt[1] if flip else splt[0]
if flip: dex = int(not bool(dex))
values = [item.strip() for item in string[string.index("?") + 1:].split(":")]
return [dst, "cmp" + ext + "\t" + ", ".join([dst, HVarNameToRegister(src0)]) + symbolMeanings[dex].replace("%0", HVarNameToRegister(values[0])).replace("%1", HVarNameToRegister(values[1]))]
dex = string.index("?") + 1
inner = string[dex:].split(":")
return [dst, "cnd" + ext + "\t" + ", ".join([dst, "r0.a", HVarNameToRegister(inner[0].strip()), HVarNameToRegister(inner[1].strip())]) + "\n"]
if "/" in string:
if string[string.index("/") + 1:].strip() != "2":
Error("Dividing can only be done by 2. It's used like saturate(), an addon to a math expression or another function, such as (a + b / 2)")
return CompileOperand(string.split("/")[0].strip(), "_d2" + ext, dst)
if "*" in string:
val = string[string.rfind("*") + 1:].replace(" ", "")
if val == "2":
ext = "_x2" + ext
mathed = True
elif val == "4":
ext = "_x4" + ext
mathed = True
if mathed:
return CompileOperand(string[:string.rfind("*")], ext, dst)
return False
def CompileOperand_PartialVS(string, ext="", dst="", components=4):
if "/" in string:
if string.split("/")[0].strip() == "1":
return [dst, "rcp\t" + dst + ", " + HVarNameToRegister(string.split("/")[1].strip()) + "\n"]
return [dst, "rcp\t" + dst + ", " + HVarNameToRegister(string.split("/")[1].strip()) + "\nmul\t" + dst + ", " + dst + ", " + HVarNameToRegister(string.split("/")[0].strip()) + "\n"]
if "?" in string:
dex = string.index("?")
inner = string[:dex].strip()
if inner[0] == "(" and inner[-1] == ")":
inner = inner[1:-1]
prefix = ""
compareOps = [("<", "slt\t%0, %1, %2"), (">", "slt\t%0, %2, %1"), ("<=", "sge\t%0, %2, %1"), (">=", "sge\t%0, %1, %2")]
for c in compareOps:
if c[0] in inner:
those = [item.strip() for item in inner.split(c[0])]
for where, these in enumerate(those):
if any([char in these for char in "-+*/("]):
that = CompileOperand(these)
prefix += that[1]
if "\"" in that[0]:
those[where] = that[0]
else:
those[where] = "\"" + that[0] + "\""
return [dst, prefix + c[1].replace("%0", dst).replace("%1", HVarNameToRegister(those[0])).replace("%2", HVarNameToRegister(those[1])) + "\n"]
return False
def ArrangeMad(muls, adds):
i = adds.index(muls[0], 1)
return (adds[0], muls[1], muls[2], adds[1 if i == 2 else 2])
# the real rfind is not working for some reason, now I have to roll my own knock-off version
def RFind(haystack, needle, start=-1):
if start == -1:
start = len(haystack) - len(needle)
if needle in haystack:
for i in range(start, 0, -2):
if haystack[i:i+len(needle)] == needle:
return i
return -1
maxR = 2
maxT = 4
maxV = 2
maxC = 5
def includes_defines(list_item, test_value):
return list_item[0] == test_value
# includes with a key
def includes(lst, item, func=includes_defines):
for i in lst:
if func(i, item):
return True
return False
# Removes vector splitting to get just the variable
def StripSplit(string):
return string.split(".")[0].strip()
# This function optimizes the assembly code that the compiler output.
# It turns multiplies and adds into mads, and skips the middle man when a result is mov'd somewhere and isn't read from the original source again
def SecondPass(script):
tempScript = ""
dex = 0
script = script.replace("\n\n", "\n")
while (mdex := script.find("mul", dex)) != -1:
tdex = script.index("\n", mdex)
muls = script[mdex + 4:tdex].split(",")
muls = [item.strip() for item in muls]
if script[tdex + 1:tdex + 4] == "add":
adds = script[script.index("\t", tdex + 1) + 1:script.index("\n", tdex + 1)].split(",")
adds = [item.strip() for item in adds]
if muls[0] in adds[1:]:
mads = [item.strip() for item in ArrangeMad(muls, adds)]
tempScript = script[:mdex] + "mad"
sdex = script.index("\n", tdex + 1)
if script[tdex + 4] == '_':
tempScript += "_" + script[tdex + 5:script.index("\t", tdex+5)]
tempScript += "\t"
tempScript += ', '.join(mads)
tempScript += script[sdex:]
script = tempScript
dex = mdex + 1
dex = 0
while (mdex := script.find("mov\t", dex)) != -1:
sdex = RFind(script, "\n", mdex - 2)
tdex = script.find("\t", sdex)
if script[mdex + 4:mdex + 8] == "a0.x":
dex = mdex + 1
continue
if tdex != -1:
muls = script[tdex + 1:script.index("\n", tdex)].split(",")
dst = ((script[script.index(",", mdex) + 1:script.index("\n", mdex + 1)].strip()) if script.find("\n", mdex + 1) != -1 else script[script.index(",", mdex) + 1:].strip())
if script[tdex + 1:script.index(",", tdex + 1)] == dst:
if not script.find("," + dst, script.index("\n", tdex)) < script.find(dst + ",", script.index("\n", tdex)):
tgt = script[mdex + 3:script.index(",", mdex)]
end = script.find("\n", mdex)
script = script[:tdex] + tgt + ", " + ", ".join([item.strip() for item in muls[1:]]) + (script[end:] if end != -1 else "")
dex = mdex + 1
return script
def HandleAssign(line):
for symb in ["*=", "+=", "-="]:
if symb in line:
splt = [item.strip() for item in line.split(symb)]
return splt[0] + " = " + splt[0] + " " + symb[0] + " " + splt[1]
return line
def HandleForLoop(code, start, condition, inc, name, ssemblystart):
referenced = CarefulIn(code, name)
output = (ssemblystart + ";\n") if referenced else ""
exec(start)
while eval(condition):
output += code + ((inc + ";\n") if referenced else "")
exec(inc)
return output
def ArraySplit(string):
rray = [""]
depth = 0
for char in string:
if char == "(":
depth += 1
if char == ")":
depth -= 1
if char == "," and not depth:
rray.append("")
continue
rray[-1] += char
return rray
prevMode = 0
def CompileHLSL(script, hv=-1, dst="r0"):
global linenum, col, scope, r0, r1, typeOfExpr, hvars
global constants
if hv == -1:
hv = []
mode = 1
bMeanwhile = False
temp = 0
liner = 0
output = ""
buffer = ""
index = 0
scopeCheck = 0
while index < len(script):
char = script[index]
index += 1
# Comments
if mode not in [0, 2]:
if liner:
if liner == 1:
if includeComments: output += char
if char != '\n': continue
liner = 0
else:
if char == "\n":
if includeComments: output += "\n;"
linenum += 1
elif includeComments:
output += char
if temp == "*" and char == "/":
output = output[:output.rfind("\n") + 1]
output += "\n"
liner = 0
continue
else:
temp = char
continue
if buffer:
if buffer[-1] == '/':
if char == '/':
buffer = buffer[:-1]
liner = 1
if includeComments:
if output:
if output[output.rfind("\n", 0, len(output) - 1) + 1] != ";":
output += "\n\n"
output += ";"
continue
if char == '*':
buffer = buffer[:-1]
liner = 2
temp = ""
if includeComments: output += "\n\n;"
continue
if char == '\n':
linenum += 1
col = 0
col += 1
# Checking for assembly
if mode != 2 and buffer[-4:-1] == "asm" and buffer[-1] in "\t\n {":
buffer = ""
prevMode = mode
mode = 0
continue
# Reading Assembly
if not mode:
if char == "}":
mode = prevMode
continue
if char == "{": continue
if output != "":
if (char in " \t\n") and (output[-1] == '\n'): continue
output += char
continue
# Reading Function
elif mode == 2:
if char == '}':
if not temp:
hfuncs[-1].code = CompileHLSL(buffer.strip(), -1, "%0")
buffer = ""
mode = 1
for dex, item in enumerate(hvars):
if item.register[0] == "%":
hvars = hvars[:dex] + hvars[dex + 1:]
scope = "PixelShader" if isPixelShader else "VertexShader"
continue
else:
temp -= 1
if char == '{' and buffer.strip():
temp += 1
buffer += char
# Reading HLSL
elif mode == 1:
if buffer:
if (char == ' ' and char == buffer[-1]):
continue
if char in '\t\n':
continue
if char == "(": scopeCheck += 1
if char == ")": scopeCheck -= 1