BsScenePicking.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. // TODO - I could limit the frustum to the visible area we're rendering for a speed boost
  124. // but this is unlikely to be a performance bottleneck
  125. const ConvexVolume& frustum = cam->getWorldFrustum();
  126. if (frustum.intersects(worldBounds.getSphere()))
  127. {
  128. // More precise with the box
  129. if (frustum.intersects(worldBounds.getBox()))
  130. {
  131. for (UINT32 i = 0; i < mesh->getNumSubMeshes(); i++)
  132. {
  133. UINT32 idx = (UINT32)pickData.size();
  134. HMaterial originalMat = renderable->getMaterial(i);
  135. if (!originalMat)
  136. continue;
  137. PassPtr firstPass;
  138. if (originalMat->getNumPasses() == 0)
  139. continue;
  140. firstPass = originalMat->getPass(0); // Note: We only ever check the first pass, problem?
  141. bool useAlphaShader = firstPass->hasBlending();
  142. CullingMode cullMode = firstPass->getRasterizerState()->getCullMode();
  143. MeshProxyPtr meshProxy;
  144. if (mesh->_isCoreDirty(MeshDirtyFlag::Proxy))
  145. meshProxy = mesh->_createProxy(i);
  146. else
  147. meshProxy = mesh->_getActiveProxy(i);
  148. HTexture mainTexture;
  149. if (useAlphaShader)
  150. {
  151. const Map<String, SHADER_OBJECT_PARAM_DESC>& objectParams = originalMat->getShader()->_getObjectParams();
  152. for (auto& objectParam : objectParams)
  153. {
  154. if (objectParam.second.rendererSemantic == RPS_MainTex)
  155. {
  156. mainTexture = originalMat->getTexture(objectParam.first);
  157. break;
  158. }
  159. }
  160. }
  161. idxToRenderable[idx] = renderable;
  162. pickData.insert({ meshProxy, idx, worldTransform, useAlphaShader, cullMode, mainTexture });
  163. }
  164. }
  165. }
  166. }
  167. Viewport vp = cam->getViewport()->clone();
  168. AsyncOp op = gCoreAccessor().queueReturnCommand(std::bind(&ScenePicking::corePickObjects, this, vp, std::cref(pickData), position, area, _1));
  169. gCoreAccessor().submitToCoreThread(true);
  170. assert(op.hasCompleted());
  171. Vector<UINT32>& selectedObjects = op.getReturnValue<Vector<UINT32>>();
  172. Vector<PickResult> results;
  173. for (auto& selectedObject : selectedObjects)
  174. {
  175. results.push_back({ idxToRenderable[selectedObject]->SO(), 0, PickResult::Type::SceneObject });
  176. }
  177. return results;
  178. }
  179. void ScenePicking::corePickObjects(const Viewport& vp, const RenderableSet& renderables, const Vector2I& position,
  180. const Vector2I& area, AsyncOp& asyncOp)
  181. {
  182. RenderSystem& rs = RenderSystem::instance();
  183. RenderTargetPtr rt = vp.getTarget();
  184. if (rt->getCore()->getProperties().isWindow())
  185. {
  186. // TODO: When I do implement this then I will likely want a method in RenderTarget that unifies both render window and render texture readback
  187. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  188. }
  189. RenderTexturePtr rtt = std::static_pointer_cast<RenderTexture>(rt);
  190. TexturePtr outputTexture = rtt->getBindableColorTexture().getInternalPtr();
  191. rs.setViewport(vp);
  192. rs.clearRenderTarget(FBT_COLOR, Color::White);
  193. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  194. Renderer::setPass(*mMaterialData[0].mMatPickingProxy, 0);
  195. bool activeMaterialIsAlpha = false;
  196. CullingMode activeMaterialCull = (CullingMode)0;
  197. rs.beginFrame();
  198. for (auto& renderable : renderables)
  199. {
  200. if (activeMaterialIsAlpha != renderable.alpha || activeMaterialCull != renderable.cullMode)
  201. {
  202. activeMaterialIsAlpha = renderable.alpha;
  203. activeMaterialCull = renderable.cullMode;
  204. if (activeMaterialIsAlpha)
  205. Renderer::setPass(*mMaterialData[(UINT32)activeMaterialCull].mMatPickingAlphaProxy, 0);
  206. else
  207. Renderer::setPass(*mMaterialData[(UINT32)activeMaterialCull].mMatPickingProxy, 0);
  208. }
  209. Color color = encodeIndex(renderable.index);
  210. MaterialData& md = mMaterialData[(UINT32)activeMaterialCull];
  211. if (activeMaterialIsAlpha)
  212. {
  213. md.mParamPickingAlphaWVP.set(renderable.wvpTransform);
  214. md.mParamPickingAlphaColor.set(color);
  215. md.mParamPickingAlphaTexture.set(renderable.mainTexture);
  216. }
  217. else
  218. {
  219. md.mParamPickingWVP.set(renderable.wvpTransform);
  220. md.mParamPickingColor.set(color);
  221. }
  222. Renderer::draw(*renderable.mesh);
  223. }
  224. rs.endFrame();
  225. PixelDataPtr outputPixelData = outputTexture->allocateSubresourceBuffer(0);
  226. GpuResourceDataPtr outputData = outputPixelData;
  227. AsyncOp unused;
  228. rs.readSubresource(outputTexture, 0, outputData, unused);
  229. Map<UINT32, UINT32> selectionScores;
  230. UINT32 numPixels = outputPixelData->getWidth() * outputPixelData->getHeight();
  231. for (UINT32 y = 0; y < outputPixelData->getHeight(); y++)
  232. {
  233. for (UINT32 x = 0; x < outputPixelData->getWidth(); x++)
  234. {
  235. Color color = outputPixelData->getColorAt(x, y);
  236. UINT32 index = decodeIndex(color);
  237. if (index == 0x00FFFFFF) // Nothing selected
  238. continue;
  239. auto iterFind = selectionScores.find(index);
  240. if (iterFind == selectionScores.end())
  241. selectionScores[index] = 1;
  242. else
  243. iterFind->second++;
  244. }
  245. }
  246. // Sort by score
  247. struct SelectedObject { UINT32 index; UINT32 score; };
  248. Vector<SelectedObject> selectedObjects(selectionScores.size());
  249. UINT32 idx = 0;
  250. for (auto& selectionScore : selectionScores)
  251. {
  252. selectedObjects[idx++] = { selectionScore.second, selectionScore.first };
  253. }
  254. std::sort(selectedObjects.begin(), selectedObjects.end(),
  255. [&](const SelectedObject& a, const SelectedObject& b)
  256. {
  257. return b.score < a.score;
  258. });
  259. Vector<UINT32> results;
  260. for (auto& selectedObject : selectedObjects)
  261. results.push_back(selectedObject.index);
  262. asyncOp._completeOperation(selectedObjects);
  263. }
  264. Color ScenePicking::encodeIndex(UINT32 index)
  265. {
  266. Color encoded;
  267. encoded.r = (index & 0xFF) / 255.0f;
  268. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  269. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  270. encoded.a = 1.0f;
  271. if (((index >> 24) & 0xFF))
  272. LOGERR("Index when picking out of valid range.");
  273. return encoded;
  274. }
  275. UINT32 ScenePicking::decodeIndex(Color color)
  276. {
  277. UINT32 r = Math::roundToInt(color.r * 255.0f);
  278. UINT32 g = Math::roundToInt(color.g * 255.0f);
  279. UINT32 b = Math::roundToInt(color.b * 255.0f);
  280. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  281. }
  282. }