lua_resource.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "array.h"
  6. #include "compile_options.h"
  7. #include "config.h"
  8. #include "dynamic_string.h"
  9. #include "lua_resource.h"
  10. #include "os.h"
  11. #include "string_stream.h"
  12. #include "temp_allocator.h"
  13. #define LUAJIT_NAME "./luajit"
  14. #if CROWN_PLATFORM_WINDOWS
  15. #define EXE ".exe"
  16. #else
  17. #define EXE ""
  18. #endif // CROWN_PLATFORM_WINDOWS
  19. #define LUAJIT_EXE LUAJIT_NAME EXE
  20. #if CROWN_DEBUG
  21. #define LUAJIT_FLAGS "-bg" // Keep debug info
  22. #else
  23. #define LUAJIT_FLAGS "-b"
  24. #endif // CROWN_DEBUG
  25. namespace crown
  26. {
  27. namespace lua_resource_internal
  28. {
  29. void compile(const char* path, CompileOptions& opts)
  30. {
  31. TempAllocator1024 ta;
  32. DynamicString luasrc(ta);
  33. DynamicString luabin(ta);
  34. opts.get_absolute_path(path, luasrc);
  35. opts.get_temporary_path("lua.bin", luabin);
  36. StringStream args(ta);
  37. args << " " << LUAJIT_FLAGS;
  38. args << " " << luasrc.c_str();
  39. args << " " << luabin.c_str();
  40. StringStream output(ta);
  41. int exitcode = os::execute_process(LUAJIT_EXE, string_stream::c_str(args), output);
  42. RESOURCE_COMPILER_ASSERT(exitcode == 0
  43. , opts
  44. , "Failed to compile lua:\n%s"
  45. , string_stream::c_str(output)
  46. );
  47. Buffer blob = opts.read_temporary(luabin.c_str());
  48. opts.delete_file(luabin.c_str());
  49. LuaResource lr;
  50. lr.version = RESOURCE_VERSION_SCRIPT;
  51. lr.size = array::size(blob);
  52. opts.write(lr.version);
  53. opts.write(lr.size);
  54. opts.write(blob);
  55. }
  56. void* load(File& file, Allocator& a)
  57. {
  58. const u32 file_size = file.size();
  59. void* res = a.allocate(file_size);
  60. file.read(res, file_size);
  61. CE_ASSERT(*(u32*)res == RESOURCE_VERSION_SCRIPT, "Wrong version");
  62. return res;
  63. }
  64. void unload(Allocator& allocator, void* resource)
  65. {
  66. allocator.deallocate(resource);
  67. }
  68. } // namespace lua_resource_internal
  69. namespace lua_resource
  70. {
  71. const char* program(const LuaResource* lr)
  72. {
  73. return (char*)&lr[1];
  74. }
  75. } // namespace lua_resource
  76. } // namespace crown