Guest User

ZnK Dumper v2.1

a guest
Jun 7th, 2014
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.89 KB | None | 0 0
  1. #OK guys, I "cheated" and modified the program to get the opcode positions from the .pre files
  2. #Not sure if that was a good idea or not but...
  3. import os
  4. import sys
  5. import struct
  6. import functools
  7.  
  8. facedict = {}
  9. facedict['00'] = 'Lloyd'
  10. facedict['01'] = 'Elie'
  11. facedict['02'] = 'Tio'
  12. facedict['03'] = 'Randy'
  13. facedict['04'] = 'Lazy'
  14. facedict['05'] = 'Noel'
  15. facedict['06'] = 'Dudley'
  16. facedict['07'] = 'Yin'
  17. facedict['08'] = 'Estelle'
  18. facedict['09'] = 'Joshua'
  19. facedict['10'] = 'Sergei'
  20. facedict['11'] = 'KeA'
  21. facedict['12'] = 'Zeit'
  22. facedict['13'] = 'Cecil'
  23. facedict['14'] = 'Arios'
  24. facedict['15'] = 'Sizuku'
  25. facedict['16'] = 'Wald'
  26. facedict['17'] = 'Ilya'
  27. facedict['18'] = 'Rixia'
  28. facedict['19'] = 'Fran'
  29. facedict['20'] = 'Sonya'
  30. facedict['21'] = 'Grace'
  31. facedict['22'] = 'Ian'
  32. facedict['23'] = 'Jona'
  33. facedict['24'] = 'Joachim'
  34. facedict['25'] = 'McDowell'
  35. facedict['26'] = 'Earnest'
  36. facedict['27'] = 'Hartman'
  37. facedict['28'] = 'Dieter'
  38. facedict['29'] = 'Mariabell'
  39. facedict['30'] = 'Marconi'
  40. facedict['31'] = 'Garcia'
  41. facedict['32'] = 'Cao'
  42. facedict['33'] = 'Renne'
  43. facedict['34'] = 'Kirika'
  44. facedict['35'] = 'Lector'
  45. facedict['36'] = 'Harold'
  46. facedict['37'] = 'Sophia'
  47. facedict['38'] = 'Colin'
  48. facedict['39'] = 'Jorg'
  49. facedict['50'] = 'Lloyd (Fancy)'
  50. facedict['51'] = 'Lloyd (Fancy Glasses)'
  51. facedict['52'] = 'Lloyd (Casual)'
  52. facedict['53'] = 'Elie (Fancy)'
  53. facedict['54'] = 'Special'
  54. facedict['55'] = 'Tio (Casual)'
  55. facedict['56'] = 'Randy (Fancy)'
  56. facedict['57'] = 'Lazy (Fancy)'
  57. facedict['58'] = 'KeA (Fancy)'
  58. facedict['59'] = 'Cecil (Fancy)'
  59. facedict['60'] = 'Sizuku (Fancy)'
  60. facedict['61'] = 'Ilya (Dancer)'
  61. facedict['62'] = 'Rixia (Priestess)'
  62. facedict['63'] = 'Noel (Casual)'
  63. facedict['64'] = 'Fran (Casual)'
  64. facedict['65'] = 'McDowell (PJs)'
  65. facedict['66'] = 'Earnest (Suit)'
  66. facedict['67'] = 'Joachim (Blue Hair)'
  67. facedict['68'] = 'Joachim (White Hair)'
  68.  
  69. #Grabs data. It's called by getpointers and myprogram
  70. #myprogram (couldn't think of better name) is the top level function
  71. def get_data(filename):
  72.     totalbytes = os.path.getsize(filename)
  73.     infile = open(filename, 'rb')
  74.     totalfiledata = infile.read(totalbytes)
  75.     return totalfiledata
  76.  
  77. #Takes the input string and makes a nicely formatted output string for the translators
  78. def calculateoutputstring(opcodeaddress,inputstring):
  79.     speaker = ""
  80.     outputstring = '\n' + opcodeaddress + ";" #1st field is address - write to output
  81.     opcode = inputstring[0].encode('hex') #What opcode is it?
  82.     outputstring += opcode + ';' #2nd field is opcode - write to output
  83.     n = -4
  84.     while ord(inputstring[n]) < 128: #looking for last shift-JIS character in opcode
  85.         n -= 2
  86.        
  87.     strpos = 1
  88.     while True:
  89.         if ord(inputstring[strpos]) == 35: break # Pound character is 1st
  90. # Shift-JIS character is first
  91.         if ord(inputstring[strpos]) > 127 and ord(inputstring[strpos]) < 255 and ord(inputstring[strpos+1]) > 39: break
  92.         if strpos == len(inputstring): break #Weird special case
  93.         strpos += 1
  94.     startofline = strpos #tells program where the start of the current line is
  95.  
  96.     userlength = len(inputstring)-startofline+n+2
  97.    
  98.     lastuserchar = len(inputstring)+n+1 #tells program when to stop
  99.  
  100.     startflag = True #tells program whether the first line in the opcode has been output yet or not (True = not yet)
  101.     JIScharpos = 0 #misleading name. Really the position of the last ascii character. lastasciichar was too long a name...
  102.  
  103. #Go byte by byte
  104.     while strpos <= lastuserchar + 2: #Until end of the string...
  105.         output = False #reset flag
  106. #Our byte is a SHIFT-JIS value
  107.         if int(inputstring[strpos].encode('hex'),16) > 127:
  108.             strpos += 2 #move pointer forward and check again
  109. #Our byte is an ASCII value (which is fine too)
  110.         elif int(inputstring[strpos].encode('hex'),16) > 19:
  111.             strpos += 1 #move pointer forward and check again
  112.             if inputstring[strpos] in ('P','K','F','N'): #If the character is the end of a text code then:
  113.                 JIScharpos = strpos #Set (or reset) the position of the last ascii character
  114. #Our byte at this point must be some weird Falcom text code
  115. #The 0x00 code is used in 0x5D opcodes to separate the name and what the name should say
  116.         elif inputstring[strpos].encode('hex') == '00':
  117.             if opcode == '5d': #For 5D opcodes, the speaker name is in the opcode itself
  118.                 speaker = inputstring[startofline:strpos] + ";"
  119.             strpos, startofline = strpos + 1, strpos + 1
  120.             JIScharpos = strpos
  121. #The 0x01 opcode is a line break
  122.         elif inputstring[strpos].encode('hex') == '01':
  123.             if opcode == '5e' and inputstring[strpos+1].encode('hex') == '00':
  124.                 breaktype = "terminalcode"
  125.             else:
  126.                 breaktype = "linebreak"
  127.             output = True #Tells the program to do the "output" routine on this pass through the loop
  128. #We output a line every time there is either linebreak, newdialogbox or terminalcode
  129.  
  130. #There's two codes starting with 0x02 that we know of:
  131. #0x0200 ends the opcode
  132. #0x0203 starts a new dialog box within the same opcode
  133.         elif strpos == lastuserchar + 1: #The pointer (within this program) is at the end of the opcode
  134. #I call it the "pointer" because we are looking at the actual opcode byte by byte, moving the pointer each time
  135.             output = True
  136.             breaktype = "terminalcode"
  137.            
  138.         elif inputstring[strpos].encode('hex') == '02':
  139.             output = True
  140.             if inputstring[strpos+1].encode('hex') == '03':
  141.                 breaktype = "newdialogbox"
  142.             else:
  143.                 print "Unknown opcode format in opcode %s at address %s." % (opcode,opcodeaddress)
  144.                 return ""
  145.         elif inputstring[strpos].encode('hex') == '07':
  146.             breaktype = '0x' + inputstring[strpos:strpos+2].encode('hex')
  147.             output = True
  148.         else:
  149.             print "Unknown opcode format in opcode %s at address %s." % (opcode,opcodeaddress)
  150.             return ""
  151.  
  152.         if output: #output routine
  153.  
  154.             thisline = inputstring[startofline:strpos] #Gives the string. Further processed below.
  155.             JIScharpos += 1 #That's because the value computed above is really the character _before_ the first JIS character
  156.            
  157.             if len(inputstring[startofline:JIScharpos]) > 1: #There are ASCII characters in thisline
  158.                 codes = inputstring[startofline:JIScharpos] + ";" #Grabs the codes
  159.                 speech = inputstring[JIScharpos:strpos] + ";" #Grabs the non-codes part of the line
  160.                 if codes.find('F') > -1 and opcode != '5d': #If there is an "F" code in the codes, we need the faces routine
  161.                     facecodepos = codes.find('F') #Gets face code position within the codes
  162.                     facecode1 = thisline[facecodepos-4:facecodepos-2] #First two numbers of face code (as string)
  163.                     facecode2 = thisline[facecodepos-2:facecodepos] #Last two numbers of face code (as string)
  164.                     speaker = facedict.get(facecode1,'Unknown') + ";" #You know that dictionary at the top? Go get the name based on the 1st two numbers.
  165.                     if speaker == 'Special': #What to do if the face code starts with "54"
  166.                         if int(facecode2) < 12: speaker = "Tio (Fancy);"
  167.                         else: speaker = "Zeit;"
  168.                 elif opcode != '5d': #For 5D opcodes, the speaker has already been set; we don't want to mess that up.
  169.                     speaker = ";" #For non 5D opcodes, there's no speaker on this line, so we make a blank
  170.             else: #No text codes on this line - make some blanks
  171.                 codes = ";"
  172.                 speaker = ";"
  173.                 speech = thisline + ";"
  174.  
  175.             if startflag == True: #What to do on the first pass
  176.                 outputstring += speaker + codes + speech + breaktype + ";" + str(userlength)
  177.                 startflag = False
  178.             else: #Second and later passes have a newline and don't have address or opcode, so two blanks are needed
  179.                 outputstring += "\n;;" + speaker + codes + speech + breaktype
  180.  
  181.             if breaktype == "linebreak": #Update state variables at the end, move the pointer, etc...
  182.                 strpos, startofline = strpos + 1, strpos + 1
  183.             else:
  184.                 strpos, startofline = strpos + 2, strpos + 2
  185.  
  186.             JIScharpos = strpos
  187.            
  188.     return outputstring
  189.  
  190. #Loads the *.pre file and returns the pointers from it
  191. def getpointers(filename, filename2):
  192.     filedata = get_data(filename)
  193.     opcodepos = filedata.find('\x00\xcc\xcc')-1 #I can't decode .pre headers so this'll have to do.
  194.     if opcodepos < 0:
  195.         return 'error' #if there's no dialog here then exit program entirely
  196.     opcodes = []
  197.     pointers = []
  198.     while opcodepos < len(filedata)-12: #Weird magic number here ("12")
  199. # Could use some help getting rid of this magic number
  200. # I need the program to stop before the end of the file to avoid string index out of range error
  201. # The last opcode usually doesn't point to dialog so I think this could be fine for now
  202.         opcode = []
  203.         for n in range(11):
  204.             opcode.append(filedata[opcodepos+n].encode('hex'))
  205.         opcodepos += 12 #This magic number is fine; opcodes/pointer bytes/whatever in .pre are 12 bytes long
  206.         opcodes.append(opcode)
  207.     del opcodes[-1]
  208.     for opcode in opcodes:
  209.         if [opcode[2],opcode[3]] == ['cc','cc']:
  210. # It converts the little endian value (which makes no sense) to big endian (which does make sense)
  211.             thisval = hex(struct.unpack('<I',(opcode[4] + opcode[5] + opcode[6] + opcode[7]).decode('hex'))[0])
  212.             if not thisval in pointers:
  213.                 pointers.append(thisval)
  214.     strpos = 0
  215.  
  216.     filedata = get_data(filename2)
  217.     while strpos > -1:
  218.         strpos = filedata.find('\x5e\x00\x00\xff\xff\xff\xff',strpos+1)
  219.         if strpos > 0 and hex(strpos) not in pointers:
  220.             pointers.append(hex(strpos))
  221.  
  222.     strpos = 0
  223.     while strpos > -1:
  224.         strpos = filedata.find('\x55\xff\x00',strpos+1)
  225.         if strpos > 0 and hex(strpos) not in pointers:
  226.             pointers.append(hex(strpos))
  227.        
  228.     return pointers
  229.  
  230. def myprogram(filename,filename2):
  231.     pointers = getpointers(filename2, filename) #First grab the pointers. We'll need these later.
  232.     if pointers == 'error':
  233.         print 'No dialog in this file.'
  234.         quit()
  235.  
  236.     filedata = get_data(filename)
  237.     outfiledata = filename
  238.  
  239.     for pointer in sorted(pointers,key=functools.partial(int,base=16)):
  240. # The 5C and 5D opcodes we're looking for in this program are variable length.
  241. # We have to search for their ends.
  242.         if int(pointer,16) < len(filedata):
  243.             opcode = filedata[int(pointer,16)].encode('hex')
  244.             if opcode == '5e':
  245.                 strend = filedata.find('\x01\x00',int(pointer,16)) #Find the end of the opcode
  246.             elif opcode in ('55','5c','5d'):
  247.                 strend = filedata.find('\x02\x00',int(pointer,16)) #Find the end of the opcode
  248.             else:
  249.                 print "Unknown opcode " + filedata[int(pointer,16)].encode('hex') + " at address " + pointer
  250.     # Pass the pointer address and entire opcode to a function for formatting the dump
  251.             if opcode in ('55','5c','5d','5e'):
  252.                 outputstring = calculateoutputstring(pointer,filedata[int(pointer,16):strend+2])
  253.                 outfiledata += outputstring #Append formatted string to program output
  254.         else:
  255.             print "Data at address " + pointer + " is not within the file."
  256.        
  257.     outfile = open(os.path.splitext(filename)[0] + '.data','wb')
  258.     outfile.write(outfiledata) #write the output
  259.     outfile.close
  260.        
  261. if __name__ == '__main__':
  262.  
  263. #    sys.argv=[sys.argv[0],'c0110']
  264.     myprogram(sys.argv[1] + '.orig',sys.argv[1] + '.pre')
Add Comment
Please, Sign In to add comment