BsScenePicking.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Scene/BsScenePicking.h"
  4. #include "Scene/BsSceneManager.h"
  5. #include "Image/BsColor.h"
  6. #include "Math/BsMatrix4.h"
  7. #include "Debug/BsDebug.h"
  8. #include "Math/BsMath.h"
  9. #include "Components/BsCRenderable.h"
  10. #include "Scene/BsSceneObject.h"
  11. #include "Mesh/BsMesh.h"
  12. #include "Math/BsConvexVolume.h"
  13. #include "Components/BsCCamera.h"
  14. #include "CoreThread/BsCoreThread.h"
  15. #include "RenderAPI/BsRenderAPI.h"
  16. #include "Material/BsMaterial.h"
  17. #include "Material/BsPass.h"
  18. #include "RenderAPI/BsRasterizerState.h"
  19. #include "RenderAPI/BsRenderTexture.h"
  20. #include "Image/BsPixelData.h"
  21. #include "RenderAPI/BsGpuParams.h"
  22. #include "Material/BsGpuParamsSet.h"
  23. #include "Utility/BsBuiltinEditorResources.h"
  24. #include "Material/BsShader.h"
  25. #include "Renderer/BsRenderer.h"
  26. #include "Scene/BsGizmoManager.h"
  27. #include "Renderer/BsRendererUtility.h"
  28. using namespace std::placeholders;
  29. namespace bs
  30. {
  31. ScenePicking::ScenePicking()
  32. {
  33. mCore = bs_new<ct::ScenePicking>();
  34. for (UINT32 i = 0; i < 3; i++)
  35. {
  36. HMaterial matPicking = BuiltinEditorResources::instance().createPicking((CullingMode)i);
  37. HMaterial matPickingAlpha = BuiltinEditorResources::instance().createPickingAlpha((CullingMode)i);
  38. mCore->mMaterials[i] = matPicking->getCore();
  39. mCore->mMaterials[3 + i] = matPickingAlpha->getCore();
  40. }
  41. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::initialize, mCore));
  42. }
  43. ScenePicking::~ScenePicking()
  44. {
  45. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::destroy, mCore));
  46. }
  47. HSceneObject ScenePicking::pickClosestObject(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  48. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  49. {
  50. Vector<HSceneObject> selectedObjects = pickObjects(cam, position, area, ignoreRenderables, data);
  51. if (selectedObjects.size() == 0)
  52. return HSceneObject();
  53. if (data != nullptr)
  54. {
  55. Matrix3 rotation;
  56. selectedObjects[0]->getTransform().getRotation().toRotationMatrix(rotation);
  57. data->normal = rotation.inverse().transpose().multiply(data->normal);
  58. }
  59. return selectedObjects[0];
  60. }
  61. Vector<HSceneObject> ScenePicking::pickObjects(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  62. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  63. {
  64. auto comparePickElement = [&] (const ScenePicking::RenderablePickData& a, const ScenePicking::RenderablePickData& b)
  65. {
  66. // Sort by alpha setting first, then by cull mode, then by index
  67. if (a.alpha == b.alpha)
  68. {
  69. if (a.cullMode == b.cullMode)
  70. return a.index > b.index;
  71. else
  72. return (UINT32)a.cullMode > (UINT32)b.cullMode;
  73. }
  74. else
  75. return (UINT32)a.alpha > (UINT32)b.alpha;
  76. };
  77. Matrix4 viewProjMatrix = cam->getProjectionMatrixRS() * cam->getViewMatrix();
  78. Vector<HRenderable> renderables = gSceneManager().findComponents<CRenderable>(true);
  79. RenderableSet pickData(comparePickElement);
  80. Map<UINT32, HSceneObject> idxToRenderable;
  81. for (auto& renderable : renderables)
  82. {
  83. HSceneObject so = renderable->SO();
  84. HMesh mesh = renderable->getMesh();
  85. if (!mesh.isLoaded())
  86. continue;
  87. bool found = false;
  88. for (UINT32 i = 0; i < (UINT32)ignoreRenderables.size(); i++)
  89. {
  90. if (ignoreRenderables[i] == so)
  91. {
  92. found = true;
  93. break;
  94. }
  95. }
  96. if (found)
  97. continue;
  98. Bounds worldBounds = mesh->getProperties().getBounds();
  99. Matrix4 worldTransform = so->getWorldMatrix();
  100. worldBounds.transformAffine(worldTransform);
  101. const ConvexVolume& frustum = cam->getWorldFrustum();
  102. if (frustum.intersects(worldBounds.getSphere()))
  103. {
  104. // More precise with the box
  105. if (frustum.intersects(worldBounds.getBox()))
  106. {
  107. for (UINT32 i = 0; i < mesh->getProperties().getNumSubMeshes(); i++)
  108. {
  109. UINT32 idx = (UINT32)pickData.size();
  110. bool useAlphaShader = false;
  111. SPtr<RasterizerState> rasterizerState = RasterizerState::getDefault();
  112. HMaterial originalMat = renderable->getMaterial(i);
  113. if (originalMat != nullptr && originalMat->getNumPasses() > 0)
  114. {
  115. SPtr<Pass> firstPass = originalMat->getPass(0); // Note: We only ever check the first pass, problem?
  116. const auto& pipelineState = firstPass->getGraphicsPipelineState();
  117. if(pipelineState)
  118. {
  119. useAlphaShader = firstPass->hasBlending();
  120. if (pipelineState->getRasterizerState() == nullptr)
  121. rasterizerState = RasterizerState::getDefault();
  122. else
  123. rasterizerState = pipelineState->getRasterizerState();
  124. }
  125. }
  126. CullingMode cullMode = rasterizerState->getProperties().getCullMode();
  127. HTexture mainTexture;
  128. if (useAlphaShader)
  129. mainTexture = originalMat->getTexture("gAlbedoTex");
  130. idxToRenderable[idx] = so;
  131. Matrix4 wvpTransform = viewProjMatrix * worldTransform;
  132. pickData.insert({ mesh->getCore(), idx, wvpTransform, useAlphaShader, cullMode, mainTexture });
  133. }
  134. }
  135. }
  136. }
  137. UINT32 firstGizmoIdx = (UINT32)pickData.size();
  138. SPtr<ct::RenderTarget> target = cam->getViewport()->getTarget()->getCore();
  139. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::corePickingBegin, mCore, target,
  140. cam->getViewport()->getArea(), std::cref(pickData), position, area));
  141. GizmoManager::instance().renderForPicking(cam, [&](UINT32 inputIdx) { return encodeIndex(firstGizmoIdx + inputIdx); });
  142. AsyncOp op = gCoreThread().queueReturnCommand(std::bind(&ct::ScenePicking::corePickingEnd, mCore, target,
  143. cam->getViewport()->getArea(), position, area, data != nullptr, _1));
  144. gCoreThread().submit(true);
  145. assert(op.hasCompleted());
  146. PickResults pickResults = op.getReturnValue<PickResults>();
  147. if (data != nullptr)
  148. {
  149. data->pickPosition = cam->screenToWorldPointDeviceDepth(position, pickResults.depth);
  150. data->normal = pickResults.normal;
  151. }
  152. Vector<UINT32> selectedObjects = pickResults.objects;
  153. Vector<HSceneObject> results;
  154. for (auto& selectedObjectIdx : selectedObjects)
  155. {
  156. if (selectedObjectIdx < firstGizmoIdx)
  157. {
  158. auto iterFind = idxToRenderable.find(selectedObjectIdx);
  159. if (iterFind != idxToRenderable.end())
  160. results.push_back(iterFind->second);
  161. }
  162. else
  163. {
  164. UINT32 gizmoIdx = selectedObjectIdx - firstGizmoIdx;
  165. HSceneObject so = GizmoManager::instance().getSceneObject(gizmoIdx);
  166. if (so)
  167. results.push_back(so);
  168. }
  169. }
  170. return results;
  171. }
  172. Color ScenePicking::encodeIndex(UINT32 index)
  173. {
  174. Color encoded;
  175. encoded.r = (index & 0xFF) / 255.0f;
  176. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  177. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  178. encoded.a = 1.0f;
  179. if (((index >> 24) & 0xFF))
  180. LOGERR("Index when picking out of valid range.");
  181. return encoded;
  182. }
  183. UINT32 ScenePicking::decodeIndex(Color color)
  184. {
  185. UINT32 r = Math::roundToInt(color.r * 255.0f);
  186. UINT32 g = Math::roundToInt(color.g * 255.0f);
  187. UINT32 b = Math::roundToInt(color.b * 255.0f);
  188. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  189. }
  190. namespace ct
  191. {
  192. const float ScenePicking::ALPHA_CUTOFF = 0.5f;
  193. PickingParamBlockDef gPickingParamBlockDef;
  194. void ScenePicking::initialize()
  195. {
  196. // Do nothing
  197. }
  198. void ScenePicking::destroy()
  199. {
  200. bs_delete(this);
  201. }
  202. void ScenePicking::corePickingBegin(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  203. const bs::ScenePicking::RenderableSet& renderables, const Vector2I& position, const Vector2I& area)
  204. {
  205. RenderAPI& rs = RenderAPI::instance();
  206. SPtr<RenderTexture> rtt = std::static_pointer_cast<RenderTexture>(target);
  207. SPtr<Texture> outputTexture = rtt->getColorTexture(0);
  208. TextureProperties outputTextureProperties = outputTexture->getProperties();
  209. TEXTURE_DESC normalTexDesc;
  210. normalTexDesc.type = TEX_TYPE_2D;
  211. normalTexDesc.width = outputTextureProperties.getWidth();
  212. normalTexDesc.height = outputTextureProperties.getHeight();
  213. normalTexDesc.format = PF_RG11B10F;
  214. normalTexDesc.usage = TU_RENDERTARGET;
  215. SPtr<Texture> normalsTexture = Texture::create(normalTexDesc);
  216. SPtr<Texture> depthTexture = rtt->getDepthStencilTexture();
  217. RENDER_TEXTURE_DESC pickingMRT;
  218. pickingMRT.colorSurfaces[0].face = 0;
  219. pickingMRT.colorSurfaces[0].texture = outputTexture;
  220. pickingMRT.colorSurfaces[1].face = 0;
  221. pickingMRT.colorSurfaces[1].texture = normalsTexture;
  222. pickingMRT.depthStencilSurface.face = 0;
  223. pickingMRT.depthStencilSurface.texture = depthTexture;
  224. mPickingTexture = RenderTexture::create(pickingMRT);
  225. rs.setRenderTarget(mPickingTexture);
  226. rs.setViewport(viewportArea);
  227. rs.clearRenderTarget(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::White);
  228. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  229. gRendererUtility().setPass(mMaterials[0]);
  230. UINT32 numEntries = (UINT32)renderables.size();
  231. UINT32* renderableIndices = bs_stack_alloc<UINT32>(numEntries);
  232. UINT32 typeCounters[6];
  233. bs_zero_out(typeCounters);
  234. UINT32 idx = 0;
  235. for (auto& renderable : renderables)
  236. {
  237. UINT32 typeIdx;
  238. if (!renderable.alpha)
  239. typeIdx = 0;
  240. else
  241. typeIdx = 3;
  242. typeIdx += (UINT32)renderable.cullMode;
  243. UINT32 renderableIdx = typeCounters[typeIdx];
  244. renderableIndices[idx] = renderableIdx;
  245. SPtr<GpuParamsSet> paramsSet;
  246. if (renderableIdx >= mParamSets[typeIdx].size())
  247. {
  248. paramsSet = mMaterials[typeIdx]->createParamsSet();
  249. mParamSets[typeIdx].push_back(paramsSet);
  250. }
  251. else
  252. paramsSet = mParamSets[typeIdx][renderableIdx];
  253. SPtr<GpuParamBlockBuffer> paramBuffer;
  254. if (idx >= mParamBuffers.size())
  255. {
  256. paramBuffer = gPickingParamBlockDef.createBuffer();
  257. mParamBuffers.push_back(paramBuffer);
  258. }
  259. else
  260. paramBuffer = mParamBuffers[idx];
  261. paramsSet->setParamBlockBuffer("Uniforms", paramBuffer, true);
  262. Color color = bs::ScenePicking::encodeIndex(renderable.index);
  263. gPickingParamBlockDef.gMatViewProj.set(paramBuffer, renderable.wvpTransform);
  264. gPickingParamBlockDef.gAlphaCutoff.set(paramBuffer, ALPHA_CUTOFF);
  265. gPickingParamBlockDef.gColorIndex.set(paramBuffer, color);
  266. typeCounters[typeIdx]++;
  267. idx++;
  268. }
  269. UINT32 activeMaterialIdx = 0;
  270. idx = 0;
  271. for (auto& renderable : renderables)
  272. {
  273. UINT32 typeIdx;
  274. if (!renderable.alpha)
  275. typeIdx = 0;
  276. else
  277. typeIdx = 3;
  278. typeIdx += (UINT32)renderable.cullMode;
  279. if (activeMaterialIdx != typeIdx)
  280. {
  281. gRendererUtility().setPass(mMaterials[typeIdx]);
  282. activeMaterialIdx = typeIdx;
  283. }
  284. UINT32 renderableIdx = renderableIndices[idx];
  285. gRendererUtility().setPassParams(mParamSets[typeIdx][renderableIdx]);
  286. UINT32 numSubmeshes = renderable.mesh->getProperties().getNumSubMeshes();
  287. for (UINT32 i = 0; i < numSubmeshes; i++)
  288. gRendererUtility().draw(renderable.mesh, renderable.mesh->getProperties().getSubMesh(i));
  289. idx++;
  290. }
  291. bs_stack_free(renderableIndices);
  292. }
  293. void ScenePicking::corePickingEnd(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  294. const Vector2I& position, const Vector2I& area, bool gatherSnapData, AsyncOp& asyncOp)
  295. {
  296. const RenderTargetProperties& rtProps = target->getProperties();
  297. RenderAPI& rs = RenderAPI::instance();
  298. rs.setRenderTarget(nullptr);
  299. rs.submitCommandBuffer(nullptr);
  300. if (rtProps.isWindow)
  301. {
  302. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  303. }
  304. SPtr<Texture> outputTexture = mPickingTexture->getColorTexture(0);
  305. SPtr<Texture> normalsTexture = mPickingTexture->getColorTexture(1);
  306. SPtr<Texture> depthTexture = mPickingTexture->getDepthStencilTexture();
  307. if (position.x < 0 || position.x >= (INT32)outputTexture->getProperties().getWidth() ||
  308. position.y < 0 || position.y >= (INT32)outputTexture->getProperties().getHeight())
  309. {
  310. mPickingTexture = nullptr;
  311. asyncOp._completeOperation(Vector<UINT32>());
  312. return;
  313. }
  314. SPtr<PixelData> outputPixelData = outputTexture->getProperties().allocBuffer(0, 0);
  315. SPtr<PixelData> normalsPixelData;
  316. SPtr<PixelData> depthPixelData;
  317. if (gatherSnapData)
  318. {
  319. normalsPixelData = normalsTexture->getProperties().allocBuffer(0, 0);
  320. depthPixelData = depthTexture->getProperties().allocBuffer(0, 0);
  321. }
  322. outputTexture->readData(*outputPixelData);
  323. Vector2I pickPosition = position;
  324. if(rtProps.requiresTextureFlipping)
  325. pickPosition.y = rtProps.height - (position.y + area.y);
  326. UINT32 maxWidth = std::min((UINT32)(pickPosition.x + area.x), outputPixelData->getWidth());
  327. UINT32 maxHeight = std::min((UINT32)(pickPosition.y + area.y), outputPixelData->getHeight());
  328. Map<UINT32, UINT32> selectionScores;
  329. for (UINT32 y = (UINT32)pickPosition.y; y < maxHeight; y++)
  330. {
  331. for (UINT32 x = (UINT32)pickPosition.x; x < maxWidth; x++)
  332. {
  333. Color color = outputPixelData->getColorAt(x, y);
  334. UINT32 index = bs::ScenePicking::decodeIndex(color);
  335. if (index == 0x00FFFFFF) // Nothing selected
  336. continue;
  337. auto iterFind = selectionScores.find(index);
  338. if (iterFind == selectionScores.end())
  339. selectionScores[index] = 1;
  340. else
  341. iterFind->second++;
  342. }
  343. }
  344. // Sort by score
  345. struct SelectedObject { UINT32 index; UINT32 score; };
  346. Vector<SelectedObject> selectedObjects(selectionScores.size());
  347. UINT32 idx = 0;
  348. for (auto& selectionScore : selectionScores)
  349. {
  350. selectedObjects[idx++] = { selectionScore.first, selectionScore.second };
  351. }
  352. std::sort(selectedObjects.begin(), selectedObjects.end(),
  353. [&](const SelectedObject& a, const SelectedObject& b)
  354. {
  355. return b.score < a.score;
  356. });
  357. Vector<UINT32> objects;
  358. for (auto& selectedObject : selectedObjects)
  359. objects.push_back(selectedObject.index);
  360. PickResults result;
  361. if (gatherSnapData)
  362. {
  363. depthTexture->readData(*depthPixelData);
  364. normalsTexture->readData(*normalsPixelData);
  365. Vector2I samplePixel = position;
  366. if (rtProps.requiresTextureFlipping)
  367. samplePixel.y = depthPixelData->getHeight() - samplePixel.y;
  368. float depth = depthPixelData->getDepthAt(samplePixel.x, samplePixel.y);
  369. Color normal = normalsPixelData->getColorAt(samplePixel.x, samplePixel.y);
  370. const RenderAPIInfo& rapiInfo = rs.getAPIInfo();
  371. float max = rapiInfo.getMaximumDepthInputValue();
  372. float min = rapiInfo.getMinimumDepthInputValue();
  373. depth = depth * Math::abs(max - min) + min;
  374. result.depth = depth;
  375. result.normal = Vector3((normal.r * 2) - 1, (normal.g * 2) - 1, (normal.b * 2) - 1);
  376. }
  377. else
  378. result.depth = 0;
  379. mPickingTexture = nullptr;
  380. result.objects = objects;
  381. asyncOp._completeOperation(result);
  382. }
  383. }
  384. }