qrsc_to_tw.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. #!/usr/bin/env python3
  2. import fileinput
  3. import io, os, re, datetime
  4. import hashlib
  5. import variables
  6. import time
  7. verbose = False
  8. #verbose = True
  9. skipMode = 0
  10. #skipMode = -1
  11. verbose_i = 20
  12. error_counter = 1
  13. regex_parts = {}
  14. regex_parts['operator_assign'] = r'=|\+=|-='
  15. regex_parts['parameter'] = r"\$ARGS\[\d+\]"
  16. regex_parts['var'] = r"\$?[a-z]+\w*"
  17. regex_parts['functioncall'] = r"\w+\s*\(\s*\w+\s*(?:,\s*\w*\s*)*\)"
  18. regex_parts['integer'] = r"\d+"
  19. regex_parts['string'] = r"""'\w'|"""+ r'''"\w"'''
  20. regex_parts['value_literal'] = "|".join([regex_parts['integer'],regex_parts['string']])
  21. regex_parts['value'] = "|".join([regex_parts['parameter'],regex_parts['var'],regex_parts['functioncall'],regex_parts['value_literal'] ])
  22. regex_parts['statement'] = '?'
  23. regex_parts['assignment'] = f"\s*({regex_parts['var']})\s*({regex_parts['operator_assign']})\s*({regex_parts['value']})\s*"
  24. def pv(desc,line):
  25. if(verbose):
  26. print(desc.ljust(verbose_i, ' ')+line)
  27. def convert_calculation(right):
  28. pv("START CALCULATION:",right)
  29. brackets_regex = r"""(?<![a-zA-Z0-9])\(\s*([^\)^\(]+(\s*\-|mod|\+|/|\*\s*)[^\)^\(]+)\s*\)"""
  30. #brackets_regex = r"""(?<![a-zA-Z0-9])(?:min|rand|max|mid)\(\s*([^\)^\(]+(\s*\-|mod|\+|/|\*\s*)[^\)^\(]+)\s*\)"""
  31. calculations = []
  32. #print(right)
  33. while b_match := re.search(brackets_regex,right):
  34. complete_match = b_match.group(0)
  35. calculation_raw = b_match.group(1)
  36. operator = b_match.group(2)
  37. if operator == 'mod':
  38. calculation_raw = calculation_raw.replace('mod','%')
  39. calculation = convert_literal(calculation_raw)
  40. index = f"$CALC_HELPER_{len(calculations)}"
  41. right = right.replace(complete_match,index)
  42. calculations.append(calculation)
  43. right = convert_literal(right)
  44. #function_name_regex = r"""(?<![a-zA-Z0-9])(min|rand|mid|max)\s*\$LIT_HELPER_(0)"""
  45. #while function_name_match := re.search(function_name_regex,right):
  46. # complete_match = function_name_match.group(0)
  47. # index = f"$LIT_HELPER_{len(calculations)}"
  48. # right = right.replace(complete_match,index)
  49. # calculations.append(complete_match)
  50. while len(calculations) > 0:
  51. calculation = calculations.pop()
  52. index = f"$CALC_HELPER_{len(calculations)}"
  53. right = right.replace(index,f"({calculation})")
  54. pv("IS CALCULATION:",right)
  55. return right
  56. def convert_command(command_raw):
  57. command = command_raw.strip()
  58. #if (command.startswith('<') or and command.endswith('>'):
  59. # return command
  60. split_by_and = command.split(' & ')
  61. if len(split_by_and) > 1:
  62. return ' '.join([convert_command(s) for s in split_by_and])
  63. assign_operators = ['=','-=','+=']
  64. for assign_operator in assign_operators:
  65. split_by_assign = command.split(assign_operator,1)
  66. if len(split_by_assign) > 1:
  67. left = split_by_assign[0]
  68. if left.startswith('set '):
  69. left = left[4:]
  70. right = split_by_assign[1]
  71. right = convert_calculation(right)
  72. pv("IS ASSIGNMENT:",right)
  73. return f'<<set {convert_literal(left)} {assign_operator} {right}>>'
  74. if match := re.match(r"^(?:set\s*)?(\$?\w+)\s*(\+=|-=|=)\s*([\$']?\w*'?|\w+\s*\(\s*\w+\s*(?:,\s*\w*\s*)*\))$",command):
  75. return f'<<set {convert_literal(match.group(1))} {match.group(2)} {convert_literal(match.group(3))}>>'
  76. if match := re.match(r"""^(x?gt|gs)([\s'"].+)$""",command):
  77. arguments = match.group(2)
  78. pv('GS OR GT:',command)
  79. i = 0
  80. replaces = []
  81. while brackets_match := re.search(r"""\(([^\(^\)]*?,[^\(^\)]*?)\)""",arguments):
  82. original = brackets_match.group(1)
  83. pv("REPLACE:",original)
  84. indentifier = f'$BRACKET_HELER_{i}'
  85. arguments = arguments.replace(original,indentifier)
  86. replaces.append(original)
  87. i += 1
  88. arguments = " ".join([convert_literal(l) for l in arguments.split(',')])
  89. while len(replaces) > 0:
  90. original = replaces.pop()
  91. indentifier = f'$BRACKET_HELER_{len(replaces)}'
  92. arguments = arguments.replace(indentifier,original)
  93. return f'<<{match.group(1)} {arguments}>>'
  94. if match := re.match(r"""^msg\s*(.+)$""",command,re.I):
  95. return f"<<msg {match.group(1)}>>"
  96. if match := re.match(r"""^dynamic \$(.*)$""",command,re.I):
  97. arguments = match.group(1).replace(',',' ')
  98. return f"<<{arguments}>>"
  99. pv("NO COMMAND MATCH:",command)
  100. return ''
  101. def convert_condition(condition_raw):
  102. condition = condition_raw.strip()
  103. if(re.match(r"dyneval\(",condition)):
  104. return condition
  105. #condition = convert_calculation(condition)
  106. #print(condition)
  107. subconditions = []
  108. bracket_search_regex = r"""(?<![a-zA-Z0-9])\(\s*([^\)^\(]+)\s*\)"""
  109. bracket_search_regex = r"""(?<![a-zA-Z0-9])\(\s*([^\)^\(]+(\s*and|or|xor\s*)[^\)^\(]+)\s*\)"""
  110. while match := re.search(bracket_search_regex,condition):
  111. fullmatch = match.group(0)
  112. subcondition = match.group(1)
  113. subcondition_converted = convert_condition(subcondition)
  114. subcondition_ident = f"$CON_HELPER_{len(subconditions)} == 1"
  115. condition = condition.replace(fullmatch,subcondition_ident)
  116. subconditions.append(subcondition_converted)
  117. #print(condition)
  118. if len(subconditions) > 0:
  119. condition = convert_condition(condition)
  120. while len(subconditions) > 0:
  121. subcondition = subconditions.pop()
  122. subcondition_ident = f"$CON_HELPER_{len(subconditions)} == 1"
  123. condition = condition.replace(subcondition_ident,f"({subcondition})")
  124. #print(condition)
  125. return condition
  126. split_by_or = condition.split(' or ')
  127. if len(split_by_or) > 1:
  128. return ' or '.join([convert_condition(s) for s in split_by_or])
  129. split_by_xor = condition.split(' xor ')
  130. if len(split_by_xor) > 1:
  131. return ' xor '.join([convert_condition(s) for s in split_by_xor])
  132. split_by_and = condition.split(' and ')
  133. if len(split_by_and) > 1:
  134. return ' and '.join([convert_condition(s) for s in split_by_and])
  135. #match = re.match(r"(\$ARGS\[\d+\]|\$?\w+)\s*([=><]+)\s*('?\w+'?)",condition)
  136. #match = re.match(r"(\S+)\s*([=><]+)\s*(\S+)",condition)
  137. if(len(condition) >= 2 and condition[0] == '(' and condition[-1] == ')'):
  138. condition = condition[1:-1]
  139. #print(condition)
  140. match = re.match(r"([^<^>^=^!]+)\s*([=><!]+)\s*([^<^>^=^!]+)",condition)
  141. if match:
  142. left = convert_literal(convert_calculation(match.group(1)))
  143. right = convert_literal(match.group(3))
  144. operator = match.group(2)
  145. if operator == '=':
  146. operator = '=='
  147. elif operator == '!':
  148. operator = '!='
  149. elif operator == '=>':
  150. operator = '>='
  151. elif operator == '=<':
  152. operator = '<='
  153. return ' '.join([left,operator,right])
  154. return f'ERROR: FAILED TO CONVERT CONDITION: {condition}'
  155. def convert_literal(literal_raw):
  156. literal = literal_raw.strip()
  157. pv("START LITERAL:",literal)
  158. if not literal:
  159. return ''
  160. subliterals = []
  161. bracket_search_regex = r"""\[\s*([^\]^\[]+)\s*\]"""
  162. while match := re.search(bracket_search_regex,literal):
  163. fullmatch = match.group(0)
  164. subcondition = match.group(1)
  165. subcondition_converted = convert_literal(subcondition)
  166. subcondition_ident = f"LIT_HELPER_{len(subliterals)}"
  167. literal = literal.replace(fullmatch,subcondition_ident)
  168. subliterals.append(subcondition_converted)
  169. #print(condition)
  170. if len(subliterals) > 0:
  171. literal = convert_literal(literal)
  172. while len(subliterals) > 0:
  173. subcondition = subliterals.pop()
  174. subcondition_ident = f"LIT_HELPER_{len(subliterals)}"
  175. literal = literal.replace(subcondition_ident,f"[{subcondition}]")
  176. #print(condition)
  177. return literal
  178. #brackets_regex = r"""\(\s*([^\)^\(]+)\s*\)"""
  179. #function_name_regex = r"""(?<![a-zA-Z0-9])(min|rand|mid|max)\s*\$LIT_HELPER_(0)"""
  180. #calculations = []
  181. #while b_match := re.search(brackets_regex,literal):
  182. # complete_match = b_match.group(0)
  183. # calculation_raw = b_match.group(1)
  184. # calculation_parts = calculation_raw.split(',')
  185. # calculation = ','.join([convert_literal(s) for s in calculation_parts])
  186. # index = f"$LIT_HELPER_{len(calculations)}"
  187. # literal = literal.replace(complete_match,index)
  188. # calculations.append(calculation)
  189. #while function_name_match := re.search(function_name_regex,literal):
  190. # complete_match = function_name_match.group(0)
  191. # index = f"$LIT_HELPER_{len(calculations)}"
  192. # literal = literal.replace(complete_match,index)
  193. # calculations.append(complete_match)
  194. #if len(calculations) > 0:
  195. # literal = convert_literal(literal)
  196. # while len(calculations) > 0:
  197. # calculation = calculations.pop()
  198. # index = f"$LIT_HELPER_{len(calculations)}"
  199. # literal = literal.replace(index,f"({calculation})")
  200. # pv("LITERAL AFTER BRACKETS:",literal)
  201. if(re.match(r"dyneval\(",literal)):
  202. return literal
  203. if literal == "''" or literal == '""':
  204. return literal
  205. if(literal.isnumeric() or (literal.startswith('-') and literal[1:].isnumeric())):
  206. pv("IS NUMERIC",literal)
  207. return literal
  208. if(literal.startswith('(') and len(literal) > 1):
  209. return '('+literal[1:]
  210. if(literal.endswith(')') and len(literal) > 1):
  211. return literal[:-1]+')'
  212. #array_braces = False
  213. #while match:=re.match(r"\$?([a-z][a-z0-9\-_{}'\+]*)(\['(.*?<<.*?>>'*?)'\])",literal,re.I):
  214. # value = match.group(3)
  215. # if not value.startswith("<"):
  216. # value = value.replace("<<","'+")
  217. # else:
  218. # value = value.replace("<<","")#
  219. #
  220. # if not value.endswith(">"):
  221. # value = value.replace(">>","+'")
  222. # else:
  223. # value = value.replace(">>","")
  224. # literal = literal.replace(match.group(2),r"{{"+value+r"}}")
  225. # array_braces = True
  226. #if array_braces:
  227. # literal = literal.replace(r'{{','[').replace(r'}}',']')
  228. if(len(literal)>= 3 and ((literal[0] == '\'' and literal[-1] == '\'') or (literal[0] == '"' and literal[-1] == '"') )):
  229. literal = literal.replace('<<','')
  230. literal = literal.replace('>>','')
  231. literal = literal.replace("''","'")
  232. return literal
  233. if(match := re.match(r"^arrsize\(\s*'(\$?)([a-z]+\w*)'\s*\)$",literal)):
  234. return f"${match.group(2)}.length"
  235. if(match := re.match(r"^killvar\s+'(\$?)([a-z]+\w*)'$",literal,re.I)):
  236. return f"<<set ${match.group(2)} to null>>"
  237. if(match := re.match(r'^\$ARGS\[(\d+)\]$',literal,re.I)):
  238. #ARGS
  239. return f'$location_var[$here][{match.group(1)}]'
  240. if(match := re.match(r'^\$ARGS(LIT_HELPER_\d+)$',literal,re.I)):
  241. #ARGS
  242. return f'$location_var[$here]'+match.group(1)
  243. if(match := re.match(r"^(\$?)[a-zA-z]+\w*(\[('\w*'|\d+)\])?$",literal)):
  244. if match.group(1):
  245. return literal
  246. return '$'+literal
  247. if(match := re.match(r"^(\$?)([a-zA-z]+\w*)\[(.+)\]$",literal)):
  248. #if match.group(1):
  249. # return f"${match.group(2)}[{convert_literal(match.group(3))}]"
  250. return f"${match.group(2)}[{convert_literal(match.group(3))}]"
  251. #print(literal)
  252. if(match := re.match(r'^(\w+)\s*\((\s*\w+\s*(?:,\s*\w*\s*)*)\)$',literal)):
  253. function_name = match.group(1)
  254. function_parameters = match.group(2)
  255. return f'{function_name}({convert_literal(function_parameters)})'
  256. while(match := re.search(r'<<(\$\w+)>>',literal)):
  257. literal = literal.replace(match.group(0),match.group(1))
  258. #Arithmetic Operations
  259. arith_operations = ['*','/','-','+','%',',','mod']
  260. for arith_operation in arith_operations:
  261. split_by_arith = literal.split(arith_operation)
  262. if len(split_by_arith) > 1:
  263. if arith_operation == 'mod':
  264. arith_operation = '%'
  265. return f' {arith_operation} '.join([convert_literal(s) for s in split_by_arith])
  266. if literal.startswith('wait '):
  267. return f'<<{literal}>>'
  268. if(match := re.match(r"""^killvar\s+['"]\$?(.*)['"]$""",literal)):
  269. return f'<<set ${match.group(1)} = 0>>'
  270. if literal.startswith('jump '):
  271. jump_san = literal.replace('"','').replace("'","")
  272. return f"<<warn 'JUMP COMMAND ENCOUNTERED: {jump_san}'>>"
  273. if literal.startswith(':'):
  274. return f"<<warn 'JUMP MARKER ENCOUNTERED: {literal}'>>"
  275. if literal == "'" or literal == '"':
  276. return ''
  277. if re.match(r"""^['"\w\s\?\.!\(\)\$]+$""",literal):
  278. pv("Plain String",literal)
  279. return literal
  280. #return literal
  281. return f'ERROR: FAILED TO CONVERT LITERAL: """{literal}"""'
  282. function_name_conversions = []
  283. def convert_lineblock(lines,location_identifier=''):
  284. outputs = []
  285. nesting = []
  286. commenting = False
  287. isfunction = False
  288. functionlines = []
  289. functionlines_temp = []
  290. function_name = ''
  291. subpassages = {}
  292. subpassage = ''
  293. for line_raw in lines:
  294. #line_raw = lines[line_num]
  295. line = line_raw.strip()
  296. original = line
  297. pv("START:",line)
  298. if len(line) == 0:
  299. continue
  300. whitespace_count = len(nesting)
  301. # Subpassages
  302. if len(subpassage) > 0:
  303. if line.startswith('~$'):
  304. endSubpassageName = line[2:]
  305. gtOrGs = 'gt'
  306. if endSubpassageName.startswith('gs:'):
  307. gtOrGs = 'gs'
  308. endSubpassageName = endSubpassageName[3:]
  309. if endSubpassageName == subpassage:
  310. outputs.append( whitespace_count * '\t' + f"<<{gtOrGs} '{subpassage}' $location_var[$here][0] $location_var[$here][1] $location_var[$here][2] $location_var[$here][3] $location_var[$here][4]>>\n")
  311. subpassages[subpassage].append('<!-- END: '+subpassage+' -->')
  312. subpassage = ''
  313. continue
  314. subpassages[subpassage].append(line)
  315. continue
  316. if len(subpassage) == 0:
  317. if line.startswith('~^'):
  318. startSubpassageName = line[2:]
  319. subpassage = startSubpassageName
  320. subpassages[subpassage] = []
  321. continue
  322. for preparation in preparations:
  323. if len(preparation) > 2:
  324. line = re.sub(preparation[0],preparation[1],line,0,preparation[2])
  325. else:
  326. line = re.sub(preparation[0],preparation[1],line)
  327. line_output = ''
  328. purges = [
  329. 'CLOSE ALL',
  330. 'close all',
  331. '*clr & cla',
  332. 'killall',
  333. 'showstat 0','showstat 1',
  334. 'showobjs 0','showobjs 1',
  335. 'showinput 0','showinput 1',
  336. "gs 'stat'","gs'stat'",
  337. ]
  338. for purge in purges:
  339. line = line.replace(purge,'')
  340. pv("AFTER PURGES:",line)
  341. #line = line.replace(" mod "," % ")
  342. #while match := re.match(r"iif\s*\((.+),(.*),(.*)\)",line):
  343. # line = line.replace(match.group(0),f"({convert_condition(match.group(1))}) ? {convert_literal(match.group(2))} : {convert_literal(match.group(3))}")
  344. # FUNCTIONS
  345. if isfunction:
  346. if line.endswith('}'):
  347. isfunction = False
  348. functionname_sanatized = function_name.replace('$','').replace('[','').replace(']','').replace("'",'')
  349. functionlines.append(f':: {functionname_sanatized}_macro[widget]\n<<widget "{functionname_sanatized}">>\n')
  350. functionlines_temp = convert_lineblock(functionlines_temp)
  351. for fl in functionlines_temp:
  352. functionlines.append(f'\t{fl}')
  353. functionlines.append(f'<</widget>>\n')
  354. function_name_conversions.append([function_name,functionname_sanatized])
  355. else:
  356. functionlines_temp.append(line)
  357. continue
  358. if match := re.match(r"""(\$[a-z][a-z0-9\-_'"\[\]]+)\s*=\s*{""",line,re.I):
  359. isfunction = True
  360. #functionlines.append(f'<<widget "{match.group(1)}">>')
  361. function_name = match.group(1)
  362. functionlines_temp = []
  363. continue
  364. pv("AFTER FUNCTIONS:",line)
  365. while fuckyoumatch := re.search(r"""\[["']([^\]]*?)<<(.*?)>>(.*?)["']\]""",line):
  366. index = f'${fuckyoumatch.group(2)}'
  367. #left = ''
  368. if fuckyoumatch.group(1):
  369. index = f"'{fuckyoumatch.group(1)}'+" + index
  370. #right = ''
  371. if fuckyoumatch.group(3):
  372. index = index + f"+'{fuckyoumatch.group(3)}'"
  373. # right = fuckyoumatch.group(3)
  374. #index = f"'{left}'+${fuckyoumatch.group(2)}+'{right}'"
  375. #print(index)
  376. line = line.replace(fuckyoumatch.group(0),f"[{index}]")
  377. #print("MATCH")
  378. pv("AFTER ARRAY []:",line)
  379. while dynevalmatch := re.search(r"""dyneval\s*\(\s*'\s*RESULT\s*=\s*(<<.*?)'\s*\)""",line):
  380. fullmatch = dynevalmatch.group(0)
  381. varname = dynevalmatch.group(1)
  382. varname = varname.replace(r"[''",r"['").replace(r"'']",r"']")
  383. varname = "State.getVar('$"+varname.replace('<<',"'+").replace('>>',"+'")+"')"
  384. line = line.replace(fullmatch,varname)
  385. #print(line)
  386. pv("AFTER DYNEVAL:",line)
  387. while dynevalmatch := re.search(r"""dyneval\s*\(\s*'\s*RESULT\s*=\s*\$?(.*?)'\s*\)""",line):
  388. fullmatch = dynevalmatch.group(0)
  389. varname = "$"+dynevalmatch.group(1)
  390. varname = varname.replace('<<',"'+").replace('>>',"+'")
  391. #varname = varname.replace(r"[''",r"['").replace(r"'']",r"']")
  392. varname = varname.replace("['+","[").replace(r"+']",r"]")
  393. varname = varname.replace('$$',"$")
  394. line = line.replace(fullmatch,varname)
  395. pv("AFTER DYNEVAL2:",line)
  396. if line.startswith('!{') or line.startswith('!!{') or line == '!!{':
  397. line_output = '<!-- ' + line
  398. if line.endswith('}'):
  399. line_output += ' -->'
  400. else:
  401. commenting = True
  402. pv("IS COMMENT:",line_output)
  403. elif line.endswith('}') and commenting:
  404. line_output = line+' -->'
  405. commenting = False
  406. pv("IS COMMENT:",line_output)
  407. elif commenting:
  408. line_output = line.replace('--','-')
  409. pv("IS COMMENT:",line_output)
  410. elif line.lower() == 'end' or line.lower().startswith('end &!'):
  411. whitespace_count -= 1
  412. if len(nesting) > 0:
  413. end_command = nesting.pop()
  414. if end_command == 'if':
  415. #file.write('<</if>>\n')
  416. line_output = '<</if>>'
  417. elif end_command == 'while':
  418. #file.write('<</while>>\n')
  419. line_output = '<</while>>'
  420. elif end_command == 'act':
  421. #file.write('<</act>>\n')
  422. line_output = '<</act>>'
  423. else:
  424. print(f'ERROR: UNKNOWN NESTRING: {end_command}')
  425. else:
  426. line_output = '<</END>>'
  427. pv("IS END:",line_output)
  428. elif line.startswith('!'):
  429. line_output = '<!-- ' + line + '-->'
  430. pv("IS COMMENT:",line_output)
  431. elif line.lower() == 'else':
  432. #file.write('<<else>>\n')
  433. line_output = '<<else>>'
  434. whitespace_count -= 1
  435. pv("IS ELSE:",line_output)
  436. elif line.lower() == 'cls':
  437. line_output = ''
  438. pv("IS CLS:",line_output)
  439. elif line.lower() == '*nl':
  440. #file.write('\n')
  441. line_output = ''
  442. pv("IS NL:",line_output)
  443. elif line[0:3] == '---':
  444. line_output = ''
  445. pv("IS EOF:",line_output)
  446. elif match := re.match(r"^\s*msg\s*'(.*)'\s*$",line,re.I):
  447. msg = match.group(1).replace("'",'"')
  448. line_output = f"""<<msg '{msg}'>>"""
  449. pv("IS MSG:",line_output)
  450. elif match := re.match(r"""act\s*'(.*?)\s*\(<font color="red"><<will_cost>> Willpower</font>\)':\s*'<br><font color="red">You don''t have enough willpower to use this action.</font>'""",line,re.I):
  451. label = match.group(1).replace("'",'"')
  452. line_output = f"<<act `'{label} ('+$will_cost+')'`>><font color=red><br/>You don`t have enough willpower to use this action.</font><</act>>"
  453. elif match := re.match(r"""^'(?:<center>)?<img\s+(?:<<\$?\w+>>\s+)src="images\/([\w\/\.]+)(?:'\s*\+\s*rand\((\d+,\d+)\)\s*\+\s*')?([\w\/\.]+)"\s*>(?:<\/center>)?'""",line,re.I):
  454. #Images
  455. if match.group(2):
  456. line_output = f'''<<image "{match.group(1)}#{match.group(3)}" {match.group(2).replace(',',' ')}>>'''
  457. else:
  458. line_output = f'''<<image "{match.group(1)}{match.group(3)}">>'''
  459. pv("IS IMAGE:",line_output)
  460. elif match := re.match(r"""^'?(?:<center>)?<video\s+(?:<<\$?\w+>>\s+)*(?:\s*autoplay\s*|\s*loop\s*)*src="images\/([\w\/\.]+)(?:'\s*\+\s*rand\((\d+,\d+)\)\s*\+\s*')?([\w\/\.]+)"\s*>(?:<\/video>)?(?:<\/center>)?'?""",line,re.I):
  461. #Images
  462. if match.group(2):
  463. line_output = f'''<<video "{match.group(1)}#{match.group(3)}" {match.group(2).replace(',',' ')}>>'''
  464. else:
  465. line_output = f'''<<video "{match.group(1)}{match.group(3)}">>'''
  466. pv("IS VIDEO:",line_output)
  467. elif line.startswith('<') and line.endswith('>'):
  468. line_output = line
  469. pv("IS HTML:",line_output)
  470. elif line.startswith("'<") and line.endswith(">'"):
  471. line_output = line[1:-1]
  472. pv("IS COMMENTED HTML:",line_output)
  473. elif match := re.match(r"""^'[\w<>\s=:'"\/\.\(\),\*]+'$""",line):
  474. #Plain HTML
  475. line_output = line[1:-1]
  476. if link_match := re.findall(r"""(<a href="exec:([^"]+)">([^<]+)<\/a>)""",line_output):
  477. #line_output = #line_output.replace(link_match[0],"moep")
  478. #print("moep")
  479. #print(link_match)
  480. for lmatch in link_match:
  481. line_output = line_output.replace(lmatch[0],f"""<<link "{lmatch[2]}">>{convert_command(lmatch[1])}<</link>>""")
  482. pv("IS PLAIN HTML:",line_output)
  483. elif match := re.match(r"^\s*(if|while)\s+([^:]+):(.*)",line,re.I):
  484. command = match.group(1).lower()
  485. line_w = f'<<{command} {convert_condition(match.group(2))}>>'
  486. if match.group(3):
  487. #if com := convert_command(match.group(3)):
  488. # line_w += '\n' + (whitespace_count+1) * '\t' + com
  489. #else:
  490. # line_w += '\n' + (whitespace_count+1) * '\t' + convert_literal(match.group(3))
  491. converted = convert_lineblock([match.group(3)])
  492. if len(converted)>0 and converted[0]:
  493. line_w += '\n' + (whitespace_count+1) * '\t' + converted[0]
  494. line_w += '\n' + whitespace_count * '\t'+f'<</{command}>>'
  495. else:
  496. nesting.append(command)
  497. #file.write(line_w)
  498. line_output = line_w
  499. pv("IS IF:",line_output)
  500. elif match := re.match(r"\s*(act)\s*(.+):(.*)",line,re.I):
  501. # Act-Command
  502. command = match.group(1).lower()
  503. line_w = f'<<{command} {convert_literal(match.group(2))}>>'
  504. if match.group(3):
  505. line_w += '\n' + (whitespace_count+1) * '\t'+convert_command(match.group(3))
  506. line_w += '\n' + whitespace_count * '\t'+f'<</{command}>>'
  507. else:
  508. nesting.append(command)
  509. #file.write(line_w)
  510. line_output = line_w
  511. pv("IS ACT:",line_output)
  512. elif match := re.match(r"\s*(elseif)\s+([^:]+):(.*)",line,re.I):
  513. # ElseIf
  514. command = match.group(1).lower()
  515. line_w = f'<<{command} {convert_condition(match.group(2))}>>'
  516. whitespace_count -= 1
  517. if match.group(3):
  518. #line_w += '\n' + (whitespace_count+1) * '\t'+convert_command(match.group(3))
  519. line_w += '\n' + whitespace_count * '\t'+f'<</if>>'
  520. #nesting.pop()
  521. #file.write(line_w)
  522. line_output = line_w
  523. pv("IS ELSEIF:",line_output)
  524. #elif match := re.match(r"^dynamic\s+'(.*)'$",line,re.I):
  525. # out = match.group(1).replace('<<',"'+").replace('>>',"+'")
  526. # line_output = f"<<dynamic {out}>>"
  527. elif match := re.match(r"^dynamic '\$?(.*?)\s*([\+\-]?=)\s*(.*?)\s*'$",line,re.I):
  528. left = match.group(1)
  529. right = match.group(3)
  530. operator = match.group(2)
  531. left = left.replace(r"[''",r"['").replace(r"'']",r"']")
  532. left = left.replace(r"['+",r"[").replace(r"+']",r"]")
  533. left = left.replace('<<',"'+").replace('>>',"+'")
  534. left = left.replace('$$',"$")
  535. right = right.replace(r"[''",r"['").replace(r"'']",r"']")
  536. right = right.replace(r"['+",r"[").replace(r"+']",r"]")
  537. right = right.replace('<<',"").replace('>>',"")
  538. right = right.replace('$$',"$")
  539. right = convert_literal(right)
  540. line_output = f'<<set {left} {operator} {right}>>'
  541. pv("IS DYNAMIC:",line_output)
  542. #elif match := re.match(r"^dynamic '\$?(.*?)\s*([\+\-]?=)\s*(.*?)\s*'$",line,re.I):
  543. elif match := re.match(r"^dynamic\s*\$([a-zA-Z]\w+)$",line,re.I):
  544. line_output = f'<<{match.group(1)}>>'
  545. elif match := re.match(r"""^([^\$])*<a\s+href\s*=\s*"exec:\s*(?:minut\s*\+=\s*(\d+)\s*&\s*)?gt(.*)?"\s*>(.*?)</a>.*$""",line,re.I):
  546. while link_match := re.search(r"""<a\s+href\s*=\s*"exec:\s*(?:minut\s*\+=\s*(\d+)\s*&\s*)?gt(.*)?"\s*>(.*?)</a>""",line,re.I):
  547. full_match = link_match.group(0)
  548. time = ""
  549. if link_match.group(1):
  550. time = f"<<set $minut += {link_match.group(1)}>>"
  551. goto = link_match.group(2)
  552. goto = goto.replace(","," ").replace(r"''",r"'")
  553. label = link_match.group(3)
  554. link = f"<<link '{label}'>>{time}<<gt {goto}>><</link>>"
  555. line = line.replace(full_match,link)
  556. line_output = line
  557. elif match := convert_command(line):
  558. line_output = match
  559. pv("IS COMMAND:",line_output)
  560. else:
  561. line_output = convert_literal(line)
  562. if len(line_output) >= 2 and line_output[0] == '\'' and line_output[-1] == '\'':
  563. line_output = f'<p>{line_output[1:-1]}</p>'
  564. pv("IS LITERAL:",line_output)
  565. whitespace = whitespace_count * '\t'
  566. output = f'{whitespace}{line_output}\n'
  567. if output.strip():
  568. #file.write(cleanUpTheMess(output))
  569. output = cleanUpTheMess(output)
  570. if "ERROR:" in output:
  571. global error_counter
  572. output = f'{whitespace}<!-- FAILED TO CONVERT\n{whitespace}\t{original}\n{whitespace}-----\n\t{output}\n{whitespace}-->\n{whitespace}<<warn "CONVERSION ERROR {(hashlib.md5(original.encode())).hexdigest()}">>\n'
  573. error_counter += 1
  574. outputs.append(output)
  575. for subpassId in subpassages:
  576. subpass = subpassages[subpassId]
  577. subpassageLines = convert_lineblock(subpass)
  578. outputs.append(f'\n:: {subpassId}\n')
  579. for subpassageLine in subpassageLines:
  580. outputs.append(subpassageLine)
  581. if len(functionlines) > 0:
  582. #outputs.append(f'::{location_identifier}_widgets[widget]\n')
  583. for functionline in functionlines:
  584. functionline = functionline.replace('$ARGS','_args').replace('$location_var[$here][','_args[')
  585. outputs.append(functionline)
  586. return outputs
  587. def convert_file(filename,skipIfNotExplicit=0,defaultsubfolder=False):
  588. skip = skipIfNotExplicit
  589. qsp_filename = filename+".qsrc"
  590. qsp_filepath = os.path.join(qsp_sources_path,qsp_filename)
  591. tw_filename = filename+".tw"
  592. tw_filepath = os.path.join(tw_sources_path,tw_filename)
  593. if defaultsubfolder:
  594. os.makedirs(os.path.join(tw_sources_path,defaultsubfolder),exist_ok =True)
  595. tw_filepath = os.path.join(tw_sources_path,defaultsubfolder,tw_filename)
  596. try:
  597. with open(qsp_filepath) as file:
  598. lines = [line.rstrip() for line in file]
  599. except:
  600. try:
  601. with open(qsp_filepath, encoding="utf-8") as file:
  602. lines = [line.rstrip() for line in file]
  603. except:
  604. return f"FAILED: {qsp_filename}"
  605. location_identifier = ''
  606. ignore_recusions = 0
  607. if match := re.match(r"^\s*!!\s*(FOLDER\s*:\s*\w+)?\s*(SKIP\s*:\s*-?\d)?\s*(IGNORERECURSIONS\s*:\s*-?\d)?\s*$",lines[0],re.I):
  608. if match.group(1):
  609. parts = match.group(1).split(':')
  610. new_path = os.path.join(tw_sources_path,parts[1].strip())
  611. os.makedirs(new_path,exist_ok =True)
  612. tw_filepath = os.path.join(new_path,tw_filename)
  613. if match.group(2):
  614. parts = match.group(2).split(':')
  615. arg = int(parts[1])
  616. if arg == 1:
  617. skip = 1
  618. elif arg == 0:
  619. skip = 0
  620. elif arg == -1:
  621. skip = -1
  622. if match.group(3):
  623. parts = match.group(3).split(':')
  624. arg = int(parts[1])
  625. if arg == 1:
  626. ignore_recusions = 1
  627. elif arg == 0:
  628. ignore_recusions = 0
  629. if skip == 1:
  630. return
  631. if skip == -1 and os.path.exists(tw_filepath):
  632. modification_time_delta = os.path.getmtime(qsp_filepath) - os.path.getmtime(tw_filepath)
  633. if modification_time_delta <= 0:
  634. return
  635. identifier_line = 0
  636. for line_num in range(0,len(lines)-1):
  637. line_raw = lines[line_num]
  638. line = line_raw.strip()
  639. match = re.match(r"#\s*(\S+)", line)
  640. if match:
  641. location_identifier = match.group(1)
  642. identifier_line = line_num
  643. break
  644. with open(tw_filepath, 'w') as file:
  645. #file.write(f'<!-- GENERATED: {datetime.datetime.now()} -->\n')
  646. file.write(f':: {location_identifier}\n')
  647. file.write(f"<<set $here = '{location_identifier}'>>\n<<set $ARGS = $location_var[$here]>>\n")
  648. if ignore_recusions == 1:
  649. file.write(f'<<set _ts to Math.floor(Date.now() / 10000)>>\n')
  650. file.write(f'<<setinit $gt_history[_ts][$here] = 0>>\n')
  651. #for line_num in range(identifier_line+1,len(lines)-1):
  652. outputs = convert_lineblock(lines[identifier_line+1:],location_identifier)
  653. for output in outputs:
  654. file.write(output)
  655. with open(tw_filepath, 'r') as file:
  656. data = file.read()
  657. with open(tw_filepath, 'w') as file:
  658. regex1 = r"""<<gs 'willpower' ([\s'\w]*)>>\s*<<if \$will_cost <= \$pc\.pcs_willpwr>>\s*<<act '([\w\s]*?)\s*\(will_cost Willpower\)'>>"""
  659. while match := re.search(regex1,data,re.I):
  660. blockStart = match.end()
  661. regex_close = r"""<<else>>\s*<<act `?'"""+match.group(2)+r""".*?<</act>>\s*<</if>>"""
  662. if close_match := re.search(regex_close,data,re.I):
  663. blockEnd = close_match.start()
  664. block = data[blockStart:blockEnd]
  665. # Remove the re-calculation of the willpower-cost
  666. newBlock = block
  667. newBlock = newBlock.replace("<<gs 'willpower' "+match.group(1)+">>",'')
  668. newBlock = re.sub(r"""<<gs 'willpower' 'pay' ([\s'\w]*)>>""","",newBlock)
  669. data = data.replace(block,newBlock)
  670. data = data.replace(close_match.group(0),"")
  671. arguments = match.group(1).replace(' ',',')
  672. data = data.replace(match.group(0),"<<act '"+match.group(2)+"' undefined `{willpower:["+arguments+"]}`>>")
  673. else:
  674. print("FAIL: "+match.group(0))
  675. break
  676. data = data.replace('<<act ','<<actCLA ')
  677. data = data.replace('<</act>>','<</actCLA>>')
  678. file.write(data)
  679. with open(tw_filepath, 'r') as file:
  680. data = file.read()
  681. regex_split = r"""::\s*SPLIT:(\w+)"""
  682. while match := re.search(regex_split,data,re.I):
  683. identifier = match.group(1)
  684. regex_split_end = r"""<!-- END: SPLIT:"""+identifier+r"""\s*-->"""
  685. if end_match := re.search(regex_split_end,data,re.I):
  686. sub_filepath = os.path.join(new_path,identifier+'.tw')
  687. subdata = data[match.start():end_match.end()]
  688. subdata = subdata.replace("SPLIT:"+identifier,identifier,1)
  689. with open(sub_filepath, 'w') as subfile:
  690. subfile.write(subdata)
  691. data = data[:match.start()]+data[end_match.end():]
  692. data = data.replace("SPLIT:"+identifier,identifier,1)
  693. with open(tw_filepath, 'w') as file:
  694. file.write(data)
  695. return tw_filepath
  696. FTCL = [r'ERROR: FAILED TO CONVERT LITERAL:\s*"""',r'"""']
  697. VAR = r"""\$?([a-zA-Z][a-zA-Z0-9-_\[\]'"]+]*)"""
  698. preparations = [
  699. [
  700. r"""\$week\[""",
  701. r"$week_name["
  702. ],
  703. [
  704. r"""pcs_pubecol\[""",
  705. r"pcs_pubecol_num["
  706. ],
  707. [
  708. r"""pcs_pubes\[""",
  709. r"pcs_pubes_num["
  710. ],
  711. [
  712. r"""^PLAY\s*.*""",
  713. r""
  714. ],
  715. [
  716. r"""^\s*pl\s+(.*)$""",
  717. r"\1"
  718. ]
  719. #[
  720. # r"""(</?(?:table|center|th|tr|td))([^>]*=[^>]*)(>)""",
  721. # r'\1\3',
  722. # re.I
  723. #]
  724. ]
  725. skill_names = [
  726. [r"\$pcs_heels","highHeels"],
  727. [r"\$pcs_stren","strength"],
  728. [r"\$pcs_agil","agility"],
  729. [r"\$pcs_intel","intelligence"],
  730. [r"\$pcs_react","reaction"],
  731. [r"\$pcs_sprt","spirit"],
  732. [r"\$pcs_chrsm","charisma"],
  733. [r"\$pcs_prcptn","perception"],
  734. [r"\$pcs_humint","people"],
  735. [r"\$pcs_persuas","persuasion"],
  736. [r"\$pcs_observ","observation"],
  737. [r"\$pcs_jab","jabs"],
  738. [r"\$pcs_punch","punch"],
  739. [r"\$pcs_kick","kick"],
  740. [r"\$pcs_def","defense"],
  741. [r"\$pcs_run","run"],
  742. [r"\$pcs_vball","volleyball"],
  743. [r"\$pcs_ftbll","football"],
  744. [r"\$pcs_wrstlng","wrestling"],
  745. [r"\$pcs_shoot","shoot"],
  746. [r"\$pcs_bushcraft","bushcraft"],
  747. [r"\$pcs_chess","chess"],
  748. [r"\$pcs_icesktng","iceskating"],
  749. [r"\$pcs_gaming","gaming"],
  750. [r"\$pcs_makupskl","makeup"],
  751. [r"\$pcs_danc","dance"],
  752. [r"\$pcs_dancero","eroticdance"],
  753. [r"\$pcs_dancpol","poledance"],
  754. [r"\$pcs_cheer","cheerleading"],
  755. [r"\$pcs_mdlng","modelling"],
  756. [r"\$pcs_vokal","singing"],
  757. [r"\$pcs_instrmusic","playInstrument"],
  758. [r"\$pcs_photoskl","photo"],
  759. [r"\$pcs_artskls","art"],
  760. [r"\$pcs_compskl","computer"],
  761. [r"\$pcs_comphckng","hacking"],
  762. [r"\$pcs_hndiwrk","handyWork"],
  763. [r"\$pcs_sewng","sewing"],
  764. [r"\$pcs_servng","serving"],
  765. [r"\$pcs_medcn","medicine"],
  766. ]
  767. replaces = [
  768. [
  769. r"ERROR: FAILED TO CONVERT CONDITION: func\(",
  770. r"func("
  771. ],
  772. [
  773. r"ERROR: FAILED TO CONVERT CONDITION: \$?([a-zA-Z])",
  774. r"$\1"
  775. ],
  776. [
  777. FTCL[0]+r"killvar\s*'"+VAR+r"'"+FTCL[1],
  778. r"<<set $\1 to undefined>>"
  779. ],
  780. [
  781. r"""<img\s+(<<\$set_imgh>>)?\s*src="([^<^\.]*)(<<\$?([a-zA-Z][a-zA-Z0-9-_\[\]'"\)\(),\s]+]*)>>)?(\.[^"]+)">""",
  782. r"<<image `'\2\3\5'`>>"
  783. ],
  784. [
  785. r"""'([\w\/]+)<<\s*rand\s*\(\s*(\-?\d+)\s*,\s*(\-?\d+)\s*\)\s*>>([^']*)'""",
  786. r"""'\1'+rand(\2,\3)+'\4'"""
  787. ],
  788. [
  789. r"""<<set \$?([a-zA-Z][a-zA-Z0-9-_'"]+]*\[.*)>>""",
  790. r"""<<setinit $\1>>"""
  791. ],
  792. [
  793. # <<set $gopnikbandQW += -1>> -> <<setn $gopnikbandQW += -1>>
  794. r"""<<set (\$[^>]*?)\s([+-]=)\s*(-?\d+)>>""",
  795. r"""<<setn \1 \2 \3>>""",
  796. 1
  797. ],
  798. [
  799. # asd
  800. r"""<<set (\$[^>]*?)\s(\+=)\s*(["'][^>]*?)>>""",
  801. r"""<<sets \1 \2 \3>>""",
  802. 1
  803. ],
  804. [
  805. r"""(\+)\s+=""",
  806. r"""\1="""
  807. ],
  808. [
  809. r"(I|you|You|he|He|she|She|it|It|we|We|they|They|can|Can|don|Don)''(m|re|s|ll|ve|t)",
  810. r"\1'\2"
  811. ],
  812. #[
  813. # r"^(.*"+FTCL[0]+r"(.*)"+FTCL[1]+r".*)$",
  814. # r"<!-- \1 -->\n<<warn 'FTCL: \1'>>"
  815. #],
  816. [
  817. r"=\s*\$(mid|MID)\s*\(",
  818. r"= mid("
  819. ],
  820. [
  821. r"(<<set\s*.*?\[)([a-zA-Z].*?)(\]\s*=.*>>)",
  822. r"\1$\2\3"
  823. ],
  824. [
  825. r"(<<act\s*'.*)(\$.*?\])(.*'>>)",
  826. r"\1'+\2+'\3"
  827. ],
  828. [
  829. r"\[([a-zA-Z]\w*)\]",
  830. r"[$\1]"
  831. ],
  832. [
  833. r"([\+\-])\s+=",
  834. r"\1="
  835. ],
  836. [
  837. r"<<setinit\s*(.*)\[\]\s*=\s*(.*)>>",
  838. r"""<<setinitpush "\1" \2>>"""
  839. ],
  840. [
  841. r"\s+min\(",
  842. r" Math.min("
  843. ],
  844. [
  845. r"\s+max\(",
  846. r" Math.max("
  847. ],
  848. [
  849. r"""<<set (.*) to null>>\s*,\s*(.*)(\s*)""",
  850. r"<<set \1[\2] to null>>\3"
  851. ]
  852. ,
  853. [
  854. r"""\$arrsize\(""",
  855. r"arrsize("
  856. ],
  857. [
  858. r"""<<set(?:init)?\s+\$?(?P<name>\w+)\[arrsize\('\$?(?P=name)'\)\]\s*=\s*(.*)\s*>>""",
  859. r"<<run $\1.push(\2)>>"
  860. ],
  861. [
  862. r"""<center><(?:h\d|b)><font color="maroon">(.*)</font></(?:h\d|b)></center>""",
  863. r"<h2>\1</h2>"
  864. ],
  865. [
  866. r"""(<<act '[^']*)'([^']*'>>)""",
  867. r"\1`\2"
  868. ],
  869. # NPC-Stuff Start
  870. [
  871. r"""\$npc_(\w*?)\[([^\]]*?)\]""",
  872. r"$npcs.get(\2,'\1')",
  873. 1
  874. ],
  875. # Fix for Sub-Arrays
  876. [
  877. r"""\$npcs\.get\((.*?),('\w*')\)(\[[^\]]*\]+?)\]""",
  878. r"$npcs.get(\1]\3,\2)",
  879. 1
  880. ],
  881. [
  882. r"""<<set(?:init)?\s+\$npcs\.get\((.*?)\)\s*=\s*(.*?)>>""",
  883. r"<<run $npcs.set(\1,\2)>>",
  884. 1
  885. ],
  886. [
  887. r"""<<set(?:init)?\s+\$npcs\.get\((.*?)\)\s*\+=\s*(.*?)>>""",
  888. r"<<run $npcs.inc(\1,\2)>>",
  889. 1
  890. ],
  891. [
  892. r"""<<set(?:init)?\s+\$npcs\.get\((.*?)\)\s*-=\s*(.*?)>>""",
  893. r"<<run $npcs.dec(\1,\2)>>",
  894. 1
  895. ],
  896. # NPC-Stuff END
  897. [
  898. r"""(\$\w+(?:\['\w+'\])?)\s*(==|>=?|<=?|!=)\s*(\-?\d+)""",
  899. r"""getvar("\1") \2 \3""",
  900. 1
  901. ],
  902. [
  903. #Example: $property_construction_status[$i] == 0 -> getvar("$property_construction_status["+$i+"]") == 0
  904. r"""(\$\w+)(?:\[(\$\w+)\])\s*(==|>=?|<=?|!=)\s*(\-?\d+)""",
  905. r"""getvar("\1["+\2+"]") \3 \4""",
  906. 1
  907. ],
  908. [
  909. r"""\*?\s*\$\s*cl[ar]\s*$""",
  910. r""
  911. ],
  912. [
  913. r"""<<gs 'clothing' 'wear'\s*(.*?)\s+(.*?)>>""",
  914. r"<<run $wardrobe.wear_clothes_legacy('clothes',\1,\2)>>"
  915. ],
  916. [
  917. r"""<<gs 'shoes' 'wear'\s+(.*?)\s+(.*?)>>""",
  918. r"<<run $wardrobe.wear('shoes',\1,\2)>>"
  919. ],
  920. [
  921. r"""<<gs\s+'shoes'\s+'wear'\s+'last_worn'\s*>>""",
  922. r"<<run $wardrobe.wear_last('shoes')>>"
  923. ],
  924. [
  925. r"""<<gs\s+'bras'\s+'wear'\s+(.+?)\s+(.+?)\s*>>""",
  926. r"<<run $wardrobe.wear('bra',\1,\2)>>"
  927. ],
  928. [
  929. r"""<<gs\s+'panties'\s+'wear'\s+(.+?)\s+(.+?)\s*>>""",
  930. r"<<run $wardrobe.wear('panties',\1,\2)>>"
  931. ],
  932. [
  933. r"""<<gs\s+'coats'\s+'wear'\s+(.+?)\s+(.+?)\s*>>""",
  934. r"<<run $wardrobe.wear('coat',\1,\2)>>"
  935. ],
  936. [
  937. r"""<<gs\s+'bras'\s+'wear'\s*>>""",
  938. r"<<run $wardrobe.wear_last('bra')>>"
  939. ],
  940. [
  941. r"""<<gs\s+'panties'\s+'wear'\s*>>""",
  942. r"<<run $wardrobe.wear_last('panties')>>"
  943. ],
  944. [
  945. r"""iif\(([^)]*?)\s*==?\s*'',""",
  946. r"iif(!\1,",
  947. 1
  948. ],
  949. # Rand in gs Fix
  950. [
  951. r"""<<g([st].*?)\srand\((.*?)\)(.*?)>>""",
  952. r"<<g\1 `rand(\2)`\3>>",
  953. 1
  954. ],
  955. # Pain
  956. [
  957. r"""(<<(?:else)?if\s+|and\s+|x?or\s+)(?:getvar\(")\$pain\[('\w+')\](?:"\))(.*?>>)""",
  958. r"\1$pc.pain(\2)\3",
  959. 1
  960. ],
  961. [
  962. r"""<<set(?:init)?\s+\$pain\[('\w+')\]\s*\+=\s*(.*?)>>""",
  963. r"<<run $pc.painInc(\1,\2)>>",
  964. 1
  965. ],
  966. [
  967. r"""<<set(?:init)?\s+\$pain\[('\w+')\]\s*-=\s*(.*?)>>""",
  968. r"<<run $pc.painDec(\1,\2)>>",
  969. 1
  970. ],
  971. [
  972. r"""<<set(?:init)?\s+\$pain\[('\w+')\]\s*=\s*(.*?)>>""",
  973. r"<<run $pc.painSet(\1,\2)>>",
  974. 1
  975. ],
  976. #Cum
  977. [
  978. r"""\$cumloc\[(\d+)\]""",
  979. r"$pc.cumAtLocation(\1)",
  980. 1
  981. ],
  982. # Inner Thought
  983. [
  984. r"""(?:'?\s*\+\s*)?\$OpenInnerThought\s*\+\s*'(.*?)'\s*\+\s*\$CloseInnerThought(?:\s*\+\s*'?)?""",
  985. r"""<span class="innerThought">\1</span>""",
  986. 1
  987. ],
  988. # Group Membership
  989. [r'(?:getvar\(")?\$grupTipe(?:"\))?\s*==\s*1',r"$q.school.func('isGroupMember','cool')",1],
  990. [r'(?:getvar\(")?\$grupTipe(?:"\))?\s*==\s*2',r"$q.school.func('isGroupMember','jocks')",1],
  991. [r'(?:getvar\(")?\$grupTipe(?:"\))?\s*==\s*3',r"$q.school.func('isGroupMember','nerds')",1],
  992. [r'(?:getvar\(")?\$grupTipe(?:"\))?\s*==\s*4',r"$q.school.func('isGroupMember','gopniks')",1],
  993. [r'(?:getvar\(")?\$grupTipe(?:"\))?\s*==\s*5',r"$q.school.func('isGroupMember','outcasts')",1],
  994. [r'(?:getvar\(")?\$grupTipe(?:"\))?\s*==\s*6',r"$q.school.func('isGroupMember','teachers')",1],
  995. [r'<<set(?:init)?\s+\$grupTipe(?:"\))?\s*=\s*1>>',r"<<run $q.school.func('setGroupMembership','cool')>>",1],
  996. [r'<<set(?:init)?\s+\$grupTipe(?:"\))?\s*=\s*2>>',r"<<run $q.school.func('setGroupMembership','jocks')>>",1],
  997. [r'<<set(?:init)?\s+\$grupTipe(?:"\))?\s*=\s*3>>',r"<<run $q.school.func('setGroupMembership','nerds')>>",1],
  998. [r'<<set(?:init)?\s+\$grupTipe(?:"\))?\s*=\s*4>>',r"<<run $q.school.func('setGroupMembership','gopniks')>>",1],
  999. [r'<<set(?:init)?\s+\$grupTipe(?:"\))?\s*=\s*5>>',r"<<run $q.school.func('setGroupMembership','outcasts')>>",1],
  1000. [r'<<set(?:init)?\s+\$grupTipe(?:"\))?\s*=\s*6>>',r"<<run $q.school.func('setGroupMembership','teachers')>>",1],
  1001. ]
  1002. purge_messes=[
  1003. r"""<<set(init)? \$npc_selfie\[""",
  1004. r'''<<set(init)? \$npcGo\[''', # We need to replace this by another function,
  1005. r'''<<set(init)? \$npcGoSchool\['''
  1006. ]
  1007. def cleanUpTheMess(output):
  1008. for purge_mess in purge_messes:
  1009. if match := re.search(purge_mess,output):
  1010. return ''
  1011. for skill_name in skill_names:
  1012. oldSN = skill_name[0]
  1013. newSN = skill_name[1]
  1014. oldSN_without_prefix = oldSN.split('_')[1]
  1015. output = re.sub(r"<<set(?:init)?\s+"+oldSN+r"\s*=\s*(.*?)\s*>>",r"<<run $pc.skillSetLevel('"+newSN+r"',\1)>>",output)
  1016. output = re.sub(r"<<gs\s+'exp_gain'\s+('"+oldSN_without_prefix+r"')\s+`?(.*?)`?>>",r"<<run $pc.skillExperienceGain('"+newSN+r"',\2)>>",output)
  1017. output = re.sub(oldSN,'$pc.skillLevel("'+newSN+'")',output)
  1018. for replace in replaces:
  1019. if len(replace) > 2:
  1020. if replace[2] == 1:
  1021. while(re.search(replace[0],output)):
  1022. output = re.sub(replace[0],replace[1],output)
  1023. else:
  1024. output = re.sub(replace[0],replace[1],output)
  1025. if warnmatch := re.search(r"""<<warn '(.*)'>>""",output):
  1026. return output.replace(warnmatch.group(1),warnmatch.group(1).replace("'",'"'))
  1027. if link_match := re.findall(r"""(<a href="exec:([^"]+)">([^<]+)<\/a>)""",output):
  1028. for lmatch in link_match:
  1029. output = output.replace(lmatch[0],f"""<<link "{lmatch[2]}">>{convert_command(lmatch[1])}<</link>>""")
  1030. output = re.sub(r"""\$result""","$result",output,0,re.I)
  1031. while image_match := re.match(r"""<img\s+(<<\$set_imgh>>)?\s*src="([^<^\.]*)(<<\$?([a-zA-Z][a-zA-Z0-9-_\[\]'"]+]*)>>)?\.[^"]+">""",output):
  1032. if len(image_match.group(3)) == 0:
  1033. break
  1034. output = output.replace(image_match.group(3),f'"+${image_match.group(4)}+"')
  1035. while match := re.search(r"""<<set(?:init)?[^=]+=\s*'([a-zA-Z0-9\.\?!<>"\s,`\-\(\)]+)('([a-zA-Z0-9\.\?!<>"\s,`\-\(\)]+))+'>>""",output):
  1036. output = output.replace(match.group(2),f"`{match.group(3)}")
  1037. # NPCs: add print to all get-calls which are not inside a macro
  1038. if(not output.strip().startswith('<<')):
  1039. output = re.sub(r"(?<!=)(\$npcs\.get\(.*?\))",r"<<=\1>>",output)
  1040. # Arousal
  1041. while match := re.search(r"<<gs 'arousal' '(\w+)' (.*?)(\s.*?)?>>",output):
  1042. if match.group(3):
  1043. arguments = "["+match.group(3).replace("' '","','").strip()+"]"
  1044. else:
  1045. arguments = ''
  1046. output = output.replace(match.group(0),"<<arouse '"+match.group(1)+"' "+match.group(2)+" "+arguments+">>")
  1047. for variable_replacement in variables.variable_replacements:
  1048. if len(variable_replacement) > 2:
  1049. if variable_replacement[2] == 1:
  1050. output = re.sub(variable_replacement[0],variable_replacement[1],output)
  1051. else:
  1052. output = output.replace(variable_replacement[0],variable_replacement[1])
  1053. else:
  1054. output = output.replace(variable_replacement[0],variable_replacement[1])
  1055. for get_set_variable in variables.get_set_variables:
  1056. output = re.sub(rf"<<set(?:init)?\s+{get_set_variable[0]}\s*=\s*(.*?)\s*>>",rf"<<run {get_set_variable[2]}>>",output)
  1057. if(len(get_set_variable) == 5):
  1058. output = re.sub(rf"<<set(?:init)?\s+{get_set_variable[0]}\s*\+=\s*(.*?)\s*>>",rf"<<run {get_set_variable[3]}>>",output)
  1059. output = re.sub(rf"<<set(?:init)?\s+{get_set_variable[0]}\s*\-=\s*(.*?)\s*>>",rf"<<run {get_set_variable[4]}>>",output)
  1060. #output = re.sub(rf"<<set(?:init)?\s+\${get_set_variable[0]}\s*-=\s*(.*?)\s*>>",rf"<<run $inventory.dec('{inventory_variable[1]}',\1)>>",output)
  1061. #output = re.sub(rf"<<set(?:init)?\s+\${get_set_variable[0]}\s*\+=\s*(.*?)\s*>>",rf"<<run $inventory.inc('{inventory_variable[1]}',\1)>>",output)
  1062. output = re.sub(rf"<<{get_set_variable[0]}>>",get_set_variable[1],output)
  1063. output = re.sub(rf"""getvar\("{get_set_variable[0]}"\)""",get_set_variable[1],output)
  1064. output = re.sub(rf"""{get_set_variable[0]}(?P<stuffToTheRight>[^\w])""",rf"""{get_set_variable[1]}\g<stuffToTheRight>""",output)
  1065. for pgsvr in variables.post_get_set_variables_replacements:
  1066. output = output.replace(pgsvr[0],pgsvr[1])
  1067. output = output.replace("$location_var[$here][0] == ''","!$location_var[$here][0]")
  1068. return output
  1069. test_line = ''
  1070. #test_line = """gs 'npc_relationship', 'socialgroup_setting', 0, 0, -10, 10, -10, -10"""
  1071. if len(test_line) > 0:
  1072. verbose = True
  1073. print(test_line)
  1074. result = convert_lineblock([test_line])
  1075. if len(result) > 0:
  1076. print(result[0])
  1077. else:
  1078. print("EMPTY RESULT")
  1079. exit()
  1080. qsp_sources_path = "locations"
  1081. tw_sources_path = os.path.join("sugarcube","src","autogenerated")
  1082. output_files = []
  1083. os.makedirs(tw_sources_path, exist_ok=True)
  1084. #for replace in replaces:
  1085. # print(replace[0])
  1086. restrictfiles = []
  1087. #restrictfiles = ['gschool_gopnik_chats']
  1088. files = os.listdir(qsp_sources_path)
  1089. file_counter = 0
  1090. last_displayed_percentage_time = time.time()
  1091. for file in files:
  1092. if len(restrictfiles) == 0 or (os.path.splitext(file)[0] in restrictfiles):
  1093. if file.endswith(".qsrc"):
  1094. filesToDo.append(os.path.splitext(file)[0])
  1095. #output_files.append(convert_file(os.path.splitext(file)[0],skipMode,'unsorted'))
  1096. with ThreadPoolExecutor(32) as executor:
  1097. # submit all tasks
  1098. futures = [executor.submit(convert_file, p, skipMode, 'unsorted') for p in filesToDo]
  1099. # process all results
  1100. for future in as_completed(futures):
  1101. # open the file and load the data
  1102. completedPath = future.result()
  1103. # report progress
  1104. #print(f'.loaded {filepath}')
  1105. file_counter += 1
  1106. if(last_displayed_percentage_time + 5 < time.time()):
  1107. print(str(round(file_counter/len(files)*100, 2))+"%")
  1108. last_displayed_percentage_time = time.time()
  1109. #for output_file in output_files:
  1110. # for line in fileinput.input(output_file, inplace=True):
  1111. #
  1112. # for function_name_conversion in function_name_conversions:
  1113. #
  1114. #
  1115. # if fileinput.filelineno() == 10:
  1116. # print(('10'+line), end='')
  1117. # break