sprite-packer.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. require_relative 'common'
  2. options = get_options(__FILE__)
  3. sprite_path = options['sprite_path']
  4. csv_path = options['generate_config_path']
  5. atlas_path = options['generate_atlas_path']
  6. padding = options['padding_size']
  7. recreate_dir atlas_path
  8. ensure_dir csv_path
  9. # $ gem install chunky_png
  10. # $ gem install binpack
  11. require 'chunky_png'
  12. require 'binpack'
  13. require 'csv'
  14. Point = Struct.new(:x, :y)
  15. Box = Struct.new(:top_left, :bottom_right)
  16. csv_atlas = CSV.open("#{csv_path}/atlas.csv", 'wb')
  17. csv_atlas << ['Id', 'Path']
  18. csv_atlas << ['', '']
  19. csv_atlas << [':id', ':path']
  20. csv_sprite = CSV.open("#{csv_path}/sprite.csv", 'wb')
  21. csv_sprite << ['Id', 'AtlasId', 'X', 'Y']
  22. csv_sprite << ['', '', '', '']
  23. csv_sprite << [':id', '@atlas', ':int', ':int']
  24. Dir["#{sprite_path}/*"].each do |path|
  25. atlas_name = convert_case(File::basename(path))
  26. next unless File::directory?(path)
  27. atlas_size = 1024
  28. sprites = Dir["#{path}/*"].collect do |file|
  29. sprite = ChunkyPNG::Image.from_file(file)
  30. sprite.define_singleton_method :file do
  31. return file
  32. end
  33. sprite
  34. end
  35. items = sprites.collect { |sprite| Binpack::Item.new(sprite, sprite.width, sprite.height) }
  36. bins = Binpack::Bin.pack(items, [], Binpack::Bin.new(atlas_size, atlas_size, padding))
  37. bins.each do |bin|
  38. atlas = ChunkyPNG::Image.new(atlas_size, atlas_size, ChunkyPNG::Color::TRANSPARENT)
  39. bin.items.each do |item|
  40. unit, x, y = *item
  41. atlas.compose!(unit.obj, x, y)
  42. csv_sprite << [convert_case(File.basename(unit.obj.file, '.png')), atlas_name, x, y]
  43. end
  44. atlas_path = "#{atlas_path}/#{File::basename(path)}.png"
  45. atlas.save atlas_path
  46. csv_atlas << [atlas_name, File.basename(atlas_path)]
  47. end
  48. end