Tiler.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. #include "anki/renderer/Tiler.h"
  2. #include "anki/renderer/Renderer.h"
  3. #include "anki/resource/ShaderProgramResource.h"
  4. #include "anki/core/ThreadPool.h"
  5. #include "anki/scene/Camera.h"
  6. // Default should be 0
  7. #define ALTERNATIVE_MIN_MAX 0
  8. namespace anki {
  9. //==============================================================================
  10. /// Job that updates the left, right, top and buttom tile planes
  11. struct UpdateTilesPlanesPerspectiveCameraJob: ThreadJob
  12. {
  13. Tiler* tiler;
  14. PerspectiveCamera* cam;
  15. Bool frustumChanged;
  16. const Tiler::PixelArray* pixels;
  17. void operator()(U threadId, U threadsCount)
  18. {
  19. U64 start, end;
  20. choseStartEnd(threadId, threadsCount,
  21. Tiler::TILES_X_COUNT * Tiler::TILES_Y_COUNT, start, end);
  22. // Precalculate some stuff for update4Planes()
  23. F32 l = 0.0, l6 = 0.0, o = 0.0, o6 = 0.0;
  24. if(frustumChanged)
  25. {
  26. const F32 fx = cam->getFovX();
  27. const F32 fy = cam->getFovY();
  28. const F32 n = cam->getNear();
  29. l = 2.0 * n * tan(fx / 2.0);
  30. l6 = l / Tiler::TILES_X_COUNT;
  31. o = 2.0 * n * tan(fy / 2.0);
  32. o6 = o / Tiler::TILES_Y_COUNT;
  33. }
  34. // Precalculate some stuff for update2Planes()
  35. Vec2 planes;
  36. Renderer::calcPlanes(Vec2(cam->getNear(), cam->getFar()), planes);
  37. Transform trf = Transform(cam->getWorldTransform());
  38. for(U64 k = start; k < end; k++)
  39. {
  40. if(frustumChanged)
  41. {
  42. update4Planes(l, l6, o, o6, k);
  43. }
  44. update2Planes(k, planes);
  45. // Transform planes
  46. Tiler::Tile& tile = tiler->tiles1d[k];
  47. for(U i = 0; i < Frustum::FP_COUNT; i++)
  48. {
  49. tile.planesWSpace[i] = tile.planes[i].getTransformed(trf);
  50. }
  51. }
  52. }
  53. void update4Planes(
  54. const F32 l, const F32 l6, const F32 o, const F32 o6,
  55. const U k)
  56. {
  57. Vec3 a, b;
  58. const F32 n = cam->getNear();
  59. Array<Plane, Frustum::FP_COUNT>& planes = tiler->tiles1d[k].planes;
  60. const U i = k % Tiler::TILES_X_COUNT;
  61. const U j = k / Tiler::TILES_X_COUNT;
  62. // left
  63. a = Vec3((I(i) - I(Tiler::TILES_X_COUNT) / 2) * l6, 0.0, -n);
  64. b = a.cross(Vec3(0.0, 1.0, 0.0));
  65. b.normalize();
  66. planes[Frustum::FP_LEFT] = Plane(b, 0.0);
  67. // right
  68. a = Vec3((I(i) - I(Tiler::TILES_X_COUNT) / 2 + 1) * l6, 0.0, -n);
  69. b = Vec3(0.0, 1.0, 0.0).cross(a);
  70. b.normalize();
  71. planes[Frustum::FP_RIGHT] = Plane(b, 0.0);
  72. // bottom
  73. a = Vec3(0.0, (I(j) - I(Tiler::TILES_Y_COUNT) / 2) * o6, -n);
  74. b = Vec3(1.0, 0.0, 0.0).cross(a);
  75. b.normalize();
  76. planes[Frustum::FP_BOTTOM] = Plane(b, 0.0);
  77. // bottom
  78. a = Vec3(0.0, (I(j) - I(Tiler::TILES_Y_COUNT) / 2 + 1) * o6, -n);
  79. b = a.cross(Vec3(1.0, 0.0, 0.0));
  80. b.normalize();
  81. planes[Frustum::FP_TOP] = Plane(b, 0.0);
  82. }
  83. void update2Planes(const U k, const Vec2& planes)
  84. {
  85. U i = k % Tiler::TILES_X_COUNT;
  86. U j = k / Tiler::TILES_X_COUNT;
  87. Tiler::Tile& tile = tiler->tiles1d[k];
  88. // Calculate depth as you do it for the vertex position inside
  89. // the shaders
  90. F32 minZ = planes.y() / (planes.x() + (*pixels)[j][i][0]);
  91. F32 maxZ = planes.y() / (planes.x() + (*pixels)[j][i][1]);
  92. tile.planes[Frustum::FP_NEAR] = Plane(Vec3(0.0, 0.0, -1.0), minZ);
  93. tile.planes[Frustum::FP_FAR] = Plane(Vec3(0.0, 0.0, 1.0), -maxZ);
  94. }
  95. };
  96. typedef Array<UpdateTilesPlanesPerspectiveCameraJob, ThreadPool::MAX_THREADS>
  97. UpdateJobArray;
  98. //==============================================================================
  99. Tiler::Tiler()
  100. {}
  101. //==============================================================================
  102. Tiler::~Tiler()
  103. {}
  104. //==============================================================================
  105. void Tiler::init(Renderer* r_)
  106. {
  107. try
  108. {
  109. initInternal(r_);
  110. }
  111. catch(const std::exception& e)
  112. {
  113. throw ANKI_EXCEPTION("Failed to init tiler") << e;
  114. }
  115. }
  116. //==============================================================================
  117. void Tiler::initInternal(Renderer* r_)
  118. {
  119. r = r_;
  120. // Load the program
  121. std::string pps =
  122. "#define TILES_X_COUNT " + std::to_string(TILES_X_COUNT) + "\n"
  123. "#define TILES_Y_COUNT " + std::to_string(TILES_Y_COUNT) + "\n"
  124. "#define RENDERER_WIDTH " + std::to_string(r->getWidth()) + "\n"
  125. "#define RENDERER_HEIGHT " + std::to_string(r->getHeight()) + "\n";
  126. prog.load(ShaderProgramResource::createSrcCodeToCache(
  127. "shaders/TilerMinMax.glsl", pps.c_str()).c_str());
  128. depthMapUniform = &(prog->findUniformVariable("depthMap"));
  129. // Create FBO
  130. Renderer::createFai(TILES_X_COUNT, TILES_Y_COUNT, GL_RG32UI,
  131. GL_RG_INTEGER, GL_UNSIGNED_INT, fai);
  132. fai.setFiltering(Texture::TFT_NEAREST);
  133. fbo.create();
  134. fbo.setColorAttachments({&fai});
  135. if(!fbo.isComplete())
  136. {
  137. throw ANKI_EXCEPTION("FBO not complete");
  138. }
  139. // Create PBO
  140. pbo.create(GL_PIXEL_PACK_BUFFER,
  141. TILES_X_COUNT * TILES_Y_COUNT * 2 * sizeof(F32), nullptr);
  142. }
  143. //==============================================================================
  144. void Tiler::runMinMax(const Texture& depthMap)
  145. {
  146. // Issue the min/max job
  147. fbo.bind();
  148. GlStateSingleton::get().setViewport(0, 0, TILES_X_COUNT, TILES_Y_COUNT);
  149. r->clearAfterBindingFbo(GL_COLOR_BUFFER_BIT);
  150. prog->bind();
  151. depthMapUniform->set(depthMap);
  152. r->drawQuad();
  153. // Issue the async pixel read
  154. pbo.bind();
  155. glReadPixels(0, 0, TILES_X_COUNT, TILES_Y_COUNT, GL_RG_INTEGER,
  156. GL_UNSIGNED_INT, nullptr);
  157. pbo.unbind();
  158. }
  159. //==============================================================================
  160. void Tiler::updateTiles(Camera& cam)
  161. {
  162. //
  163. // Read the results from the minmax job
  164. //
  165. PixelArray pixels;
  166. pbo.read(&pixels[0][0]);
  167. //
  168. // Issue parallel jobs
  169. //
  170. UpdateJobArray jobs;
  171. U32 camTimestamp = cam.getFrustumable()->getFrustumableTimestamp();
  172. // Transform only the planes when:
  173. // - it is the same camera as before and
  174. // - the camera frustum have not changed
  175. Bool update4Planes =
  176. camTimestamp >= planes4UpdateTimestamp || prevCam != &cam;
  177. // Update the planes in parallel
  178. //
  179. ThreadPool& threadPool = ThreadPoolSingleton::get();
  180. switch(cam.getCameraType())
  181. {
  182. case Camera::CT_PERSPECTIVE:
  183. for(U i = 0; i < threadPool.getThreadsCount(); i++)
  184. {
  185. jobs[i].pixels = &pixels;
  186. jobs[i].tiler = this;
  187. jobs[i].cam = static_cast<PerspectiveCamera*>(&cam);
  188. jobs[i].frustumChanged = update4Planes;
  189. threadPool.assignNewJob(i, &jobs[i]);
  190. }
  191. break;
  192. default:
  193. ANKI_ASSERT(0 && "Unimplemented");
  194. break;
  195. }
  196. if(update4Planes)
  197. {
  198. planes4UpdateTimestamp = Timestamp::getTimestamp();
  199. }
  200. threadPool.waitForAllJobsToFinish();
  201. //
  202. // Misc
  203. //
  204. prevCam = &cam;
  205. }
  206. //==============================================================================
  207. Bool Tiler::testInternal(const CollisionShape& cs, const Tile& tile,
  208. const U startPlane) const
  209. {
  210. for(U j = startPlane; j < Frustum::FP_COUNT; j++)
  211. {
  212. if(cs.testPlane(tile.planesWSpace[j]) < 0.0)
  213. {
  214. return false;
  215. }
  216. }
  217. return true;
  218. }
  219. //==============================================================================
  220. Bool Tiler::test(const CollisionShape& cs, const U32 tileId,
  221. const Bool skipNearPlaneCheck) const
  222. {
  223. return testInternal(cs, tiles1d[tileId], (skipNearPlaneCheck) ? 1 : 0);
  224. }
  225. //==============================================================================
  226. Bool Tiler::testAll(const CollisionShape& cs,
  227. const Bool skipNearPlaneCheck) const
  228. {
  229. static_assert(Frustum::FP_NEAR == 0, "Frustum::FP_NEAR should be 0");
  230. U startPlane = (skipNearPlaneCheck) ? 1 : 0;
  231. for(const Tile& tile : tiles1d)
  232. {
  233. if(testInternal(cs, tile, startPlane))
  234. {
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. } // end namespace anki