ProgramResource.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (C) 2014, Panagiotis Christopoulos Charitos.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include "anki/resource/ProgramResource.h"
  6. #include "anki/resource/ProgramPrePreprocessor.h"
  7. #include "anki/resource/ResourceManager.h"
  8. #include "anki/core/App.h" // To get cache dir
  9. #include "anki/util/File.h"
  10. #include "anki/util/Exception.h"
  11. #include <cstring>
  12. namespace anki {
  13. //==============================================================================
  14. void ProgramResource::load(const char* filename, ResourceInitializer& init)
  15. {
  16. load(filename, "");
  17. }
  18. //==============================================================================
  19. void ProgramResource::load(const char* filename, const char* extraSrc)
  20. {
  21. ProgramPrePreprocessor pars(filename);
  22. std::string source = extraSrc + pars.getShaderSource();
  23. GlDevice& gl = GlDeviceSingleton::get();
  24. GlCommandBufferHandle jobs(&gl);
  25. GlClientBufferHandle glsource(jobs, source.length() + 1, nullptr);
  26. strcpy((char*)glsource.getBaseAddress(), &source[0]);
  27. m_prog = GlProgramHandle(jobs,
  28. computeGlShaderType((U)pars.getShaderType()), glsource);
  29. jobs.flush();
  30. }
  31. //==============================================================================
  32. String ProgramResource::createSourceToCache(
  33. const char* filename, const char* preAppendedSrcCode,
  34. const char* filenamePrefix, App& app)
  35. {
  36. ANKI_ASSERT(filename && preAppendedSrcCode && filenamePrefix);
  37. auto& alloc = app.getAllocator();
  38. if(std::strlen(preAppendedSrcCode) < 1)
  39. {
  40. return String(filename, alloc);
  41. }
  42. // Create suffix
  43. std::hash<String> stringHasher;
  44. PtrSize h = stringHasher(String(filename, alloc) + preAppendedSrcCode);
  45. String suffix(alloc);
  46. toString(h, suffix);
  47. // Compose cached filename
  48. String newFilename(app.getCachePath()
  49. + "/" + filenamePrefix + suffix + ".glsl";
  50. if(File::fileExists(newFilename.c_str()))
  51. {
  52. return newFilename;
  53. }
  54. // Read file and append code
  55. String src(alloc);
  56. File(ResourceManagerSingleton::get().fixResourcePath(filename).c_str(),
  57. File::OpenFlag::READ).readAllText(src);
  58. src = preAppendedSrcCode + src;
  59. // Write cached file
  60. File f(newFilename.c_str(), File::OpenFlag::WRITE);
  61. f.writeText("%s\n", src.c_str());
  62. return newFilename;
  63. }
  64. } // end namespace anki