BsScenePicking.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. #include "BsScenePicking.h"
  2. #include "BsSceneManager.h"
  3. #include "BsColor.h"
  4. #include "BsMatrix4.h"
  5. #include "BsDebug.h"
  6. #include "BsMath.h"
  7. #include "BsRenderable.h"
  8. #include "BsSceneObject.h"
  9. #include "BsMesh.h"
  10. #include "BsConvexVolume.h"
  11. #include "BsCamera.h"
  12. #include "BsCoreThread.h"
  13. #include "BsRenderSystem.h"
  14. #include "BsMaterial.h"
  15. #include "BsPass.h"
  16. #include "BsBlendState.h"
  17. #include "BsDepthStencilState.h"
  18. #include "BsRasterizerState.h"
  19. #include "BsRenderTarget.h"
  20. #include "BsPixelData.h"
  21. #include "BsGpuParams.h"
  22. #include "BsBuiltinEditorResources.h"
  23. #include "BsShader.h"
  24. #include "BsRenderer.h"
  25. using namespace std::placeholders;
  26. namespace BansheeEngine
  27. {
  28. const float ScenePicking::ALPHA_CUTOFF = 0.5f;
  29. ScenePicking::ScenePicking()
  30. {
  31. for (UINT32 i = 0; i < 3; i++)
  32. {
  33. mMaterialData[i].mMatPicking = BuiltinEditorResources::instance().createPicking((CullingMode)i);
  34. mMaterialData[i].mMatPickingAlpha = BuiltinEditorResources::instance().createPickingAlpha((CullingMode)i);
  35. mMaterialData[i].mMatPickingProxy = mMaterialData[i].mMatPicking->_createProxy();
  36. mMaterialData[i].mMatPickingAlphaProxy = mMaterialData[i].mMatPickingAlpha->_createProxy();
  37. }
  38. gCoreAccessor().queueCommand(std::bind(&ScenePicking::initializeCore, this));
  39. }
  40. void ScenePicking::initializeCore()
  41. {
  42. for (UINT32 i = 0; i < 3; i++)
  43. {
  44. MaterialData& md = mMaterialData[i];
  45. {
  46. // TODO - Make a better interface when dealing with parameters through proxies?
  47. MaterialProxyPtr proxy = md.mMatPickingProxy;
  48. GpuParamsPtr vertParams = proxy->params[proxy->passes[0].vertexProgParamsIdx];
  49. vertParams->getParam("matWorldViewProj", md.mParamPickingWVP);
  50. GpuParamsPtr fragParams = proxy->params[proxy->passes[0].fragmentProgParamsIdx];
  51. fragParams->getParam("colorIndex", md.mParamPickingColor);
  52. }
  53. {
  54. MaterialProxyPtr proxy = md.mMatPickingAlphaProxy;
  55. GpuParamsPtr vertParams = proxy->params[proxy->passes[0].vertexProgParamsIdx];
  56. vertParams->getParam("matWorldViewProj", md.mParamPickingAlphaWVP);
  57. GpuParamsPtr fragParams = proxy->params[proxy->passes[0].fragmentProgParamsIdx];
  58. fragParams->getParam("colorIndex", md.mParamPickingAlphaColor);
  59. fragParams->getTextureParam("mainTexture", md.mParamPickingAlphaTexture);
  60. GpuParamFloat alphaCutoffParam;
  61. fragParams->getParam("alphaCutoff", alphaCutoffParam);
  62. alphaCutoffParam.set(ALPHA_CUTOFF);
  63. }
  64. }
  65. }
  66. HSceneObject ScenePicking::pickClosestSceneObject(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  67. {
  68. Vector<PickResult> selectedObjects = pickObjects(cam, position, area);
  69. for (auto& object : selectedObjects)
  70. {
  71. if (object.type == PickResult::Type::SceneObject)
  72. return object.sceneObject;
  73. }
  74. return HSceneObject();
  75. }
  76. PickResult ScenePicking::pickClosestObject(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  77. {
  78. Vector<PickResult> selectedObjects = pickObjects(cam, position, area);
  79. if (selectedObjects.size() == 0)
  80. return { HSceneObject(), 0, PickResult::Type::None };
  81. return selectedObjects[0];
  82. }
  83. Vector<HSceneObject> ScenePicking::pickSceneObjects(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  84. {
  85. Vector<HSceneObject> results;
  86. Vector<PickResult> selectedObjects = pickObjects(cam, position, area);
  87. for (auto& object : selectedObjects)
  88. {
  89. if (object.type == PickResult::Type::SceneObject)
  90. results.push_back(object.sceneObject);
  91. }
  92. return results;
  93. }
  94. Vector<PickResult> ScenePicking::pickObjects(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  95. {
  96. auto comparePickElement = [&] (const ScenePicking::RenderablePickData& a, const ScenePicking::RenderablePickData& b)
  97. {
  98. // Sort by alpha setting first, then by cull mode, then by index
  99. if (a.alpha == b.alpha)
  100. {
  101. if (a.cullMode == b.cullMode)
  102. return a.index > b.index;
  103. else
  104. return (UINT32)a.cullMode > (UINT32)b.cullMode;
  105. }
  106. else
  107. return (UINT32)a.alpha > (UINT32)b.alpha;
  108. };
  109. const Vector<HRenderable>& renderables = SceneManager::instance().getAllRenderables();
  110. RenderableSet pickData(comparePickElement);
  111. Map<UINT32, HRenderable> idxToRenderable;
  112. for (auto& renderable : renderables)
  113. {
  114. HSceneObject so = renderable->SO();
  115. if (!so->getActive())
  116. continue;
  117. HMesh mesh = renderable->getMesh();
  118. if (!mesh)
  119. continue;
  120. Bounds worldBounds = mesh->getBounds();
  121. Matrix4 worldTransform = so->getWorldTfrm();
  122. worldBounds.transformAffine(worldTransform);
  123. const ConvexVolume& frustum = cam->getWorldFrustum();
  124. if (frustum.intersects(worldBounds.getSphere()))
  125. {
  126. // More precise with the box
  127. if (frustum.intersects(worldBounds.getBox()))
  128. {
  129. for (UINT32 i = 0; i < mesh->getNumSubMeshes(); i++)
  130. {
  131. UINT32 idx = (UINT32)pickData.size();
  132. HMaterial originalMat = renderable->getMaterial(i);
  133. if (!originalMat)
  134. continue;
  135. PassPtr firstPass;
  136. if (originalMat->getNumPasses() == 0)
  137. continue;
  138. firstPass = originalMat->getPass(0); // Note: We only ever check the first pass, problem?
  139. bool useAlphaShader = firstPass->hasBlending();
  140. CullingMode cullMode = firstPass->getRasterizerState()->getCullMode();
  141. MeshProxyPtr meshProxy;
  142. if (mesh->_isCoreDirty(MeshDirtyFlag::Proxy))
  143. meshProxy = mesh->_createProxy(i);
  144. else
  145. meshProxy = mesh->_getActiveProxy(i);
  146. idxToRenderable[idx] = renderable;
  147. pickData.insert({ meshProxy, idx, worldTransform, useAlphaShader, cullMode });
  148. }
  149. }
  150. }
  151. }
  152. Viewport vp = cam->getViewport()->clone();
  153. AsyncOp op = gCoreAccessor().queueReturnCommand(std::bind(&ScenePicking::corePickObjects, this, vp, std::cref(pickData), position, area, _1));
  154. gCoreAccessor().submitToCoreThread(true);
  155. assert(op.hasCompleted());
  156. Vector<UINT32>& selectedObjects = op.getReturnValue<Vector<UINT32>>();
  157. Vector<PickResult> results;
  158. for (auto& selectedObject : selectedObjects)
  159. {
  160. results.push_back({ idxToRenderable[selectedObject]->SO(), 0, PickResult::Type::SceneObject });
  161. }
  162. return results;
  163. }
  164. void ScenePicking::corePickObjects(const Viewport& vp, const RenderableSet& renderables, const Vector2I& position,
  165. const Vector2I& area, AsyncOp& asyncOp)
  166. {
  167. RenderSystem& rs = RenderSystem::instance();
  168. RenderTargetPtr rt = vp.getTarget();
  169. if (rt->getCore()->getProperties().isWindow())
  170. {
  171. // TODO: When I do implement this then I will likely want a method in RenderTarget that unifies both render window and render texture readback
  172. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  173. }
  174. RenderTexturePtr rtt = std::static_pointer_cast<RenderTexture>(rt);
  175. TexturePtr outputTexture = rtt->getBindableColorTexture().getInternalPtr();
  176. rs.setViewport(vp);
  177. rs.clearRenderTarget(FBT_COLOR, Color::White);
  178. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  179. Renderer::setPass(*mMaterialData[0].mMatPickingProxy, 0);
  180. bool activeMaterialIsAlpha = false;
  181. CullingMode activeMaterialCull = (CullingMode)0;
  182. rs.beginFrame();
  183. for (auto& renderable : renderables)
  184. {
  185. if (activeMaterialIsAlpha != renderable.alpha || activeMaterialCull != renderable.cullMode)
  186. {
  187. activeMaterialIsAlpha = renderable.alpha;
  188. activeMaterialCull = renderable.cullMode;
  189. if (activeMaterialIsAlpha)
  190. Renderer::setPass(*mMaterialData[(UINT32)activeMaterialCull].mMatPickingAlphaProxy, 0);
  191. else
  192. Renderer::setPass(*mMaterialData[(UINT32)activeMaterialCull].mMatPickingProxy, 0);
  193. }
  194. Color color = encodeIndex(renderable.index);
  195. MaterialData& md = mMaterialData[(UINT32)activeMaterialCull];
  196. if (activeMaterialIsAlpha)
  197. {
  198. md.mParamPickingAlphaWVP.set(renderable.wvpTransform);
  199. md.mParamPickingAlphaColor.set(color);
  200. md.mParamPickingAlphaTexture.set(HTexture()); // TODO - Get main texture from original
  201. }
  202. else
  203. {
  204. md.mParamPickingWVP.set(renderable.wvpTransform);
  205. md.mParamPickingColor.set(color);
  206. }
  207. Renderer::draw(*renderable.mesh);
  208. }
  209. rs.endFrame();
  210. PixelDataPtr outputPixelData = outputTexture->allocateSubresourceBuffer(0);
  211. GpuResourceDataPtr outputData = outputPixelData;
  212. AsyncOp unused;
  213. rs.readSubresource(outputTexture, 0, outputData, unused);
  214. Map<UINT32, UINT32> selectionScores;
  215. UINT32 numPixels = outputPixelData->getWidth() * outputPixelData->getHeight();
  216. for (UINT32 y = 0; y < outputPixelData->getHeight(); y++)
  217. {
  218. for (UINT32 x = 0; x < outputPixelData->getWidth(); x++)
  219. {
  220. Color color = outputPixelData->getColorAt(x, y);
  221. UINT32 index = decodeIndex(color);
  222. if (index == 0x00FFFFFF) // Nothing selected
  223. continue;
  224. auto iterFind = selectionScores.find(index);
  225. if (iterFind == selectionScores.end())
  226. selectionScores[index] = 1;
  227. else
  228. iterFind->second++;
  229. }
  230. }
  231. // Sort by score
  232. struct SelectedObject { UINT32 index; UINT32 score; };
  233. Vector<SelectedObject> selectedObjects(selectionScores.size());
  234. UINT32 idx = 0;
  235. for (auto& selectionScore : selectionScores)
  236. {
  237. selectedObjects[idx++] = { selectionScore.second, selectionScore.first };
  238. }
  239. std::sort(selectedObjects.begin(), selectedObjects.end(),
  240. [&](const SelectedObject& a, const SelectedObject& b)
  241. {
  242. return b.score < a.score;
  243. });
  244. Vector<UINT32> results;
  245. for (auto& selectedObject : selectedObjects)
  246. results.push_back(selectedObject.index);
  247. asyncOp._completeOperation(selectedObjects);
  248. }
  249. Color ScenePicking::encodeIndex(UINT32 index)
  250. {
  251. Color encoded;
  252. encoded.r = (index & 0xFF) / 255.0f;
  253. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  254. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  255. encoded.a = 1.0f;
  256. if (((index >> 24) & 0xFF))
  257. LOGERR("Index when picking out of valid range.");
  258. return encoded;
  259. }
  260. UINT32 ScenePicking::decodeIndex(Color color)
  261. {
  262. UINT32 r = Math::roundToInt(color.r * 255.0f);
  263. UINT32 g = Math::roundToInt(color.g * 255.0f);
  264. UINT32 b = Math::roundToInt(color.b * 255.0f);
  265. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  266. }
  267. }