Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 31.48 KB | None | 0 0
  1. #include "StdAfx.h"
  2.  
  3. #include "../Include/MetaShaderImpl.h"
  4.  
  5. #include "ed_log.h"
  6. #include "ed_vfs.hpp"
  7. #include "Util/Strings.h"
  8.  
  9. #include "renderer/BinderFactory.h"
  10. #include "renderer/ShadingModelFactory.h"
  11. #include "renderer/IShaderManager.h"
  12.  
  13. #include "../Include/MetaShaderManager.h"
  14. #include "../Include/Preprocessor.h"
  15. #include "../Include/render.h"
  16. #include "../Include/MetaShaderCache.h"
  17.  
  18. #include <Windows.h>
  19.  
  20. #ifndef EDGE
  21. #define SHADERS_DIR "Bazar/shaders/"
  22. #else
  23. #define SHADERS_DIR "graphics/shaders/"
  24. #endif
  25.  
  26. static bool DEBUG_LOG = false;
  27.  
  28.  
  29. namespace render
  30. {
  31.  
  32. namespace
  33. {
  34.  
  35.  
  36. // для compute
  37. const int GROUPSIZE = 128;
  38.  
  39.  
  40. class MsgException : public std::exception
  41. {
  42. public:
  43.  
  44.     MsgException(const ed::string& msg)
  45.         :   msg(msg)
  46.     {
  47.     }
  48.  
  49.  
  50.     virtual ~MsgException() throw ()
  51.     {
  52.     }
  53.  
  54.  
  55.     virtual const char* what() const throw ()
  56.     {
  57.         return msg.c_str();
  58.     }
  59.  
  60. private:
  61.  
  62.     ed::string msg;
  63. };
  64.  
  65.  
  66. struct SortOccurrence
  67. {
  68. public:
  69.     MetaShaderImpl::BinderDesc *binderDesc;
  70.     const render::BindVariable *variable;
  71.     size_t pos;
  72.     size_t len;
  73.     render::VariableOccurrenceType occurrenceType;
  74.  
  75.     SortOccurrence(MetaShaderImpl::BinderDesc *a_binder_desc, const render::BindVariable* a_variable,
  76.                    size_t a_pos, size_t a_len, render::VariableOccurrenceType occurrenceType)
  77.         :   binderDesc(a_binder_desc),
  78.             variable(a_variable),
  79.             pos(a_pos),
  80.             len(a_len),
  81.             occurrenceType(occurrenceType)
  82.     {
  83.     }
  84.  
  85.     bool operator<(const SortOccurrence& other) const
  86.     {
  87.         return pos < other.pos;
  88. /*
  89.         if (pos < other.pos)
  90.             return true;
  91.         else if (pos > other.pos)
  92.             return false;
  93.         if (binderDesc < other.binderDesc)
  94.             return true;
  95.         else if (binderDesc > other.binderDesc)
  96.             return false;
  97.         return len < other.len;
  98. */
  99.     }
  100. };
  101.  
  102.  
  103. bool readFile(const ed::string& filePath, ed::string& content)
  104. {
  105.     // read content of metashader file
  106.     VFS::File file(filePath.c_str(), VFS::OpenRead);
  107.     if (!(VFS_File*)file)
  108.         return false;
  109.     size_t inputFileSize = file.getsize();
  110.     if (inputFileSize == 0)
  111.         return false;
  112.     ed::vector<char> raw_content(inputFileSize, ' ');
  113.     auto code = file.read((void*)&raw_content.front(), inputFileSize);
  114.     content = ed::string(raw_content.begin(), raw_content.end());
  115.     return code != 0;
  116. }
  117.  
  118.  
  119. uint32_t GetLastErrorCode()
  120. {
  121. #ifdef _WINDOWS
  122.     return ::GetLastError();
  123. #else
  124.     return 1;
  125. #endif
  126. }
  127.  
  128.  
  129. uint32_t writeFile(const ed::string& filePath, const ed::string& content)
  130. {
  131.     ed::string path = filePath;
  132. #if 0
  133.     //def _WINDOWS
  134.     /*
  135.      * TODO: HACK: fix this in edCore.
  136.      * On Windows if we want to handle path over MAX_PATH length (about 260 symbols), we need
  137.      * to operate with paths, that start with `\\?\` namespace:
  138.      *     instead d:\dir\file.txt use \\?\d:\dir\file.txt
  139.      */
  140.     std::replace(path.begin(), path.end(), '/', '\\');
  141.     ed::array<char, MAX_PATH + 1> currentDir;
  142.     ::GetCurrentDirectoryA(currentDir.size(), &currentDir.front());
  143.     path = ed::string() + "\\\\?\\" + currentDir.data() + "\\" + path;
  144. #endif
  145.     VFS::File outfile(path.c_str(), VFS::OpenWrite);
  146.     if (outfile.operator VFS_File *() == nullptr)
  147.         return GetLastErrorCode();
  148.     if (content.empty())
  149.         return 0;
  150.     auto written = outfile.write(&content.front(), content.size());
  151.     uint32_t errorCode = written > 0 ? 0 : 1;
  152.     if (errorCode == 1)
  153.         errorCode = GetLastErrorCode();
  154.     return errorCode;
  155. }
  156.  
  157.  
  158. const ed::string DELIMS = "\r\n";
  159. const ed::string SHARP_LINE = "#line";
  160.  
  161.  
  162. /*
  163.  * In-place replacer of lines that starts with #line. Such lines will be replaced with empty ones.
  164.  */
  165. class SharpLineReplacer
  166. {
  167. public:
  168.  
  169.     SharpLineReplacer(ed::string& content)
  170.         :   content(content),
  171.             original(content)
  172.     {
  173.     }
  174.  
  175.     /*
  176.      * Replaces all lines.
  177.      */
  178.     void replace()
  179.     {
  180.         splittedLines = ed::splitStringAndDelims(content, DELIMS);
  181.         content = "";
  182.         size_t sharpLineSize = SHARP_LINE.size();
  183.         for (size_t i = 0; i != splittedLines.size(); ++i)
  184.         {
  185.             ed::string& line = splittedLines[i].second;
  186.             if (!splittedLines[i].first) // line feeds
  187.             {
  188.                 content += line;
  189.                 continue;
  190.             }
  191.             if (line.size() < sharpLineSize)
  192.             {
  193.                 content += line;
  194.                 continue;
  195.             }
  196.             ed::string::size_type nonWhiteSpacePos = line.find_first_not_of(" \t");
  197.             if (nonWhiteSpacePos == ed::string::npos ||
  198.                 line.size() - nonWhiteSpacePos < sharpLineSize ||
  199.                 line.substr(nonWhiteSpacePos, sharpLineSize) != SHARP_LINE)
  200.             {
  201.                 content += line;
  202.             }
  203.         }
  204.     }
  205.  
  206.     /*
  207.      * Reverts to original.
  208.      */
  209.     void undo()
  210.     {
  211.         content = original;
  212.         return;
  213. #if 0
  214.         size_t goalSize = SHARP_LINE.size();
  215.         for (size_t i = 0; i != splittedLines.size(); ++i)
  216.         {
  217.             ed::string& line = splittedLines[i].second;
  218.             content += line;
  219.         }
  220. #endif
  221.     }
  222.  
  223. private:
  224.  
  225.     ed::string& content;
  226.     ed::string original;
  227.     ed::vector<std::pair<bool, ed::string>> splittedLines;
  228. };
  229.  
  230.  
  231. } // namespace
  232.  
  233. MetaShaderImpl::BinderDesc::BinderDesc()
  234. {
  235.     binder = 0;
  236.     subItem = 0;
  237. }
  238. MetaShaderImpl::BinderDesc::~BinderDesc()
  239. {
  240.     if( subItem)
  241.         delete subItem;
  242. }
  243.  
  244. ed::string MetaShaderImpl::getFolderForInterShader()
  245. {
  246.     return MetaShaderCache::instance().getInterDir();
  247. }
  248.  
  249. ed::string MetaShaderImpl::getFolderForFinalShader()
  250. {
  251.     return MetaShaderCache::instance().getFinalDir();
  252. }
  253.  
  254.  
  255. ed::string MetaShaderImpl::getDestShaderPath(const ed::string& suffix, const ed::string& ext, bool inter)
  256. {
  257.     ed::string transformModifierName = ed::extractFileNameNoExt(ed::extractFileNameNoExt(transformModifier));
  258.     ed::string name = filePath + ";" + transformModifierName + suffix;
  259.     ed::string hex = ed::md5(name.c_str(), name.length()).str();
  260.     ed::string shaderName = ed::extractFileNameNoExt(filePath);
  261.    
  262.     ed::string dir = inter ? getFolderForInterShader() : getFolderForFinalShader();
  263.     ed::string path = dir + shaderName;
  264.     if (!transformModifierName.empty())
  265.         path += "." + transformModifierName;
  266.     path += "." + hex + "."+ext;
  267.     return path;
  268. }
  269.  
  270.  
  271. MetaShaderImpl::MetaShaderImpl()
  272. {
  273. }
  274.  
  275. void MetaShaderImpl::normalizeInput(
  276.     const ed::string& aFilePath,
  277.     const ed::string& aTransformModifier,
  278.     const ed::vector<render::DefinePair>* definitions_
  279.     )
  280. {
  281.     ed::normalizePath(aFilePath, clearFilePath);
  282.     ed::normalizePath(aTransformModifier, clearTransformModifier);
  283.  
  284.     ed::string filePath;
  285.     ed::normalizePath(SHADERS_DIR + aFilePath, filePath);
  286.     ed::string transformModifier;
  287.     if (!aTransformModifier.empty())
  288.     {
  289.         ed::normalizePath(SHADERS_DIR + aTransformModifier, transformModifier);
  290.     }
  291.     const ed::vector<render::DefinePair>* definitions = nullptr;
  292.     ed::vector<render::DefinePair> definitionsCopy;
  293.     if (definitions_)
  294.     {
  295.         definitionsCopy = *definitions_;
  296.         definitions = &definitionsCopy;
  297.         MetaShaderCache::normalizeDefinitions(definitionsCopy);
  298.     }
  299.  
  300.     MetaShaderManager::instance().registerMetaShader(this, aFilePath, aTransformModifier, definitions);
  301.     // fileName
  302.     this->fileName = filePath;
  303.     this->filePath = filePath;
  304.     this->transformModifier = transformModifier;
  305.     if (definitions)
  306.     {
  307.         this->definitions = *definitions;
  308.         for(int i = 0; i < definitions->size(); i++)
  309.         {
  310.             this->fileName += "|";
  311.             const render::DefinePair& dp = (*definitions)[i];
  312.             this->fileName += dp.getName();
  313.             if(dp.getValue() && dp.getValue()[0])
  314.                 this->fileName += ed::string("=") + dp.getValue();
  315.         }
  316.     }
  317. }
  318.  
  319.  
  320. bool MetaShaderImpl::buildMetaShader(
  321.     const ed::string& aFilePath,
  322.     const ed::string& aTransformModifier,
  323.     const ed::vector<render::DefinePair>* definitions_,
  324.     const ed::string& outfx,
  325.     ed::string& cacheKey
  326.     )
  327. {
  328.     normalizeInput(aFilePath, aTransformModifier, definitions_);
  329.     cacheKey = getCacheKey(&definitions);
  330.  
  331.     ed::string shaderContent;
  332.     ed::string definitionsString = getDefinitionsString(&definitions);
  333.        
  334.     ed::vector<ed::string> errors;
  335.     ed::string msg;
  336.     bool buildFailed = false;
  337.     bool criticalError = false;
  338.     BUILD_CODE code = BC_OK;
  339.     try
  340.     {
  341.         code = buildShaderFromMetaShader(filePath, transformModifier, &definitions, shaderContent, definitionsString, errors);
  342.         if (code != BC_OK)
  343.         {
  344.             for (size_t i = 0; i != errors.size(); ++i)
  345.                 msg += errors[i] + "\n";
  346.             buildFailed = true;
  347.             if (code == BC_CRITICAL_ERROR)
  348.                 criticalError = true;
  349.         }
  350.     }
  351.     catch (const char* e)
  352.     {
  353.         msg += e;
  354.         criticalError = true;
  355.     }
  356.     catch (const ed::string& e)
  357.     {
  358.         msg += e;
  359.         criticalError = true;
  360.     }
  361.     catch(const std::exception& e)
  362.     {
  363.         msg += ed::string() + "std::exception: " + e.what();
  364.         criticalError = true;
  365.     }
  366.  
  367.     if (!msg.empty())
  368.         ED_ERROR("%s", msg.c_str());
  369.  
  370.     if (buildFailed || criticalError)
  371.         return false;
  372.  
  373.     {
  374.         VFS_mkdir(getFolderForFinalShader().c_str());
  375.         auto code = writeFile(outfx, shaderContent);
  376.         if (code != 0)
  377.             ED_ERROR("%s", "Failed to write metashader to \"" + outfx + "\", error code: " + ed::to_string(code));
  378.  
  379.         return code == 0;
  380.     }
  381. }
  382.  
  383.  
  384. bool MetaShaderImpl::open(
  385.     const ed::string& aFilePath,
  386.     const ed::string& aTransformModifier,
  387.     const ed::vector<render::DefinePair>* definitions_
  388.     )
  389. {
  390.     normalizeInput(aFilePath, aTransformModifier, definitions_);
  391.  
  392.     // для проверки валидности рендерайтемов
  393.     ed::map<ed::string, BinderDesc> prev_bindersDesc = this->bindersDesc;
  394.  
  395.     // process
  396.     auto prevCompileErrorAction = render::getCompileErrorAction();
  397.     render::setCompileErrorAction(render::CEA_RISE_EXCEPTION);
  398.     for (;;)
  399.     {
  400.         reset();
  401.         ed::string shaderContent;
  402.         ed::string definitionsString = getDefinitionsString(&definitions);
  403.        
  404.         ed::vector<ed::string> errors;
  405.         ed::string msg;
  406.         bool buildFailed = false;
  407.         bool criticalError = false;
  408.         BUILD_CODE code = BC_OK;
  409.         try
  410.         {
  411.             code = buildShaderFromMetaShader(filePath, transformModifier, &definitions, shaderContent,
  412.                                              definitionsString, errors);
  413.             if (code != BC_OK)
  414.             {
  415.                 for (size_t i = 0; i != errors.size(); ++i)
  416.                     msg += errors[i] + "\n";
  417.                 buildFailed = true;
  418.                 if (code == BC_CRITICAL_ERROR)
  419.                     criticalError = true;
  420.             }
  421.         }
  422.         catch (const char* e)
  423.         {
  424.             msg += e;
  425.             criticalError = true;
  426.         }
  427.         catch (const ed::string& e)
  428.         {
  429.             msg += e;
  430.             criticalError = true;
  431.         }
  432.         catch(const std::exception& e)
  433.         {
  434.             msg += ed::string() + "std::exception: " + e.what();
  435.             criticalError = true;
  436.         }
  437. /*
  438.         catch(...)
  439.         {
  440.             msg += "Unhandled exception";
  441.             criticalError = true;
  442.         }
  443. */
  444.         if (buildFailed || criticalError)
  445.         {
  446.             ED_ERROR("Failed build metashader: '%s' transform: '%s'", fileName.c_str(), transformModifier.c_str());
  447.             if (!msg.empty())
  448.                 ED_ERROR("    Reason: %s", msg.c_str());
  449.         }
  450.            
  451.         // Не требует показа MB
  452.         if (code == BC_REGULAR_ERROR)
  453.         {
  454.             render::setCompileErrorAction(prevCompileErrorAction);
  455.             return false;
  456.         }
  457.  
  458.         if (criticalError)
  459.         {
  460.             msg = "Cannot create shader from metashader:\n    " + filePath + ".\n    Reason: " + msg;
  461.             invalidateCachedShaders(&definitions);
  462.             if (prevCompileErrorAction == render::CEA_RISE_EXCEPTION)
  463.                 throw ed::string(msg);
  464.         #ifdef _WINDOWS
  465.             auto choice = MessageBox(0, msg.c_str(), "MetaShader - Shader Creation Error",
  466.                                         MB_RETRYCANCEL | MB_ICONQUESTION);
  467.             if (choice == IDCANCEL)
  468.             {
  469.                 render::setCompileErrorAction(prevCompileErrorAction);
  470.                 exit(0);
  471.                 return false;
  472.             }
  473.         #endif
  474.             continue;
  475.         }
  476.  
  477.         if (!compileShader(definitionsString, shaderContent, &definitions, prevCompileErrorAction))
  478.         {
  479.             invalidateCachedShaders(&definitions);
  480.             continue;
  481.         }
  482.  
  483.         for (auto it = bindersDesc.begin(); it != bindersDesc.end(); )
  484.         {
  485.             auto& binderDesc = (*it).second;
  486.             if (!binderDesc.binder->postprocessing(this, binderDesc.subItem))
  487.             {
  488.                 // discard binder
  489.                 it = bindersDesc.erase(it);
  490.             }
  491.             else
  492.             {
  493.                 ++it;
  494.             }
  495.         }
  496.         break;
  497.     }
  498.     render::setCompileErrorAction(prevCompileErrorAction);
  499.     inited = true;
  500.  
  501.     // проверить валидность уже созданных рендерайтемов
  502.     if (!prev_bindersDesc.empty())
  503.     {
  504.         ed::string text1, text2;
  505.         for (auto& it : bindersDesc)
  506.             text1 += it.first + ", ";
  507.         for (auto& it : prev_bindersDesc)
  508.             text2 += it.first + ", ";
  509.  
  510.         if ( text1!= text2)
  511.         {
  512.             inited = false;
  513.             ED_ERROR("Failed to reload metashader, binders is not matched: '%s' transform: '%s'", fileName.c_str(), transformModifier.c_str());
  514.             ED_ERROR("prev binders = '%s'", text2.c_str());
  515.             ED_ERROR("     binders = '%s'", text1.c_str());
  516.         }
  517.  
  518.         for (auto& it : prev_bindersDesc)
  519.         {
  520.             it.second.binder = nullptr;
  521.             it.second.subItem = nullptr;
  522.         }
  523.     }
  524.     return true;
  525. }
  526.  
  527. // декларация функции
  528. bool MetaShaderImpl::getFunctionInfo(const ed::string& name, Function& function)
  529. {
  530.     ed::string clearname = name.substr(1);
  531.     auto found = cachedShader->functions.find(clearname);
  532.     if (found == cachedShader->functions.end())
  533.         return false;
  534.  
  535.     function = found->second;
  536.  
  537.     return true;
  538. }
  539.  
  540. bool MetaShaderImpl::bind(
  541.     MetaShaderRenderItem* renderItem,
  542.     render::MetaContext& metaContext)
  543. {
  544.     if (!inited)
  545.         return false;
  546. // Так compute не работает
  547. //  if (!geometry->getPrimitives("", renderItem->ib, renderItem->primtype, renderItem->startprim, renderItem->facecount))
  548. //      return false;
  549.  
  550.     renderItem->subitems.resize(bindersDesc.size(), nullptr);
  551.     int i=0;
  552.     for (auto it = bindersDesc.begin(); it != bindersDesc.end(); ++it, i++)
  553.     {
  554.         auto& binderDesc = (*it).second;
  555.         if (renderItem->subitems[i])
  556.             continue;       // already binded
  557.  
  558.         render::RenderSubItem* rsi = binderDesc.binder->bind(
  559.             this, *renderItem, binderDesc.subItem, metaContext);
  560.         if( !rsi)
  561.             return false;
  562.         if (rsi == DELAYSUBITEM)
  563.             continue;
  564.  
  565.         if(rsi == EMPTYSUBITEM)
  566.             // сделаем свой делетер, ибо удалять не нужно
  567.             renderItem->subitems[i].reset(rsi, [](render::RenderSubItem*){});
  568.         else
  569.             renderItem->subitems[i].reset(rsi);
  570.     }
  571.     return true;
  572. }
  573.  
  574. // setupParams
  575. bool MetaShaderImpl::setupParams(
  576.     MetaShaderRenderItem* renderItem,
  577.     render::MetaContext& metaContext
  578.     )
  579. {
  580.     if (!inited)
  581.         return false;
  582.  
  583.     int i=0;
  584.     for (auto it = bindersDesc.begin(); it != bindersDesc.end(); ++it, i++)
  585.     {
  586.         auto& binderDesc = (*it).second;
  587.         render::RenderSubItem* pEDTGRenderSubItem = renderItem->subitems[i].get();
  588. //      if (pEDTGRenderSubItem == EMPTYSUBITEM)
  589. //          return false;
  590.  
  591.         bool res = binderDesc.binder->render(this, binderDesc.subItem, pEDTGRenderSubItem, metaContext);
  592.         if( !res)
  593.             return false;
  594.     }
  595.     if( renderItem->ib)
  596.         shader.bindIndices(*renderItem->ib);
  597.     return true;
  598. }
  599.  
  600. bool MetaShaderImpl::render(
  601.     MetaShaderRenderItem* renderItem,
  602.     render::MetaContext& metaContext,
  603.     int instanceCount
  604.     )
  605. {
  606.     if (!inited)
  607.         return false;
  608.  
  609. //  if( !renderItem->ib.isValid())
  610. //      return false;
  611.     shader.begin();
  612.  
  613.     render::ShaderSubItem* pDrawShaderSubItem  = 0;
  614.     render::RenderSubItem* pDrawRenderSubItem  = 0;
  615.  
  616.     int i=0;
  617.     for (auto it = bindersDesc.begin(); it != bindersDesc.end(); ++it, i++)
  618.     {
  619.         auto& binderDesc = (*it).second;
  620.         render::RenderSubItem* pEDTGRenderSubItem = renderItem->subitems[i].get();
  621. //      if (pEDTGRenderSubItem == EMPTYSUBITEM)
  622. //      {
  623. //          shader.end();
  624. //          return false;
  625. //      }
  626.  
  627.         bool res = binderDesc.binder->render(this, binderDesc.subItem, pEDTGRenderSubItem, metaContext);
  628.         if( !res)
  629.         {
  630.             shader.end();
  631.             return false;
  632.         }
  633.     }
  634.  
  635.     if (renderItem->ib && renderItem->ib->isValid())
  636.         shader.bindIndices(*renderItem->ib);
  637.  
  638.     if( instanceCount<=1)
  639.         shader.draw(0, renderItem->primtype, renderItem->startprim, renderItem->facecount);
  640.     else
  641.         shader.drawInstanced(0, renderItem->primtype, renderItem->startprim, renderItem->facecount, instanceCount);
  642.  
  643.     shader.end();
  644.  
  645.     return true;
  646. }
  647.  
  648. // render
  649. bool MetaShaderImpl::compute(
  650.     MetaShaderRenderItem* renderItem,
  651.     render::MetaContext& metaContext
  652.     )
  653. {
  654.     if (!inited)
  655.         return false;
  656.  
  657.     if( renderItem->computeElements==0)
  658.         return false;
  659.  
  660.     shader.begin();
  661.  
  662.     render::ShaderSubItem* pDrawShaderSubItem  = 0;
  663.     render::RenderSubItem* pDrawRenderSubItem  = 0;
  664.  
  665.     int i=0;
  666.     for (auto it = bindersDesc.begin(); it != bindersDesc.end(); ++it, i++)
  667.     {
  668.         auto& binderDesc = (*it).second;
  669.         bool res = binderDesc.binder->render(this, binderDesc.subItem, renderItem->subitems[i].get(), metaContext);
  670.         if( !res)
  671.         {
  672.             shader.end();
  673.             return false;
  674.         }
  675.     }
  676.  
  677.     int groupCount = (renderItem->computeElements + GROUPSIZE - 1) / GROUPSIZE;
  678.     shader.compute(groupCount, 1, 1);
  679.  
  680.     shader.end();
  681.     return true;
  682. }
  683.  
  684. // dump
  685. ed::string MetaShaderImpl::dump(
  686.     MetaShaderRenderItem* renderItem,
  687.     render::MetaContext& metaContext
  688.     )
  689. {
  690.     ed::string text;
  691. #ifdef DUMPRENDER
  692.  
  693.     text += "META: ";
  694.     if( renderItem->primtype!=render::PT_NONE)
  695.     {
  696.         text += render::verbose(renderItem->primtype);
  697.         text.appendf(":%06d startPrim=%d ", renderItem->facecount, renderItem->startprim);
  698.     }
  699.     if( renderItem->computeElements)
  700.     {
  701.         text.appendf("elements: %05d ", renderItem->computeElements);
  702.     }
  703.  
  704.     text += getName() + " ";
  705.  
  706.     if (inited)
  707.     {
  708.         text.appendf("binders[%d]: \n", bindersDesc.size());
  709.         int i = 0;
  710.         for (auto it = bindersDesc.begin(); it != bindersDesc.end(); ++it, i++)
  711.         {
  712.             auto& binderDesc = (*it).second;
  713.             text.append("            ");
  714.             text.append(binderDesc.binder->dump(this, binderDesc.subItem, renderItem->subitems[i].get(), metaContext));
  715.             text.append("\n");
  716.         }
  717.     }
  718.     else
  719.     {
  720.         text.appendf(" binders not inited");
  721.     }
  722. #endif
  723.     return text;
  724. }
  725.  
  726. ed::string MetaShaderImpl::dump()
  727. {
  728.     ed::string text;
  729. #ifdef DUMPRENDER
  730.  
  731.     ed::string definitionsString = getDefinitionsString(&definitions);
  732.     ed::string dstPath = getDestShaderPath(definitionsString, "metafx", false);
  733.     text += "\n" + dstPath;
  734.  
  735.     if (inited)
  736.     {
  737.         text += ed::string() + "\n\t" + "binders:";
  738.         for (auto it = bindersDesc.begin(); it != bindersDesc.end(); ++it)
  739.         {
  740.             const auto& name = it->first;
  741.             auto& binderDesc = (*it).second;
  742.             text += "\n\t\t" + name + " " + ed::string_format("0x%p", binderDesc.binder);
  743.         }
  744.     }
  745.     else
  746.     {
  747.         text.appendf(" binders not inited");
  748.     }
  749. #endif
  750.     return text;
  751. }
  752.  
  753.  
  754. bool MetaShaderImpl::addVertexStream(const render::BindVariable& variable, ed::string& semantic)
  755. {
  756.     auto entry = vertexStreams.find(variable.name);
  757.     if (entry != vertexStreams.end())
  758.     {
  759.         semantic = entry->second.semantic;
  760.         return true;
  761.     }
  762.  
  763.     if( variable.name=="VertexID")
  764.         semantic = "SV_VertexID";
  765.     else
  766.         semantic = "TEXCOORD" + ed::to_string(vertexStreams.size());
  767.  
  768.     vertexStreams[variable.name].handle = render::INVALID_VE_HANDLE;
  769.     vertexStreams[variable.name].semantic = semantic;
  770.     return true;
  771. }
  772.  
  773.  
  774. MetaShaderImpl::BUILD_CODE MetaShaderImpl::buildShaderFromMetaShader(
  775.     const ed::string& filePath,
  776.     const ed::string& transformModifier,
  777.     const ed::vector<render::DefinePair>* definitions,
  778.     ed::string& shaderContent,
  779.     ed::string& definitionsString,
  780.     ed::vector<ed::string>& errors)
  781. {
  782.     definitionsString = getDefinitionsString(definitions);
  783.     auto cacheKey = getCacheKey(definitions);
  784.  
  785.     auto& shaderCache = render::MetaShaderCache::instance();
  786.     auto shader = shaderCache.getShader(cacheKey);
  787.     if (shader == nullptr)
  788.         shader = shaderCache.createShader(cacheKey);
  789.     cachedShader = shader;
  790.  
  791.     ed::string content;
  792.  
  793.     auto readFiles = [&]()
  794.     {
  795.         if (!readFile(filePath, content))
  796.         {
  797.             ED_ERROR("Failed to read %s", filePath.c_str());
  798.             return BC_CRITICAL_ERROR;
  799.         }
  800.  
  801.         // transform modifier
  802.         if (!transformModifier.empty())
  803.         {
  804.             ed::string transformModifierContent;
  805.             if (!readFile(transformModifier, transformModifierContent))
  806.             {
  807.                 ED_ERROR("Failed to read %s", transformModifier.c_str());
  808.                 return BC_CRITICAL_ERROR;
  809.             }
  810.             content += "\n#line 1 \"" + transformModifier + "\"\n";
  811.             content += transformModifierContent;
  812.         }
  813.         return BC_OK;
  814.     };
  815.  
  816.     bool isFilesRead = false;
  817.  
  818.     // Первый прогон, с добавлением шейдинг моделей
  819.     if (shader->sourceAvailable)
  820.     {
  821.         if (shader->preprocessed.needCompilation || shader->preprocessedAfterShadingModels.needCompilation)
  822.         {
  823.             auto code = readFiles();
  824.             if (code != BC_OK)
  825.                 return code;
  826.             isFilesRead = true;
  827.         }
  828.         // preprocess metashader
  829.         if (shader->preprocessed.needCompilation)
  830.         {
  831.             if (DEBUG_LOG)
  832.                 ED_INFO("    PREP 1 %s", cacheKey.c_str());
  833.             ed::string parsed;
  834.             ed::vector<ed::string> foundIncludes;
  835.             if (!preprocess(filePath, cacheKey,
  836.                             definitions, content, parsed, definitionsString,
  837.                             errors, getFolderForInterShader(), foundIncludes))
  838.                 return BC_CRITICAL_ERROR;
  839.             // parse metashader
  840.             ed::vector<ed::string> includes;
  841.             includes.reserve(foundIncludes.size()+2);
  842.             includes.push_back(this->filePath);
  843.             for (size_t i = 0; i != foundIncludes.size(); ++i)
  844.                 includes.push_back(std::move(foundIncludes[i]));
  845.             if (!transformModifier.empty())
  846.                 includes.push_back(transformModifier);
  847.             ed::normalizePath(this->filePath, includes.front());
  848.            
  849.             shaderCache.uploadCacheFirstPass(shader, includes, std::move(parsed));
  850.  
  851.             // parse functions
  852.             shader->functions.clear();
  853.             SharpLineReplacer sharpLineReplacer(shader->preprocessed.content);
  854.             sharpLineReplacer.replace();
  855.             render::MetaShaderParser parser;
  856.             parser.parseFunctions(shader->preprocessed.content, shader->functions);
  857.             sharpLineReplacer.undo();
  858.  
  859.             shader->preprocessed.needCompilation = false;
  860.         }
  861.  
  862.         // shading models
  863.         ed::string shadingModelsText;
  864.         ed::vector<render::IShadingModel*> shadingmodels;
  865.         render::ShadingModelFactory::getInstance().getShadingModels(shadingmodels);
  866.         for (int i = 0; i < shadingmodels.size(); i++)
  867.         {
  868.             shadingModelsText += shadingmodels[i]->Apply(this);
  869.         }
  870.  
  871.         // detect changes in shading models
  872.         shader->preprocessedAfterShadingModels.needCompilation |= shader->shadingModels != shadingModelsText;
  873.         shader->shadingModels = std::move(shadingModelsText);
  874.     }
  875.  
  876.     // Основной прогон
  877.     // preprocess metashader
  878.     if (shader->sourceAvailable && shader->preprocessedAfterShadingModels.needCompilation)
  879.     {
  880.         if (!isFilesRead)
  881.         {
  882.             auto code = readFiles();
  883.             if (code != BC_OK)
  884.                 return code;
  885.         }
  886.         content += shader->shadingModels;
  887.         // remove "@"
  888.         content.replace_all("@", "");
  889.  
  890.         // write shadingmodels shader
  891.         ed::string shadingmodelsFilePath = getDestShaderPath(definitionsString, "parse.metafx", true);
  892.         VFS_mkdir(getFolderForInterShader().c_str());
  893.         auto code = writeFile(shadingmodelsFilePath, content);
  894.         if (code != 0)
  895.             throw MsgException("failed to write shading models intermediate metashader to \""
  896.                                + shadingmodelsFilePath + "\", error code: " + ed::to_string(code));
  897.        
  898.         if (DEBUG_LOG)
  899.             ED_INFO("    PREP 2 %s", cacheKey.c_str());
  900.         ed::string parsed;
  901.         ed::vector<ed::string> foundIncludes;
  902.         if (!preprocess(filePath, cacheKey,
  903.                         definitions, content, parsed, definitionsString, errors,
  904.                         getFolderForInterShader(), foundIncludes))
  905.             return BC_CRITICAL_ERROR;
  906.  
  907.         ed::string preprocessedFilePath = getDestShaderPath(definitionsString, "prep.metafx", true);
  908.         VFS_mkdir(getFolderForInterShader().c_str());
  909.         code = writeFile(preprocessedFilePath, parsed);
  910.         if (code != 0)
  911.             throw MsgException("failed to write preprocessed intermediate metashader to \""
  912.                                + preprocessedFilePath + "\", error code: " + ed::to_string(code));
  913.        
  914.         render::MetaShaderParser parser;
  915.         // parse metashader
  916.         shader->bindVariables.clear();
  917.         parser.parseMetaShader(parsed, shader->bindVariables);
  918.         ed::vector<ed::string> includes;
  919.         includes.reserve(foundIncludes.size()+2);
  920.         includes.push_back(this->filePath);
  921.         for (size_t i = 0; i != foundIncludes.size(); ++i)
  922.             includes.push_back(std::move(foundIncludes[i]));
  923.         if (!transformModifier.empty())
  924.             includes.push_back(transformModifier);
  925.         ed::normalizePath(this->filePath, includes.front());
  926.         shaderCache.uploadCacheSecondPass(shader, includes, std::move(parsed));
  927.     }
  928.     shaderContent = shader->preprocessedAfterShadingModels.content;
  929.    
  930.     // const guard for using pointers on map keys
  931.     const auto& bindVariables = shader->bindVariables;
  932.  
  933.     bindVariablesSet.clear();
  934.     for (auto it = bindVariables.begin(); it != bindVariables.end(); ++it)
  935.     {
  936.         bindVariablesSet.insert(it->first);
  937.     }
  938.  
  939.     // determining all used binders
  940.     for (auto it = bindVariables.begin(); it != bindVariables.end(); ++it)
  941.     {
  942.         const ed::string& bindType = (*it).first.binder;
  943.         auto found = bindersDesc.find(bindType);
  944.         // add binderDesc if first occurrence
  945.         if (found == bindersDesc.end())
  946.         {
  947.             render::IBinder* binder = render::BinderFactory::getInstance().getBinder(bindType);
  948.             if (binder == NULL)
  949.             {
  950.                 #ifndef EDGE
  951.                     return BC_REGULAR_ERROR;
  952.                 #else
  953.                     continue;
  954.                 #endif // EDGE
  955.             }
  956.             render::ShaderSubItem* subItem = binder->initSubItem(this);
  957.             if (subItem == NULL)
  958.             {
  959.                 ED_ERROR("%s: %s binder sub item is NULL", getName().c_str(), bindType.c_str());
  960.                 return BC_REGULAR_ERROR;
  961.             }
  962.             BinderDesc& binderDesc = bindersDesc[bindType];
  963.             binderDesc.binder = binder;
  964.             binderDesc.subItem = subItem;
  965.         }
  966.     }
  967.    
  968.     // building all occurrences
  969.     ed::vector<SortOccurrence> allOccurrences;
  970.     allOccurrences.reserve(bindVariables.size()*4);
  971.     for (auto it = bindVariables.begin(); it != bindVariables.end(); ++it)
  972.     {
  973.         auto& occurrences = (*it).second;
  974.         // length = bindername + :: + variable name
  975.         const ed::string& binderName = (*it).first.binder;
  976.         if (bindersDesc.find(binderName) == bindersDesc.end())
  977.             continue;
  978.         for (size_t i = 0; i != occurrences.size(); ++i)
  979.         {
  980.             SortOccurrence occurrence(&bindersDesc[binderName], &it->first, occurrences[i].declPos,
  981.                                       occurrences[i].declLen, occurrences[i].type);
  982.             allOccurrences.push_back(occurrence);
  983.         }
  984.     }
  985.     // sorting all variables occurrences by position
  986.     std::sort(allOccurrences.begin(), allOccurrences.end());
  987.  
  988.     // Calling all binder->preprocess, replacing "::".
  989.     // Variable declaration occurrences must be passed first and |globalOffset| helps in case if
  990.     // outputted text has different size.
  991.     size_t globalOffset = 0;
  992.     for (size_t i = 0; i != allOccurrences.size(); ++i)
  993.     {
  994.         auto& occurrence = allOccurrences[i];
  995.         size_t offset = occurrence.pos + globalOffset;
  996.         size_t len = occurrence.len;
  997.         ed::string text = shaderContent.substr(offset, len);
  998.  
  999.         // Removing duplicated uniform definitions which can be appeared from shading models.
  1000.         auto& varOccurrences = bindVariables.find(*occurrence.variable)->second;
  1001.         if (occurrence.variable->interpolation == render::VT_UNIFORM
  1002.             && varOccurrences[0].declPos != occurrence.pos
  1003.             && occurrence.occurrenceType != render::VOT_VALUE)
  1004.         {
  1005.             text.clear();
  1006.             // Removing all variable declaration up to ';' symbol. It helps to consider variable
  1007.             // with register specification:
  1008.             //       Texture2DArray varyhouse__decalTexture : register(ps, t[0]);
  1009.             while ( offset + len < shaderContent.size() && shaderContent[offset + len] != ';')
  1010.                 ++len;
  1011.         }
  1012.         else
  1013.         {
  1014.             occurrence.binderDesc->binder->preprocessing(this, *occurrence.variable,
  1015.                                                          occurrence.occurrenceType,
  1016.                                                          text, occurrence.binderDesc->subItem);
  1017.         }
  1018.         auto globalOffsetChange = text.end() - text.begin() - len;
  1019.         shaderContent.replace(shaderContent.begin() + offset, shaderContent.begin() + offset + len,
  1020.                               text.begin(), text.end());
  1021.         globalOffset += globalOffsetChange;
  1022.     }
  1023.     return BC_OK;
  1024. }
  1025.  
  1026.  
  1027. void MetaShaderImpl::reset()
  1028. {
  1029.     cachedShader = nullptr;
  1030.     bindersDesc.clear();
  1031.     vertexStreams.clear();
  1032.     bindVariablesSet.clear();
  1033.     inited = false;
  1034. }
  1035.  
  1036.  
  1037. const render::BindVariable* MetaShaderImpl::getBindVariable(const ed::string& binder, const ed::string& name)
  1038. {
  1039.     auto found = bindVariablesSet.find(render::BindVariable("", binder, name));
  1040.     if (found == bindVariablesSet.end())
  1041.         return 0;
  1042.     return &(*found);
  1043. }
  1044.  
  1045. bool MetaShaderImpl::compileShader(
  1046.     const ed::string& definitionsString,
  1047.     const ed::string& shaderContent,
  1048.     const ed::vector<render::DefinePair>* definitions,
  1049.     render::COMPILEERRORACTION_ENUM globalRenderSetting
  1050.     )
  1051. {
  1052.     ed::string proceededFilePath = getDestShaderPath(definitionsString, "metafx", false);
  1053.     if (!customFinalPath.empty())
  1054.         proceededFilePath = customFinalPath;
  1055.  
  1056.     ed::string contentOnDisk;
  1057.     auto cacheKey = getCacheKey(definitions);
  1058.     auto& shaderCache = MetaShaderCache::instance();
  1059.     try
  1060.     {
  1061.         auto shaderEntry = shaderCache.getShader(cacheKey);
  1062.         if (!shaderEntry)
  1063.             throw ed::string("No cached metashader " + cacheKey);
  1064.         if (shaderEntry->sourceAvailable)
  1065.         {
  1066.             if (!readFile(proceededFilePath, contentOnDisk) || contentOnDisk != shaderContent)
  1067.             {
  1068.                 // write proceeded shader
  1069.                 VFS_mkdir(getFolderForFinalShader().c_str());
  1070.                 auto code = writeFile(proceededFilePath, shaderContent);
  1071.                 if (code != 0)
  1072.                     throw MsgException("failed to write created intermediate metashader to \""
  1073.                     + proceededFilePath + "\", error code: " + ed::to_string(code));
  1074.             }
  1075.         }
  1076.         ed::string shaderName = clearFilePath + ":" + clearTransformModifier;
  1077.         auto file = shaderEntry->sourceAvailable ? proceededFilePath.c_str() : "no source";
  1078.         if (!shader.open(file, definitions, true, false, shaderName.c_str()))
  1079.             return false;
  1080.     }
  1081.     catch (const ed::string& e)
  1082.     {
  1083.         ED_ERROR("%s", e.c_str());
  1084.         if (globalRenderSetting == render::CEA_RISE_EXCEPTION)
  1085.             throw ed::string(e);
  1086.     #ifdef _WINDOWS
  1087.         auto choice = MessageBox(0, e.c_str(), "MetaShader - Compilation Error",
  1088.             MB_RETRYCANCEL | MB_ICONQUESTION);
  1089.         if (choice == IDCANCEL)
  1090.         {
  1091.             exit(0);
  1092.             return false;
  1093.         }
  1094.     #endif
  1095.         return false;
  1096.     }
  1097.     return true;
  1098. }
  1099.  
  1100.  
  1101. bool MetaShaderImpl::preprocess(const ed::string& filePath, const ed::string& cacheKey,
  1102.                             const ed::vector<render::DefinePair>* definitions,
  1103.                             const ed::string& content, ed::string& parsedContent,
  1104.                             ed::string& definitionsString, ed::vector<ed::string>& errors,
  1105.                             const ed::string& destDir, ed::vector<ed::string>& foundIncludes)
  1106. {
  1107.     render::Preprocessor preprocessor;
  1108.     auto& preprocessorIncludePaths = MetaShaderCache::instance().getPreprocessorIncludePaths();
  1109.     for (auto path : preprocessorIncludePaths)
  1110.         preprocessor.addIncludeDir(path);
  1111.  
  1112.     definitionsString = getDefinitionsString(definitions);
  1113.  
  1114.     ed::vector<render::DefinePair> defArray;
  1115.     MetaShaderCache::instance().getGlobalDefined(defArray);
  1116.     for (int i = 0; i < defArray.size(); i++)
  1117.     {
  1118.         preprocessor.addMacroDefinition(defArray[i].getName(), defArray[i].getValue());
  1119.     }
  1120.  
  1121.     if( definitions)
  1122.     {
  1123.         for (size_t i = 0; i != definitions->size(); ++i)
  1124.         {
  1125.             preprocessor.addMacroDefinition((*definitions)[i].getName(), (*definitions)[i].getValue());
  1126.         }
  1127.     }
  1128.     ed::string stdParsedContent(parsedContent.c_str());
  1129.     if (!preprocessor.preprocess(content.c_str(), filePath.c_str(), stdParsedContent, destDir.c_str()))
  1130.     {
  1131.         parsedContent = stdParsedContent;
  1132.         ED_ERROR("Failed to preprocess shader:\n   %s\nreason:", cacheKey.c_str());
  1133.         preprocessor.getErrors(errors);
  1134.         for (size_t i = 0; i != errors.size(); ++i)
  1135.         {
  1136.             ED_ERROR("%s", errors[i].c_str());
  1137.         }
  1138.         return false;
  1139.     }
  1140.     parsedContent = stdParsedContent;
  1141.  
  1142.     {
  1143.         const ed::vector<ed::string> &fi = preprocessor.getIncludes();
  1144.         foundIncludes.clear();
  1145.         foundIncludes.reserve(fi.size());
  1146.         for(auto it = fi.begin(); it != fi.end(); ++it){
  1147.             foundIncludes.push_back(*it);
  1148.         }
  1149.     }
  1150.     return true;
  1151. }
  1152.  
  1153.  
  1154. ed::string MetaShaderImpl::getDefinitionsString(const ed::vector<render::DefinePair>* definitions)
  1155.     const
  1156. {
  1157.     return MetaShaderCache::getDefinitionsString(definitions);
  1158. }
  1159.  
  1160. ed::string MetaShaderImpl::getCacheKey(const ed::vector<render::DefinePair>* definitions) const
  1161. {
  1162.     return MetaShaderCache::getCacheKey(clearFilePath, clearTransformModifier, definitions);
  1163. }
  1164.  
  1165. void MetaShaderImpl::invalidateCachedShaders(const ed::vector<render::DefinePair>* definitions) const
  1166. {
  1167.     auto cacheKey = getCacheKey(definitions);
  1168.     auto &shaderCache = render::MetaShaderCache::instance();
  1169.     shaderCache.invalidateShader(cacheKey);
  1170. }
  1171.  
  1172.  
  1173. } // namespace render
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement