rasterizer_canvas_gles3.cpp 120 KB

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