BsScenePicking.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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.isLoaded() && 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 = any_cast<PickResults>(op.getGenericReturnValue());
  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. BS_LOG(Error, Editor, "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. for (UINT32 i = 0; i < bs_size(mMaterials); i++)
  197. mMaterials[i]->getTechnique(0)->compile();
  198. }
  199. void ScenePicking::destroy()
  200. {
  201. bs_delete(this);
  202. }
  203. void ScenePicking::corePickingBegin(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  204. const bs::ScenePicking::RenderableSet& renderables, const Vector2I& position, const Vector2I& area)
  205. {
  206. RenderAPI& rs = RenderAPI::instance();
  207. SPtr<RenderTexture> rtt = std::static_pointer_cast<RenderTexture>(target);
  208. SPtr<Texture> outputTexture = rtt->getColorTexture(0);
  209. TextureProperties outputTextureProperties = outputTexture->getProperties();
  210. TEXTURE_DESC normalTexDesc;
  211. normalTexDesc.type = TEX_TYPE_2D;
  212. normalTexDesc.width = outputTextureProperties.getWidth();
  213. normalTexDesc.height = outputTextureProperties.getHeight();
  214. normalTexDesc.format = PF_RG11B10F;
  215. normalTexDesc.usage = TU_RENDERTARGET;
  216. SPtr<Texture> normalsTexture = Texture::create(normalTexDesc);
  217. SPtr<Texture> depthTexture = rtt->getDepthStencilTexture();
  218. RENDER_TEXTURE_DESC pickingMRT;
  219. pickingMRT.colorSurfaces[0].face = 0;
  220. pickingMRT.colorSurfaces[0].texture = outputTexture;
  221. pickingMRT.colorSurfaces[1].face = 0;
  222. pickingMRT.colorSurfaces[1].texture = normalsTexture;
  223. pickingMRT.depthStencilSurface.face = 0;
  224. pickingMRT.depthStencilSurface.texture = depthTexture;
  225. mPickingTexture = RenderTexture::create(pickingMRT);
  226. rs.setRenderTarget(mPickingTexture);
  227. rs.setViewport(viewportArea);
  228. rs.clearRenderTarget(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::White);
  229. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  230. gRendererUtility().setPass(mMaterials[0]);
  231. UINT32 numEntries = (UINT32)renderables.size();
  232. UINT32* renderableIndices = bs_stack_alloc<UINT32>(numEntries);
  233. UINT32 typeCounters[6];
  234. bs_zero_out(typeCounters);
  235. UINT32 idx = 0;
  236. for (auto& renderable : renderables)
  237. {
  238. UINT32 typeIdx;
  239. if (!renderable.alpha)
  240. typeIdx = 0;
  241. else
  242. typeIdx = 3;
  243. typeIdx += (UINT32)renderable.cullMode;
  244. UINT32 renderableIdx = typeCounters[typeIdx];
  245. renderableIndices[idx] = renderableIdx;
  246. SPtr<GpuParamsSet> paramsSet;
  247. if (renderableIdx >= mParamSets[typeIdx].size())
  248. {
  249. paramsSet = mMaterials[typeIdx]->createParamsSet();
  250. mParamSets[typeIdx].push_back(paramsSet);
  251. }
  252. else
  253. paramsSet = mParamSets[typeIdx][renderableIdx];
  254. SPtr<GpuParamBlockBuffer> paramBuffer;
  255. if (idx >= mParamBuffers.size())
  256. {
  257. paramBuffer = gPickingParamBlockDef.createBuffer();
  258. mParamBuffers.push_back(paramBuffer);
  259. }
  260. else
  261. paramBuffer = mParamBuffers[idx];
  262. paramsSet->setParamBlockBuffer("Uniforms", paramBuffer, true);
  263. Color color = bs::ScenePicking::encodeIndex(renderable.index);
  264. gPickingParamBlockDef.gMatViewProj.set(paramBuffer, renderable.wvpTransform);
  265. gPickingParamBlockDef.gAlphaCutoff.set(paramBuffer, ALPHA_CUTOFF);
  266. gPickingParamBlockDef.gColorIndex.set(paramBuffer, color);
  267. typeCounters[typeIdx]++;
  268. idx++;
  269. }
  270. UINT32 activeMaterialIdx = 0;
  271. idx = 0;
  272. for (auto& renderable : renderables)
  273. {
  274. UINT32 typeIdx;
  275. if (!renderable.alpha)
  276. typeIdx = 0;
  277. else
  278. typeIdx = 3;
  279. typeIdx += (UINT32)renderable.cullMode;
  280. if (activeMaterialIdx != typeIdx)
  281. {
  282. gRendererUtility().setPass(mMaterials[typeIdx]);
  283. activeMaterialIdx = typeIdx;
  284. }
  285. UINT32 renderableIdx = renderableIndices[idx];
  286. gRendererUtility().setPassParams(mParamSets[typeIdx][renderableIdx]);
  287. UINT32 numSubmeshes = renderable.mesh->getProperties().getNumSubMeshes();
  288. for (UINT32 i = 0; i < numSubmeshes; i++)
  289. gRendererUtility().draw(renderable.mesh, renderable.mesh->getProperties().getSubMesh(i));
  290. idx++;
  291. }
  292. bs_stack_free(renderableIndices);
  293. }
  294. void ScenePicking::corePickingEnd(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  295. const Vector2I& position, const Vector2I& area, bool gatherSnapData, AsyncOp& asyncOp)
  296. {
  297. const RenderTargetProperties& rtProps = target->getProperties();
  298. RenderAPI& rs = RenderAPI::instance();
  299. rs.setRenderTarget(nullptr);
  300. rs.submitCommandBuffer(nullptr);
  301. if (rtProps.isWindow)
  302. {
  303. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  304. }
  305. SPtr<Texture> outputTexture = mPickingTexture->getColorTexture(0);
  306. SPtr<Texture> normalsTexture = mPickingTexture->getColorTexture(1);
  307. SPtr<Texture> depthTexture = mPickingTexture->getDepthStencilTexture();
  308. if (position.x < 0 || position.x >= (INT32)outputTexture->getProperties().getWidth() ||
  309. position.y < 0 || position.y >= (INT32)outputTexture->getProperties().getHeight())
  310. {
  311. mPickingTexture = nullptr;
  312. asyncOp._completeOperation(Vector<UINT32>());
  313. return;
  314. }
  315. SPtr<PixelData> outputPixelData = outputTexture->getProperties().allocBuffer(0, 0);
  316. SPtr<PixelData> normalsPixelData;
  317. SPtr<PixelData> depthPixelData;
  318. if (gatherSnapData)
  319. {
  320. normalsPixelData = normalsTexture->getProperties().allocBuffer(0, 0);
  321. depthPixelData = depthTexture->getProperties().allocBuffer(0, 0);
  322. }
  323. outputTexture->readData(*outputPixelData);
  324. Vector2I pickPosition = position;
  325. if(rtProps.requiresTextureFlipping)
  326. pickPosition.y = rtProps.height - (position.y + area.y);
  327. UINT32 maxWidth = std::min((UINT32)(pickPosition.x + area.x), outputPixelData->getWidth());
  328. UINT32 maxHeight = std::min((UINT32)(pickPosition.y + area.y), outputPixelData->getHeight());
  329. Map<UINT32, UINT32> selectionScores;
  330. for (UINT32 y = (UINT32)pickPosition.y; y < maxHeight; y++)
  331. {
  332. for (UINT32 x = (UINT32)pickPosition.x; x < maxWidth; x++)
  333. {
  334. Color color = outputPixelData->getColorAt(x, y);
  335. UINT32 index = bs::ScenePicking::decodeIndex(color);
  336. if (index == 0x00FFFFFF) // Nothing selected
  337. continue;
  338. auto iterFind = selectionScores.find(index);
  339. if (iterFind == selectionScores.end())
  340. selectionScores[index] = 1;
  341. else
  342. iterFind->second++;
  343. }
  344. }
  345. // Sort by score
  346. struct SelectedObject { UINT32 index; UINT32 score; };
  347. Vector<SelectedObject> selectedObjects(selectionScores.size());
  348. UINT32 idx = 0;
  349. for (auto& selectionScore : selectionScores)
  350. {
  351. selectedObjects[idx++] = { selectionScore.first, selectionScore.second };
  352. }
  353. std::sort(selectedObjects.begin(), selectedObjects.end(),
  354. [&](const SelectedObject& a, const SelectedObject& b)
  355. {
  356. return b.score < a.score;
  357. });
  358. Vector<UINT32> objects;
  359. for (auto& selectedObject : selectedObjects)
  360. objects.push_back(selectedObject.index);
  361. PickResults result;
  362. if (gatherSnapData)
  363. {
  364. depthTexture->readData(*depthPixelData);
  365. normalsTexture->readData(*normalsPixelData);
  366. Vector2I samplePixel = position;
  367. if (rtProps.requiresTextureFlipping)
  368. samplePixel.y = depthPixelData->getHeight() - samplePixel.y;
  369. float depth = depthPixelData->getDepthAt(samplePixel.x, samplePixel.y);
  370. Color normal = normalsPixelData->getColorAt(samplePixel.x, samplePixel.y);
  371. const RenderAPICapabilities& caps = gCaps();
  372. float max = caps.maxDepth;
  373. float min = caps.minDepth;
  374. depth = depth * Math::abs(max - min) + min;
  375. result.depth = depth;
  376. result.normal = Vector3((normal.r * 2) - 1, (normal.g * 2) - 1, (normal.b * 2) - 1);
  377. }
  378. else
  379. result.depth = 0;
  380. mPickingTexture = nullptr;
  381. result.objects = objects;
  382. asyncOp._completeOperation(result);
  383. }
  384. }
  385. }