lua_resource.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. #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 alloc;
  33. DynamicString res_abs_path(alloc);
  34. TempAllocator1024 alloc2;
  35. DynamicString bc_abs_path(alloc2);
  36. opts.get_absolute_path(path, res_abs_path);
  37. opts.get_absolute_path("bc.tmp", bc_abs_path);
  38. TempAllocator1024 ta;
  39. StringStream args(ta);
  40. args << " " << LUAJIT_FLAGS;
  41. args << " " << res_abs_path.c_str();
  42. args << " " << bc_abs_path.c_str();
  43. StringStream output(ta);
  44. int exitcode = os::execute_process(LUAJIT_EXE, c_str(args), output);
  45. CE_ASSERT(exitcode == 0, "Failed to compile lua:\n%s", c_str(output));
  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 = SCRIPT_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 uint32_t file_size = file.size();
  58. void* res = a.allocate(file_size);
  59. file.read(res, file_size);
  60. CE_ASSERT(*(uint32_t*)res == SCRIPT_VERSION, "Wrong version");
  61. return res;
  62. }
  63. void unload(Allocator& allocator, void* resource)
  64. {
  65. allocator.deallocate(resource);
  66. }
  67. uint32_t size(const LuaResource* lr)
  68. {
  69. return lr->size;
  70. }
  71. const char* program(const LuaResource* lr)
  72. {
  73. return (char*)lr + sizeof(LuaResource);
  74. }
  75. } // namespace lua_resource
  76. } // namespace crown