lua_resource.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (c) 2012-2016 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. #include "string_stream.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
  28. {
  29. void compile(const char* path, CompileOptions& opts)
  30. {
  31. using namespace string_stream;
  32. TempAllocator1024 ta;
  33. DynamicString luasrc(ta);
  34. DynamicString luabin(ta);
  35. opts.get_absolute_path(path, luasrc);
  36. opts.get_absolute_path("luabin.tmp", luabin);
  37. StringStream args(ta);
  38. args << " " << LUAJIT_FLAGS;
  39. args << " " << luasrc.c_str();
  40. args << " " << luabin.c_str();
  41. StringStream output(ta);
  42. int exitcode = os::execute_process(LUAJIT_EXE, c_str(args), output);
  43. RESOURCE_COMPILER_ASSERT(exitcode == 0
  44. , opts
  45. , "Failed to compile lua:\n%s"
  46. , c_str(output)
  47. );
  48. Buffer blob = opts.read_temporary(luabin.c_str());
  49. opts.delete_file(luabin.c_str());
  50. LuaResource lr;
  51. lr.version = RESOURCE_VERSION_SCRIPT;
  52. lr.size = array::size(blob);
  53. opts.write(lr.version);
  54. opts.write(lr.size);
  55. opts.write(blob);
  56. }
  57. void* load(File& file, Allocator& a)
  58. {
  59. const u32 file_size = file.size();
  60. void* res = a.allocate(file_size);
  61. file.read(res, file_size);
  62. CE_ASSERT(*(u32*)res == RESOURCE_VERSION_SCRIPT, "Wrong version");
  63. return res;
  64. }
  65. void unload(Allocator& allocator, void* resource)
  66. {
  67. allocator.deallocate(resource);
  68. }
  69. const char* program(const LuaResource* lr)
  70. {
  71. return (char*)&lr[1];
  72. }
  73. } // namespace lua_resource
  74. } // namespace crown