rasterizer_canvas_rd.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572
  1. /*************************************************************************/
  2. /* rasterizer_canvas_rd.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "rasterizer_canvas_rd.h"
  31. #include "core/math/math_funcs.h"
  32. #include "core/project_settings.h"
  33. #include "rasterizer_rd.h"
  34. void RasterizerCanvasRD::_update_transform_2d_to_mat4(const Transform2D &p_transform, float *p_mat4) {
  35. p_mat4[0] = p_transform.elements[0][0];
  36. p_mat4[1] = p_transform.elements[0][1];
  37. p_mat4[2] = 0;
  38. p_mat4[3] = 0;
  39. p_mat4[4] = p_transform.elements[1][0];
  40. p_mat4[5] = p_transform.elements[1][1];
  41. p_mat4[6] = 0;
  42. p_mat4[7] = 0;
  43. p_mat4[8] = 0;
  44. p_mat4[9] = 0;
  45. p_mat4[10] = 1;
  46. p_mat4[11] = 0;
  47. p_mat4[12] = p_transform.elements[2][0];
  48. p_mat4[13] = p_transform.elements[2][1];
  49. p_mat4[14] = 0;
  50. p_mat4[15] = 1;
  51. }
  52. void RasterizerCanvasRD::_update_transform_2d_to_mat2x4(const Transform2D &p_transform, float *p_mat2x4) {
  53. p_mat2x4[0] = p_transform.elements[0][0];
  54. p_mat2x4[1] = p_transform.elements[1][0];
  55. p_mat2x4[2] = 0;
  56. p_mat2x4[3] = p_transform.elements[2][0];
  57. p_mat2x4[4] = p_transform.elements[0][1];
  58. p_mat2x4[5] = p_transform.elements[1][1];
  59. p_mat2x4[6] = 0;
  60. p_mat2x4[7] = p_transform.elements[2][1];
  61. }
  62. void RasterizerCanvasRD::_update_transform_2d_to_mat2x3(const Transform2D &p_transform, float *p_mat2x3) {
  63. p_mat2x3[0] = p_transform.elements[0][0];
  64. p_mat2x3[1] = p_transform.elements[0][1];
  65. p_mat2x3[2] = p_transform.elements[1][0];
  66. p_mat2x3[3] = p_transform.elements[1][1];
  67. p_mat2x3[4] = p_transform.elements[2][0];
  68. p_mat2x3[5] = p_transform.elements[2][1];
  69. }
  70. void RasterizerCanvasRD::_update_transform_to_mat4(const Transform &p_transform, float *p_mat4) {
  71. p_mat4[0] = p_transform.basis.elements[0][0];
  72. p_mat4[1] = p_transform.basis.elements[1][0];
  73. p_mat4[2] = p_transform.basis.elements[2][0];
  74. p_mat4[3] = 0;
  75. p_mat4[4] = p_transform.basis.elements[0][1];
  76. p_mat4[5] = p_transform.basis.elements[1][1];
  77. p_mat4[6] = p_transform.basis.elements[2][1];
  78. p_mat4[7] = 0;
  79. p_mat4[8] = p_transform.basis.elements[0][2];
  80. p_mat4[9] = p_transform.basis.elements[1][2];
  81. p_mat4[10] = p_transform.basis.elements[2][2];
  82. p_mat4[11] = 0;
  83. p_mat4[12] = p_transform.origin.x;
  84. p_mat4[13] = p_transform.origin.y;
  85. p_mat4[14] = p_transform.origin.z;
  86. p_mat4[15] = 1;
  87. }
  88. RasterizerCanvas::PolygonID RasterizerCanvasRD::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) {
  89. // Care must be taken to generate array formats
  90. // in ways where they could be reused, so we will
  91. // put single-occuring elements first, and repeated
  92. // elements later. This way the generated formats are
  93. // the same no matter the length of the arrays.
  94. // This dramatically reduces the amount of pipeline objects
  95. // that need to be created for these formats.
  96. uint32_t vertex_count = p_points.size();
  97. uint32_t stride = 2; //vertices always repeat
  98. if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {
  99. stride += 4;
  100. }
  101. if ((uint32_t)p_uvs.size() == vertex_count) {
  102. stride += 2;
  103. }
  104. if ((uint32_t)p_bones.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
  105. stride += 4;
  106. }
  107. uint32_t buffer_size = stride * p_points.size();
  108. Vector<uint8_t> polygon_buffer;
  109. polygon_buffer.resize(buffer_size * sizeof(float));
  110. Vector<RD::VertexAttribute> descriptions;
  111. descriptions.resize(4);
  112. Vector<RID> buffers;
  113. buffers.resize(4);
  114. {
  115. const uint8_t *r = polygon_buffer.ptr();
  116. float *fptr = (float *)r;
  117. uint32_t *uptr = (uint32_t *)r;
  118. uint32_t base_offset = 0;
  119. { //vertices
  120. RD::VertexAttribute vd;
  121. vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
  122. vd.offset = base_offset * sizeof(float);
  123. vd.location = RS::ARRAY_VERTEX;
  124. vd.stride = stride * sizeof(float);
  125. descriptions.write[0] = vd;
  126. const Vector2 *points_ptr = p_points.ptr();
  127. for (uint32_t i = 0; i < vertex_count; i++) {
  128. fptr[base_offset + i * stride + 0] = points_ptr[i].x;
  129. fptr[base_offset + i * stride + 1] = points_ptr[i].y;
  130. }
  131. base_offset += 2;
  132. }
  133. //colors
  134. if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {
  135. RD::VertexAttribute vd;
  136. vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  137. vd.offset = base_offset * sizeof(float);
  138. vd.location = RS::ARRAY_COLOR;
  139. vd.stride = stride * sizeof(float);
  140. descriptions.write[1] = vd;
  141. if (p_colors.size() == 1) {
  142. Color color = p_colors[0];
  143. for (uint32_t i = 0; i < vertex_count; i++) {
  144. fptr[base_offset + i * stride + 0] = color.r;
  145. fptr[base_offset + i * stride + 1] = color.g;
  146. fptr[base_offset + i * stride + 2] = color.b;
  147. fptr[base_offset + i * stride + 3] = color.a;
  148. }
  149. } else {
  150. const Color *color_ptr = p_colors.ptr();
  151. for (uint32_t i = 0; i < vertex_count; i++) {
  152. fptr[base_offset + i * stride + 0] = color_ptr[i].r;
  153. fptr[base_offset + i * stride + 1] = color_ptr[i].g;
  154. fptr[base_offset + i * stride + 2] = color_ptr[i].b;
  155. fptr[base_offset + i * stride + 3] = color_ptr[i].a;
  156. }
  157. }
  158. base_offset += 4;
  159. } else {
  160. RD::VertexAttribute vd;
  161. vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  162. vd.offset = 0;
  163. vd.location = RS::ARRAY_COLOR;
  164. vd.stride = 0;
  165. descriptions.write[1] = vd;
  166. buffers.write[1] = storage->mesh_get_default_rd_buffer(RasterizerStorageRD::DEFAULT_RD_BUFFER_COLOR);
  167. }
  168. //uvs
  169. if ((uint32_t)p_uvs.size() == vertex_count) {
  170. RD::VertexAttribute vd;
  171. vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
  172. vd.offset = base_offset * sizeof(float);
  173. vd.location = RS::ARRAY_TEX_UV;
  174. vd.stride = stride * sizeof(float);
  175. descriptions.write[2] = vd;
  176. const Vector2 *uv_ptr = p_uvs.ptr();
  177. for (uint32_t i = 0; i < vertex_count; i++) {
  178. fptr[base_offset + i * stride + 0] = uv_ptr[i].x;
  179. fptr[base_offset + i * stride + 1] = uv_ptr[i].y;
  180. }
  181. base_offset += 2;
  182. } else {
  183. RD::VertexAttribute vd;
  184. vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
  185. vd.offset = 0;
  186. vd.location = RS::ARRAY_TEX_UV;
  187. vd.stride = 0;
  188. descriptions.write[2] = vd;
  189. buffers.write[2] = storage->mesh_get_default_rd_buffer(RasterizerStorageRD::DEFAULT_RD_BUFFER_TEX_UV);
  190. }
  191. //bones
  192. if ((uint32_t)p_indices.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
  193. RD::VertexAttribute vd;
  194. vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT;
  195. vd.offset = base_offset * sizeof(float);
  196. vd.location = RS::ARRAY_BONES;
  197. vd.stride = stride * sizeof(float);
  198. descriptions.write[3] = vd;
  199. const int *bone_ptr = p_bones.ptr();
  200. const float *weight_ptr = p_weights.ptr();
  201. for (uint32_t i = 0; i < vertex_count; i++) {
  202. uint16_t *bone16w = (uint16_t *)&uptr[base_offset + i * stride];
  203. uint16_t *weight16w = (uint16_t *)&uptr[base_offset + i * stride + 2];
  204. bone16w[0] = bone_ptr[i * 4 + 0];
  205. bone16w[1] = bone_ptr[i * 4 + 1];
  206. bone16w[2] = bone_ptr[i * 4 + 2];
  207. bone16w[3] = bone_ptr[i * 4 + 3];
  208. weight16w[0] = CLAMP(weight_ptr[i * 4 + 0] * 65535, 0, 65535);
  209. weight16w[1] = CLAMP(weight_ptr[i * 4 + 1] * 65535, 0, 65535);
  210. weight16w[2] = CLAMP(weight_ptr[i * 4 + 2] * 65535, 0, 65535);
  211. weight16w[3] = CLAMP(weight_ptr[i * 4 + 3] * 65535, 0, 65535);
  212. }
  213. base_offset += 4;
  214. } else {
  215. RD::VertexAttribute vd;
  216. vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT;
  217. vd.offset = 0;
  218. vd.location = RS::ARRAY_BONES;
  219. vd.stride = 0;
  220. descriptions.write[3] = vd;
  221. buffers.write[3] = storage->mesh_get_default_rd_buffer(RasterizerStorageRD::DEFAULT_RD_BUFFER_BONES);
  222. }
  223. //check that everything is as it should be
  224. ERR_FAIL_COND_V(base_offset != stride, 0); //bug
  225. }
  226. RD::VertexFormatID vertex_id = RD::get_singleton()->vertex_format_create(descriptions);
  227. ERR_FAIL_COND_V(vertex_id == RD::INVALID_ID, 0);
  228. PolygonBuffers pb;
  229. pb.vertex_buffer = RD::get_singleton()->vertex_buffer_create(polygon_buffer.size(), polygon_buffer);
  230. for (int i = 0; i < descriptions.size(); i++) {
  231. if (buffers[i] == RID()) { //if put in vertex, use as vertex
  232. buffers.write[i] = pb.vertex_buffer;
  233. }
  234. }
  235. pb.vertex_array = RD::get_singleton()->vertex_array_create(p_points.size(), vertex_id, buffers);
  236. if (p_indices.size()) {
  237. //create indices, as indices were requested
  238. Vector<uint8_t> index_buffer;
  239. index_buffer.resize(p_indices.size() * sizeof(int32_t));
  240. {
  241. uint8_t *w = index_buffer.ptrw();
  242. copymem(w, p_indices.ptr(), sizeof(int32_t) * p_indices.size());
  243. }
  244. pb.index_buffer = RD::get_singleton()->index_buffer_create(p_indices.size(), RD::INDEX_BUFFER_FORMAT_UINT32, index_buffer);
  245. pb.indices = RD::get_singleton()->index_array_create(pb.index_buffer, 0, p_indices.size());
  246. }
  247. pb.vertex_format_id = vertex_id;
  248. PolygonID id = polygon_buffers.last_id++;
  249. polygon_buffers.polygons[id] = pb;
  250. return id;
  251. }
  252. void RasterizerCanvasRD::free_polygon(PolygonID p_polygon) {
  253. PolygonBuffers *pb_ptr = polygon_buffers.polygons.getptr(p_polygon);
  254. ERR_FAIL_COND(!pb_ptr);
  255. PolygonBuffers &pb = *pb_ptr;
  256. if (pb.indices.is_valid()) {
  257. RD::get_singleton()->free(pb.indices);
  258. }
  259. if (pb.index_buffer.is_valid()) {
  260. RD::get_singleton()->free(pb.index_buffer);
  261. }
  262. RD::get_singleton()->free(pb.vertex_array);
  263. RD::get_singleton()->free(pb.vertex_buffer);
  264. polygon_buffers.polygons.erase(p_polygon);
  265. }
  266. ////////////////////
  267. void RasterizerCanvasRD::_bind_canvas_texture(RD::DrawListID p_draw_list, RID p_texture, RS::CanvasItemTextureFilter p_base_filter, RS::CanvasItemTextureRepeat p_base_repeat, RID &r_last_texture, PushConstant &push_constant, Size2 &r_texpixel_size) {
  268. if (p_texture == RID()) {
  269. p_texture = default_canvas_texture;
  270. }
  271. if (r_last_texture == p_texture) {
  272. return; //nothing to do, its the same
  273. }
  274. RID uniform_set;
  275. Color specular_shininess;
  276. Size2i size;
  277. bool use_normal;
  278. bool use_specular;
  279. bool success = storage->canvas_texture_get_unifom_set(p_texture, p_base_filter, p_base_repeat, shader.default_version_rd_shader, CANVAS_TEXTURE_UNIFORM_SET, uniform_set, size, specular_shininess, use_normal, use_specular);
  280. //something odd happened
  281. if (!success) {
  282. _bind_canvas_texture(p_draw_list, default_canvas_texture, p_base_filter, p_base_repeat, r_last_texture, push_constant, r_texpixel_size);
  283. return;
  284. }
  285. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, uniform_set, CANVAS_TEXTURE_UNIFORM_SET);
  286. if (specular_shininess.a < 0.999) {
  287. push_constant.flags |= FLAGS_DEFAULT_SPECULAR_MAP_USED;
  288. } else {
  289. push_constant.flags &= ~FLAGS_DEFAULT_SPECULAR_MAP_USED;
  290. }
  291. if (use_normal) {
  292. push_constant.flags |= FLAGS_DEFAULT_NORMAL_MAP_USED;
  293. } else {
  294. push_constant.flags &= ~FLAGS_DEFAULT_NORMAL_MAP_USED;
  295. }
  296. push_constant.specular_shininess = uint32_t(CLAMP(specular_shininess.a * 255.0, 0, 255)) << 24;
  297. push_constant.specular_shininess |= uint32_t(CLAMP(specular_shininess.b * 255.0, 0, 255)) << 16;
  298. push_constant.specular_shininess |= uint32_t(CLAMP(specular_shininess.g * 255.0, 0, 255)) << 8;
  299. push_constant.specular_shininess |= uint32_t(CLAMP(specular_shininess.r * 255.0, 0, 255));
  300. r_texpixel_size.x = 1.0 / float(size.x);
  301. r_texpixel_size.y = 1.0 / float(size.y);
  302. push_constant.color_texture_pixel_size[0] = r_texpixel_size.x;
  303. push_constant.color_texture_pixel_size[1] = r_texpixel_size.y;
  304. r_last_texture = p_texture;
  305. }
  306. void RasterizerCanvasRD::_render_item(RD::DrawListID p_draw_list, const Item *p_item, RD::FramebufferFormatID p_framebuffer_format, const Transform2D &p_canvas_transform_inverse, Item *&current_clip, Light *p_lights, PipelineVariants *p_pipeline_variants) {
  307. //create an empty push constant
  308. RS::CanvasItemTextureFilter current_filter = default_filter;
  309. RS::CanvasItemTextureRepeat current_repeat = default_repeat;
  310. if (p_item->texture_filter != RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT) {
  311. current_filter = p_item->texture_filter;
  312. }
  313. if (p_item->texture_repeat != RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT) {
  314. current_repeat = p_item->texture_repeat;
  315. }
  316. PushConstant push_constant;
  317. Transform2D base_transform = p_canvas_transform_inverse * p_item->final_transform;
  318. _update_transform_2d_to_mat2x3(base_transform, push_constant.world);
  319. Color base_color = p_item->final_modulate;
  320. for (int i = 0; i < 4; i++) {
  321. push_constant.modulation[i] = 0;
  322. push_constant.ninepatch_margins[i] = 0;
  323. push_constant.src_rect[i] = 0;
  324. push_constant.dst_rect[i] = 0;
  325. }
  326. push_constant.flags = 0;
  327. push_constant.color_texture_pixel_size[0] = 0;
  328. push_constant.color_texture_pixel_size[1] = 0;
  329. push_constant.pad[0] = 0;
  330. push_constant.pad[1] = 0;
  331. push_constant.lights[0] = 0;
  332. push_constant.lights[1] = 0;
  333. push_constant.lights[2] = 0;
  334. push_constant.lights[3] = 0;
  335. uint32_t base_flags = 0;
  336. uint16_t light_count = 0;
  337. PipelineLightMode light_mode;
  338. {
  339. Light *light = p_lights;
  340. while (light) {
  341. 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_transformed(light->xform_cache, light->rect_cache)) {
  342. uint32_t light_index = light->render_index_cache;
  343. push_constant.lights[light_count >> 2] |= light_index << ((light_count & 3) * 8);
  344. light_count++;
  345. if (light_count == MAX_LIGHTS_PER_ITEM) {
  346. break;
  347. }
  348. }
  349. light = light->next_ptr;
  350. }
  351. base_flags |= light_count << FLAGS_LIGHT_COUNT_SHIFT;
  352. }
  353. light_mode = (light_count > 0 || using_directional_lights) ? PIPELINE_LIGHT_MODE_ENABLED : PIPELINE_LIGHT_MODE_DISABLED;
  354. PipelineVariants *pipeline_variants = p_pipeline_variants;
  355. bool reclip = false;
  356. RID last_texture;
  357. Size2 texpixel_size;
  358. const Item::Command *c = p_item->commands;
  359. while (c) {
  360. push_constant.flags = base_flags | (push_constant.flags & (FLAGS_DEFAULT_NORMAL_MAP_USED | FLAGS_DEFAULT_SPECULAR_MAP_USED)); //reset on each command for sanity, keep canvastexture binding config
  361. switch (c->type) {
  362. case Item::Command::TYPE_RECT: {
  363. const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);
  364. //bind pipeline
  365. {
  366. RID pipeline = pipeline_variants->variants[light_mode][PIPELINE_VARIANT_QUAD].get_render_pipeline(RD::INVALID_ID, p_framebuffer_format);
  367. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  368. }
  369. //bind textures
  370. _bind_canvas_texture(p_draw_list, rect->texture, current_filter, current_repeat, last_texture, push_constant, texpixel_size);
  371. Rect2 src_rect;
  372. Rect2 dst_rect;
  373. if (rect->texture != RID()) {
  374. src_rect = (rect->flags & CANVAS_RECT_REGION) ? Rect2(rect->source.position * texpixel_size, rect->source.size * texpixel_size) : Rect2(0, 0, 1, 1);
  375. dst_rect = Rect2(rect->rect.position, rect->rect.size);
  376. if (dst_rect.size.width < 0) {
  377. dst_rect.position.x += dst_rect.size.width;
  378. dst_rect.size.width *= -1;
  379. }
  380. if (dst_rect.size.height < 0) {
  381. dst_rect.position.y += dst_rect.size.height;
  382. dst_rect.size.height *= -1;
  383. }
  384. if (rect->flags & CANVAS_RECT_FLIP_H) {
  385. src_rect.size.x *= -1;
  386. }
  387. if (rect->flags & CANVAS_RECT_FLIP_V) {
  388. src_rect.size.y *= -1;
  389. }
  390. if (rect->flags & CANVAS_RECT_TRANSPOSE) {
  391. dst_rect.size.x *= -1; // Encoding in the dst_rect.z uniform
  392. }
  393. if (rect->flags & CANVAS_RECT_CLIP_UV) {
  394. push_constant.flags |= FLAGS_CLIP_RECT_UV;
  395. }
  396. } else {
  397. dst_rect = Rect2(rect->rect.position, rect->rect.size);
  398. if (dst_rect.size.width < 0) {
  399. dst_rect.position.x += dst_rect.size.width;
  400. dst_rect.size.width *= -1;
  401. }
  402. if (dst_rect.size.height < 0) {
  403. dst_rect.position.y += dst_rect.size.height;
  404. dst_rect.size.height *= -1;
  405. }
  406. src_rect = Rect2(0, 0, 1, 1);
  407. }
  408. push_constant.modulation[0] = rect->modulate.r * base_color.r;
  409. push_constant.modulation[1] = rect->modulate.g * base_color.g;
  410. push_constant.modulation[2] = rect->modulate.b * base_color.b;
  411. push_constant.modulation[3] = rect->modulate.a * base_color.a;
  412. push_constant.src_rect[0] = src_rect.position.x;
  413. push_constant.src_rect[1] = src_rect.position.y;
  414. push_constant.src_rect[2] = src_rect.size.width;
  415. push_constant.src_rect[3] = src_rect.size.height;
  416. push_constant.dst_rect[0] = dst_rect.position.x;
  417. push_constant.dst_rect[1] = dst_rect.position.y;
  418. push_constant.dst_rect[2] = dst_rect.size.width;
  419. push_constant.dst_rect[3] = dst_rect.size.height;
  420. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  421. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, shader.quad_index_array);
  422. RD::get_singleton()->draw_list_draw(p_draw_list, true);
  423. } break;
  424. case Item::Command::TYPE_NINEPATCH: {
  425. const Item::CommandNinePatch *np = static_cast<const Item::CommandNinePatch *>(c);
  426. //bind pipeline
  427. {
  428. RID pipeline = pipeline_variants->variants[light_mode][PIPELINE_VARIANT_NINEPATCH].get_render_pipeline(RD::INVALID_ID, p_framebuffer_format);
  429. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  430. }
  431. //bind textures
  432. _bind_canvas_texture(p_draw_list, np->texture, current_filter, current_repeat, last_texture, push_constant, texpixel_size);
  433. Rect2 src_rect;
  434. Rect2 dst_rect(np->rect.position.x, np->rect.position.y, np->rect.size.x, np->rect.size.y);
  435. if (np->texture == RID()) {
  436. texpixel_size = Size2(1, 1);
  437. src_rect = Rect2(0, 0, 1, 1);
  438. } else {
  439. if (np->source != Rect2()) {
  440. 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);
  441. push_constant.color_texture_pixel_size[0] = 1.0 / np->source.size.width;
  442. push_constant.color_texture_pixel_size[1] = 1.0 / np->source.size.height;
  443. } else {
  444. src_rect = Rect2(0, 0, 1, 1);
  445. }
  446. }
  447. push_constant.modulation[0] = np->color.r * base_color.r;
  448. push_constant.modulation[1] = np->color.g * base_color.g;
  449. push_constant.modulation[2] = np->color.b * base_color.b;
  450. push_constant.modulation[3] = np->color.a * base_color.a;
  451. push_constant.src_rect[0] = src_rect.position.x;
  452. push_constant.src_rect[1] = src_rect.position.y;
  453. push_constant.src_rect[2] = src_rect.size.width;
  454. push_constant.src_rect[3] = src_rect.size.height;
  455. push_constant.dst_rect[0] = dst_rect.position.x;
  456. push_constant.dst_rect[1] = dst_rect.position.y;
  457. push_constant.dst_rect[2] = dst_rect.size.width;
  458. push_constant.dst_rect[3] = dst_rect.size.height;
  459. push_constant.flags |= int(np->axis_x) << FLAGS_NINEPATCH_H_MODE_SHIFT;
  460. push_constant.flags |= int(np->axis_y) << FLAGS_NINEPATCH_V_MODE_SHIFT;
  461. if (np->draw_center) {
  462. push_constant.flags |= FLAGS_NINEPACH_DRAW_CENTER;
  463. }
  464. push_constant.ninepatch_margins[0] = np->margin[MARGIN_LEFT];
  465. push_constant.ninepatch_margins[1] = np->margin[MARGIN_TOP];
  466. push_constant.ninepatch_margins[2] = np->margin[MARGIN_RIGHT];
  467. push_constant.ninepatch_margins[3] = np->margin[MARGIN_BOTTOM];
  468. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  469. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, shader.quad_index_array);
  470. RD::get_singleton()->draw_list_draw(p_draw_list, true);
  471. //restore if overrided
  472. push_constant.color_texture_pixel_size[0] = texpixel_size.x;
  473. push_constant.color_texture_pixel_size[1] = texpixel_size.y;
  474. } break;
  475. case Item::Command::TYPE_POLYGON: {
  476. const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c);
  477. PolygonBuffers *pb = polygon_buffers.polygons.getptr(polygon->polygon.polygon_id);
  478. ERR_CONTINUE(!pb);
  479. //bind pipeline
  480. {
  481. static const PipelineVariant variant[RS::PRIMITIVE_MAX] = { PIPELINE_VARIANT_ATTRIBUTE_POINTS, PIPELINE_VARIANT_ATTRIBUTE_LINES, PIPELINE_VARIANT_ATTRIBUTE_LINES_STRIP, PIPELINE_VARIANT_ATTRIBUTE_TRIANGLES, PIPELINE_VARIANT_ATTRIBUTE_TRIANGLE_STRIP };
  482. ERR_CONTINUE(polygon->primitive < 0 || polygon->primitive >= RS::PRIMITIVE_MAX);
  483. RID pipeline = pipeline_variants->variants[light_mode][variant[polygon->primitive]].get_render_pipeline(pb->vertex_format_id, p_framebuffer_format);
  484. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  485. }
  486. if (polygon->primitive == RS::PRIMITIVE_LINES) {
  487. //not supported in most hardware, so pointless
  488. //RD::get_singleton()->draw_list_set_line_width(p_draw_list, polygon->line_width);
  489. }
  490. //bind textures
  491. _bind_canvas_texture(p_draw_list, polygon->texture, current_filter, current_repeat, last_texture, push_constant, texpixel_size);
  492. push_constant.modulation[0] = base_color.r;
  493. push_constant.modulation[1] = base_color.g;
  494. push_constant.modulation[2] = base_color.b;
  495. push_constant.modulation[3] = base_color.a;
  496. for (int j = 0; j < 4; j++) {
  497. push_constant.src_rect[j] = 0;
  498. push_constant.dst_rect[j] = 0;
  499. push_constant.ninepatch_margins[j] = 0;
  500. }
  501. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  502. RD::get_singleton()->draw_list_bind_vertex_array(p_draw_list, pb->vertex_array);
  503. if (pb->indices.is_valid()) {
  504. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, pb->indices);
  505. }
  506. RD::get_singleton()->draw_list_draw(p_draw_list, pb->indices.is_valid());
  507. } break;
  508. case Item::Command::TYPE_PRIMITIVE: {
  509. const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c);
  510. //bind pipeline
  511. {
  512. static const PipelineVariant variant[4] = { PIPELINE_VARIANT_PRIMITIVE_POINTS, PIPELINE_VARIANT_PRIMITIVE_LINES, PIPELINE_VARIANT_PRIMITIVE_TRIANGLES, PIPELINE_VARIANT_PRIMITIVE_TRIANGLES };
  513. ERR_CONTINUE(primitive->point_count == 0 || primitive->point_count > 4);
  514. RID pipeline = pipeline_variants->variants[light_mode][variant[primitive->point_count - 1]].get_render_pipeline(RD::INVALID_ID, p_framebuffer_format);
  515. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  516. }
  517. //bind textures
  518. _bind_canvas_texture(p_draw_list, RID(), current_filter, current_repeat, last_texture, push_constant, texpixel_size);
  519. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, primitive_arrays.index_array[MIN(3, primitive->point_count) - 1]);
  520. for (uint32_t j = 0; j < MIN(3, primitive->point_count); j++) {
  521. push_constant.points[j * 2 + 0] = primitive->points[j].x;
  522. push_constant.points[j * 2 + 1] = primitive->points[j].y;
  523. push_constant.uvs[j * 2 + 0] = primitive->uvs[j].x;
  524. push_constant.uvs[j * 2 + 1] = primitive->uvs[j].y;
  525. Color col = primitive->colors[j] * base_color;
  526. push_constant.colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
  527. push_constant.colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
  528. }
  529. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  530. RD::get_singleton()->draw_list_draw(p_draw_list, true);
  531. if (primitive->point_count == 4) {
  532. for (uint32_t j = 1; j < 3; j++) {
  533. //second half of triangle
  534. push_constant.points[j * 2 + 0] = primitive->points[j + 1].x;
  535. push_constant.points[j * 2 + 1] = primitive->points[j + 1].y;
  536. push_constant.uvs[j * 2 + 0] = primitive->uvs[j + 1].x;
  537. push_constant.uvs[j * 2 + 1] = primitive->uvs[j + 1].y;
  538. Color col = primitive->colors[j + 1] * base_color;
  539. push_constant.colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
  540. push_constant.colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
  541. }
  542. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  543. RD::get_singleton()->draw_list_draw(p_draw_list, true);
  544. }
  545. } break;
  546. case Item::Command::TYPE_MESH:
  547. case Item::Command::TYPE_MULTIMESH:
  548. case Item::Command::TYPE_PARTICLES: {
  549. ERR_PRINT("FIXME: Mesh, MultiMesh and Particles render commands are unimplemented currently, they need to be ported to the 4.0 rendering architecture.");
  550. #ifndef _MSC_VER
  551. #warning Item::Command types for Mesh, MultiMesh and Particles need to be implemented.
  552. #endif
  553. // See #if 0'ed code below to port from GLES3.
  554. } break;
  555. #if 0
  556. case Item::Command::TYPE_MESH: {
  557. Item::CommandMesh *mesh = static_cast<Item::CommandMesh *>(c);
  558. _set_texture_rect_mode(false);
  559. RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(mesh->texture, mesh->normal_map);
  560. if (texture) {
  561. Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
  562. state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
  563. }
  564. state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform * mesh->transform);
  565. RasterizerStorageGLES3::Mesh *mesh_data = storage->mesh_owner.getornull(mesh->mesh);
  566. if (mesh_data) {
  567. for (int j = 0; j < mesh_data->surfaces.size(); j++) {
  568. RasterizerStorageGLES3::Surface *s = mesh_data->surfaces[j];
  569. // materials are ignored in 2D meshes, could be added but many things (ie, lighting mode, reading from screen, etc) would break as they are not meant be set up at this point of drawing
  570. glBindVertexArray(s->array_id);
  571. glVertexAttrib4f(RS::ARRAY_COLOR, mesh->modulate.r, mesh->modulate.g, mesh->modulate.b, mesh->modulate.a);
  572. if (s->index_array_len) {
  573. glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
  574. } else {
  575. glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
  576. }
  577. glBindVertexArray(0);
  578. }
  579. }
  580. state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform);
  581. } break;
  582. case Item::Command::TYPE_MULTIMESH: {
  583. Item::CommandMultiMesh *mmesh = static_cast<Item::CommandMultiMesh *>(c);
  584. RasterizerStorageGLES3::MultiMesh *multi_mesh = storage->multimesh_owner.getornull(mmesh->multimesh);
  585. if (!multi_mesh)
  586. break;
  587. RasterizerStorageGLES3::Mesh *mesh_data = storage->mesh_owner.getornull(multi_mesh->mesh);
  588. if (!mesh_data)
  589. break;
  590. RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(mmesh->texture, mmesh->normal_map);
  591. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, multi_mesh->custom_data_format != RS::MULTIMESH_CUSTOM_DATA_NONE);
  592. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, true);
  593. //reset shader and force rebind
  594. state.using_texture_rect = true;
  595. _set_texture_rect_mode(false);
  596. if (texture) {
  597. Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
  598. state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
  599. }
  600. int amount = MIN(multi_mesh->size, multi_mesh->visible_instances);
  601. if (amount == -1) {
  602. amount = multi_mesh->size;
  603. }
  604. for (int j = 0; j < mesh_data->surfaces.size(); j++) {
  605. RasterizerStorageGLES3::Surface *s = mesh_data->surfaces[j];
  606. // materials are ignored in 2D meshes, could be added but many things (ie, lighting mode, reading from screen, etc) would break as they are not meant be set up at this point of drawing
  607. glBindVertexArray(s->instancing_array_id);
  608. glBindBuffer(GL_ARRAY_BUFFER, multi_mesh->buffer); //modify the buffer
  609. int stride = (multi_mesh->xform_floats + multi_mesh->color_floats + multi_mesh->custom_data_floats) * 4;
  610. glEnableVertexAttribArray(8);
  611. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(0));
  612. glVertexAttribDivisor(8, 1);
  613. glEnableVertexAttribArray(9);
  614. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(4 * 4));
  615. glVertexAttribDivisor(9, 1);
  616. int color_ofs;
  617. if (multi_mesh->transform_format == RS::MULTIMESH_TRANSFORM_3D) {
  618. glEnableVertexAttribArray(10);
  619. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(8 * 4));
  620. glVertexAttribDivisor(10, 1);
  621. color_ofs = 12 * 4;
  622. } else {
  623. glDisableVertexAttribArray(10);
  624. glVertexAttrib4f(10, 0, 0, 1, 0);
  625. color_ofs = 8 * 4;
  626. }
  627. int custom_data_ofs = color_ofs;
  628. switch (multi_mesh->color_format) {
  629. case RS::MULTIMESH_COLOR_NONE: {
  630. glDisableVertexAttribArray(11);
  631. glVertexAttrib4f(11, 1, 1, 1, 1);
  632. } break;
  633. case RS::MULTIMESH_COLOR_8BIT: {
  634. glEnableVertexAttribArray(11);
  635. glVertexAttribPointer(11, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs));
  636. glVertexAttribDivisor(11, 1);
  637. custom_data_ofs += 4;
  638. } break;
  639. case RS::MULTIMESH_COLOR_FLOAT: {
  640. glEnableVertexAttribArray(11);
  641. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs));
  642. glVertexAttribDivisor(11, 1);
  643. custom_data_ofs += 4 * 4;
  644. } break;
  645. }
  646. switch (multi_mesh->custom_data_format) {
  647. case RS::MULTIMESH_CUSTOM_DATA_NONE: {
  648. glDisableVertexAttribArray(12);
  649. glVertexAttrib4f(12, 1, 1, 1, 1);
  650. } break;
  651. case RS::MULTIMESH_CUSTOM_DATA_8BIT: {
  652. glEnableVertexAttribArray(12);
  653. glVertexAttribPointer(12, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs));
  654. glVertexAttribDivisor(12, 1);
  655. } break;
  656. case RS::MULTIMESH_CUSTOM_DATA_FLOAT: {
  657. glEnableVertexAttribArray(12);
  658. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs));
  659. glVertexAttribDivisor(12, 1);
  660. } break;
  661. }
  662. if (s->index_array_len) {
  663. glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount);
  664. } else {
  665. glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount);
  666. }
  667. glBindVertexArray(0);
  668. }
  669. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, false);
  670. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, false);
  671. state.using_texture_rect = true;
  672. _set_texture_rect_mode(false);
  673. } break;
  674. case Item::Command::TYPE_PARTICLES: {
  675. Item::CommandParticles *particles_cmd = static_cast<Item::CommandParticles *>(c);
  676. RasterizerStorageGLES3::Particles *particles = storage->particles_owner.getornull(particles_cmd->particles);
  677. if (!particles)
  678. break;
  679. if (particles->inactive && !particles->emitting)
  680. break;
  681. glVertexAttrib4f(RS::ARRAY_COLOR, 1, 1, 1, 1); //not used, so keep white
  682. RenderingServerRaster::redraw_request();
  683. storage->particles_request_process(particles_cmd->particles);
  684. //enable instancing
  685. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, true);
  686. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_PARTICLES, true);
  687. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, true);
  688. //reset shader and force rebind
  689. state.using_texture_rect = true;
  690. _set_texture_rect_mode(false);
  691. RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(particles_cmd->texture, particles_cmd->normal_map);
  692. if (texture) {
  693. Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
  694. state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
  695. } else {
  696. state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, Vector2(1.0, 1.0));
  697. }
  698. if (!particles->use_local_coords) {
  699. Transform2D inv_xf;
  700. inv_xf.set_axis(0, Vector2(particles->emission_transform.basis.get_axis(0).x, particles->emission_transform.basis.get_axis(0).y));
  701. inv_xf.set_axis(1, Vector2(particles->emission_transform.basis.get_axis(1).x, particles->emission_transform.basis.get_axis(1).y));
  702. inv_xf.set_origin(Vector2(particles->emission_transform.get_origin().x, particles->emission_transform.get_origin().y));
  703. inv_xf.affine_invert();
  704. state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform * inv_xf);
  705. }
  706. glBindVertexArray(data.particle_quad_array); //use particle quad array
  707. glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]); //bind particle buffer
  708. int stride = sizeof(float) * 4 * 6;
  709. int amount = particles->amount;
  710. if (particles->draw_order != RS::PARTICLES_DRAW_ORDER_LIFETIME) {
  711. glEnableVertexAttribArray(8); //xform x
  712. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3));
  713. glVertexAttribDivisor(8, 1);
  714. glEnableVertexAttribArray(9); //xform y
  715. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4));
  716. glVertexAttribDivisor(9, 1);
  717. glEnableVertexAttribArray(10); //xform z
  718. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5));
  719. glVertexAttribDivisor(10, 1);
  720. glEnableVertexAttribArray(11); //color
  721. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, nullptr);
  722. glVertexAttribDivisor(11, 1);
  723. glEnableVertexAttribArray(12); //custom
  724. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2));
  725. glVertexAttribDivisor(12, 1);
  726. glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, amount);
  727. } else {
  728. //split
  729. int split = int(Math::ceil(particles->phase * particles->amount));
  730. if (amount - split > 0) {
  731. glEnableVertexAttribArray(8); //xform x
  732. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 3));
  733. glVertexAttribDivisor(8, 1);
  734. glEnableVertexAttribArray(9); //xform y
  735. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 4));
  736. glVertexAttribDivisor(9, 1);
  737. glEnableVertexAttribArray(10); //xform z
  738. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 5));
  739. glVertexAttribDivisor(10, 1);
  740. glEnableVertexAttribArray(11); //color
  741. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + 0));
  742. glVertexAttribDivisor(11, 1);
  743. glEnableVertexAttribArray(12); //custom
  744. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 2));
  745. glVertexAttribDivisor(12, 1);
  746. glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, amount - split);
  747. }
  748. if (split > 0) {
  749. glEnableVertexAttribArray(8); //xform x
  750. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3));
  751. glVertexAttribDivisor(8, 1);
  752. glEnableVertexAttribArray(9); //xform y
  753. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4));
  754. glVertexAttribDivisor(9, 1);
  755. glEnableVertexAttribArray(10); //xform z
  756. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5));
  757. glVertexAttribDivisor(10, 1);
  758. glEnableVertexAttribArray(11); //color
  759. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, nullptr);
  760. glVertexAttribDivisor(11, 1);
  761. glEnableVertexAttribArray(12); //custom
  762. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2));
  763. glVertexAttribDivisor(12, 1);
  764. glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, split);
  765. }
  766. }
  767. glBindVertexArray(0);
  768. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, false);
  769. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_PARTICLES, false);
  770. state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, false);
  771. state.using_texture_rect = true;
  772. _set_texture_rect_mode(false);
  773. } break;
  774. #endif
  775. case Item::Command::TYPE_TRANSFORM: {
  776. const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c);
  777. _update_transform_2d_to_mat2x3(base_transform * transform->xform, push_constant.world);
  778. } break;
  779. case Item::Command::TYPE_CLIP_IGNORE: {
  780. const Item::CommandClipIgnore *ci = static_cast<const Item::CommandClipIgnore *>(c);
  781. if (current_clip) {
  782. if (ci->ignore != reclip) {
  783. if (ci->ignore) {
  784. RD::get_singleton()->draw_list_disable_scissor(p_draw_list);
  785. reclip = true;
  786. } else {
  787. RD::get_singleton()->draw_list_enable_scissor(p_draw_list, current_clip->final_clip_rect);
  788. reclip = false;
  789. }
  790. }
  791. }
  792. } break;
  793. }
  794. c = c->next;
  795. }
  796. if (current_clip && reclip) {
  797. //will make it re-enable clipping if needed afterwards
  798. current_clip = nullptr;
  799. }
  800. }
  801. RID RasterizerCanvasRD::_create_base_uniform_set(RID p_to_render_target, bool p_backbuffer) {
  802. //re create canvas state
  803. Vector<RD::Uniform> uniforms;
  804. {
  805. RD::Uniform u;
  806. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  807. u.binding = 1;
  808. u.ids.push_back(state.canvas_state_buffer);
  809. uniforms.push_back(u);
  810. }
  811. {
  812. RD::Uniform u;
  813. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  814. u.binding = 2;
  815. u.ids.push_back(state.lights_uniform_buffer);
  816. uniforms.push_back(u);
  817. }
  818. {
  819. RD::Uniform u;
  820. u.type = RD::UNIFORM_TYPE_TEXTURE;
  821. u.binding = 3;
  822. u.ids.push_back(storage->decal_atlas_get_texture());
  823. uniforms.push_back(u);
  824. }
  825. {
  826. RD::Uniform u;
  827. u.type = RD::UNIFORM_TYPE_TEXTURE;
  828. u.binding = 4;
  829. u.ids.push_back(state.shadow_texture);
  830. uniforms.push_back(u);
  831. }
  832. {
  833. RD::Uniform u;
  834. u.type = RD::UNIFORM_TYPE_SAMPLER;
  835. u.binding = 5;
  836. u.ids.push_back(state.shadow_sampler);
  837. uniforms.push_back(u);
  838. }
  839. {
  840. RD::Uniform u;
  841. u.type = RD::UNIFORM_TYPE_TEXTURE;
  842. u.binding = 6;
  843. RID screen;
  844. if (p_backbuffer) {
  845. screen = storage->render_target_get_rd_texture(p_to_render_target);
  846. } else {
  847. screen = storage->render_target_get_rd_backbuffer(p_to_render_target);
  848. if (screen.is_null()) { //unallocated backbuffer
  849. screen = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE);
  850. }
  851. }
  852. u.ids.push_back(screen);
  853. uniforms.push_back(u);
  854. }
  855. {
  856. //needs samplers for the material (uses custom textures) create them
  857. RD::Uniform u;
  858. u.type = RD::UNIFORM_TYPE_SAMPLER;
  859. u.binding = 7;
  860. u.ids.resize(12);
  861. RID *ids_ptr = u.ids.ptrw();
  862. ids_ptr[0] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  863. ids_ptr[1] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  864. ids_ptr[2] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  865. ids_ptr[3] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  866. ids_ptr[4] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  867. ids_ptr[5] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  868. ids_ptr[6] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  869. ids_ptr[7] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  870. ids_ptr[8] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  871. ids_ptr[9] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  872. ids_ptr[10] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  873. ids_ptr[11] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  874. uniforms.push_back(u);
  875. }
  876. {
  877. RD::Uniform u;
  878. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  879. u.binding = 8;
  880. u.ids.push_back(storage->global_variables_get_storage_buffer());
  881. uniforms.push_back(u);
  882. }
  883. RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader, BASE_UNIFORM_SET);
  884. if (p_backbuffer) {
  885. storage->render_target_set_backbuffer_uniform_set(p_to_render_target, uniform_set);
  886. } else {
  887. storage->render_target_set_framebuffer_uniform_set(p_to_render_target, uniform_set);
  888. }
  889. return uniform_set;
  890. }
  891. void RasterizerCanvasRD::_render_items(RID p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, bool p_to_backbuffer) {
  892. Item *current_clip = nullptr;
  893. Transform2D canvas_transform_inverse = p_canvas_transform_inverse;
  894. RID framebuffer;
  895. RID fb_uniform_set;
  896. bool clear = false;
  897. Vector<Color> clear_colors;
  898. if (p_to_backbuffer) {
  899. framebuffer = storage->render_target_get_rd_backbuffer_framebuffer(p_to_render_target);
  900. fb_uniform_set = storage->render_target_get_backbuffer_uniform_set(p_to_render_target);
  901. } else {
  902. framebuffer = storage->render_target_get_rd_framebuffer(p_to_render_target);
  903. if (storage->render_target_is_clear_requested(p_to_render_target)) {
  904. clear = true;
  905. clear_colors.push_back(storage->render_target_get_clear_request_color(p_to_render_target));
  906. storage->render_target_disable_clear_request(p_to_render_target);
  907. }
  908. #ifndef _MSC_VER
  909. #warning TODO obtain from framebuffer format eventually when this is implemented
  910. #endif
  911. fb_uniform_set = storage->render_target_get_framebuffer_uniform_set(p_to_render_target);
  912. }
  913. if (fb_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(fb_uniform_set)) {
  914. fb_uniform_set = _create_base_uniform_set(p_to_render_target, p_to_backbuffer);
  915. }
  916. RD::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(framebuffer);
  917. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(framebuffer, clear ? RD::INITIAL_ACTION_CLEAR : RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD, clear_colors);
  918. RD::get_singleton()->draw_list_bind_uniform_set(draw_list, fb_uniform_set, BASE_UNIFORM_SET);
  919. RD::get_singleton()->draw_list_bind_uniform_set(draw_list, state.default_transforms_uniform_set, TRANSFORMS_UNIFORM_SET);
  920. RID prev_material;
  921. PipelineVariants *pipeline_variants = &shader.pipeline_variants;
  922. for (int i = 0; i < p_item_count; i++) {
  923. Item *ci = items[i];
  924. if (current_clip != ci->final_clip_owner) {
  925. current_clip = ci->final_clip_owner;
  926. //setup clip
  927. if (current_clip) {
  928. RD::get_singleton()->draw_list_enable_scissor(draw_list, current_clip->final_clip_rect);
  929. } else {
  930. RD::get_singleton()->draw_list_disable_scissor(draw_list);
  931. }
  932. }
  933. RID material = ci->material;
  934. if (material.is_null() && ci->canvas_group != nullptr) {
  935. material = default_canvas_group_material;
  936. }
  937. if (material != prev_material) {
  938. MaterialData *material_data = nullptr;
  939. if (material.is_valid()) {
  940. material_data = (MaterialData *)storage->material_get_data(material, RasterizerStorageRD::SHADER_TYPE_2D);
  941. }
  942. if (material_data) {
  943. if (material_data->shader_data->version.is_valid() && material_data->shader_data->valid) {
  944. pipeline_variants = &material_data->shader_data->pipeline_variants;
  945. if (material_data->uniform_set.is_valid()) {
  946. RD::get_singleton()->draw_list_bind_uniform_set(draw_list, material_data->uniform_set, MATERIAL_UNIFORM_SET);
  947. }
  948. } else {
  949. pipeline_variants = &shader.pipeline_variants;
  950. }
  951. } else {
  952. pipeline_variants = &shader.pipeline_variants;
  953. }
  954. }
  955. _render_item(draw_list, ci, fb_format, canvas_transform_inverse, current_clip, p_lights, pipeline_variants);
  956. prev_material = material;
  957. }
  958. RD::get_singleton()->draw_list_end();
  959. }
  960. void RasterizerCanvasRD::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, RenderingServer::CanvasItemTextureFilter p_default_filter, RenderingServer::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel) {
  961. int item_count = 0;
  962. //setup canvas state uniforms if needed
  963. Transform2D canvas_transform_inverse = p_canvas_transform.affine_inverse();
  964. //setup directional lights if exist
  965. uint32_t light_count = 0;
  966. uint32_t directional_light_count = 0;
  967. {
  968. Light *l = p_directional_light_list;
  969. uint32_t index = 0;
  970. while (l) {
  971. if (index == state.max_lights_per_render) {
  972. l->render_index_cache = -1;
  973. l = l->next_ptr;
  974. continue;
  975. }
  976. CanvasLight *clight = canvas_light_owner.getornull(l->light_internal);
  977. if (!clight) { //unused or invalid texture
  978. l->render_index_cache = -1;
  979. l = l->next_ptr;
  980. ERR_CONTINUE(!clight);
  981. }
  982. Vector2 canvas_light_dir = l->xform_cache.elements[1].normalized();
  983. state.light_uniforms[index].position[0] = -canvas_light_dir.x;
  984. state.light_uniforms[index].position[1] = -canvas_light_dir.y;
  985. _update_transform_2d_to_mat2x4(clight->shadow.directional_xform, state.light_uniforms[index].shadow_matrix);
  986. state.light_uniforms[index].height = l->height; //0..1 here
  987. for (int i = 0; i < 4; i++) {
  988. state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
  989. state.light_uniforms[index].color[i] = l->color[i];
  990. }
  991. state.light_uniforms[index].color[3] = l->energy; //use alpha for energy, so base color can go separate
  992. if (state.shadow_fb.is_valid()) {
  993. state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
  994. state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
  995. state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
  996. } else {
  997. state.light_uniforms[index].shadow_pixel_size = 1.0;
  998. state.light_uniforms[index].shadow_z_far_inv = 1.0;
  999. state.light_uniforms[index].shadow_y_ofs = 0;
  1000. }
  1001. state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
  1002. state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
  1003. if (clight->shadow.enabled) {
  1004. state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
  1005. }
  1006. l->render_index_cache = index;
  1007. index++;
  1008. l = l->next_ptr;
  1009. }
  1010. light_count = index;
  1011. directional_light_count = light_count;
  1012. using_directional_lights = directional_light_count > 0;
  1013. }
  1014. //setup lights if exist
  1015. {
  1016. Light *l = p_light_list;
  1017. uint32_t index = light_count;
  1018. while (l) {
  1019. if (index == state.max_lights_per_render) {
  1020. l->render_index_cache = -1;
  1021. l = l->next_ptr;
  1022. continue;
  1023. }
  1024. CanvasLight *clight = canvas_light_owner.getornull(l->light_internal);
  1025. if (!clight) { //unused or invalid texture
  1026. l->render_index_cache = -1;
  1027. l = l->next_ptr;
  1028. ERR_CONTINUE(!clight);
  1029. }
  1030. Transform2D to_light_xform = (p_canvas_transform * l->light_shader_xform).affine_inverse();
  1031. Vector2 canvas_light_pos = p_canvas_transform.xform(l->xform.get_origin()); //convert light position to canvas coordinates, as all computation is done in canvas coords to avoid precision loss
  1032. state.light_uniforms[index].position[0] = canvas_light_pos.x;
  1033. state.light_uniforms[index].position[1] = canvas_light_pos.y;
  1034. _update_transform_2d_to_mat2x4(to_light_xform, state.light_uniforms[index].matrix);
  1035. _update_transform_2d_to_mat2x4(l->xform_cache.affine_inverse(), state.light_uniforms[index].shadow_matrix);
  1036. state.light_uniforms[index].height = l->height * (p_canvas_transform.elements[0].length() + p_canvas_transform.elements[1].length()) * 0.5; //approximate height conversion to the canvas size, since all calculations are done in canvas coords to avoid precision loss
  1037. for (int i = 0; i < 4; i++) {
  1038. state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
  1039. state.light_uniforms[index].color[i] = l->color[i];
  1040. }
  1041. state.light_uniforms[index].color[3] = l->energy; //use alpha for energy, so base color can go separate
  1042. if (state.shadow_fb.is_valid()) {
  1043. state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
  1044. state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
  1045. state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
  1046. } else {
  1047. state.light_uniforms[index].shadow_pixel_size = 1.0;
  1048. state.light_uniforms[index].shadow_z_far_inv = 1.0;
  1049. state.light_uniforms[index].shadow_y_ofs = 0;
  1050. }
  1051. state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
  1052. state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
  1053. if (clight->shadow.enabled) {
  1054. state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
  1055. }
  1056. if (clight->texture.is_valid()) {
  1057. Rect2 atlas_rect = storage->decal_atlas_get_texture_rect(clight->texture);
  1058. state.light_uniforms[index].atlas_rect[0] = atlas_rect.position.x;
  1059. state.light_uniforms[index].atlas_rect[1] = atlas_rect.position.y;
  1060. state.light_uniforms[index].atlas_rect[2] = atlas_rect.size.width;
  1061. state.light_uniforms[index].atlas_rect[3] = atlas_rect.size.height;
  1062. } else {
  1063. state.light_uniforms[index].atlas_rect[0] = 0;
  1064. state.light_uniforms[index].atlas_rect[1] = 0;
  1065. state.light_uniforms[index].atlas_rect[2] = 0;
  1066. state.light_uniforms[index].atlas_rect[3] = 0;
  1067. }
  1068. l->render_index_cache = index;
  1069. index++;
  1070. l = l->next_ptr;
  1071. }
  1072. light_count = index;
  1073. }
  1074. if (light_count > 0) {
  1075. RD::get_singleton()->buffer_update(state.lights_uniform_buffer, 0, sizeof(LightUniform) * light_count, &state.light_uniforms[0], true);
  1076. }
  1077. {
  1078. //update canvas state uniform buffer
  1079. State::Buffer state_buffer;
  1080. Size2i ssize = storage->render_target_get_size(p_to_render_target);
  1081. Transform screen_transform;
  1082. screen_transform.translate(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f);
  1083. screen_transform.scale(Vector3(2.0f / ssize.width, 2.0f / ssize.height, 1.0f));
  1084. _update_transform_to_mat4(screen_transform, state_buffer.screen_transform);
  1085. _update_transform_2d_to_mat4(p_canvas_transform, state_buffer.canvas_transform);
  1086. Transform2D normal_transform = p_canvas_transform;
  1087. normal_transform.elements[0].normalize();
  1088. normal_transform.elements[1].normalize();
  1089. normal_transform.elements[2] = Vector2();
  1090. _update_transform_2d_to_mat4(normal_transform, state_buffer.canvas_normal_transform);
  1091. state_buffer.canvas_modulate[0] = p_modulate.r;
  1092. state_buffer.canvas_modulate[1] = p_modulate.g;
  1093. state_buffer.canvas_modulate[2] = p_modulate.b;
  1094. state_buffer.canvas_modulate[3] = p_modulate.a;
  1095. Size2 render_target_size = storage->render_target_get_size(p_to_render_target);
  1096. state_buffer.screen_pixel_size[0] = 1.0 / render_target_size.x;
  1097. state_buffer.screen_pixel_size[1] = 1.0 / render_target_size.y;
  1098. state_buffer.time = state.time;
  1099. state_buffer.use_pixel_snap = p_snap_2d_vertices_to_pixel;
  1100. state_buffer.directional_light_count = directional_light_count;
  1101. RD::get_singleton()->buffer_update(state.canvas_state_buffer, 0, sizeof(State::Buffer), &state_buffer, true);
  1102. }
  1103. { //default filter/repeat
  1104. default_filter = p_default_filter;
  1105. default_repeat = p_default_repeat;
  1106. }
  1107. //fill the list until rendering is possible.
  1108. bool material_screen_texture_found = false;
  1109. Item *ci = p_item_list;
  1110. Rect2 back_buffer_rect;
  1111. bool backbuffer_copy = false;
  1112. Item *canvas_group_owner = nullptr;
  1113. while (ci) {
  1114. if (ci->copy_back_buffer && canvas_group_owner == nullptr) {
  1115. backbuffer_copy = true;
  1116. if (ci->copy_back_buffer->full) {
  1117. back_buffer_rect = Rect2();
  1118. } else {
  1119. back_buffer_rect = ci->copy_back_buffer->rect;
  1120. }
  1121. }
  1122. if (ci->material.is_valid()) {
  1123. MaterialData *md = (MaterialData *)storage->material_get_data(ci->material, RasterizerStorageRD::SHADER_TYPE_2D);
  1124. if (md && md->shader_data->valid) {
  1125. if (md->shader_data->uses_screen_texture && canvas_group_owner == nullptr) {
  1126. if (!material_screen_texture_found) {
  1127. backbuffer_copy = true;
  1128. back_buffer_rect = Rect2();
  1129. }
  1130. }
  1131. if (md->last_frame != RasterizerRD::singleton->get_frame_number()) {
  1132. md->last_frame = RasterizerRD::singleton->get_frame_number();
  1133. if (!RD::get_singleton()->uniform_set_is_valid(md->uniform_set)) {
  1134. // uniform set may be gone because a dependency was erased. In this case, it will happen
  1135. // if a texture is deleted, so just re-create it.
  1136. storage->material_force_update_textures(ci->material, RasterizerStorageRD::SHADER_TYPE_2D);
  1137. }
  1138. }
  1139. }
  1140. }
  1141. if (ci->canvas_group_owner != nullptr) {
  1142. if (canvas_group_owner == nullptr) {
  1143. //Canvas group begins here, render until before this item
  1144. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list);
  1145. item_count = 0;
  1146. Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
  1147. if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_OPAQUE) {
  1148. storage->render_target_copy_to_back_buffer(p_to_render_target, group_rect, false);
  1149. } else {
  1150. storage->render_target_clear_back_buffer(p_to_render_target, group_rect, Color(0, 0, 0, 0));
  1151. }
  1152. backbuffer_copy = false;
  1153. canvas_group_owner = ci->canvas_group_owner; //continue until owner found
  1154. }
  1155. ci->canvas_group_owner = nullptr; //must be cleared
  1156. }
  1157. if (ci == canvas_group_owner) {
  1158. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, true);
  1159. item_count = 0;
  1160. if (ci->canvas_group->blur_mipmaps) {
  1161. storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, ci->global_rect_cache);
  1162. }
  1163. canvas_group_owner = nullptr;
  1164. }
  1165. if (backbuffer_copy) {
  1166. //render anything pending, including clearing if no items
  1167. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list);
  1168. item_count = 0;
  1169. storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, true);
  1170. backbuffer_copy = false;
  1171. material_screen_texture_found = true; //after a backbuffer copy, screen texture makes no further copies
  1172. }
  1173. items[item_count++] = ci;
  1174. if (!ci->next || item_count == MAX_RENDER_ITEMS - 1) {
  1175. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list);
  1176. //then reset
  1177. item_count = 0;
  1178. }
  1179. ci = ci->next;
  1180. }
  1181. }
  1182. RID RasterizerCanvasRD::light_create() {
  1183. CanvasLight canvas_light;
  1184. return canvas_light_owner.make_rid(canvas_light);
  1185. }
  1186. void RasterizerCanvasRD::light_set_texture(RID p_rid, RID p_texture) {
  1187. CanvasLight *cl = canvas_light_owner.getornull(p_rid);
  1188. ERR_FAIL_COND(!cl);
  1189. if (cl->texture == p_texture) {
  1190. return;
  1191. }
  1192. if (cl->texture.is_valid()) {
  1193. storage->texture_remove_from_decal_atlas(cl->texture);
  1194. }
  1195. cl->texture = p_texture;
  1196. if (cl->texture.is_valid()) {
  1197. storage->texture_add_to_decal_atlas(cl->texture);
  1198. }
  1199. }
  1200. void RasterizerCanvasRD::light_set_use_shadow(RID p_rid, bool p_enable) {
  1201. CanvasLight *cl = canvas_light_owner.getornull(p_rid);
  1202. ERR_FAIL_COND(!cl);
  1203. cl->shadow.enabled = p_enable;
  1204. }
  1205. void RasterizerCanvasRD::_update_shadow_atlas() {
  1206. if (state.shadow_fb == RID()) {
  1207. //ah, we lack the shadow texture..
  1208. RD::get_singleton()->free(state.shadow_texture); //erase placeholder
  1209. Vector<RID> fb_textures;
  1210. { //texture
  1211. RD::TextureFormat tf;
  1212. tf.type = RD::TEXTURE_TYPE_2D;
  1213. tf.width = state.shadow_texture_size;
  1214. tf.height = state.max_lights_per_render * 2;
  1215. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  1216. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  1217. state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1218. fb_textures.push_back(state.shadow_texture);
  1219. }
  1220. {
  1221. RD::TextureFormat tf;
  1222. tf.type = RD::TEXTURE_TYPE_2D;
  1223. tf.width = state.shadow_texture_size;
  1224. tf.height = state.max_lights_per_render * 2;
  1225. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1226. tf.format = RD::DATA_FORMAT_D32_SFLOAT;
  1227. //chunks to write
  1228. state.shadow_depth_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1229. fb_textures.push_back(state.shadow_depth_texture);
  1230. }
  1231. state.shadow_fb = RD::get_singleton()->framebuffer_create(fb_textures);
  1232. }
  1233. }
  1234. void RasterizerCanvasRD::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) {
  1235. CanvasLight *cl = canvas_light_owner.getornull(p_rid);
  1236. ERR_FAIL_COND(!cl->shadow.enabled);
  1237. _update_shadow_atlas();
  1238. cl->shadow.z_far = p_far;
  1239. cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(state.max_lights_per_render * 2);
  1240. Vector<Color> cc;
  1241. cc.push_back(Color(p_far, p_far, p_far, 1.0));
  1242. for (int i = 0; i < 4; i++) {
  1243. //make sure it remains orthogonal, makes easy to read angle later
  1244. //light.basis.scale(Vector3(to_light.elements[0].length(),to_light.elements[1].length(),1));
  1245. Rect2i rect((state.shadow_texture_size / 4) * i, p_shadow_index * 2, (state.shadow_texture_size / 4), 2);
  1246. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(state.shadow_fb, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, cc, 1.0, 0, rect);
  1247. CameraMatrix projection;
  1248. {
  1249. real_t fov = 90;
  1250. real_t nearp = p_near;
  1251. real_t farp = p_far;
  1252. real_t aspect = 1.0;
  1253. real_t ymax = nearp * Math::tan(Math::deg2rad(fov * 0.5));
  1254. real_t ymin = -ymax;
  1255. real_t xmin = ymin * aspect;
  1256. real_t xmax = ymax * aspect;
  1257. projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp);
  1258. }
  1259. Vector3 cam_target = Basis(Vector3(0, 0, Math_PI * 2 * ((i + 3) / 4.0))).xform(Vector3(0, 1, 0));
  1260. projection = projection * CameraMatrix(Transform().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse());
  1261. ShadowRenderPushConstant push_constant;
  1262. for (int y = 0; y < 4; y++) {
  1263. for (int x = 0; x < 4; x++) {
  1264. push_constant.projection[y * 4 + x] = projection.matrix[y][x];
  1265. }
  1266. }
  1267. static const Vector2 directions[4] = { Vector2(1, 0), Vector2(0, 1), Vector2(-1, 0), Vector2(0, -1) };
  1268. push_constant.direction[0] = directions[i].x;
  1269. push_constant.direction[1] = directions[i].y;
  1270. push_constant.z_far = p_far;
  1271. push_constant.pad = 0;
  1272. /*if (i == 0)
  1273. *p_xform_cache = projection;*/
  1274. LightOccluderInstance *instance = p_occluders;
  1275. while (instance) {
  1276. OccluderPolygon *co = occluder_polygon_owner.getornull(instance->occluder);
  1277. if (!co || co->index_array.is_null() || !(p_light_mask & instance->light_mask)) {
  1278. instance = instance->next;
  1279. continue;
  1280. }
  1281. _update_transform_2d_to_mat2x4(p_light_xform * instance->xform_cache, push_constant.modelview);
  1282. RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.render_pipelines[co->cull_mode]);
  1283. RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->vertex_array);
  1284. RD::get_singleton()->draw_list_bind_index_array(draw_list, co->index_array);
  1285. RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));
  1286. RD::get_singleton()->draw_list_draw(draw_list, true);
  1287. instance = instance->next;
  1288. }
  1289. RD::get_singleton()->draw_list_end();
  1290. }
  1291. }
  1292. void RasterizerCanvasRD::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) {
  1293. CanvasLight *cl = canvas_light_owner.getornull(p_rid);
  1294. ERR_FAIL_COND(!cl->shadow.enabled);
  1295. _update_shadow_atlas();
  1296. Vector2 light_dir = p_light_xform.elements[1].normalized();
  1297. Vector2 center = p_clip_rect.position + p_clip_rect.size * 0.5;
  1298. float to_edge_distance = ABS(light_dir.dot(p_clip_rect.get_support(light_dir)) - light_dir.dot(center));
  1299. Vector2 from_pos = center - light_dir * (to_edge_distance + p_cull_distance);
  1300. float distance = to_edge_distance * 2.0 + p_cull_distance;
  1301. float half_size = p_clip_rect.size.length() * 0.5; //shadow length, must keep this no matter the angle
  1302. cl->shadow.z_far = distance;
  1303. cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(state.max_lights_per_render * 2);
  1304. Transform2D to_light_xform;
  1305. to_light_xform[2] = from_pos;
  1306. to_light_xform[1] = light_dir;
  1307. to_light_xform[0] = -light_dir.tangent();
  1308. to_light_xform.invert();
  1309. Vector<Color> cc;
  1310. cc.push_back(Color(1, 1, 1, 1));
  1311. Rect2i rect(0, p_shadow_index * 2, state.shadow_texture_size, 2);
  1312. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(state.shadow_fb, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, cc, 1.0, 0, rect);
  1313. CameraMatrix projection;
  1314. projection.set_orthogonal(-half_size, half_size, -0.5, 0.5, 0.0, distance);
  1315. projection = projection * CameraMatrix(Transform().looking_at(Vector3(0, 1, 0), Vector3(0, 0, -1)).affine_inverse());
  1316. ShadowRenderPushConstant push_constant;
  1317. for (int y = 0; y < 4; y++) {
  1318. for (int x = 0; x < 4; x++) {
  1319. push_constant.projection[y * 4 + x] = projection.matrix[y][x];
  1320. }
  1321. }
  1322. push_constant.direction[0] = 0.0;
  1323. push_constant.direction[1] = 1.0;
  1324. push_constant.z_far = distance;
  1325. push_constant.pad = 0;
  1326. LightOccluderInstance *instance = p_occluders;
  1327. while (instance) {
  1328. OccluderPolygon *co = occluder_polygon_owner.getornull(instance->occluder);
  1329. if (!co || co->index_array.is_null() || !(p_light_mask & instance->light_mask)) {
  1330. instance = instance->next;
  1331. continue;
  1332. }
  1333. _update_transform_2d_to_mat2x4(to_light_xform * instance->xform_cache, push_constant.modelview);
  1334. RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.render_pipelines[co->cull_mode]);
  1335. RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->vertex_array);
  1336. RD::get_singleton()->draw_list_bind_index_array(draw_list, co->index_array);
  1337. RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));
  1338. RD::get_singleton()->draw_list_draw(draw_list, true);
  1339. instance = instance->next;
  1340. }
  1341. RD::get_singleton()->draw_list_end();
  1342. Transform2D to_shadow;
  1343. to_shadow.elements[0].x = 1.0 / -(half_size * 2.0);
  1344. to_shadow.elements[2].x = 0.5;
  1345. cl->shadow.directional_xform = to_shadow * to_light_xform;
  1346. }
  1347. RID RasterizerCanvasRD::occluder_polygon_create() {
  1348. OccluderPolygon occluder;
  1349. occluder.point_count = 0;
  1350. occluder.cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
  1351. return occluder_polygon_owner.make_rid(occluder);
  1352. }
  1353. void RasterizerCanvasRD::occluder_polygon_set_shape_as_lines(RID p_occluder, const Vector<Vector2> &p_lines) {
  1354. OccluderPolygon *oc = occluder_polygon_owner.getornull(p_occluder);
  1355. ERR_FAIL_COND(!oc);
  1356. if (oc->point_count != p_lines.size() && oc->vertex_array.is_valid()) {
  1357. RD::get_singleton()->free(oc->vertex_array);
  1358. RD::get_singleton()->free(oc->vertex_buffer);
  1359. RD::get_singleton()->free(oc->index_array);
  1360. RD::get_singleton()->free(oc->index_buffer);
  1361. oc->vertex_array = RID();
  1362. oc->vertex_buffer = RID();
  1363. oc->index_array = RID();
  1364. oc->index_buffer = RID();
  1365. }
  1366. if (p_lines.size()) {
  1367. Vector<uint8_t> geometry;
  1368. Vector<uint8_t> indices;
  1369. int lc = p_lines.size();
  1370. geometry.resize(lc * 6 * sizeof(float));
  1371. indices.resize(lc * 3 * sizeof(uint16_t));
  1372. {
  1373. uint8_t *vw = geometry.ptrw();
  1374. float *vwptr = (float *)vw;
  1375. uint8_t *iw = indices.ptrw();
  1376. uint16_t *iwptr = (uint16_t *)iw;
  1377. const Vector2 *lr = p_lines.ptr();
  1378. const int POLY_HEIGHT = 16384;
  1379. for (int i = 0; i < lc / 2; i++) {
  1380. vwptr[i * 12 + 0] = lr[i * 2 + 0].x;
  1381. vwptr[i * 12 + 1] = lr[i * 2 + 0].y;
  1382. vwptr[i * 12 + 2] = POLY_HEIGHT;
  1383. vwptr[i * 12 + 3] = lr[i * 2 + 1].x;
  1384. vwptr[i * 12 + 4] = lr[i * 2 + 1].y;
  1385. vwptr[i * 12 + 5] = POLY_HEIGHT;
  1386. vwptr[i * 12 + 6] = lr[i * 2 + 1].x;
  1387. vwptr[i * 12 + 7] = lr[i * 2 + 1].y;
  1388. vwptr[i * 12 + 8] = -POLY_HEIGHT;
  1389. vwptr[i * 12 + 9] = lr[i * 2 + 0].x;
  1390. vwptr[i * 12 + 10] = lr[i * 2 + 0].y;
  1391. vwptr[i * 12 + 11] = -POLY_HEIGHT;
  1392. iwptr[i * 6 + 0] = i * 4 + 0;
  1393. iwptr[i * 6 + 1] = i * 4 + 1;
  1394. iwptr[i * 6 + 2] = i * 4 + 2;
  1395. iwptr[i * 6 + 3] = i * 4 + 2;
  1396. iwptr[i * 6 + 4] = i * 4 + 3;
  1397. iwptr[i * 6 + 5] = i * 4 + 0;
  1398. }
  1399. }
  1400. //if same buffer len is being set, just use BufferSubData to avoid a pipeline flush
  1401. if (oc->vertex_array.is_null()) {
  1402. //create from scratch
  1403. //vertices
  1404. oc->vertex_buffer = RD::get_singleton()->vertex_buffer_create(lc * 6 * sizeof(real_t), geometry);
  1405. Vector<RID> buffer;
  1406. buffer.push_back(oc->vertex_buffer);
  1407. oc->vertex_array = RD::get_singleton()->vertex_array_create(4 * lc / 2, shadow_render.vertex_format, buffer);
  1408. //indices
  1409. oc->index_buffer = RD::get_singleton()->index_buffer_create(3 * lc, RD::INDEX_BUFFER_FORMAT_UINT16, indices);
  1410. oc->index_array = RD::get_singleton()->index_array_create(oc->index_buffer, 0, 3 * lc);
  1411. } else {
  1412. //update existing
  1413. const uint8_t *vr = geometry.ptr();
  1414. RD::get_singleton()->buffer_update(oc->vertex_buffer, 0, geometry.size(), vr);
  1415. const uint8_t *ir = indices.ptr();
  1416. RD::get_singleton()->buffer_update(oc->index_buffer, 0, indices.size(), ir);
  1417. }
  1418. }
  1419. }
  1420. void RasterizerCanvasRD::occluder_polygon_set_cull_mode(RID p_occluder, RS::CanvasOccluderPolygonCullMode p_mode) {
  1421. OccluderPolygon *oc = occluder_polygon_owner.getornull(p_occluder);
  1422. ERR_FAIL_COND(!oc);
  1423. oc->cull_mode = p_mode;
  1424. }
  1425. void RasterizerCanvasRD::ShaderData::set_code(const String &p_code) {
  1426. //compile
  1427. code = p_code;
  1428. valid = false;
  1429. ubo_size = 0;
  1430. uniforms.clear();
  1431. uses_screen_texture = false;
  1432. if (code == String()) {
  1433. return; //just invalid, but no error
  1434. }
  1435. ShaderCompilerRD::GeneratedCode gen_code;
  1436. int light_mode = LIGHT_MODE_NORMAL;
  1437. int blend_mode = BLEND_MODE_MIX;
  1438. uses_screen_texture = false;
  1439. ShaderCompilerRD::IdentifierActions actions;
  1440. actions.render_mode_values["blend_add"] = Pair<int *, int>(&blend_mode, BLEND_MODE_ADD);
  1441. actions.render_mode_values["blend_mix"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MIX);
  1442. actions.render_mode_values["blend_sub"] = Pair<int *, int>(&blend_mode, BLEND_MODE_SUB);
  1443. actions.render_mode_values["blend_mul"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MUL);
  1444. actions.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&blend_mode, BLEND_MODE_PMALPHA);
  1445. actions.render_mode_values["blend_disabled"] = Pair<int *, int>(&blend_mode, BLEND_MODE_DISABLED);
  1446. actions.render_mode_values["unshaded"] = Pair<int *, int>(&light_mode, LIGHT_MODE_UNSHADED);
  1447. actions.render_mode_values["light_only"] = Pair<int *, int>(&light_mode, LIGHT_MODE_LIGHT_ONLY);
  1448. actions.usage_flag_pointers["SCREEN_TEXTURE"] = &uses_screen_texture;
  1449. actions.uniforms = &uniforms;
  1450. RasterizerCanvasRD *canvas_singleton = (RasterizerCanvasRD *)RasterizerCanvas::singleton;
  1451. Error err = canvas_singleton->shader.compiler.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code);
  1452. ERR_FAIL_COND(err != OK);
  1453. if (version.is_null()) {
  1454. version = canvas_singleton->shader.canvas_shader.version_create();
  1455. }
  1456. #if 0
  1457. print_line("**compiling shader:");
  1458. print_line("**defines:\n");
  1459. for (int i = 0; i < gen_code.defines.size(); i++) {
  1460. print_line(gen_code.defines[i]);
  1461. }
  1462. print_line("\n**uniforms:\n" + gen_code.uniforms);
  1463. print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
  1464. print_line("\n**vertex_code:\n" + gen_code.vertex);
  1465. print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
  1466. print_line("\n**fragment_code:\n" + gen_code.fragment);
  1467. print_line("\n**light_code:\n" + gen_code.light);
  1468. #endif
  1469. canvas_singleton->shader.canvas_shader.version_set_code(version, gen_code.uniforms, gen_code.vertex_global, gen_code.vertex, gen_code.fragment_global, gen_code.light, gen_code.fragment, gen_code.defines);
  1470. ERR_FAIL_COND(!canvas_singleton->shader.canvas_shader.version_is_valid(version));
  1471. ubo_size = gen_code.uniform_total_size;
  1472. ubo_offsets = gen_code.uniform_offsets;
  1473. texture_uniforms = gen_code.texture_uniforms;
  1474. //update them pipelines
  1475. RD::PipelineColorBlendState::Attachment attachment;
  1476. switch (blend_mode) {
  1477. case BLEND_MODE_DISABLED: {
  1478. // nothing to do here, disabled by default
  1479. } break;
  1480. case BLEND_MODE_MIX: {
  1481. attachment.enable_blend = true;
  1482. attachment.color_blend_op = RD::BLEND_OP_ADD;
  1483. attachment.src_color_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
  1484. attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  1485. attachment.alpha_blend_op = RD::BLEND_OP_ADD;
  1486. attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1487. attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  1488. } break;
  1489. case BLEND_MODE_ADD: {
  1490. attachment.enable_blend = true;
  1491. attachment.alpha_blend_op = RD::BLEND_OP_ADD;
  1492. attachment.color_blend_op = RD::BLEND_OP_ADD;
  1493. attachment.src_color_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
  1494. attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE;
  1495. attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
  1496. attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1497. } break;
  1498. case BLEND_MODE_SUB: {
  1499. attachment.enable_blend = true;
  1500. attachment.alpha_blend_op = RD::BLEND_OP_SUBTRACT;
  1501. attachment.color_blend_op = RD::BLEND_OP_SUBTRACT;
  1502. attachment.src_color_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
  1503. attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE;
  1504. attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
  1505. attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1506. } break;
  1507. case BLEND_MODE_MUL: {
  1508. attachment.enable_blend = true;
  1509. attachment.alpha_blend_op = RD::BLEND_OP_ADD;
  1510. attachment.color_blend_op = RD::BLEND_OP_ADD;
  1511. attachment.src_color_blend_factor = RD::BLEND_FACTOR_DST_COLOR;
  1512. attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ZERO;
  1513. attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_DST_ALPHA;
  1514. attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
  1515. } break;
  1516. case BLEND_MODE_PMALPHA: {
  1517. attachment.enable_blend = true;
  1518. attachment.alpha_blend_op = RD::BLEND_OP_ADD;
  1519. attachment.color_blend_op = RD::BLEND_OP_ADD;
  1520. attachment.src_color_blend_factor = RD::BLEND_FACTOR_ONE;
  1521. attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  1522. attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1523. attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  1524. } break;
  1525. }
  1526. RD::PipelineColorBlendState blend_state;
  1527. blend_state.attachments.push_back(attachment);
  1528. //update pipelines
  1529. for (int i = 0; i < PIPELINE_LIGHT_MODE_MAX; i++) {
  1530. for (int j = 0; j < PIPELINE_VARIANT_MAX; j++) {
  1531. RD::RenderPrimitive primitive[PIPELINE_VARIANT_MAX] = {
  1532. RD::RENDER_PRIMITIVE_TRIANGLES,
  1533. RD::RENDER_PRIMITIVE_TRIANGLES,
  1534. RD::RENDER_PRIMITIVE_TRIANGLES,
  1535. RD::RENDER_PRIMITIVE_LINES,
  1536. RD::RENDER_PRIMITIVE_POINTS,
  1537. RD::RENDER_PRIMITIVE_TRIANGLES,
  1538. RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS,
  1539. RD::RENDER_PRIMITIVE_LINES,
  1540. RD::RENDER_PRIMITIVE_LINESTRIPS,
  1541. RD::RENDER_PRIMITIVE_POINTS,
  1542. };
  1543. ShaderVariant shader_variants[PIPELINE_LIGHT_MODE_MAX][PIPELINE_VARIANT_MAX] = {
  1544. { //non lit
  1545. SHADER_VARIANT_QUAD,
  1546. SHADER_VARIANT_NINEPATCH,
  1547. SHADER_VARIANT_PRIMITIVE,
  1548. SHADER_VARIANT_PRIMITIVE,
  1549. SHADER_VARIANT_PRIMITIVE_POINTS,
  1550. SHADER_VARIANT_ATTRIBUTES,
  1551. SHADER_VARIANT_ATTRIBUTES,
  1552. SHADER_VARIANT_ATTRIBUTES,
  1553. SHADER_VARIANT_ATTRIBUTES,
  1554. SHADER_VARIANT_ATTRIBUTES_POINTS },
  1555. { //lit
  1556. SHADER_VARIANT_QUAD_LIGHT,
  1557. SHADER_VARIANT_NINEPATCH_LIGHT,
  1558. SHADER_VARIANT_PRIMITIVE_LIGHT,
  1559. SHADER_VARIANT_PRIMITIVE_LIGHT,
  1560. SHADER_VARIANT_PRIMITIVE_POINTS_LIGHT,
  1561. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1562. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1563. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1564. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1565. SHADER_VARIANT_ATTRIBUTES_POINTS_LIGHT },
  1566. };
  1567. RID shader_variant = canvas_singleton->shader.canvas_shader.version_get_shader(version, shader_variants[i][j]);
  1568. pipeline_variants.variants[i][j].setup(shader_variant, primitive[j], RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), blend_state, 0);
  1569. }
  1570. }
  1571. valid = true;
  1572. }
  1573. void RasterizerCanvasRD::ShaderData::set_default_texture_param(const StringName &p_name, RID p_texture) {
  1574. if (!p_texture.is_valid()) {
  1575. default_texture_params.erase(p_name);
  1576. } else {
  1577. default_texture_params[p_name] = p_texture;
  1578. }
  1579. }
  1580. void RasterizerCanvasRD::ShaderData::get_param_list(List<PropertyInfo> *p_param_list) const {
  1581. Map<int, StringName> order;
  1582. for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
  1583. if (E->get().scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
  1584. continue;
  1585. }
  1586. if (E->get().texture_order >= 0) {
  1587. order[E->get().texture_order + 100000] = E->key();
  1588. } else {
  1589. order[E->get().order] = E->key();
  1590. }
  1591. }
  1592. for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
  1593. PropertyInfo pi = ShaderLanguage::uniform_to_property_info(uniforms[E->get()]);
  1594. pi.name = E->get();
  1595. p_param_list->push_back(pi);
  1596. }
  1597. }
  1598. void RasterizerCanvasRD::ShaderData::get_instance_param_list(List<RasterizerStorage::InstanceShaderParam> *p_param_list) const {
  1599. for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
  1600. if (E->get().scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
  1601. continue;
  1602. }
  1603. RasterizerStorage::InstanceShaderParam p;
  1604. p.info = ShaderLanguage::uniform_to_property_info(E->get());
  1605. p.info.name = E->key(); //supply name
  1606. p.index = E->get().instance_index;
  1607. p.default_value = ShaderLanguage::constant_value_to_variant(E->get().default_value, E->get().type, E->get().hint);
  1608. p_param_list->push_back(p);
  1609. }
  1610. }
  1611. bool RasterizerCanvasRD::ShaderData::is_param_texture(const StringName &p_param) const {
  1612. if (!uniforms.has(p_param)) {
  1613. return false;
  1614. }
  1615. return uniforms[p_param].texture_order >= 0;
  1616. }
  1617. bool RasterizerCanvasRD::ShaderData::is_animated() const {
  1618. return false;
  1619. }
  1620. bool RasterizerCanvasRD::ShaderData::casts_shadows() const {
  1621. return false;
  1622. }
  1623. Variant RasterizerCanvasRD::ShaderData::get_default_parameter(const StringName &p_parameter) const {
  1624. if (uniforms.has(p_parameter)) {
  1625. ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter];
  1626. Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
  1627. return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint);
  1628. }
  1629. return Variant();
  1630. }
  1631. RasterizerCanvasRD::ShaderData::ShaderData() {
  1632. valid = false;
  1633. uses_screen_texture = false;
  1634. }
  1635. RasterizerCanvasRD::ShaderData::~ShaderData() {
  1636. RasterizerCanvasRD *canvas_singleton = (RasterizerCanvasRD *)RasterizerCanvas::singleton;
  1637. ERR_FAIL_COND(!canvas_singleton);
  1638. //pipeline variants will clear themselves if shader is gone
  1639. if (version.is_valid()) {
  1640. canvas_singleton->shader.canvas_shader.version_free(version);
  1641. }
  1642. }
  1643. RasterizerStorageRD::ShaderData *RasterizerCanvasRD::_create_shader_func() {
  1644. ShaderData *shader_data = memnew(ShaderData);
  1645. return shader_data;
  1646. }
  1647. void RasterizerCanvasRD::MaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
  1648. RasterizerCanvasRD *canvas_singleton = (RasterizerCanvasRD *)RasterizerCanvas::singleton;
  1649. if ((uint32_t)ubo_data.size() != shader_data->ubo_size) {
  1650. p_uniform_dirty = true;
  1651. if (uniform_buffer.is_valid()) {
  1652. RD::get_singleton()->free(uniform_buffer);
  1653. uniform_buffer = RID();
  1654. }
  1655. ubo_data.resize(shader_data->ubo_size);
  1656. if (ubo_data.size()) {
  1657. uniform_buffer = RD::get_singleton()->uniform_buffer_create(ubo_data.size());
  1658. memset(ubo_data.ptrw(), 0, ubo_data.size()); //clear
  1659. }
  1660. //clear previous uniform set
  1661. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  1662. RD::get_singleton()->free(uniform_set);
  1663. uniform_set = RID();
  1664. }
  1665. }
  1666. //check whether buffer changed
  1667. if (p_uniform_dirty && ubo_data.size()) {
  1668. update_uniform_buffer(shader_data->uniforms, shader_data->ubo_offsets.ptr(), p_parameters, ubo_data.ptrw(), ubo_data.size(), false);
  1669. RD::get_singleton()->buffer_update(uniform_buffer, 0, ubo_data.size(), ubo_data.ptrw());
  1670. }
  1671. uint32_t tex_uniform_count = shader_data->texture_uniforms.size();
  1672. if ((uint32_t)texture_cache.size() != tex_uniform_count) {
  1673. texture_cache.resize(tex_uniform_count);
  1674. p_textures_dirty = true;
  1675. //clear previous uniform set
  1676. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  1677. RD::get_singleton()->free(uniform_set);
  1678. uniform_set = RID();
  1679. }
  1680. }
  1681. if (p_textures_dirty && tex_uniform_count) {
  1682. update_textures(p_parameters, shader_data->default_texture_params, shader_data->texture_uniforms, texture_cache.ptrw(), false);
  1683. }
  1684. if (shader_data->ubo_size == 0) {
  1685. // This material does not require an uniform set, so don't create it.
  1686. return;
  1687. }
  1688. if (!p_textures_dirty && uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  1689. //no reason to update uniform set, only UBO (or nothing) was needed to update
  1690. return;
  1691. }
  1692. Vector<RD::Uniform> uniforms;
  1693. {
  1694. if (shader_data->ubo_size) {
  1695. RD::Uniform u;
  1696. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1697. u.binding = 0;
  1698. u.ids.push_back(uniform_buffer);
  1699. uniforms.push_back(u);
  1700. }
  1701. const RID *textures = texture_cache.ptrw();
  1702. for (uint32_t i = 0; i < tex_uniform_count; i++) {
  1703. RD::Uniform u;
  1704. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1705. u.binding = 1 + i;
  1706. u.ids.push_back(textures[i]);
  1707. uniforms.push_back(u);
  1708. }
  1709. }
  1710. uniform_set = RD::get_singleton()->uniform_set_create(uniforms, canvas_singleton->shader.canvas_shader.version_get_shader(shader_data->version, 0), MATERIAL_UNIFORM_SET);
  1711. }
  1712. RasterizerCanvasRD::MaterialData::~MaterialData() {
  1713. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  1714. RD::get_singleton()->free(uniform_set);
  1715. }
  1716. if (uniform_buffer.is_valid()) {
  1717. RD::get_singleton()->free(uniform_buffer);
  1718. }
  1719. }
  1720. RasterizerStorageRD::MaterialData *RasterizerCanvasRD::_create_material_func(ShaderData *p_shader) {
  1721. MaterialData *material_data = memnew(MaterialData);
  1722. material_data->shader_data = p_shader;
  1723. material_data->last_frame = false;
  1724. //update will happen later anyway so do nothing.
  1725. return material_data;
  1726. }
  1727. void RasterizerCanvasRD::set_time(double p_time) {
  1728. state.time = p_time;
  1729. }
  1730. void RasterizerCanvasRD::update() {
  1731. }
  1732. RasterizerCanvasRD::RasterizerCanvasRD(RasterizerStorageRD *p_storage) {
  1733. storage = p_storage;
  1734. { //create default samplers
  1735. default_samplers.default_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR;
  1736. default_samplers.default_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED;
  1737. }
  1738. { //shader variants
  1739. String global_defines;
  1740. uint32_t uniform_max_size = RD::get_singleton()->limit_get(RD::LIMIT_MAX_UNIFORM_BUFFER_SIZE);
  1741. if (uniform_max_size < 65536) {
  1742. //Yes, you guessed right, ARM again
  1743. state.max_lights_per_render = 64;
  1744. global_defines += "#define MAX_LIGHTS 64\n";
  1745. } else {
  1746. state.max_lights_per_render = DEFAULT_MAX_LIGHTS_PER_RENDER;
  1747. global_defines += "#define MAX_LIGHTS " + itos(DEFAULT_MAX_LIGHTS_PER_RENDER) + "\n";
  1748. }
  1749. state.light_uniforms = memnew_arr(LightUniform, state.max_lights_per_render);
  1750. Vector<String> variants;
  1751. //non light variants
  1752. variants.push_back(""); //none by default is first variant
  1753. variants.push_back("#define USE_NINEPATCH\n"); //ninepatch is the second variant
  1754. variants.push_back("#define USE_PRIMITIVE\n"); //primitive is the third
  1755. variants.push_back("#define USE_PRIMITIVE\n#define USE_POINT_SIZE\n"); //points need point size
  1756. variants.push_back("#define USE_ATTRIBUTES\n"); // attributes for vertex arrays
  1757. variants.push_back("#define USE_ATTRIBUTES\n#define USE_POINT_SIZE\n"); //attributes with point size
  1758. //light variants
  1759. variants.push_back("#define USE_LIGHTING\n"); //none by default is first variant
  1760. variants.push_back("#define USE_LIGHTING\n#define USE_NINEPATCH\n"); //ninepatch is the second variant
  1761. variants.push_back("#define USE_LIGHTING\n#define USE_PRIMITIVE\n"); //primitive is the third
  1762. variants.push_back("#define USE_LIGHTING\n#define USE_PRIMITIVE\n#define USE_POINT_SIZE\n"); //points need point size
  1763. variants.push_back("#define USE_LIGHTING\n#define USE_ATTRIBUTES\n"); // attributes for vertex arrays
  1764. variants.push_back("#define USE_LIGHTING\n#define USE_ATTRIBUTES\n#define USE_POINT_SIZE\n"); //attributes with point size
  1765. shader.canvas_shader.initialize(variants, global_defines);
  1766. shader.default_version = shader.canvas_shader.version_create();
  1767. shader.default_version_rd_shader = shader.canvas_shader.version_get_shader(shader.default_version, SHADER_VARIANT_QUAD);
  1768. RD::PipelineColorBlendState blend_state;
  1769. RD::PipelineColorBlendState::Attachment blend_attachment;
  1770. blend_attachment.enable_blend = true;
  1771. blend_attachment.color_blend_op = RD::BLEND_OP_ADD;
  1772. blend_attachment.src_color_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
  1773. blend_attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  1774. blend_attachment.alpha_blend_op = RD::BLEND_OP_ADD;
  1775. blend_attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1776. blend_attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  1777. blend_state.attachments.push_back(blend_attachment);
  1778. for (int i = 0; i < PIPELINE_LIGHT_MODE_MAX; i++) {
  1779. for (int j = 0; j < PIPELINE_VARIANT_MAX; j++) {
  1780. RD::RenderPrimitive primitive[PIPELINE_VARIANT_MAX] = {
  1781. RD::RENDER_PRIMITIVE_TRIANGLES,
  1782. RD::RENDER_PRIMITIVE_TRIANGLES,
  1783. RD::RENDER_PRIMITIVE_TRIANGLES,
  1784. RD::RENDER_PRIMITIVE_LINES,
  1785. RD::RENDER_PRIMITIVE_POINTS,
  1786. RD::RENDER_PRIMITIVE_TRIANGLES,
  1787. RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS,
  1788. RD::RENDER_PRIMITIVE_LINES,
  1789. RD::RENDER_PRIMITIVE_LINESTRIPS,
  1790. RD::RENDER_PRIMITIVE_POINTS,
  1791. };
  1792. ShaderVariant shader_variants[PIPELINE_LIGHT_MODE_MAX][PIPELINE_VARIANT_MAX] = {
  1793. { //non lit
  1794. SHADER_VARIANT_QUAD,
  1795. SHADER_VARIANT_NINEPATCH,
  1796. SHADER_VARIANT_PRIMITIVE,
  1797. SHADER_VARIANT_PRIMITIVE,
  1798. SHADER_VARIANT_PRIMITIVE_POINTS,
  1799. SHADER_VARIANT_ATTRIBUTES,
  1800. SHADER_VARIANT_ATTRIBUTES,
  1801. SHADER_VARIANT_ATTRIBUTES,
  1802. SHADER_VARIANT_ATTRIBUTES,
  1803. SHADER_VARIANT_ATTRIBUTES_POINTS },
  1804. { //lit
  1805. SHADER_VARIANT_QUAD_LIGHT,
  1806. SHADER_VARIANT_NINEPATCH_LIGHT,
  1807. SHADER_VARIANT_PRIMITIVE_LIGHT,
  1808. SHADER_VARIANT_PRIMITIVE_LIGHT,
  1809. SHADER_VARIANT_PRIMITIVE_POINTS_LIGHT,
  1810. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1811. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1812. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1813. SHADER_VARIANT_ATTRIBUTES_LIGHT,
  1814. SHADER_VARIANT_ATTRIBUTES_POINTS_LIGHT },
  1815. };
  1816. RID shader_variant = shader.canvas_shader.version_get_shader(shader.default_version, shader_variants[i][j]);
  1817. shader.pipeline_variants.variants[i][j].setup(shader_variant, primitive[j], RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), blend_state, 0);
  1818. }
  1819. }
  1820. }
  1821. {
  1822. //shader compiler
  1823. ShaderCompilerRD::DefaultIdentifierActions actions;
  1824. actions.renames["VERTEX"] = "vertex";
  1825. actions.renames["LIGHT_VERTEX"] = "light_vertex";
  1826. actions.renames["SHADOW_VERTEX"] = "shadow_vertex";
  1827. actions.renames["UV"] = "uv";
  1828. actions.renames["POINT_SIZE"] = "gl_PointSize";
  1829. actions.renames["WORLD_MATRIX"] = "world_matrix";
  1830. actions.renames["CANVAS_MATRIX"] = "canvas_data.canvas_transform";
  1831. actions.renames["SCREEN_MATRIX"] = "canvas_data.screen_transform";
  1832. actions.renames["TIME"] = "canvas_data.time";
  1833. actions.renames["AT_LIGHT_PASS"] = "false";
  1834. actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
  1835. actions.renames["COLOR"] = "color";
  1836. actions.renames["NORMAL"] = "normal";
  1837. actions.renames["NORMALMAP"] = "normal_map";
  1838. actions.renames["NORMALMAP_DEPTH"] = "normal_depth";
  1839. actions.renames["TEXTURE"] = "color_texture";
  1840. actions.renames["TEXTURE_PIXEL_SIZE"] = "draw_data.color_texture_pixel_size";
  1841. actions.renames["NORMAL_TEXTURE"] = "normal_texture";
  1842. actions.renames["SPECULAR_SHININESS_TEXTURE"] = "specular_texture";
  1843. actions.renames["SPECULAR_SHININESS"] = "specular_shininess";
  1844. actions.renames["SCREEN_UV"] = "screen_uv";
  1845. actions.renames["SCREEN_TEXTURE"] = "screen_texture";
  1846. actions.renames["SCREEN_PIXEL_SIZE"] = "canvas_data.screen_pixel_size";
  1847. actions.renames["FRAGCOORD"] = "gl_FragCoord";
  1848. actions.renames["POINT_COORD"] = "gl_PointCoord";
  1849. actions.renames["LIGHT_POSITION"] = "light_pos";
  1850. actions.renames["LIGHT_COLOR"] = "light_color";
  1851. actions.renames["LIGHT_ENERGY"] = "light_energy";
  1852. actions.renames["LIGHT"] = "light";
  1853. actions.renames["SHADOW_MODULATE"] = "shadow_modulate";
  1854. actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
  1855. actions.usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n";
  1856. actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
  1857. actions.usage_defines["SCREEN_PIXEL_SIZE"] = "@SCREEN_UV";
  1858. actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";
  1859. actions.usage_defines["NORMALMAP"] = "#define NORMALMAP_USED\n";
  1860. actions.usage_defines["LIGHT"] = "#define LIGHT_SHADER_CODE_USED\n";
  1861. actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
  1862. actions.custom_samplers["TEXTURE"] = "texture_sampler";
  1863. actions.custom_samplers["NORMAL_TEXTURE"] = "texture_sampler";
  1864. actions.custom_samplers["SPECULAR_SHININESS_TEXTURE"] = "texture_sampler";
  1865. actions.custom_samplers["SCREEN_TEXTURE"] = "material_samplers[3]"; //mipmap and filter for screen texture
  1866. actions.sampler_array_name = "material_samplers";
  1867. actions.base_texture_binding_index = 1;
  1868. actions.texture_layout_set = MATERIAL_UNIFORM_SET;
  1869. actions.base_uniform_string = "material.";
  1870. actions.default_filter = ShaderLanguage::FILTER_LINEAR;
  1871. actions.default_repeat = ShaderLanguage::REPEAT_DISABLE;
  1872. actions.base_varying_index = 4;
  1873. actions.global_buffer_array_variable = "global_variables.data";
  1874. shader.compiler.initialize(actions);
  1875. }
  1876. { //shadow rendering
  1877. Vector<String> versions;
  1878. versions.push_back(String()); //no versions
  1879. shadow_render.shader.initialize(versions);
  1880. {
  1881. Vector<RD::AttachmentFormat> attachments;
  1882. RD::AttachmentFormat af_color;
  1883. af_color.format = RD::DATA_FORMAT_R32_SFLOAT;
  1884. af_color.usage_flags = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  1885. attachments.push_back(af_color);
  1886. RD::AttachmentFormat af_depth;
  1887. af_depth.format = RD::DATA_FORMAT_D32_SFLOAT;
  1888. af_depth.usage_flags = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1889. attachments.push_back(af_depth);
  1890. shadow_render.framebuffer_format = RD::get_singleton()->framebuffer_format_create(attachments);
  1891. }
  1892. //pipelines
  1893. Vector<RD::VertexAttribute> vf;
  1894. RD::VertexAttribute vd;
  1895. vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT;
  1896. vd.location = 0;
  1897. vd.offset = 0;
  1898. vd.stride = sizeof(float) * 3;
  1899. vf.push_back(vd);
  1900. shadow_render.vertex_format = RD::get_singleton()->vertex_format_create(vf);
  1901. shadow_render.shader_version = shadow_render.shader.version_create();
  1902. for (int i = 0; i < 3; i++) {
  1903. RD::PipelineRasterizationState rs;
  1904. rs.cull_mode = i == 0 ? RD::POLYGON_CULL_DISABLED : (i == 1 ? RD::POLYGON_CULL_FRONT : RD::POLYGON_CULL_BACK);
  1905. RD::PipelineDepthStencilState ds;
  1906. ds.enable_depth_write = true;
  1907. ds.enable_depth_test = true;
  1908. ds.depth_compare_operator = RD::COMPARE_OP_LESS;
  1909. shadow_render.render_pipelines[i] = RD::get_singleton()->render_pipeline_create(shadow_render.shader.version_get_shader(shadow_render.shader_version, 0), shadow_render.framebuffer_format, shadow_render.vertex_format, RD::RENDER_PRIMITIVE_TRIANGLES, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
  1910. }
  1911. }
  1912. { //bindings
  1913. state.canvas_state_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(State::Buffer));
  1914. state.lights_uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(LightUniform) * state.max_lights_per_render);
  1915. RD::SamplerState shadow_sampler_state;
  1916. shadow_sampler_state.mag_filter = RD::SAMPLER_FILTER_LINEAR;
  1917. shadow_sampler_state.min_filter = RD::SAMPLER_FILTER_LINEAR;
  1918. shadow_sampler_state.repeat_u = RD::SAMPLER_REPEAT_MODE_REPEAT; //shadow wrap around
  1919. shadow_sampler_state.compare_op = RD::COMPARE_OP_GREATER;
  1920. shadow_sampler_state.enable_compare = true;
  1921. state.shadow_sampler = RD::get_singleton()->sampler_create(shadow_sampler_state);
  1922. }
  1923. {
  1924. //polygon buffers
  1925. polygon_buffers.last_id = 1;
  1926. }
  1927. { // default index buffer
  1928. Vector<uint8_t> pv;
  1929. pv.resize(6 * 4);
  1930. {
  1931. uint8_t *w = pv.ptrw();
  1932. int *p32 = (int *)w;
  1933. p32[0] = 0;
  1934. p32[1] = 1;
  1935. p32[2] = 2;
  1936. p32[3] = 0;
  1937. p32[4] = 2;
  1938. p32[5] = 3;
  1939. }
  1940. shader.quad_index_buffer = RD::get_singleton()->index_buffer_create(6, RenderingDevice::INDEX_BUFFER_FORMAT_UINT32, pv);
  1941. shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);
  1942. }
  1943. { //primitive
  1944. primitive_arrays.index_array[0] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 1);
  1945. primitive_arrays.index_array[1] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 2);
  1946. primitive_arrays.index_array[2] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 3);
  1947. primitive_arrays.index_array[3] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);
  1948. }
  1949. { //default skeleton buffer
  1950. shader.default_skeleton_uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(SkeletonUniform));
  1951. SkeletonUniform su;
  1952. _update_transform_2d_to_mat4(Transform2D(), su.skeleton_inverse);
  1953. _update_transform_2d_to_mat4(Transform2D(), su.skeleton_transform);
  1954. RD::get_singleton()->buffer_update(shader.default_skeleton_uniform_buffer, 0, sizeof(SkeletonUniform), &su);
  1955. shader.default_skeleton_texture_buffer = RD::get_singleton()->texture_buffer_create(32, RD::DATA_FORMAT_R32G32B32A32_SFLOAT);
  1956. }
  1957. {
  1958. //default shadow texture to keep uniform set happy
  1959. RD::TextureFormat tf;
  1960. tf.type = RD::TEXTURE_TYPE_2D;
  1961. tf.width = 4;
  1962. tf.height = 4;
  1963. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;
  1964. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  1965. state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1966. }
  1967. {
  1968. Vector<RD::Uniform> uniforms;
  1969. {
  1970. RD::Uniform u;
  1971. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1972. u.binding = 0;
  1973. u.ids.push_back(storage->get_default_rd_storage_buffer());
  1974. uniforms.push_back(u);
  1975. }
  1976. state.default_transforms_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET);
  1977. }
  1978. default_canvas_texture = storage->canvas_texture_create();
  1979. state.shadow_texture_size = GLOBAL_GET("rendering/quality/2d_shadow_atlas/size");
  1980. //create functions for shader and material
  1981. storage->shader_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_2D, _create_shader_funcs);
  1982. storage->material_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_2D, _create_material_funcs);
  1983. state.time = 0;
  1984. {
  1985. default_canvas_group_shader = storage->shader_create();
  1986. storage->shader_set_code(default_canvas_group_shader, "shader_type canvas_item; \nvoid fragment() {\n\tvec4 c = textureLod(SCREEN_TEXTURE,SCREEN_UV,0.0); if (c.a > 0.0001) c.rgb/=c.a; COLOR *= c; \n}\n");
  1987. default_canvas_group_material = storage->material_create();
  1988. storage->material_set_shader(default_canvas_group_material, default_canvas_group_shader);
  1989. }
  1990. static_assert(sizeof(PushConstant) == 128);
  1991. }
  1992. bool RasterizerCanvasRD::free(RID p_rid) {
  1993. if (canvas_light_owner.owns(p_rid)) {
  1994. CanvasLight *cl = canvas_light_owner.getornull(p_rid);
  1995. ERR_FAIL_COND_V(!cl, false);
  1996. light_set_use_shadow(p_rid, false);
  1997. canvas_light_owner.free(p_rid);
  1998. } else if (occluder_polygon_owner.owns(p_rid)) {
  1999. occluder_polygon_set_shape_as_lines(p_rid, Vector<Vector2>());
  2000. occluder_polygon_owner.free(p_rid);
  2001. } else {
  2002. return false;
  2003. }
  2004. return true;
  2005. }
  2006. void RasterizerCanvasRD::set_shadow_texture_size(int p_size) {
  2007. p_size = nearest_power_of_2_templated(p_size);
  2008. if (p_size == state.shadow_texture_size) {
  2009. return;
  2010. }
  2011. state.shadow_texture_size = p_size;
  2012. if (state.shadow_fb.is_valid()) {
  2013. RD::get_singleton()->free(state.shadow_texture);
  2014. RD::get_singleton()->free(state.shadow_depth_texture);
  2015. state.shadow_fb = RID();
  2016. {
  2017. //create a default shadow texture to keep uniform set happy (and that it gets erased when a new one is created)
  2018. RD::TextureFormat tf;
  2019. tf.type = RD::TEXTURE_TYPE_2D;
  2020. tf.width = 4;
  2021. tf.height = 4;
  2022. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;
  2023. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  2024. state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  2025. }
  2026. }
  2027. }
  2028. RasterizerCanvasRD::~RasterizerCanvasRD() {
  2029. //canvas state
  2030. storage->free(default_canvas_group_material);
  2031. storage->free(default_canvas_group_shader);
  2032. {
  2033. if (state.canvas_state_buffer.is_valid()) {
  2034. RD::get_singleton()->free(state.canvas_state_buffer);
  2035. }
  2036. memdelete_arr(state.light_uniforms);
  2037. RD::get_singleton()->free(state.lights_uniform_buffer);
  2038. RD::get_singleton()->free(shader.default_skeleton_uniform_buffer);
  2039. RD::get_singleton()->free(shader.default_skeleton_texture_buffer);
  2040. }
  2041. //shadow rendering
  2042. {
  2043. shadow_render.shader.version_free(shadow_render.shader_version);
  2044. //this will also automatically clear all pipelines
  2045. RD::get_singleton()->free(state.shadow_sampler);
  2046. }
  2047. //bindings
  2048. //shaders
  2049. shader.canvas_shader.version_free(shader.default_version);
  2050. //buffers
  2051. {
  2052. RD::get_singleton()->free(shader.quad_index_array);
  2053. RD::get_singleton()->free(shader.quad_index_buffer);
  2054. //primitives are erase by dependency
  2055. }
  2056. if (state.shadow_fb.is_valid()) {
  2057. RD::get_singleton()->free(state.shadow_depth_texture);
  2058. }
  2059. RD::get_singleton()->free(state.shadow_texture);
  2060. storage->free(default_canvas_texture);
  2061. //pipelines don't need freeing, they are all gone after shaders are gone
  2062. RD::get_singleton()->free(state.default_transforms_uniform_set);
  2063. }