cargo.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. -- cargo v0.1.1
  2. -- https://github.com/bjornbytes/cargo
  3. -- MIT License
  4. local cargo = {}
  5. local function merge(target, source, ...)
  6. if not target or not source then return target end
  7. for k, v in pairs(source) do target[k] = v end
  8. return merge(target, ...)
  9. end
  10. local la, lf, lg = love.audio, love.filesystem, love.graphics
  11. local function makeSound(path)
  12. local info = lf.getInfo(path, 'file')
  13. return la.newSource(path, (info and info.size and info.size < 5e5) and 'static' or 'stream')
  14. end
  15. local function makeFont(path)
  16. return function(size)
  17. return lg.newFont(path, size)
  18. end
  19. end
  20. local function loadFile(path)
  21. return lf.load(path)()
  22. end
  23. cargo.loaders = {
  24. lua = lf and loadFile,
  25. png = lg and lg.newImage,
  26. jpg = lg and lg.newImage,
  27. dds = lg and lg.newImage,
  28. ogv = lg and lg.newVideo,
  29. glsl = lg and lg.newShader,
  30. mp3 = la and makeSound,
  31. ogg = la and makeSound,
  32. wav = la and makeSound,
  33. flac = la and makeSound,
  34. txt = lf and lf.read,
  35. ttf = lg and makeFont,
  36. otf = lg and makeFont,
  37. fnt = lg and lg.newFont
  38. }
  39. cargo.processors = {}
  40. function cargo.init(config)
  41. if type(config) == 'string' then
  42. config = { dir = config }
  43. end
  44. local loaders = merge({}, cargo.loaders, config.loaders)
  45. local processors = merge({}, cargo.processors, config.processors)
  46. local init
  47. local function halp(t, k)
  48. local path = (t._path .. '/' .. k):gsub('^/+', '')
  49. local fileInfo = lf.getInfo(path, 'directory')
  50. if fileInfo then
  51. rawset(t, k, init(path))
  52. return t[k]
  53. else
  54. for extension, loader in pairs(loaders) do
  55. local file = path .. '.' .. extension
  56. local fileInfo = lf.getInfo(file)
  57. if loader and fileInfo then
  58. local asset = loader(file)
  59. rawset(t, k, asset)
  60. for pattern, processor in pairs(processors) do
  61. if file:match(pattern) then
  62. processor(asset, file, t)
  63. end
  64. end
  65. return asset
  66. end
  67. end
  68. end
  69. return rawget(t, k)
  70. end
  71. local function __call(t, recurse)
  72. for i, f in ipairs(love.filesystem.getDirectoryItems(t._path)) do
  73. local key = f:gsub('%..-$', '')
  74. halp(t, key)
  75. if recurse and love.filesystem.getInfo(t._path .. '/' .. f, 'directory') then
  76. t[key](recurse)
  77. end
  78. end
  79. return t
  80. end
  81. init = function(path)
  82. return setmetatable({ _path = path }, { __index = halp, __call = __call })
  83. end
  84. return init(config.dir)
  85. end
  86. return cargo