modelAPI.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2019 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #include "modelAPI.h"
  24. #include "imageAPI.h"
  25. #include "drawAPI.h"
  26. #include "../render/model/Model.h"
  27. #include <limits>
  28. #define MUST_EXIST(OBJECT, METHOD) if (OBJECT.get() == nullptr) { throwError("The " #OBJECT " handle was null in " #METHOD "\n"); }
  29. namespace dsr {
  30. Model model_create() {
  31. return std::make_shared<ModelImpl>();
  32. }
  33. Model model_clone(const Model& model) {
  34. MUST_EXIST(model,model_clone);
  35. return std::make_shared<ModelImpl>(model->filter, model->partBuffer, model->positionBuffer);
  36. }
  37. void model_setFilter(const Model& model, Filter filter) {
  38. MUST_EXIST(model,model_setFilter);
  39. model->filter = filter;
  40. }
  41. Filter model_getFilter(const Model& model) {
  42. MUST_EXIST(model,model_getFilter);
  43. return model->filter;
  44. }
  45. bool model_exists(const Model& model) {
  46. return model.get() != nullptr;
  47. }
  48. int model_addEmptyPart(Model& model, const String &name) {
  49. MUST_EXIST(model,model_addEmptyPart);
  50. return model->addEmptyPart(name);
  51. }
  52. int model_getNumberOfParts(const Model& model) {
  53. MUST_EXIST(model,model_getNumberOfParts);
  54. return model->getNumberOfParts();
  55. }
  56. void model_setPartName(Model& model, int partIndex, const String &name) {
  57. MUST_EXIST(model,model_setPartName);
  58. model->setPartName(partIndex, name);
  59. }
  60. String model_getPartName(const Model& model, int partIndex) {
  61. MUST_EXIST(model,model_getPartName);
  62. return model->getPartName(partIndex);
  63. }
  64. int model_getNumberOfPoints(const Model& model) {
  65. MUST_EXIST(model,model_getNumberOfPoints);
  66. return model->getNumberOfPoints();
  67. }
  68. FVector3D model_getPoint(const Model& model, int pointIndex) {
  69. MUST_EXIST(model,model_getPoint);
  70. return model->getPoint(pointIndex);
  71. }
  72. void model_setPoint(Model& model, int pointIndex, const FVector3D& position) {
  73. MUST_EXIST(model,model_setPoint);
  74. model->setPoint(pointIndex, position);
  75. }
  76. int model_findPoint(const Model& model, const FVector3D &position, float threshold) {
  77. MUST_EXIST(model,model_findPoint);
  78. return model->findPoint(position, threshold);
  79. }
  80. int model_addPoint(const Model& model, const FVector3D &position) {
  81. MUST_EXIST(model,model_addPoint);
  82. return model->addPoint(position);
  83. }
  84. int model_addPointIfNeeded(Model& model, const FVector3D &position, float threshold) {
  85. MUST_EXIST(model,model_addPointIfNeeded);
  86. return model->addPointIfNeeded(position, threshold);
  87. }
  88. int model_getVertexPointIndex(const Model& model, int partIndex, int polygonIndex, int vertexIndex) {
  89. MUST_EXIST(model,model_getVertexPointIndex);
  90. return model->getVertexPointIndex(partIndex, polygonIndex, vertexIndex);
  91. }
  92. void model_setVertexPointIndex(Model& model, int partIndex, int polygonIndex, int vertexIndex, int pointIndex) {
  93. MUST_EXIST(model,model_setVertexPointIndex);
  94. model->setVertexPointIndex(partIndex, polygonIndex, vertexIndex, pointIndex);
  95. }
  96. FVector3D model_getVertexPosition(const Model& model, int partIndex, int polygonIndex, int vertexIndex) {
  97. MUST_EXIST(model,model_getVertexPosition);
  98. return model->getVertexPosition(partIndex, polygonIndex, vertexIndex);
  99. }
  100. FVector4D model_getVertexColor(const Model& model, int partIndex, int polygonIndex, int vertexIndex) {
  101. MUST_EXIST(model,model_getVertexColor);
  102. return model->getVertexColor(partIndex, polygonIndex, vertexIndex);
  103. }
  104. void model_setVertexColor(Model& model, int partIndex, int polygonIndex, int vertexIndex, const FVector4D& color) {
  105. MUST_EXIST(model,model_setVertexColor);
  106. model->setVertexColor(partIndex, polygonIndex, vertexIndex, color);
  107. }
  108. FVector4D model_getTexCoord(const Model& model, int partIndex, int polygonIndex, int vertexIndex) {
  109. MUST_EXIST(model,model_getTexCoord);
  110. return model->getTexCoord(partIndex, polygonIndex, vertexIndex);
  111. }
  112. void model_setTexCoord(Model& model, int partIndex, int polygonIndex, int vertexIndex, const FVector4D& texCoord) {
  113. MUST_EXIST(model,model_setTexCoord);
  114. model->setTexCoord(partIndex, polygonIndex, vertexIndex, texCoord);
  115. }
  116. int model_addTriangle(Model& model, int partIndex, int pointA, int pointB, int pointC) {
  117. MUST_EXIST(model,model_addTriangle);
  118. return model->addPolygon(Polygon(pointA, pointB, pointC), partIndex);
  119. }
  120. int model_addQuad(Model& model, int partIndex, int pointA, int pointB, int pointC, int pointD) {
  121. MUST_EXIST(model,model_addQuad);
  122. return model->addPolygon(Polygon(pointA, pointB, pointC, pointD), partIndex);
  123. }
  124. int model_getNumberOfPolygons(const Model& model, int partIndex) {
  125. MUST_EXIST(model,model_getNumberOfPolygons);
  126. return model->getNumberOfPolygons(partIndex);
  127. }
  128. int model_getPolygonVertexCount(const Model& model, int partIndex, int polygonIndex) {
  129. MUST_EXIST(model,model_getPolygonVertexCount);
  130. return model->getPolygonVertexCount(partIndex, polygonIndex);
  131. }
  132. ImageRgbaU8 model_getDiffuseMap(const Model& model, int partIndex) {
  133. MUST_EXIST(model,model_getDiffuseMap);
  134. return model->getDiffuseMap(partIndex);
  135. }
  136. void model_setDiffuseMap(Model& model, int partIndex, const ImageRgbaU8 &diffuseMap) {
  137. MUST_EXIST(model,model_setDiffuseMap);
  138. model->setDiffuseMap(diffuseMap, partIndex);
  139. }
  140. void model_setDiffuseMapByName(Model& model, int partIndex, ResourcePool &pool, const String &filename) {
  141. MUST_EXIST(model,model_setDiffuseMapByName);
  142. model->setDiffuseMapByName(pool, filename, partIndex);
  143. }
  144. ImageRgbaU8 model_getLightMap(Model& model, int partIndex) {
  145. MUST_EXIST(model,model_getLightMap);
  146. return model->getLightMap(partIndex);
  147. }
  148. void model_setLightMap(Model& model, int partIndex, const ImageRgbaU8 &lightMap) {
  149. MUST_EXIST(model,model_setLightMap);
  150. model->setLightMap(lightMap, partIndex);
  151. }
  152. void model_setLightMapByName(Model& model, int partIndex, ResourcePool &pool, const String &filename) {
  153. MUST_EXIST(model,model_setLightMapByName);
  154. model->setLightMapByName(pool, filename, partIndex);
  155. }
  156. // Single-threaded rendering for the simple cases where you just want it to work
  157. void model_render(const Model& model, const Transform3D &modelToWorldTransform, ImageRgbaU8& colorBuffer, ImageF32& depthBuffer, const Camera &camera) {
  158. if (model.get() != nullptr) {
  159. model->render((CommandQueue*)nullptr, colorBuffer, depthBuffer, modelToWorldTransform, camera);
  160. }
  161. }
  162. void model_renderDepth(const Model& model, const Transform3D &modelToWorldTransform, ImageF32& depthBuffer, const Camera &camera) {
  163. if (model.get() != nullptr) {
  164. model->renderDepth(depthBuffer, modelToWorldTransform, camera);
  165. }
  166. }
  167. void model_getBoundingBox(const Model& model, FVector3D& minimum, FVector3D& maximum) {
  168. MUST_EXIST(model,model_getBoundingBox);
  169. minimum = model->minBound;
  170. maximum = model->maxBound;
  171. }
  172. static const int cellSize = 16;
  173. struct DebugLine {
  174. int64_t x1, y1, x2, y2;
  175. ColorRgbaI32 color;
  176. DebugLine(int64_t x1, int64_t y1, int64_t x2, int64_t y2, const ColorRgbaI32& color)
  177. : x1(x1), y1(y1), x2(x2), y2(y2), color(color) {}
  178. };
  179. // Context for rendering multiple models at the same time for improved speed
  180. class RendererImpl {
  181. private:
  182. bool receiving = false; // Preventing version dependency by only allowing calls in the expected order
  183. ImageRgbaU8 colorBuffer; // The color image being rendered to
  184. ImageF32 depthBuffer; // Linear depth for isometric cameras, 1 / depth for perspective cameras
  185. ImageF32 depthGrid; // An occlusion grid of cellSize² cells representing the longest linear depth where something might be visible
  186. CommandQueue commandQueue; // Triangles to be drawn
  187. List<DebugLine> debugLines; // Additional lines to be drawn as an overlay for debugging occlusion
  188. int width = 0, height = 0, gridWidth = 0, gridHeight = 0;
  189. bool occluded = false;
  190. public:
  191. RendererImpl() {}
  192. void beginFrame(ImageRgbaU8& colorBuffer, ImageF32& depthBuffer) {
  193. if (this->receiving) {
  194. throwError("Called renderer_begin on the same renderer twice without ending the previous batch!\n");
  195. }
  196. this->receiving = true;
  197. this->colorBuffer = colorBuffer;
  198. this->depthBuffer = depthBuffer;
  199. if (image_exists(this->colorBuffer)) {
  200. this->width = image_getWidth(this->colorBuffer);
  201. this->height = image_getHeight(this->colorBuffer);
  202. } else if (image_exists(this->depthBuffer)) {
  203. this->width = image_getWidth(this->depthBuffer);
  204. this->height = image_getHeight(this->depthBuffer);
  205. }
  206. this->gridWidth = (this->width + (cellSize - 1)) / cellSize;
  207. this->gridHeight = (this->height + (cellSize - 1)) / cellSize;
  208. this->occluded = false;
  209. }
  210. bool pointInsideOfEdge(const LVector2D &edgeA, const LVector2D &edgeB, const LVector2D &point) {
  211. LVector2D edgeDirection = LVector2D(edgeB.y - edgeA.y, edgeA.x - edgeB.x);
  212. LVector2D relativePosition = point - edgeA;
  213. int64_t dotProduct = (edgeDirection.x * relativePosition.x) + (edgeDirection.y * relativePosition.y);
  214. return dotProduct <= 0;
  215. }
  216. // Returns true iff the point is inside of the hull
  217. // convexHullCorners from 0 to cornerCount-1 must be sorted clockwise and may not include any concave corners
  218. bool pointInsideOfHull(const ProjectedPoint* convexHullCorners, int cornerCount, const LVector2D &point) {
  219. for (int c = 0; c < cornerCount; c++) {
  220. int nc = c + 1;
  221. if (nc == cornerCount) {
  222. nc = 0;
  223. }
  224. if (!pointInsideOfEdge(convexHullCorners[c].flat, convexHullCorners[nc].flat, point)) {
  225. // Outside of one edge, not inside
  226. return false;
  227. }
  228. }
  229. // Passed all edge tests
  230. return true;
  231. }
  232. // Returns true iff all corners of the rectangle are inside of the hull
  233. bool rectangleInsideOfHull(const ProjectedPoint* convexHullCorners, int cornerCount, const IRect &rectangle) {
  234. return pointInsideOfHull(convexHullCorners, cornerCount, LVector2D(rectangle.left(), rectangle.top()))
  235. && pointInsideOfHull(convexHullCorners, cornerCount, LVector2D(rectangle.right(), rectangle.top()))
  236. && pointInsideOfHull(convexHullCorners, cornerCount, LVector2D(rectangle.left(), rectangle.bottom()))
  237. && pointInsideOfHull(convexHullCorners, cornerCount, LVector2D(rectangle.right(), rectangle.bottom()));
  238. }
  239. IRect getOuterCellBound(const IRect &pixelBound) {
  240. int minCellX = pixelBound.left() / cellSize;
  241. int maxCellX = pixelBound.right() / cellSize + 1;
  242. int minCellY = pixelBound.top() / cellSize;
  243. int maxCellY = pixelBound.bottom() / cellSize + 1;
  244. if (minCellX < 0) { minCellX = 0; }
  245. if (minCellY < 0) { minCellY = 0; }
  246. if (maxCellX > this->gridWidth) { maxCellX = this->gridWidth; }
  247. if (maxCellY > this->gridHeight) { maxCellY = this->gridHeight; }
  248. return IRect(minCellX, minCellY, maxCellX - minCellX, maxCellY - minCellY);
  249. }
  250. // Called before occluding so that the grid is initialized once when used and skipped when not used
  251. void prepareForOcclusion() {
  252. if (!this->occluded) {
  253. // Allocate the grid if a sufficiently large one does not already exist
  254. if (!(image_exists(this->depthGrid) && image_getWidth(this->depthGrid) >= gridWidth && image_getHeight(this->depthGrid) >= gridHeight)) {
  255. this->depthGrid = image_create_F32(gridWidth, gridHeight);
  256. }
  257. // Use inifnite depth in camera space
  258. image_fill(this->depthGrid, std::numeric_limits<float>::infinity());
  259. }
  260. this->occluded = true;
  261. }
  262. // If any occluder has been used during this pass, all triangles in the buffer will be filtered based using depthGrid
  263. void completeOcclusion() {
  264. if (this->occluded) {
  265. for (int t = this->commandQueue.buffer.length() - 1; t >= 0; t--) {
  266. bool anyVisible = false;
  267. ITriangle2D triangle = this->commandQueue.buffer[t].triangle;
  268. IRect outerBound = getOuterCellBound(triangle.wholeBound);
  269. for (int cellY = outerBound.top(); cellY < outerBound.bottom(); cellY++) {
  270. for (int cellX = outerBound.left(); cellX < outerBound.right(); cellX++) {
  271. // TODO: Optimize access using SafePointer iteration
  272. float backgroundDepth = image_readPixel_clamp(this->depthGrid, cellX, cellY);
  273. float triangleDepth = triangle.position[0].cs.z;
  274. replaceWithSmaller(triangleDepth, triangle.position[1].cs.z);
  275. replaceWithSmaller(triangleDepth, triangle.position[2].cs.z);
  276. if (triangleDepth < backgroundDepth + 0.001) {
  277. anyVisible = true;
  278. }
  279. }
  280. }
  281. if (!anyVisible) {
  282. // TODO: Make triangle swapping work so that the list can be sorted
  283. this->commandQueue.buffer[t].occluded = true;
  284. }
  285. }
  286. }
  287. }
  288. void occludeFromSortedHull(const ProjectedPoint* convexHullCorners, int cornerCount, const IRect& pixelBound) {
  289. // Loop over the outer bound
  290. if (pixelBound.width() > cellSize && pixelBound.height() > cellSize) {
  291. float distance = 0.0f;
  292. for (int c = 0; c < cornerCount; c++) {
  293. replaceWithLarger(distance, convexHullCorners[c].cs.z);
  294. }
  295. // Loop over all cells within the bound
  296. IRect outerBound = getOuterCellBound(pixelBound);
  297. for (int cellY = outerBound.top(); cellY < outerBound.bottom(); cellY++) {
  298. for (int cellX = outerBound.left(); cellX < outerBound.right(); cellX++) {
  299. IRect pixelRegion = IRect(cellX * cellSize, cellY * cellSize, cellSize, cellSize);
  300. IRect subPixelRegion = pixelRegion * constants::unitsPerPixel;
  301. if (rectangleInsideOfHull(convexHullCorners, cornerCount, subPixelRegion)) {
  302. float oldDepth = image_readPixel_clamp(this->depthGrid, cellX, cellY);
  303. if (distance < oldDepth) {
  304. image_writePixel(this->depthGrid, cellX, cellY, distance);
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }
  311. IRect getPixelBoundFromProjection(const ProjectedPoint* convexHullCorners, int cornerCount) {
  312. IRect result = IRect(convexHullCorners[0].flat.x / constants::unitsPerPixel, convexHullCorners[0].flat.y / constants::unitsPerPixel, 1, 1);
  313. for (int p = 1; p < cornerCount; p++) {
  314. result = IRect::merge(result, IRect(convexHullCorners[p].flat.x / constants::unitsPerPixel, convexHullCorners[p].flat.y / constants::unitsPerPixel, 1, 1));
  315. }
  316. return result;
  317. }
  318. void occludeFromSortedHull(const ProjectedPoint* convexHullCorners, int cornerCount) {
  319. occludeFromSortedHull(convexHullCorners, cornerCount, getPixelBoundFromProjection(convexHullCorners, cornerCount));
  320. }
  321. void occludeFromExistingTriangles() {
  322. if (!this->receiving) {
  323. throwError("Cannot call renderer_occludeFromExistingTriangles without first calling renderer_begin!\n");
  324. }
  325. prepareForOcclusion();
  326. // Generate a depth grid to remove many small triangles behind larger triangles
  327. // This will leave triangles along seams but at least begin to remove the worst unwanted drawing
  328. for (int t = 0; t < this->commandQueue.buffer.length(); t++) {
  329. // Get the current triangle from the queue
  330. Filter filter = this->commandQueue.buffer[t].filter;
  331. if (filter == Filter::Solid) {
  332. ITriangle2D triangle = this->commandQueue.buffer[t].triangle;
  333. occludeFromSortedHull(triangle.position, 3, triangle.wholeBound);
  334. }
  335. }
  336. }
  337. bool counterClockwise(const ProjectedPoint& p, const ProjectedPoint& q, const ProjectedPoint& r) {
  338. return (q.flat.y - p.flat.y) * (r.flat.x - q.flat.x) - (q.flat.x - p.flat.x) * (r.flat.y - q.flat.y) < 0;
  339. }
  340. // outputHullCorners must be at least as big as inputHullCorners, so that it can hold the worst case output size.
  341. // Instead of not allowing less than three points, it copies the input as output when it happens to reduce pre-conditions.
  342. void jarvisConvexHullAlgorithm(ProjectedPoint* outputHullCorners, int& outputCornerCount, const ProjectedPoint* inputHullCorners, int inputCornerCount) {
  343. if (inputCornerCount < 3) {
  344. outputCornerCount = inputCornerCount;
  345. for (int p = 0; p < inputCornerCount; p++) {
  346. outputHullCorners[p] = inputHullCorners[p];
  347. }
  348. } else {
  349. int l = 0;
  350. outputCornerCount = 0;
  351. for (int i = 1; i < inputCornerCount; i++) {
  352. if (inputHullCorners[i].flat.x < inputHullCorners[l].flat.x) {
  353. l = i;
  354. }
  355. }
  356. int p = l;
  357. do {
  358. if (outputCornerCount >= inputCornerCount) {
  359. // Prevent getting stuck in an infinite loop from overflow
  360. return;
  361. }
  362. outputHullCorners[outputCornerCount] = inputHullCorners[p]; outputCornerCount++;
  363. int q = (p + 1) % inputCornerCount;
  364. for (int i = 0; i < inputCornerCount; i++) {
  365. if (counterClockwise(inputHullCorners[p], inputHullCorners[i], inputHullCorners[q])) {
  366. q = i;
  367. }
  368. }
  369. p = q;
  370. } while (p != l);
  371. }
  372. }
  373. // Transform and project the corners of a hull, so that the output can be given to the convex hull algorithm and used for occluding
  374. // Returns true if occluder culling passed, which may skip occluders that could have been visible
  375. bool projectHull(ProjectedPoint* outputHullCorners, const FVector3D* inputHullCorners, int cornerCount, const Transform3D &modelToWorldTransform, const Camera &camera) {
  376. for (int p = 0; p < cornerCount; p++) {
  377. FVector3D worldPoint = modelToWorldTransform.transformPoint(inputHullCorners[p]);
  378. FVector3D cameraPoint = camera.worldToCamera(worldPoint);
  379. FVector3D narrowPoint = cameraPoint * FVector3D(0.5f, 0.5f, 1.0f);
  380. for (int s = 0; s < camera.cullFrustum.getPlaneCount(); s++) {
  381. FPlane3D plane = camera.cullFrustum.getPlane(s);
  382. if (!plane.inside(narrowPoint)) {
  383. return false;
  384. }
  385. }
  386. outputHullCorners[p] = camera.cameraToScreen(cameraPoint);
  387. }
  388. return true;
  389. }
  390. #define GENERATE_BOX_CORNERS(TARGET, MIN, MAX) \
  391. TARGET[0] = FVector3D(MIN.x, MIN.y, MIN.z); \
  392. TARGET[1] = FVector3D(MIN.x, MIN.y, MAX.z); \
  393. TARGET[2] = FVector3D(MIN.x, MAX.y, MIN.z); \
  394. TARGET[3] = FVector3D(MIN.x, MAX.y, MAX.z); \
  395. TARGET[4] = FVector3D(MAX.x, MIN.y, MIN.z); \
  396. TARGET[5] = FVector3D(MAX.x, MIN.y, MAX.z); \
  397. TARGET[6] = FVector3D(MAX.x, MAX.y, MIN.z); \
  398. TARGET[7] = FVector3D(MAX.x, MAX.y, MAX.z);
  399. // Fills the occlusion grid using the box, so that things behind it can skip rendering
  400. void occludeFromBox(const FVector3D& minimum, const FVector3D& maximum, const Transform3D &modelToWorldTransform, const Camera &camera, bool debugSilhouette) {
  401. if (!this->receiving) {
  402. throwError("Cannot call renderer_occludeFromBox without first calling renderer_begin!\n");
  403. }
  404. prepareForOcclusion();
  405. static const int pointCount = 8;
  406. FVector3D localPoints[pointCount];
  407. ProjectedPoint projections[pointCount];
  408. ProjectedPoint edgeCorners[pointCount];
  409. GENERATE_BOX_CORNERS(localPoints, minimum, maximum)
  410. if (projectHull(projections, localPoints, 8, modelToWorldTransform, camera)) {
  411. // Get a 2D convex hull from the projected corners
  412. int edgeCornerCount = 0;
  413. jarvisConvexHullAlgorithm(edgeCorners, edgeCornerCount, projections, 8);
  414. occludeFromSortedHull(edgeCorners, edgeCornerCount);
  415. // Allow saving the 2D silhouette for debugging
  416. if (debugSilhouette) {
  417. for (int p = 0; p < edgeCornerCount; p++) {
  418. int q = (p + 1) % edgeCornerCount;
  419. if (projections[p].cs.z > camera.nearClip) {
  420. this->debugLines.pushConstruct(
  421. edgeCorners[p].flat.x / constants::unitsPerPixel, edgeCorners[p].flat.y / constants::unitsPerPixel,
  422. edgeCorners[q].flat.x / constants::unitsPerPixel, edgeCorners[q].flat.y / constants::unitsPerPixel,
  423. ColorRgbaI32(0, 255, 255, 255)
  424. );
  425. }
  426. }
  427. }
  428. }
  429. }
  430. // Occlusion test for whole model bounds
  431. // Because outerBound gives negative regions when outside of the picture, it can also be used as a rough culling test
  432. bool isHullOccluded(ProjectedPoint* outputHullCorners, const FVector3D* inputHullCorners, int cornerCount, const Transform3D &modelToWorldTransform, const Camera &camera) {
  433. for (int p = 0; p < cornerCount; p++) {
  434. FVector3D worldPoint = modelToWorldTransform.transformPoint(inputHullCorners[p]);
  435. FVector3D cameraPoint = camera.worldToCamera(worldPoint);
  436. outputHullCorners[p] = camera.cameraToScreen(cameraPoint);
  437. }
  438. IRect pixelBound = getPixelBoundFromProjection(outputHullCorners, cornerCount);
  439. float closestDistance = std::numeric_limits<float>::infinity();
  440. for (int c = 0; c < cornerCount; c++) {
  441. replaceWithSmaller(closestDistance, outputHullCorners[c].cs.z);
  442. }
  443. // Loop over all cells within the bound
  444. IRect outerBound = getOuterCellBound(pixelBound);
  445. for (int cellY = outerBound.top(); cellY < outerBound.bottom(); cellY++) {
  446. for (int cellX = outerBound.left(); cellX < outerBound.right(); cellX++) {
  447. if (closestDistance < image_readPixel_clamp(this->depthGrid, cellX, cellY)) {
  448. return false;
  449. }
  450. }
  451. }
  452. return true;
  453. }
  454. // Checks if the box from minimum to maximum in object space is fully occluded when seen by the camera
  455. // Must be the same camera as when occluders filled the grid with occlusion depth
  456. bool isBoxOccluded(const FVector3D &minimum, const FVector3D &maximum, const Transform3D &modelToWorldTransform, const Camera &camera) {
  457. if (!this->receiving) {
  458. throwError("Cannot call renderer_isBoxVisible without first calling renderer_begin and giving occluder shapes to the pass!\n");
  459. }
  460. FVector3D corners[8];
  461. GENERATE_BOX_CORNERS(corners, minimum, maximum)
  462. ProjectedPoint projections[8];
  463. return isHullOccluded(projections, corners, 8, modelToWorldTransform, camera);
  464. }
  465. void giveTask(const Model& model, const Transform3D &modelToWorldTransform, const Camera &camera) {
  466. if (!this->receiving) {
  467. throwError("Cannot call renderer_giveTask before renderer_begin!\n");
  468. }
  469. // If occluders are present, check if the model's bound is visible
  470. if (this->occluded) {
  471. FVector3D minimum, maximum;
  472. model_getBoundingBox(model, minimum, maximum);
  473. if (isBoxOccluded(minimum, maximum, modelToWorldTransform, camera)) {
  474. // Skip projection of triangles if the whole bounding box is already behind occluders
  475. return;
  476. }
  477. }
  478. // TODO: Make an algorithm for selecting if the model should be queued as an instance or triangulated at once
  479. // An extra argument may choose to force an instance directly into the command queue
  480. // Because the model is being borrowed for vertex animation
  481. // To prevent the command queue from getting full hold as much as possible in a sorted list of instances
  482. // When the command queue is full, the solid instances will be drawn front to back before filtered is drawn back to front
  483. model->render(&this->commandQueue, this->colorBuffer, this->depthBuffer, modelToWorldTransform, camera);
  484. }
  485. void endFrame(bool debugWireframe) {
  486. if (!this->receiving) {
  487. throwError("Called renderer_end without renderer_begin!\n");
  488. }
  489. this->receiving = false;
  490. // Mark occluded triangles to prevent them from being rendered
  491. completeOcclusion();
  492. this->commandQueue.execute(IRect::FromSize(this->width, this->height));
  493. if (image_exists(this->colorBuffer)) {
  494. // Debug drawn triangles
  495. if (debugWireframe) {
  496. /*if (image_exists(this->depthGrid)) {
  497. for (int cellY = 0; cellY < this->gridHeight; cellY++) {
  498. for (int cellX = 0; cellX < this->gridWidth; cellX++) {
  499. float depth = image_readPixel_clamp(this->depthGrid, cellX, cellY);
  500. if (depth < std::numeric_limits<float>::infinity()) {
  501. int intensity = depth;
  502. draw_rectangle(this->colorBuffer, IRect(cellX * cellSize + 4, cellY * cellSize + 4, cellSize - 8, cellSize - 8), ColorRgbaI32(intensity, intensity, 0, 255));
  503. }
  504. }
  505. }
  506. }*/
  507. for (int t = 0; t < this->commandQueue.buffer.length(); t++) {
  508. if (!this->commandQueue.buffer[t].occluded) {
  509. ITriangle2D *triangle = &(this->commandQueue.buffer[t].triangle);
  510. draw_line(this->colorBuffer,
  511. triangle->position[0].flat.x / constants::unitsPerPixel, triangle->position[0].flat.y / constants::unitsPerPixel,
  512. triangle->position[1].flat.x / constants::unitsPerPixel, triangle->position[1].flat.y / constants::unitsPerPixel,
  513. ColorRgbaI32(255, 255, 255, 255)
  514. );
  515. draw_line(this->colorBuffer,
  516. triangle->position[1].flat.x / constants::unitsPerPixel, triangle->position[1].flat.y / constants::unitsPerPixel,
  517. triangle->position[2].flat.x / constants::unitsPerPixel, triangle->position[2].flat.y / constants::unitsPerPixel,
  518. ColorRgbaI32(255, 255, 255, 255)
  519. );
  520. draw_line(this->colorBuffer,
  521. triangle->position[2].flat.x / constants::unitsPerPixel, triangle->position[2].flat.y / constants::unitsPerPixel,
  522. triangle->position[0].flat.x / constants::unitsPerPixel, triangle->position[0].flat.y / constants::unitsPerPixel,
  523. ColorRgbaI32(255, 255, 255, 255)
  524. );
  525. }
  526. }
  527. }
  528. // Debug anything else added to debugLines
  529. for (int l = 0; l < this->debugLines.length(); l++) {
  530. draw_line(this->colorBuffer, this->debugLines[l].x1, this->debugLines[l].y1, this->debugLines[l].x2, this->debugLines[l].y2, this->debugLines[l].color);
  531. }
  532. this->debugLines.clear();
  533. }
  534. this->commandQueue.clear();
  535. }
  536. void occludeFromTopRows(const Camera &camera) {
  537. // Make sure that the depth grid exists with the correct dimensions.
  538. this->prepareForOcclusion();
  539. if (!this->receiving) {
  540. throwError("Cannot call renderer_occludeFromTopRows without first calling renderer_begin!\n");
  541. }
  542. if (!image_exists(this->depthBuffer)) {
  543. throwError("Cannot call renderer_occludeFromTopRows without having given a depth buffer in renderer_begin!\n");
  544. }
  545. SafePointer<float> depthRow = image_getSafePointer(this->depthBuffer);
  546. int depthStride = image_getStride(this->depthBuffer);
  547. SafePointer<float> gridRow = image_getSafePointer(this->depthGrid);
  548. int gridStride = image_getStride(this->depthGrid);
  549. if (camera.perspective) {
  550. // Perspective case using 1/depth for the depth buffer.
  551. for (int y = 0; y < this->height; y += cellSize) {
  552. SafePointer<float> gridPixel = gridRow;
  553. SafePointer<float> depthPixel = depthRow;
  554. int x = 0;
  555. int right = cellSize - 1;
  556. float maxInvDistance;
  557. // Scan bottom row of whole cell width
  558. for (int gridX = 0; gridX < this->gridWidth; gridX++) {
  559. maxInvDistance = std::numeric_limits<float>::infinity();
  560. if (right >= this->width) { right = this->width; }
  561. while (x < right) {
  562. float newInvDistance = *depthPixel;
  563. if (newInvDistance < maxInvDistance) { maxInvDistance = newInvDistance; }
  564. depthPixel += 1;
  565. x += 1;
  566. }
  567. float maxDistance = 1.0f / maxInvDistance;
  568. float oldDistance = *gridPixel;
  569. if (maxDistance < oldDistance) {
  570. *gridPixel = maxDistance;
  571. }
  572. gridPixel += 1;
  573. right += cellSize;
  574. }
  575. // Go to the next grid row
  576. depthRow.increaseBytes(depthStride * cellSize);
  577. gridRow.increaseBytes(gridStride);
  578. }
  579. } else {
  580. // Orthogonal case where linear depth is used for both grid and depth buffer.
  581. // TODO: Create test cases for many ways to use occlusion, even these strange cases like isometric occlusion where plain culling does not leave many occluded models.
  582. for (int y = 0; y < this->height; y += cellSize) {
  583. SafePointer<float> gridPixel = gridRow;
  584. SafePointer<float> depthPixel = depthRow;
  585. int x = 0;
  586. int right = cellSize - 1;
  587. float maxDistance;
  588. // Scan bottom row of whole cell width
  589. for (int gridX = 0; gridX < this->gridWidth; gridX++) {
  590. maxDistance = 0.0f;
  591. if (right >= this->width) { right = this->width; }
  592. while (x < right) {
  593. float newDistance = *depthPixel;
  594. if (newDistance > maxDistance) { maxDistance = newDistance; }
  595. depthPixel += 1;
  596. x += 1;
  597. }
  598. float oldDistance = *gridPixel;
  599. if (maxDistance < oldDistance) {
  600. *gridPixel = maxDistance;
  601. }
  602. gridPixel += 1;
  603. right += cellSize;
  604. }
  605. // Go to the next grid row
  606. depthRow.increaseBytes(depthStride * cellSize);
  607. gridRow.increaseBytes(gridStride);
  608. }
  609. }
  610. }
  611. };
  612. Renderer renderer_create() {
  613. return std::make_shared<RendererImpl>();
  614. }
  615. bool renderer_exists(const Renderer& renderer) {
  616. return renderer.get() != nullptr;
  617. }
  618. void renderer_begin(Renderer& renderer, ImageRgbaU8& colorBuffer, ImageF32& depthBuffer) {
  619. MUST_EXIST(renderer,renderer_begin);
  620. renderer->beginFrame(colorBuffer, depthBuffer);
  621. }
  622. // TODO: Synchronous setting
  623. // * Asynchronous (default)
  624. // Only works on models that are locked from further editing
  625. // Locked models can also be safely pooled for reuse then (ResourcePool)
  626. // * Synced (for animation)
  627. // Dispatch triangles directly to the command queue so that the current state of the model is captured
  628. // This allow rendering many instances using the same model at different times
  629. // Enabling vertex light, reflection maps and bone animation
  630. void renderer_giveTask(Renderer& renderer, const Model& model, const Transform3D &modelToWorldTransform, const Camera &camera) {
  631. MUST_EXIST(renderer,renderer_giveTask);
  632. if (model.get() != nullptr) {
  633. renderer->giveTask(model, modelToWorldTransform, camera);
  634. }
  635. }
  636. void renderer_occludeFromBox(Renderer& renderer, const FVector3D& minimum, const FVector3D& maximum, const Transform3D &modelToWorldTransform, const Camera &camera, bool debugSilhouette) {
  637. MUST_EXIST(renderer,renderer_occludeFromBox);
  638. renderer->occludeFromBox(minimum, maximum, modelToWorldTransform, camera, debugSilhouette);
  639. }
  640. void renderer_occludeFromExistingTriangles(Renderer& renderer) {
  641. MUST_EXIST(renderer,renderer_optimize);
  642. renderer->occludeFromExistingTriangles();
  643. }
  644. void renderer_occludeFromTopRows(Renderer& renderer, const Camera &camera) {
  645. MUST_EXIST(renderer,renderer_occludeFromTopRows);
  646. renderer->occludeFromTopRows(camera);
  647. }
  648. bool renderer_isBoxVisible(Renderer& renderer, const FVector3D &minimum, const FVector3D &maximum, const Transform3D &modelToWorldTransform, const Camera &camera) {
  649. MUST_EXIST(renderer,renderer_isBoxVisible);
  650. return !(renderer->isBoxOccluded(minimum, maximum, modelToWorldTransform, camera));
  651. }
  652. void renderer_end(Renderer& renderer, bool debugWireframe) {
  653. MUST_EXIST(renderer,renderer_end);
  654. renderer->endFrame(debugWireframe);
  655. }
  656. }