conv_lvs.py 8.9 KB

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