lua_resource.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2012-2014 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "config.h"
  6. #include "dynamic_string.h"
  7. #include "filesystem.h"
  8. #include "log.h"
  9. #include "lua_resource.h"
  10. #include "os.h"
  11. #include "temp_allocator.h"
  12. #include "array.h"
  13. #include "compile_options.h"
  14. #if defined(CROWN_DEBUG)
  15. #define LUAJIT_FLAGS "-bg" // Keep debug info
  16. #else
  17. #define LUAJIT_FLAGS "-b"
  18. #endif
  19. namespace crown
  20. {
  21. namespace lua_resource
  22. {
  23. void compile(const char* path, CompileOptions& opts)
  24. {
  25. static const uint32_t VERSION = 1;
  26. TempAllocator1024 alloc;
  27. DynamicString res_abs_path(alloc);
  28. TempAllocator1024 alloc2;
  29. DynamicString bc_abs_path(alloc2);
  30. opts.get_absolute_path(path, res_abs_path);
  31. opts.get_absolute_path("bc.tmp", bc_abs_path);
  32. const char* luajit[] =
  33. {
  34. #if CROWN_PLATFORM_LINUX
  35. "./luajit",
  36. #else
  37. "luajit.exe",
  38. #endif // CROWN_PLATFORM_LINUX
  39. LUAJIT_FLAGS,
  40. res_abs_path.c_str(),
  41. bc_abs_path.c_str(),
  42. NULL
  43. };
  44. int exitcode = os::execute_process(luajit);
  45. CE_ASSERT(exitcode == 0, "Failed to compile lua");
  46. Buffer blob = opts.read(bc_abs_path.c_str());
  47. opts.delete_file(bc_abs_path.c_str());
  48. LuaResource lr;
  49. lr.version = VERSION;
  50. lr.size = array::size(blob);
  51. opts.write(lr.version);
  52. opts.write(lr.size);
  53. opts.write(blob);
  54. }
  55. void* load(File& file, Allocator& a)
  56. {
  57. const size_t file_size = file.size();
  58. void* res = a.allocate(file_size);
  59. file.read(res, file_size);
  60. return res;
  61. }
  62. void online(StringId64 /*id*/, ResourceManager& /*rm*/)
  63. {
  64. }
  65. void offline(StringId64 /*id*/, ResourceManager& /*rm*/)
  66. {
  67. }
  68. void unload(Allocator& allocator, void* resource)
  69. {
  70. allocator.deallocate(resource);
  71. }
  72. uint32_t size(const LuaResource* lr)
  73. {
  74. return lr->size;
  75. }
  76. const char* program(const LuaResource* lr)
  77. {
  78. return (char*)lr + sizeof(LuaResource);
  79. }
  80. } // namespace lua_resource
  81. } // namespace crown