conv_lvs.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # Desc: 将用到的关卡文件压缩成程序使用的protobuf格式
  2. # Date: 2017-04-18
  3. import os
  4. import sys
  5. import json
  6. import levelData_pb2
  7. def read_json(file_path):
  8. with open(file_path, 'r') as file:
  9. return json.load(file)
  10. def write_json(data, file_path):
  11. with open(file_path, 'w+') as file:
  12. json.dump(data, file, indent=4)
  13. # 将 ../conf/levelInstInfo.csv 里面的每一个实例的模板名加上“tf_”前缀
  14. def add_prefix_to_inst_name():
  15. with open('../conf/levelInstInfo.csv', 'r') as f:
  16. hdr_done = False
  17. with open('../conf/levelInstInfo_new.csv', 'w+') as f_new:
  18. for line in f.readlines():
  19. if line.startswith('#'):
  20. f_new.write(line)
  21. continue
  22. if not hdr_done:
  23. f_new.write(line)
  24. hdr_done = True
  25. continue
  26. line = line.split(',')
  27. if line[1].startswith('tf_'):
  28. f_new.write(line)
  29. continue
  30. line[1] = 'tf_' + line[1]
  31. f_new.write(','.join(line))
  32. # 解析 ../conf/levelInstInfo.csv 文件,得到所有被用到的模板列表
  33. def parse_level_inst_info():
  34. temp_list = set()
  35. with open('../conf/levelInstInfo.csv', 'r') as f:
  36. # 跳过第一行
  37. f.readline()
  38. for line in f.readlines():
  39. if line.startswith('#'):
  40. continue
  41. temp_list.add(line.split(',')[1])
  42. return temp_list
  43. # 将某个tiled的json文件转换成protobuf格式
  44. def conver_json_to_proto(tDir, tFileName, outDir):
  45. global lvFileInfo, lvInfo
  46. jsonFile = os.path.join(tDir, tFileName + '.json')
  47. with open(jsonFile, 'r') as f:#, encoding='utf-8'
  48. jsonData = json.load(f)
  49. levelData = levelData_pb2.LevelData()
  50. levelData.tileWidth = jsonData['width']
  51. levelData.tileHeight = jsonData['height']
  52. cntUndefined = 0
  53. tilesByPos = {}
  54. maxZ = 0
  55. maxX = 0
  56. maxY = 0
  57. # 首先得到stacked的坐标数据
  58. stacked_map = {}
  59. for item in jsonData['layers']:
  60. name = item['name']
  61. if name == 'Marks':
  62. data = item['data']
  63. for i in range(0, len(data)):
  64. if data[i] == 0:
  65. continue
  66. x = (int)(i % levelData.tileWidth)
  67. y = (int)(i / (int)(levelData.tileWidth))
  68. stacked_map[(x, y)] = 0
  69. # 处理各层的tile数据
  70. cntTiles = 0
  71. for item in jsonData['layers']:
  72. name = item['name']
  73. if not name.startswith('Tile_'):
  74. # stacked
  75. continue
  76. z = int(name[5:])
  77. data = item['data']
  78. for i in range(0, len(data)):
  79. if data[i] == 0:
  80. continue
  81. tile = levelData.tiles.add()
  82. tile.x = (int)(i % levelData.tileWidth)
  83. tile.y = (int)(i / (int)(levelData.tileWidth))
  84. tile.z = z
  85. if (tile.x, tile.y) in stacked_map:
  86. stacked_map[(x, y)] += 1
  87. tiledata = tile.tileData
  88. tiledata.zv = 0
  89. tiledata.weight = 0
  90. tiledata.id = data[i]
  91. if tiledata.id == -10:
  92. cntUndefined += 1
  93. tiledata.type = 1
  94. tiledata.subtype = 0
  95. # 一些统计信息
  96. tilesByPos[(tile.x, tile.y, tile.z)] = tile
  97. if tile.z > maxZ:
  98. maxZ = tile.z
  99. if tile.x > maxX:
  100. maxX = tile.x
  101. if tile.y > maxY:
  102. maxY = tile.y
  103. cntTiles += 1
  104. if cntTiles%3 != 0:
  105. print('Error: tile count is not a multiple of 3: %d' % (cntTiles,))
  106. exit(1)
  107. # 根据上面的布局信息,计算每个tile的几个信息:
  108. # 1. 每个tile的视觉层级(不同于上面z的信息,那是一个布局信息,相同的z可能出在不同的视觉层级)
  109. # 从maxZ开始,逐层向下计算;对于每一个位置,如果该位置有tile,则计算该tile的视觉层级
  110. # 对于每一个tile,如果其上方(从该tile的z+1层,一直到maxZ层)有tile,则其视觉层级为上方tile的视觉层级+1
  111. for z in range(0, maxZ+1):
  112. z = maxZ - z
  113. for x in range(0, maxX+1):
  114. for y in range(0, maxY+1):
  115. if (x,y,z) in tilesByPos:
  116. tile = tilesByPos[(x, y, z)]
  117. adjs = [(x,y),(x,y+1),(x,y-1),(x+1,y),(x+1,y+1),(x+1,y-1),(x-1,y),(x-1,y-1),(x-1,y+1)]
  118. # 确定视觉层级
  119. zvMax = -1
  120. for zup in range(z+1, maxZ+1):
  121. for adj in adjs:
  122. if (adj[0],adj[1],zup) in tilesByPos:
  123. zv = tilesByPos[adj[0],adj[1],zup].tileData.zv
  124. if zv > zvMax:
  125. zvMax = zv
  126. tile.tileData.zv = zvMax + 1
  127. # 计算权重
  128. # 从最底下开始,逐层向上计算
  129. # 每个tile的初始权重为4,然后加上其下方压住的tile的权重:如果压了全部,则该加上被压住的tile权重;
  130. # 如果压住了一半,则加上被压住的tile权重的一半;如果是压住1/4,则加上被压住的tile权重的1/4
  131. for z in range(0, maxZ+1):
  132. for x in range(0, maxX+1):
  133. for y in range(0, maxY+1):
  134. if (x,y,z) in tilesByPos:
  135. tile = tilesByPos[(x,y,z)]
  136. adjs = [(x,y,1.0),(x,y+1,0.5),(x,y-1,0.5),(x+1,y,0.5),(x+1,y+1,0.25),(x+1,y-1,0.25),(x-1,y,0.5),(x-1,y-1,0.25),(x-1,y+1,0.25)]
  137. weight = 4
  138. for adj in adjs:
  139. # 从临近层往下,在某个位置找到了tile,则该tile被压住了,就不再找了
  140. for zb in range(0, z):
  141. zb = z-1-zb
  142. if (adj[0], adj[1], zb) in tilesByPos:
  143. tileB = tilesByPos[(adj[0], adj[1], zb)]
  144. weight += tileB.tileData.weight * adj[2]
  145. break
  146. tile.tileData.weight = int(weight)
  147. pass
  148. for item in stacked_map:
  149. stack_data = levelData.stacks.add()
  150. stack_data.x = int(item[0])
  151. stack_data.y = int(item[1])
  152. stack_data.direction = 0 # 先默认都是0
  153. # 数据序列化
  154. level_protobuf_data = levelData.SerializeToString()
  155. protoFile = os.path.join(outDir, tFileName + '.bin')
  156. with open(protoFile, 'w+b') as f:
  157. f.write(level_protobuf_data)
  158. def gen_index_and_data(binDir, group = None):
  159. lvelsIndex = levelData_pb2.LevelsIndex()
  160. if group is not None:
  161. protoDataTrunk = os.path.join(binDir, 'levels-' + str(group) + '.bin')
  162. protoDataIndex = os.path.join(binDir, 'levelsIndex-' + str(group) + '.bin')
  163. else:
  164. protoDataTrunk = os.path.join(binDir, 'levels' + '.bin')
  165. protoDataIndex = os.path.join(binDir, 'levelsIndex' + '.bin')
  166. offset = 0
  167. for filename in os.listdir(binDir):
  168. my_message = levelData_pb2.LevelData()
  169. binFile = os.path.splitext(filename)[0] + '.bin'
  170. binFile = os.path.join(binDir, binFile)
  171. if os.path.exists(binFile) :
  172. # print(binFile)
  173. with open(binFile, "rb") as f:
  174. binary_data = f.read()
  175. my_message.ParseFromString(binary_data)
  176. os.remove(binFile)
  177. with open(protoDataTrunk, 'ab') as f:
  178. f.write(binary_data)
  179. lvelsIndex.LevelsIndex[os.path.splitext(filename)[0]].len = len(binary_data)
  180. lvelsIndex.LevelsIndex[os.path.splitext(filename)[0]].offset = offset
  181. offset += len(binary_data)
  182. level_protobuf_index = lvelsIndex.SerializePartialToString()
  183. with open(protoDataIndex, 'w+b') as f:
  184. f.write(level_protobuf_index)
  185. # 将所有的模板文件转换成protobuf格式
  186. def convert_all_templates():
  187. # 清空loadable目录
  188. for root, dirs, files in os.walk('../loadable'):
  189. for name in files:
  190. os.remove(os.path.join(root, name))
  191. temp_list = parse_level_inst_info()
  192. dirs = ['../tf_templates', '../miniGame']
  193. for temp_name in temp_list:
  194. print(f"Converting template {temp_name}")
  195. # 判断正确的目录
  196. for d in dirs:
  197. if os.path.exists(os.path.join(d, temp_name + '.json')):
  198. conver_json_to_proto(d, temp_name, '../loadable')
  199. break
  200. gen_index_and_data('../loadable')
  201. # 获取当前工作目录
  202. current_dir = os.getcwd()
  203. script_dir = os.path.dirname(os.path.abspath(__file__))
  204. os.chdir(script_dir)
  205. convert_all_templates()
  206. # 恢复当前工作目录
  207. os.chdir(current_dir)