Debian Codegraph @

drivers/gles3/rasterizer_canvas_gles3.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* rasterizer_canvas_gles3.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "rasterizer_canvas_gles3.h"
32
33 #ifdef GLES3_ENABLED
34
35 #include "rasterizer_gles3.h"
36 #include "rasterizer_scene_gles3.h"
37
38 #include "core/config/project_settings.h"
39 #include "core/math/geometry_2d.h"
40 #include "core/math/transform_interpolator.h"
41 #include "servers/rendering/rendering_server_default.h"
42 #include "storage/config.h"
43 #include "storage/material_storage.h"
44 #include "storage/mesh_storage.h"
45 #include "storage/particles_storage.h"
46 #include "storage/texture_storage.h"
47
48 void RasterizerCanvasGLES3::_update_transform_2d_to_mat4(const Transform2D &p_transform, float *p_mat4) {
49 p_mat4[0] = p_transform.columns[0][0];
50 p_mat4[1] = p_transform.columns[0][1];
51 p_mat4[2] = 0;
52 p_mat4[3] = 0;
53 p_mat4[4] = p_transform.columns[1][0];
54 p_mat4[5] = p_transform.columns[1][1];
55 p_mat4[6] = 0;
56 p_mat4[7] = 0;
57 p_mat4[8] = 0;
58 p_mat4[9] = 0;
59 p_mat4[10] = 1;
60 p_mat4[11] = 0;
61 p_mat4[12] = p_transform.columns[2][0];
62 p_mat4[13] = p_transform.columns[2][1];
63 p_mat4[14] = 0;
64 p_mat4[15] = 1;
65 }
66
67 void RasterizerCanvasGLES3::_update_transform_2d_to_mat2x4(const Transform2D &p_transform, float *p_mat2x4) {
68 p_mat2x4[0] = p_transform.columns[0][0];
69 p_mat2x4[1] = p_transform.columns[1][0];
70 p_mat2x4[2] = 0;
71 p_mat2x4[3] = p_transform.columns[2][0];
72
73 p_mat2x4[4] = p_transform.columns[0][1];
74 p_mat2x4[5] = p_transform.columns[1][1];
75 p_mat2x4[6] = 0;
76 p_mat2x4[7] = p_transform.columns[2][1];
77 }
78
79 void RasterizerCanvasGLES3::_update_transform_2d_to_mat2x3(const Transform2D &p_transform, float *p_mat2x3) {
80 p_mat2x3[0] = p_transform.columns[0][0];
81 p_mat2x3[1] = p_transform.columns[0][1];
82 p_mat2x3[2] = p_transform.columns[1][0];
83 p_mat2x3[3] = p_transform.columns[1][1];
84 p_mat2x3[4] = p_transform.columns[2][0];
85 p_mat2x3[5] = p_transform.columns[2][1];
86 }
87
88 void RasterizerCanvasGLES3::_update_transform_to_mat4(const Transform3D &p_transform, float *p_mat4) {
89 p_mat4[0] = p_transform.basis.rows[0][0];
90 p_mat4[1] = p_transform.basis.rows[1][0];
91 p_mat4[2] = p_transform.basis.rows[2][0];
92 p_mat4[3] = 0;
93 p_mat4[4] = p_transform.basis.rows[0][1];
94 p_mat4[5] = p_transform.basis.rows[1][1];
95 p_mat4[6] = p_transform.basis.rows[2][1];
96 p_mat4[7] = 0;
97 p_mat4[8] = p_transform.basis.rows[0][2];
98 p_mat4[9] = p_transform.basis.rows[1][2];
99 p_mat4[10] = p_transform.basis.rows[2][2];
100 p_mat4[11] = 0;
101 p_mat4[12] = p_transform.origin.x;
102 p_mat4[13] = p_transform.origin.y;
103 p_mat4[14] = p_transform.origin.z;
104 p_mat4[15] = 1;
105 }
106
107 void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_light_list, const Transform2D &p_canvas_transform, RS::CanvasItemTextureFilter p_default_filter, RS::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used, RenderingMethod::RenderInfo *r_render_info) {
108 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
109 GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
110 GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
111
112 Transform2D canvas_transform_inverse = p_canvas_transform.affine_inverse();
113
114 // Clear out any state that may have been left from the 3D pass.
115 reset_canvas();
116
117 if (state.canvas_instance_data_buffers[state.current_data_buffer_index].fence != GLsync()) {
118 GLint syncStatus;
119 glGetSynciv(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence, GL_SYNC_STATUS, 1, nullptr, &syncStatus);
120 if (syncStatus == GL_UNSIGNALED) {
121 // If older than 2 frames, wait for sync OpenGL can have up to 3 frames in flight, any more and we need to sync anyway.
122 if (state.canvas_instance_data_buffers[state.current_data_buffer_index].last_frame_used < RSG::rasterizer->get_frame_number() - 2) {
123 #ifndef WEB_ENABLED
124 // On web, we do nothing as the glSubBufferData will force a sync anyway and WebGL does not like waiting.
125 glClientWaitSync(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence, 0, 100000000); // wait for up to 100ms
126 #endif
127 state.canvas_instance_data_buffers[state.current_data_buffer_index].last_frame_used = RSG::rasterizer->get_frame_number();
128 glDeleteSync(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence);
129 state.canvas_instance_data_buffers[state.current_data_buffer_index].fence = GLsync();
130 } else {
131 // Used in last frame or frame before that. OpenGL can get up to two frames behind, so these buffers may still be in use
132 // Allocate a new buffer and use that.
133 _allocate_instance_data_buffer();
134 }
135 } else {
136 // Already finished all rendering commands, we can use it.
137 state.canvas_instance_data_buffers[state.current_data_buffer_index].last_frame_used = RSG::rasterizer->get_frame_number();
138 glDeleteSync(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence);
139 state.canvas_instance_data_buffers[state.current_data_buffer_index].fence = GLsync();
140 }
141 }
142
143 //setup directional lights if exist
144
145 uint32_t light_count = 0;
146 uint32_t directional_light_count = 0;
147 {
148 Light *l = p_directional_light_list;
149 uint32_t index = 0;
150
151 while (l) {
152 if (index == data.max_lights_per_render) {
153 l->render_index_cache = -1;
154 l = l->next_ptr;
155 continue;
156 }
157
158 CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
159 if (!clight) { //unused or invalid texture
160 l->render_index_cache = -1;
161 l = l->next_ptr;
162 ERR_CONTINUE(!clight);
163 }
164
165 Vector2 canvas_light_dir = l->xform_cache.columns[1].normalized();
166
167 state.light_uniforms[index].position[0] = -canvas_light_dir.x;
168 state.light_uniforms[index].position[1] = -canvas_light_dir.y;
169
170 _update_transform_2d_to_mat2x4(clight->shadow.directional_xform, state.light_uniforms[index].shadow_matrix);
171
172 state.light_uniforms[index].height = l->height; //0..1 here
173
174 for (int i = 0; i < 4; i++) {
175 state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
176 state.light_uniforms[index].color[i] = l->color[i];
177 }
178
179 state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate
180
181 if (state.shadow_fb != 0) {
182 state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
183 state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
184 state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
185 } else {
186 state.light_uniforms[index].shadow_pixel_size = 1.0;
187 state.light_uniforms[index].shadow_z_far_inv = 1.0;
188 state.light_uniforms[index].shadow_y_ofs = 0;
189 }
190
191 state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
192 state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
193
194 if (clight->shadow.enabled) {
195 state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
196 }
197
198 l->render_index_cache = index;
199
200 index++;
201 l = l->next_ptr;
202 }
203
204 light_count = index;
205 directional_light_count = light_count;
206 state.using_directional_lights = directional_light_count > 0;
207 }
208
209 //setup lights if exist
210
211 {
212 Light *l = p_light_list;
213 uint32_t index = light_count;
214
215 while (l) {
216 if (index == data.max_lights_per_render) {
217 l->render_index_cache = -1;
218 l = l->next_ptr;
219 continue;
220 }
221
222 CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
223 if (!clight) { //unused or invalid texture
224 l->render_index_cache = -1;
225 l = l->next_ptr;
226 ERR_CONTINUE(!clight);
227 }
228
229 Transform2D final_xform;
230 if (!RSG::canvas->_interpolation_data.interpolation_enabled || !l->interpolated) {
231 final_xform = l->xform_curr;
232 } else {
233 real_t f = Engine::get_singleton()->get_physics_interpolation_fraction();
234 TransformInterpolator::interpolate_transform_2d(l->xform_prev, l->xform_curr, final_xform, f);
235 }
236 // Convert light position to canvas coordinates, as all computation is done in canvas coordinates to avoid precision loss.
237 Vector2 canvas_light_pos = p_canvas_transform.xform(final_xform.get_origin());
238 state.light_uniforms[index].position[0] = canvas_light_pos.x;
239 state.light_uniforms[index].position[1] = canvas_light_pos.y;
240
241 _update_transform_2d_to_mat2x4(l->light_shader_xform.affine_inverse(), state.light_uniforms[index].matrix);
242 _update_transform_2d_to_mat2x4(l->xform_cache.affine_inverse(), state.light_uniforms[index].shadow_matrix);
243
244 state.light_uniforms[index].height = l->height * (p_canvas_transform.columns[0].length() + p_canvas_transform.columns[1].length()) * 0.5; //approximate height conversion to the canvas size, since all calculations are done in canvas coords to avoid precision loss
245 for (int i = 0; i < 4; i++) {
246 state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
247 state.light_uniforms[index].color[i] = l->color[i];
248 }
249
250 state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate
251
252 if (state.shadow_fb != 0) {
253 state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
254 state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
255 state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
256 } else {
257 state.light_uniforms[index].shadow_pixel_size = 1.0;
258 state.light_uniforms[index].shadow_z_far_inv = 1.0;
259 state.light_uniforms[index].shadow_y_ofs = 0;
260 }
261
262 state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
263 state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
264
265 if (clight->shadow.enabled) {
266 state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
267 }
268
269 if (clight->texture.is_valid()) {
270 Rect2 atlas_rect = GLES3::TextureStorage::get_singleton()->texture_atlas_get_texture_rect(clight->texture);
271 state.light_uniforms[index].atlas_rect[0] = atlas_rect.position.x;
272 state.light_uniforms[index].atlas_rect[1] = atlas_rect.position.y;
273 state.light_uniforms[index].atlas_rect[2] = atlas_rect.size.width;
274 state.light_uniforms[index].atlas_rect[3] = atlas_rect.size.height;
275
276 } else {
277 state.light_uniforms[index].atlas_rect[0] = 0;
278 state.light_uniforms[index].atlas_rect[1] = 0;
279 state.light_uniforms[index].atlas_rect[2] = 0;
280 state.light_uniforms[index].atlas_rect[3] = 0;
281 }
282
283 l->render_index_cache = index;
284
285 index++;
286 l = l->next_ptr;
287 }
288
289 light_count = index;
290 }
291
292 if (light_count > 0) {
293 glBindBufferBase(GL_UNIFORM_BUFFER, LIGHT_UNIFORM_LOCATION, state.canvas_instance_data_buffers[state.current_data_buffer_index].light_ubo);
294
295 #ifdef WEB_ENABLED
296 glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightUniform) * light_count, state.light_uniforms);
297 #else
298 // On Desktop and mobile we map the memory without synchronizing for maximum speed.
299 void *ubo = glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(LightUniform) * light_count, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
300 memcpy(ubo, state.light_uniforms, sizeof(LightUniform) * light_count);
301 glUnmapBuffer(GL_UNIFORM_BUFFER);
302 #endif
303
304 GLuint texture_atlas = texture_storage->texture_atlas_get_texture();
305 if (texture_atlas == 0) {
306 GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
307 texture_atlas = tex->tex_id;
308 }
309 glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 2);
310 glBindTexture(GL_TEXTURE_2D, texture_atlas);
311 GLuint shadow_tex = state.shadow_texture;
312 if (shadow_tex == 0) {
313 GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
314 shadow_tex = tex->tex_id;
315 }
316 glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 3);
317 glBindTexture(GL_TEXTURE_2D, shadow_tex);
318 }
319
320 {
321 //update canvas state uniform buffer
322 StateBuffer state_buffer;
323
324 Size2i ssize = texture_storage->render_target_get_size(p_to_render_target);
325
326 // If we've overridden the render target's color texture, then we need
327 // to invert the Y axis, so 2D texture appear right side up.
328 // We're probably rendering directly to an XR device.
329 float y_scale = texture_storage->render_target_get_override_color(p_to_render_target).is_valid() ? -2.0f : 2.0f;
330
331 Transform3D screen_transform;
332 screen_transform.translate_local(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f);
333 screen_transform.scale(Vector3(2.0f / ssize.width, y_scale / ssize.height, 1.0f));
334 _update_transform_to_mat4(screen_transform, state_buffer.screen_transform);
335 _update_transform_2d_to_mat4(p_canvas_transform, state_buffer.canvas_transform);
336
337 Transform2D normal_transform = p_canvas_transform;
338 normal_transform.columns[0].normalize();
339 normal_transform.columns[1].normalize();
340 normal_transform.columns[2] = Vector2();
341 _update_transform_2d_to_mat4(normal_transform, state_buffer.canvas_normal_transform);
342
343 state_buffer.canvas_modulate[0] = p_modulate.r;
344 state_buffer.canvas_modulate[1] = p_modulate.g;
345 state_buffer.canvas_modulate[2] = p_modulate.b;
346 state_buffer.canvas_modulate[3] = p_modulate.a;
347
348 Size2 render_target_size = texture_storage->render_target_get_size(p_to_render_target);
349 state_buffer.screen_pixel_size[0] = 1.0 / render_target_size.x;
350 state_buffer.screen_pixel_size[1] = 1.0 / render_target_size.y;
351
352 state_buffer.time = state.time;
353 state_buffer.use_pixel_snap = p_snap_2d_vertices_to_pixel;
354
355 state_buffer.directional_light_count = directional_light_count;
356
357 Vector2 canvas_scale = p_canvas_transform.get_scale();
358
359 state_buffer.sdf_to_screen[0] = render_target_size.width / canvas_scale.x;
360 state_buffer.sdf_to_screen[1] = render_target_size.height / canvas_scale.y;
361
362 state_buffer.screen_to_sdf[0] = 1.0 / state_buffer.sdf_to_screen[0];
363 state_buffer.screen_to_sdf[1] = 1.0 / state_buffer.sdf_to_screen[1];
364
365 Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_to_render_target);
366 Rect2 sdf_tex_rect(sdf_rect.position / canvas_scale, sdf_rect.size / canvas_scale);
367
368 state_buffer.sdf_to_tex[0] = 1.0 / sdf_tex_rect.size.width;
369 state_buffer.sdf_to_tex[1] = 1.0 / sdf_tex_rect.size.height;
370 state_buffer.sdf_to_tex[2] = -sdf_tex_rect.position.x / sdf_tex_rect.size.width;
371 state_buffer.sdf_to_tex[3] = -sdf_tex_rect.position.y / sdf_tex_rect.size.height;
372
373 state_buffer.tex_to_sdf = 1.0 / ((canvas_scale.x + canvas_scale.y) * 0.5);
374
375 glBindBufferBase(GL_UNIFORM_BUFFER, BASE_UNIFORM_LOCATION, state.canvas_instance_data_buffers[state.current_data_buffer_index].state_ubo);
376 glBufferData(GL_UNIFORM_BUFFER, sizeof(StateBuffer), &state_buffer, GL_STREAM_DRAW);
377
378 GLuint global_buffer = material_storage->global_shader_parameters_get_uniform_buffer();
379
380 glBindBufferBase(GL_UNIFORM_BUFFER, GLOBAL_UNIFORM_LOCATION, global_buffer);
381 glBindBuffer(GL_UNIFORM_BUFFER, 0);
382 }
383
384 glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 5);
385 glBindTexture(GL_TEXTURE_2D, texture_storage->render_target_get_sdf_texture(p_to_render_target));
386
387 {
388 state.default_filter = p_default_filter;
389 state.default_repeat = p_default_repeat;
390 }
391
392 Size2 render_target_size = texture_storage->render_target_get_size(p_to_render_target);
393 glViewport(0, 0, render_target_size.x, render_target_size.y);
394
395 r_sdf_used = false;
396 int item_count = 0;
397 bool backbuffer_cleared = false;
398 bool time_used = false;
399 bool material_screen_texture_cached = false;
400 bool material_screen_texture_mipmaps_cached = false;
401 Rect2 back_buffer_rect;
402 bool backbuffer_copy = false;
403 bool backbuffer_gen_mipmaps = false;
404 bool update_skeletons = false;
405
406 Item *ci = p_item_list;
407 Item *canvas_group_owner = nullptr;
408 bool skip_item = false;
409
410 state.last_item_index = 0;
411
412 while (ci) {
413 if (ci->copy_back_buffer && canvas_group_owner == nullptr) {
414 backbuffer_copy = true;
415
416 if (ci->copy_back_buffer->full) {
417 back_buffer_rect = Rect2();
418 } else {
419 back_buffer_rect = ci->copy_back_buffer->rect;
420 }
421 }
422
423 // Check material for something that may change flow of rendering, but do not bind for now.
424 RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
425 if (material.is_valid()) {
426 GLES3::CanvasMaterialData *md = static_cast<GLES3::CanvasMaterialData *>(material_storage->material_get_data(material, RS::SHADER_CANVAS_ITEM));
427 if (md && md->shader_data->valid) {
428 if (md->shader_data->uses_screen_texture && canvas_group_owner == nullptr) {
429 if (!material_screen_texture_cached) {
430 backbuffer_copy = true;
431 back_buffer_rect = Rect2();
432 backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
433 } else if (!material_screen_texture_mipmaps_cached) {
434 backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
435 }
436 }
437
438 if (md->shader_data->uses_sdf) {
439 r_sdf_used = true;
440 }
441 if (md->shader_data->uses_time) {
442 time_used = true;
443 }
444 }
445 }
446
447 if (ci->skeleton.is_valid()) {
448 const Item::Command *c = ci->commands;
449
450 while (c) {
451 if (c->type == Item::Command::TYPE_MESH) {
452 const Item::CommandMesh *cm = static_cast<const Item::CommandMesh *>(c);
453 if (cm->mesh_instance.is_valid()) {
454 mesh_storage->mesh_instance_check_for_update(cm->mesh_instance);
455 mesh_storage->mesh_instance_set_canvas_item_transform(cm->mesh_instance, canvas_transform_inverse * ci->final_transform);
456 update_skeletons = true;
457 }
458 }
459 c = c->next;
460 }
461 }
462
463 if (ci->canvas_group_owner != nullptr) {
464 if (canvas_group_owner == nullptr) {
465 if (update_skeletons) {
466 mesh_storage->update_mesh_instances();
467 update_skeletons = false;
468 }
469 // Canvas group begins here, render until before this item
470 _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, false, r_render_info, material_screen_texture_mipmaps_cached);
471 item_count = 0;
472
473 if (ci->canvas_group_owner->canvas_group->mode != RS::CANVAS_GROUP_MODE_TRANSPARENT) {
474 Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
475 texture_storage->render_target_copy_to_back_buffer(p_to_render_target, group_rect, false);
476 if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
477 ci->canvas_group_owner->use_canvas_group = false;
478 items[item_count++] = ci->canvas_group_owner;
479 }
480 } else if (!backbuffer_cleared) {
481 texture_storage->render_target_clear_back_buffer(p_to_render_target, Rect2i(), Color(0, 0, 0, 0));
482 backbuffer_cleared = true;
483 }
484
485 backbuffer_copy = false;
486 canvas_group_owner = ci->canvas_group_owner; //continue until owner found
487 }
488
489 ci->canvas_group_owner = nullptr; //must be cleared
490 }
491
492 if (canvas_group_owner == nullptr && ci->canvas_group != nullptr && ci->canvas_group->mode != RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
493 skip_item = true;
494 }
495
496 if (ci == canvas_group_owner) {
497 if (update_skeletons) {
498 mesh_storage->update_mesh_instances();
499 update_skeletons = false;
500 }
501 _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, true, r_render_info, material_screen_texture_mipmaps_cached);
502 item_count = 0;
503
504 if (ci->canvas_group->blur_mipmaps) {
505 texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, ci->global_rect_cache);
506 }
507
508 canvas_group_owner = nullptr;
509 // Backbuffer is dirty now and needs to be re-cleared if another CanvasGroup needs it.
510 backbuffer_cleared = false;
511
512 // Tell the renderer to paint this as a canvas group
513 ci->use_canvas_group = true;
514 } else {
515 ci->use_canvas_group = false;
516 }
517
518 if (backbuffer_copy) {
519 if (update_skeletons) {
520 mesh_storage->update_mesh_instances();
521 update_skeletons = false;
522 }
523 //render anything pending, including clearing if no items
524
525 _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, false, r_render_info, material_screen_texture_mipmaps_cached);
526 item_count = 0;
527
528 texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, backbuffer_gen_mipmaps);
529
530 backbuffer_copy = false;
531 material_screen_texture_cached = true; // After a backbuffer copy, screen texture makes no further copies.
532 material_screen_texture_mipmaps_cached = backbuffer_gen_mipmaps;
533 backbuffer_gen_mipmaps = false;
534 }
535
536 if (backbuffer_gen_mipmaps) {
537 texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, back_buffer_rect);
538
539 backbuffer_gen_mipmaps = false;
540 material_screen_texture_mipmaps_cached = true;
541 }
542
543 // just add all items for now
544 if (skip_item) {
545 skip_item = false;
546 } else {
547 items[item_count++] = ci;
548 }
549
550 if (!ci->next || item_count == MAX_RENDER_ITEMS - 1) {
551 if (update_skeletons) {
552 mesh_storage->update_mesh_instances();
553 update_skeletons = false;
554 }
555 _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, canvas_group_owner != nullptr, r_render_info, material_screen_texture_mipmaps_cached);
556 //then reset
557 item_count = 0;
558 }
559
560 ci = ci->next;
561 }
562
563 if (time_used) {
564 RenderingServerDefault::redraw_request();
565 }
566
567 state.canvas_instance_data_buffers[state.current_data_buffer_index].fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
568
569 // Clear out state used in 2D pass
570 reset_canvas();
571 state.current_data_buffer_index = (state.current_data_buffer_index + 1) % state.canvas_instance_data_buffers.size();
572 state.current_instance_buffer_index = 0;
573 }
574
575 void RasterizerCanvasGLES3::_render_items(RID p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, bool &r_sdf_used, bool p_to_backbuffer, RenderingMethod::RenderInfo *r_render_info, bool p_backbuffer_has_mipmaps) {
576 GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
577
578 canvas_begin(p_to_render_target, p_to_backbuffer, p_backbuffer_has_mipmaps);
579
580 if (p_item_count <= 0) {
581 // Nothing to draw, just call canvas_begin() to clear the render target and return.
582 return;
583 }
584
585 uint32_t index = 0;
586 Item *current_clip = nullptr;
587 GLES3::CanvasShaderData *shader_data_cache = nullptr;
588
589 // Record Batches.
590 // First item always forms its own batch.
591 bool batch_broken = false;
592 _new_batch(batch_broken);
593
594 // Override the start position and index as we want to start from where we finished off last time.
595 state.canvas_instance_batches[state.current_batch_index].start = state.last_item_index;
596 index = 0;
597
598 for (int i = 0; i < p_item_count; i++) {
599 Item *ci = items[i];
600
601 if (ci->final_clip_owner != state.canvas_instance_batches[state.current_batch_index].clip) {
602 _new_batch(batch_broken);
603 state.canvas_instance_batches[state.current_batch_index].clip = ci->final_clip_owner;
604 current_clip = ci->final_clip_owner;
605 }
606
607 RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
608 if (ci->use_canvas_group) {
609 if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
610 material = default_clip_children_material;
611 } else {
612 if (material.is_null()) {
613 if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_ONLY) {
614 material = default_clip_children_material;
615 } else {
616 material = default_canvas_group_material;
617 }
618 }
619 }
620 }
621
622 if (material != state.canvas_instance_batches[state.current_batch_index].material) {
623 _new_batch(batch_broken);
624
625 GLES3::CanvasMaterialData *material_data = nullptr;
626 if (material.is_valid()) {
627 material_data = static_cast<GLES3::CanvasMaterialData *>(material_storage->material_get_data(material, RS::SHADER_CANVAS_ITEM));
628 }
629 shader_data_cache = nullptr;
630 if (material_data) {
631 if (material_data->shader_data->version.is_valid() && material_data->shader_data->valid) {
632 shader_data_cache = material_data->shader_data;
633 }
634 }
635
636 state.canvas_instance_batches[state.current_batch_index].material = material;
637 state.canvas_instance_batches[state.current_batch_index].material_data = material_data;
638 if (shader_data_cache) {
639 state.canvas_instance_batches[state.current_batch_index].vertex_input_mask = shader_data_cache->vertex_input_mask;
640 }
641 }
642
643 GLES3::CanvasShaderData::BlendMode blend_mode = shader_data_cache ? shader_data_cache->blend_mode : GLES3::CanvasShaderData::BLEND_MODE_MIX;
644
645 if (!ci->repeat_size.x && !ci->repeat_size.y) {
646 _record_item_commands(ci, p_to_render_target, p_canvas_transform_inverse, current_clip, blend_mode, p_lights, index, batch_broken, r_sdf_used, Point2());
647 } else {
648 Point2 start_pos = ci->repeat_size * -(ci->repeat_times / 2);
649 Point2 offset;
650
651 int repeat_times_x = ci->repeat_size.x ? ci->repeat_times : 0;
652 int repeat_times_y = ci->repeat_size.y ? ci->repeat_times : 0;
653 for (int ry = 0; ry <= repeat_times_y; ry++) {
654 offset.y = start_pos.y + ry * ci->repeat_size.y;
655 for (int rx = 0; rx <= repeat_times_x; rx++) {
656 offset.x = start_pos.x + rx * ci->repeat_size.x;
657 _record_item_commands(ci, p_to_render_target, p_canvas_transform_inverse, current_clip, blend_mode, p_lights, index, batch_broken, r_sdf_used, offset);
658 }
659 }
660 }
661 }
662
663 if (state.current_batch_index == 0 && state.canvas_instance_batches[0].instance_count == 0) {
664 // Nothing to render, just return.
665 return;
666 }
667
668 // Copy over all data needed for rendering.
669 glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.current_instance_buffer_index]);
670 #ifdef WEB_ENABLED
671 glBufferSubData(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), sizeof(InstanceData) * index, state.instance_data_array);
672 #else
673 // On Desktop and mobile we map the memory without synchronizing for maximum speed.
674 void *buffer = glMapBufferRange(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), index * sizeof(InstanceData), GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
675 memcpy(buffer, state.instance_data_array, index * sizeof(InstanceData));
676 glUnmapBuffer(GL_ARRAY_BUFFER);
677 #endif
678
679 glDisable(GL_SCISSOR_TEST);
680 current_clip = nullptr;
681
682 GLES3::CanvasShaderData::BlendMode last_blend_mode = GLES3::CanvasShaderData::BLEND_MODE_MIX;
683 Color last_blend_color;
684
685 state.current_tex = RID();
686
687 const uint64_t base_specialization = GLES3::Config::get_singleton()->float_texture_supported ? 0 : CanvasShaderGLES3::USE_RGBA_SHADOWS;
688
689 for (uint32_t i = 0; i <= state.current_batch_index; i++) {
690 // Skipping when there is no instances.
691 if (state.canvas_instance_batches[i].instance_count == 0) {
692 continue;
693 }
694
695 //setup clip
696 if (current_clip != state.canvas_instance_batches[i].clip) {
697 current_clip = state.canvas_instance_batches[i].clip;
698 if (current_clip) {
699 glEnable(GL_SCISSOR_TEST);
700 glScissor(current_clip->final_clip_rect.position.x, current_clip->final_clip_rect.position.y, current_clip->final_clip_rect.size.x, current_clip->final_clip_rect.size.y);
701 } else {
702 glDisable(GL_SCISSOR_TEST);
703 }
704 }
705
706 GLES3::CanvasMaterialData *material_data = state.canvas_instance_batches[i].material_data;
707 CanvasShaderGLES3::ShaderVariant variant = CanvasShaderGLES3::MODE_DEFAULT;
708 uint64_t specialization = state.canvas_instance_batches[i].specialization;
709 specialization |= base_specialization;
710 RID shader_version = data.canvas_shader_default_version;
711
712 if (material_data) {
713 if (material_data->shader_data->version.is_valid() && material_data->shader_data->valid) {
714 // Bind uniform buffer and textures
715 material_data->bind_uniforms();
716 shader_version = material_data->shader_data->version;
717 }
718 }
719
720 bool success = material_storage->shaders.canvas_shader.version_bind_shader(shader_version, variant, specialization);
721 if (!success) {
722 continue;
723 }
724
725 // Bind per-batch uniforms.
726 material_storage->shaders.canvas_shader.version_set_uniform(CanvasShaderGLES3::BATCH_FLAGS, state.canvas_instance_batches[i].flags, shader_version, variant, specialization);
727 material_storage->shaders.canvas_shader.version_set_uniform(CanvasShaderGLES3::SPECULAR_SHININESS_IN, state.canvas_instance_batches[i].specular_shininess, shader_version, variant, specialization);
728
729 GLES3::CanvasShaderData::BlendMode blend_mode = state.canvas_instance_batches[i].blend_mode;
730 Color blend_color = state.canvas_instance_batches[i].blend_color;
731
732 if (last_blend_mode != blend_mode || last_blend_color != blend_color) {
733 if (last_blend_mode == GLES3::CanvasShaderData::BLEND_MODE_DISABLED) {
734 // re-enable it
735 glEnable(GL_BLEND);
736 } else if (blend_mode == GLES3::CanvasShaderData::BLEND_MODE_DISABLED) {
737 // disable it
738 glDisable(GL_BLEND);
739 }
740
741 switch (blend_mode) {
742 case GLES3::CanvasShaderData::BLEND_MODE_DISABLED: {
743 // Nothing to do here.
744 } break;
745 case GLES3::CanvasShaderData::BLEND_MODE_LCD: {
746 glBlendEquation(GL_FUNC_ADD);
747 if (state.transparent_render_target) {
748 glBlendFuncSeparate(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
749 } else {
750 glBlendFuncSeparate(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_ZERO, GL_ONE);
751 }
752 glBlendColor(blend_color.r, blend_color.g, blend_color.b, blend_color.a);
753
754 } break;
755 case GLES3::CanvasShaderData::BLEND_MODE_MIX: {
756 glBlendEquation(GL_FUNC_ADD);
757 if (state.transparent_render_target) {
758 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
759 } else {
760 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
761 }
762
763 } break;
764 case GLES3::CanvasShaderData::BLEND_MODE_ADD: {
765 glBlendEquation(GL_FUNC_ADD);
766 if (state.transparent_render_target) {
767 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE);
768 } else {
769 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE);
770 }
771
772 } break;
773 case GLES3::CanvasShaderData::BLEND_MODE_SUB: {
774 glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
775 if (state.transparent_render_target) {
776 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE);
777 } else {
778 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE);
779 }
780 } break;
781 case GLES3::CanvasShaderData::BLEND_MODE_MUL: {
782 glBlendEquation(GL_FUNC_ADD);
783 if (state.transparent_render_target) {
784 glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO);
785 } else {
786 glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE);
787 }
788
789 } break;
790 case GLES3::CanvasShaderData::BLEND_MODE_PMALPHA: {
791 glBlendEquation(GL_FUNC_ADD);
792 if (state.transparent_render_target) {
793 glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
794 } else {
795 glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
796 }
797
798 } break;
799 }
800 last_blend_mode = blend_mode;
801 last_blend_color = blend_color;
802 }
803
804 _render_batch(p_lights, i, r_render_info);
805 }
806
807 glDisable(GL_SCISSOR_TEST);
808 state.current_batch_index = 0;
809 state.canvas_instance_batches.clear();
810 state.last_item_index += index;
811 }
812
813 void RasterizerCanvasGLES3::_record_item_commands(const Item *p_item, RID p_render_target, const Transform2D &p_canvas_transform_inverse, Item *&current_clip, GLES3::CanvasShaderData::BlendMode p_blend_mode, Light *p_lights, uint32_t &r_index, bool &r_batch_broken, bool &r_sdf_used, const Point2 &p_repeat_offset) {
814 RenderingServer::CanvasItemTextureFilter texture_filter = p_item->texture_filter == RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT ? state.default_filter : p_item->texture_filter;
815 const uint64_t specialization_command_mask = ~(CanvasShaderGLES3::USE_NINEPATCH | CanvasShaderGLES3::USE_PRIMITIVE | CanvasShaderGLES3::USE_ATTRIBUTES | CanvasShaderGLES3::USE_INSTANCING);
816
817 if (texture_filter != state.canvas_instance_batches[state.current_batch_index].filter) {
818 _new_batch(r_batch_broken);
819
820 state.canvas_instance_batches[state.current_batch_index].filter = texture_filter;
821 }
822
823 Transform2D base_transform = p_item->final_transform;
824 if (p_item->repeat_source_item && (p_repeat_offset.x || p_repeat_offset.y)) {
825 base_transform.columns[2] += p_item->repeat_source_item->final_transform.basis_xform(p_repeat_offset);
826 }
827 base_transform = p_canvas_transform_inverse * base_transform;
828
829 Transform2D draw_transform; // Used by transform command
830
831 Color base_color = p_item->final_modulate;
832 uint32_t base_flags = 0;
833 Size2 texpixel_size;
834
835 bool reclip = false;
836
837 bool skipping = false;
838
839 // TODO: consider making lights a per-batch property and then baking light operations in the shader for better performance.
840 uint32_t lights[4] = { 0, 0, 0, 0 };
841
842 uint16_t light_count = 0;
843 uint16_t shadow_mask = 0;
844
845 {
846 Light *light = p_lights;
847
848 while (light) {
849 if (light->render_index_cache >= 0 && p_item->light_mask & light->item_mask && p_item->z_final >= light->z_min && p_item->z_final <= light->z_max && p_item->global_rect_cache.intersects(light->rect_cache)) {
850 uint32_t light_index = light->render_index_cache;
851 lights[light_count >> 2] |= light_index << ((light_count & 3) * 8);
852
853 if (p_item->light_mask & light->item_shadow_mask) {
854 shadow_mask |= 1 << light_count;
855 }
856
857 light_count++;
858
859 if (light_count == data.max_lights_per_item - 1) {
860 break;
861 }
862 }
863 light = light->next_ptr;
864 }
865
866 base_flags |= light_count << INSTANCE_FLAGS_LIGHT_COUNT_SHIFT;
867 base_flags |= shadow_mask << INSTANCE_FLAGS_SHADOW_MASKED_SHIFT;
868 }
869
870 bool lights_disabled = light_count == 0 && !state.using_directional_lights;
871
872 if (lights_disabled != bool(state.canvas_instance_batches[state.current_batch_index].specialization & CanvasShaderGLES3::DISABLE_LIGHTING)) {
873 _new_batch(r_batch_broken);
874 state.canvas_instance_batches[state.current_batch_index].specialization ^= CanvasShaderGLES3::DISABLE_LIGHTING;
875 }
876
877 const RS::CanvasItemTextureRepeat base_texture_repeat = p_item->texture_repeat == RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT ? state.default_repeat : p_item->texture_repeat;
878 const Item::Command *c = p_item->commands;
879 while (c) {
880 if (skipping && c->type != Item::Command::TYPE_ANIMATION_SLICE) {
881 c = c->next;
882 continue;
883 }
884
885 if (c->type != Item::Command::TYPE_MESH) {
886 // For Meshes, this gets updated below.
887 _update_transform_2d_to_mat2x3(base_transform * draw_transform, state.instance_data_array[r_index].world);
888 }
889
890 // Zero out most fields.
891 for (int i = 0; i < 4; i++) {
892 state.instance_data_array[r_index].modulation[i] = 0.0;
893 state.instance_data_array[r_index].ninepatch_margins[i] = 0.0;
894 state.instance_data_array[r_index].src_rect[i] = 0.0;
895 state.instance_data_array[r_index].dst_rect[i] = 0.0;
896 state.instance_data_array[r_index].lights[i] = uint32_t(0);
897 }
898 state.instance_data_array[r_index].color_texture_pixel_size[0] = 0.0;
899 state.instance_data_array[r_index].color_texture_pixel_size[1] = 0.0;
900
901 state.instance_data_array[r_index].lights[0] = lights[0];
902 state.instance_data_array[r_index].lights[1] = lights[1];
903 state.instance_data_array[r_index].lights[2] = lights[2];
904 state.instance_data_array[r_index].lights[3] = lights[3];
905
906 state.instance_data_array[r_index].flags = base_flags;
907 state.instance_data_array[r_index].instance_uniforms_ofs = p_item->instance_allocated_shader_uniforms_offset;
908
909 Color blend_color = base_color;
910 GLES3::CanvasShaderData::BlendMode blend_mode = p_blend_mode;
911 RS::CanvasItemTextureRepeat texture_repeat = base_texture_repeat;
912 if (c->type == Item::Command::TYPE_RECT) {
913 const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);
914 if (rect->flags & CANVAS_RECT_LCD) {
915 blend_mode = GLES3::CanvasShaderData::BLEND_MODE_LCD;
916 blend_color = rect->modulate * base_color;
917 }
918
919 if (rect->flags & CANVAS_RECT_TILE) {
920 texture_repeat = RS::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED;
921 }
922 }
923 if (texture_repeat != state.canvas_instance_batches[state.current_batch_index].repeat) {
924 _new_batch(r_batch_broken);
925 state.canvas_instance_batches[state.current_batch_index].repeat = texture_repeat;
926 }
927
928 if (blend_mode != state.canvas_instance_batches[state.current_batch_index].blend_mode || blend_color != state.canvas_instance_batches[state.current_batch_index].blend_color) {
929 _new_batch(r_batch_broken);
930 state.canvas_instance_batches[state.current_batch_index].blend_mode = blend_mode;
931 state.canvas_instance_batches[state.current_batch_index].blend_color = blend_color;
932 }
933
934 switch (c->type) {
935 case Item::Command::TYPE_RECT: {
936 const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);
937 if (rect->texture != state.canvas_instance_batches[state.current_batch_index].tex || state.canvas_instance_batches[state.current_batch_index].command_type != Item::Command::TYPE_RECT) {
938 _new_batch(r_batch_broken);
939 state.canvas_instance_batches[state.current_batch_index].tex = rect->texture;
940 state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_RECT;
941 state.canvas_instance_batches[state.current_batch_index].command = c;
942 state.canvas_instance_batches[state.current_batch_index].specialization &= specialization_command_mask;
943 state.canvas_instance_batches[state.current_batch_index].flags = 0;
944 }
945
946 _prepare_canvas_texture(rect->texture, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
947
948 Rect2 src_rect;
949 Rect2 dst_rect;
950
951 if (rect->texture != RID()) {
952 src_rect = (rect->flags & CANVAS_RECT_REGION) ? Rect2(rect->source.position * texpixel_size, rect->source.size * texpixel_size) : Rect2(0, 0, 1, 1);
953 dst_rect = Rect2(rect->rect.position, rect->rect.size);
954
955 if (dst_rect.size.width < 0) {
956 dst_rect.position.x += dst_rect.size.width;
957 dst_rect.size.width *= -1;
958 }
959 if (dst_rect.size.height < 0) {
960 dst_rect.position.y += dst_rect.size.height;
961 dst_rect.size.height *= -1;
962 }
963
964 if (rect->flags & CANVAS_RECT_FLIP_H) {
965 src_rect.size.x *= -1;
966 }
967
968 if (rect->flags & CANVAS_RECT_FLIP_V) {
969 src_rect.size.y *= -1;
970 }
971
972 if (rect->flags & CANVAS_RECT_TRANSPOSE) {
973 state.instance_data_array[r_index].flags |= INSTANCE_FLAGS_TRANSPOSE_RECT;
974 }
975
976 if (rect->flags & CANVAS_RECT_CLIP_UV) {
977 state.instance_data_array[r_index].flags |= INSTANCE_FLAGS_CLIP_RECT_UV;
978 }
979
980 } else {
981 dst_rect = Rect2(rect->rect.position, rect->rect.size);
982
983 if (dst_rect.size.width < 0) {
984 dst_rect.position.x += dst_rect.size.width;
985 dst_rect.size.width *= -1;
986 }
987 if (dst_rect.size.height < 0) {
988 dst_rect.position.y += dst_rect.size.height;
989 dst_rect.size.height *= -1;
990 }
991
992 src_rect = Rect2(0, 0, 1, 1);
993 }
994
995 if (rect->flags & CANVAS_RECT_MSDF) {
996 state.instance_data_array[r_index].flags |= INSTANCE_FLAGS_USE_MSDF;
997 state.instance_data_array[r_index].msdf[0] = rect->px_range; // Pixel range.
998 state.instance_data_array[r_index].msdf[1] = rect->outline; // Outline size.
999 state.instance_data_array[r_index].msdf[2] = 0.f; // Reserved.
1000 state.instance_data_array[r_index].msdf[3] = 0.f; // Reserved.
1001 } else if (rect->flags & CANVAS_RECT_LCD) {
1002 state.instance_data_array[r_index].flags |= INSTANCE_FLAGS_USE_LCD;
1003 }
1004
1005 state.instance_data_array[r_index].modulation[0] = rect->modulate.r * base_color.r;
1006 state.instance_data_array[r_index].modulation[1] = rect->modulate.g * base_color.g;
1007 state.instance_data_array[r_index].modulation[2] = rect->modulate.b * base_color.b;
1008 state.instance_data_array[r_index].modulation[3] = rect->modulate.a * base_color.a;
1009
1010 state.instance_data_array[r_index].src_rect[0] = src_rect.position.x;
1011 state.instance_data_array[r_index].src_rect[1] = src_rect.position.y;
1012 state.instance_data_array[r_index].src_rect[2] = src_rect.size.width;
1013 state.instance_data_array[r_index].src_rect[3] = src_rect.size.height;
1014
1015 state.instance_data_array[r_index].dst_rect[0] = dst_rect.position.x;
1016 state.instance_data_array[r_index].dst_rect[1] = dst_rect.position.y;
1017 state.instance_data_array[r_index].dst_rect[2] = dst_rect.size.width;
1018 state.instance_data_array[r_index].dst_rect[3] = dst_rect.size.height;
1019
1020 _add_to_batch(r_index, r_batch_broken);
1021 } break;
1022
1023 case Item::Command::TYPE_NINEPATCH: {
1024 const Item::CommandNinePatch *np = static_cast<const Item::CommandNinePatch *>(c);
1025
1026 if (np->texture != state.canvas_instance_batches[state.current_batch_index].tex || state.canvas_instance_batches[state.current_batch_index].command_type != Item::Command::TYPE_NINEPATCH) {
1027 _new_batch(r_batch_broken);
1028 state.canvas_instance_batches[state.current_batch_index].tex = np->texture;
1029 state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_NINEPATCH;
1030 state.canvas_instance_batches[state.current_batch_index].command = c;
1031 state.canvas_instance_batches[state.current_batch_index].specialization &= specialization_command_mask;
1032 state.canvas_instance_batches[state.current_batch_index].specialization |= CanvasShaderGLES3::USE_NINEPATCH;
1033 state.canvas_instance_batches[state.current_batch_index].flags = 0;
1034 }
1035
1036 _prepare_canvas_texture(np->texture, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
1037
1038 Rect2 src_rect;
1039 Rect2 dst_rect(np->rect.position.x, np->rect.position.y, np->rect.size.x, np->rect.size.y);
1040
1041 if (np->texture == RID()) {
1042 texpixel_size = Size2(1, 1);
1043 src_rect = Rect2(0, 0, 1, 1);
1044
1045 } else {
1046 if (np->source != Rect2()) {
1047 src_rect = Rect2(np->source.position.x * texpixel_size.width, np->source.position.y * texpixel_size.height, np->source.size.x * texpixel_size.width, np->source.size.y * texpixel_size.height);
1048 state.instance_data_array[r_index].color_texture_pixel_size[0] = 1.0 / np->source.size.width;
1049 state.instance_data_array[r_index].color_texture_pixel_size[1] = 1.0 / np->source.size.height;
1050
1051 } else {
1052 src_rect = Rect2(0, 0, 1, 1);
1053 }
1054 }
1055
1056 state.instance_data_array[r_index].modulation[0] = np->color.r * base_color.r;
1057 state.instance_data_array[r_index].modulation[1] = np->color.g * base_color.g;
1058 state.instance_data_array[r_index].modulation[2] = np->color.b * base_color.b;
1059 state.instance_data_array[r_index].modulation[3] = np->color.a * base_color.a;
1060
1061 state.instance_data_array[r_index].src_rect[0] = src_rect.position.x;
1062 state.instance_data_array[r_index].src_rect[1] = src_rect.position.y;
1063 state.instance_data_array[r_index].src_rect[2] = src_rect.size.width;
1064 state.instance_data_array[r_index].src_rect[3] = src_rect.size.height;
1065
1066 state.instance_data_array[r_index].dst_rect[0] = dst_rect.position.x;
1067 state.instance_data_array[r_index].dst_rect[1] = dst_rect.position.y;
1068 state.instance_data_array[r_index].dst_rect[2] = dst_rect.size.width;
1069 state.instance_data_array[r_index].dst_rect[3] = dst_rect.size.height;
1070
1071 state.instance_data_array[r_index].flags |= int(np->axis_x) << INSTANCE_FLAGS_NINEPATCH_H_MODE_SHIFT;
1072 state.instance_data_array[r_index].flags |= int(np->axis_y) << INSTANCE_FLAGS_NINEPATCH_V_MODE_SHIFT;
1073
1074 if (np->draw_center) {
1075 state.instance_data_array[r_index].flags |= INSTANCE_FLAGS_NINEPACH_DRAW_CENTER;
1076 }
1077
1078 state.instance_data_array[r_index].ninepatch_margins[0] = np->margin[SIDE_LEFT];
1079 state.instance_data_array[r_index].ninepatch_margins[1] = np->margin[SIDE_TOP];
1080 state.instance_data_array[r_index].ninepatch_margins[2] = np->margin[SIDE_RIGHT];
1081 state.instance_data_array[r_index].ninepatch_margins[3] = np->margin[SIDE_BOTTOM];
1082
1083 _add_to_batch(r_index, r_batch_broken);
1084
1085 // Restore if overridden.
1086 state.instance_data_array[r_index].color_texture_pixel_size[0] = texpixel_size.x;
1087 state.instance_data_array[r_index].color_texture_pixel_size[1] = texpixel_size.y;
1088 } break;
1089
1090 case Item::Command::TYPE_POLYGON: {
1091 const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c);
1092
1093 // Polygon's can't be batched, so always create a new batch
1094 _new_batch(r_batch_broken);
1095
1096 state.canvas_instance_batches[state.current_batch_index].tex = polygon->texture;
1097 state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_POLYGON;
1098 state.canvas_instance_batches[state.current_batch_index].command = c;
1099 state.canvas_instance_batches[state.current_batch_index].specialization &= specialization_command_mask;
1100 state.canvas_instance_batches[state.current_batch_index].specialization |= CanvasShaderGLES3::USE_ATTRIBUTES;
1101 state.canvas_instance_batches[state.current_batch_index].flags = 0;
1102
1103 _prepare_canvas_texture(polygon->texture, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
1104
1105 state.instance_data_array[r_index].modulation[0] = base_color.r;
1106 state.instance_data_array[r_index].modulation[1] = base_color.g;
1107 state.instance_data_array[r_index].modulation[2] = base_color.b;
1108 state.instance_data_array[r_index].modulation[3] = base_color.a;
1109
1110 for (int j = 0; j < 4; j++) {
1111 state.instance_data_array[r_index].src_rect[j] = 0;
1112 state.instance_data_array[r_index].dst_rect[j] = 0;
1113 state.instance_data_array[r_index].ninepatch_margins[j] = 0;
1114 }
1115
1116 _add_to_batch(r_index, r_batch_broken);
1117 } break;
1118
1119 case Item::Command::TYPE_PRIMITIVE: {
1120 const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c);
1121
1122 if (primitive->point_count != state.canvas_instance_batches[state.current_batch_index].primitive_points || state.canvas_instance_batches[state.current_batch_index].command_type != Item::Command::TYPE_PRIMITIVE || primitive->texture != state.canvas_instance_batches[state.current_batch_index].tex) {
1123 _new_batch(r_batch_broken);
1124 state.canvas_instance_batches[state.current_batch_index].tex = primitive->texture;
1125 state.canvas_instance_batches[state.current_batch_index].primitive_points = primitive->point_count;
1126 state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_PRIMITIVE;
1127 state.canvas_instance_batches[state.current_batch_index].command = c;
1128 state.canvas_instance_batches[state.current_batch_index].specialization &= specialization_command_mask;
1129 state.canvas_instance_batches[state.current_batch_index].specialization |= CanvasShaderGLES3::USE_PRIMITIVE;
1130 state.canvas_instance_batches[state.current_batch_index].flags = 0;
1131 }
1132
1133 _prepare_canvas_texture(state.canvas_instance_batches[state.current_batch_index].tex, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
1134
1135 for (uint32_t j = 0; j < MIN(3u, primitive->point_count); j++) {
1136 state.instance_data_array[r_index].points[j * 2 + 0] = primitive->points[j].x;
1137 state.instance_data_array[r_index].points[j * 2 + 1] = primitive->points[j].y;
1138 state.instance_data_array[r_index].uvs[j * 2 + 0] = primitive->uvs[j].x;
1139 state.instance_data_array[r_index].uvs[j * 2 + 1] = primitive->uvs[j].y;
1140 Color col = primitive->colors[j] * base_color;
1141 state.instance_data_array[r_index].colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
1142 state.instance_data_array[r_index].colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
1143 }
1144
1145 _add_to_batch(r_index, r_batch_broken);
1146
1147 if (primitive->point_count == 4) {
1148 // Reset base data.
1149 _update_transform_2d_to_mat2x3(base_transform * draw_transform, state.instance_data_array[r_index].world);
1150 _prepare_canvas_texture(state.canvas_instance_batches[state.current_batch_index].tex, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
1151 state.instance_data_array[r_index].lights[0] = lights[0];
1152 state.instance_data_array[r_index].lights[1] = lights[1];
1153 state.instance_data_array[r_index].lights[2] = lights[2];
1154 state.instance_data_array[r_index].lights[3] = lights[3];
1155 state.instance_data_array[r_index].flags = base_flags;
1156 state.instance_data_array[r_index].instance_uniforms_ofs = p_item->instance_allocated_shader_uniforms_offset;
1157
1158 for (uint32_t j = 0; j < 3; j++) {
1159 int offset = j == 0 ? 0 : 1;
1160 // Second triangle in the quad. Uses vertices 0, 2, 3.
1161 state.instance_data_array[r_index].points[j * 2 + 0] = primitive->points[j + offset].x;
1162 state.instance_data_array[r_index].points[j * 2 + 1] = primitive->points[j + offset].y;
1163 state.instance_data_array[r_index].uvs[j * 2 + 0] = primitive->uvs[j + offset].x;
1164 state.instance_data_array[r_index].uvs[j * 2 + 1] = primitive->uvs[j + offset].y;
1165 Color col = primitive->colors[j + offset] * base_color;
1166 state.instance_data_array[r_index].colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
1167 state.instance_data_array[r_index].colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
1168 }
1169
1170 _add_to_batch(r_index, r_batch_broken);
1171 }
1172 } break;
1173
1174 case Item::Command::TYPE_MESH:
1175 case Item::Command::TYPE_MULTIMESH:
1176 case Item::Command::TYPE_PARTICLES: {
1177 // Meshes can't be batched, so always create a new batch.
1178 _new_batch(r_batch_broken);
1179
1180 Color modulate(1, 1, 1, 1);
1181 state.canvas_instance_batches[state.current_batch_index].specialization &= specialization_command_mask;
1182 state.canvas_instance_batches[state.current_batch_index].specialization |= CanvasShaderGLES3::USE_ATTRIBUTES;
1183 state.canvas_instance_batches[state.current_batch_index].flags = 0;
1184 if (c->type == Item::Command::TYPE_MESH) {
1185 const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(c);
1186 state.canvas_instance_batches[state.current_batch_index].tex = m->texture;
1187 _update_transform_2d_to_mat2x3(base_transform * draw_transform * m->transform, state.instance_data_array[r_index].world);
1188 modulate = m->modulate;
1189
1190 } else if (c->type == Item::Command::TYPE_MULTIMESH) {
1191 const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(c);
1192 state.canvas_instance_batches[state.current_batch_index].tex = mm->texture;
1193 state.canvas_instance_batches[state.current_batch_index].specialization |= CanvasShaderGLES3::USE_INSTANCING;
1194
1195 if (GLES3::MeshStorage::get_singleton()->multimesh_uses_colors(mm->multimesh)) {
1196 state.canvas_instance_batches[state.current_batch_index].flags |= BATCH_FLAGS_INSTANCING_HAS_COLORS;
1197 }
1198 if (GLES3::MeshStorage::get_singleton()->multimesh_uses_custom_data(mm->multimesh)) {
1199 state.canvas_instance_batches[state.current_batch_index].flags |= BATCH_FLAGS_INSTANCING_HAS_CUSTOM_DATA;
1200 }
1201 } else if (c->type == Item::Command::TYPE_PARTICLES) {
1202 GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
1203 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
1204
1205 const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(c);
1206 RID particles = pt->particles;
1207 state.canvas_instance_batches[state.current_batch_index].tex = pt->texture;
1208 state.canvas_instance_batches[state.current_batch_index].specialization |= CanvasShaderGLES3::USE_INSTANCING;
1209 state.canvas_instance_batches[state.current_batch_index].flags |= BATCH_FLAGS_INSTANCING_HAS_COLORS;
1210 state.canvas_instance_batches[state.current_batch_index].flags |= BATCH_FLAGS_INSTANCING_HAS_CUSTOM_DATA;
1211
1212 if (particles_storage->particles_has_collision(particles) && texture_storage->render_target_is_sdf_enabled(p_render_target)) {
1213 // Pass collision information.
1214 Transform2D xform = p_item->final_transform;
1215
1216 GLuint sdf_texture = texture_storage->render_target_get_sdf_texture(p_render_target);
1217
1218 Rect2 to_screen;
1219 {
1220 Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_render_target);
1221
1222 to_screen.size = Vector2(1.0 / sdf_rect.size.width, 1.0 / sdf_rect.size.height);
1223 to_screen.position = -sdf_rect.position * to_screen.size;
1224 }
1225
1226 particles_storage->particles_set_canvas_sdf_collision(pt->particles, true, xform, to_screen, sdf_texture);
1227 } else {
1228 particles_storage->particles_set_canvas_sdf_collision(pt->particles, false, Transform2D(), Rect2(), 0);
1229 }
1230 r_sdf_used |= particles_storage->particles_has_collision(particles);
1231 }
1232
1233 state.canvas_instance_batches[state.current_batch_index].command = c;
1234 state.canvas_instance_batches[state.current_batch_index].command_type = c->type;
1235
1236 _prepare_canvas_texture(state.canvas_instance_batches[state.current_batch_index].tex, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
1237
1238 state.instance_data_array[r_index].modulation[0] = base_color.r * modulate.r;
1239 state.instance_data_array[r_index].modulation[1] = base_color.g * modulate.g;
1240 state.instance_data_array[r_index].modulation[2] = base_color.b * modulate.b;
1241 state.instance_data_array[r_index].modulation[3] = base_color.a * modulate.a;
1242
1243 for (int j = 0; j < 4; j++) {
1244 state.instance_data_array[r_index].src_rect[j] = 0;
1245 state.instance_data_array[r_index].dst_rect[j] = 0;
1246 state.instance_data_array[r_index].ninepatch_margins[j] = 0;
1247 }
1248 _add_to_batch(r_index, r_batch_broken);
1249 } break;
1250
1251 case Item::Command::TYPE_TRANSFORM: {
1252 const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c);
1253 draw_transform = transform->xform;
1254 } break;
1255
1256 case Item::Command::TYPE_CLIP_IGNORE: {
1257 const Item::CommandClipIgnore *ci = static_cast<const Item::CommandClipIgnore *>(c);
1258 if (current_clip) {
1259 if (ci->ignore != reclip) {
1260 _new_batch(r_batch_broken);
1261 if (ci->ignore) {
1262 state.canvas_instance_batches[state.current_batch_index].clip = nullptr;
1263 reclip = true;
1264 } else {
1265 state.canvas_instance_batches[state.current_batch_index].clip = current_clip;
1266 reclip = false;
1267 }
1268 }
1269 }
1270 } break;
1271
1272 case Item::Command::TYPE_ANIMATION_SLICE: {
1273 const Item::CommandAnimationSlice *as = static_cast<const Item::CommandAnimationSlice *>(c);
1274 double current_time = RSG::rasterizer->get_total_time();
1275 double local_time = Math::fposmod(current_time - as->offset, as->animation_length);
1276 skipping = !(local_time >= as->slice_begin && local_time < as->slice_end);
1277
1278 RenderingServerDefault::redraw_request(); // animation visible means redraw request
1279 } break;
1280 }
1281
1282 c = c->next;
1283 r_batch_broken = false;
1284 }
1285
1286 if (current_clip && reclip) {
1287 //will make it re-enable clipping if needed afterwards
1288 current_clip = nullptr;
1289 }
1290 }
1291
1292 _FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primitive, uint32_t p_indices) {
1293 static const uint32_t divisor[RS::PRIMITIVE_MAX] = { 1, 2, 1, 3, 1 };
1294 static const uint32_t subtractor[RS::PRIMITIVE_MAX] = { 0, 0, 1, 0, 2 };
1295 return (p_indices - subtractor[p_primitive]) / divisor[p_primitive];
1296 }
1297
1298 void RasterizerCanvasGLES3::_render_batch(Light *p_lights, uint32_t p_index, RenderingMethod::RenderInfo *r_render_info) {
1299 ERR_FAIL_NULL(state.canvas_instance_batches[state.current_batch_index].command);
1300
1301 // Used by Polygon and Mesh.
1302 static const GLenum prim[5] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP };
1303
1304 _bind_canvas_texture(state.canvas_instance_batches[p_index].tex, state.canvas_instance_batches[p_index].filter, state.canvas_instance_batches[p_index].repeat);
1305
1306 switch (state.canvas_instance_batches[p_index].command_type) {
1307 case Item::Command::TYPE_RECT:
1308 case Item::Command::TYPE_NINEPATCH: {
1309 glBindVertexArray(data.indexed_quad_array);
1310 glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
1311 uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
1312 _enable_attributes(range_start, false);
1313
1314 glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr, state.canvas_instance_batches[p_index].instance_count);
1315 glBindVertexArray(0);
1316
1317 if (r_render_info) {
1318 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += state.canvas_instance_batches[p_index].instance_count;
1319 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += 2 * state.canvas_instance_batches[p_index].instance_count;
1320 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
1321 }
1322
1323 } break;
1324
1325 case Item::Command::TYPE_POLYGON: {
1326 const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(state.canvas_instance_batches[p_index].command);
1327
1328 PolygonBuffers *pb = polygon_buffers.polygons.getptr(polygon->polygon.polygon_id);
1329 ERR_FAIL_NULL(pb);
1330
1331 glBindVertexArray(pb->vertex_array);
1332 glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
1333
1334 uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
1335 _enable_attributes(range_start, false);
1336
1337 if (pb->color_disabled && pb->color != Color(1.0, 1.0, 1.0, 1.0)) {
1338 glVertexAttrib4f(RS::ARRAY_COLOR, pb->color.r, pb->color.g, pb->color.b, pb->color.a);
1339 }
1340
1341 if (pb->index_buffer != 0) {
1342 glDrawElementsInstanced(prim[polygon->primitive], pb->count, GL_UNSIGNED_INT, nullptr, 1);
1343 } else {
1344 glDrawArraysInstanced(prim[polygon->primitive], 0, pb->count, 1);
1345 }
1346 glBindVertexArray(0);
1347
1348 if (pb->color_disabled && pb->color != Color(1.0, 1.0, 1.0, 1.0)) {
1349 // Reset so this doesn't pollute other draw calls.
1350 glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0);
1351 }
1352
1353 if (r_render_info) {
1354 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME]++;
1355 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(polygon->primitive, pb->count);
1356 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
1357 }
1358 } break;
1359
1360 case Item::Command::TYPE_PRIMITIVE: {
1361 glBindVertexArray(data.canvas_quad_array);
1362 glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
1363 uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
1364 _enable_attributes(range_start, true);
1365
1366 const GLenum primitive[5] = { GL_POINTS, GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLES };
1367 int instance_count = state.canvas_instance_batches[p_index].instance_count;
1368 ERR_FAIL_COND(instance_count <= 0);
1369 if (instance_count >= 1) {
1370 glDrawArraysInstanced(primitive[state.canvas_instance_batches[p_index].primitive_points], 0, state.canvas_instance_batches[p_index].primitive_points, instance_count);
1371 }
1372 if (r_render_info) {
1373 const RenderingServer::PrimitiveType rs_primitive[5] = { RS::PRIMITIVE_POINTS, RS::PRIMITIVE_POINTS, RS::PRIMITIVE_LINES, RS::PRIMITIVE_TRIANGLES, RS::PRIMITIVE_TRIANGLES };
1374 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += instance_count;
1375 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(rs_primitive[state.canvas_instance_batches[p_index].primitive_points], state.canvas_instance_batches[p_index].primitive_points) * instance_count;
1376 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
1377 }
1378
1379 } break;
1380
1381 case Item::Command::TYPE_MESH:
1382 case Item::Command::TYPE_MULTIMESH:
1383 case Item::Command::TYPE_PARTICLES: {
1384 GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
1385 GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
1386 RID mesh;
1387 RID mesh_instance;
1388 uint32_t instance_count = 1;
1389 GLuint instance_buffer = 0;
1390 uint32_t instance_stride = 0;
1391 uint32_t instance_color_offset = 0;
1392 bool instance_uses_color = false;
1393 bool instance_uses_custom_data = false;
1394 bool use_instancing = false;
1395
1396 if (state.canvas_instance_batches[p_index].command_type == Item::Command::TYPE_MESH) {
1397 const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(state.canvas_instance_batches[p_index].command);
1398 mesh = m->mesh;
1399 mesh_instance = m->mesh_instance;
1400
1401 } else if (state.canvas_instance_batches[p_index].command_type == Item::Command::TYPE_MULTIMESH) {
1402 const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(state.canvas_instance_batches[p_index].command);
1403 RID multimesh = mm->multimesh;
1404 mesh = mesh_storage->multimesh_get_mesh(multimesh);
1405
1406 if (mesh_storage->multimesh_get_transform_format(multimesh) != RS::MULTIMESH_TRANSFORM_2D) {
1407 break;
1408 }
1409
1410 instance_count = mesh_storage->multimesh_get_instances_to_draw(multimesh);
1411
1412 if (instance_count == 0) {
1413 break;
1414 }
1415
1416 instance_buffer = mesh_storage->multimesh_get_gl_buffer(multimesh);
1417 instance_stride = mesh_storage->multimesh_get_stride(multimesh);
1418 instance_color_offset = mesh_storage->multimesh_get_color_offset(multimesh);
1419 instance_uses_color = mesh_storage->multimesh_uses_colors(multimesh);
1420 instance_uses_custom_data = mesh_storage->multimesh_uses_custom_data(multimesh);
1421 use_instancing = true;
1422
1423 } else if (state.canvas_instance_batches[p_index].command_type == Item::Command::TYPE_PARTICLES) {
1424 const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(state.canvas_instance_batches[p_index].command);
1425 RID particles = pt->particles;
1426 mesh = particles_storage->particles_get_draw_pass_mesh(particles, 0);
1427
1428 ERR_BREAK(particles_storage->particles_get_mode(particles) != RS::PARTICLES_MODE_2D);
1429 particles_storage->particles_request_process(particles);
1430
1431 if (particles_storage->particles_is_inactive(particles)) {
1432 break;
1433 }
1434
1435 RenderingServerDefault::redraw_request(); // Active particles means redraw request.
1436
1437 int dpc = particles_storage->particles_get_draw_passes(particles);
1438 if (dpc == 0) {
1439 break; // Nothing to draw.
1440 }
1441
1442 instance_count = particles_storage->particles_get_amount(particles);
1443 instance_buffer = particles_storage->particles_get_gl_buffer(particles);
1444 instance_stride = 12; // 8 bytes for instance transform and 4 bytes for packed color and custom.
1445 instance_color_offset = 8; // 8 bytes for instance transform.
1446 instance_uses_color = true;
1447 instance_uses_custom_data = true;
1448 use_instancing = true;
1449 }
1450
1451 ERR_FAIL_COND(mesh.is_null());
1452
1453 uint32_t surf_count = mesh_storage->mesh_get_surface_count(mesh);
1454
1455 for (uint32_t j = 0; j < surf_count; j++) {
1456 void *surface = mesh_storage->mesh_get_surface(mesh, j);
1457
1458 RS::PrimitiveType primitive = mesh_storage->mesh_surface_get_primitive(surface);
1459 ERR_CONTINUE(primitive < 0 || primitive >= RS::PRIMITIVE_MAX);
1460
1461 GLuint vertex_array_gl = 0;
1462 GLuint index_array_gl = 0;
1463
1464 uint64_t vertex_input_mask = state.canvas_instance_batches[p_index].vertex_input_mask;
1465
1466 if (mesh_instance.is_valid()) {
1467 mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(mesh_instance, j, vertex_input_mask, false, vertex_array_gl);
1468 } else {
1469 mesh_storage->mesh_surface_get_vertex_arrays_and_format(surface, vertex_input_mask, false, vertex_array_gl);
1470 }
1471
1472 index_array_gl = mesh_storage->mesh_surface_get_index_buffer(surface, 0);
1473 bool use_index_buffer = false;
1474 glBindVertexArray(vertex_array_gl);
1475 glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
1476
1477 uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
1478 _enable_attributes(range_start, false, instance_count);
1479
1480 if (index_array_gl != 0) {
1481 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_array_gl);
1482 use_index_buffer = true;
1483 }
1484
1485 if (use_instancing) {
1486 if (instance_buffer == 0) {
1487 break;
1488 }
1489 // Bind instance buffers.
1490 glBindBuffer(GL_ARRAY_BUFFER, instance_buffer);
1491 glEnableVertexAttribArray(1);
1492 glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, instance_stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(0));
1493 glVertexAttribDivisor(1, 1);
1494 glEnableVertexAttribArray(2);
1495 glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, instance_stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(4 * 4));
1496 glVertexAttribDivisor(2, 1);
1497
1498 if (instance_uses_color || instance_uses_custom_data) {
1499 glEnableVertexAttribArray(5);
1500 glVertexAttribIPointer(5, 4, GL_UNSIGNED_INT, instance_stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(instance_color_offset * sizeof(float)));
1501 glVertexAttribDivisor(5, 1);
1502 } else {
1503 // Set all default instance color and custom data values to 1.0 or 0.0 using a compressed format.
1504 uint16_t zero = Math::make_half_float(0.0f);
1505 uint16_t one = Math::make_half_float(1.0f);
1506 GLuint default_color = (uint32_t(one) << 16) | one;
1507 GLuint default_custom = (uint32_t(zero) << 16) | zero;
1508 glVertexAttribI4ui(5, default_color, default_color, default_custom, default_custom);
1509 }
1510 }
1511
1512 GLenum primitive_gl = prim[int(primitive)];
1513
1514 uint32_t vertex_count = mesh_storage->mesh_surface_get_vertices_drawn_count(surface);
1515
1516 if (use_index_buffer) {
1517 glDrawElementsInstanced(primitive_gl, vertex_count, mesh_storage->mesh_surface_get_index_type(surface), nullptr, instance_count);
1518 } else {
1519 glDrawArraysInstanced(primitive_gl, 0, vertex_count, instance_count);
1520 }
1521 glBindBuffer(GL_ARRAY_BUFFER, 0);
1522 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1523 if (use_instancing) {
1524 glDisableVertexAttribArray(5);
1525 glDisableVertexAttribArray(8);
1526 glDisableVertexAttribArray(9);
1527 glDisableVertexAttribArray(10);
1528 }
1529 if (r_render_info) {
1530 // Meshes, Particles, and MultiMesh are always just one object with one draw call.
1531 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME]++;
1532 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(primitive, vertex_count) * instance_count;
1533 r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
1534 }
1535 }
1536
1537 } break;
1538 case Item::Command::TYPE_TRANSFORM:
1539 case Item::Command::TYPE_CLIP_IGNORE:
1540 case Item::Command::TYPE_ANIMATION_SLICE: {
1541 // Can ignore these as they only impact batch creation.
1542 } break;
1543 }
1544 }
1545
1546 void RasterizerCanvasGLES3::_add_to_batch(uint32_t &r_index, bool &r_batch_broken) {
1547 state.canvas_instance_batches[state.current_batch_index].instance_count++;
1548 r_index++;
1549 if (r_index + state.last_item_index >= data.max_instances_per_buffer) {
1550 // Copy over all data needed for rendering right away
1551 // then go back to recording item commands.
1552 glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.current_instance_buffer_index]);
1553 #ifdef WEB_ENABLED
1554 glBufferSubData(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), sizeof(InstanceData) * r_index, state.instance_data_array);
1555 #else
1556 // On Desktop and mobile we map the memory without synchronizing for maximum speed.
1557 void *buffer = glMapBufferRange(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), r_index * sizeof(InstanceData), GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
1558 memcpy(buffer, state.instance_data_array, r_index * sizeof(InstanceData));
1559 glUnmapBuffer(GL_ARRAY_BUFFER);
1560 #endif
1561 _allocate_instance_buffer();
1562 r_index = 0;
1563 state.last_item_index = 0;
1564 r_batch_broken = false; // Force a new batch to be created
1565 _new_batch(r_batch_broken);
1566 state.canvas_instance_batches[state.current_batch_index].start = 0;
1567 }
1568 }
1569
1570 void RasterizerCanvasGLES3::_new_batch(bool &r_batch_broken) {
1571 if (state.canvas_instance_batches.is_empty()) {
1572 Batch new_batch;
1573 new_batch.instance_buffer_index = state.current_instance_buffer_index;
1574 state.canvas_instance_batches.push_back(new_batch);
1575 return;
1576 }
1577
1578 if (r_batch_broken || state.canvas_instance_batches[state.current_batch_index].instance_count == 0) {
1579 return;
1580 }
1581
1582 r_batch_broken = true;
1583
1584 // Copy the properties of the current batch, we will manually update the things that changed.
1585 Batch new_batch = state.canvas_instance_batches[state.current_batch_index];
1586 new_batch.instance_count = 0;
1587 new_batch.start = state.canvas_instance_batches[state.current_batch_index].start + state.canvas_instance_batches[state.current_batch_index].instance_count;
1588 new_batch.instance_buffer_index = state.current_instance_buffer_index;
1589 state.current_batch_index++;
1590 state.canvas_instance_batches.push_back(new_batch);
1591 }
1592
1593 void RasterizerCanvasGLES3::_enable_attributes(uint32_t p_start, bool p_primitive, uint32_t p_rate) {
1594 uint32_t split = p_primitive ? 13 : 14;
1595 for (uint32_t i = 8; i < split; i++) {
1596 glEnableVertexAttribArray(i);
1597 glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, sizeof(InstanceData), CAST_INT_TO_UCHAR_PTR(p_start + (i - 8) * 4 * sizeof(float)));
1598 glVertexAttribDivisor(i, p_rate);
1599 }
1600 for (uint32_t i = split; i <= 15; i++) {
1601 glEnableVertexAttribArray(i);
1602 glVertexAttribIPointer(i, 4, GL_UNSIGNED_INT, sizeof(InstanceData), CAST_INT_TO_UCHAR_PTR(p_start + (i - 8) * 4 * sizeof(float)));
1603 glVertexAttribDivisor(i, p_rate);
1604 }
1605 }
1606 RID RasterizerCanvasGLES3::light_create() {
1607 CanvasLight canvas_light;
1608 return canvas_light_owner.make_rid(canvas_light);
1609 }
1610
1611 void RasterizerCanvasGLES3::light_set_texture(RID p_rid, RID p_texture) {
1612 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
1613
1614 CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
1615 ERR_FAIL_NULL(cl);
1616 if (cl->texture == p_texture) {
1617 return;
1618 }
1619
1620 ERR_FAIL_COND(p_texture.is_valid() && !texture_storage->owns_texture(p_texture));
1621
1622 if (cl->texture.is_valid()) {
1623 texture_storage->texture_remove_from_texture_atlas(cl->texture);
1624 }
1625 cl->texture = p_texture;
1626
1627 if (cl->texture.is_valid()) {
1628 texture_storage->texture_add_to_texture_atlas(cl->texture);
1629 }
1630 }
1631
1632 void RasterizerCanvasGLES3::light_set_use_shadow(RID p_rid, bool p_enable) {
1633 CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
1634 ERR_FAIL_NULL(cl);
1635
1636 cl->shadow.enabled = p_enable;
1637 }
1638
1639 void RasterizerCanvasGLES3::light_update_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, const Rect2 &p_light_rect) {
1640 GLES3::Config *config = GLES3::Config::get_singleton();
1641
1642 CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
1643 ERR_FAIL_COND(!cl->shadow.enabled);
1644
1645 _update_shadow_atlas();
1646
1647 cl->shadow.z_far = p_far;
1648 cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(data.max_lights_per_render * 2);
1649
1650 glBindFramebuffer(GL_FRAMEBUFFER, state.shadow_fb);
1651 glViewport(0, p_shadow_index * 2, state.shadow_texture_size, 2);
1652
1653 glDepthMask(GL_TRUE);
1654 glEnable(GL_DEPTH_TEST);
1655 glDepthFunc(GL_LESS);
1656 glDisable(GL_BLEND);
1657
1658 glEnable(GL_SCISSOR_TEST);
1659 glScissor(0, p_shadow_index * 2, state.shadow_texture_size, 2);
1660 glClearColor(p_far, p_far, p_far, 1.0);
1661 RasterizerGLES3::clear_depth(1.0);
1662
1663 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1664
1665 glCullFace(GL_BACK);
1666 glDisable(GL_CULL_FACE);
1667 RS::CanvasOccluderPolygonCullMode cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
1668
1669 CanvasOcclusionShaderGLES3::ShaderVariant variant = config->float_texture_supported ? CanvasOcclusionShaderGLES3::MODE_SHADOW : CanvasOcclusionShaderGLES3::MODE_SHADOW_RGBA;
1670 bool success = shadow_render.shader.version_bind_shader(shadow_render.shader_version, variant);
1671 if (!success) {
1672 return;
1673 }
1674
1675 Projection projection;
1676 {
1677 real_t fov = 90;
1678 real_t nearp = p_near;
1679 real_t farp = p_far;
1680 real_t aspect = 1.0;
1681
1682 real_t ymax = nearp * Math::tan(Math::deg_to_rad(fov * 0.5));
1683 real_t ymin = -ymax;
1684 real_t xmin = ymin * aspect;
1685 real_t xmax = ymax * aspect;
1686
1687 projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp);
1688 }
1689
1690 // Precomputed:
1691 // Vector3 cam_target = Basis::from_euler(Vector3(0, 0, Math::TAU * ((i + 3) / 4.0))).xform(Vector3(0, 1, 0));
1692 // projection = projection * Projection(Transform3D().looking_at(cam_targets[i], Vector3(0, 0, -1)).affine_inverse());
1693 const Projection projections[4] = {
1694 projection * Projection(Vector4(0, 0, -1, 0), Vector4(1, 0, 0, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1)),
1695
1696 projection * Projection(Vector4(-1, 0, 0, 0), Vector4(0, 0, -1, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1)),
1697
1698 projection * Projection(Vector4(0, 0, 1, 0), Vector4(-1, 0, 0, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1)),
1699
1700 projection * Projection(Vector4(1, 0, 0, 0), Vector4(0, 0, 1, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1))
1701
1702 };
1703
1704 for (int i = 0; i < 4; i++) {
1705 glViewport((state.shadow_texture_size / 4) * i, p_shadow_index * 2, (state.shadow_texture_size / 4), 2);
1706
1707 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::PROJECTION, projections[i], shadow_render.shader_version, variant);
1708
1709 static const Vector2 directions[4] = { Vector2(1, 0), Vector2(0, 1), Vector2(-1, 0), Vector2(0, -1) };
1710 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::DIRECTION, directions[i].x, directions[i].y, shadow_render.shader_version, variant);
1711 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::Z_FAR, p_far, shadow_render.shader_version, variant);
1712
1713 LightOccluderInstance *instance = p_occluders;
1714
1715 while (instance) {
1716 OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);
1717
1718 if (!co || co->vertex_array == 0 || !(p_light_mask & instance->light_mask)) {
1719 instance = instance->next;
1720 continue;
1721 }
1722
1723 Transform2D modelview = p_light_xform * instance->xform_cache;
1724 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW1, modelview.columns[0][0], modelview.columns[1][0], 0, modelview.columns[2][0], shadow_render.shader_version, variant);
1725 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW2, modelview.columns[0][1], modelview.columns[1][1], 0, modelview.columns[2][1], shadow_render.shader_version, variant);
1726
1727 if (co->cull_mode != cull_mode) {
1728 if (co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
1729 glDisable(GL_CULL_FACE);
1730 } else {
1731 if (cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
1732 // Last time was disabled, so enable and set proper face.
1733 glEnable(GL_CULL_FACE);
1734 }
1735 glCullFace(co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE ? GL_FRONT : GL_BACK);
1736 }
1737 cull_mode = co->cull_mode;
1738 }
1739
1740 glBindVertexArray(co->vertex_array);
1741 glDrawElements(GL_TRIANGLES, 3 * co->line_point_count, GL_UNSIGNED_SHORT, nullptr);
1742
1743 instance = instance->next;
1744 }
1745 }
1746
1747 glBindVertexArray(0);
1748 glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
1749 glDepthMask(GL_FALSE);
1750 glDisable(GL_DEPTH_TEST);
1751 glDisable(GL_SCISSOR_TEST);
1752 }
1753
1754 void RasterizerCanvasGLES3::light_update_directional_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_cull_distance, const Rect2 &p_clip_rect, LightOccluderInstance *p_occluders) {
1755 GLES3::Config *config = GLES3::Config::get_singleton();
1756
1757 CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
1758 ERR_FAIL_COND(!cl->shadow.enabled);
1759
1760 _update_shadow_atlas();
1761
1762 Vector2 light_dir = p_light_xform.columns[1].normalized();
1763
1764 Vector2 center = p_clip_rect.get_center();
1765
1766 float to_edge_distance = Math::abs(light_dir.dot(p_clip_rect.get_support(-light_dir)) - light_dir.dot(center));
1767
1768 Vector2 from_pos = center - light_dir * (to_edge_distance + p_cull_distance);
1769 float distance = to_edge_distance * 2.0 + p_cull_distance;
1770 float half_size = p_clip_rect.size.length() * 0.5; //shadow length, must keep this no matter the angle
1771
1772 cl->shadow.z_far = distance;
1773 cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(data.max_lights_per_render * 2);
1774
1775 Transform2D to_light_xform;
1776
1777 to_light_xform[2] = from_pos;
1778 to_light_xform[1] = light_dir;
1779 to_light_xform[0] = -light_dir.orthogonal();
1780
1781 to_light_xform.invert();
1782
1783 glBindFramebuffer(GL_FRAMEBUFFER, state.shadow_fb);
1784 glViewport(0, p_shadow_index * 2, state.shadow_texture_size, 2);
1785
1786 glDepthMask(GL_TRUE);
1787 glEnable(GL_DEPTH_TEST);
1788 glDepthFunc(GL_LESS);
1789 glDisable(GL_BLEND);
1790
1791 glEnable(GL_SCISSOR_TEST);
1792 glScissor(0, p_shadow_index * 2, state.shadow_texture_size, 2);
1793 glClearColor(1.0, 1.0, 1.0, 1.0);
1794 RasterizerGLES3::clear_depth(1.0);
1795
1796 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1797
1798 glCullFace(GL_BACK);
1799 glDisable(GL_CULL_FACE);
1800 RS::CanvasOccluderPolygonCullMode cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
1801
1802 CanvasOcclusionShaderGLES3::ShaderVariant variant = config->float_texture_supported ? CanvasOcclusionShaderGLES3::MODE_SHADOW : CanvasOcclusionShaderGLES3::MODE_SHADOW_RGBA;
1803 bool success = shadow_render.shader.version_bind_shader(shadow_render.shader_version, variant);
1804 if (!success) {
1805 return;
1806 }
1807
1808 Projection projection;
1809 projection.set_orthogonal(-half_size, half_size, -0.5, 0.5, 0.0, distance);
1810 projection = projection * Projection(Transform3D().looking_at(Vector3(0, 1, 0), Vector3(0, 0, -1)).affine_inverse());
1811
1812 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::PROJECTION, projection, shadow_render.shader_version, variant);
1813 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::DIRECTION, 0.0, 1.0, shadow_render.shader_version, variant);
1814 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::Z_FAR, distance, shadow_render.shader_version, variant);
1815
1816 LightOccluderInstance *instance = p_occluders;
1817
1818 while (instance) {
1819 OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);
1820
1821 if (!co || co->vertex_array == 0 || !(p_light_mask & instance->light_mask)) {
1822 instance = instance->next;
1823 continue;
1824 }
1825
1826 Transform2D modelview = to_light_xform * instance->xform_cache;
1827 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW1, modelview.columns[0][0], modelview.columns[1][0], 0, modelview.columns[2][0], shadow_render.shader_version, variant);
1828 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW2, modelview.columns[0][1], modelview.columns[1][1], 0, modelview.columns[2][1], shadow_render.shader_version, variant);
1829
1830 if (co->cull_mode != cull_mode) {
1831 if (co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
1832 glDisable(GL_CULL_FACE);
1833 } else {
1834 if (cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
1835 // Last time was disabled, so enable and set proper face.
1836 glEnable(GL_CULL_FACE);
1837 }
1838 glCullFace(co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE ? GL_FRONT : GL_BACK);
1839 }
1840 cull_mode = co->cull_mode;
1841 }
1842
1843 glBindVertexArray(co->vertex_array);
1844 glDrawElements(GL_TRIANGLES, 3 * co->line_point_count, GL_UNSIGNED_SHORT, nullptr);
1845
1846 instance = instance->next;
1847 }
1848
1849 Transform2D to_shadow;
1850 to_shadow.columns[0].x = 1.0 / -(half_size * 2.0);
1851 to_shadow.columns[2].x = 0.5;
1852
1853 cl->shadow.directional_xform = to_shadow * to_light_xform;
1854
1855 glBindVertexArray(0);
1856 glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
1857 glDepthMask(GL_FALSE);
1858 glDisable(GL_DEPTH_TEST);
1859 glDisable(GL_SCISSOR_TEST);
1860 glDisable(GL_CULL_FACE);
1861 }
1862
1863 void RasterizerCanvasGLES3::_update_shadow_atlas() {
1864 GLES3::Config *config = GLES3::Config::get_singleton();
1865
1866 if (state.shadow_fb == 0) {
1867 glActiveTexture(GL_TEXTURE0);
1868
1869 glGenFramebuffers(1, &state.shadow_fb);
1870 glBindFramebuffer(GL_FRAMEBUFFER, state.shadow_fb);
1871
1872 glGenRenderbuffers(1, &state.shadow_depth_buffer);
1873 glBindRenderbuffer(GL_RENDERBUFFER, state.shadow_depth_buffer);
1874 glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, state.shadow_texture_size, data.max_lights_per_render * 2);
1875 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, state.shadow_depth_buffer);
1876
1877 glGenTextures(1, &state.shadow_texture);
1878 glBindTexture(GL_TEXTURE_2D, state.shadow_texture);
1879 if (config->float_texture_supported) {
1880 glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, state.shadow_texture_size, data.max_lights_per_render * 2, 0, GL_RED, GL_FLOAT, nullptr);
1881 } else {
1882 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, state.shadow_texture_size, data.max_lights_per_render * 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
1883 }
1884
1885 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1886 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1887 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1888 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
1889 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
1890 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
1891 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, state.shadow_texture, 0);
1892
1893 GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
1894 if (status != GL_FRAMEBUFFER_COMPLETE) {
1895 glDeleteFramebuffers(1, &state.shadow_fb);
1896 glDeleteTextures(1, &state.shadow_texture);
1897 glDeleteRenderbuffers(1, &state.shadow_depth_buffer);
1898 state.shadow_fb = 0;
1899 state.shadow_texture = 0;
1900 state.shadow_depth_buffer = 0;
1901 WARN_PRINT("Could not create CanvasItem shadow atlas, status: " + GLES3::TextureStorage::get_singleton()->get_framebuffer_error(status));
1902 }
1903 GLES3::Utilities::get_singleton()->texture_allocated_data(state.shadow_texture, state.shadow_texture_size * data.max_lights_per_render * 2 * 4, "2D shadow atlas texture");
1904 glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
1905 }
1906 }
1907
1908 void RasterizerCanvasGLES3::render_sdf(RID p_render_target, LightOccluderInstance *p_occluders) {
1909 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
1910
1911 GLuint fb = texture_storage->render_target_get_sdf_framebuffer(p_render_target);
1912 Rect2i rect = texture_storage->render_target_get_sdf_rect(p_render_target);
1913
1914 Transform2D to_sdf;
1915 to_sdf.columns[0] *= rect.size.width;
1916 to_sdf.columns[1] *= rect.size.height;
1917 to_sdf.columns[2] = rect.position;
1918
1919 Transform2D to_clip;
1920 to_clip.columns[0] *= 2.0;
1921 to_clip.columns[1] *= 2.0;
1922 to_clip.columns[2] = -Vector2(1.0, 1.0);
1923
1924 to_clip = to_clip * to_sdf.affine_inverse();
1925
1926 glBindFramebuffer(GL_FRAMEBUFFER, fb);
1927 glViewport(0, 0, rect.size.width, rect.size.height);
1928
1929 glDepthMask(GL_FALSE);
1930 glDisable(GL_DEPTH_TEST);
1931 glDisable(GL_BLEND);
1932 glDisable(GL_CULL_FACE);
1933 glDisable(GL_SCISSOR_TEST);
1934
1935 glClearColor(0.0, 0.0, 0.0, 0.0);
1936 glClear(GL_COLOR_BUFFER_BIT);
1937
1938 CanvasOcclusionShaderGLES3::ShaderVariant variant = CanvasOcclusionShaderGLES3::MODE_SDF;
1939 bool success = shadow_render.shader.version_bind_shader(shadow_render.shader_version, variant);
1940 if (!success) {
1941 return;
1942 }
1943
1944 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::PROJECTION, Projection(), shadow_render.shader_version, variant);
1945 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::DIRECTION, 0.0, 0.0, shadow_render.shader_version, variant);
1946 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::Z_FAR, 0.0, shadow_render.shader_version, variant);
1947
1948 LightOccluderInstance *instance = p_occluders;
1949
1950 while (instance) {
1951 OccluderPolygon *oc = occluder_polygon_owner.get_or_null(instance->occluder);
1952
1953 if (!oc || oc->sdf_vertex_array == 0 || !instance->sdf_collision) {
1954 instance = instance->next;
1955 continue;
1956 }
1957
1958 Transform2D modelview = to_clip * instance->xform_cache;
1959 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW1, modelview.columns[0][0], modelview.columns[1][0], 0, modelview.columns[2][0], shadow_render.shader_version, variant);
1960 shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW2, modelview.columns[0][1], modelview.columns[1][1], 0, modelview.columns[2][1], shadow_render.shader_version, variant);
1961
1962 glBindVertexArray(oc->sdf_vertex_array);
1963 glDrawElements(oc->sdf_is_lines ? GL_LINES : GL_TRIANGLES, oc->sdf_index_count, GL_UNSIGNED_INT, nullptr);
1964
1965 instance = instance->next;
1966 }
1967
1968 texture_storage->render_target_sdf_process(p_render_target); //done rendering, process it
1969 glBindVertexArray(0);
1970 glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
1971 }
1972
1973 RID RasterizerCanvasGLES3::occluder_polygon_create() {
1974 OccluderPolygon occluder;
1975
1976 return occluder_polygon_owner.make_rid(occluder);
1977 }
1978
1979 void RasterizerCanvasGLES3::occluder_polygon_set_shape(RID p_occluder, const Vector<Vector2> &p_points, bool p_closed) {
1980 OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);
1981 ERR_FAIL_NULL(oc);
1982
1983 Vector<Vector2> lines;
1984
1985 if (p_points.size()) {
1986 int lc = p_points.size() * 2;
1987
1988 lines.resize(lc - (p_closed ? 0 : 2));
1989 {
1990 Vector2 *w = lines.ptrw();
1991 const Vector2 *r = p_points.ptr();
1992
1993 int max = lc / 2;
1994 if (!p_closed) {
1995 max--;
1996 }
1997 for (int i = 0; i < max; i++) {
1998 Vector2 a = r[i];
1999 Vector2 b = r[(i + 1) % (lc / 2)];
2000 w[i * 2 + 0] = a;
2001 w[i * 2 + 1] = b;
2002 }
2003 }
2004 }
2005
2006 if (oc->line_point_count != lines.size() && oc->vertex_array != 0) {
2007 glDeleteVertexArrays(1, &oc->vertex_array);
2008 GLES3::Utilities::get_singleton()->buffer_free_data(oc->vertex_buffer);
2009 GLES3::Utilities::get_singleton()->buffer_free_data(oc->index_buffer);
2010
2011 oc->vertex_array = 0;
2012 oc->vertex_buffer = 0;
2013 oc->index_buffer = 0;
2014 }
2015
2016 if (lines.size()) {
2017 Vector<uint8_t> geometry;
2018 Vector<uint8_t> indices;
2019 int lc = lines.size();
2020
2021 geometry.resize(lc * 6 * sizeof(float));
2022 indices.resize(lc * 3 * sizeof(uint16_t));
2023
2024 {
2025 uint8_t *vw = geometry.ptrw();
2026 float *vwptr = reinterpret_cast<float *>(vw);
2027 uint8_t *iw = indices.ptrw();
2028 uint16_t *iwptr = (uint16_t *)iw;
2029
2030 const Vector2 *lr = lines.ptr();
2031
2032 const int POLY_HEIGHT = 16384;
2033
2034 for (int i = 0; i < lc / 2; i++) {
2035 vwptr[i * 12 + 0] = lr[i * 2 + 0].x;
2036 vwptr[i * 12 + 1] = lr[i * 2 + 0].y;
2037 vwptr[i * 12 + 2] = POLY_HEIGHT;
2038
2039 vwptr[i * 12 + 3] = lr[i * 2 + 1].x;
2040 vwptr[i * 12 + 4] = lr[i * 2 + 1].y;
2041 vwptr[i * 12 + 5] = POLY_HEIGHT;
2042
2043 vwptr[i * 12 + 6] = lr[i * 2 + 1].x;
2044 vwptr[i * 12 + 7] = lr[i * 2 + 1].y;
2045 vwptr[i * 12 + 8] = -POLY_HEIGHT;
2046
2047 vwptr[i * 12 + 9] = lr[i * 2 + 0].x;
2048 vwptr[i * 12 + 10] = lr[i * 2 + 0].y;
2049 vwptr[i * 12 + 11] = -POLY_HEIGHT;
2050
2051 iwptr[i * 6 + 0] = i * 4 + 0;
2052 iwptr[i * 6 + 1] = i * 4 + 1;
2053 iwptr[i * 6 + 2] = i * 4 + 2;
2054
2055 iwptr[i * 6 + 3] = i * 4 + 2;
2056 iwptr[i * 6 + 4] = i * 4 + 3;
2057 iwptr[i * 6 + 5] = i * 4 + 0;
2058 }
2059 }
2060
2061 if (oc->vertex_array == 0) {
2062 oc->line_point_count = lc;
2063 glGenVertexArrays(1, &oc->vertex_array);
2064 glBindVertexArray(oc->vertex_array);
2065 glGenBuffers(1, &oc->vertex_buffer);
2066 glBindBuffer(GL_ARRAY_BUFFER, oc->vertex_buffer);
2067
2068 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, oc->vertex_buffer, lc * 6 * sizeof(float), geometry.ptr(), GL_STATIC_DRAW, "Occluder polygon vertex buffer");
2069
2070 glEnableVertexAttribArray(RS::ARRAY_VERTEX);
2071 glVertexAttribPointer(RS::ARRAY_VERTEX, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr);
2072
2073 glGenBuffers(1, &oc->index_buffer);
2074 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->index_buffer);
2075 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ELEMENT_ARRAY_BUFFER, oc->index_buffer, 3 * lc * sizeof(uint16_t), indices.ptr(), GL_STATIC_DRAW, "Occluder polygon index buffer");
2076
2077 glBindVertexArray(0);
2078 } else {
2079 glBindBuffer(GL_ARRAY_BUFFER, oc->vertex_buffer);
2080 glBufferData(GL_ARRAY_BUFFER, lc * 6 * sizeof(float), geometry.ptr(), GL_STATIC_DRAW);
2081 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->index_buffer);
2082 glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * lc * sizeof(uint16_t), indices.ptr(), GL_STATIC_DRAW);
2083 glBindBuffer(GL_ARRAY_BUFFER, 0);
2084 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2085 }
2086 }
2087
2088 // sdf
2089
2090 Vector<int> sdf_indices;
2091
2092 if (p_points.size()) {
2093 if (p_closed) {
2094 sdf_indices = Geometry2D::triangulate_polygon(p_points);
2095 oc->sdf_is_lines = false;
2096 } else {
2097 int max = p_points.size();
2098 sdf_indices.resize(max * 2);
2099
2100 int *iw = sdf_indices.ptrw();
2101 for (int i = 0; i < max; i++) {
2102 iw[i * 2 + 0] = i;
2103 iw[i * 2 + 1] = (i + 1) % max;
2104 }
2105 oc->sdf_is_lines = true;
2106 }
2107 }
2108
2109 if (oc->sdf_index_count != sdf_indices.size() && oc->sdf_point_count != p_points.size() && oc->sdf_vertex_array != 0) {
2110 glDeleteVertexArrays(1, &oc->sdf_vertex_array);
2111 GLES3::Utilities::get_singleton()->buffer_free_data(oc->sdf_vertex_buffer);
2112 GLES3::Utilities::get_singleton()->buffer_free_data(oc->sdf_index_buffer);
2113
2114 oc->sdf_vertex_array = 0;
2115 oc->sdf_vertex_buffer = 0;
2116 oc->sdf_index_buffer = 0;
2117
2118 oc->sdf_index_count = sdf_indices.size();
2119 oc->sdf_point_count = p_points.size();
2120 }
2121
2122 if (sdf_indices.size()) {
2123 if (oc->sdf_vertex_array == 0) {
2124 oc->sdf_index_count = sdf_indices.size();
2125 oc->sdf_point_count = p_points.size();
2126 glGenVertexArrays(1, &oc->sdf_vertex_array);
2127 glBindVertexArray(oc->sdf_vertex_array);
2128 glGenBuffers(1, &oc->sdf_vertex_buffer);
2129 glBindBuffer(GL_ARRAY_BUFFER, oc->sdf_vertex_buffer);
2130
2131 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, oc->sdf_vertex_buffer, oc->sdf_point_count * 2 * sizeof(float), p_points.ptr(), GL_STATIC_DRAW, "Occluder polygon SDF vertex buffer");
2132
2133 glEnableVertexAttribArray(RS::ARRAY_VERTEX);
2134 glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), nullptr);
2135
2136 glGenBuffers(1, &oc->sdf_index_buffer);
2137 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->sdf_index_buffer);
2138 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ELEMENT_ARRAY_BUFFER, oc->sdf_index_buffer, oc->sdf_index_count * sizeof(uint32_t), sdf_indices.ptr(), GL_STATIC_DRAW, "Occluder polygon SDF index buffer");
2139
2140 glBindVertexArray(0);
2141 } else {
2142 glBindBuffer(GL_ARRAY_BUFFER, oc->sdf_vertex_buffer);
2143 glBufferData(GL_ARRAY_BUFFER, p_points.size() * 2 * sizeof(float), p_points.ptr(), GL_STATIC_DRAW);
2144 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->sdf_index_buffer);
2145 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sdf_indices.size() * sizeof(uint32_t), sdf_indices.ptr(), GL_STATIC_DRAW);
2146 glBindBuffer(GL_ARRAY_BUFFER, 0);
2147 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2148 }
2149 }
2150 }
2151
2152 void RasterizerCanvasGLES3::occluder_polygon_set_cull_mode(RID p_occluder, RS::CanvasOccluderPolygonCullMode p_mode) {
2153 OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);
2154 ERR_FAIL_NULL(oc);
2155 oc->cull_mode = p_mode;
2156 }
2157
2158 void RasterizerCanvasGLES3::set_shadow_texture_size(int p_size) {
2159 GLES3::Config *config = GLES3::Config::get_singleton();
2160 p_size = nearest_power_of_2_templated(p_size);
2161
2162 if (p_size > config->max_texture_size) {
2163 p_size = config->max_texture_size;
2164 WARN_PRINT("Attempting to set CanvasItem shadow atlas size to " + itos(p_size) + " which is beyond limit of " + itos(config->max_texture_size) + "supported by hardware.");
2165 }
2166
2167 if (p_size == state.shadow_texture_size) {
2168 return;
2169 }
2170 state.shadow_texture_size = p_size;
2171
2172 if (state.shadow_fb != 0) {
2173 glDeleteFramebuffers(1, &state.shadow_fb);
2174 GLES3::Utilities::get_singleton()->texture_free_data(state.shadow_texture);
2175 glDeleteRenderbuffers(1, &state.shadow_depth_buffer);
2176 state.shadow_fb = 0;
2177 state.shadow_texture = 0;
2178 state.shadow_depth_buffer = 0;
2179 }
2180 _update_shadow_atlas();
2181 }
2182
2183 bool RasterizerCanvasGLES3::free(RID p_rid) {
2184 if (canvas_light_owner.owns(p_rid)) {
2185 CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
2186 ERR_FAIL_NULL_V(cl, false);
2187 canvas_light_owner.free(p_rid);
2188 } else if (occluder_polygon_owner.owns(p_rid)) {
2189 occluder_polygon_set_shape(p_rid, Vector<Vector2>(), false);
2190 occluder_polygon_owner.free(p_rid);
2191 } else {
2192 return false;
2193 }
2194
2195 return true;
2196 }
2197
2198 void RasterizerCanvasGLES3::update() {
2199 }
2200
2201 void RasterizerCanvasGLES3::canvas_begin(RID p_to_render_target, bool p_to_backbuffer, bool p_backbuffer_has_mipmaps) {
2202 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
2203 GLES3::Config *config = GLES3::Config::get_singleton();
2204
2205 GLES3::RenderTarget *render_target = texture_storage->get_render_target(p_to_render_target);
2206
2207 if (p_to_backbuffer) {
2208 glBindFramebuffer(GL_FRAMEBUFFER, render_target->backbuffer_fbo);
2209 glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 4);
2210 GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
2211 glBindTexture(GL_TEXTURE_2D, tex->tex_id);
2212 } else {
2213 glBindFramebuffer(GL_FRAMEBUFFER, render_target->fbo);
2214 glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 4);
2215 glBindTexture(GL_TEXTURE_2D, render_target->backbuffer);
2216 if (render_target->backbuffer != 0) {
2217 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, p_backbuffer_has_mipmaps ? render_target->mipmap_count - 1 : 0);
2218 }
2219 }
2220
2221 if (render_target->is_transparent || p_to_backbuffer) {
2222 state.transparent_render_target = true;
2223 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2224 } else {
2225 state.transparent_render_target = false;
2226 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
2227 }
2228
2229 if (render_target && render_target->clear_requested) {
2230 const Color &col = render_target->clear_color;
2231 glClearColor(col.r, col.g, col.b, render_target->is_transparent ? col.a : 1.0f);
2232
2233 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
2234 render_target->clear_requested = false;
2235 }
2236
2237 glActiveTexture(GL_TEXTURE0);
2238 GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
2239 glBindTexture(GL_TEXTURE_2D, tex->tex_id);
2240 }
2241
2242 void RasterizerCanvasGLES3::_bind_canvas_texture(RID p_texture, RS::CanvasItemTextureFilter p_base_filter, RS::CanvasItemTextureRepeat p_base_repeat) {
2243 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
2244 GLES3::Config *config = GLES3::Config::get_singleton();
2245
2246 if (p_texture == RID()) {
2247 p_texture = default_canvas_texture;
2248 }
2249
2250 if (state.current_tex == p_texture && state.current_filter_mode == p_base_filter && state.current_repeat_mode == p_base_repeat) {
2251 return;
2252 }
2253
2254 state.current_tex = p_texture;
2255 state.current_filter_mode = p_base_filter;
2256 state.current_repeat_mode = p_base_repeat;
2257
2258 GLES3::CanvasTexture *ct = nullptr;
2259
2260 GLES3::Texture *t = texture_storage->get_texture(p_texture);
2261
2262 if (t) {
2263 ERR_FAIL_NULL(t->canvas_texture);
2264 ct = t->canvas_texture;
2265 if (t->render_target) {
2266 t->render_target->used_in_frame = true;
2267 }
2268 } else {
2269 ct = texture_storage->get_canvas_texture(p_texture);
2270 }
2271
2272 if (!ct) {
2273 // Invalid Texture RID.
2274 _bind_canvas_texture(default_canvas_texture, p_base_filter, p_base_repeat);
2275 return;
2276 }
2277
2278 RS::CanvasItemTextureFilter filter = ct->texture_filter != RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT ? ct->texture_filter : p_base_filter;
2279 ERR_FAIL_COND(filter == RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT);
2280
2281 RS::CanvasItemTextureRepeat repeat = ct->texture_repeat != RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT ? ct->texture_repeat : p_base_repeat;
2282 ERR_FAIL_COND(repeat == RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT);
2283
2284 GLES3::Texture *texture = texture_storage->get_texture(ct->diffuse);
2285
2286 if (!texture) {
2287 GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
2288 glActiveTexture(GL_TEXTURE0);
2289 glBindTexture(GL_TEXTURE_2D, tex->tex_id);
2290 } else {
2291 glActiveTexture(GL_TEXTURE0);
2292 glBindTexture(GL_TEXTURE_2D, texture->tex_id);
2293 texture->gl_set_filter(filter);
2294 texture->gl_set_repeat(repeat);
2295 if (texture->render_target) {
2296 texture->render_target->used_in_frame = true;
2297 }
2298 }
2299
2300 GLES3::Texture *normal_map = texture_storage->get_texture(ct->normal_map);
2301
2302 if (!normal_map) {
2303 glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6);
2304 GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_NORMAL));
2305 glBindTexture(GL_TEXTURE_2D, tex->tex_id);
2306 } else {
2307 glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6);
2308 glBindTexture(GL_TEXTURE_2D, normal_map->tex_id);
2309 normal_map->gl_set_filter(filter);
2310 normal_map->gl_set_repeat(repeat);
2311 if (normal_map->render_target) {
2312 normal_map->render_target->used_in_frame = true;
2313 }
2314 }
2315
2316 GLES3::Texture *specular_map = texture_storage->get_texture(ct->specular);
2317
2318 if (!specular_map) {
2319 glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 7);
2320 GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
2321 glBindTexture(GL_TEXTURE_2D, tex->tex_id);
2322 } else {
2323 glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 7);
2324 glBindTexture(GL_TEXTURE_2D, specular_map->tex_id);
2325 specular_map->gl_set_filter(filter);
2326 specular_map->gl_set_repeat(repeat);
2327 if (specular_map->render_target) {
2328 specular_map->render_target->used_in_frame = true;
2329 }
2330 }
2331 }
2332
2333 void RasterizerCanvasGLES3::_prepare_canvas_texture(RID p_texture, RS::CanvasItemTextureFilter p_base_filter, RS::CanvasItemTextureRepeat p_base_repeat, uint32_t &r_index, Size2 &r_texpixel_size) {
2334 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
2335
2336 if (p_texture == RID()) {
2337 p_texture = default_canvas_texture;
2338 }
2339
2340 GLES3::CanvasTexture *ct = nullptr;
2341
2342 GLES3::Texture *t = texture_storage->get_texture(p_texture);
2343
2344 if (t) {
2345 //regular texture
2346 if (!t->canvas_texture) {
2347 t->canvas_texture = memnew(GLES3::CanvasTexture);
2348 t->canvas_texture->diffuse = p_texture;
2349 }
2350
2351 ct = t->canvas_texture;
2352 } else {
2353 ct = texture_storage->get_canvas_texture(p_texture);
2354 }
2355
2356 if (!ct) {
2357 // Invalid Texture RID.
2358 _prepare_canvas_texture(default_canvas_texture, p_base_filter, p_base_repeat, r_index, r_texpixel_size);
2359 return;
2360 }
2361
2362 GLES3::Texture *texture = texture_storage->get_texture(ct->diffuse);
2363 Size2i size_cache;
2364
2365 // Cache default white resource ID.
2366 const RID default_texture_id = texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE);
2367
2368 // If no texture is assigned, assign default white.
2369 if (!texture) {
2370 ct->diffuse = default_texture_id;
2371 }
2372
2373 // Enforce a 1x1 size if default white texture.
2374 size_cache = ct->diffuse == default_texture_id ? Size2i(1, 1) : Size2i(texture->width, texture->height);
2375
2376 GLES3::Texture *normal_map = texture_storage->get_texture(ct->normal_map);
2377
2378 if (ct->specular_color.a < 0.999) {
2379 state.canvas_instance_batches[state.current_batch_index].flags |= BATCH_FLAGS_DEFAULT_SPECULAR_MAP_USED;
2380 } else {
2381 state.canvas_instance_batches[state.current_batch_index].flags &= ~BATCH_FLAGS_DEFAULT_SPECULAR_MAP_USED;
2382 }
2383
2384 if (normal_map) {
2385 state.canvas_instance_batches[state.current_batch_index].flags |= BATCH_FLAGS_DEFAULT_NORMAL_MAP_USED;
2386 } else {
2387 state.canvas_instance_batches[state.current_batch_index].flags &= ~BATCH_FLAGS_DEFAULT_NORMAL_MAP_USED;
2388 }
2389
2390 state.canvas_instance_batches[state.current_batch_index].specular_shininess = uint32_t(CLAMP(ct->specular_color.a * 255.0, 0, 255)) << 24;
2391 state.canvas_instance_batches[state.current_batch_index].specular_shininess |= uint32_t(CLAMP(ct->specular_color.b * 255.0, 0, 255)) << 16;
2392 state.canvas_instance_batches[state.current_batch_index].specular_shininess |= uint32_t(CLAMP(ct->specular_color.g * 255.0, 0, 255)) << 8;
2393 state.canvas_instance_batches[state.current_batch_index].specular_shininess |= uint32_t(CLAMP(ct->specular_color.r * 255.0, 0, 255));
2394
2395 r_texpixel_size.x = 1.0 / float(size_cache.x);
2396 r_texpixel_size.y = 1.0 / float(size_cache.y);
2397
2398 state.instance_data_array[r_index].color_texture_pixel_size[0] = r_texpixel_size.x;
2399 state.instance_data_array[r_index].color_texture_pixel_size[1] = r_texpixel_size.y;
2400 }
2401
2402 void RasterizerCanvasGLES3::reset_canvas() {
2403 glDisable(GL_CULL_FACE);
2404 glDisable(GL_DEPTH_TEST);
2405 glDisable(GL_SCISSOR_TEST);
2406 glEnable(GL_BLEND);
2407 glBlendEquation(GL_FUNC_ADD);
2408 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
2409
2410 glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 2);
2411 glBindTexture(GL_TEXTURE_2D, 0);
2412 glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 3);
2413 glBindTexture(GL_TEXTURE_2D, 0);
2414 glActiveTexture(GL_TEXTURE0);
2415
2416 glBindBuffer(GL_ARRAY_BUFFER, 0);
2417 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2418 }
2419
2420 void RasterizerCanvasGLES3::draw_lens_distortion_rect(const Rect2 &p_rect, float p_k1, float p_k2, const Vector2 &p_eye_center, float p_oversample) {
2421 }
2422
2423 RendererCanvasRender::PolygonID RasterizerCanvasGLES3::request_polygon(const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, const Vector<int> &p_bones, const Vector<float> &p_weights, int p_count) {
2424 // We interleave the vertex data into one big VBO to improve cache coherence
2425 uint32_t vertex_count = p_points.size();
2426 uint32_t stride = 2;
2427 if ((uint32_t)p_colors.size() == vertex_count) {
2428 stride += 4;
2429 }
2430 if ((uint32_t)p_uvs.size() == vertex_count) {
2431 stride += 2;
2432 }
2433 if ((uint32_t)p_bones.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
2434 stride += 4;
2435 }
2436
2437 PolygonBuffers pb;
2438 glGenBuffers(1, &pb.vertex_buffer);
2439 glGenVertexArrays(1, &pb.vertex_array);
2440 glBindVertexArray(pb.vertex_array);
2441 pb.count = vertex_count;
2442 pb.index_buffer = 0;
2443
2444 uint32_t buffer_size = stride * p_points.size();
2445
2446 Vector<uint8_t> polygon_buffer;
2447 polygon_buffer.resize(buffer_size * sizeof(float));
2448 {
2449 glBindBuffer(GL_ARRAY_BUFFER, pb.vertex_buffer);
2450 uint8_t *r = polygon_buffer.ptrw();
2451 float *fptr = reinterpret_cast<float *>(r);
2452 uint32_t *uptr = (uint32_t *)r;
2453 uint32_t base_offset = 0;
2454 {
2455 // Always uses vertex positions
2456 glEnableVertexAttribArray(RS::ARRAY_VERTEX);
2457 glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, stride * sizeof(float), nullptr);
2458 const Vector2 *points_ptr = p_points.ptr();
2459
2460 for (uint32_t i = 0; i < vertex_count; i++) {
2461 fptr[base_offset + i * stride + 0] = points_ptr[i].x;
2462 fptr[base_offset + i * stride + 1] = points_ptr[i].y;
2463 }
2464
2465 base_offset += 2;
2466 }
2467
2468 // Next add colors
2469 if ((uint32_t)p_colors.size() == vertex_count) {
2470 glEnableVertexAttribArray(RS::ARRAY_COLOR);
2471 glVertexAttribPointer(RS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
2472
2473 const Color *color_ptr = p_colors.ptr();
2474
2475 for (uint32_t i = 0; i < vertex_count; i++) {
2476 fptr[base_offset + i * stride + 0] = color_ptr[i].r;
2477 fptr[base_offset + i * stride + 1] = color_ptr[i].g;
2478 fptr[base_offset + i * stride + 2] = color_ptr[i].b;
2479 fptr[base_offset + i * stride + 3] = color_ptr[i].a;
2480 }
2481 base_offset += 4;
2482 } else {
2483 glDisableVertexAttribArray(RS::ARRAY_COLOR);
2484 pb.color_disabled = true;
2485 pb.color = p_colors.size() == 1 ? p_colors[0] : Color(1.0, 1.0, 1.0, 1.0);
2486 }
2487
2488 if ((uint32_t)p_uvs.size() == vertex_count) {
2489 glEnableVertexAttribArray(RS::ARRAY_TEX_UV);
2490 glVertexAttribPointer(RS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
2491
2492 const Vector2 *uv_ptr = p_uvs.ptr();
2493
2494 for (uint32_t i = 0; i < vertex_count; i++) {
2495 fptr[base_offset + i * stride + 0] = uv_ptr[i].x;
2496 fptr[base_offset + i * stride + 1] = uv_ptr[i].y;
2497 }
2498
2499 base_offset += 2;
2500 } else {
2501 glDisableVertexAttribArray(RS::ARRAY_TEX_UV);
2502 }
2503
2504 if ((uint32_t)p_indices.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
2505 glEnableVertexAttribArray(RS::ARRAY_BONES);
2506 glVertexAttribPointer(RS::ARRAY_BONES, 4, GL_UNSIGNED_INT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
2507
2508 const int *bone_ptr = p_bones.ptr();
2509
2510 for (uint32_t i = 0; i < vertex_count; i++) {
2511 uint16_t *bone16w = (uint16_t *)&uptr[base_offset + i * stride];
2512
2513 bone16w[0] = bone_ptr[i * 4 + 0];
2514 bone16w[1] = bone_ptr[i * 4 + 1];
2515 bone16w[2] = bone_ptr[i * 4 + 2];
2516 bone16w[3] = bone_ptr[i * 4 + 3];
2517 }
2518
2519 base_offset += 2;
2520 } else {
2521 glDisableVertexAttribArray(RS::ARRAY_BONES);
2522 }
2523
2524 if ((uint32_t)p_weights.size() == vertex_count * 4) {
2525 glEnableVertexAttribArray(RS::ARRAY_WEIGHTS);
2526 glVertexAttribPointer(RS::ARRAY_WEIGHTS, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
2527
2528 const float *weight_ptr = p_weights.ptr();
2529
2530 for (uint32_t i = 0; i < vertex_count; i++) {
2531 uint16_t *weight16w = (uint16_t *)&uptr[base_offset + i * stride];
2532
2533 weight16w[0] = CLAMP(weight_ptr[i * 4 + 0] * 65535, 0, 65535);
2534 weight16w[1] = CLAMP(weight_ptr[i * 4 + 1] * 65535, 0, 65535);
2535 weight16w[2] = CLAMP(weight_ptr[i * 4 + 2] * 65535, 0, 65535);
2536 weight16w[3] = CLAMP(weight_ptr[i * 4 + 3] * 65535, 0, 65535);
2537 }
2538
2539 base_offset += 2;
2540 } else {
2541 glDisableVertexAttribArray(RS::ARRAY_WEIGHTS);
2542 }
2543
2544 ERR_FAIL_COND_V(base_offset != stride, 0);
2545 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, pb.vertex_buffer, vertex_count * stride * sizeof(float), polygon_buffer.ptr(), GL_STATIC_DRAW, "Polygon 2D vertex buffer");
2546 }
2547
2548 if (p_indices.size()) {
2549 //create indices, as indices were requested
2550 Vector<uint8_t> index_buffer;
2551 index_buffer.resize(p_count * sizeof(int32_t));
2552 {
2553 uint8_t *w = index_buffer.ptrw();
2554 memcpy(w, p_indices.ptr(), sizeof(int32_t) * p_count);
2555 }
2556 glGenBuffers(1, &pb.index_buffer);
2557 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pb.index_buffer);
2558 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ELEMENT_ARRAY_BUFFER, pb.index_buffer, p_count * 4, index_buffer.ptr(), GL_STATIC_DRAW, "Polygon 2D index buffer");
2559 pb.count = p_count;
2560 }
2561
2562 glBindVertexArray(0);
2563 glBindBuffer(GL_ARRAY_BUFFER, 0);
2564 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2565
2566 PolygonID id = polygon_buffers.last_id++;
2567
2568 polygon_buffers.polygons[id] = pb;
2569
2570 return id;
2571 }
2572
2573 void RasterizerCanvasGLES3::free_polygon(PolygonID p_polygon) {
2574 PolygonBuffers *pb_ptr = polygon_buffers.polygons.getptr(p_polygon);
2575 ERR_FAIL_NULL(pb_ptr);
2576
2577 PolygonBuffers &pb = *pb_ptr;
2578
2579 if (pb.index_buffer != 0) {
2580 GLES3::Utilities::get_singleton()->buffer_free_data(pb.index_buffer);
2581 }
2582
2583 glDeleteVertexArrays(1, &pb.vertex_array);
2584 GLES3::Utilities::get_singleton()->buffer_free_data(pb.vertex_buffer);
2585
2586 polygon_buffers.polygons.erase(p_polygon);
2587 }
2588
2589 // Creates a new uniform buffer and uses it right away
2590 // This expands the instance buffer continually
2591 // In theory allocations can reach as high as number of windows * 3 frames
2592 // because OpenGL can start rendering subsequent frames before finishing the current one
2593 void RasterizerCanvasGLES3::_allocate_instance_data_buffer() {
2594 GLuint new_buffers[3];
2595 glGenBuffers(3, new_buffers);
2596 // Batch UBO.
2597 glBindBuffer(GL_ARRAY_BUFFER, new_buffers[0]);
2598 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, new_buffers[0], data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW, "2D Batch UBO[" + itos(state.current_data_buffer_index) + "][0]");
2599 // Light uniform buffer.
2600 glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[1]);
2601 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[1], sizeof(LightUniform) * data.max_lights_per_render, nullptr, GL_STREAM_DRAW, "2D Lights UBO[" + itos(state.current_data_buffer_index) + "]");
2602 // State buffer.
2603 glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[2]);
2604 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[2], sizeof(StateBuffer), nullptr, GL_STREAM_DRAW, "2D State UBO[" + itos(state.current_data_buffer_index) + "]");
2605
2606 state.current_data_buffer_index = (state.current_data_buffer_index + 1);
2607 DataBuffer db;
2608 db.instance_buffers.push_back(new_buffers[0]);
2609 db.light_ubo = new_buffers[1];
2610 db.state_ubo = new_buffers[2];
2611 db.last_frame_used = RSG::rasterizer->get_frame_number();
2612 state.canvas_instance_data_buffers.insert(state.current_data_buffer_index, db);
2613 state.current_data_buffer_index = state.current_data_buffer_index % state.canvas_instance_data_buffers.size();
2614 glBindBuffer(GL_ARRAY_BUFFER, 0);
2615 glBindBuffer(GL_UNIFORM_BUFFER, 0);
2616 }
2617 void RasterizerCanvasGLES3::_allocate_instance_buffer() {
2618 state.current_instance_buffer_index++;
2619
2620 if (int(state.current_instance_buffer_index) < state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.size()) {
2621 // We already allocated another buffer in a previous frame, so we can just use it.
2622 return;
2623 }
2624
2625 GLuint new_buffer;
2626 glGenBuffers(1, &new_buffer);
2627
2628 glBindBuffer(GL_ARRAY_BUFFER, new_buffer);
2629 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, new_buffer, data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW, "Batch UBO[" + itos(state.current_data_buffer_index) + "][" + itos(state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.size()) + "]");
2630
2631 state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.push_back(new_buffer);
2632
2633 glBindBuffer(GL_ARRAY_BUFFER, 0);
2634 }
2635
2636 void RasterizerCanvasGLES3::set_time(double p_time) {
2637 state.time = p_time;
2638 }
2639
2640 RasterizerCanvasGLES3 *RasterizerCanvasGLES3::singleton = nullptr;
2641
2642 RasterizerCanvasGLES3 *RasterizerCanvasGLES3::get_singleton() {
2643 return singleton;
2644 }
2645
2646 RasterizerCanvasGLES3::RasterizerCanvasGLES3() {
2647 singleton = this;
2648 GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
2649 GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
2650 GLES3::Config *config = GLES3::Config::get_singleton();
2651
2652 glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0);
2653
2654 polygon_buffers.last_id = 1;
2655 // quad buffer
2656 {
2657 glGenBuffers(1, &data.canvas_quad_vertices);
2658 glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
2659
2660 const float qv[8] = {
2661 0, 0,
2662 0, 1,
2663 1, 1,
2664 1, 0
2665 };
2666
2667 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 8, qv, GL_STATIC_DRAW);
2668
2669 glBindBuffer(GL_ARRAY_BUFFER, 0);
2670
2671 glGenVertexArrays(1, &data.canvas_quad_array);
2672 glBindVertexArray(data.canvas_quad_array);
2673 glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
2674 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, nullptr);
2675 glEnableVertexAttribArray(0);
2676 glBindVertexArray(0);
2677 glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
2678 }
2679
2680 {
2681 //particle quad buffers
2682
2683 glGenBuffers(1, &data.particle_quad_vertices);
2684 glBindBuffer(GL_ARRAY_BUFFER, data.particle_quad_vertices);
2685 {
2686 //quad of size 1, with pivot on the center for particles, then regular UVS. Color is general plus fetched from particle
2687 const float qv[16] = {
2688 -0.5, -0.5,
2689 0.0, 0.0,
2690 -0.5, 0.5,
2691 0.0, 1.0,
2692 0.5, 0.5,
2693 1.0, 1.0,
2694 0.5, -0.5,
2695 1.0, 0.0
2696 };
2697
2698 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, qv, GL_STATIC_DRAW);
2699 }
2700
2701 glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
2702
2703 glGenVertexArrays(1, &data.particle_quad_array);
2704 glBindVertexArray(data.particle_quad_array);
2705 glBindBuffer(GL_ARRAY_BUFFER, data.particle_quad_vertices);
2706 glEnableVertexAttribArray(RS::ARRAY_VERTEX);
2707 glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, nullptr);
2708 glEnableVertexAttribArray(RS::ARRAY_TEX_UV);
2709 glVertexAttribPointer(RS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(8));
2710 glBindVertexArray(0);
2711 glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
2712 }
2713
2714 // ninepatch buffers
2715 {
2716 // array buffer
2717 glGenBuffers(1, &data.ninepatch_vertices);
2718 glBindBuffer(GL_ARRAY_BUFFER, data.ninepatch_vertices);
2719
2720 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * (16 + 16) * 2, nullptr, GL_DYNAMIC_DRAW);
2721
2722 glBindBuffer(GL_ARRAY_BUFFER, 0);
2723
2724 // element buffer
2725 glGenBuffers(1, &data.ninepatch_elements);
2726 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ninepatch_elements);
2727
2728 #define _EIDX(y, x) (y * 4 + x)
2729 uint8_t elems[3 * 2 * 9] = {
2730 // first row
2731
2732 _EIDX(0, 0), _EIDX(0, 1), _EIDX(1, 1),
2733 _EIDX(1, 1), _EIDX(1, 0), _EIDX(0, 0),
2734
2735 _EIDX(0, 1), _EIDX(0, 2), _EIDX(1, 2),
2736 _EIDX(1, 2), _EIDX(1, 1), _EIDX(0, 1),
2737
2738 _EIDX(0, 2), _EIDX(0, 3), _EIDX(1, 3),
2739 _EIDX(1, 3), _EIDX(1, 2), _EIDX(0, 2),
2740
2741 // second row
2742
2743 _EIDX(1, 0), _EIDX(1, 1), _EIDX(2, 1),
2744 _EIDX(2, 1), _EIDX(2, 0), _EIDX(1, 0),
2745
2746 // the center one would be here, but we'll put it at the end
2747 // so it's easier to disable the center and be able to use
2748 // one draw call for both
2749
2750 _EIDX(1, 2), _EIDX(1, 3), _EIDX(2, 3),
2751 _EIDX(2, 3), _EIDX(2, 2), _EIDX(1, 2),
2752
2753 // third row
2754
2755 _EIDX(2, 0), _EIDX(2, 1), _EIDX(3, 1),
2756 _EIDX(3, 1), _EIDX(3, 0), _EIDX(2, 0),
2757
2758 _EIDX(2, 1), _EIDX(2, 2), _EIDX(3, 2),
2759 _EIDX(3, 2), _EIDX(3, 1), _EIDX(2, 1),
2760
2761 _EIDX(2, 2), _EIDX(2, 3), _EIDX(3, 3),
2762 _EIDX(3, 3), _EIDX(3, 2), _EIDX(2, 2),
2763
2764 // center field
2765
2766 _EIDX(1, 1), _EIDX(1, 2), _EIDX(2, 2),
2767 _EIDX(2, 2), _EIDX(2, 1), _EIDX(1, 1)
2768 };
2769 #undef _EIDX
2770
2771 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elems), elems, GL_STATIC_DRAW);
2772
2773 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2774 }
2775
2776 if (config->max_uniform_buffer_size < 65536) {
2777 data.max_lights_per_render = 64;
2778 } else {
2779 data.max_lights_per_render = 256;
2780 }
2781
2782 // Reserve 3 Uniform Buffers for instance data Frame N, N+1 and N+2
2783 data.max_instances_per_buffer = uint32_t(GLOBAL_GET("rendering/gl_compatibility/item_buffer_size"));
2784 data.max_instance_buffer_size = data.max_instances_per_buffer * sizeof(InstanceData); // 16,384 instances * 128 bytes = 2,097,152 bytes = 2,048 kb
2785 state.canvas_instance_data_buffers.resize(3);
2786 state.canvas_instance_batches.reserve(200);
2787
2788 for (int i = 0; i < 3; i++) {
2789 GLuint new_buffers[3];
2790 glGenBuffers(3, new_buffers);
2791 // Batch UBO.
2792 glBindBuffer(GL_ARRAY_BUFFER, new_buffers[0]);
2793 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, new_buffers[0], data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW, "Batch UBO[0][0]");
2794 // Light uniform buffer.
2795 glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[1]);
2796 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[1], sizeof(LightUniform) * data.max_lights_per_render, nullptr, GL_STREAM_DRAW, "2D lights UBO[0]");
2797 // State buffer.
2798 glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[2]);
2799 GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[2], sizeof(StateBuffer), nullptr, GL_STREAM_DRAW, "2D state UBO[0]");
2800 DataBuffer db;
2801 db.instance_buffers.push_back(new_buffers[0]);
2802 db.light_ubo = new_buffers[1];
2803 db.state_ubo = new_buffers[2];
2804 db.last_frame_used = 0;
2805 db.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
2806 state.canvas_instance_data_buffers[i] = db;
2807 }
2808 glBindBuffer(GL_ARRAY_BUFFER, 0);
2809 glBindBuffer(GL_UNIFORM_BUFFER, 0);
2810
2811 state.instance_data_array = memnew_arr(InstanceData, data.max_instances_per_buffer);
2812 state.light_uniforms = memnew_arr(LightUniform, data.max_lights_per_render);
2813
2814 {
2815 const uint32_t indices[6] = { 0, 2, 1, 3, 2, 0 };
2816 glGenVertexArrays(1, &data.indexed_quad_array);
2817 glBindVertexArray(data.indexed_quad_array);
2818 glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
2819 glGenBuffers(1, &data.indexed_quad_buffer);
2820 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.indexed_quad_buffer);
2821 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32_t) * 6, indices, GL_STATIC_DRAW);
2822 glBindVertexArray(0);
2823 }
2824
2825 String global_defines;
2826 global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
2827 global_defines += "#define MAX_LIGHTS " + itos(data.max_lights_per_render) + "\n";
2828
2829 GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.initialize(global_defines, 1);
2830 data.canvas_shader_default_version = GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_create();
2831
2832 state.shadow_texture_size = GLOBAL_GET("rendering/2d/shadow_atlas/size");
2833 shadow_render.shader.initialize();
2834 shadow_render.shader_version = shadow_render.shader.version_create();
2835
2836 {
2837 default_canvas_group_shader = material_storage->shader_allocate();
2838 material_storage->shader_initialize(default_canvas_group_shader);
2839
2840 material_storage->shader_set_code(default_canvas_group_shader, R"(
2841 // Default CanvasGroup shader.
2842
2843 shader_type canvas_item;
2844 render_mode unshaded;
2845
2846 uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;
2847
2848 void fragment() {
2849 vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);
2850
2851 if (c.a > 0.0001) {
2852 c.rgb /= c.a;
2853 }
2854
2855 COLOR *= c;
2856 }
2857 )");
2858 default_canvas_group_material = material_storage->material_allocate();
2859 material_storage->material_initialize(default_canvas_group_material);
2860
2861 material_storage->material_set_shader(default_canvas_group_material, default_canvas_group_shader);
2862 }
2863
2864 {
2865 default_clip_children_shader = material_storage->shader_allocate();
2866 material_storage->shader_initialize(default_clip_children_shader);
2867
2868 material_storage->shader_set_code(default_clip_children_shader, R"(
2869 // Default clip children shader.
2870
2871 shader_type canvas_item;
2872 render_mode unshaded;
2873
2874 uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;
2875
2876 void fragment() {
2877 vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);
2878 COLOR.rgb = c.rgb;
2879 }
2880 )");
2881 default_clip_children_material = material_storage->material_allocate();
2882 material_storage->material_initialize(default_clip_children_material);
2883
2884 material_storage->material_set_shader(default_clip_children_material, default_clip_children_shader);
2885 }
2886
2887 default_canvas_texture = texture_storage->canvas_texture_allocate();
2888 texture_storage->canvas_texture_initialize(default_canvas_texture);
2889
2890 state.time = 0.0;
2891 }
2892
2893 RasterizerCanvasGLES3::~RasterizerCanvasGLES3() {
2894 singleton = nullptr;
2895
2896 GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
2897 material_storage->shaders.canvas_shader.version_free(data.canvas_shader_default_version);
2898 shadow_render.shader.version_free(shadow_render.shader_version);
2899 material_storage->material_free(default_canvas_group_material);
2900 material_storage->shader_free(default_canvas_group_shader);
2901 material_storage->material_free(default_clip_children_material);
2902 material_storage->shader_free(default_clip_children_shader);
2903 singleton = nullptr;
2904
2905 glDeleteBuffers(1, &data.canvas_quad_vertices);
2906 glDeleteVertexArrays(1, &data.canvas_quad_array);
2907
2908 glDeleteBuffers(1, &data.canvas_quad_vertices);
2909 glDeleteVertexArrays(1, &data.canvas_quad_array);
2910
2911 GLES3::TextureStorage::get_singleton()->canvas_texture_free(default_canvas_texture);
2912 memdelete_arr(state.instance_data_array);
2913 memdelete_arr(state.light_uniforms);
2914
2915 if (state.shadow_fb != 0) {
2916 glDeleteFramebuffers(1, &state.shadow_fb);
2917 GLES3::Utilities::get_singleton()->texture_free_data(state.shadow_texture);
2918 glDeleteRenderbuffers(1, &state.shadow_depth_buffer);
2919 state.shadow_fb = 0;
2920 state.shadow_texture = 0;
2921 state.shadow_depth_buffer = 0;
2922 }
2923
2924 for (uint32_t i = 0; i < state.canvas_instance_data_buffers.size(); i++) {
2925 for (int j = 0; j < state.canvas_instance_data_buffers[i].instance_buffers.size(); j++) {
2926 if (state.canvas_instance_data_buffers[i].instance_buffers[j]) {
2927 GLES3::Utilities::get_singleton()->buffer_free_data(state.canvas_instance_data_buffers[i].instance_buffers[j]);
2928 }
2929 }
2930 if (state.canvas_instance_data_buffers[i].light_ubo) {
2931 GLES3::Utilities::get_singleton()->buffer_free_data(state.canvas_instance_data_buffers[i].light_ubo);
2932 }
2933 if (state.canvas_instance_data_buffers[i].state_ubo) {
2934 GLES3::Utilities::get_singleton()->buffer_free_data(state.canvas_instance_data_buffers[i].state_ubo);
2935 }
2936 }
2937 }
2938
2939 #endif // GLES3_ENABLED