process_atlas.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. from PIL import Image
  2. from xml.dom import minidom
  3. import os
  4. import atlas
  5. import process
  6. def as_int(attr, df = 0):
  7. if not attr:
  8. return df
  9. return int(attr)
  10. def as_bool(attr):
  11. if not attr:
  12. return False
  13. lw = attr.lower()
  14. return lw == "true" or lw == "1"
  15. def fixImage(image):
  16. if image.mode != "RGBA":
  17. return image
  18. data = image.load()
  19. for y in xrange(image.size[1]):
  20. for x in xrange(image.size[0]):
  21. a = data[x,y][3]
  22. #if a == 0 or a == 1:
  23. if a == 0:
  24. data[x, y] = (0,0,0,0)
  25. return image
  26. def premultipliedAlpha(image):
  27. if image.mode != "RGBA":
  28. return image
  29. data = image.load()
  30. for y in xrange(image.size[1]):
  31. for x in xrange(image.size[0]):
  32. dt = data[x,y]
  33. a = dt[3]
  34. data[x, y] = ((dt[0] * a) / 255, (dt[1] * a) / 255, (dt[2] * a) / 255, a)
  35. return image
  36. class frame:
  37. def __init__(self, image, bbox, image_element, rs):
  38. self.image = image
  39. self.image_element = image_element
  40. self.node = None
  41. self.resanim = rs
  42. self.border_top = self.border_left = 0
  43. self.border_right = self.border_bottom = 1
  44. if not bbox:
  45. bbox = (0,0,1,1)
  46. self.bbox = bbox
  47. class ResAnim:
  48. def __init__(self):
  49. self.frames = []
  50. self.name = ""
  51. self.frame_size = (1, 1)
  52. self.frame_scale = 1.0
  53. self.columns = 0
  54. self.rows = 0
  55. def frame_cmp_sort(f1, f2):
  56. return f2.image.size[0] - f1.image.size[0]
  57. def applyScale(intVal, scale):
  58. return int(intVal * scale + 0.5)
  59. def applyScale2(x, scale):
  60. initialX = x
  61. best = None
  62. while 1:
  63. X = x * scale
  64. d = abs(X - int(X))
  65. if not best:
  66. best = (d, X)
  67. if best[0] > d:
  68. best = (d, X)
  69. eps = 0.00000001
  70. if d < eps:
  71. return int(X)
  72. if x > initialX * 2:
  73. return int(best[1])
  74. x += 1
  75. def nextPOT(v):
  76. v = v - 1;
  77. v = v | (v >> 1);
  78. v = v | (v >> 2);
  79. v = v | (v >> 4);
  80. v = v | (v >> 8);
  81. v = v | (v >>16);
  82. return v + 1
  83. class settings:
  84. def __init__(self):
  85. self.get_size = None
  86. self.set_node = None
  87. self.padding = 1
  88. self.max_w = 2048
  89. self.max_h = 2048
  90. self.atlasses = []
  91. self.square = False
  92. def pack(st, frames, sw, sh):
  93. atl = atlas.Atlas(st.padding, sw, sh)
  94. not_packed = []
  95. for fr in frames:
  96. ns = st.get_size(fr)
  97. node = atl.add(ns[0], ns[1], fr)
  98. if not node:
  99. not_packed.append(fr)
  100. else:
  101. st.set_node(fr, node)
  102. #atl.add(250, 250)
  103. #atl.save()
  104. return not_packed, atl
  105. def get_pow2list(mn, mx):
  106. ls = []
  107. mn = nextPOT(mn)
  108. mx = nextPOT(mx)
  109. while 1:
  110. ls.append(mn)
  111. mn *= 2
  112. if mn > mx:
  113. break
  114. return ls
  115. def pck(st, frames):
  116. if 0:
  117. st = settings()
  118. while frames:
  119. sq = 0
  120. min_w = 64
  121. min_h = 64
  122. for f in frames:
  123. size = st.get_size(f)
  124. sq += size[0] * size[1]
  125. min_w = max(min_w, size[0])
  126. min_h = max(min_h, size[1])
  127. sizes_w = get_pow2list(min_w, st.max_w)
  128. sizes_h = get_pow2list(min_h, st.max_h)
  129. for sw in sizes_w:
  130. for sh in sizes_h:
  131. end = sh == sizes_h[-1] and sw == sizes_w[-1]
  132. if st.square and sw != sh:
  133. continue
  134. if sw * sh < sq and not end:
  135. continue
  136. not_packed, bn = pack(st, frames, sw, sh)
  137. st.atlasses.append(bn)
  138. if not not_packed:
  139. return
  140. if end:
  141. frames = not_packed
  142. else:
  143. st.atlasses.pop()
  144. class atlas_Processor(process.Process):
  145. node_id = "atlas"
  146. def __init__(self):
  147. self.atlas_group_id = 0
  148. def process(self, context, el):
  149. self.atlas_group_id += 1
  150. meta = context.add_meta()
  151. anims = []
  152. frames = []
  153. for image_el in el.childNodes:
  154. if image_el.nodeName == "set":
  155. context._process_set(image_el)
  156. if image_el.nodeName != "image":
  157. continue
  158. image_name = image_el.getAttribute("file")
  159. if not image_name:
  160. continue
  161. #print image_path
  162. image = None
  163. #fn = self._getExistsFile(image_path)
  164. #virtual_width = 1
  165. #virtual_height = 1
  166. path = context.get_current_src_path(image_name)
  167. try:
  168. image = Image.open(path)
  169. except IOError:
  170. pass
  171. if image:
  172. # virtual_width = int(image.size[0] * scale + 0.001)
  173. # virtual_height= int(image.size[1] * scale + 0.001)
  174. pass
  175. else:
  176. context.error("can't find image:\n%s\n" % (path, ))
  177. image = Image.new("RGBA", (0, 0))
  178. resAnim = ResAnim()
  179. resAnim.image = image
  180. resAnim.name = image_name
  181. anims.append(resAnim)
  182. columns = as_int(image_el.getAttribute("cols"))
  183. frame_width = as_int(image_el.getAttribute("frame_width"))
  184. rows = as_int(image_el.getAttribute("rows"))
  185. frame_height = as_int(image_el.getAttribute("frame_height"))
  186. border = as_int(image_el.getAttribute("border"))
  187. if not columns:
  188. columns = 1
  189. if not rows:
  190. rows = 1
  191. if frame_width:
  192. columns = image.size[0] / frame_width
  193. else:
  194. frame_width = image.size[0] / columns
  195. if frame_height:
  196. rows = image.size[1] / frame_height
  197. else:
  198. frame_height = image.size[1] / rows
  199. size_warning = False
  200. if frame_width * columns != image.size[0]:
  201. size_warning = True
  202. context.warning("image has width %d and %d columns:" % (image.size[0], columns))
  203. if frame_height * rows != image.size[1]:
  204. size_warning = True
  205. context.warning("<image has height %d and %d rows:" % (image.size[1], rows))
  206. if size_warning:
  207. context.warnings += 1
  208. scale_quality = image_el.getAttribute("scale_quality")
  209. if scale_quality:
  210. scale_quality = float(scale_quality)
  211. else:
  212. scale_quality = 1.0
  213. finalScale = context.get_apply_scale(True, scale_quality)
  214. upscale = False
  215. if finalScale > 1:
  216. if not context.args.upscale:
  217. finalScale = 1
  218. else:
  219. upscale = True
  220. resAnim.frame_scale = context.get_apply_scale(False, scale_quality)
  221. resAnim.frame_size = (applyScale(frame_width, finalScale),
  222. applyScale(frame_height, finalScale))
  223. resAnim.columns = columns
  224. resAnim.rows = rows
  225. for row in xrange(rows):
  226. for col in xrange(columns):
  227. rect = (col * frame_width, row * frame_height, (col + 1) * frame_width, (row + 1)* frame_height, )
  228. frame_image = image.crop(rect)
  229. def resize():
  230. ax = applyScale2(frame_width, finalScale);
  231. ay = applyScale2(frame_height, finalScale);
  232. bx = int(ax / finalScale)
  233. by = int(ay / finalScale)
  234. im = Image.new("RGBA", (bx, by))
  235. im.paste(frame_image, (0, 0, frame_image.size[0], frame_image.size[1]))
  236. frame_image = im.resize((ax, ay), Image.ANTIALIAS)
  237. frame_image = frame_image.crop((0, 0, resAnim.frame_size[0], resAnim.frame_size[1]))
  238. if context.args.resize:
  239. if as_bool(image_el.getAttribute("trueds")):
  240. frame_image = frame_image.resize((resAnim.frame_size[0], resAnim.frame_size[1]), Image.ANTIALIAS)
  241. else:
  242. ax = applyScale2(frame_width, finalScale);
  243. ay = applyScale2(frame_height, finalScale);
  244. bx = int(ax / finalScale)
  245. by = int(ay / finalScale)
  246. im = Image.new("RGBA", (bx, by))
  247. im.paste(frame_image, (0, 0, frame_image.size[0], frame_image.size[1]))
  248. frame_image = im.resize((ax, ay), Image.ANTIALIAS)
  249. frame_image = frame_image.crop((0,0,resAnim.frame_size[0], resAnim.frame_size[1]))
  250. trim = True
  251. if image_el.getAttribute("trim") == "0":
  252. trim = False
  253. if image.mode == "RGBA" and trim:
  254. r,g,b,a = frame_image.split()
  255. frame_bbox = a.getbbox()
  256. else:
  257. frame_bbox = frame_image.getbbox()
  258. if not frame_bbox:
  259. frame_bbox = (0,0,0,0)
  260. w = frame_bbox[2] - frame_bbox[0]
  261. h = frame_bbox[3] - frame_bbox[1]
  262. frame_image = frame_image.crop(frame_bbox)
  263. fr = frame(frame_image, frame_bbox, image_el, resAnim)
  264. if border:
  265. fr.border_left = fr.border_right = fr.border_top = fr.border_bottom = border
  266. frames.append(fr)
  267. resAnim.frames.append(fr)
  268. #sort frames by size
  269. #frames = sorted(frames, key = lambda fr: -fr.image.size[1])
  270. #frames = sorted(frames, key = lambda fr: -fr.image.size[0])
  271. frames = sorted(frames, key = lambda fr: -1 * max(fr.image.size[0], fr.image.size[1]) * max(fr.image.size[0], fr.image.size[1]))
  272. sq = 0
  273. for f in frames:
  274. sq += f.image.size[0] * f.image.size[1]
  275. compression = context.compression
  276. def get_frame_size(frame):
  277. def align_pixel(p):
  278. if not context.compression:
  279. return p + 1
  280. align = 4
  281. v = p % align
  282. if v == 0:
  283. p += align
  284. else:
  285. p += 8 - v
  286. return p
  287. sz = frame.image.size
  288. return align_pixel(sz[0] + frame.border_left + frame.border_right), align_pixel(sz[1] + frame.border_top + frame.border_bottom)
  289. def set_node(frame, node):
  290. frame.node = node
  291. st = settings()
  292. st.get_size = get_frame_size
  293. st.set_node = set_node
  294. st.max_w = context.args.max_width
  295. st.max_h = context.args.max_height
  296. st.square = context.compression == "pvrtc"
  297. pck(st, frames)
  298. #print "done"
  299. for atlas_id, atl in enumerate(st.atlasses):
  300. image = Image.new("RGBA", (atl.w, atl.h))
  301. for node in atl.nodes:
  302. fr = node.data
  303. x = node.rect.x + fr.border_left
  304. y = node.rect.y + fr.border_top
  305. sz = fr.image.size
  306. rect = (x, y, x + sz[0], y + sz[1])
  307. image.paste(fr.image, rect)
  308. fr.atlas_id = atlas_id
  309. image_atlas_el = context.get_meta_doc().createElement("image")
  310. meta.appendChild(image_atlas_el)
  311. base_name = "%d_%d" % (self.atlas_group_id, atlas_id)
  312. ox_fmt = "r8g8b8a8"
  313. def compress(src, dest, fmt):
  314. cmd = context.helper.path_pvrtextool + " -i %s -f %s,UBN,lRGB -o %s" % (src, fmt, dest)
  315. cmd += " -l" #alpha bleed
  316. if context.args.quality == "best":
  317. cmd += " -q pvrtcbest"
  318. else:
  319. cmd += " -q pvrtcfast"
  320. if upscale or context.args.dither:
  321. cmd += " -dither"
  322. cmd += " -shh" #silent
  323. os.system(cmd)
  324. if compression == "etc1":
  325. #premultipliedAlpha(v)
  326. r, g, b, a = image.split()
  327. rgb = Image.merge("RGB", (r, g, b))
  328. alpha = Image.merge("RGB", (a,a,a))
  329. base_alpha_name = base_name + "_alpha"
  330. alpha_path = context.get_inner_dest(base_alpha_name + ".png")
  331. alpha.save(alpha_path)
  332. image_atlas_el.setAttribute("alpha", base_alpha_name + ".png")
  333. path_base = base_name + ".png"
  334. rs = ".pvr"
  335. rgb_path = context.get_inner_dest(path_base)
  336. path = context.get_inner_dest(path_base)
  337. rgb.save(path)
  338. pkm_rgb = base_name + rs
  339. pkm_alpha = base_alpha_name + rs
  340. def compress_etc1(src, dest):
  341. compress(src, dest, "etc1")
  342. #os.system(context.etc1tool + "%s -o %s -f etc1" %(src, dest))
  343. ox_fmt = "ETC1"
  344. compress_etc1(rgb_path, context.get_inner_dest() + pkm_rgb)
  345. os.remove(rgb_path)
  346. image_atlas_el.setAttribute("file", pkm_rgb)
  347. compress_etc1(alpha_path, context.get_inner_dest() + pkm_alpha)
  348. os.remove(alpha_path)
  349. image_atlas_el.setAttribute("alpha", pkm_alpha)
  350. else:
  351. if context.args.nopng:
  352. path_base = base_name + ".tga"
  353. else:
  354. path_base = base_name + ".png"
  355. path = context.get_inner_dest(path_base)
  356. image_atlas_el.setAttribute("file", path_base)
  357. image.save(path)
  358. if context.compression == "pvrtc":
  359. ox_fmt = "PVRTC_4RGBA"
  360. compress(path, context.get_inner_dest(base_name + ".pvr"), "PVRTC1_4")
  361. image_atlas_el.setAttribute("file", base_name + ".pvr")
  362. os.remove(path)
  363. image_atlas_el.setAttribute("format", ox_fmt)
  364. image_atlas_el.setAttribute("w", str(image.size[0]))
  365. image_atlas_el.setAttribute("h", str(image.size[1]))
  366. for anim in anims:
  367. if 0:
  368. anim = ResAnim()
  369. image_frames_el = context.get_meta_doc().createElement("frames")
  370. image_frames_el.setAttribute("fs", "%d,%d,%d,%d,%f" % (anim.columns, anim.rows,
  371. anim.frame_size[0], anim.frame_size[1],
  372. anim.frame_scale))
  373. meta.appendChild(image_frames_el)
  374. if context.debug:
  375. image_frames_el.setAttribute("debug_image", anim.name)
  376. data = ""
  377. for fr in anim.frames:
  378. data += "%d,%d,%d,%d,%d,%d,%d;" %(fr.atlas_id,
  379. fr.node.rect.x + fr.border_left, fr.node.rect.y + fr.border_top,
  380. fr.bbox[0], fr.bbox[1],
  381. fr.bbox[2] - fr.bbox[0], fr.bbox[3] - fr.bbox[1])
  382. text = context.get_meta_doc().createTextNode(data)
  383. image_frames_el.appendChild(text)