lua_resource.cpp 1.9 KB

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