rasterizer_canvas_rd.cpp 92 KB

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