cargo.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. local cargo = {}
  2. local function merge(target, source, ...)
  3. if not target or not source then return target end
  4. for k, v in pairs(source) do target[k] = v end
  5. return merge(target, ...)
  6. end
  7. local la, lf, lg = love.audio, love.filesystem, love.graphics
  8. local function makeFont(path)
  9. return function(size)
  10. return lg.newFont(path, size)
  11. end
  12. end
  13. local function loadFile(path)
  14. return lf.load(path)()
  15. end
  16. cargo.loaders = {
  17. lua = lf and loadFile,
  18. png = lg and lg.newImage,
  19. jpg = lg and lg.newImage,
  20. dds = lg and lg.newImage,
  21. glsl = lg and lg.newShader,
  22. mp3 = la and la.newSource,
  23. ogg = la and la.newSource,
  24. wav = la and la.newSource,
  25. txt = lf and lf.read,
  26. ttf = lg and makeFont
  27. }
  28. cargo.processors = {}
  29. function cargo.init(config)
  30. if type(config) == 'string' then
  31. config = {dir = config}
  32. end
  33. local loaders = merge({}, cargo.loaders, config.loaders)
  34. local processors = merge({}, cargo.processors, config.processors)
  35. local init
  36. local function halp(t, k)
  37. local path = (t._path .. '/' .. k):gsub('^/+', '')
  38. if lf.isDirectory(path) then
  39. rawset(t, k, init(path))
  40. return t[k]
  41. else
  42. for extension, loader in pairs(loaders) do
  43. local file = path .. '.' .. extension
  44. if loader and lf.exists(file) then
  45. local asset = loader(file)
  46. rawset(t, k, asset)
  47. for pattern, processor in pairs(processors) do
  48. if file:match(pattern) then
  49. processor(asset, file, t)
  50. end
  51. end
  52. return asset
  53. end
  54. end
  55. end
  56. return rawget(t, k)
  57. end
  58. init = function(path)
  59. return setmetatable({_path = path}, {__index = halp})
  60. end
  61. return init(config.dir)
  62. end
  63. return cargo