raycast_occlusion_cull.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. Projection inv_camera_matrix = p_cam_projection.inverse();
  78. Vector3 camera_corner_proj = Vector3(-1.0f, -1.0f, -1.0f);
  79. Vector3 camera_corner_view = inv_camera_matrix.xform(camera_corner_proj);
  80. td.pixel_corner = p_cam_transform.xform(camera_corner_view);
  81. Vector3 top_corner_proj = Vector3(-1.0f, 1.0f, -1.0f);
  82. Vector3 top_corner_view = inv_camera_matrix.xform(top_corner_proj);
  83. Vector3 top_corner_world = p_cam_transform.xform(top_corner_view);
  84. Vector3 left_corner_proj = Vector3(1.0f, -1.0f, -1.0f);
  85. Vector3 left_corner_view = inv_camera_matrix.xform(left_corner_proj);
  86. Vector3 left_corner_world = p_cam_transform.xform(left_corner_view);
  87. td.pixel_u_interp = left_corner_world - td.pixel_corner;
  88. td.pixel_v_interp = top_corner_world - td.pixel_corner;
  89. debug_tex_range = td.z_far;
  90. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RaycastHZBuffer::_camera_rays_threaded, &td, td.thread_count, -1, true, SNAME("RaycastOcclusionCullUpdateCamera"));
  91. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  92. }
  93. void RaycastOcclusionCull::RaycastHZBuffer::_camera_rays_threaded(uint32_t p_thread, const CameraRayThreadData *p_data) {
  94. uint32_t total_tiles = camera_rays_tile_count;
  95. uint32_t total_threads = p_data->thread_count;
  96. uint32_t from = p_thread * total_tiles / total_threads;
  97. uint32_t to = (p_thread + 1 == total_threads) ? total_tiles : ((p_thread + 1) * total_tiles / total_threads);
  98. _generate_camera_rays(p_data, from, to);
  99. }
  100. void RaycastOcclusionCull::RaycastHZBuffer::_generate_camera_rays(const CameraRayThreadData *p_data, int p_from, int p_to) {
  101. const Size2i &buffer_size = sizes[0];
  102. for (int i = p_from; i < p_to; i++) {
  103. CameraRayTile &tile = camera_rays[i];
  104. int tile_x = (i % tile_grid_size.x) * TILE_SIZE;
  105. int tile_y = (i / tile_grid_size.x) * TILE_SIZE;
  106. for (int j = 0; j < TILE_RAYS; j++) {
  107. int x = tile_x + j % TILE_SIZE;
  108. int y = tile_y + j / TILE_SIZE;
  109. float u = (float(x) + 0.5f) / buffer_size.x;
  110. float v = (float(y) + 0.5f) / buffer_size.y;
  111. Vector3 pixel_pos = p_data->pixel_corner + u * p_data->pixel_u_interp + v * p_data->pixel_v_interp;
  112. tile.ray.tnear[j] = p_data->z_near;
  113. Vector3 dir;
  114. if (p_data->camera_orthogonal) {
  115. dir = -p_data->camera_dir;
  116. tile.ray.org_x[j] = pixel_pos.x - dir.x * p_data->z_near;
  117. tile.ray.org_y[j] = pixel_pos.y - dir.y * p_data->z_near;
  118. tile.ray.org_z[j] = pixel_pos.z - dir.z * p_data->z_near;
  119. } else {
  120. dir = (pixel_pos - p_data->camera_pos).normalized();
  121. tile.ray.org_x[j] = p_data->camera_pos.x;
  122. tile.ray.org_y[j] = p_data->camera_pos.y;
  123. tile.ray.org_z[j] = p_data->camera_pos.z;
  124. tile.ray.tnear[j] /= dir.dot(p_data->camera_dir);
  125. }
  126. tile.ray.dir_x[j] = dir.x;
  127. tile.ray.dir_y[j] = dir.y;
  128. tile.ray.dir_z[j] = dir.z;
  129. tile.ray.tfar[j] = p_data->z_far;
  130. tile.ray.time[j] = 0.0f;
  131. tile.ray.flags[j] = 0;
  132. tile.ray.mask[j] = ~0U;
  133. tile.hit.geomID[j] = RTC_INVALID_GEOMETRY_ID;
  134. }
  135. }
  136. }
  137. void RaycastOcclusionCull::RaycastHZBuffer::sort_rays(const Vector3 &p_camera_dir, bool p_orthogonal) {
  138. ERR_FAIL_COND(is_empty());
  139. Size2i buffer_size = sizes[0];
  140. for (int i = 0; i < tile_grid_size.y; i++) {
  141. for (int j = 0; j < tile_grid_size.x; j++) {
  142. for (int tile_i = 0; tile_i < TILE_SIZE; tile_i++) {
  143. for (int tile_j = 0; tile_j < TILE_SIZE; tile_j++) {
  144. int x = j * TILE_SIZE + tile_j;
  145. int y = i * TILE_SIZE + tile_i;
  146. if (x >= buffer_size.x || y >= buffer_size.y) {
  147. continue;
  148. }
  149. int k = tile_i * TILE_SIZE + tile_j;
  150. int tile_index = i * tile_grid_size.x + j;
  151. float d = camera_rays[tile_index].ray.tfar[k];
  152. if (!p_orthogonal) {
  153. const float &dir_x = camera_rays[tile_index].ray.dir_x[k];
  154. const float &dir_y = camera_rays[tile_index].ray.dir_y[k];
  155. const float &dir_z = camera_rays[tile_index].ray.dir_z[k];
  156. float cos_theta = p_camera_dir.x * dir_x + p_camera_dir.y * dir_y + p_camera_dir.z * dir_z;
  157. d *= cos_theta;
  158. }
  159. mips[0][y * buffer_size.x + x] = d;
  160. }
  161. }
  162. }
  163. }
  164. }
  165. RaycastOcclusionCull::RaycastHZBuffer::~RaycastHZBuffer() {
  166. if (camera_rays_unaligned_buffer) {
  167. memfree(camera_rays_unaligned_buffer);
  168. }
  169. }
  170. ////////////////////////////////////////////////////////
  171. bool RaycastOcclusionCull::is_occluder(RID p_rid) {
  172. return occluder_owner.owns(p_rid);
  173. }
  174. RID RaycastOcclusionCull::occluder_allocate() {
  175. return occluder_owner.allocate_rid();
  176. }
  177. void RaycastOcclusionCull::occluder_initialize(RID p_occluder) {
  178. Occluder *occluder = memnew(Occluder);
  179. occluder_owner.initialize_rid(p_occluder, occluder);
  180. }
  181. void RaycastOcclusionCull::occluder_set_mesh(RID p_occluder, const PackedVector3Array &p_vertices, const PackedInt32Array &p_indices) {
  182. Occluder *occluder = occluder_owner.get_or_null(p_occluder);
  183. ERR_FAIL_NULL(occluder);
  184. occluder->vertices = p_vertices;
  185. occluder->indices = p_indices;
  186. for (const InstanceID &E : occluder->users) {
  187. RID scenario_rid = E.scenario;
  188. RID instance_rid = E.instance;
  189. ERR_CONTINUE(!scenarios.has(scenario_rid));
  190. Scenario &scenario = scenarios[scenario_rid];
  191. ERR_CONTINUE(!scenario.instances.has(instance_rid));
  192. if (!scenario.dirty_instances.has(instance_rid)) {
  193. scenario.dirty_instances.insert(instance_rid);
  194. scenario.dirty_instances_array.push_back(instance_rid);
  195. }
  196. }
  197. }
  198. void RaycastOcclusionCull::free_occluder(RID p_occluder) {
  199. Occluder *occluder = occluder_owner.get_or_null(p_occluder);
  200. ERR_FAIL_NULL(occluder);
  201. memdelete(occluder);
  202. occluder_owner.free(p_occluder);
  203. }
  204. ////////////////////////////////////////////////////////
  205. void RaycastOcclusionCull::add_scenario(RID p_scenario) {
  206. ERR_FAIL_COND(scenarios.has(p_scenario));
  207. scenarios[p_scenario] = Scenario();
  208. }
  209. void RaycastOcclusionCull::remove_scenario(RID p_scenario) {
  210. Scenario *scenario = scenarios.getptr(p_scenario);
  211. ERR_FAIL_NULL(scenario);
  212. scenario->free();
  213. scenarios.erase(p_scenario);
  214. }
  215. void RaycastOcclusionCull::scenario_set_instance(RID p_scenario, RID p_instance, RID p_occluder, const Transform3D &p_xform, bool p_enabled) {
  216. ERR_FAIL_COND(!scenarios.has(p_scenario));
  217. Scenario &scenario = scenarios[p_scenario];
  218. if (!scenario.instances.has(p_instance)) {
  219. scenario.instances[p_instance] = OccluderInstance();
  220. }
  221. OccluderInstance &instance = scenario.instances[p_instance];
  222. bool changed = false;
  223. if (instance.removed) {
  224. instance.removed = false;
  225. scenario.removed_instances.erase(p_instance);
  226. changed = true; // It was removed and re-added, we might have missed some changes
  227. }
  228. if (instance.occluder != p_occluder) {
  229. Occluder *old_occluder = occluder_owner.get_or_null(instance.occluder);
  230. if (old_occluder) {
  231. old_occluder->users.erase(InstanceID(p_scenario, p_instance));
  232. }
  233. instance.occluder = p_occluder;
  234. if (p_occluder.is_valid()) {
  235. Occluder *occluder = occluder_owner.get_or_null(p_occluder);
  236. ERR_FAIL_NULL(occluder);
  237. occluder->users.insert(InstanceID(p_scenario, p_instance));
  238. }
  239. changed = true;
  240. }
  241. if (instance.xform != p_xform) {
  242. scenario.instances[p_instance].xform = p_xform;
  243. changed = true;
  244. }
  245. if (instance.enabled != p_enabled) {
  246. instance.enabled = p_enabled;
  247. scenario.dirty = true; // The scenario needs a scene re-build, but the instance doesn't need update
  248. }
  249. if (changed && !scenario.dirty_instances.has(p_instance)) {
  250. scenario.dirty_instances.insert(p_instance);
  251. scenario.dirty_instances_array.push_back(p_instance);
  252. scenario.dirty = true;
  253. }
  254. }
  255. void RaycastOcclusionCull::scenario_remove_instance(RID p_scenario, RID p_instance) {
  256. ERR_FAIL_COND(!scenarios.has(p_scenario));
  257. Scenario &scenario = scenarios[p_scenario];
  258. if (scenario.instances.has(p_instance)) {
  259. OccluderInstance &instance = scenario.instances[p_instance];
  260. if (!instance.removed) {
  261. Occluder *occluder = occluder_owner.get_or_null(instance.occluder);
  262. if (occluder) {
  263. occluder->users.erase(InstanceID(p_scenario, p_instance));
  264. }
  265. scenario.removed_instances.push_back(p_instance);
  266. instance.removed = true;
  267. }
  268. }
  269. }
  270. void RaycastOcclusionCull::Scenario::_update_dirty_instance_thread(int p_idx, RID *p_instances) {
  271. _update_dirty_instance(p_idx, p_instances);
  272. }
  273. void RaycastOcclusionCull::Scenario::_update_dirty_instance(int p_idx, RID *p_instances) {
  274. OccluderInstance *occ_inst = instances.getptr(p_instances[p_idx]);
  275. if (!occ_inst) {
  276. return;
  277. }
  278. Occluder *occ = raycast_singleton->occluder_owner.get_or_null(occ_inst->occluder);
  279. if (!occ) {
  280. return;
  281. }
  282. int vertices_size = occ->vertices.size();
  283. // Embree requires the last element to be readable by a 16-byte SSE load instruction, so we add padding to be safe.
  284. occ_inst->xformed_vertices.resize(vertices_size + 1);
  285. const Vector3 *read_ptr = occ->vertices.ptr();
  286. Vector3 *write_ptr = occ_inst->xformed_vertices.ptr();
  287. if (vertices_size > 1024) {
  288. TransformThreadData td;
  289. td.xform = occ_inst->xform;
  290. td.read = read_ptr;
  291. td.write = write_ptr;
  292. td.vertex_count = vertices_size;
  293. td.thread_count = WorkerThreadPool::get_singleton()->get_thread_count();
  294. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &Scenario::_transform_vertices_thread, &td, td.thread_count, -1, true, SNAME("RaycastOcclusionCull"));
  295. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  296. } else {
  297. _transform_vertices_range(read_ptr, write_ptr, occ_inst->xform, 0, vertices_size);
  298. }
  299. occ_inst->indices.resize(occ->indices.size());
  300. memcpy(occ_inst->indices.ptr(), occ->indices.ptr(), occ->indices.size() * sizeof(int32_t));
  301. }
  302. void RaycastOcclusionCull::Scenario::_transform_vertices_thread(uint32_t p_thread, TransformThreadData *p_data) {
  303. uint32_t vertex_total = p_data->vertex_count;
  304. uint32_t total_threads = p_data->thread_count;
  305. uint32_t from = p_thread * vertex_total / total_threads;
  306. uint32_t to = (p_thread + 1 == total_threads) ? vertex_total : ((p_thread + 1) * vertex_total / total_threads);
  307. _transform_vertices_range(p_data->read, p_data->write, p_data->xform, from, to);
  308. }
  309. void RaycastOcclusionCull::Scenario::_transform_vertices_range(const Vector3 *p_read, Vector3 *p_write, const Transform3D &p_xform, int p_from, int p_to) {
  310. for (int i = p_from; i < p_to; i++) {
  311. p_write[i] = p_xform.xform(p_read[i]);
  312. }
  313. }
  314. void RaycastOcclusionCull::Scenario::free() {
  315. if (commit_thread) {
  316. if (commit_thread->is_started()) {
  317. commit_thread->wait_to_finish();
  318. }
  319. memdelete(commit_thread);
  320. commit_thread = nullptr;
  321. }
  322. for (int i = 0; i < 2; i++) {
  323. if (ebr_scene[i]) {
  324. rtcReleaseScene(ebr_scene[i]);
  325. ebr_scene[i] = nullptr;
  326. }
  327. }
  328. }
  329. void RaycastOcclusionCull::Scenario::_commit_scene(void *p_ud) {
  330. Scenario *scenario = (Scenario *)p_ud;
  331. int commit_idx = 1 - (scenario->current_scene_idx);
  332. rtcCommitScene(scenario->ebr_scene[commit_idx]);
  333. scenario->commit_done = true;
  334. }
  335. void RaycastOcclusionCull::Scenario::update() {
  336. ERR_FAIL_NULL(singleton);
  337. if (commit_thread == nullptr) {
  338. commit_thread = memnew(Thread);
  339. }
  340. if (commit_thread->is_started()) {
  341. if (commit_done) {
  342. commit_thread->wait_to_finish();
  343. current_scene_idx = 1 - current_scene_idx;
  344. } else {
  345. return;
  346. }
  347. }
  348. if (!dirty && removed_instances.is_empty() && dirty_instances_array.is_empty()) {
  349. return;
  350. }
  351. for (const RID &scenario : removed_instances) {
  352. instances.erase(scenario);
  353. }
  354. if (dirty_instances_array.size() / WorkerThreadPool::get_singleton()->get_thread_count() > 128) {
  355. // Lots of instances, use per-instance threading
  356. 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"));
  357. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  358. } else {
  359. // Few instances, use threading on the vertex transforms
  360. for (unsigned int i = 0; i < dirty_instances_array.size(); i++) {
  361. _update_dirty_instance(i, dirty_instances_array.ptr());
  362. }
  363. }
  364. dirty_instances.clear();
  365. dirty_instances_array.clear();
  366. removed_instances.clear();
  367. if (raycast_singleton->ebr_device == nullptr) {
  368. raycast_singleton->_init_embree();
  369. }
  370. int next_scene_idx = 1 - current_scene_idx;
  371. RTCScene &next_scene = ebr_scene[next_scene_idx];
  372. if (next_scene) {
  373. rtcReleaseScene(next_scene);
  374. }
  375. next_scene = rtcNewScene(raycast_singleton->ebr_device);
  376. rtcSetSceneBuildQuality(next_scene, RTCBuildQuality(raycast_singleton->build_quality));
  377. for (const KeyValue<RID, OccluderInstance> &E : instances) {
  378. const OccluderInstance *occ_inst = &E.value;
  379. const Occluder *occ = raycast_singleton->occluder_owner.get_or_null(occ_inst->occluder);
  380. if (!occ || !occ_inst->enabled) {
  381. continue;
  382. }
  383. RTCGeometry geom = rtcNewGeometry(raycast_singleton->ebr_device, RTC_GEOMETRY_TYPE_TRIANGLE);
  384. rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, occ_inst->xformed_vertices.ptr(), 0, sizeof(Vector3), occ_inst->xformed_vertices.size());
  385. rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, occ_inst->indices.ptr(), 0, sizeof(uint32_t) * 3, occ_inst->indices.size() / 3);
  386. rtcCommitGeometry(geom);
  387. rtcAttachGeometry(next_scene, geom);
  388. rtcReleaseGeometry(geom);
  389. }
  390. dirty = false;
  391. commit_done = false;
  392. commit_thread->start(&Scenario::_commit_scene, this);
  393. }
  394. void RaycastOcclusionCull::Scenario::_raycast(uint32_t p_idx, const RaycastThreadData *p_raycast_data) const {
  395. RTCRayQueryContext context;
  396. rtcInitRayQueryContext(&context);
  397. RTCIntersectArguments args;
  398. rtcInitIntersectArguments(&args);
  399. args.flags = RTC_RAY_QUERY_FLAG_COHERENT;
  400. args.context = &context;
  401. rtcIntersect16((const int *)&p_raycast_data->masks[p_idx * TILE_RAYS], ebr_scene[current_scene_idx], &p_raycast_data->rays[p_idx], &args);
  402. }
  403. void RaycastOcclusionCull::Scenario::raycast(CameraRayTile *r_rays, const uint32_t *p_valid_masks, uint32_t p_tile_count) const {
  404. ERR_FAIL_NULL(singleton);
  405. if (raycast_singleton->ebr_device == nullptr) {
  406. return; // Embree is initialized on demand when there is some scenario with occluders in it.
  407. }
  408. if (ebr_scene[current_scene_idx] == nullptr) {
  409. return;
  410. }
  411. RaycastThreadData td;
  412. td.rays = r_rays;
  413. td.masks = p_valid_masks;
  414. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &Scenario::_raycast, &td, p_tile_count, -1, true, SNAME("RaycastOcclusionCullRaycast"));
  415. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  416. }
  417. ////////////////////////////////////////////////////////
  418. void RaycastOcclusionCull::add_buffer(RID p_buffer) {
  419. ERR_FAIL_COND(buffers.has(p_buffer));
  420. buffers[p_buffer] = RaycastHZBuffer();
  421. }
  422. void RaycastOcclusionCull::remove_buffer(RID p_buffer) {
  423. ERR_FAIL_COND(!buffers.has(p_buffer));
  424. buffers.erase(p_buffer);
  425. }
  426. void RaycastOcclusionCull::buffer_set_scenario(RID p_buffer, RID p_scenario) {
  427. ERR_FAIL_COND(!buffers.has(p_buffer));
  428. ERR_FAIL_COND(p_scenario.is_valid() && !scenarios.has(p_scenario));
  429. buffers[p_buffer].scenario_rid = p_scenario;
  430. }
  431. void RaycastOcclusionCull::buffer_set_size(RID p_buffer, const Vector2i &p_size) {
  432. ERR_FAIL_COND(!buffers.has(p_buffer));
  433. buffers[p_buffer].resize(p_size);
  434. }
  435. Projection RaycastOcclusionCull::_jitter_projection(const Projection &p_cam_projection, const Size2i &p_viewport_size) {
  436. if (!_jitter_enabled) {
  437. return p_cam_projection;
  438. }
  439. // Prevent divide by zero when using NULL viewport.
  440. if ((p_viewport_size.x <= 0) || (p_viewport_size.y <= 0)) {
  441. return p_cam_projection;
  442. }
  443. Projection p = p_cam_projection;
  444. int32_t frame = Engine::get_singleton()->get_frames_drawn();
  445. frame %= 9;
  446. Vector2 jitter;
  447. switch (frame) {
  448. default:
  449. break;
  450. case 1: {
  451. jitter = Vector2(-1, -1);
  452. } break;
  453. case 2: {
  454. jitter = Vector2(1, -1);
  455. } break;
  456. case 3: {
  457. jitter = Vector2(-1, 1);
  458. } break;
  459. case 4: {
  460. jitter = Vector2(1, 1);
  461. } break;
  462. case 5: {
  463. jitter = Vector2(-0.5f, -0.5f);
  464. } break;
  465. case 6: {
  466. jitter = Vector2(0.5f, -0.5f);
  467. } break;
  468. case 7: {
  469. jitter = Vector2(-0.5f, 0.5f);
  470. } break;
  471. case 8: {
  472. jitter = Vector2(0.5f, 0.5f);
  473. } break;
  474. }
  475. // The multiplier here determines the divergence from center,
  476. // and is to some extent a balancing act.
  477. // Higher divergence gives fewer false hidden, but more false shown.
  478. // False hidden is obvious to viewer, false shown is not.
  479. // False shown can lower percentage that are occluded, and therefore performance.
  480. jitter *= Vector2(1 / (float)p_viewport_size.x, 1 / (float)p_viewport_size.y) * 0.05f;
  481. p.add_jitter_offset(jitter);
  482. return p;
  483. }
  484. void RaycastOcclusionCull::buffer_update(RID p_buffer, const Transform3D &p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal) {
  485. if (!buffers.has(p_buffer)) {
  486. return;
  487. }
  488. RaycastHZBuffer &buffer = buffers[p_buffer];
  489. if (buffer.is_empty() || !scenarios.has(buffer.scenario_rid)) {
  490. return;
  491. }
  492. Scenario &scenario = scenarios[buffer.scenario_rid];
  493. scenario.update();
  494. Projection jittered_proj = _jitter_projection(p_cam_projection, buffer.get_occlusion_buffer_size());
  495. buffer.update_camera_rays(p_cam_transform, jittered_proj, p_cam_orthogonal);
  496. scenario.raycast(buffer.camera_rays, buffer.camera_ray_masks.ptr(), buffer.camera_rays_tile_count);
  497. buffer.sort_rays(-p_cam_transform.basis.get_column(2), p_cam_orthogonal);
  498. buffer.update_mips();
  499. }
  500. RaycastOcclusionCull::HZBuffer *RaycastOcclusionCull::buffer_get_ptr(RID p_buffer) {
  501. if (!buffers.has(p_buffer)) {
  502. return nullptr;
  503. }
  504. return &buffers[p_buffer];
  505. }
  506. RID RaycastOcclusionCull::buffer_get_debug_texture(RID p_buffer) {
  507. ERR_FAIL_COND_V(!buffers.has(p_buffer), RID());
  508. return buffers[p_buffer].get_debug_texture();
  509. }
  510. ////////////////////////////////////////////////////////
  511. void RaycastOcclusionCull::set_build_quality(RS::ViewportOcclusionCullingBuildQuality p_quality) {
  512. if (build_quality == p_quality) {
  513. return;
  514. }
  515. build_quality = p_quality;
  516. for (KeyValue<RID, Scenario> &K : scenarios) {
  517. K.value.dirty = true;
  518. }
  519. }
  520. void RaycastOcclusionCull::_init_embree() {
  521. #ifdef __SSE2__
  522. _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
  523. _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
  524. #endif
  525. String settings = vformat("threads=%d", MAX(1, OS::get_singleton()->get_processor_count() - 2));
  526. ebr_device = rtcNewDevice(settings.utf8().ptr());
  527. }
  528. RaycastOcclusionCull::RaycastOcclusionCull() {
  529. raycast_singleton = this;
  530. int default_quality = GLOBAL_GET("rendering/occlusion_culling/bvh_build_quality");
  531. _jitter_enabled = GLOBAL_GET("rendering/occlusion_culling/jitter_projection");
  532. build_quality = RS::ViewportOcclusionCullingBuildQuality(default_quality);
  533. }
  534. RaycastOcclusionCull::~RaycastOcclusionCull() {
  535. for (KeyValue<RID, Scenario> &K : scenarios) {
  536. K.value.free();
  537. }
  538. if (ebr_device != nullptr) {
  539. rtcReleaseDevice(ebr_device);
  540. }
  541. raycast_singleton = nullptr;
  542. }