2
0

BsScenePicking.cpp 16 KB

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