1 /*************************************************************************/
2 /*  visual_server_scene.cpp                                              */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
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 
31 #include "visual_server_scene.h"
32 
33 #include "core/os/os.h"
34 #include "visual_server_globals.h"
35 #include "visual_server_raster.h"
36 
37 #include <new>
38 
39 /* CAMERA API */
40 
camera_create()41 RID VisualServerScene::camera_create() {
42 
43 	Camera *camera = memnew(Camera);
44 	return camera_owner.make_rid(camera);
45 }
46 
camera_set_perspective(RID p_camera,float p_fovy_degrees,float p_z_near,float p_z_far)47 void VisualServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
48 
49 	Camera *camera = camera_owner.get(p_camera);
50 	ERR_FAIL_COND(!camera);
51 	camera->type = Camera::PERSPECTIVE;
52 	camera->fov = p_fovy_degrees;
53 	camera->znear = p_z_near;
54 	camera->zfar = p_z_far;
55 }
56 
camera_set_orthogonal(RID p_camera,float p_size,float p_z_near,float p_z_far)57 void VisualServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
58 
59 	Camera *camera = camera_owner.get(p_camera);
60 	ERR_FAIL_COND(!camera);
61 	camera->type = Camera::ORTHOGONAL;
62 	camera->size = p_size;
63 	camera->znear = p_z_near;
64 	camera->zfar = p_z_far;
65 }
66 
camera_set_frustum(RID p_camera,float p_size,Vector2 p_offset,float p_z_near,float p_z_far)67 void VisualServerScene::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
68 	Camera *camera = camera_owner.get(p_camera);
69 	ERR_FAIL_COND(!camera);
70 	camera->type = Camera::FRUSTUM;
71 	camera->size = p_size;
72 	camera->offset = p_offset;
73 	camera->znear = p_z_near;
74 	camera->zfar = p_z_far;
75 }
76 
camera_set_transform(RID p_camera,const Transform & p_transform)77 void VisualServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {
78 
79 	Camera *camera = camera_owner.get(p_camera);
80 	ERR_FAIL_COND(!camera);
81 	camera->transform = p_transform.orthonormalized();
82 }
83 
camera_set_cull_mask(RID p_camera,uint32_t p_layers)84 void VisualServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
85 
86 	Camera *camera = camera_owner.get(p_camera);
87 	ERR_FAIL_COND(!camera);
88 
89 	camera->visible_layers = p_layers;
90 }
91 
camera_set_environment(RID p_camera,RID p_env)92 void VisualServerScene::camera_set_environment(RID p_camera, RID p_env) {
93 
94 	Camera *camera = camera_owner.get(p_camera);
95 	ERR_FAIL_COND(!camera);
96 	camera->env = p_env;
97 }
98 
camera_set_use_vertical_aspect(RID p_camera,bool p_enable)99 void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
100 
101 	Camera *camera = camera_owner.get(p_camera);
102 	ERR_FAIL_COND(!camera);
103 	camera->vaspect = p_enable;
104 }
105 
106 /* SCENARIO API */
107 
_instance_pair(void * p_self,OctreeElementID,Instance * p_A,int,OctreeElementID,Instance * p_B,int)108 void *VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) {
109 
110 	//VisualServerScene *self = (VisualServerScene*)p_self;
111 	Instance *A = p_A;
112 	Instance *B = p_B;
113 
114 	//instance indices are designed so greater always contains lesser
115 	if (A->base_type > B->base_type) {
116 		SWAP(A, B); //lesser always first
117 	}
118 
119 	if (B->base_type == VS::INSTANCE_LIGHT && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
120 
121 		InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
122 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
123 
124 		InstanceLightData::PairInfo pinfo;
125 		pinfo.geometry = A;
126 		pinfo.L = geom->lighting.push_back(B);
127 
128 		List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
129 
130 		if (geom->can_cast_shadows) {
131 
132 			light->shadow_dirty = true;
133 		}
134 		geom->lighting_dirty = true;
135 
136 		return E; //this element should make freeing faster
137 	} else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
138 
139 		InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
140 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
141 
142 		InstanceReflectionProbeData::PairInfo pinfo;
143 		pinfo.geometry = A;
144 		pinfo.L = geom->reflection_probes.push_back(B);
145 
146 		List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);
147 
148 		geom->reflection_dirty = true;
149 
150 		return E; //this element should make freeing faster
151 	} else if (B->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
152 
153 		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
154 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
155 
156 		InstanceLightmapCaptureData::PairInfo pinfo;
157 		pinfo.geometry = A;
158 		pinfo.L = geom->lightmap_captures.push_back(B);
159 
160 		List<InstanceLightmapCaptureData::PairInfo>::Element *E = lightmap_capture->geometries.push_back(pinfo);
161 		((VisualServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
162 
163 		return E; //this element should make freeing faster
164 	} else if (B->base_type == VS::INSTANCE_GI_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
165 
166 		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
167 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
168 
169 		InstanceGIProbeData::PairInfo pinfo;
170 		pinfo.geometry = A;
171 		pinfo.L = geom->gi_probes.push_back(B);
172 
173 		List<InstanceGIProbeData::PairInfo>::Element *E = gi_probe->geometries.push_back(pinfo);
174 
175 		geom->gi_probes_dirty = true;
176 
177 		return E; //this element should make freeing faster
178 
179 	} else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
180 
181 		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
182 		return gi_probe->lights.insert(A);
183 	}
184 
185 	return NULL;
186 }
_instance_unpair(void * p_self,OctreeElementID,Instance * p_A,int,OctreeElementID,Instance * p_B,int,void * udata)187 void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) {
188 
189 	//VisualServerScene *self = (VisualServerScene*)p_self;
190 	Instance *A = p_A;
191 	Instance *B = p_B;
192 
193 	//instance indices are designed so greater always contains lesser
194 	if (A->base_type > B->base_type) {
195 		SWAP(A, B); //lesser always first
196 	}
197 
198 	if (B->base_type == VS::INSTANCE_LIGHT && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
199 
200 		InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
201 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
202 
203 		List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);
204 
205 		geom->lighting.erase(E->get().L);
206 		light->geometries.erase(E);
207 
208 		if (geom->can_cast_shadows) {
209 			light->shadow_dirty = true;
210 		}
211 		geom->lighting_dirty = true;
212 
213 	} else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
214 
215 		InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
216 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
217 
218 		List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);
219 
220 		geom->reflection_probes.erase(E->get().L);
221 		reflection_probe->geometries.erase(E);
222 
223 		geom->reflection_dirty = true;
224 	} else if (B->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
225 
226 		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
227 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
228 
229 		List<InstanceLightmapCaptureData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightmapCaptureData::PairInfo>::Element *>(udata);
230 
231 		geom->lightmap_captures.erase(E->get().L);
232 		lightmap_capture->geometries.erase(E);
233 		((VisualServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
234 
235 	} else if (B->base_type == VS::INSTANCE_GI_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
236 
237 		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
238 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
239 
240 		List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);
241 
242 		geom->gi_probes.erase(E->get().L);
243 		gi_probe->geometries.erase(E);
244 
245 		geom->gi_probes_dirty = true;
246 
247 	} else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
248 
249 		InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
250 		Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);
251 
252 		gi_probe->lights.erase(E);
253 	}
254 }
255 
scenario_create()256 RID VisualServerScene::scenario_create() {
257 
258 	Scenario *scenario = memnew(Scenario);
259 	ERR_FAIL_COND_V(!scenario, RID());
260 	RID scenario_rid = scenario_owner.make_rid(scenario);
261 	scenario->self = scenario_rid;
262 
263 	scenario->octree.set_pair_callback(_instance_pair, this);
264 	scenario->octree.set_unpair_callback(_instance_unpair, this);
265 	scenario->reflection_probe_shadow_atlas = VSG::scene_render->shadow_atlas_create();
266 	VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
267 	VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
268 	VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
269 	VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
270 	VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
271 	scenario->reflection_atlas = VSG::scene_render->reflection_atlas_create();
272 
273 	return scenario_rid;
274 }
275 
scenario_set_debug(RID p_scenario,VS::ScenarioDebugMode p_debug_mode)276 void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) {
277 
278 	Scenario *scenario = scenario_owner.get(p_scenario);
279 	ERR_FAIL_COND(!scenario);
280 	scenario->debug = p_debug_mode;
281 }
282 
scenario_set_environment(RID p_scenario,RID p_environment)283 void VisualServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {
284 
285 	Scenario *scenario = scenario_owner.get(p_scenario);
286 	ERR_FAIL_COND(!scenario);
287 	scenario->environment = p_environment;
288 }
289 
scenario_set_fallback_environment(RID p_scenario,RID p_environment)290 void VisualServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
291 
292 	Scenario *scenario = scenario_owner.get(p_scenario);
293 	ERR_FAIL_COND(!scenario);
294 	scenario->fallback_environment = p_environment;
295 }
296 
scenario_set_reflection_atlas_size(RID p_scenario,int p_size,int p_subdiv)297 void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) {
298 
299 	Scenario *scenario = scenario_owner.get(p_scenario);
300 	ERR_FAIL_COND(!scenario);
301 	VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_size);
302 	VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas, p_subdiv);
303 }
304 
305 /* INSTANCING API */
306 
_instance_queue_update(Instance * p_instance,bool p_update_aabb,bool p_update_materials)307 void VisualServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials) {
308 
309 	if (p_update_aabb)
310 		p_instance->update_aabb = true;
311 	if (p_update_materials)
312 		p_instance->update_materials = true;
313 
314 	if (p_instance->update_item.in_list())
315 		return;
316 
317 	_instance_update_list.add(&p_instance->update_item);
318 }
319 
instance_create()320 RID VisualServerScene::instance_create() {
321 
322 	Instance *instance = memnew(Instance);
323 	ERR_FAIL_COND_V(!instance, RID());
324 
325 	RID instance_rid = instance_owner.make_rid(instance);
326 	instance->self = instance_rid;
327 
328 	return instance_rid;
329 }
330 
instance_set_base(RID p_instance,RID p_base)331 void VisualServerScene::instance_set_base(RID p_instance, RID p_base) {
332 
333 	Instance *instance = instance_owner.get(p_instance);
334 	ERR_FAIL_COND(!instance);
335 
336 	Scenario *scenario = instance->scenario;
337 
338 	if (instance->base_type != VS::INSTANCE_NONE) {
339 		//free anything related to that base
340 
341 		VSG::storage->instance_remove_dependency(instance->base, instance);
342 
343 		if (instance->base_type == VS::INSTANCE_GI_PROBE) {
344 			//if gi probe is baking, wait until done baking, else race condition may happen when removing it
345 			//from octree
346 			InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
347 
348 			//make sure probes are done baking
349 			while (!probe_bake_list.empty()) {
350 				OS::get_singleton()->delay_usec(1);
351 			}
352 			//make sure this one is done baking
353 
354 			while (gi_probe->dynamic.updating_stage == GI_UPDATE_STAGE_LIGHTING) {
355 				//wait until bake is done if it's baking
356 				OS::get_singleton()->delay_usec(1);
357 			}
358 		}
359 
360 		if (scenario && instance->octree_id) {
361 			scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
362 			instance->octree_id = 0;
363 		}
364 
365 		switch (instance->base_type) {
366 			case VS::INSTANCE_LIGHT: {
367 
368 				InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
369 
370 				if (instance->scenario && light->D) {
371 					instance->scenario->directional_lights.erase(light->D);
372 					light->D = NULL;
373 				}
374 				VSG::scene_render->free(light->instance);
375 			} break;
376 			case VS::INSTANCE_REFLECTION_PROBE: {
377 
378 				InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
379 				VSG::scene_render->free(reflection_probe->instance);
380 				if (reflection_probe->update_list.in_list()) {
381 					reflection_probe_render_list.remove(&reflection_probe->update_list);
382 				}
383 			} break;
384 			case VS::INSTANCE_LIGHTMAP_CAPTURE: {
385 
386 				InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(instance->base_data);
387 				//erase dependencies, since no longer a lightmap
388 				while (lightmap_capture->users.front()) {
389 					instance_set_use_lightmap(lightmap_capture->users.front()->get()->self, RID(), RID());
390 				}
391 			} break;
392 			case VS::INSTANCE_GI_PROBE: {
393 
394 				InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
395 
396 				if (gi_probe->update_element.in_list()) {
397 					gi_probe_update_list.remove(&gi_probe->update_element);
398 				}
399 				if (gi_probe->dynamic.probe_data.is_valid()) {
400 					VSG::storage->free(gi_probe->dynamic.probe_data);
401 				}
402 
403 				if (instance->lightmap_capture) {
404 					Instance *capture = (Instance *)instance->lightmap_capture;
405 					InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(capture->base_data);
406 					lightmap_capture->users.erase(instance);
407 					instance->lightmap_capture = NULL;
408 					instance->lightmap = RID();
409 				}
410 
411 				VSG::scene_render->free(gi_probe->probe_instance);
412 
413 			} break;
414 			default: {
415 			}
416 		}
417 
418 		if (instance->base_data) {
419 			memdelete(instance->base_data);
420 			instance->base_data = NULL;
421 		}
422 
423 		instance->blend_values.clear();
424 
425 		for (int i = 0; i < instance->materials.size(); i++) {
426 			if (instance->materials[i].is_valid()) {
427 				VSG::storage->material_remove_instance_owner(instance->materials[i], instance);
428 			}
429 		}
430 		instance->materials.clear();
431 	}
432 
433 	instance->base_type = VS::INSTANCE_NONE;
434 	instance->base = RID();
435 
436 	if (p_base.is_valid()) {
437 
438 		instance->base_type = VSG::storage->get_base_type(p_base);
439 		ERR_FAIL_COND(instance->base_type == VS::INSTANCE_NONE);
440 
441 		switch (instance->base_type) {
442 			case VS::INSTANCE_LIGHT: {
443 
444 				InstanceLightData *light = memnew(InstanceLightData);
445 
446 				if (scenario && VSG::storage->light_get_type(p_base) == VS::LIGHT_DIRECTIONAL) {
447 					light->D = scenario->directional_lights.push_back(instance);
448 				}
449 
450 				light->instance = VSG::scene_render->light_instance_create(p_base);
451 
452 				instance->base_data = light;
453 			} break;
454 			case VS::INSTANCE_MESH:
455 			case VS::INSTANCE_MULTIMESH:
456 			case VS::INSTANCE_IMMEDIATE:
457 			case VS::INSTANCE_PARTICLES: {
458 
459 				InstanceGeometryData *geom = memnew(InstanceGeometryData);
460 				instance->base_data = geom;
461 				if (instance->base_type == VS::INSTANCE_MESH) {
462 					instance->blend_values.resize(VSG::storage->mesh_get_blend_shape_count(p_base));
463 				}
464 			} break;
465 			case VS::INSTANCE_REFLECTION_PROBE: {
466 
467 				InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
468 				reflection_probe->owner = instance;
469 				instance->base_data = reflection_probe;
470 
471 				reflection_probe->instance = VSG::scene_render->reflection_probe_instance_create(p_base);
472 			} break;
473 			case VS::INSTANCE_LIGHTMAP_CAPTURE: {
474 
475 				InstanceLightmapCaptureData *lightmap_capture = memnew(InstanceLightmapCaptureData);
476 				instance->base_data = lightmap_capture;
477 				//lightmap_capture->instance = VSG::scene_render->lightmap_capture_instance_create(p_base);
478 			} break;
479 			case VS::INSTANCE_GI_PROBE: {
480 
481 				InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
482 				instance->base_data = gi_probe;
483 				gi_probe->owner = instance;
484 
485 				if (scenario && !gi_probe->update_element.in_list()) {
486 					gi_probe_update_list.add(&gi_probe->update_element);
487 				}
488 
489 				gi_probe->probe_instance = VSG::scene_render->gi_probe_instance_create();
490 
491 			} break;
492 			default: {
493 			}
494 		}
495 
496 		VSG::storage->instance_add_dependency(p_base, instance);
497 
498 		instance->base = p_base;
499 
500 		if (scenario)
501 			_instance_queue_update(instance, true, true);
502 	}
503 }
instance_set_scenario(RID p_instance,RID p_scenario)504 void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
505 
506 	Instance *instance = instance_owner.get(p_instance);
507 	ERR_FAIL_COND(!instance);
508 
509 	if (instance->scenario) {
510 
511 		instance->scenario->instances.remove(&instance->scenario_item);
512 
513 		if (instance->octree_id) {
514 			instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
515 			instance->octree_id = 0;
516 		}
517 
518 		switch (instance->base_type) {
519 
520 			case VS::INSTANCE_LIGHT: {
521 
522 				InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
523 
524 				if (light->D) {
525 					instance->scenario->directional_lights.erase(light->D);
526 					light->D = NULL;
527 				}
528 			} break;
529 			case VS::INSTANCE_REFLECTION_PROBE: {
530 
531 				InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
532 				VSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
533 			} break;
534 			case VS::INSTANCE_GI_PROBE: {
535 
536 				InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
537 				if (gi_probe->update_element.in_list()) {
538 					gi_probe_update_list.remove(&gi_probe->update_element);
539 				}
540 			} break;
541 			default: {
542 			}
543 		}
544 
545 		instance->scenario = NULL;
546 	}
547 
548 	if (p_scenario.is_valid()) {
549 
550 		Scenario *scenario = scenario_owner.get(p_scenario);
551 		ERR_FAIL_COND(!scenario);
552 
553 		instance->scenario = scenario;
554 
555 		scenario->instances.add(&instance->scenario_item);
556 
557 		switch (instance->base_type) {
558 
559 			case VS::INSTANCE_LIGHT: {
560 
561 				InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
562 
563 				if (VSG::storage->light_get_type(instance->base) == VS::LIGHT_DIRECTIONAL) {
564 					light->D = scenario->directional_lights.push_back(instance);
565 				}
566 			} break;
567 			case VS::INSTANCE_GI_PROBE: {
568 
569 				InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
570 				if (!gi_probe->update_element.in_list()) {
571 					gi_probe_update_list.add(&gi_probe->update_element);
572 				}
573 			} break;
574 			default: {
575 			}
576 		}
577 
578 		_instance_queue_update(instance, true, true);
579 	}
580 }
instance_set_layer_mask(RID p_instance,uint32_t p_mask)581 void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
582 
583 	Instance *instance = instance_owner.get(p_instance);
584 	ERR_FAIL_COND(!instance);
585 
586 	instance->layer_mask = p_mask;
587 }
instance_set_transform(RID p_instance,const Transform & p_transform)588 void VisualServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {
589 
590 	Instance *instance = instance_owner.get(p_instance);
591 	ERR_FAIL_COND(!instance);
592 
593 	if (instance->transform == p_transform)
594 		return; //must be checked to avoid worst evil
595 
596 #ifdef DEBUG_ENABLED
597 
598 	for (int i = 0; i < 4; i++) {
599 		const Vector3 &v = i < 3 ? p_transform.basis.elements[i] : p_transform.origin;
600 		ERR_FAIL_COND(Math::is_inf(v.x));
601 		ERR_FAIL_COND(Math::is_nan(v.x));
602 		ERR_FAIL_COND(Math::is_inf(v.y));
603 		ERR_FAIL_COND(Math::is_nan(v.y));
604 		ERR_FAIL_COND(Math::is_inf(v.z));
605 		ERR_FAIL_COND(Math::is_nan(v.z));
606 	}
607 
608 #endif
609 	instance->transform = p_transform;
610 	_instance_queue_update(instance, true);
611 }
instance_attach_object_instance_id(RID p_instance,ObjectID p_id)612 void VisualServerScene::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
613 
614 	Instance *instance = instance_owner.get(p_instance);
615 	ERR_FAIL_COND(!instance);
616 
617 	instance->object_id = p_id;
618 }
instance_set_blend_shape_weight(RID p_instance,int p_shape,float p_weight)619 void VisualServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
620 
621 	Instance *instance = instance_owner.get(p_instance);
622 	ERR_FAIL_COND(!instance);
623 
624 	if (instance->update_item.in_list()) {
625 		_update_dirty_instance(instance);
626 	}
627 
628 	ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
629 	instance->blend_values.write[p_shape] = p_weight;
630 }
631 
instance_set_surface_material(RID p_instance,int p_surface,RID p_material)632 void VisualServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
633 
634 	Instance *instance = instance_owner.get(p_instance);
635 	ERR_FAIL_COND(!instance);
636 
637 	if (instance->base_type == VS::INSTANCE_MESH) {
638 		//may not have been updated yet
639 		instance->materials.resize(VSG::storage->mesh_get_surface_count(instance->base));
640 	}
641 
642 	ERR_FAIL_INDEX(p_surface, instance->materials.size());
643 
644 	if (instance->materials[p_surface].is_valid()) {
645 		VSG::storage->material_remove_instance_owner(instance->materials[p_surface], instance);
646 	}
647 	instance->materials.write[p_surface] = p_material;
648 	instance->base_changed(false, true);
649 
650 	if (instance->materials[p_surface].is_valid()) {
651 		VSG::storage->material_add_instance_owner(instance->materials[p_surface], instance);
652 	}
653 }
654 
instance_set_visible(RID p_instance,bool p_visible)655 void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) {
656 
657 	Instance *instance = instance_owner.get(p_instance);
658 	ERR_FAIL_COND(!instance);
659 
660 	if (instance->visible == p_visible)
661 		return;
662 
663 	instance->visible = p_visible;
664 
665 	switch (instance->base_type) {
666 		case VS::INSTANCE_LIGHT: {
667 			if (VSG::storage->light_get_type(instance->base) != VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
668 				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_LIGHT, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
669 			}
670 
671 		} break;
672 		case VS::INSTANCE_REFLECTION_PROBE: {
673 			if (instance->octree_id && instance->scenario) {
674 				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_REFLECTION_PROBE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
675 			}
676 
677 		} break;
678 		case VS::INSTANCE_LIGHTMAP_CAPTURE: {
679 			if (instance->octree_id && instance->scenario) {
680 				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_LIGHTMAP_CAPTURE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
681 			}
682 
683 		} break;
684 		case VS::INSTANCE_GI_PROBE: {
685 			if (instance->octree_id && instance->scenario) {
686 				instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_GI_PROBE, p_visible ? (VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT)) : 0);
687 			}
688 
689 		} break;
690 		default: {
691 		}
692 	}
693 }
is_geometry_instance(VisualServer::InstanceType p_type)694 inline bool is_geometry_instance(VisualServer::InstanceType p_type) {
695 	return p_type == VS::INSTANCE_MESH || p_type == VS::INSTANCE_MULTIMESH || p_type == VS::INSTANCE_PARTICLES || p_type == VS::INSTANCE_IMMEDIATE;
696 }
697 
instance_set_use_lightmap(RID p_instance,RID p_lightmap_instance,RID p_lightmap)698 void VisualServerScene::instance_set_use_lightmap(RID p_instance, RID p_lightmap_instance, RID p_lightmap) {
699 
700 	Instance *instance = instance_owner.get(p_instance);
701 	ERR_FAIL_COND(!instance);
702 
703 	if (instance->lightmap_capture) {
704 		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
705 		lightmap_capture->users.erase(instance);
706 		instance->lightmap = RID();
707 		instance->lightmap_capture = NULL;
708 	}
709 
710 	if (p_lightmap_instance.is_valid()) {
711 		Instance *lightmap_instance = instance_owner.get(p_lightmap_instance);
712 		ERR_FAIL_COND(!lightmap_instance);
713 		ERR_FAIL_COND(lightmap_instance->base_type != VS::INSTANCE_LIGHTMAP_CAPTURE);
714 		instance->lightmap_capture = lightmap_instance;
715 
716 		InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
717 		lightmap_capture->users.insert(instance);
718 		instance->lightmap = p_lightmap;
719 	}
720 }
721 
instance_set_custom_aabb(RID p_instance,AABB p_aabb)722 void VisualServerScene::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
723 
724 	Instance *instance = instance_owner.get(p_instance);
725 	ERR_FAIL_COND(!instance);
726 	ERR_FAIL_COND(!is_geometry_instance(instance->base_type));
727 
728 	if (p_aabb != AABB()) {
729 
730 		// Set custom AABB
731 		if (instance->custom_aabb == NULL)
732 			instance->custom_aabb = memnew(AABB);
733 		*instance->custom_aabb = p_aabb;
734 
735 	} else {
736 
737 		// Clear custom AABB
738 		if (instance->custom_aabb != NULL) {
739 			memdelete(instance->custom_aabb);
740 			instance->custom_aabb = NULL;
741 		}
742 	}
743 
744 	if (instance->scenario)
745 		_instance_queue_update(instance, true, false);
746 }
747 
instance_attach_skeleton(RID p_instance,RID p_skeleton)748 void VisualServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
749 
750 	Instance *instance = instance_owner.get(p_instance);
751 	ERR_FAIL_COND(!instance);
752 
753 	if (instance->skeleton == p_skeleton)
754 		return;
755 
756 	if (instance->skeleton.is_valid()) {
757 		VSG::storage->instance_remove_skeleton(instance->skeleton, instance);
758 	}
759 
760 	instance->skeleton = p_skeleton;
761 
762 	if (instance->skeleton.is_valid()) {
763 		VSG::storage->instance_add_skeleton(instance->skeleton, instance);
764 	}
765 
766 	_instance_queue_update(instance, true);
767 }
768 
instance_set_exterior(RID p_instance,bool p_enabled)769 void VisualServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
770 }
771 
instance_set_extra_visibility_margin(RID p_instance,real_t p_margin)772 void VisualServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
773 	Instance *instance = instance_owner.get(p_instance);
774 	ERR_FAIL_COND(!instance);
775 
776 	instance->extra_margin = p_margin;
777 	_instance_queue_update(instance, true, false);
778 }
779 
instances_cull_aabb(const AABB & p_aabb,RID p_scenario) const780 Vector<ObjectID> VisualServerScene::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
781 
782 	Vector<ObjectID> instances;
783 	Scenario *scenario = scenario_owner.get(p_scenario);
784 	ERR_FAIL_COND_V(!scenario, instances);
785 
786 	const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
787 
788 	int culled = 0;
789 	Instance *cull[1024];
790 	culled = scenario->octree.cull_aabb(p_aabb, cull, 1024);
791 
792 	for (int i = 0; i < culled; i++) {
793 
794 		Instance *instance = cull[i];
795 		ERR_CONTINUE(!instance);
796 		if (instance->object_id == 0)
797 			continue;
798 
799 		instances.push_back(instance->object_id);
800 	}
801 
802 	return instances;
803 }
instances_cull_ray(const Vector3 & p_from,const Vector3 & p_to,RID p_scenario) const804 Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
805 
806 	Vector<ObjectID> instances;
807 	Scenario *scenario = scenario_owner.get(p_scenario);
808 	ERR_FAIL_COND_V(!scenario, instances);
809 	const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
810 
811 	int culled = 0;
812 	Instance *cull[1024];
813 	culled = scenario->octree.cull_segment(p_from, p_from + p_to * 10000, cull, 1024);
814 
815 	for (int i = 0; i < culled; i++) {
816 		Instance *instance = cull[i];
817 		ERR_CONTINUE(!instance);
818 		if (instance->object_id == 0)
819 			continue;
820 
821 		instances.push_back(instance->object_id);
822 	}
823 
824 	return instances;
825 }
instances_cull_convex(const Vector<Plane> & p_convex,RID p_scenario) const826 Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
827 
828 	Vector<ObjectID> instances;
829 	Scenario *scenario = scenario_owner.get(p_scenario);
830 	ERR_FAIL_COND_V(!scenario, instances);
831 	const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
832 
833 	int culled = 0;
834 	Instance *cull[1024];
835 
836 	culled = scenario->octree.cull_convex(p_convex, cull, 1024);
837 
838 	for (int i = 0; i < culled; i++) {
839 
840 		Instance *instance = cull[i];
841 		ERR_CONTINUE(!instance);
842 		if (instance->object_id == 0)
843 			continue;
844 
845 		instances.push_back(instance->object_id);
846 	}
847 
848 	return instances;
849 }
850 
instance_geometry_set_flag(RID p_instance,VS::InstanceFlags p_flags,bool p_enabled)851 void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled) {
852 
853 	Instance *instance = instance_owner.get(p_instance);
854 	ERR_FAIL_COND(!instance);
855 
856 	switch (p_flags) {
857 
858 		case VS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
859 
860 			instance->baked_light = p_enabled;
861 
862 		} break;
863 		case VS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
864 
865 			instance->redraw_if_visible = p_enabled;
866 
867 		} break;
868 		default: {
869 		}
870 	}
871 }
instance_geometry_set_cast_shadows_setting(RID p_instance,VS::ShadowCastingSetting p_shadow_casting_setting)872 void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) {
873 
874 	Instance *instance = instance_owner.get(p_instance);
875 	ERR_FAIL_COND(!instance);
876 
877 	instance->cast_shadows = p_shadow_casting_setting;
878 	instance->base_changed(false, true); // to actually compute if shadows are visible or not
879 }
instance_geometry_set_material_override(RID p_instance,RID p_material)880 void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {
881 
882 	Instance *instance = instance_owner.get(p_instance);
883 	ERR_FAIL_COND(!instance);
884 
885 	if (instance->material_override.is_valid()) {
886 		VSG::storage->material_remove_instance_owner(instance->material_override, instance);
887 	}
888 	instance->material_override = p_material;
889 	instance->base_changed(false, true);
890 
891 	if (instance->material_override.is_valid()) {
892 		VSG::storage->material_add_instance_owner(instance->material_override, instance);
893 	}
894 }
895 
instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin)896 void VisualServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
897 }
instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance)898 void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
899 }
900 
_update_instance(Instance * p_instance)901 void VisualServerScene::_update_instance(Instance *p_instance) {
902 
903 	p_instance->version++;
904 
905 	if (p_instance->base_type == VS::INSTANCE_LIGHT) {
906 
907 		InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
908 
909 		VSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform);
910 		light->shadow_dirty = true;
911 	}
912 
913 	if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
914 
915 		InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
916 
917 		VSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
918 		reflection_probe->reflection_dirty = true;
919 	}
920 
921 	if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
922 
923 		VSG::storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
924 	}
925 
926 	if (p_instance->aabb.has_no_surface()) {
927 		return;
928 	}
929 
930 	if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
931 
932 		InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
933 		//make sure lights are updated if it casts shadow
934 
935 		if (geom->can_cast_shadows) {
936 			for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
937 				InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
938 				light->shadow_dirty = true;
939 			}
940 		}
941 
942 		if (!p_instance->lightmap_capture && geom->lightmap_captures.size()) {
943 			//affected by lightmap captures, must update capture info!
944 			_update_instance_lightmap_captures(p_instance);
945 		} else {
946 			if (!p_instance->lightmap_capture_data.empty()) {
947 				p_instance->lightmap_capture_data.resize(0); //not in use, clear capture data
948 			}
949 		}
950 	}
951 
952 	p_instance->mirror = p_instance->transform.basis.determinant() < 0.0;
953 
954 	AABB new_aabb;
955 
956 	new_aabb = p_instance->transform.xform(p_instance->aabb);
957 
958 	p_instance->transformed_aabb = new_aabb;
959 
960 	if (!p_instance->scenario) {
961 
962 		return;
963 	}
964 
965 	if (p_instance->octree_id == 0) {
966 
967 		uint32_t base_type = 1 << p_instance->base_type;
968 		uint32_t pairable_mask = 0;
969 		bool pairable = false;
970 
971 		if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE || p_instance->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE) {
972 
973 			pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK : 0;
974 			pairable = true;
975 		}
976 
977 		if (p_instance->base_type == VS::INSTANCE_GI_PROBE) {
978 			//lights and geometries
979 			pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT) : 0;
980 			pairable = true;
981 		}
982 
983 		// not inside octree
984 		p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);
985 
986 	} else {
987 
988 		/*
989 		if (new_aabb==p_instance->data.transformed_aabb)
990 			return;
991 		*/
992 
993 		p_instance->scenario->octree.move(p_instance->octree_id, new_aabb);
994 	}
995 }
996 
_update_instance_aabb(Instance * p_instance)997 void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
998 
999 	AABB new_aabb;
1000 
1001 	ERR_FAIL_COND(p_instance->base_type != VS::INSTANCE_NONE && !p_instance->base.is_valid());
1002 
1003 	switch (p_instance->base_type) {
1004 		case VisualServer::INSTANCE_NONE: {
1005 
1006 			// do nothing
1007 		} break;
1008 		case VisualServer::INSTANCE_MESH: {
1009 
1010 			if (p_instance->custom_aabb)
1011 				new_aabb = *p_instance->custom_aabb;
1012 			else
1013 				new_aabb = VSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
1014 
1015 		} break;
1016 
1017 		case VisualServer::INSTANCE_MULTIMESH: {
1018 
1019 			if (p_instance->custom_aabb)
1020 				new_aabb = *p_instance->custom_aabb;
1021 			else
1022 				new_aabb = VSG::storage->multimesh_get_aabb(p_instance->base);
1023 
1024 		} break;
1025 		case VisualServer::INSTANCE_IMMEDIATE: {
1026 
1027 			if (p_instance->custom_aabb)
1028 				new_aabb = *p_instance->custom_aabb;
1029 			else
1030 				new_aabb = VSG::storage->immediate_get_aabb(p_instance->base);
1031 
1032 		} break;
1033 		case VisualServer::INSTANCE_PARTICLES: {
1034 
1035 			if (p_instance->custom_aabb)
1036 				new_aabb = *p_instance->custom_aabb;
1037 			else
1038 				new_aabb = VSG::storage->particles_get_aabb(p_instance->base);
1039 
1040 		} break;
1041 		case VisualServer::INSTANCE_LIGHT: {
1042 
1043 			new_aabb = VSG::storage->light_get_aabb(p_instance->base);
1044 
1045 		} break;
1046 		case VisualServer::INSTANCE_REFLECTION_PROBE: {
1047 
1048 			new_aabb = VSG::storage->reflection_probe_get_aabb(p_instance->base);
1049 
1050 		} break;
1051 		case VisualServer::INSTANCE_GI_PROBE: {
1052 
1053 			new_aabb = VSG::storage->gi_probe_get_bounds(p_instance->base);
1054 
1055 		} break;
1056 		case VisualServer::INSTANCE_LIGHTMAP_CAPTURE: {
1057 
1058 			new_aabb = VSG::storage->lightmap_capture_get_bounds(p_instance->base);
1059 
1060 		} break;
1061 		default: {
1062 		}
1063 	}
1064 
1065 	// <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
1066 	if (p_instance->extra_margin)
1067 		new_aabb.grow_by(p_instance->extra_margin);
1068 
1069 	p_instance->aabb = new_aabb;
1070 }
1071 
_light_capture_sample_octree(const RasterizerStorage::LightmapCaptureOctree * p_octree,int p_cell_subdiv,const Vector3 & p_pos,const Vector3 & p_dir,float p_level,Vector3 & r_color,float & r_alpha)1072 _FORCE_INLINE_ static void _light_capture_sample_octree(const RasterizerStorage::LightmapCaptureOctree *p_octree, int p_cell_subdiv, const Vector3 &p_pos, const Vector3 &p_dir, float p_level, Vector3 &r_color, float &r_alpha) {
1073 
1074 	static const Vector3 aniso_normal[6] = {
1075 		Vector3(-1, 0, 0),
1076 		Vector3(1, 0, 0),
1077 		Vector3(0, -1, 0),
1078 		Vector3(0, 1, 0),
1079 		Vector3(0, 0, -1),
1080 		Vector3(0, 0, 1)
1081 	};
1082 
1083 	int size = 1 << (p_cell_subdiv - 1);
1084 
1085 	int clamp_v = size - 1;
1086 	//first of all, clamp
1087 	Vector3 pos;
1088 	pos.x = CLAMP(p_pos.x, 0, clamp_v);
1089 	pos.y = CLAMP(p_pos.y, 0, clamp_v);
1090 	pos.z = CLAMP(p_pos.z, 0, clamp_v);
1091 
1092 	float level = (p_cell_subdiv - 1) - p_level;
1093 
1094 	int target_level;
1095 	float level_filter;
1096 	if (level <= 0.0) {
1097 		level_filter = 0;
1098 		target_level = 0;
1099 	} else {
1100 		target_level = Math::ceil(level);
1101 		level_filter = target_level - level;
1102 	}
1103 
1104 	Vector3 color[2][8];
1105 	float alpha[2][8];
1106 	zeromem(alpha, sizeof(float) * 2 * 8);
1107 
1108 	//find cell at given level first
1109 
1110 	for (int c = 0; c < 2; c++) {
1111 
1112 		int current_level = MAX(0, target_level - c);
1113 		int level_cell_size = (1 << (p_cell_subdiv - 1)) >> current_level;
1114 
1115 		for (int n = 0; n < 8; n++) {
1116 
1117 			int x = int(pos.x);
1118 			int y = int(pos.y);
1119 			int z = int(pos.z);
1120 
1121 			if (n & 1)
1122 				x += level_cell_size;
1123 			if (n & 2)
1124 				y += level_cell_size;
1125 			if (n & 4)
1126 				z += level_cell_size;
1127 
1128 			int ofs_x = 0;
1129 			int ofs_y = 0;
1130 			int ofs_z = 0;
1131 
1132 			x = CLAMP(x, 0, clamp_v);
1133 			y = CLAMP(y, 0, clamp_v);
1134 			z = CLAMP(z, 0, clamp_v);
1135 
1136 			int half = size / 2;
1137 			uint32_t cell = 0;
1138 			for (int i = 0; i < current_level; i++) {
1139 
1140 				const RasterizerStorage::LightmapCaptureOctree *bc = &p_octree[cell];
1141 
1142 				int child = 0;
1143 				if (x >= ofs_x + half) {
1144 					child |= 1;
1145 					ofs_x += half;
1146 				}
1147 				if (y >= ofs_y + half) {
1148 					child |= 2;
1149 					ofs_y += half;
1150 				}
1151 				if (z >= ofs_z + half) {
1152 					child |= 4;
1153 					ofs_z += half;
1154 				}
1155 
1156 				cell = bc->children[child];
1157 				if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY)
1158 					break;
1159 
1160 				half >>= 1;
1161 			}
1162 
1163 			if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY) {
1164 				alpha[c][n] = 0;
1165 			} else {
1166 				alpha[c][n] = p_octree[cell].alpha;
1167 
1168 				for (int i = 0; i < 6; i++) {
1169 					//anisotropic read light
1170 					float amount = p_dir.dot(aniso_normal[i]);
1171 					if (amount < 0)
1172 						amount = 0;
1173 					color[c][n].x += p_octree[cell].light[i][0] / 1024.0 * amount;
1174 					color[c][n].y += p_octree[cell].light[i][1] / 1024.0 * amount;
1175 					color[c][n].z += p_octree[cell].light[i][2] / 1024.0 * amount;
1176 				}
1177 			}
1178 
1179 			//print_line("\tlev " + itos(c) + " - " + itos(n) + " alpha: " + rtos(cells[test_cell].alpha) + " col: " + color[c][n]);
1180 		}
1181 	}
1182 
1183 	float target_level_size = size >> target_level;
1184 	Vector3 pos_fract[2];
1185 
1186 	pos_fract[0].x = Math::fmod(pos.x, target_level_size) / target_level_size;
1187 	pos_fract[0].y = Math::fmod(pos.y, target_level_size) / target_level_size;
1188 	pos_fract[0].z = Math::fmod(pos.z, target_level_size) / target_level_size;
1189 
1190 	target_level_size = size >> MAX(0, target_level - 1);
1191 
1192 	pos_fract[1].x = Math::fmod(pos.x, target_level_size) / target_level_size;
1193 	pos_fract[1].y = Math::fmod(pos.y, target_level_size) / target_level_size;
1194 	pos_fract[1].z = Math::fmod(pos.z, target_level_size) / target_level_size;
1195 
1196 	float alpha_interp[2];
1197 	Vector3 color_interp[2];
1198 
1199 	for (int i = 0; i < 2; i++) {
1200 
1201 		Vector3 color_x00 = color[i][0].linear_interpolate(color[i][1], pos_fract[i].x);
1202 		Vector3 color_xy0 = color[i][2].linear_interpolate(color[i][3], pos_fract[i].x);
1203 		Vector3 blend_z0 = color_x00.linear_interpolate(color_xy0, pos_fract[i].y);
1204 
1205 		Vector3 color_x0z = color[i][4].linear_interpolate(color[i][5], pos_fract[i].x);
1206 		Vector3 color_xyz = color[i][6].linear_interpolate(color[i][7], pos_fract[i].x);
1207 		Vector3 blend_z1 = color_x0z.linear_interpolate(color_xyz, pos_fract[i].y);
1208 
1209 		color_interp[i] = blend_z0.linear_interpolate(blend_z1, pos_fract[i].z);
1210 
1211 		float alpha_x00 = Math::lerp(alpha[i][0], alpha[i][1], pos_fract[i].x);
1212 		float alpha_xy0 = Math::lerp(alpha[i][2], alpha[i][3], pos_fract[i].x);
1213 		float alpha_z0 = Math::lerp(alpha_x00, alpha_xy0, pos_fract[i].y);
1214 
1215 		float alpha_x0z = Math::lerp(alpha[i][4], alpha[i][5], pos_fract[i].x);
1216 		float alpha_xyz = Math::lerp(alpha[i][6], alpha[i][7], pos_fract[i].x);
1217 		float alpha_z1 = Math::lerp(alpha_x0z, alpha_xyz, pos_fract[i].y);
1218 
1219 		alpha_interp[i] = Math::lerp(alpha_z0, alpha_z1, pos_fract[i].z);
1220 	}
1221 
1222 	r_color = color_interp[0].linear_interpolate(color_interp[1], level_filter);
1223 	r_alpha = Math::lerp(alpha_interp[0], alpha_interp[1], level_filter);
1224 
1225 	//print_line("pos: " + p_posf + " level " + rtos(p_level) + " down to " + itos(target_level) + "." + rtos(level_filter) + " color " + r_color + " alpha " + rtos(r_alpha));
1226 }
1227 
_light_capture_voxel_cone_trace(const RasterizerStorage::LightmapCaptureOctree * p_octree,const Vector3 & p_pos,const Vector3 & p_dir,float p_aperture,int p_cell_subdiv)1228 _FORCE_INLINE_ static Color _light_capture_voxel_cone_trace(const RasterizerStorage::LightmapCaptureOctree *p_octree, const Vector3 &p_pos, const Vector3 &p_dir, float p_aperture, int p_cell_subdiv) {
1229 
1230 	float bias = 0.0; //no need for bias here
1231 	float max_distance = (Vector3(1, 1, 1) * (1 << (p_cell_subdiv - 1))).length();
1232 
1233 	float dist = bias;
1234 	float alpha = 0.0;
1235 	Vector3 color;
1236 
1237 	Vector3 scolor;
1238 	float salpha;
1239 
1240 	while (dist < max_distance && alpha < 0.95) {
1241 		float diameter = MAX(1.0, 2.0 * p_aperture * dist);
1242 		_light_capture_sample_octree(p_octree, p_cell_subdiv, p_pos + dist * p_dir, p_dir, log2(diameter), scolor, salpha);
1243 		float a = (1.0 - alpha);
1244 		color += scolor * a;
1245 		alpha += a * salpha;
1246 		dist += diameter * 0.5;
1247 	}
1248 
1249 	return Color(color.x, color.y, color.z, alpha);
1250 }
1251 
_update_instance_lightmap_captures(Instance * p_instance)1252 void VisualServerScene::_update_instance_lightmap_captures(Instance *p_instance) {
1253 
1254 	InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
1255 
1256 	static const Vector3 cone_traces[12] = {
1257 		Vector3(0, 0, 1),
1258 		Vector3(0.866025, 0, 0.5),
1259 		Vector3(0.267617, 0.823639, 0.5),
1260 		Vector3(-0.700629, 0.509037, 0.5),
1261 		Vector3(-0.700629, -0.509037, 0.5),
1262 		Vector3(0.267617, -0.823639, 0.5),
1263 		Vector3(0, 0, -1),
1264 		Vector3(0.866025, 0, -0.5),
1265 		Vector3(0.267617, 0.823639, -0.5),
1266 		Vector3(-0.700629, 0.509037, -0.5),
1267 		Vector3(-0.700629, -0.509037, -0.5),
1268 		Vector3(0.267617, -0.823639, -0.5)
1269 	};
1270 
1271 	float cone_aperture = 0.577; // tan(angle) 60 degrees
1272 
1273 	if (p_instance->lightmap_capture_data.empty()) {
1274 		p_instance->lightmap_capture_data.resize(12);
1275 	}
1276 
1277 	//print_line("update captures for pos: " + p_instance->transform.origin);
1278 
1279 	for (int i = 0; i < 12; i++)
1280 		new (&p_instance->lightmap_capture_data.ptrw()[i]) Color;
1281 
1282 	//this could use some sort of blending..
1283 	for (List<Instance *>::Element *E = geom->lightmap_captures.front(); E; E = E->next()) {
1284 		const PoolVector<RasterizerStorage::LightmapCaptureOctree> *octree = VSG::storage->lightmap_capture_get_octree_ptr(E->get()->base);
1285 		//print_line("octree size: " + itos(octree->size()));
1286 		if (octree->size() == 0)
1287 			continue;
1288 		Transform to_cell_xform = VSG::storage->lightmap_capture_get_octree_cell_transform(E->get()->base);
1289 		int cell_subdiv = VSG::storage->lightmap_capture_get_octree_cell_subdiv(E->get()->base);
1290 		to_cell_xform = to_cell_xform * E->get()->transform.affine_inverse();
1291 
1292 		PoolVector<RasterizerStorage::LightmapCaptureOctree>::Read octree_r = octree->read();
1293 
1294 		Vector3 pos = to_cell_xform.xform(p_instance->transform.origin);
1295 
1296 		for (int i = 0; i < 12; i++) {
1297 
1298 			Vector3 dir = to_cell_xform.basis.xform(cone_traces[i]).normalized();
1299 			Color capture = _light_capture_voxel_cone_trace(octree_r.ptr(), pos, dir, cone_aperture, cell_subdiv);
1300 			p_instance->lightmap_capture_data.write[i] += capture;
1301 		}
1302 	}
1303 }
1304 
_light_instance_update_shadow(Instance * p_instance,const Transform p_cam_transform,const CameraMatrix & p_cam_projection,bool p_cam_orthogonal,RID p_shadow_atlas,Scenario * p_scenario)1305 bool VisualServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario) {
1306 
1307 	InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
1308 
1309 	Transform light_transform = p_instance->transform;
1310 	light_transform.orthonormalize(); //scale does not count on lights
1311 
1312 	bool animated_material_found = false;
1313 
1314 	switch (VSG::storage->light_get_type(p_instance->base)) {
1315 
1316 		case VS::LIGHT_DIRECTIONAL: {
1317 
1318 			float max_distance = p_cam_projection.get_z_far();
1319 			float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
1320 			if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
1321 				max_distance = MIN(shadow_max, max_distance);
1322 			}
1323 			max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
1324 			float min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
1325 
1326 			VS::LightDirectionalShadowDepthRangeMode depth_range_mode = VSG::storage->light_directional_get_shadow_depth_range_mode(p_instance->base);
1327 
1328 			if (depth_range_mode == VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_OPTIMIZED) {
1329 				//optimize min/max
1330 				Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
1331 				int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
1332 				Plane base(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2));
1333 				//check distance max and min
1334 
1335 				bool found_items = false;
1336 				float z_max = -1e20;
1337 				float z_min = 1e20;
1338 
1339 				for (int i = 0; i < cull_count; i++) {
1340 
1341 					Instance *instance = instance_shadow_cull_result[i];
1342 					if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
1343 						continue;
1344 					}
1345 
1346 					if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
1347 						animated_material_found = true;
1348 					}
1349 
1350 					float max, min;
1351 					instance->transformed_aabb.project_range_in_plane(base, min, max);
1352 
1353 					if (max > z_max) {
1354 						z_max = max;
1355 					}
1356 
1357 					if (min < z_min) {
1358 						z_min = min;
1359 					}
1360 
1361 					found_items = true;
1362 				}
1363 
1364 				if (found_items) {
1365 					min_distance = MAX(min_distance, z_min);
1366 					max_distance = MIN(max_distance, z_max);
1367 				}
1368 			}
1369 
1370 			float range = max_distance - min_distance;
1371 
1372 			int splits = 0;
1373 			switch (VSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
1374 				case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits = 1; break;
1375 				case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits = 2; break;
1376 				case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits = 4; break;
1377 			}
1378 
1379 			float distances[5];
1380 
1381 			distances[0] = min_distance;
1382 			for (int i = 0; i < splits; i++) {
1383 				distances[i + 1] = min_distance + VSG::storage->light_get_param(p_instance->base, VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
1384 			};
1385 
1386 			distances[splits] = max_distance;
1387 
1388 			float texture_size = VSG::scene_render->get_directional_light_shadow_size(light->instance);
1389 
1390 			bool overlap = VSG::storage->light_directional_get_blend_splits(p_instance->base);
1391 
1392 			float first_radius = 0.0;
1393 
1394 			for (int i = 0; i < splits; i++) {
1395 
1396 				// setup a camera matrix for that range!
1397 				CameraMatrix camera_matrix;
1398 
1399 				float aspect = p_cam_projection.get_aspect();
1400 
1401 				if (p_cam_orthogonal) {
1402 
1403 					Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
1404 
1405 					camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
1406 				} else {
1407 
1408 					float fov = p_cam_projection.get_fov();
1409 					camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
1410 				}
1411 
1412 				//obtain the frustum endpoints
1413 
1414 				Vector3 endpoints[8]; // frustum plane endpoints
1415 				bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
1416 				ERR_CONTINUE(!res);
1417 
1418 				// obtain the light frustm ranges (given endpoints)
1419 
1420 				Transform transform = light_transform; //discard scale and stabilize light
1421 
1422 				Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
1423 				Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
1424 				Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
1425 				//z_vec points agsint the camera, like in default opengl
1426 
1427 				float x_min = 0.f, x_max = 0.f;
1428 				float y_min = 0.f, y_max = 0.f;
1429 				float z_min = 0.f, z_max = 0.f;
1430 
1431 				// FIXME: z_max_cam is defined, computed, but not used below when setting up
1432 				// ortho_camera. Commented out for now to fix warnings but should be investigated.
1433 				float x_min_cam = 0.f, x_max_cam = 0.f;
1434 				float y_min_cam = 0.f, y_max_cam = 0.f;
1435 				float z_min_cam = 0.f;
1436 				//float z_max_cam = 0.f;
1437 
1438 				float bias_scale = 1.0;
1439 
1440 				//used for culling
1441 
1442 				for (int j = 0; j < 8; j++) {
1443 
1444 					float d_x = x_vec.dot(endpoints[j]);
1445 					float d_y = y_vec.dot(endpoints[j]);
1446 					float d_z = z_vec.dot(endpoints[j]);
1447 
1448 					if (j == 0 || d_x < x_min)
1449 						x_min = d_x;
1450 					if (j == 0 || d_x > x_max)
1451 						x_max = d_x;
1452 
1453 					if (j == 0 || d_y < y_min)
1454 						y_min = d_y;
1455 					if (j == 0 || d_y > y_max)
1456 						y_max = d_y;
1457 
1458 					if (j == 0 || d_z < z_min)
1459 						z_min = d_z;
1460 					if (j == 0 || d_z > z_max)
1461 						z_max = d_z;
1462 				}
1463 
1464 				{
1465 					//camera viewport stuff
1466 
1467 					Vector3 center;
1468 
1469 					for (int j = 0; j < 8; j++) {
1470 
1471 						center += endpoints[j];
1472 					}
1473 					center /= 8.0;
1474 
1475 					//center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5;
1476 
1477 					float radius = 0;
1478 
1479 					for (int j = 0; j < 8; j++) {
1480 
1481 						float d = center.distance_to(endpoints[j]);
1482 						if (d > radius)
1483 							radius = d;
1484 					}
1485 
1486 					radius *= texture_size / (texture_size - 2.0); //add a texel by each side
1487 
1488 					if (i == 0) {
1489 						first_radius = radius;
1490 					} else {
1491 						bias_scale = radius / first_radius;
1492 					}
1493 
1494 					x_max_cam = x_vec.dot(center) + radius;
1495 					x_min_cam = x_vec.dot(center) - radius;
1496 					y_max_cam = y_vec.dot(center) + radius;
1497 					y_min_cam = y_vec.dot(center) - radius;
1498 					//z_max_cam = z_vec.dot(center) + radius;
1499 					z_min_cam = z_vec.dot(center) - radius;
1500 
1501 					if (depth_range_mode == VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE) {
1502 						//this trick here is what stabilizes the shadow (make potential jaggies to not move)
1503 						//at the cost of some wasted resolution. Still the quality increase is very well worth it
1504 
1505 						float unit = radius * 2.0 / texture_size;
1506 
1507 						x_max_cam = Math::stepify(x_max_cam, unit);
1508 						x_min_cam = Math::stepify(x_min_cam, unit);
1509 						y_max_cam = Math::stepify(y_max_cam, unit);
1510 						y_min_cam = Math::stepify(y_min_cam, unit);
1511 					}
1512 				}
1513 
1514 				//now that we now all ranges, we can proceed to make the light frustum planes, for culling octree
1515 
1516 				Vector<Plane> light_frustum_planes;
1517 				light_frustum_planes.resize(6);
1518 
1519 				//right/left
1520 				light_frustum_planes.write[0] = Plane(x_vec, x_max);
1521 				light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
1522 				//top/bottom
1523 				light_frustum_planes.write[2] = Plane(y_vec, y_max);
1524 				light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
1525 				//near/far
1526 				light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
1527 				light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
1528 
1529 				int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
1530 
1531 				// a pre pass will need to be needed to determine the actual z-near to be used
1532 
1533 				Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
1534 
1535 				for (int j = 0; j < cull_count; j++) {
1536 
1537 					float min, max;
1538 					Instance *instance = instance_shadow_cull_result[j];
1539 					if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
1540 						cull_count--;
1541 						SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
1542 						j--;
1543 						continue;
1544 					}
1545 
1546 					instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
1547 					instance->depth = near_plane.distance_to(instance->transform.origin);
1548 					instance->depth_layer = 0;
1549 					if (max > z_max)
1550 						z_max = max;
1551 				}
1552 
1553 				{
1554 
1555 					CameraMatrix ortho_camera;
1556 					real_t half_x = (x_max_cam - x_min_cam) * 0.5;
1557 					real_t half_y = (y_max_cam - y_min_cam) * 0.5;
1558 
1559 					ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
1560 
1561 					Transform ortho_transform;
1562 					ortho_transform.basis = transform.basis;
1563 					ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
1564 
1565 					VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i, bias_scale);
1566 				}
1567 
1568 				VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
1569 			}
1570 
1571 		} break;
1572 		case VS::LIGHT_OMNI: {
1573 
1574 			VS::LightOmniShadowMode shadow_mode = VSG::storage->light_omni_get_shadow_mode(p_instance->base);
1575 
1576 			if (shadow_mode == VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !VSG::scene_render->light_instances_can_render_shadow_cube()) {
1577 
1578 				for (int i = 0; i < 2; i++) {
1579 
1580 					//using this one ensures that raster deferred will have it
1581 
1582 					float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
1583 
1584 					float z = i == 0 ? -1 : 1;
1585 					Vector<Plane> planes;
1586 					planes.resize(6);
1587 					planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
1588 					planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
1589 					planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
1590 					planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
1591 					planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
1592 					planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
1593 
1594 					int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
1595 					Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z);
1596 
1597 					for (int j = 0; j < cull_count; j++) {
1598 
1599 						Instance *instance = instance_shadow_cull_result[j];
1600 						if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
1601 							cull_count--;
1602 							SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
1603 							j--;
1604 						} else {
1605 							if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
1606 								animated_material_found = true;
1607 							}
1608 
1609 							instance->depth = near_plane.distance_to(instance->transform.origin);
1610 							instance->depth_layer = 0;
1611 						}
1612 					}
1613 
1614 					VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, i);
1615 					VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
1616 				}
1617 			} else { //shadow cube
1618 
1619 				float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
1620 				CameraMatrix cm;
1621 				cm.set_perspective(90, 1, 0.01, radius);
1622 
1623 				for (int i = 0; i < 6; i++) {
1624 
1625 					//using this one ensures that raster deferred will have it
1626 
1627 					static const Vector3 view_normals[6] = {
1628 						Vector3(-1, 0, 0),
1629 						Vector3(+1, 0, 0),
1630 						Vector3(0, -1, 0),
1631 						Vector3(0, +1, 0),
1632 						Vector3(0, 0, -1),
1633 						Vector3(0, 0, +1)
1634 					};
1635 					static const Vector3 view_up[6] = {
1636 						Vector3(0, -1, 0),
1637 						Vector3(0, -1, 0),
1638 						Vector3(0, 0, -1),
1639 						Vector3(0, 0, +1),
1640 						Vector3(0, -1, 0),
1641 						Vector3(0, -1, 0)
1642 					};
1643 
1644 					Transform xform = light_transform * Transform().looking_at(view_normals[i], view_up[i]);
1645 
1646 					Vector<Plane> planes = cm.get_projection_planes(xform);
1647 
1648 					int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
1649 
1650 					Plane near_plane(xform.origin, -xform.basis.get_axis(2));
1651 					for (int j = 0; j < cull_count; j++) {
1652 
1653 						Instance *instance = instance_shadow_cull_result[j];
1654 						if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
1655 							cull_count--;
1656 							SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
1657 							j--;
1658 						} else {
1659 							if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
1660 								animated_material_found = true;
1661 							}
1662 							instance->depth = near_plane.distance_to(instance->transform.origin);
1663 							instance->depth_layer = 0;
1664 						}
1665 					}
1666 
1667 					VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i);
1668 					VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
1669 				}
1670 
1671 				//restore the regular DP matrix
1672 				VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, 0);
1673 			}
1674 
1675 		} break;
1676 		case VS::LIGHT_SPOT: {
1677 
1678 			float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
1679 			float angle = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE);
1680 
1681 			CameraMatrix cm;
1682 			cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
1683 
1684 			Vector<Plane> planes = cm.get_projection_planes(light_transform);
1685 			int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
1686 
1687 			Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
1688 			for (int j = 0; j < cull_count; j++) {
1689 
1690 				Instance *instance = instance_shadow_cull_result[j];
1691 				if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
1692 					cull_count--;
1693 					SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
1694 					j--;
1695 				} else {
1696 					if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
1697 						animated_material_found = true;
1698 					}
1699 					instance->depth = near_plane.distance_to(instance->transform.origin);
1700 					instance->depth_layer = 0;
1701 				}
1702 			}
1703 
1704 			VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0);
1705 			VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
1706 
1707 		} break;
1708 	}
1709 
1710 	return animated_material_found;
1711 }
1712 
render_camera(RID p_camera,RID p_scenario,Size2 p_viewport_size,RID p_shadow_atlas)1713 void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
1714 // render to mono camera
1715 #ifndef _3D_DISABLED
1716 
1717 	Camera *camera = camera_owner.getornull(p_camera);
1718 	ERR_FAIL_COND(!camera);
1719 
1720 	/* STEP 1 - SETUP CAMERA */
1721 	CameraMatrix camera_matrix;
1722 	bool ortho = false;
1723 
1724 	switch (camera->type) {
1725 		case Camera::ORTHOGONAL: {
1726 
1727 			camera_matrix.set_orthogonal(
1728 					camera->size,
1729 					p_viewport_size.width / (float)p_viewport_size.height,
1730 					camera->znear,
1731 					camera->zfar,
1732 					camera->vaspect);
1733 			ortho = true;
1734 		} break;
1735 		case Camera::PERSPECTIVE: {
1736 
1737 			camera_matrix.set_perspective(
1738 					camera->fov,
1739 					p_viewport_size.width / (float)p_viewport_size.height,
1740 					camera->znear,
1741 					camera->zfar,
1742 					camera->vaspect);
1743 			ortho = false;
1744 
1745 		} break;
1746 		case Camera::FRUSTUM: {
1747 
1748 			camera_matrix.set_frustum(
1749 					camera->size,
1750 					p_viewport_size.width / (float)p_viewport_size.height,
1751 					camera->offset,
1752 					camera->znear,
1753 					camera->zfar,
1754 					camera->vaspect);
1755 			ortho = false;
1756 		} break;
1757 	}
1758 
1759 	_prepare_scene(camera->transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
1760 	_render_scene(camera->transform, camera_matrix, ortho, camera->env, p_scenario, p_shadow_atlas, RID(), -1);
1761 #endif
1762 }
1763 
render_camera(Ref<ARVRInterface> & p_interface,ARVRInterface::Eyes p_eye,RID p_camera,RID p_scenario,Size2 p_viewport_size,RID p_shadow_atlas)1764 void VisualServerScene::render_camera(Ref<ARVRInterface> &p_interface, ARVRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
1765 	// render for AR/VR interface
1766 
1767 	Camera *camera = camera_owner.getornull(p_camera);
1768 	ERR_FAIL_COND(!camera);
1769 
1770 	/* SETUP CAMERA, we are ignoring type and FOV here */
1771 	float aspect = p_viewport_size.width / (float)p_viewport_size.height;
1772 	CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);
1773 
1774 	// We also ignore our camera position, it will have been positioned with a slightly old tracking position.
1775 	// Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
1776 	Transform world_origin = ARVRServer::get_singleton()->get_world_origin();
1777 	Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);
1778 
1779 	// For stereo render we only prepare for our left eye and then reuse the outcome for our right eye
1780 	if (p_eye == ARVRInterface::EYE_LEFT) {
1781 		///@TODO possibly move responsibility for this into our ARVRServer or ARVRInterface?
1782 
1783 		// Center our transform, we assume basis is equal.
1784 		Transform mono_transform = cam_transform;
1785 		Transform right_transform = p_interface->get_transform_for_eye(ARVRInterface::EYE_RIGHT, world_origin);
1786 		mono_transform.origin += right_transform.origin;
1787 		mono_transform.origin *= 0.5;
1788 
1789 		// We need to combine our projection frustums for culling.
1790 		// Ideally we should use our clipping planes for this and combine them,
1791 		// however our shadow map logic uses our projection matrix.
1792 		// Note: as our left and right frustums should be mirrored, we don't need our right projection matrix.
1793 
1794 		// - get some base values we need
1795 		float eye_dist = (mono_transform.origin - cam_transform.origin).length();
1796 		float z_near = camera_matrix.get_z_near(); // get our near plane
1797 		float z_far = camera_matrix.get_z_far(); // get our far plane
1798 		float width = (2.0 * z_near) / camera_matrix.matrix[0][0];
1799 		float x_shift = width * camera_matrix.matrix[2][0];
1800 		float height = (2.0 * z_near) / camera_matrix.matrix[1][1];
1801 		float y_shift = height * camera_matrix.matrix[2][1];
1802 
1803 		// printf("Eye_dist = %f, Near = %f, Far = %f, Width = %f, Shift = %f\n", eye_dist, z_near, z_far, width, x_shift);
1804 
1805 		// - calculate our near plane size (horizontal only, right_near is mirrored)
1806 		float left_near = -eye_dist - ((width - x_shift) * 0.5);
1807 
1808 		// - calculate our far plane size (horizontal only, right_far is mirrored)
1809 		float left_far = -eye_dist - (z_far * (width - x_shift) * 0.5 / z_near);
1810 		float left_far_right_eye = eye_dist - (z_far * (width + x_shift) * 0.5 / z_near);
1811 		if (left_far > left_far_right_eye) {
1812 			// on displays smaller then double our iod, the right eye far frustrum can overtake the left eyes.
1813 			left_far = left_far_right_eye;
1814 		}
1815 
1816 		// - figure out required z-shift
1817 		float slope = (left_far - left_near) / (z_far - z_near);
1818 		float z_shift = (left_near / slope) - z_near;
1819 
1820 		// - figure out new vertical near plane size (this will be slightly oversized thanks to our z-shift)
1821 		float top_near = (height - y_shift) * 0.5;
1822 		top_near += (top_near / z_near) * z_shift;
1823 		float bottom_near = -(height + y_shift) * 0.5;
1824 		bottom_near += (bottom_near / z_near) * z_shift;
1825 
1826 		// printf("Left_near = %f, Left_far = %f, Top_near = %f, Bottom_near = %f, Z_shift = %f\n", left_near, left_far, top_near, bottom_near, z_shift);
1827 
1828 		// - generate our frustum
1829 		CameraMatrix combined_matrix;
1830 		combined_matrix.set_frustum(left_near, -left_near, bottom_near, top_near, z_near + z_shift, z_far + z_shift);
1831 
1832 		// and finally move our camera back
1833 		Transform apply_z_shift;
1834 		apply_z_shift.origin = Vector3(0.0, 0.0, z_shift); // z negative is forward so this moves it backwards
1835 		mono_transform *= apply_z_shift;
1836 
1837 		// now prepare our scene with our adjusted transform projection matrix
1838 		_prepare_scene(mono_transform, combined_matrix, false, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
1839 	} else if (p_eye == ARVRInterface::EYE_MONO) {
1840 		// For mono render, prepare as per usual
1841 		_prepare_scene(cam_transform, camera_matrix, false, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
1842 	}
1843 
1844 	// And render our scene...
1845 	_render_scene(cam_transform, camera_matrix, false, camera->env, p_scenario, p_shadow_atlas, RID(), -1);
1846 };
1847 
_prepare_scene(const Transform p_cam_transform,const CameraMatrix & p_cam_projection,bool p_cam_orthogonal,RID p_force_environment,uint32_t p_visible_layers,RID p_scenario,RID p_shadow_atlas,RID p_reflection_probe)1848 void VisualServerScene::_prepare_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe) {
1849 	// Note, in stereo rendering:
1850 	// - p_cam_transform will be a transform in the middle of our two eyes
1851 	// - p_cam_projection is a wider frustrum that encompasses both eyes
1852 
1853 	Scenario *scenario = scenario_owner.getornull(p_scenario);
1854 
1855 	render_pass++;
1856 	uint32_t camera_layer_mask = p_visible_layers;
1857 
1858 	VSG::scene_render->set_scene_pass(render_pass);
1859 
1860 	//rasterizer->set_camera(camera->transform, camera_matrix,ortho);
1861 
1862 	Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
1863 
1864 	Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
1865 	float z_far = p_cam_projection.get_z_far();
1866 
1867 	/* STEP 2 - CULL */
1868 	instance_cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL);
1869 	light_cull_count = 0;
1870 
1871 	reflection_probe_cull_count = 0;
1872 
1873 	//light_samplers_culled=0;
1874 
1875 	/*
1876 	print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
1877 	print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
1878 	print_line("OTE: "+itos(p_scenario->octree.get_elem_count()));
1879 	print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
1880 	*/
1881 
1882 	/* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
1883 	//removed, will replace with culling
1884 
1885 	/* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */
1886 
1887 	for (int i = 0; i < instance_cull_count; i++) {
1888 
1889 		Instance *ins = instance_cull_result[i];
1890 
1891 		bool keep = false;
1892 
1893 		if ((camera_layer_mask & ins->layer_mask) == 0) {
1894 
1895 			//failure
1896 		} else if (ins->base_type == VS::INSTANCE_LIGHT && ins->visible) {
1897 
1898 			if (light_cull_count < MAX_LIGHTS_CULLED) {
1899 
1900 				InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
1901 
1902 				if (!light->geometries.empty()) {
1903 					//do not add this light if no geometry is affected by it..
1904 					light_cull_result[light_cull_count] = ins;
1905 					light_instance_cull_result[light_cull_count] = light->instance;
1906 					if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(ins->base)) {
1907 						VSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
1908 					}
1909 
1910 					light_cull_count++;
1911 				}
1912 			}
1913 		} else if (ins->base_type == VS::INSTANCE_REFLECTION_PROBE && ins->visible) {
1914 
1915 			if (reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {
1916 
1917 				InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);
1918 
1919 				if (p_reflection_probe != reflection_probe->instance) {
1920 					//avoid entering The Matrix
1921 
1922 					if (!reflection_probe->geometries.empty()) {
1923 						//do not add this light if no geometry is affected by it..
1924 
1925 						if (reflection_probe->reflection_dirty || VSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
1926 							if (!reflection_probe->update_list.in_list()) {
1927 								reflection_probe->render_step = 0;
1928 								reflection_probe_render_list.add_last(&reflection_probe->update_list);
1929 							}
1930 
1931 							reflection_probe->reflection_dirty = false;
1932 						}
1933 
1934 						if (VSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
1935 							reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
1936 							reflection_probe_cull_count++;
1937 						}
1938 					}
1939 				}
1940 			}
1941 
1942 		} else if (ins->base_type == VS::INSTANCE_GI_PROBE && ins->visible) {
1943 
1944 			InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
1945 			if (!gi_probe->update_element.in_list()) {
1946 				gi_probe_update_list.add(&gi_probe->update_element);
1947 			}
1948 
1949 		} else if (((1 << ins->base_type) & VS::INSTANCE_GEOMETRY_MASK) && ins->visible && ins->cast_shadows != VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
1950 
1951 			keep = true;
1952 
1953 			InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);
1954 
1955 			if (ins->redraw_if_visible) {
1956 				VisualServerRaster::redraw_request();
1957 			}
1958 
1959 			if (ins->base_type == VS::INSTANCE_PARTICLES) {
1960 				//particles visible? process them
1961 				if (VSG::storage->particles_is_inactive(ins->base)) {
1962 					//but if nothing is going on, don't do it.
1963 					keep = false;
1964 				} else {
1965 					VSG::storage->particles_request_process(ins->base);
1966 					//particles visible? request redraw
1967 					VisualServerRaster::redraw_request();
1968 				}
1969 			}
1970 
1971 			if (geom->lighting_dirty) {
1972 				int l = 0;
1973 				//only called when lights AABB enter/exit this geometry
1974 				ins->light_instances.resize(geom->lighting.size());
1975 
1976 				for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
1977 
1978 					InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
1979 
1980 					ins->light_instances.write[l++] = light->instance;
1981 				}
1982 
1983 				geom->lighting_dirty = false;
1984 			}
1985 
1986 			if (geom->reflection_dirty) {
1987 				int l = 0;
1988 				//only called when reflection probe AABB enter/exit this geometry
1989 				ins->reflection_probe_instances.resize(geom->reflection_probes.size());
1990 
1991 				for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
1992 
1993 					InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
1994 
1995 					ins->reflection_probe_instances.write[l++] = reflection_probe->instance;
1996 				}
1997 
1998 				geom->reflection_dirty = false;
1999 			}
2000 
2001 			if (geom->gi_probes_dirty) {
2002 				int l = 0;
2003 				//only called when reflection probe AABB enter/exit this geometry
2004 				ins->gi_probe_instances.resize(geom->gi_probes.size());
2005 
2006 				for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
2007 
2008 					InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
2009 
2010 					ins->gi_probe_instances.write[l++] = gi_probe->probe_instance;
2011 				}
2012 
2013 				geom->gi_probes_dirty = false;
2014 			}
2015 
2016 			ins->depth = near_plane.distance_to(ins->transform.origin);
2017 			ins->depth_layer = CLAMP(int(ins->depth * 16 / z_far), 0, 15);
2018 		}
2019 
2020 		if (!keep) {
2021 			// remove, no reason to keep
2022 			instance_cull_count--;
2023 			SWAP(instance_cull_result[i], instance_cull_result[instance_cull_count]);
2024 			i--;
2025 			ins->last_render_pass = 0; // make invalid
2026 		} else {
2027 
2028 			ins->last_render_pass = render_pass;
2029 		}
2030 	}
2031 
2032 	/* STEP 5 - PROCESS LIGHTS */
2033 
2034 	RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
2035 	directional_light_count = 0;
2036 
2037 	// directional lights
2038 	{
2039 
2040 		Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
2041 		int directional_shadow_count = 0;
2042 
2043 		for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
2044 
2045 			if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
2046 				break;
2047 			}
2048 
2049 			if (!E->get()->visible)
2050 				continue;
2051 
2052 			InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
2053 
2054 			//check shadow..
2055 
2056 			if (light) {
2057 				if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(E->get()->base)) {
2058 					lights_with_shadow[directional_shadow_count++] = E->get();
2059 				}
2060 				//add to list
2061 				directional_light_ptr[directional_light_count++] = light->instance;
2062 			}
2063 		}
2064 
2065 		VSG::scene_render->set_directional_shadow_count(directional_shadow_count);
2066 
2067 		for (int i = 0; i < directional_shadow_count; i++) {
2068 
2069 			_light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
2070 		}
2071 	}
2072 
2073 	{ //setup shadow maps
2074 
2075 		//SortArray<Instance*,_InstanceLightsort> sorter;
2076 		//sorter.sort(light_cull_result,light_cull_count);
2077 		for (int i = 0; i < light_cull_count; i++) {
2078 
2079 			Instance *ins = light_cull_result[i];
2080 
2081 			if (!p_shadow_atlas.is_valid() || !VSG::storage->light_has_shadow(ins->base))
2082 				continue;
2083 
2084 			InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
2085 
2086 			float coverage = 0.f;
2087 
2088 			{ //compute coverage
2089 
2090 				Transform cam_xf = p_cam_transform;
2091 				float zn = p_cam_projection.get_z_near();
2092 				Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
2093 
2094 				// near plane half width and height
2095 				Vector2 vp_half_extents = p_cam_projection.get_viewport_half_extents();
2096 
2097 				switch (VSG::storage->light_get_type(ins->base)) {
2098 
2099 					case VS::LIGHT_OMNI: {
2100 
2101 						float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
2102 
2103 						//get two points parallel to near plane
2104 						Vector3 points[2] = {
2105 							ins->transform.origin,
2106 							ins->transform.origin + cam_xf.basis.get_axis(0) * radius
2107 						};
2108 
2109 						if (!p_cam_orthogonal) {
2110 							//if using perspetive, map them to near plane
2111 							for (int j = 0; j < 2; j++) {
2112 								if (p.distance_to(points[j]) < 0) {
2113 									points[j].z = -zn; //small hack to keep size constant when hitting the screen
2114 								}
2115 
2116 								p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
2117 							}
2118 						}
2119 
2120 						float screen_diameter = points[0].distance_to(points[1]) * 2;
2121 						coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
2122 					} break;
2123 					case VS::LIGHT_SPOT: {
2124 
2125 						float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
2126 						float angle = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_SPOT_ANGLE);
2127 
2128 						float w = radius * Math::sin(Math::deg2rad(angle));
2129 						float d = radius * Math::cos(Math::deg2rad(angle));
2130 
2131 						Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
2132 
2133 						Vector3 points[2] = {
2134 							base,
2135 							base + cam_xf.basis.get_axis(0) * w
2136 						};
2137 
2138 						if (!p_cam_orthogonal) {
2139 							//if using perspetive, map them to near plane
2140 							for (int j = 0; j < 2; j++) {
2141 								if (p.distance_to(points[j]) < 0) {
2142 									points[j].z = -zn; //small hack to keep size constant when hitting the screen
2143 								}
2144 
2145 								p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
2146 							}
2147 						}
2148 
2149 						float screen_diameter = points[0].distance_to(points[1]) * 2;
2150 						coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
2151 
2152 					} break;
2153 					default: {
2154 						ERR_PRINT("Invalid Light Type");
2155 					}
2156 				}
2157 			}
2158 
2159 			if (light->shadow_dirty) {
2160 				light->last_version++;
2161 				light->shadow_dirty = false;
2162 			}
2163 
2164 			bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
2165 
2166 			if (redraw) {
2167 				//must redraw!
2168 				light->shadow_dirty = _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
2169 			}
2170 		}
2171 	}
2172 }
2173 
_render_scene(const Transform p_cam_transform,const CameraMatrix & p_cam_projection,bool p_cam_orthogonal,RID p_force_environment,RID p_scenario,RID p_shadow_atlas,RID p_reflection_probe,int p_reflection_probe_pass)2174 void VisualServerScene::_render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
2175 
2176 	Scenario *scenario = scenario_owner.getornull(p_scenario);
2177 
2178 	/* ENVIRONMENT */
2179 
2180 	RID environment;
2181 	if (p_force_environment.is_valid()) //camera has more environment priority
2182 		environment = p_force_environment;
2183 	else if (scenario->environment.is_valid())
2184 		environment = scenario->environment;
2185 	else
2186 		environment = scenario->fallback_environment;
2187 
2188 	/* PROCESS GEOMETRY AND DRAW SCENE */
2189 
2190 	VSG::scene_render->render_scene(p_cam_transform, p_cam_projection, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, instance_cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, environment, p_shadow_atlas, scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
2191 }
2192 
render_empty_scene(RID p_scenario,RID p_shadow_atlas)2193 void VisualServerScene::render_empty_scene(RID p_scenario, RID p_shadow_atlas) {
2194 
2195 #ifndef _3D_DISABLED
2196 
2197 	Scenario *scenario = scenario_owner.getornull(p_scenario);
2198 
2199 	RID environment;
2200 	if (scenario->environment.is_valid())
2201 		environment = scenario->environment;
2202 	else
2203 		environment = scenario->fallback_environment;
2204 	VSG::scene_render->render_scene(Transform(), CameraMatrix(), true, NULL, 0, NULL, 0, NULL, 0, environment, p_shadow_atlas, scenario->reflection_atlas, RID(), 0);
2205 #endif
2206 }
2207 
_render_reflection_probe_step(Instance * p_instance,int p_step)2208 bool VisualServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {
2209 
2210 	InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
2211 	Scenario *scenario = p_instance->scenario;
2212 	ERR_FAIL_COND_V(!scenario, true);
2213 
2214 	VisualServerRaster::redraw_request(); //update, so it updates in editor
2215 
2216 	if (p_step == 0) {
2217 
2218 		if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
2219 			return true; //sorry, all full :(
2220 		}
2221 	}
2222 
2223 	if (p_step >= 0 && p_step < 6) {
2224 
2225 		static const Vector3 view_normals[6] = {
2226 			Vector3(-1, 0, 0),
2227 			Vector3(+1, 0, 0),
2228 			Vector3(0, -1, 0),
2229 			Vector3(0, +1, 0),
2230 			Vector3(0, 0, -1),
2231 			Vector3(0, 0, +1)
2232 		};
2233 
2234 		Vector3 extents = VSG::storage->reflection_probe_get_extents(p_instance->base);
2235 		Vector3 origin_offset = VSG::storage->reflection_probe_get_origin_offset(p_instance->base);
2236 		float max_distance = VSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
2237 
2238 		Vector3 edge = view_normals[p_step] * extents;
2239 		float distance = ABS(view_normals[p_step].dot(edge) - view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit
2240 
2241 		max_distance = MAX(max_distance, distance);
2242 
2243 		//render cubemap side
2244 		CameraMatrix cm;
2245 		cm.set_perspective(90, 1, 0.01, max_distance);
2246 
2247 		static const Vector3 view_up[6] = {
2248 			Vector3(0, -1, 0),
2249 			Vector3(0, -1, 0),
2250 			Vector3(0, 0, -1),
2251 			Vector3(0, 0, +1),
2252 			Vector3(0, -1, 0),
2253 			Vector3(0, -1, 0)
2254 		};
2255 
2256 		Transform local_view;
2257 		local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
2258 
2259 		Transform xform = p_instance->transform * local_view;
2260 
2261 		RID shadow_atlas;
2262 
2263 		if (VSG::storage->reflection_probe_renders_shadows(p_instance->base)) {
2264 
2265 			shadow_atlas = scenario->reflection_probe_shadow_atlas;
2266 		}
2267 
2268 		_prepare_scene(xform, cm, false, RID(), VSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance);
2269 		_render_scene(xform, cm, false, RID(), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);
2270 
2271 	} else {
2272 		//do roughness postprocess step until it believes it's done
2273 		return VSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
2274 	}
2275 
2276 	return false;
2277 }
2278 
_gi_probe_fill_local_data(int p_idx,int p_level,int p_x,int p_y,int p_z,const GIProbeDataCell * p_cell,const GIProbeDataHeader * p_header,InstanceGIProbeData::LocalData * p_local_data,Vector<uint32_t> * prev_cell)2279 void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) {
2280 
2281 	if ((uint32_t)p_level == p_header->cell_subdiv - 1) {
2282 
2283 		Vector3 emission;
2284 		emission.x = (p_cell[p_idx].emission >> 24) / 255.0;
2285 		emission.y = ((p_cell[p_idx].emission >> 16) & 0xFF) / 255.0;
2286 		emission.z = ((p_cell[p_idx].emission >> 8) & 0xFF) / 255.0;
2287 		float l = (p_cell[p_idx].emission & 0xFF) / 255.0;
2288 		l *= 8.0;
2289 
2290 		emission *= l;
2291 
2292 		p_local_data[p_idx].energy[0] = uint16_t(emission.x * 1024); //go from 0 to 1024 for light
2293 		p_local_data[p_idx].energy[1] = uint16_t(emission.y * 1024); //go from 0 to 1024 for light
2294 		p_local_data[p_idx].energy[2] = uint16_t(emission.z * 1024); //go from 0 to 1024 for light
2295 	} else {
2296 
2297 		p_local_data[p_idx].energy[0] = 0;
2298 		p_local_data[p_idx].energy[1] = 0;
2299 		p_local_data[p_idx].energy[2] = 0;
2300 
2301 		int half = (1 << (p_header->cell_subdiv - 1)) >> (p_level + 1);
2302 
2303 		for (int i = 0; i < 8; i++) {
2304 
2305 			uint32_t child = p_cell[p_idx].children[i];
2306 
2307 			if (child == 0xFFFFFFFF)
2308 				continue;
2309 
2310 			int x = p_x;
2311 			int y = p_y;
2312 			int z = p_z;
2313 
2314 			if (i & 1)
2315 				x += half;
2316 			if (i & 2)
2317 				y += half;
2318 			if (i & 4)
2319 				z += half;
2320 
2321 			_gi_probe_fill_local_data(child, p_level + 1, x, y, z, p_cell, p_header, p_local_data, prev_cell);
2322 		}
2323 	}
2324 
2325 	//position for each part of the mipmaped texture
2326 	p_local_data[p_idx].pos[0] = p_x >> (p_header->cell_subdiv - p_level - 1);
2327 	p_local_data[p_idx].pos[1] = p_y >> (p_header->cell_subdiv - p_level - 1);
2328 	p_local_data[p_idx].pos[2] = p_z >> (p_header->cell_subdiv - p_level - 1);
2329 
2330 	prev_cell[p_level].push_back(p_idx);
2331 }
2332 
_gi_probe_bake_threads(void * self)2333 void VisualServerScene::_gi_probe_bake_threads(void *self) {
2334 
2335 	VisualServerScene *vss = (VisualServerScene *)self;
2336 	vss->_gi_probe_bake_thread();
2337 }
2338 
_setup_gi_probe(Instance * p_instance)2339 void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
2340 
2341 	InstanceGIProbeData *probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
2342 
2343 	if (probe->dynamic.probe_data.is_valid()) {
2344 		VSG::storage->free(probe->dynamic.probe_data);
2345 		probe->dynamic.probe_data = RID();
2346 	}
2347 
2348 	probe->dynamic.light_data = VSG::storage->gi_probe_get_dynamic_data(p_instance->base);
2349 
2350 	if (probe->dynamic.light_data.size() == 0)
2351 		return;
2352 	//using dynamic data
2353 	PoolVector<int>::Read r = probe->dynamic.light_data.read();
2354 
2355 	const GIProbeDataHeader *header = (GIProbeDataHeader *)r.ptr();
2356 
2357 	probe->dynamic.local_data.resize(header->cell_count);
2358 
2359 	int cell_count = probe->dynamic.local_data.size();
2360 	PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe->dynamic.local_data.write();
2361 	const GIProbeDataCell *cells = (GIProbeDataCell *)&r[16];
2362 
2363 	probe->dynamic.level_cell_lists.resize(header->cell_subdiv);
2364 
2365 	_gi_probe_fill_local_data(0, 0, 0, 0, 0, cells, header, ldw.ptr(), probe->dynamic.level_cell_lists.ptrw());
2366 
2367 	bool compress = VSG::storage->gi_probe_is_compressed(p_instance->base);
2368 
2369 	probe->dynamic.compression = compress ? VSG::storage->gi_probe_get_dynamic_data_get_preferred_compression() : RasterizerStorage::GI_PROBE_UNCOMPRESSED;
2370 
2371 	probe->dynamic.probe_data = VSG::storage->gi_probe_dynamic_data_create(header->width, header->height, header->depth, probe->dynamic.compression);
2372 
2373 	probe->dynamic.bake_dynamic_range = VSG::storage->gi_probe_get_dynamic_range(p_instance->base);
2374 
2375 	probe->dynamic.mipmaps_3d.clear();
2376 	probe->dynamic.propagate = VSG::storage->gi_probe_get_propagation(p_instance->base);
2377 
2378 	probe->dynamic.grid_size[0] = header->width;
2379 	probe->dynamic.grid_size[1] = header->height;
2380 	probe->dynamic.grid_size[2] = header->depth;
2381 
2382 	int size_limit = 1;
2383 	int size_divisor = 1;
2384 
2385 	if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
2386 		size_limit = 4;
2387 		size_divisor = 4;
2388 	}
2389 	for (int i = 0; i < (int)header->cell_subdiv; i++) {
2390 
2391 		int x = header->width >> i;
2392 		int y = header->height >> i;
2393 		int z = header->depth >> i;
2394 
2395 		//create and clear mipmap
2396 		PoolVector<uint8_t> mipmap;
2397 		int size = x * y * z * 4;
2398 		size /= size_divisor;
2399 		mipmap.resize(size);
2400 		PoolVector<uint8_t>::Write w = mipmap.write();
2401 		zeromem(w.ptr(), size);
2402 		w.release();
2403 
2404 		probe->dynamic.mipmaps_3d.push_back(mipmap);
2405 
2406 		if (x <= size_limit || y <= size_limit || z <= size_limit)
2407 			break;
2408 	}
2409 
2410 	probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
2411 	probe->invalid = false;
2412 	probe->dynamic.enabled = true;
2413 
2414 	Transform cell_to_xform = VSG::storage->gi_probe_get_to_cell_xform(p_instance->base);
2415 	AABB bounds = VSG::storage->gi_probe_get_bounds(p_instance->base);
2416 	float cell_size = VSG::storage->gi_probe_get_cell_size(p_instance->base);
2417 
2418 	probe->dynamic.light_to_cell_xform = cell_to_xform * p_instance->transform.affine_inverse();
2419 
2420 	VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance, p_instance->base, probe->dynamic.probe_data);
2421 	VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance, probe->dynamic.light_to_cell_xform);
2422 
2423 	VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance, bounds.size / cell_size);
2424 
2425 	probe->base_version = VSG::storage->gi_probe_get_version(p_instance->base);
2426 
2427 	//if compression is S3TC, fill it up
2428 	if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
2429 
2430 		//create all blocks
2431 		Vector<Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> > comp_blocks;
2432 		int mipmap_count = probe->dynamic.mipmaps_3d.size();
2433 		comp_blocks.resize(mipmap_count);
2434 
2435 		for (int i = 0; i < cell_count; i++) {
2436 
2437 			const GIProbeDataCell &c = cells[i];
2438 			const InstanceGIProbeData::LocalData &ld = ldw[i];
2439 			int level = c.level_alpha >> 16;
2440 			int mipmap = header->cell_subdiv - level - 1;
2441 			if (mipmap >= mipmap_count)
2442 				continue; //uninteresting
2443 
2444 			int blockx = (ld.pos[0] >> 2);
2445 			int blocky = (ld.pos[1] >> 2);
2446 			int blockz = (ld.pos[2]); //compression is x/y only
2447 
2448 			int blockw = (header->width >> mipmap) >> 2;
2449 			int blockh = (header->height >> mipmap) >> 2;
2450 
2451 			//print_line("cell "+itos(i)+" level "+itos(level)+"mipmap: "+itos(mipmap)+" pos: "+Vector3(blockx,blocky,blockz)+" size "+Vector2(blockw,blockh));
2452 
2453 			uint32_t key = blockz * blockw * blockh + blocky * blockw + blockx;
2454 
2455 			Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> &cmap = comp_blocks.write[mipmap];
2456 
2457 			if (!cmap.has(key)) {
2458 
2459 				InstanceGIProbeData::CompBlockS3TC k;
2460 				k.offset = key; //use offset as counter first
2461 				k.source_count = 0;
2462 				cmap[key] = k;
2463 			}
2464 
2465 			InstanceGIProbeData::CompBlockS3TC &k = cmap[key];
2466 			ERR_CONTINUE(k.source_count == 16);
2467 			k.sources[k.source_count++] = i;
2468 		}
2469 
2470 		//fix the blocks, precomputing what is needed
2471 		probe->dynamic.mipmaps_s3tc.resize(mipmap_count);
2472 
2473 		for (int i = 0; i < mipmap_count; i++) {
2474 			//print_line("S3TC level: " + itos(i) + " blocks: " + itos(comp_blocks[i].size()));
2475 			probe->dynamic.mipmaps_s3tc.write[i].resize(comp_blocks[i].size());
2476 			PoolVector<InstanceGIProbeData::CompBlockS3TC>::Write w = probe->dynamic.mipmaps_s3tc.write[i].write();
2477 			int block_idx = 0;
2478 
2479 			for (Map<uint32_t, InstanceGIProbeData::CompBlockS3TC>::Element *E = comp_blocks[i].front(); E; E = E->next()) {
2480 
2481 				InstanceGIProbeData::CompBlockS3TC k = E->get();
2482 
2483 				//PRECOMPUTE ALPHA
2484 				int max_alpha = -100000;
2485 				int min_alpha = k.source_count == 16 ? 100000 : 0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero)
2486 
2487 				uint8_t alpha_block[4][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
2488 
2489 				for (uint32_t j = 0; j < k.source_count; j++) {
2490 
2491 					int alpha = (cells[k.sources[j]].level_alpha >> 8) & 0xFF;
2492 					if (alpha < min_alpha)
2493 						min_alpha = alpha;
2494 					if (alpha > max_alpha)
2495 						max_alpha = alpha;
2496 					//fill up alpha block
2497 					alpha_block[ldw[k.sources[j]].pos[0] % 4][ldw[k.sources[j]].pos[1] % 4] = alpha;
2498 				}
2499 
2500 				//use the first mode (8 adjustable levels)
2501 				k.alpha[0] = max_alpha;
2502 				k.alpha[1] = min_alpha;
2503 
2504 				uint64_t alpha_bits = 0;
2505 
2506 				if (max_alpha != min_alpha) {
2507 
2508 					int idx = 0;
2509 
2510 					for (int y = 0; y < 4; y++) {
2511 						for (int x = 0; x < 4; x++) {
2512 
2513 							//subtract minimum
2514 							uint32_t a = uint32_t(alpha_block[x][y]) - min_alpha;
2515 							//convert range to 3 bits
2516 							a = int((a * 7.0 / (max_alpha - min_alpha)) + 0.5);
2517 							a = MIN(a, 7); //just to be sure
2518 							a = 7 - a; //because range is inverted in this mode
2519 							if (a == 0) {
2520 								//do none, remain
2521 							} else if (a == 7) {
2522 								a = 1;
2523 							} else {
2524 								a = a + 1;
2525 							}
2526 
2527 							alpha_bits |= uint64_t(a) << (idx * 3);
2528 							idx++;
2529 						}
2530 					}
2531 				}
2532 
2533 				k.alpha[2] = (alpha_bits >> 0) & 0xFF;
2534 				k.alpha[3] = (alpha_bits >> 8) & 0xFF;
2535 				k.alpha[4] = (alpha_bits >> 16) & 0xFF;
2536 				k.alpha[5] = (alpha_bits >> 24) & 0xFF;
2537 				k.alpha[6] = (alpha_bits >> 32) & 0xFF;
2538 				k.alpha[7] = (alpha_bits >> 40) & 0xFF;
2539 
2540 				w[block_idx++] = k;
2541 			}
2542 		}
2543 	}
2544 }
2545 
_gi_probe_bake_thread()2546 void VisualServerScene::_gi_probe_bake_thread() {
2547 
2548 	while (true) {
2549 
2550 		probe_bake_sem->wait();
2551 		if (probe_bake_thread_exit) {
2552 			break;
2553 		}
2554 
2555 		Instance *to_bake = NULL;
2556 
2557 		probe_bake_mutex->lock();
2558 
2559 		if (!probe_bake_list.empty()) {
2560 			to_bake = probe_bake_list.front()->get();
2561 			probe_bake_list.pop_front();
2562 		}
2563 		probe_bake_mutex->unlock();
2564 
2565 		if (!to_bake)
2566 			continue;
2567 
2568 		_bake_gi_probe(to_bake);
2569 	}
2570 }
2571 
_gi_bake_find_cell(const GIProbeDataCell * cells,int x,int y,int z,int p_cell_subdiv)2572 uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv) {
2573 
2574 	uint32_t cell = 0;
2575 
2576 	int ofs_x = 0;
2577 	int ofs_y = 0;
2578 	int ofs_z = 0;
2579 	int size = 1 << (p_cell_subdiv - 1);
2580 	int half = size / 2;
2581 
2582 	if (x < 0 || x >= size)
2583 		return -1;
2584 	if (y < 0 || y >= size)
2585 		return -1;
2586 	if (z < 0 || z >= size)
2587 		return -1;
2588 
2589 	for (int i = 0; i < p_cell_subdiv - 1; i++) {
2590 
2591 		const GIProbeDataCell *bc = &cells[cell];
2592 
2593 		int child = 0;
2594 		if (x >= ofs_x + half) {
2595 			child |= 1;
2596 			ofs_x += half;
2597 		}
2598 		if (y >= ofs_y + half) {
2599 			child |= 2;
2600 			ofs_y += half;
2601 		}
2602 		if (z >= ofs_z + half) {
2603 			child |= 4;
2604 			ofs_z += half;
2605 		}
2606 
2607 		cell = bc->children[child];
2608 		if (cell == 0xFFFFFFFF)
2609 			return 0xFFFFFFFF;
2610 
2611 		half >>= 1;
2612 	}
2613 
2614 	return cell;
2615 }
2616 
_get_normal_advance(const Vector3 & p_normal)2617 static float _get_normal_advance(const Vector3 &p_normal) {
2618 
2619 	Vector3 normal = p_normal;
2620 	Vector3 unorm = normal.abs();
2621 
2622 	if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
2623 		// x code
2624 		unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
2625 	} else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
2626 		// y code
2627 		unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
2628 	} else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
2629 		// z code
2630 		unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
2631 	} else {
2632 		// oh-no we messed up code
2633 		// has to be
2634 		unorm = Vector3(1.0, 0.0, 0.0);
2635 	}
2636 
2637 	return 1.0 / normal.dot(unorm);
2638 }
2639 
_bake_gi_probe_light(const GIProbeDataHeader * header,const GIProbeDataCell * cells,InstanceGIProbeData::LocalData * local_data,const uint32_t * leaves,int p_leaf_count,const InstanceGIProbeData::LightCache & light_cache,int p_sign)2640 void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int p_leaf_count, const InstanceGIProbeData::LightCache &light_cache, int p_sign) {
2641 
2642 	int light_r = int(light_cache.color.r * light_cache.energy * 1024.0) * p_sign;
2643 	int light_g = int(light_cache.color.g * light_cache.energy * 1024.0) * p_sign;
2644 	int light_b = int(light_cache.color.b * light_cache.energy * 1024.0) * p_sign;
2645 
2646 	float limits[3] = { float(header->width), float(header->height), float(header->depth) };
2647 	Plane clip[3];
2648 	int clip_planes = 0;
2649 
2650 	switch (light_cache.type) {
2651 
2652 		case VS::LIGHT_DIRECTIONAL: {
2653 
2654 			float max_len = Vector3(limits[0], limits[1], limits[2]).length() * 1.1;
2655 
2656 			Vector3 light_axis = -light_cache.transform.basis.get_axis(2).normalized();
2657 
2658 			for (int i = 0; i < 3; i++) {
2659 
2660 				if (Math::is_zero_approx(light_axis[i]))
2661 					continue;
2662 				clip[clip_planes].normal[i] = 1.0;
2663 
2664 				if (light_axis[i] < 0) {
2665 
2666 					clip[clip_planes].d = limits[i] + 1;
2667 				} else {
2668 					clip[clip_planes].d -= 1.0;
2669 				}
2670 
2671 				clip_planes++;
2672 			}
2673 
2674 			float distance_adv = _get_normal_advance(light_axis);
2675 
2676 			int success_count = 0;
2677 
2678 			// uint64_t us = OS::get_singleton()->get_ticks_usec();
2679 
2680 			for (int i = 0; i < p_leaf_count; i++) {
2681 
2682 				uint32_t idx = leaves[i];
2683 
2684 				const GIProbeDataCell *cell = &cells[idx];
2685 				InstanceGIProbeData::LocalData *light = &local_data[idx];
2686 
2687 				Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
2688 				to += -light_axis.sign() * 0.47; //make it more likely to receive a ray
2689 
2690 				Vector3 norm(
2691 						(((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
2692 						(((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
2693 						(((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
2694 
2695 				float att = norm.dot(-light_axis);
2696 				if (att < 0.001) {
2697 					//not lighting towards this
2698 					continue;
2699 				}
2700 
2701 				Vector3 from = to - max_len * light_axis;
2702 
2703 				for (int j = 0; j < clip_planes; j++) {
2704 
2705 					clip[j].intersects_segment(from, to, &from);
2706 				}
2707 
2708 				float distance = (to - from).length();
2709 				distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
2710 				from = to - light_axis * distance;
2711 
2712 				uint32_t result = 0xFFFFFFFF;
2713 
2714 				while (distance > -distance_adv) { //use this to avoid precision errors
2715 
2716 					result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
2717 					if (result != 0xFFFFFFFF) {
2718 						break;
2719 					}
2720 
2721 					from += light_axis * distance_adv;
2722 					distance -= distance_adv;
2723 				}
2724 
2725 				if (result == idx) {
2726 					//cell hit itself! hooray!
2727 					light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
2728 					light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
2729 					light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
2730 					success_count++;
2731 				}
2732 			}
2733 
2734 			// print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
2735 			// print_line("valid cells: " + itos(success_count));
2736 
2737 		} break;
2738 		case VS::LIGHT_OMNI:
2739 		case VS::LIGHT_SPOT: {
2740 
2741 			// uint64_t us = OS::get_singleton()->get_ticks_usec();
2742 
2743 			Vector3 light_pos = light_cache.transform.origin;
2744 			Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
2745 
2746 			float local_radius = light_cache.radius * light_cache.transform.basis.get_axis(2).length();
2747 
2748 			for (int i = 0; i < p_leaf_count; i++) {
2749 
2750 				uint32_t idx = leaves[i];
2751 
2752 				const GIProbeDataCell *cell = &cells[idx];
2753 				InstanceGIProbeData::LocalData *light = &local_data[idx];
2754 
2755 				Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
2756 				to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
2757 
2758 				Vector3 norm(
2759 						(((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
2760 						(((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
2761 						(((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
2762 
2763 				Vector3 light_axis = (to - light_pos).normalized();
2764 				float distance_adv = _get_normal_advance(light_axis);
2765 
2766 				float att = norm.dot(-light_axis);
2767 				if (att < 0.001) {
2768 					//not lighting towards this
2769 					continue;
2770 				}
2771 
2772 				{
2773 					float d = light_pos.distance_to(to);
2774 					if (d + distance_adv > local_radius)
2775 						continue; // too far away
2776 
2777 					float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
2778 					att *= powf(1.0 - dt, light_cache.attenuation);
2779 				}
2780 
2781 				if (light_cache.type == VS::LIGHT_SPOT) {
2782 
2783 					float angle = Math::rad2deg(acos(light_axis.dot(spot_axis)));
2784 					if (angle > light_cache.spot_angle)
2785 						continue;
2786 
2787 					float d = CLAMP(angle / light_cache.spot_angle, 0, 1);
2788 					att *= powf(1.0 - d, light_cache.spot_attenuation);
2789 				}
2790 
2791 				clip_planes = 0;
2792 
2793 				for (int c = 0; c < 3; c++) {
2794 
2795 					if (Math::is_zero_approx(light_axis[c]))
2796 						continue;
2797 					clip[clip_planes].normal[c] = 1.0;
2798 
2799 					if (light_axis[c] < 0) {
2800 
2801 						clip[clip_planes].d = limits[c] + 1;
2802 					} else {
2803 						clip[clip_planes].d -= 1.0;
2804 					}
2805 
2806 					clip_planes++;
2807 				}
2808 
2809 				Vector3 from = light_pos;
2810 
2811 				for (int j = 0; j < clip_planes; j++) {
2812 
2813 					clip[j].intersects_segment(from, to, &from);
2814 				}
2815 
2816 				float distance = (to - from).length();
2817 
2818 				distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
2819 				from = to - light_axis * distance;
2820 
2821 				uint32_t result = 0xFFFFFFFF;
2822 
2823 				while (distance > -distance_adv) { //use this to avoid precision errors
2824 
2825 					result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
2826 					if (result != 0xFFFFFFFF) {
2827 						break;
2828 					}
2829 
2830 					from += light_axis * distance_adv;
2831 					distance -= distance_adv;
2832 				}
2833 
2834 				if (result == idx) {
2835 					//cell hit itself! hooray!
2836 
2837 					light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
2838 					light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
2839 					light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
2840 				}
2841 			}
2842 			//print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
2843 		} break;
2844 	}
2845 }
2846 
_bake_gi_downscale_light(int p_idx,int p_level,const GIProbeDataCell * p_cells,const GIProbeDataHeader * p_header,InstanceGIProbeData::LocalData * p_local_data,float p_propagate)2847 void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate) {
2848 
2849 	//average light to upper level
2850 
2851 	float divisor = 0;
2852 	float sum[3] = { 0.0, 0.0, 0.0 };
2853 
2854 	for (int i = 0; i < 8; i++) {
2855 
2856 		uint32_t child = p_cells[p_idx].children[i];
2857 
2858 		if (child == 0xFFFFFFFF)
2859 			continue;
2860 
2861 		if (p_level + 1 < (int)p_header->cell_subdiv - 1) {
2862 			_bake_gi_downscale_light(child, p_level + 1, p_cells, p_header, p_local_data, p_propagate);
2863 		}
2864 
2865 		sum[0] += p_local_data[child].energy[0];
2866 		sum[1] += p_local_data[child].energy[1];
2867 		sum[2] += p_local_data[child].energy[2];
2868 		divisor += 1.0;
2869 	}
2870 
2871 	divisor = Math::lerp((float)8.0, divisor, p_propagate);
2872 	sum[0] /= divisor;
2873 	sum[1] /= divisor;
2874 	sum[2] /= divisor;
2875 
2876 	//divide by eight for average
2877 	p_local_data[p_idx].energy[0] = Math::fast_ftoi(sum[0]);
2878 	p_local_data[p_idx].energy[1] = Math::fast_ftoi(sum[1]);
2879 	p_local_data[p_idx].energy[2] = Math::fast_ftoi(sum[2]);
2880 }
2881 
_bake_gi_probe(Instance * p_gi_probe)2882 void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) {
2883 
2884 	InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
2885 
2886 	PoolVector<int>::Read r = probe_data->dynamic.light_data.read();
2887 
2888 	const GIProbeDataHeader *header = (const GIProbeDataHeader *)r.ptr();
2889 	const GIProbeDataCell *cells = (const GIProbeDataCell *)&r[16];
2890 
2891 	int leaf_count = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].size();
2892 	const uint32_t *leaves = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].ptr();
2893 
2894 	PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe_data->dynamic.local_data.write();
2895 
2896 	InstanceGIProbeData::LocalData *local_data = ldw.ptr();
2897 
2898 	//remove what must be removed
2899 	for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache.front(); E; E = E->next()) {
2900 
2901 		RID rid = E->key();
2902 		const InstanceGIProbeData::LightCache &lc = E->get();
2903 
2904 		if ((!probe_data->dynamic.light_cache_changes.has(rid) || probe_data->dynamic.light_cache_changes[rid] != lc) && lc.visible) {
2905 			//erase light data
2906 
2907 			_bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, -1);
2908 		}
2909 	}
2910 
2911 	//add what must be added
2912 	for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache_changes.front(); E; E = E->next()) {
2913 
2914 		RID rid = E->key();
2915 		const InstanceGIProbeData::LightCache &lc = E->get();
2916 
2917 		if ((!probe_data->dynamic.light_cache.has(rid) || probe_data->dynamic.light_cache[rid] != lc) && lc.visible) {
2918 			//add light data
2919 
2920 			_bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, 1);
2921 		}
2922 	}
2923 
2924 	SWAP(probe_data->dynamic.light_cache_changes, probe_data->dynamic.light_cache);
2925 
2926 	//downscale to lower res levels
2927 	_bake_gi_downscale_light(0, 0, cells, header, local_data, probe_data->dynamic.propagate);
2928 
2929 	//plot result to 3D texture!
2930 
2931 	if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_UNCOMPRESSED) {
2932 
2933 		for (int i = 0; i < (int)header->cell_subdiv; i++) {
2934 
2935 			int stage = header->cell_subdiv - i - 1;
2936 
2937 			if (stage >= probe_data->dynamic.mipmaps_3d.size())
2938 				continue; //no mipmap for this one
2939 
2940 			//print_line("generating mipmap stage: " + itos(stage));
2941 			int level_cell_count = probe_data->dynamic.level_cell_lists[i].size();
2942 			const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[i].ptr();
2943 
2944 			PoolVector<uint8_t>::Write lw = probe_data->dynamic.mipmaps_3d.write[stage].write();
2945 			uint8_t *mipmapw = lw.ptr();
2946 
2947 			uint32_t sizes[3] = { header->width >> stage, header->height >> stage, header->depth >> stage };
2948 
2949 			for (int j = 0; j < level_cell_count; j++) {
2950 
2951 				uint32_t idx = level_cells[j];
2952 
2953 				uint32_t r2 = (uint32_t(local_data[idx].energy[0]) / probe_data->dynamic.bake_dynamic_range) >> 2;
2954 				uint32_t g = (uint32_t(local_data[idx].energy[1]) / probe_data->dynamic.bake_dynamic_range) >> 2;
2955 				uint32_t b = (uint32_t(local_data[idx].energy[2]) / probe_data->dynamic.bake_dynamic_range) >> 2;
2956 				uint32_t a = (cells[idx].level_alpha >> 8) & 0xFF;
2957 
2958 				uint32_t mm_ofs = sizes[0] * sizes[1] * (local_data[idx].pos[2]) + sizes[0] * (local_data[idx].pos[1]) + (local_data[idx].pos[0]);
2959 				mm_ofs *= 4; //for RGBA (4 bytes)
2960 
2961 				mipmapw[mm_ofs + 0] = uint8_t(MIN(r2, 255));
2962 				mipmapw[mm_ofs + 1] = uint8_t(MIN(g, 255));
2963 				mipmapw[mm_ofs + 2] = uint8_t(MIN(b, 255));
2964 				mipmapw[mm_ofs + 3] = uint8_t(MIN(a, 255));
2965 			}
2966 		}
2967 	} else if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
2968 
2969 		int mipmap_count = probe_data->dynamic.mipmaps_3d.size();
2970 
2971 		for (int mmi = 0; mmi < mipmap_count; mmi++) {
2972 
2973 			PoolVector<uint8_t>::Write mmw = probe_data->dynamic.mipmaps_3d.write[mmi].write();
2974 			int block_count = probe_data->dynamic.mipmaps_s3tc[mmi].size();
2975 			PoolVector<InstanceGIProbeData::CompBlockS3TC>::Read mmr = probe_data->dynamic.mipmaps_s3tc[mmi].read();
2976 
2977 			for (int i = 0; i < block_count; i++) {
2978 
2979 				const InstanceGIProbeData::CompBlockS3TC &b = mmr[i];
2980 
2981 				uint8_t *blockptr = &mmw[b.offset * 16];
2982 				copymem(blockptr, b.alpha, 8); //copy alpha part, which is precomputed
2983 
2984 				Vector3 colors[16];
2985 
2986 				for (uint32_t j = 0; j < b.source_count; j++) {
2987 
2988 					colors[j].x = (local_data[b.sources[j]].energy[0] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
2989 					colors[j].y = (local_data[b.sources[j]].energy[1] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
2990 					colors[j].z = (local_data[b.sources[j]].energy[2] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
2991 				}
2992 				//super quick and dirty compression
2993 				//find 2 most further apart
2994 				float distance = 0;
2995 				Vector3 from, to;
2996 
2997 				if (b.source_count == 16) {
2998 					//all cells are used so, find minmax between them
2999 					int further_apart[2] = { 0, 0 };
3000 					for (uint32_t j = 0; j < b.source_count; j++) {
3001 						for (uint32_t k = j + 1; k < b.source_count; k++) {
3002 							float d = colors[j].distance_squared_to(colors[k]);
3003 							if (d > distance) {
3004 								distance = d;
3005 								further_apart[0] = j;
3006 								further_apart[1] = k;
3007 							}
3008 						}
3009 					}
3010 
3011 					from = colors[further_apart[0]];
3012 					to = colors[further_apart[1]];
3013 
3014 				} else {
3015 					//if a block is missing, the priority is that this block remains black,
3016 					//otherwise the geometry will appear deformed
3017 					//correct shape wins over correct color in this case
3018 					//average all colors first
3019 					Vector3 average;
3020 
3021 					for (uint32_t j = 0; j < b.source_count; j++) {
3022 						average += colors[j];
3023 					}
3024 					average.normalize();
3025 					//find max distance in normal from average
3026 					for (uint32_t j = 0; j < b.source_count; j++) {
3027 						float d = average.dot(colors[j]);
3028 						distance = MAX(d, distance);
3029 					}
3030 
3031 					from = Vector3(); //from black
3032 					to = average * distance;
3033 					//find max distance
3034 				}
3035 
3036 				int indices[16];
3037 				uint16_t color_0 = 0;
3038 				color_0 = CLAMP(int(from.x * 31), 0, 31) << 11;
3039 				color_0 |= CLAMP(int(from.y * 63), 0, 63) << 5;
3040 				color_0 |= CLAMP(int(from.z * 31), 0, 31);
3041 
3042 				uint16_t color_1 = 0;
3043 				color_1 = CLAMP(int(to.x * 31), 0, 31) << 11;
3044 				color_1 |= CLAMP(int(to.y * 63), 0, 63) << 5;
3045 				color_1 |= CLAMP(int(to.z * 31), 0, 31);
3046 
3047 				if (color_1 > color_0) {
3048 					SWAP(color_1, color_0);
3049 					SWAP(from, to);
3050 				}
3051 
3052 				if (distance > 0) {
3053 
3054 					Vector3 dir = (to - from).normalized();
3055 
3056 					for (uint32_t j = 0; j < b.source_count; j++) {
3057 
3058 						float d = (colors[j] - from).dot(dir) / distance;
3059 						indices[j] = int(d * 3 + 0.5);
3060 
3061 						static const int index_swap[4] = { 0, 3, 1, 2 };
3062 
3063 						indices[j] = index_swap[CLAMP(indices[j], 0, 3)];
3064 					}
3065 				} else {
3066 					for (uint32_t j = 0; j < b.source_count; j++) {
3067 						indices[j] = 0;
3068 					}
3069 				}
3070 
3071 				//by default, 1 is black, otherwise it will be overridden by source
3072 
3073 				uint32_t index_block[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
3074 
3075 				for (uint32_t j = 0; j < b.source_count; j++) {
3076 
3077 					int x = local_data[b.sources[j]].pos[0] % 4;
3078 					int y = local_data[b.sources[j]].pos[1] % 4;
3079 
3080 					index_block[y * 4 + x] = indices[j];
3081 				}
3082 
3083 				uint32_t encode = 0;
3084 
3085 				for (int j = 0; j < 16; j++) {
3086 					encode |= index_block[j] << (j * 2);
3087 				}
3088 
3089 				blockptr[8] = color_0 & 0xFF;
3090 				blockptr[9] = (color_0 >> 8) & 0xFF;
3091 				blockptr[10] = color_1 & 0xFF;
3092 				blockptr[11] = (color_1 >> 8) & 0xFF;
3093 				blockptr[12] = encode & 0xFF;
3094 				blockptr[13] = (encode >> 8) & 0xFF;
3095 				blockptr[14] = (encode >> 16) & 0xFF;
3096 				blockptr[15] = (encode >> 24) & 0xFF;
3097 			}
3098 		}
3099 	}
3100 
3101 	//send back to main thread to update un little chunks
3102 	if (probe_bake_mutex) {
3103 		probe_bake_mutex->lock();
3104 	}
3105 
3106 	probe_data->dynamic.updating_stage = GI_UPDATE_STAGE_UPLOADING;
3107 
3108 	if (probe_bake_mutex) {
3109 		probe_bake_mutex->unlock();
3110 	}
3111 }
3112 
_check_gi_probe(Instance * p_gi_probe)3113 bool VisualServerScene::_check_gi_probe(Instance *p_gi_probe) {
3114 
3115 	InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
3116 
3117 	probe_data->dynamic.light_cache_changes.clear();
3118 
3119 	bool all_equal = true;
3120 
3121 	for (List<Instance *>::Element *E = p_gi_probe->scenario->directional_lights.front(); E; E = E->next()) {
3122 
3123 		if (!VSG::storage->light_get_use_gi(E->get()->base))
3124 			continue;
3125 
3126 		InstanceGIProbeData::LightCache lc;
3127 		lc.type = VSG::storage->light_get_type(E->get()->base);
3128 		lc.color = VSG::storage->light_get_color(E->get()->base);
3129 		lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY) * VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_INDIRECT_ENERGY);
3130 		lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
3131 		lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
3132 		lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
3133 		lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
3134 		lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
3135 		lc.visible = E->get()->visible;
3136 
3137 		if (!probe_data->dynamic.light_cache.has(E->get()->self) || probe_data->dynamic.light_cache[E->get()->self] != lc) {
3138 			all_equal = false;
3139 		}
3140 
3141 		probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
3142 	}
3143 
3144 	for (Set<Instance *>::Element *E = probe_data->lights.front(); E; E = E->next()) {
3145 
3146 		if (!VSG::storage->light_get_use_gi(E->get()->base))
3147 			continue;
3148 
3149 		InstanceGIProbeData::LightCache lc;
3150 		lc.type = VSG::storage->light_get_type(E->get()->base);
3151 		lc.color = VSG::storage->light_get_color(E->get()->base);
3152 		lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY) * VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_INDIRECT_ENERGY);
3153 		lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
3154 		lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
3155 		lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
3156 		lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
3157 		lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
3158 		lc.visible = E->get()->visible;
3159 
3160 		if (!probe_data->dynamic.light_cache.has(E->get()->self) || probe_data->dynamic.light_cache[E->get()->self] != lc) {
3161 			all_equal = false;
3162 		}
3163 
3164 		probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
3165 	}
3166 
3167 	//lighting changed from after to before, must do some updating
3168 	return !all_equal || probe_data->dynamic.light_cache_changes.size() != probe_data->dynamic.light_cache.size();
3169 }
3170 
render_probes()3171 void VisualServerScene::render_probes() {
3172 
3173 	/* REFLECTION PROBES */
3174 
3175 	SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
3176 
3177 	bool busy = false;
3178 
3179 	while (ref_probe) {
3180 
3181 		SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
3182 		RID base = ref_probe->self()->owner->base;
3183 
3184 		switch (VSG::storage->reflection_probe_get_update_mode(base)) {
3185 
3186 			case VS::REFLECTION_PROBE_UPDATE_ONCE: {
3187 				if (busy) //already rendering something
3188 					break;
3189 
3190 				bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
3191 				if (done) {
3192 					reflection_probe_render_list.remove(ref_probe);
3193 				} else {
3194 					ref_probe->self()->render_step++;
3195 				}
3196 
3197 				busy = true; //do not render another one of this kind
3198 			} break;
3199 			case VS::REFLECTION_PROBE_UPDATE_ALWAYS: {
3200 
3201 				int step = 0;
3202 				bool done = false;
3203 				while (!done) {
3204 					done = _render_reflection_probe_step(ref_probe->self()->owner, step);
3205 					step++;
3206 				}
3207 
3208 				reflection_probe_render_list.remove(ref_probe);
3209 			} break;
3210 		}
3211 
3212 		ref_probe = next;
3213 	}
3214 
3215 	/* GI PROBES */
3216 
3217 	SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
3218 
3219 	while (gi_probe) {
3220 
3221 		SelfList<InstanceGIProbeData> *next = gi_probe->next();
3222 
3223 		InstanceGIProbeData *probe = gi_probe->self();
3224 		Instance *instance_probe = probe->owner;
3225 
3226 		//check if probe must be setup, but don't do if on the lighting thread
3227 
3228 		bool force_lighting = false;
3229 
3230 		if (probe->invalid || (probe->dynamic.updating_stage == GI_UPDATE_STAGE_CHECK && probe->base_version != VSG::storage->gi_probe_get_version(instance_probe->base))) {
3231 
3232 			_setup_gi_probe(instance_probe);
3233 			force_lighting = true;
3234 		}
3235 
3236 		float propagate = VSG::storage->gi_probe_get_propagation(instance_probe->base);
3237 
3238 		if (probe->dynamic.propagate != propagate) {
3239 			probe->dynamic.propagate = propagate;
3240 			force_lighting = true;
3241 		}
3242 
3243 		if (!probe->invalid && probe->dynamic.enabled) {
3244 
3245 			switch (probe->dynamic.updating_stage) {
3246 				case GI_UPDATE_STAGE_CHECK: {
3247 
3248 					if (_check_gi_probe(instance_probe) || force_lighting) { //send to lighting thread
3249 
3250 #ifndef NO_THREADS
3251 						probe_bake_mutex->lock();
3252 						probe->dynamic.updating_stage = GI_UPDATE_STAGE_LIGHTING;
3253 						probe_bake_list.push_back(instance_probe);
3254 						probe_bake_mutex->unlock();
3255 						probe_bake_sem->post();
3256 
3257 #else
3258 
3259 						_bake_gi_probe(instance_probe);
3260 #endif
3261 					}
3262 				} break;
3263 				case GI_UPDATE_STAGE_LIGHTING: {
3264 					//do none, wait til done!
3265 
3266 				} break;
3267 				case GI_UPDATE_STAGE_UPLOADING: {
3268 
3269 					//uint64_t us = OS::get_singleton()->get_ticks_usec();
3270 
3271 					for (int i = 0; i < (int)probe->dynamic.mipmaps_3d.size(); i++) {
3272 
3273 						PoolVector<uint8_t>::Read r = probe->dynamic.mipmaps_3d[i].read();
3274 						VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data, 0, probe->dynamic.grid_size[2] >> i, i, r.ptr());
3275 					}
3276 
3277 					probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
3278 
3279 					//print_line("UPLOAD TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
3280 				} break;
3281 			}
3282 		}
3283 		//_update_gi_probe(gi_probe->self()->owner);
3284 
3285 		gi_probe = next;
3286 	}
3287 }
3288 
_update_dirty_instance(Instance * p_instance)3289 void VisualServerScene::_update_dirty_instance(Instance *p_instance) {
3290 
3291 	if (p_instance->update_aabb) {
3292 		_update_instance_aabb(p_instance);
3293 	}
3294 
3295 	if (p_instance->update_materials) {
3296 
3297 		if (p_instance->base_type == VS::INSTANCE_MESH) {
3298 			//remove materials no longer used and un-own them
3299 
3300 			int new_mat_count = VSG::storage->mesh_get_surface_count(p_instance->base);
3301 			for (int i = p_instance->materials.size() - 1; i >= new_mat_count; i--) {
3302 				if (p_instance->materials[i].is_valid()) {
3303 					VSG::storage->material_remove_instance_owner(p_instance->materials[i], p_instance);
3304 				}
3305 			}
3306 			p_instance->materials.resize(new_mat_count);
3307 
3308 			int new_blend_shape_count = VSG::storage->mesh_get_blend_shape_count(p_instance->base);
3309 			if (new_blend_shape_count != p_instance->blend_values.size()) {
3310 				p_instance->blend_values.resize(new_blend_shape_count);
3311 				for (int i = 0; i < new_blend_shape_count; i++) {
3312 					p_instance->blend_values.write[i] = 0;
3313 				}
3314 			}
3315 		}
3316 
3317 		if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
3318 
3319 			InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
3320 
3321 			bool can_cast_shadows = true;
3322 			bool is_animated = false;
3323 
3324 			if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) {
3325 				can_cast_shadows = false;
3326 			} else if (p_instance->material_override.is_valid()) {
3327 				can_cast_shadows = VSG::storage->material_casts_shadows(p_instance->material_override);
3328 				is_animated = VSG::storage->material_is_animated(p_instance->material_override);
3329 			} else {
3330 
3331 				if (p_instance->base_type == VS::INSTANCE_MESH) {
3332 					RID mesh = p_instance->base;
3333 
3334 					if (mesh.is_valid()) {
3335 						bool cast_shadows = false;
3336 
3337 						for (int i = 0; i < p_instance->materials.size(); i++) {
3338 
3339 							RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : VSG::storage->mesh_surface_get_material(mesh, i);
3340 
3341 							if (!mat.is_valid()) {
3342 								cast_shadows = true;
3343 							} else {
3344 
3345 								if (VSG::storage->material_casts_shadows(mat)) {
3346 									cast_shadows = true;
3347 								}
3348 
3349 								if (VSG::storage->material_is_animated(mat)) {
3350 									is_animated = true;
3351 								}
3352 							}
3353 						}
3354 
3355 						if (!cast_shadows) {
3356 							can_cast_shadows = false;
3357 						}
3358 					}
3359 
3360 				} else if (p_instance->base_type == VS::INSTANCE_MULTIMESH) {
3361 					RID mesh = VSG::storage->multimesh_get_mesh(p_instance->base);
3362 					if (mesh.is_valid()) {
3363 
3364 						bool cast_shadows = false;
3365 
3366 						int sc = VSG::storage->mesh_get_surface_count(mesh);
3367 						for (int i = 0; i < sc; i++) {
3368 
3369 							RID mat = VSG::storage->mesh_surface_get_material(mesh, i);
3370 
3371 							if (!mat.is_valid()) {
3372 								cast_shadows = true;
3373 
3374 							} else {
3375 
3376 								if (VSG::storage->material_casts_shadows(mat)) {
3377 									cast_shadows = true;
3378 								}
3379 								if (VSG::storage->material_is_animated(mat)) {
3380 									is_animated = true;
3381 								}
3382 							}
3383 						}
3384 
3385 						if (!cast_shadows) {
3386 							can_cast_shadows = false;
3387 						}
3388 					}
3389 				} else if (p_instance->base_type == VS::INSTANCE_IMMEDIATE) {
3390 
3391 					RID mat = VSG::storage->immediate_get_material(p_instance->base);
3392 
3393 					can_cast_shadows = !mat.is_valid() || VSG::storage->material_casts_shadows(mat);
3394 
3395 					if (mat.is_valid() && VSG::storage->material_is_animated(mat)) {
3396 						is_animated = true;
3397 					}
3398 				} else if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
3399 
3400 					bool cast_shadows = false;
3401 
3402 					int dp = VSG::storage->particles_get_draw_passes(p_instance->base);
3403 
3404 					for (int i = 0; i < dp; i++) {
3405 
3406 						RID mesh = VSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
3407 						if (!mesh.is_valid())
3408 							continue;
3409 
3410 						int sc = VSG::storage->mesh_get_surface_count(mesh);
3411 						for (int j = 0; j < sc; j++) {
3412 
3413 							RID mat = VSG::storage->mesh_surface_get_material(mesh, j);
3414 
3415 							if (!mat.is_valid()) {
3416 								cast_shadows = true;
3417 							} else {
3418 
3419 								if (VSG::storage->material_casts_shadows(mat)) {
3420 									cast_shadows = true;
3421 								}
3422 
3423 								if (VSG::storage->material_is_animated(mat)) {
3424 									is_animated = true;
3425 								}
3426 							}
3427 						}
3428 					}
3429 
3430 					if (!cast_shadows) {
3431 						can_cast_shadows = false;
3432 					}
3433 				}
3434 			}
3435 
3436 			if (can_cast_shadows != geom->can_cast_shadows) {
3437 				//ability to cast shadows change, let lights now
3438 				for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
3439 					InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
3440 					light->shadow_dirty = true;
3441 				}
3442 
3443 				geom->can_cast_shadows = can_cast_shadows;
3444 			}
3445 
3446 			geom->material_is_animated = is_animated;
3447 		}
3448 	}
3449 
3450 	_instance_update_list.remove(&p_instance->update_item);
3451 
3452 	_update_instance(p_instance);
3453 
3454 	p_instance->update_aabb = false;
3455 	p_instance->update_materials = false;
3456 }
3457 
update_dirty_instances()3458 void VisualServerScene::update_dirty_instances() {
3459 
3460 	VSG::storage->update_dirty_resources();
3461 
3462 	while (_instance_update_list.first()) {
3463 
3464 		_update_dirty_instance(_instance_update_list.first()->self());
3465 	}
3466 }
3467 
free(RID p_rid)3468 bool VisualServerScene::free(RID p_rid) {
3469 
3470 	if (camera_owner.owns(p_rid)) {
3471 
3472 		Camera *camera = camera_owner.get(p_rid);
3473 
3474 		camera_owner.free(p_rid);
3475 		memdelete(camera);
3476 
3477 	} else if (scenario_owner.owns(p_rid)) {
3478 
3479 		Scenario *scenario = scenario_owner.get(p_rid);
3480 
3481 		while (scenario->instances.first()) {
3482 			instance_set_scenario(scenario->instances.first()->self()->self, RID());
3483 		}
3484 		VSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
3485 		VSG::scene_render->free(scenario->reflection_atlas);
3486 		scenario_owner.free(p_rid);
3487 		memdelete(scenario);
3488 
3489 	} else if (instance_owner.owns(p_rid)) {
3490 		// delete the instance
3491 
3492 		update_dirty_instances();
3493 
3494 		Instance *instance = instance_owner.get(p_rid);
3495 
3496 		instance_set_use_lightmap(p_rid, RID(), RID());
3497 		instance_set_scenario(p_rid, RID());
3498 		instance_set_base(p_rid, RID());
3499 		instance_geometry_set_material_override(p_rid, RID());
3500 		instance_attach_skeleton(p_rid, RID());
3501 
3502 		update_dirty_instances(); //in case something changed this
3503 
3504 		instance_owner.free(p_rid);
3505 		memdelete(instance);
3506 	} else {
3507 		return false;
3508 	}
3509 
3510 	return true;
3511 }
3512 
3513 VisualServerScene *VisualServerScene::singleton = NULL;
3514 
VisualServerScene()3515 VisualServerScene::VisualServerScene() {
3516 
3517 #ifndef NO_THREADS
3518 	probe_bake_sem = Semaphore::create();
3519 	probe_bake_mutex = Mutex::create();
3520 	probe_bake_thread = Thread::create(_gi_probe_bake_threads, this);
3521 	probe_bake_thread_exit = false;
3522 #endif
3523 
3524 	render_pass = 1;
3525 	singleton = this;
3526 }
3527 
~VisualServerScene()3528 VisualServerScene::~VisualServerScene() {
3529 
3530 #ifndef NO_THREADS
3531 	probe_bake_thread_exit = true;
3532 	probe_bake_sem->post();
3533 	Thread::wait_to_finish(probe_bake_thread);
3534 	memdelete(probe_bake_thread);
3535 	memdelete(probe_bake_sem);
3536 	memdelete(probe_bake_mutex);
3537 
3538 #endif
3539 }
3540