raycast_occlusion_cull.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. /**************************************************************************/
  2. /* raycast_occlusion_cull.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "raycast_occlusion_cull.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/object/worker_thread_pool.h"
  33. #include "core/templates/local_vector.h"
  34. #ifdef __SSE2__
  35. #include <pmmintrin.h>
  36. #endif
  37. RaycastOcclusionCull *RaycastOcclusionCull::raycast_singleton = nullptr;
  38. void RaycastOcclusionCull::RaycastHZBuffer::clear() {
  39. HZBuffer::clear();
  40. if (camera_rays_unaligned_buffer) {
  41. memfree(camera_rays_unaligned_buffer);
  42. camera_rays_unaligned_buffer = nullptr;
  43. camera_rays = nullptr;
  44. }
  45. camera_ray_masks.clear();
  46. camera_rays_tile_count = 0;
  47. tile_grid_size = Size2i();
  48. }
  49. void RaycastOcclusionCull::RaycastHZBuffer::resize(const Size2i &p_size) {
  50. if (p_size == Size2i()) {
  51. clear();
  52. return;
  53. }
  54. if (!sizes.is_empty() && p_size == sizes[0]) {
  55. return; // Size didn't change
  56. }
  57. HZBuffer::resize(p_size);
  58. tile_grid_size = Size2i(Math::ceil(p_size.x / (float)TILE_SIZE), Math::ceil(p_size.y / (float)TILE_SIZE));
  59. camera_rays_tile_count = tile_grid_size.x * tile_grid_size.y;
  60. if (camera_rays_unaligned_buffer) {
  61. memfree(camera_rays_unaligned_buffer);
  62. }
  63. const int alignment = 64; // Embree requires ray packets to be 64-aligned
  64. camera_rays_unaligned_buffer = (uint8_t *)memalloc(camera_rays_tile_count * sizeof(CameraRayTile) + alignment);
  65. camera_rays = (CameraRayTile *)(camera_rays_unaligned_buffer + alignment - (((uint64_t)camera_rays_unaligned_buffer) % alignment));
  66. camera_ray_masks.resize(camera_rays_tile_count * TILE_RAYS);
  67. memset(camera_ray_masks.ptr(), ~0, camera_rays_tile_count * TILE_RAYS * sizeof(uint32_t));
  68. }
  69. void RaycastOcclusionCull::RaycastHZBuffer::update_camera_rays(const Transform3D &p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal) {
  70. CameraRayThreadData td;
  71. td.thread_count = WorkerThreadPool::get_singleton()->get_thread_count();
  72. td.z_near = p_cam_projection.get_z_near();
  73. td.z_far = p_cam_projection.get_z_far() * 1.05f;
  74. td.camera_pos = p_cam_transform.origin;
  75. td.camera_dir = -p_cam_transform.basis.get_column(2);
  76. td.camera_orthogonal = p_cam_orthogonal;
  77. // Calculate the world coordinates of the viewport.
  78. Vector2 viewport_half = p_cam_projection.get_viewport_half_extents();
  79. td.pixel_corner = p_cam_transform.xform(Vector3(-viewport_half.x, -viewport_half.y, -p_cam_projection.get_z_near()));
  80. Vector3 top_corner_world = p_cam_transform.xform(Vector3(-viewport_half.x, viewport_half.y, -p_cam_projection.get_z_near()));
  81. Vector3 left_corner_world = p_cam_transform.xform(Vector3(viewport_half.x, -viewport_half.y, -p_cam_projection.get_z_near()));
  82. td.pixel_u_interp = left_corner_world - td.pixel_corner;
  83. td.pixel_v_interp = top_corner_world - td.pixel_corner;
  84. debug_tex_range = td.z_far;
  85. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RaycastHZBuffer::_camera_rays_threaded, &td, td.thread_count, -1, true, SNAME("RaycastOcclusionCullUpdateCamera"));
  86. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  87. }
  88. void RaycastOcclusionCull::RaycastHZBuffer::_camera_rays_threaded(uint32_t p_thread, const CameraRayThreadData *p_data) {
  89. uint32_t total_tiles = camera_rays_tile_count;
  90. uint32_t total_threads = p_data->thread_count;
  91. uint32_t from = p_thread * total_tiles / total_threads;
  92. uint32_t to = (p_thread + 1 == total_threads) ? total_tiles : ((p_thread + 1) * total_tiles / total_threads);
  93. _generate_camera_rays(p_data, from, to);
  94. }
  95. void RaycastOcclusionCull::RaycastHZBuffer::_generate_camera_rays(const CameraRayThreadData *p_data, int p_from, int p_to) {
  96. const Size2i &buffer_size = sizes[0];
  97. for (int i = p_from; i < p_to; i++) {
  98. CameraRayTile &tile = camera_rays[i];
  99. int tile_x = (i % tile_grid_size.x) * TILE_SIZE;
  100. int tile_y = (i / tile_grid_size.x) * TILE_SIZE;
  101. for (int j = 0; j < TILE_RAYS; j++) {
  102. int x = tile_x + j % TILE_SIZE;
  103. int y = tile_y + j / TILE_SIZE;
  104. float u = (float(x) + 0.5f) / buffer_size.x;
  105. float v = (float(y) + 0.5f) / buffer_size.y;
  106. Vector3 pixel_pos = p_data->pixel_corner + u * p_data->pixel_u_interp + v * p_data->pixel_v_interp;
  107. tile.ray.tnear[j] = p_data->z_near;
  108. Vector3 dir;
  109. if (p_data->camera_orthogonal) {
  110. dir = p_data->camera_dir;
  111. tile.ray.org_x[j] = pixel_pos.x - dir.x * p_data->z_near;
  112. tile.ray.org_y[j] = pixel_pos.y - dir.y * p_data->z_near;
  113. tile.ray.org_z[j] = pixel_pos.z - dir.z * p_data->z_near;
  114. } else {
  115. dir = (pixel_pos - p_data->camera_pos).normalized();
  116. tile.ray.org_x[j] = p_data->camera_pos.x;
  117. tile.ray.org_y[j] = p_data->camera_pos.y;
  118. tile.ray.org_z[j] = p_data->camera_pos.z;
  119. tile.ray.tnear[j] /= dir.dot(p_data->camera_dir);
  120. }
  121. tile.ray.dir_x[j] = dir.x;
  122. tile.ray.dir_y[j] = dir.y;
  123. tile.ray.dir_z[j] = dir.z;
  124. tile.ray.tfar[j] = p_data->z_far;
  125. tile.ray.time[j] = 0.0f;
  126. tile.ray.flags[j] = 0;
  127. tile.ray.mask[j] = ~0U;
  128. tile.hit.geomID[j] = RTC_INVALID_GEOMETRY_ID;
  129. }
  130. }
  131. }
  132. void RaycastOcclusionCull::RaycastHZBuffer::sort_rays(const Vector3 &p_camera_dir, bool p_orthogonal) {
  133. ERR_FAIL_COND(is_empty());
  134. Size2i buffer_size = sizes[0];
  135. for (int i = 0; i < tile_grid_size.y; i++) {
  136. for (int j = 0; j < tile_grid_size.x; j++) {
  137. for (int tile_i = 0; tile_i < TILE_SIZE; tile_i++) {
  138. for (int tile_j = 0; tile_j < TILE_SIZE; tile_j++) {
  139. int x = j * TILE_SIZE + tile_j;
  140. int y = i * TILE_SIZE + tile_i;
  141. if (x >= buffer_size.x || y >= buffer_size.y) {
  142. continue;
  143. }
  144. int k = tile_i * TILE_SIZE + tile_j;
  145. int tile_index = i * tile_grid_size.x + j;
  146. mips[0][y * buffer_size.x + x] = camera_rays[tile_index].ray.tfar[k];
  147. }
  148. }
  149. }
  150. }
  151. }
  152. RaycastOcclusionCull::RaycastHZBuffer::~RaycastHZBuffer() {
  153. if (camera_rays_unaligned_buffer) {
  154. memfree(camera_rays_unaligned_buffer);
  155. }
  156. }
  157. ////////////////////////////////////////////////////////
  158. bool RaycastOcclusionCull::is_occluder(RID p_rid) {
  159. return occluder_owner.owns(p_rid);
  160. }
  161. RID RaycastOcclusionCull::occluder_allocate() {
  162. return occluder_owner.allocate_rid();
  163. }
  164. void RaycastOcclusionCull::occluder_initialize(RID p_occluder) {
  165. Occluder *occluder = memnew(Occluder);
  166. occluder_owner.initialize_rid(p_occluder, occluder);
  167. }
  168. void RaycastOcclusionCull::occluder_set_mesh(RID p_occluder, const PackedVector3Array &p_vertices, const PackedInt32Array &p_indices) {
  169. Occluder *occluder = occluder_owner.get_or_null(p_occluder);
  170. ERR_FAIL_NULL(occluder);
  171. occluder->vertices = p_vertices;
  172. occluder->indices = p_indices;
  173. for (const InstanceID &E : occluder->users) {
  174. RID scenario_rid = E.scenario;
  175. RID instance_rid = E.instance;
  176. ERR_CONTINUE(!scenarios.has(scenario_rid));
  177. Scenario &scenario = scenarios[scenario_rid];
  178. ERR_CONTINUE(!scenario.instances.has(instance_rid));
  179. if (!scenario.dirty_instances.has(instance_rid)) {
  180. scenario.dirty_instances.insert(instance_rid);
  181. scenario.dirty_instances_array.push_back(instance_rid);
  182. }
  183. }
  184. }
  185. void RaycastOcclusionCull::free_occluder(RID p_occluder) {
  186. Occluder *occluder = occluder_owner.get_or_null(p_occluder);
  187. ERR_FAIL_NULL(occluder);
  188. memdelete(occluder);
  189. occluder_owner.free(p_occluder);
  190. }
  191. ////////////////////////////////////////////////////////
  192. void RaycastOcclusionCull::add_scenario(RID p_scenario) {
  193. ERR_FAIL_COND(scenarios.has(p_scenario));
  194. scenarios[p_scenario] = Scenario();
  195. }
  196. void RaycastOcclusionCull::remove_scenario(RID p_scenario) {
  197. Scenario *scenario = scenarios.getptr(p_scenario);
  198. ERR_FAIL_NULL(scenario);
  199. scenario->free();
  200. scenarios.erase(p_scenario);
  201. }
  202. void RaycastOcclusionCull::scenario_set_instance(RID p_scenario, RID p_instance, RID p_occluder, const Transform3D &p_xform, bool p_enabled) {
  203. ERR_FAIL_COND(!scenarios.has(p_scenario));
  204. Scenario &scenario = scenarios[p_scenario];
  205. if (!scenario.instances.has(p_instance)) {
  206. scenario.instances[p_instance] = OccluderInstance();
  207. }
  208. OccluderInstance &instance = scenario.instances[p_instance];
  209. bool changed = false;
  210. if (instance.removed) {
  211. instance.removed = false;
  212. scenario.removed_instances.erase(p_instance);
  213. changed = true; // It was removed and re-added, we might have missed some changes
  214. }
  215. if (instance.occluder != p_occluder) {
  216. Occluder *old_occluder = occluder_owner.get_or_null(instance.occluder);
  217. if (old_occluder) {
  218. old_occluder->users.erase(InstanceID(p_scenario, p_instance));
  219. }
  220. instance.occluder = p_occluder;
  221. if (p_occluder.is_valid()) {
  222. Occluder *occluder = occluder_owner.get_or_null(p_occluder);
  223. ERR_FAIL_NULL(occluder);
  224. occluder->users.insert(InstanceID(p_scenario, p_instance));
  225. }
  226. changed = true;
  227. }
  228. if (instance.xform != p_xform) {
  229. scenario.instances[p_instance].xform = p_xform;
  230. changed = true;
  231. }
  232. if (instance.enabled != p_enabled) {
  233. instance.enabled = p_enabled;
  234. scenario.dirty = true; // The scenario needs a scene re-build, but the instance doesn't need update
  235. }
  236. if (changed && !scenario.dirty_instances.has(p_instance)) {
  237. scenario.dirty_instances.insert(p_instance);
  238. scenario.dirty_instances_array.push_back(p_instance);
  239. scenario.dirty = true;
  240. }
  241. }
  242. void RaycastOcclusionCull::scenario_remove_instance(RID p_scenario, RID p_instance) {
  243. ERR_FAIL_COND(!scenarios.has(p_scenario));
  244. Scenario &scenario = scenarios[p_scenario];
  245. if (scenario.instances.has(p_instance)) {
  246. OccluderInstance &instance = scenario.instances[p_instance];
  247. if (!instance.removed) {
  248. Occluder *occluder = occluder_owner.get_or_null(instance.occluder);
  249. if (occluder) {
  250. occluder->users.erase(InstanceID(p_scenario, p_instance));
  251. }
  252. scenario.removed_instances.push_back(p_instance);
  253. instance.removed = true;
  254. }
  255. }
  256. }
  257. void RaycastOcclusionCull::Scenario::_update_dirty_instance_thread(int p_idx, RID *p_instances) {
  258. _update_dirty_instance(p_idx, p_instances);
  259. }
  260. void RaycastOcclusionCull::Scenario::_update_dirty_instance(int p_idx, RID *p_instances) {
  261. OccluderInstance *occ_inst = instances.getptr(p_instances[p_idx]);
  262. if (!occ_inst) {
  263. return;
  264. }
  265. Occluder *occ = raycast_singleton->occluder_owner.get_or_null(occ_inst->occluder);
  266. if (!occ) {
  267. return;
  268. }
  269. int vertices_size = occ->vertices.size();
  270. // Embree requires the last element to be readable by a 16-byte SSE load instruction, so we add padding to be safe.
  271. occ_inst->xformed_vertices.resize(vertices_size + 1);
  272. const Vector3 *read_ptr = occ->vertices.ptr();
  273. Vector3 *write_ptr = occ_inst->xformed_vertices.ptr();
  274. if (vertices_size > 1024) {
  275. TransformThreadData td;
  276. td.xform = occ_inst->xform;
  277. td.read = read_ptr;
  278. td.write = write_ptr;
  279. td.vertex_count = vertices_size;
  280. td.thread_count = WorkerThreadPool::get_singleton()->get_thread_count();
  281. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &Scenario::_transform_vertices_thread, &td, td.thread_count, -1, true, SNAME("RaycastOcclusionCull"));
  282. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  283. } else {
  284. _transform_vertices_range(read_ptr, write_ptr, occ_inst->xform, 0, vertices_size);
  285. }
  286. occ_inst->indices.resize(occ->indices.size());
  287. memcpy(occ_inst->indices.ptr(), occ->indices.ptr(), occ->indices.size() * sizeof(int32_t));
  288. }
  289. void RaycastOcclusionCull::Scenario::_transform_vertices_thread(uint32_t p_thread, TransformThreadData *p_data) {
  290. uint32_t vertex_total = p_data->vertex_count;
  291. uint32_t total_threads = p_data->thread_count;
  292. uint32_t from = p_thread * vertex_total / total_threads;
  293. uint32_t to = (p_thread + 1 == total_threads) ? vertex_total : ((p_thread + 1) * vertex_total / total_threads);
  294. _transform_vertices_range(p_data->read, p_data->write, p_data->xform, from, to);
  295. }
  296. void RaycastOcclusionCull::Scenario::_transform_vertices_range(const Vector3 *p_read, Vector3 *p_write, const Transform3D &p_xform, int p_from, int p_to) {
  297. for (int i = p_from; i < p_to; i++) {
  298. p_write[i] = p_xform.xform(p_read[i]);
  299. }
  300. }
  301. void RaycastOcclusionCull::Scenario::free() {
  302. if (commit_thread) {
  303. if (commit_thread->is_started()) {
  304. commit_thread->wait_to_finish();
  305. }
  306. memdelete(commit_thread);
  307. commit_thread = nullptr;
  308. }
  309. for (int i = 0; i < 2; i++) {
  310. if (ebr_scene[i]) {
  311. rtcReleaseScene(ebr_scene[i]);
  312. ebr_scene[i] = nullptr;
  313. }
  314. }
  315. }
  316. void RaycastOcclusionCull::Scenario::_commit_scene(void *p_ud) {
  317. Scenario *scenario = (Scenario *)p_ud;
  318. int commit_idx = 1 - (scenario->current_scene_idx);
  319. rtcCommitScene(scenario->ebr_scene[commit_idx]);
  320. scenario->commit_done = true;
  321. }
  322. void RaycastOcclusionCull::Scenario::update() {
  323. ERR_FAIL_NULL(singleton);
  324. if (commit_thread == nullptr) {
  325. commit_thread = memnew(Thread);
  326. }
  327. if (commit_thread->is_started()) {
  328. if (commit_done) {
  329. commit_thread->wait_to_finish();
  330. current_scene_idx = 1 - current_scene_idx;
  331. } else {
  332. return;
  333. }
  334. }
  335. if (!dirty && removed_instances.is_empty() && dirty_instances_array.is_empty()) {
  336. return;
  337. }
  338. for (const RID &scenario : removed_instances) {
  339. instances.erase(scenario);
  340. }
  341. if (dirty_instances_array.size() / WorkerThreadPool::get_singleton()->get_thread_count() > 128) {
  342. // Lots of instances, use per-instance threading
  343. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &Scenario::_update_dirty_instance_thread, dirty_instances_array.ptr(), dirty_instances_array.size(), -1, true, SNAME("RaycastOcclusionCullUpdate"));
  344. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  345. } else {
  346. // Few instances, use threading on the vertex transforms
  347. for (unsigned int i = 0; i < dirty_instances_array.size(); i++) {
  348. _update_dirty_instance(i, dirty_instances_array.ptr());
  349. }
  350. }
  351. dirty_instances.clear();
  352. dirty_instances_array.clear();
  353. removed_instances.clear();
  354. if (raycast_singleton->ebr_device == nullptr) {
  355. raycast_singleton->_init_embree();
  356. }
  357. int next_scene_idx = 1 - current_scene_idx;
  358. RTCScene &next_scene = ebr_scene[next_scene_idx];
  359. if (next_scene) {
  360. rtcReleaseScene(next_scene);
  361. }
  362. next_scene = rtcNewScene(raycast_singleton->ebr_device);
  363. rtcSetSceneBuildQuality(next_scene, RTCBuildQuality(raycast_singleton->build_quality));
  364. for (const KeyValue<RID, OccluderInstance> &E : instances) {
  365. const OccluderInstance *occ_inst = &E.value;
  366. const Occluder *occ = raycast_singleton->occluder_owner.get_or_null(occ_inst->occluder);
  367. if (!occ || !occ_inst->enabled) {
  368. continue;
  369. }
  370. RTCGeometry geom = rtcNewGeometry(raycast_singleton->ebr_device, RTC_GEOMETRY_TYPE_TRIANGLE);
  371. rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, occ_inst->xformed_vertices.ptr(), 0, sizeof(Vector3), occ_inst->xformed_vertices.size());
  372. rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, occ_inst->indices.ptr(), 0, sizeof(uint32_t) * 3, occ_inst->indices.size() / 3);
  373. rtcCommitGeometry(geom);
  374. rtcAttachGeometry(next_scene, geom);
  375. rtcReleaseGeometry(geom);
  376. }
  377. dirty = false;
  378. commit_done = false;
  379. commit_thread->start(&Scenario::_commit_scene, this);
  380. }
  381. void RaycastOcclusionCull::Scenario::_raycast(uint32_t p_idx, const RaycastThreadData *p_raycast_data) const {
  382. RTCRayQueryContext context;
  383. rtcInitRayQueryContext(&context);
  384. RTCIntersectArguments args;
  385. rtcInitIntersectArguments(&args);
  386. args.flags = RTC_RAY_QUERY_FLAG_COHERENT;
  387. args.context = &context;
  388. rtcIntersect16((const int *)&p_raycast_data->masks[p_idx * TILE_RAYS], ebr_scene[current_scene_idx], &p_raycast_data->rays[p_idx], &args);
  389. }
  390. void RaycastOcclusionCull::Scenario::raycast(CameraRayTile *r_rays, const uint32_t *p_valid_masks, uint32_t p_tile_count) const {
  391. ERR_FAIL_NULL(singleton);
  392. if (raycast_singleton->ebr_device == nullptr) {
  393. return; // Embree is initialized on demand when there is some scenario with occluders in it.
  394. }
  395. if (ebr_scene[current_scene_idx] == nullptr) {
  396. return;
  397. }
  398. RaycastThreadData td;
  399. td.rays = r_rays;
  400. td.masks = p_valid_masks;
  401. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &Scenario::_raycast, &td, p_tile_count, -1, true, SNAME("RaycastOcclusionCullRaycast"));
  402. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  403. }
  404. ////////////////////////////////////////////////////////
  405. void RaycastOcclusionCull::add_buffer(RID p_buffer) {
  406. ERR_FAIL_COND(buffers.has(p_buffer));
  407. buffers[p_buffer] = RaycastHZBuffer();
  408. }
  409. void RaycastOcclusionCull::remove_buffer(RID p_buffer) {
  410. ERR_FAIL_COND(!buffers.has(p_buffer));
  411. buffers.erase(p_buffer);
  412. }
  413. void RaycastOcclusionCull::buffer_set_scenario(RID p_buffer, RID p_scenario) {
  414. ERR_FAIL_COND(!buffers.has(p_buffer));
  415. ERR_FAIL_COND(p_scenario.is_valid() && !scenarios.has(p_scenario));
  416. buffers[p_buffer].scenario_rid = p_scenario;
  417. }
  418. void RaycastOcclusionCull::buffer_set_size(RID p_buffer, const Vector2i &p_size) {
  419. ERR_FAIL_COND(!buffers.has(p_buffer));
  420. buffers[p_buffer].resize(p_size);
  421. }
  422. Projection RaycastOcclusionCull::_jitter_projection(const Projection &p_cam_projection, const Size2i &p_viewport_size) {
  423. if (!_jitter_enabled) {
  424. return p_cam_projection;
  425. }
  426. // Prevent divide by zero when using NULL viewport.
  427. if ((p_viewport_size.x <= 0) || (p_viewport_size.y <= 0)) {
  428. return p_cam_projection;
  429. }
  430. Projection p = p_cam_projection;
  431. int32_t frame = Engine::get_singleton()->get_frames_drawn();
  432. frame %= 9;
  433. Vector2 jitter;
  434. switch (frame) {
  435. default:
  436. break;
  437. case 1: {
  438. jitter = Vector2(-1, -1);
  439. } break;
  440. case 2: {
  441. jitter = Vector2(1, -1);
  442. } break;
  443. case 3: {
  444. jitter = Vector2(-1, 1);
  445. } break;
  446. case 4: {
  447. jitter = Vector2(1, 1);
  448. } break;
  449. case 5: {
  450. jitter = Vector2(-0.5f, -0.5f);
  451. } break;
  452. case 6: {
  453. jitter = Vector2(0.5f, -0.5f);
  454. } break;
  455. case 7: {
  456. jitter = Vector2(-0.5f, 0.5f);
  457. } break;
  458. case 8: {
  459. jitter = Vector2(0.5f, 0.5f);
  460. } break;
  461. }
  462. // The multiplier here determines the divergence from center,
  463. // and is to some extent a balancing act.
  464. // Higher divergence gives fewer false hidden, but more false shown.
  465. // False hidden is obvious to viewer, false shown is not.
  466. // False shown can lower percentage that are occluded, and therefore performance.
  467. jitter *= Vector2(1 / (float)p_viewport_size.x, 1 / (float)p_viewport_size.y) * 0.05f;
  468. p.add_jitter_offset(jitter);
  469. return p;
  470. }
  471. void RaycastOcclusionCull::buffer_update(RID p_buffer, const Transform3D &p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal) {
  472. if (!buffers.has(p_buffer)) {
  473. return;
  474. }
  475. RaycastHZBuffer &buffer = buffers[p_buffer];
  476. if (buffer.is_empty() || !scenarios.has(buffer.scenario_rid)) {
  477. return;
  478. }
  479. Scenario &scenario = scenarios[buffer.scenario_rid];
  480. scenario.update();
  481. Projection jittered_proj = _jitter_projection(p_cam_projection, buffer.get_occlusion_buffer_size());
  482. buffer.update_camera_rays(p_cam_transform, jittered_proj, p_cam_orthogonal);
  483. scenario.raycast(buffer.camera_rays, buffer.camera_ray_masks.ptr(), buffer.camera_rays_tile_count);
  484. buffer.sort_rays(-p_cam_transform.basis.get_column(2), p_cam_orthogonal);
  485. buffer.update_mips();
  486. }
  487. RaycastOcclusionCull::HZBuffer *RaycastOcclusionCull::buffer_get_ptr(RID p_buffer) {
  488. if (!buffers.has(p_buffer)) {
  489. return nullptr;
  490. }
  491. return &buffers[p_buffer];
  492. }
  493. RID RaycastOcclusionCull::buffer_get_debug_texture(RID p_buffer) {
  494. ERR_FAIL_COND_V(!buffers.has(p_buffer), RID());
  495. return buffers[p_buffer].get_debug_texture();
  496. }
  497. ////////////////////////////////////////////////////////
  498. void RaycastOcclusionCull::set_build_quality(RS::ViewportOcclusionCullingBuildQuality p_quality) {
  499. if (build_quality == p_quality) {
  500. return;
  501. }
  502. build_quality = p_quality;
  503. for (KeyValue<RID, Scenario> &K : scenarios) {
  504. K.value.dirty = true;
  505. }
  506. }
  507. void RaycastOcclusionCull::_init_embree() {
  508. #ifdef __SSE2__
  509. _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
  510. _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
  511. #endif
  512. String settings = vformat("threads=%d", MAX(1, OS::get_singleton()->get_processor_count() - 2));
  513. ebr_device = rtcNewDevice(settings.utf8().ptr());
  514. }
  515. RaycastOcclusionCull::RaycastOcclusionCull() {
  516. raycast_singleton = this;
  517. int default_quality = GLOBAL_GET("rendering/occlusion_culling/bvh_build_quality");
  518. _jitter_enabled = GLOBAL_GET("rendering/occlusion_culling/jitter_projection");
  519. build_quality = RS::ViewportOcclusionCullingBuildQuality(default_quality);
  520. }
  521. RaycastOcclusionCull::~RaycastOcclusionCull() {
  522. for (KeyValue<RID, Scenario> &K : scenarios) {
  523. K.value.free();
  524. }
  525. if (ebr_device != nullptr) {
  526. rtcReleaseDevice(ebr_device);
  527. }
  528. raycast_singleton = nullptr;
  529. }