lua_resource.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 "file.h"
  10. #include "lua_resource.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 output(ta);
  37. const char* argv[] =
  38. {
  39. LUAJIT_EXE,
  40. LUAJIT_FLAGS,
  41. luasrc.c_str(),
  42. luabin.c_str(),
  43. NULL
  44. };
  45. int ec = opts.run_external_compiler(argv, output);
  46. DATA_COMPILER_ASSERT(ec == 0
  47. , opts
  48. , "Failed to compile lua:\n%s"
  49. , string_stream::c_str(output)
  50. );
  51. Buffer blob = opts.read_temporary(luabin.c_str());
  52. opts.delete_file(luabin.c_str());
  53. LuaResource lr;
  54. lr.version = RESOURCE_VERSION_SCRIPT;
  55. lr.size = array::size(blob);
  56. opts.write(lr.version);
  57. opts.write(lr.size);
  58. opts.write(blob);
  59. }
  60. void* load(File& file, Allocator& a)
  61. {
  62. const u32 file_size = file.size();
  63. void* res = a.allocate(file_size);
  64. file.read(res, file_size);
  65. CE_ASSERT(*(u32*)res == RESOURCE_VERSION_SCRIPT, "Wrong version");
  66. return res;
  67. }
  68. void unload(Allocator& allocator, void* resource)
  69. {
  70. allocator.deallocate(resource);
  71. }
  72. } // namespace lua_resource_internal
  73. namespace lua_resource
  74. {
  75. const char* program(const LuaResource* lr)
  76. {
  77. return (char*)&lr[1];
  78. }
  79. } // namespace lua_resource
  80. } // namespace crown