core_bind.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590
  1. /*************************************************************************/
  2. /* core_bind.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "core_bind.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/crypto/crypto_core.h"
  33. #include "core/debugger/engine_debugger.h"
  34. #include "core/io/file_access_compressed.h"
  35. #include "core/io/file_access_encrypted.h"
  36. #include "core/io/json.h"
  37. #include "core/io/marshalls.h"
  38. #include "core/math/geometry_2d.h"
  39. #include "core/math/geometry_3d.h"
  40. #include "core/os/keyboard.h"
  41. #include "core/os/os.h"
  42. /**
  43. * Time constants borrowed from loc_time.h
  44. */
  45. #define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */
  46. #define SECS_DAY (24L * 60L * 60L)
  47. #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
  48. #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
  49. #define SECOND_KEY "second"
  50. #define MINUTE_KEY "minute"
  51. #define HOUR_KEY "hour"
  52. #define DAY_KEY "day"
  53. #define MONTH_KEY "month"
  54. #define YEAR_KEY "year"
  55. #define WEEKDAY_KEY "weekday"
  56. #define DST_KEY "dst"
  57. /// Table of number of days in each month (for regular year and leap year)
  58. static const unsigned int MONTH_DAYS_TABLE[2][12] = {
  59. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
  60. { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
  61. };
  62. ////// _ResourceLoader //////
  63. _ResourceLoader *_ResourceLoader::singleton = nullptr;
  64. Error _ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads) {
  65. return ResourceLoader::load_threaded_request(p_path, p_type_hint, p_use_sub_threads);
  66. }
  67. _ResourceLoader::ThreadLoadStatus _ResourceLoader::load_threaded_get_status(const String &p_path, Array r_progress) {
  68. float progress = 0;
  69. ResourceLoader::ThreadLoadStatus tls = ResourceLoader::load_threaded_get_status(p_path, &progress);
  70. r_progress.resize(1);
  71. r_progress[0] = progress;
  72. return (ThreadLoadStatus)tls;
  73. }
  74. RES _ResourceLoader::load_threaded_get(const String &p_path) {
  75. Error error;
  76. RES res = ResourceLoader::load_threaded_get(p_path, &error);
  77. return res;
  78. }
  79. RES _ResourceLoader::load(const String &p_path, const String &p_type_hint, CacheMode p_cache_mode) {
  80. Error err = OK;
  81. RES ret = ResourceLoader::load(p_path, p_type_hint, ResourceFormatLoader::CacheMode(p_cache_mode), &err);
  82. ERR_FAIL_COND_V_MSG(err != OK, ret, "Error loading resource: '" + p_path + "'.");
  83. return ret;
  84. }
  85. Vector<String> _ResourceLoader::get_recognized_extensions_for_type(const String &p_type) {
  86. List<String> exts;
  87. ResourceLoader::get_recognized_extensions_for_type(p_type, &exts);
  88. Vector<String> ret;
  89. for (List<String>::Element *E = exts.front(); E; E = E->next()) {
  90. ret.push_back(E->get());
  91. }
  92. return ret;
  93. }
  94. void _ResourceLoader::set_abort_on_missing_resources(bool p_abort) {
  95. ResourceLoader::set_abort_on_missing_resources(p_abort);
  96. }
  97. PackedStringArray _ResourceLoader::get_dependencies(const String &p_path) {
  98. List<String> deps;
  99. ResourceLoader::get_dependencies(p_path, &deps);
  100. PackedStringArray ret;
  101. for (List<String>::Element *E = deps.front(); E; E = E->next()) {
  102. ret.push_back(E->get());
  103. }
  104. return ret;
  105. }
  106. bool _ResourceLoader::has_cached(const String &p_path) {
  107. String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  108. return ResourceCache::has(local_path);
  109. }
  110. bool _ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  111. return ResourceLoader::exists(p_path, p_type_hint);
  112. }
  113. void _ResourceLoader::_bind_methods() {
  114. ClassDB::bind_method(D_METHOD("load_threaded_request", "path", "type_hint", "use_sub_threads"), &_ResourceLoader::load_threaded_request, DEFVAL(""), DEFVAL(false));
  115. ClassDB::bind_method(D_METHOD("load_threaded_get_status", "path", "progress"), &_ResourceLoader::load_threaded_get_status, DEFVAL(Array()));
  116. ClassDB::bind_method(D_METHOD("load_threaded_get", "path"), &_ResourceLoader::load_threaded_get);
  117. ClassDB::bind_method(D_METHOD("load", "path", "type_hint", "cache_mode"), &_ResourceLoader::load, DEFVAL(""), DEFVAL(CACHE_MODE_REUSE));
  118. ClassDB::bind_method(D_METHOD("get_recognized_extensions_for_type", "type"), &_ResourceLoader::get_recognized_extensions_for_type);
  119. ClassDB::bind_method(D_METHOD("set_abort_on_missing_resources", "abort"), &_ResourceLoader::set_abort_on_missing_resources);
  120. ClassDB::bind_method(D_METHOD("get_dependencies", "path"), &_ResourceLoader::get_dependencies);
  121. ClassDB::bind_method(D_METHOD("has_cached", "path"), &_ResourceLoader::has_cached);
  122. ClassDB::bind_method(D_METHOD("exists", "path", "type_hint"), &_ResourceLoader::exists, DEFVAL(""));
  123. BIND_ENUM_CONSTANT(THREAD_LOAD_INVALID_RESOURCE);
  124. BIND_ENUM_CONSTANT(THREAD_LOAD_IN_PROGRESS);
  125. BIND_ENUM_CONSTANT(THREAD_LOAD_FAILED);
  126. BIND_ENUM_CONSTANT(THREAD_LOAD_LOADED);
  127. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  128. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  129. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  130. }
  131. ////// _ResourceSaver //////
  132. Error _ResourceSaver::save(const String &p_path, const RES &p_resource, SaverFlags p_flags) {
  133. ERR_FAIL_COND_V_MSG(p_resource.is_null(), ERR_INVALID_PARAMETER, "Can't save empty resource to path '" + String(p_path) + "'.");
  134. return ResourceSaver::save(p_path, p_resource, p_flags);
  135. }
  136. Vector<String> _ResourceSaver::get_recognized_extensions(const RES &p_resource) {
  137. ERR_FAIL_COND_V_MSG(p_resource.is_null(), Vector<String>(), "It's not a reference to a valid Resource object.");
  138. List<String> exts;
  139. ResourceSaver::get_recognized_extensions(p_resource, &exts);
  140. Vector<String> ret;
  141. for (List<String>::Element *E = exts.front(); E; E = E->next()) {
  142. ret.push_back(E->get());
  143. }
  144. return ret;
  145. }
  146. _ResourceSaver *_ResourceSaver::singleton = nullptr;
  147. void _ResourceSaver::_bind_methods() {
  148. ClassDB::bind_method(D_METHOD("save", "path", "resource", "flags"), &_ResourceSaver::save, DEFVAL(0));
  149. ClassDB::bind_method(D_METHOD("get_recognized_extensions", "type"), &_ResourceSaver::get_recognized_extensions);
  150. BIND_ENUM_CONSTANT(FLAG_RELATIVE_PATHS);
  151. BIND_ENUM_CONSTANT(FLAG_BUNDLE_RESOURCES);
  152. BIND_ENUM_CONSTANT(FLAG_CHANGE_PATH);
  153. BIND_ENUM_CONSTANT(FLAG_OMIT_EDITOR_PROPERTIES);
  154. BIND_ENUM_CONSTANT(FLAG_SAVE_BIG_ENDIAN);
  155. BIND_ENUM_CONSTANT(FLAG_COMPRESS);
  156. BIND_ENUM_CONSTANT(FLAG_REPLACE_SUBRESOURCE_PATHS);
  157. }
  158. ////// _OS //////
  159. PackedStringArray _OS::get_connected_midi_inputs() {
  160. return OS::get_singleton()->get_connected_midi_inputs();
  161. }
  162. void _OS::open_midi_inputs() {
  163. OS::get_singleton()->open_midi_inputs();
  164. }
  165. void _OS::close_midi_inputs() {
  166. OS::get_singleton()->close_midi_inputs();
  167. }
  168. void _OS::set_use_file_access_save_and_swap(bool p_enable) {
  169. FileAccess::set_backup_save(p_enable);
  170. }
  171. void _OS::set_low_processor_usage_mode(bool p_enabled) {
  172. OS::get_singleton()->set_low_processor_usage_mode(p_enabled);
  173. }
  174. bool _OS::is_in_low_processor_usage_mode() const {
  175. return OS::get_singleton()->is_in_low_processor_usage_mode();
  176. }
  177. void _OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  178. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(p_usec);
  179. }
  180. int _OS::get_low_processor_usage_mode_sleep_usec() const {
  181. return OS::get_singleton()->get_low_processor_usage_mode_sleep_usec();
  182. }
  183. String _OS::get_executable_path() const {
  184. return OS::get_singleton()->get_executable_path();
  185. }
  186. Error _OS::shell_open(String p_uri) {
  187. if (p_uri.begins_with("res://")) {
  188. WARN_PRINT("Attempting to open an URL with the \"res://\" protocol. Use `ProjectSettings.globalize_path()` to convert a Godot-specific path to a system path before opening it with `OS.shell_open()`.");
  189. } else if (p_uri.begins_with("user://")) {
  190. WARN_PRINT("Attempting to open an URL with the \"user://\" protocol. Use `ProjectSettings.globalize_path()` to convert a Godot-specific path to a system path before opening it with `OS.shell_open()`.");
  191. }
  192. return OS::get_singleton()->shell_open(p_uri);
  193. }
  194. int _OS::execute(const String &p_path, const Vector<String> &p_arguments, Array r_output, bool p_read_stderr) {
  195. List<String> args;
  196. for (int i = 0; i < p_arguments.size(); i++) {
  197. args.push_back(p_arguments[i]);
  198. }
  199. String pipe;
  200. int exitcode = 0;
  201. Error err = OS::get_singleton()->execute(p_path, args, &pipe, &exitcode, p_read_stderr);
  202. r_output.push_back(pipe);
  203. if (err != OK) {
  204. return -1;
  205. }
  206. return exitcode;
  207. }
  208. int _OS::create_process(const String &p_path, const Vector<String> &p_arguments) {
  209. List<String> args;
  210. for (int i = 0; i < p_arguments.size(); i++) {
  211. args.push_back(p_arguments[i]);
  212. }
  213. OS::ProcessID pid = 0;
  214. Error err = OS::get_singleton()->create_process(p_path, args, &pid);
  215. if (err != OK) {
  216. return -1;
  217. }
  218. return pid;
  219. }
  220. Error _OS::kill(int p_pid) {
  221. return OS::get_singleton()->kill(p_pid);
  222. }
  223. int _OS::get_process_id() const {
  224. return OS::get_singleton()->get_process_id();
  225. }
  226. bool _OS::has_environment(const String &p_var) const {
  227. return OS::get_singleton()->has_environment(p_var);
  228. }
  229. String _OS::get_environment(const String &p_var) const {
  230. return OS::get_singleton()->get_environment(p_var);
  231. }
  232. bool _OS::set_environment(const String &p_var, const String &p_value) const {
  233. return OS::get_singleton()->set_environment(p_var, p_value);
  234. }
  235. String _OS::get_name() const {
  236. return OS::get_singleton()->get_name();
  237. }
  238. Vector<String> _OS::get_cmdline_args() {
  239. List<String> cmdline = OS::get_singleton()->get_cmdline_args();
  240. Vector<String> cmdlinev;
  241. for (List<String>::Element *E = cmdline.front(); E; E = E->next()) {
  242. cmdlinev.push_back(E->get());
  243. }
  244. return cmdlinev;
  245. }
  246. String _OS::get_locale() const {
  247. return OS::get_singleton()->get_locale();
  248. }
  249. String _OS::get_model_name() const {
  250. return OS::get_singleton()->get_model_name();
  251. }
  252. Error _OS::set_thread_name(const String &p_name) {
  253. return Thread::set_name(p_name);
  254. }
  255. Thread::ID _OS::get_thread_caller_id() const {
  256. return Thread::get_caller_id();
  257. };
  258. bool _OS::has_feature(const String &p_feature) const {
  259. return OS::get_singleton()->has_feature(p_feature);
  260. }
  261. uint64_t _OS::get_static_memory_usage() const {
  262. return OS::get_singleton()->get_static_memory_usage();
  263. }
  264. uint64_t _OS::get_static_memory_peak_usage() const {
  265. return OS::get_singleton()->get_static_memory_peak_usage();
  266. }
  267. /**
  268. * Get current datetime with consideration for utc and
  269. * dst
  270. */
  271. Dictionary _OS::get_datetime(bool utc) const {
  272. Dictionary dated = get_date(utc);
  273. Dictionary timed = get_time(utc);
  274. List<Variant> keys;
  275. timed.get_key_list(&keys);
  276. for (int i = 0; i < keys.size(); i++) {
  277. dated[keys[i]] = timed[keys[i]];
  278. }
  279. return dated;
  280. }
  281. Dictionary _OS::get_date(bool utc) const {
  282. OS::Date date = OS::get_singleton()->get_date(utc);
  283. Dictionary dated;
  284. dated[YEAR_KEY] = date.year;
  285. dated[MONTH_KEY] = date.month;
  286. dated[DAY_KEY] = date.day;
  287. dated[WEEKDAY_KEY] = date.weekday;
  288. dated[DST_KEY] = date.dst;
  289. return dated;
  290. }
  291. Dictionary _OS::get_time(bool utc) const {
  292. OS::Time time = OS::get_singleton()->get_time(utc);
  293. Dictionary timed;
  294. timed[HOUR_KEY] = time.hour;
  295. timed[MINUTE_KEY] = time.min;
  296. timed[SECOND_KEY] = time.sec;
  297. return timed;
  298. }
  299. /**
  300. * Get an epoch time value from a dictionary of time values
  301. * @p datetime must be populated with the following keys:
  302. * day, hour, minute, month, second, year. (dst is ignored).
  303. *
  304. * You can pass the output from
  305. * get_datetime_from_unix_time directly into this function
  306. *
  307. * @param datetime dictionary of date and time values to convert
  308. *
  309. * @return epoch calculated
  310. */
  311. int64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const {
  312. // if datetime is an empty Dictionary throws an error
  313. ERR_FAIL_COND_V_MSG(datetime.is_empty(), 0, "Invalid datetime Dictionary: Dictionary is empty");
  314. // Bunch of conversion constants
  315. static const unsigned int SECONDS_PER_MINUTE = 60;
  316. static const unsigned int MINUTES_PER_HOUR = 60;
  317. static const unsigned int HOURS_PER_DAY = 24;
  318. static const unsigned int SECONDS_PER_HOUR = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;
  319. static const unsigned int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;
  320. // Get all time values from the dictionary, set to zero if it doesn't exist.
  321. // Risk incorrect calculation over throwing errors
  322. unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast<unsigned int>(datetime[SECOND_KEY]) : 0);
  323. unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast<unsigned int>(datetime[MINUTE_KEY]) : 0);
  324. unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast<unsigned int>(datetime[HOUR_KEY]) : 0);
  325. unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast<unsigned int>(datetime[DAY_KEY]) : 1);
  326. unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast<unsigned int>(datetime[MONTH_KEY]) : 1);
  327. unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast<unsigned int>(datetime[YEAR_KEY]) : 0);
  328. /// How many days come before each month (0-12)
  329. static const unsigned short int DAYS_PAST_THIS_YEAR_TABLE[2][13] = {
  330. /* Normal years. */
  331. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
  332. /* Leap years. */
  333. { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
  334. };
  335. ERR_FAIL_COND_V_MSG(second > 59, 0, "Invalid second value of: " + itos(second) + ".");
  336. ERR_FAIL_COND_V_MSG(minute > 59, 0, "Invalid minute value of: " + itos(minute) + ".");
  337. ERR_FAIL_COND_V_MSG(hour > 23, 0, "Invalid hour value of: " + itos(hour) + ".");
  338. ERR_FAIL_COND_V_MSG(month > 12 || month == 0, 0, "Invalid month value of: " + itos(month) + ".");
  339. // Do this check after month is tested as valid
  340. ERR_FAIL_COND_V_MSG(day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1] || day == 0, 0, "Invalid day value of '" + itos(day) + "' which is larger than '" + itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1]) + "' or 0.");
  341. // Calculate all the seconds from months past in this year
  342. uint64_t SECONDS_FROM_MONTHS_PAST_THIS_YEAR = DAYS_PAST_THIS_YEAR_TABLE[LEAPYEAR(year)][month - 1] * SECONDS_PER_DAY;
  343. int64_t SECONDS_FROM_YEARS_PAST = 0;
  344. if (year >= EPOCH_YR) {
  345. for (unsigned int iyear = EPOCH_YR; iyear < year; iyear++) {
  346. SECONDS_FROM_YEARS_PAST += YEARSIZE(iyear) * SECONDS_PER_DAY;
  347. }
  348. } else {
  349. for (unsigned int iyear = EPOCH_YR - 1; iyear >= year; iyear--) {
  350. SECONDS_FROM_YEARS_PAST -= YEARSIZE(iyear) * SECONDS_PER_DAY;
  351. }
  352. }
  353. int64_t epoch =
  354. second +
  355. minute * SECONDS_PER_MINUTE +
  356. hour * SECONDS_PER_HOUR +
  357. // Subtract 1 from day, since the current day isn't over yet
  358. // and we cannot count all 24 hours.
  359. (day - 1) * SECONDS_PER_DAY +
  360. SECONDS_FROM_MONTHS_PAST_THIS_YEAR +
  361. SECONDS_FROM_YEARS_PAST;
  362. return epoch;
  363. }
  364. /**
  365. * Get a dictionary of time values when given epoch time
  366. *
  367. * Dictionary Time values will be a union if values from #get_time
  368. * and #get_date dictionaries (with the exception of dst =
  369. * day light standard time, as it cannot be determined from epoch)
  370. *
  371. * @param unix_time_val epoch time to convert
  372. *
  373. * @return dictionary of date and time values
  374. */
  375. Dictionary _OS::get_datetime_from_unix_time(int64_t unix_time_val) const {
  376. OS::Date date;
  377. OS::Time time;
  378. long dayclock, dayno;
  379. int year = EPOCH_YR;
  380. if (unix_time_val >= 0) {
  381. dayno = unix_time_val / SECS_DAY;
  382. dayclock = unix_time_val % SECS_DAY;
  383. /* day 0 was a thursday */
  384. date.weekday = static_cast<OS::Weekday>((dayno + 4) % 7);
  385. while (dayno >= YEARSIZE(year)) {
  386. dayno -= YEARSIZE(year);
  387. year++;
  388. }
  389. } else {
  390. dayno = (unix_time_val - SECS_DAY + 1) / SECS_DAY;
  391. dayclock = unix_time_val - dayno * SECS_DAY;
  392. date.weekday = static_cast<OS::Weekday>(((dayno % 7) + 11) % 7);
  393. do {
  394. year--;
  395. dayno += YEARSIZE(year);
  396. } while (dayno < 0);
  397. }
  398. time.sec = dayclock % 60;
  399. time.min = (dayclock % 3600) / 60;
  400. time.hour = dayclock / 3600;
  401. date.year = year;
  402. size_t imonth = 0;
  403. while ((unsigned long)dayno >= MONTH_DAYS_TABLE[LEAPYEAR(year)][imonth]) {
  404. dayno -= MONTH_DAYS_TABLE[LEAPYEAR(year)][imonth];
  405. imonth++;
  406. }
  407. /// Add 1 to month to make sure months are indexed starting at 1
  408. date.month = static_cast<OS::Month>(imonth + 1);
  409. date.day = dayno + 1;
  410. Dictionary timed;
  411. timed[HOUR_KEY] = time.hour;
  412. timed[MINUTE_KEY] = time.min;
  413. timed[SECOND_KEY] = time.sec;
  414. timed[YEAR_KEY] = date.year;
  415. timed[MONTH_KEY] = date.month;
  416. timed[DAY_KEY] = date.day;
  417. timed[WEEKDAY_KEY] = date.weekday;
  418. return timed;
  419. }
  420. Dictionary _OS::get_time_zone_info() const {
  421. OS::TimeZoneInfo info = OS::get_singleton()->get_time_zone_info();
  422. Dictionary infod;
  423. infod["bias"] = info.bias;
  424. infod["name"] = info.name;
  425. return infod;
  426. }
  427. double _OS::get_unix_time() const {
  428. return OS::get_singleton()->get_unix_time();
  429. }
  430. /** This method uses a signed argument for better error reporting as it's used from the scripting API. */
  431. void _OS::delay_usec(int p_usec) const {
  432. ERR_FAIL_COND_MSG(
  433. p_usec < 0,
  434. vformat("Can't sleep for %d microseconds. The delay provided must be greater than or equal to 0 microseconds.", p_usec));
  435. OS::get_singleton()->delay_usec(p_usec);
  436. }
  437. /** This method uses a signed argument for better error reporting as it's used from the scripting API. */
  438. void _OS::delay_msec(int p_msec) const {
  439. ERR_FAIL_COND_MSG(
  440. p_msec < 0,
  441. vformat("Can't sleep for %d milliseconds. The delay provided must be greater than or equal to 0 milliseconds.", p_msec));
  442. OS::get_singleton()->delay_usec(int64_t(p_msec) * 1000);
  443. }
  444. uint32_t _OS::get_ticks_msec() const {
  445. return OS::get_singleton()->get_ticks_msec();
  446. }
  447. uint64_t _OS::get_ticks_usec() const {
  448. return OS::get_singleton()->get_ticks_usec();
  449. }
  450. bool _OS::can_use_threads() const {
  451. return OS::get_singleton()->can_use_threads();
  452. }
  453. bool _OS::is_userfs_persistent() const {
  454. return OS::get_singleton()->is_userfs_persistent();
  455. }
  456. int _OS::get_processor_count() const {
  457. return OS::get_singleton()->get_processor_count();
  458. }
  459. bool _OS::is_stdout_verbose() const {
  460. return OS::get_singleton()->is_stdout_verbose();
  461. }
  462. void _OS::dump_memory_to_file(const String &p_file) {
  463. OS::get_singleton()->dump_memory_to_file(p_file.utf8().get_data());
  464. }
  465. struct _OSCoreBindImg {
  466. String path;
  467. Size2 size;
  468. int fmt = 0;
  469. ObjectID id;
  470. int vram = 0;
  471. bool operator<(const _OSCoreBindImg &p_img) const { return vram == p_img.vram ? id < p_img.id : vram > p_img.vram; }
  472. };
  473. void _OS::print_all_textures_by_size() {
  474. List<_OSCoreBindImg> imgs;
  475. uint64_t total = 0;
  476. {
  477. List<Ref<Resource>> rsrc;
  478. ResourceCache::get_cached_resources(&rsrc);
  479. for (List<Ref<Resource>>::Element *E = rsrc.front(); E; E = E->next()) {
  480. if (!E->get()->is_class("ImageTexture")) {
  481. continue;
  482. }
  483. Size2 size = E->get()->call("get_size");
  484. int fmt = E->get()->call("get_format");
  485. _OSCoreBindImg img;
  486. img.size = size;
  487. img.fmt = fmt;
  488. img.path = E->get()->get_path();
  489. img.vram = Image::get_image_data_size(img.size.width, img.size.height, Image::Format(img.fmt));
  490. img.id = E->get()->get_instance_id();
  491. total += img.vram;
  492. imgs.push_back(img);
  493. }
  494. }
  495. imgs.sort();
  496. for (List<_OSCoreBindImg>::Element *E = imgs.front(); E; E = E->next()) {
  497. total -= E->get().vram;
  498. }
  499. }
  500. void _OS::print_resources_by_type(const Vector<String> &p_types) {
  501. Map<String, int> type_count;
  502. List<Ref<Resource>> resources;
  503. ResourceCache::get_cached_resources(&resources);
  504. for (List<Ref<Resource>>::Element *E = resources.front(); E; E = E->next()) {
  505. Ref<Resource> r = E->get();
  506. bool found = false;
  507. for (int i = 0; i < p_types.size(); i++) {
  508. if (r->is_class(p_types[i])) {
  509. found = true;
  510. }
  511. }
  512. if (!found) {
  513. continue;
  514. }
  515. if (!type_count.has(r->get_class())) {
  516. type_count[r->get_class()] = 0;
  517. }
  518. type_count[r->get_class()]++;
  519. }
  520. }
  521. void _OS::print_all_resources(const String &p_to_file) {
  522. OS::get_singleton()->print_all_resources(p_to_file);
  523. }
  524. void _OS::print_resources_in_use(bool p_short) {
  525. OS::get_singleton()->print_resources_in_use(p_short);
  526. }
  527. void _OS::dump_resources_to_file(const String &p_file) {
  528. OS::get_singleton()->dump_resources_to_file(p_file.utf8().get_data());
  529. }
  530. String _OS::get_user_data_dir() const {
  531. return OS::get_singleton()->get_user_data_dir();
  532. }
  533. bool _OS::is_debug_build() const {
  534. #ifdef DEBUG_ENABLED
  535. return true;
  536. #else
  537. return false;
  538. #endif
  539. }
  540. String _OS::get_system_dir(SystemDir p_dir) const {
  541. return OS::get_singleton()->get_system_dir(OS::SystemDir(p_dir));
  542. }
  543. String _OS::get_keycode_string(uint32_t p_code) const {
  544. return keycode_get_string(p_code);
  545. }
  546. bool _OS::is_keycode_unicode(uint32_t p_unicode) const {
  547. return keycode_has_unicode(p_unicode);
  548. }
  549. int _OS::find_keycode_from_string(const String &p_code) const {
  550. return find_keycode(p_code);
  551. }
  552. bool _OS::request_permission(const String &p_name) {
  553. return OS::get_singleton()->request_permission(p_name);
  554. }
  555. bool _OS::request_permissions() {
  556. return OS::get_singleton()->request_permissions();
  557. }
  558. Vector<String> _OS::get_granted_permissions() const {
  559. return OS::get_singleton()->get_granted_permissions();
  560. }
  561. String _OS::get_unique_id() const {
  562. return OS::get_singleton()->get_unique_id();
  563. }
  564. _OS *_OS::singleton = nullptr;
  565. void _OS::_bind_methods() {
  566. ClassDB::bind_method(D_METHOD("get_connected_midi_inputs"), &_OS::get_connected_midi_inputs);
  567. ClassDB::bind_method(D_METHOD("open_midi_inputs"), &_OS::open_midi_inputs);
  568. ClassDB::bind_method(D_METHOD("close_midi_inputs"), &_OS::close_midi_inputs);
  569. ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode", "enable"), &_OS::set_low_processor_usage_mode);
  570. ClassDB::bind_method(D_METHOD("is_in_low_processor_usage_mode"), &_OS::is_in_low_processor_usage_mode);
  571. ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode_sleep_usec", "usec"), &_OS::set_low_processor_usage_mode_sleep_usec);
  572. ClassDB::bind_method(D_METHOD("get_low_processor_usage_mode_sleep_usec"), &_OS::get_low_processor_usage_mode_sleep_usec);
  573. ClassDB::bind_method(D_METHOD("get_processor_count"), &_OS::get_processor_count);
  574. ClassDB::bind_method(D_METHOD("get_executable_path"), &_OS::get_executable_path);
  575. ClassDB::bind_method(D_METHOD("execute", "path", "arguments", "output", "read_stderr"), &_OS::execute, DEFVAL(Array()), DEFVAL(false));
  576. ClassDB::bind_method(D_METHOD("create_process", "path", "arguments"), &_OS::create_process);
  577. ClassDB::bind_method(D_METHOD("kill", "pid"), &_OS::kill);
  578. ClassDB::bind_method(D_METHOD("shell_open", "uri"), &_OS::shell_open);
  579. ClassDB::bind_method(D_METHOD("get_process_id"), &_OS::get_process_id);
  580. ClassDB::bind_method(D_METHOD("get_environment", "variable"), &_OS::get_environment);
  581. ClassDB::bind_method(D_METHOD("set_environment", "variable", "value"), &_OS::set_environment);
  582. ClassDB::bind_method(D_METHOD("has_environment", "variable"), &_OS::has_environment);
  583. ClassDB::bind_method(D_METHOD("get_name"), &_OS::get_name);
  584. ClassDB::bind_method(D_METHOD("get_cmdline_args"), &_OS::get_cmdline_args);
  585. ClassDB::bind_method(D_METHOD("get_datetime", "utc"), &_OS::get_datetime, DEFVAL(false));
  586. ClassDB::bind_method(D_METHOD("get_date", "utc"), &_OS::get_date, DEFVAL(false));
  587. ClassDB::bind_method(D_METHOD("get_time", "utc"), &_OS::get_time, DEFVAL(false));
  588. ClassDB::bind_method(D_METHOD("get_time_zone_info"), &_OS::get_time_zone_info);
  589. ClassDB::bind_method(D_METHOD("get_unix_time"), &_OS::get_unix_time);
  590. ClassDB::bind_method(D_METHOD("get_datetime_from_unix_time", "unix_time_val"), &_OS::get_datetime_from_unix_time);
  591. ClassDB::bind_method(D_METHOD("get_unix_time_from_datetime", "datetime"), &_OS::get_unix_time_from_datetime);
  592. ClassDB::bind_method(D_METHOD("delay_usec", "usec"), &_OS::delay_usec);
  593. ClassDB::bind_method(D_METHOD("delay_msec", "msec"), &_OS::delay_msec);
  594. ClassDB::bind_method(D_METHOD("get_ticks_msec"), &_OS::get_ticks_msec);
  595. ClassDB::bind_method(D_METHOD("get_ticks_usec"), &_OS::get_ticks_usec);
  596. ClassDB::bind_method(D_METHOD("get_locale"), &_OS::get_locale);
  597. ClassDB::bind_method(D_METHOD("get_model_name"), &_OS::get_model_name);
  598. ClassDB::bind_method(D_METHOD("is_userfs_persistent"), &_OS::is_userfs_persistent);
  599. ClassDB::bind_method(D_METHOD("is_stdout_verbose"), &_OS::is_stdout_verbose);
  600. ClassDB::bind_method(D_METHOD("can_use_threads"), &_OS::can_use_threads);
  601. ClassDB::bind_method(D_METHOD("is_debug_build"), &_OS::is_debug_build);
  602. ClassDB::bind_method(D_METHOD("dump_memory_to_file", "file"), &_OS::dump_memory_to_file);
  603. ClassDB::bind_method(D_METHOD("dump_resources_to_file", "file"), &_OS::dump_resources_to_file);
  604. ClassDB::bind_method(D_METHOD("print_resources_in_use", "short"), &_OS::print_resources_in_use, DEFVAL(false));
  605. ClassDB::bind_method(D_METHOD("print_all_resources", "tofile"), &_OS::print_all_resources, DEFVAL(""));
  606. ClassDB::bind_method(D_METHOD("get_static_memory_usage"), &_OS::get_static_memory_usage);
  607. ClassDB::bind_method(D_METHOD("get_static_memory_peak_usage"), &_OS::get_static_memory_peak_usage);
  608. ClassDB::bind_method(D_METHOD("get_user_data_dir"), &_OS::get_user_data_dir);
  609. ClassDB::bind_method(D_METHOD("get_system_dir", "dir"), &_OS::get_system_dir);
  610. ClassDB::bind_method(D_METHOD("get_unique_id"), &_OS::get_unique_id);
  611. ClassDB::bind_method(D_METHOD("print_all_textures_by_size"), &_OS::print_all_textures_by_size);
  612. ClassDB::bind_method(D_METHOD("print_resources_by_type", "types"), &_OS::print_resources_by_type);
  613. ClassDB::bind_method(D_METHOD("get_keycode_string", "code"), &_OS::get_keycode_string);
  614. ClassDB::bind_method(D_METHOD("is_keycode_unicode", "code"), &_OS::is_keycode_unicode);
  615. ClassDB::bind_method(D_METHOD("find_keycode_from_string", "string"), &_OS::find_keycode_from_string);
  616. ClassDB::bind_method(D_METHOD("set_use_file_access_save_and_swap", "enabled"), &_OS::set_use_file_access_save_and_swap);
  617. ClassDB::bind_method(D_METHOD("set_thread_name", "name"), &_OS::set_thread_name);
  618. ClassDB::bind_method(D_METHOD("get_thread_caller_id"), &_OS::get_thread_caller_id);
  619. ClassDB::bind_method(D_METHOD("has_feature", "tag_name"), &_OS::has_feature);
  620. ClassDB::bind_method(D_METHOD("request_permission", "name"), &_OS::request_permission);
  621. ClassDB::bind_method(D_METHOD("request_permissions"), &_OS::request_permissions);
  622. ClassDB::bind_method(D_METHOD("get_granted_permissions"), &_OS::get_granted_permissions);
  623. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "low_processor_usage_mode"), "set_low_processor_usage_mode", "is_in_low_processor_usage_mode");
  624. ADD_PROPERTY(PropertyInfo(Variant::INT, "low_processor_usage_mode_sleep_usec"), "set_low_processor_usage_mode_sleep_usec", "get_low_processor_usage_mode_sleep_usec");
  625. // Those default values need to be specified for the docs generator,
  626. // to avoid using values from the documentation writer's own OS instance.
  627. ADD_PROPERTY_DEFAULT("exit_code", 0);
  628. ADD_PROPERTY_DEFAULT("low_processor_usage_mode", false);
  629. ADD_PROPERTY_DEFAULT("low_processor_usage_mode_sleep_usec", 6900);
  630. BIND_ENUM_CONSTANT(VIDEO_DRIVER_GLES2);
  631. BIND_ENUM_CONSTANT(VIDEO_DRIVER_VULKAN);
  632. BIND_ENUM_CONSTANT(DAY_SUNDAY);
  633. BIND_ENUM_CONSTANT(DAY_MONDAY);
  634. BIND_ENUM_CONSTANT(DAY_TUESDAY);
  635. BIND_ENUM_CONSTANT(DAY_WEDNESDAY);
  636. BIND_ENUM_CONSTANT(DAY_THURSDAY);
  637. BIND_ENUM_CONSTANT(DAY_FRIDAY);
  638. BIND_ENUM_CONSTANT(DAY_SATURDAY);
  639. BIND_ENUM_CONSTANT(MONTH_JANUARY);
  640. BIND_ENUM_CONSTANT(MONTH_FEBRUARY);
  641. BIND_ENUM_CONSTANT(MONTH_MARCH);
  642. BIND_ENUM_CONSTANT(MONTH_APRIL);
  643. BIND_ENUM_CONSTANT(MONTH_MAY);
  644. BIND_ENUM_CONSTANT(MONTH_JUNE);
  645. BIND_ENUM_CONSTANT(MONTH_JULY);
  646. BIND_ENUM_CONSTANT(MONTH_AUGUST);
  647. BIND_ENUM_CONSTANT(MONTH_SEPTEMBER);
  648. BIND_ENUM_CONSTANT(MONTH_OCTOBER);
  649. BIND_ENUM_CONSTANT(MONTH_NOVEMBER);
  650. BIND_ENUM_CONSTANT(MONTH_DECEMBER);
  651. BIND_ENUM_CONSTANT(SYSTEM_DIR_DESKTOP);
  652. BIND_ENUM_CONSTANT(SYSTEM_DIR_DCIM);
  653. BIND_ENUM_CONSTANT(SYSTEM_DIR_DOCUMENTS);
  654. BIND_ENUM_CONSTANT(SYSTEM_DIR_DOWNLOADS);
  655. BIND_ENUM_CONSTANT(SYSTEM_DIR_MOVIES);
  656. BIND_ENUM_CONSTANT(SYSTEM_DIR_MUSIC);
  657. BIND_ENUM_CONSTANT(SYSTEM_DIR_PICTURES);
  658. BIND_ENUM_CONSTANT(SYSTEM_DIR_RINGTONES);
  659. }
  660. ////// _Geometry2D //////
  661. _Geometry2D *_Geometry2D::singleton = nullptr;
  662. _Geometry2D *_Geometry2D::get_singleton() {
  663. return singleton;
  664. }
  665. bool _Geometry2D::is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  666. return Geometry2D::is_point_in_circle(p_point, p_circle_pos, p_circle_radius);
  667. }
  668. real_t _Geometry2D::segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  669. return Geometry2D::segment_intersects_circle(p_from, p_to, p_circle_pos, p_circle_radius);
  670. }
  671. Variant _Geometry2D::segment_intersects_segment(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b) {
  672. Vector2 result;
  673. if (Geometry2D::segment_intersects_segment(p_from_a, p_to_a, p_from_b, p_to_b, &result)) {
  674. return result;
  675. } else {
  676. return Variant();
  677. }
  678. }
  679. Variant _Geometry2D::line_intersects_line(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b) {
  680. Vector2 result;
  681. if (Geometry2D::line_intersects_line(p_from_a, p_dir_a, p_from_b, p_dir_b, result)) {
  682. return result;
  683. } else {
  684. return Variant();
  685. }
  686. }
  687. Vector<Vector2> _Geometry2D::get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2) {
  688. Vector2 r1, r2;
  689. Geometry2D::get_closest_points_between_segments(p1, q1, p2, q2, r1, r2);
  690. Vector<Vector2> r;
  691. r.resize(2);
  692. r.set(0, r1);
  693. r.set(1, r2);
  694. return r;
  695. }
  696. Vector2 _Geometry2D::get_closest_point_to_segment(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) {
  697. Vector2 s[2] = { p_a, p_b };
  698. return Geometry2D::get_closest_point_to_segment(p_point, s);
  699. }
  700. Vector2 _Geometry2D::get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) {
  701. Vector2 s[2] = { p_a, p_b };
  702. return Geometry2D::get_closest_point_to_segment_uncapped(p_point, s);
  703. }
  704. bool _Geometry2D::point_is_inside_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) const {
  705. return Geometry2D::is_point_in_triangle(s, a, b, c);
  706. }
  707. bool _Geometry2D::is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  708. return Geometry2D::is_polygon_clockwise(p_polygon);
  709. }
  710. bool _Geometry2D::is_point_in_polygon(const Point2 &p_point, const Vector<Vector2> &p_polygon) {
  711. return Geometry2D::is_point_in_polygon(p_point, p_polygon);
  712. }
  713. Vector<int> _Geometry2D::triangulate_polygon(const Vector<Vector2> &p_polygon) {
  714. return Geometry2D::triangulate_polygon(p_polygon);
  715. }
  716. Vector<int> _Geometry2D::triangulate_delaunay(const Vector<Vector2> &p_points) {
  717. return Geometry2D::triangulate_delaunay(p_points);
  718. }
  719. Vector<Point2> _Geometry2D::convex_hull(const Vector<Point2> &p_points) {
  720. return Geometry2D::convex_hull(p_points);
  721. }
  722. Array _Geometry2D::merge_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  723. Vector<Vector<Point2>> polys = Geometry2D::merge_polygons(p_polygon_a, p_polygon_b);
  724. Array ret;
  725. for (int i = 0; i < polys.size(); ++i) {
  726. ret.push_back(polys[i]);
  727. }
  728. return ret;
  729. }
  730. Array _Geometry2D::clip_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  731. Vector<Vector<Point2>> polys = Geometry2D::clip_polygons(p_polygon_a, p_polygon_b);
  732. Array ret;
  733. for (int i = 0; i < polys.size(); ++i) {
  734. ret.push_back(polys[i]);
  735. }
  736. return ret;
  737. }
  738. Array _Geometry2D::intersect_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  739. Vector<Vector<Point2>> polys = Geometry2D::intersect_polygons(p_polygon_a, p_polygon_b);
  740. Array ret;
  741. for (int i = 0; i < polys.size(); ++i) {
  742. ret.push_back(polys[i]);
  743. }
  744. return ret;
  745. }
  746. Array _Geometry2D::exclude_polygons(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  747. Vector<Vector<Point2>> polys = Geometry2D::exclude_polygons(p_polygon_a, p_polygon_b);
  748. Array ret;
  749. for (int i = 0; i < polys.size(); ++i) {
  750. ret.push_back(polys[i]);
  751. }
  752. return ret;
  753. }
  754. Array _Geometry2D::clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  755. Vector<Vector<Point2>> polys = Geometry2D::clip_polyline_with_polygon(p_polyline, p_polygon);
  756. Array ret;
  757. for (int i = 0; i < polys.size(); ++i) {
  758. ret.push_back(polys[i]);
  759. }
  760. return ret;
  761. }
  762. Array _Geometry2D::intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  763. Vector<Vector<Point2>> polys = Geometry2D::intersect_polyline_with_polygon(p_polyline, p_polygon);
  764. Array ret;
  765. for (int i = 0; i < polys.size(); ++i) {
  766. ret.push_back(polys[i]);
  767. }
  768. return ret;
  769. }
  770. Array _Geometry2D::offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  771. Vector<Vector<Point2>> polys = Geometry2D::offset_polygon(p_polygon, p_delta, Geometry2D::PolyJoinType(p_join_type));
  772. Array ret;
  773. for (int i = 0; i < polys.size(); ++i) {
  774. ret.push_back(polys[i]);
  775. }
  776. return ret;
  777. }
  778. Array _Geometry2D::offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  779. Vector<Vector<Point2>> polys = Geometry2D::offset_polyline(p_polygon, p_delta, Geometry2D::PolyJoinType(p_join_type), Geometry2D::PolyEndType(p_end_type));
  780. Array ret;
  781. for (int i = 0; i < polys.size(); ++i) {
  782. ret.push_back(polys[i]);
  783. }
  784. return ret;
  785. }
  786. Dictionary _Geometry2D::make_atlas(const Vector<Size2> &p_rects) {
  787. Dictionary ret;
  788. Vector<Size2i> rects;
  789. for (int i = 0; i < p_rects.size(); i++) {
  790. rects.push_back(p_rects[i]);
  791. }
  792. Vector<Point2i> result;
  793. Size2i size;
  794. Geometry2D::make_atlas(rects, result, size);
  795. Size2 r_size = size;
  796. Vector<Point2> r_result;
  797. for (int i = 0; i < result.size(); i++) {
  798. r_result.push_back(result[i]);
  799. }
  800. ret["points"] = r_result;
  801. ret["size"] = r_size;
  802. return ret;
  803. }
  804. void _Geometry2D::_bind_methods() {
  805. ClassDB::bind_method(D_METHOD("is_point_in_circle", "point", "circle_position", "circle_radius"), &_Geometry2D::is_point_in_circle);
  806. ClassDB::bind_method(D_METHOD("segment_intersects_segment", "from_a", "to_a", "from_b", "to_b"), &_Geometry2D::segment_intersects_segment);
  807. ClassDB::bind_method(D_METHOD("line_intersects_line", "from_a", "dir_a", "from_b", "dir_b"), &_Geometry2D::line_intersects_line);
  808. ClassDB::bind_method(D_METHOD("get_closest_points_between_segments", "p1", "q1", "p2", "q2"), &_Geometry2D::get_closest_points_between_segments);
  809. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment", "point", "s1", "s2"), &_Geometry2D::get_closest_point_to_segment);
  810. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped", "point", "s1", "s2"), &_Geometry2D::get_closest_point_to_segment_uncapped);
  811. ClassDB::bind_method(D_METHOD("point_is_inside_triangle", "point", "a", "b", "c"), &_Geometry2D::point_is_inside_triangle);
  812. ClassDB::bind_method(D_METHOD("is_polygon_clockwise", "polygon"), &_Geometry2D::is_polygon_clockwise);
  813. ClassDB::bind_method(D_METHOD("is_point_in_polygon", "point", "polygon"), &_Geometry2D::is_point_in_polygon);
  814. ClassDB::bind_method(D_METHOD("triangulate_polygon", "polygon"), &_Geometry2D::triangulate_polygon);
  815. ClassDB::bind_method(D_METHOD("triangulate_delaunay", "points"), &_Geometry2D::triangulate_delaunay);
  816. ClassDB::bind_method(D_METHOD("convex_hull", "points"), &_Geometry2D::convex_hull);
  817. ClassDB::bind_method(D_METHOD("merge_polygons", "polygon_a", "polygon_b"), &_Geometry2D::merge_polygons);
  818. ClassDB::bind_method(D_METHOD("clip_polygons", "polygon_a", "polygon_b"), &_Geometry2D::clip_polygons);
  819. ClassDB::bind_method(D_METHOD("intersect_polygons", "polygon_a", "polygon_b"), &_Geometry2D::intersect_polygons);
  820. ClassDB::bind_method(D_METHOD("exclude_polygons", "polygon_a", "polygon_b"), &_Geometry2D::exclude_polygons);
  821. ClassDB::bind_method(D_METHOD("clip_polyline_with_polygon", "polyline", "polygon"), &_Geometry2D::clip_polyline_with_polygon);
  822. ClassDB::bind_method(D_METHOD("intersect_polyline_with_polygon", "polyline", "polygon"), &_Geometry2D::intersect_polyline_with_polygon);
  823. ClassDB::bind_method(D_METHOD("offset_polygon", "polygon", "delta", "join_type"), &_Geometry2D::offset_polygon, DEFVAL(JOIN_SQUARE));
  824. ClassDB::bind_method(D_METHOD("offset_polyline", "polyline", "delta", "join_type", "end_type"), &_Geometry2D::offset_polyline, DEFVAL(JOIN_SQUARE), DEFVAL(END_SQUARE));
  825. ClassDB::bind_method(D_METHOD("make_atlas", "sizes"), &_Geometry2D::make_atlas);
  826. BIND_ENUM_CONSTANT(OPERATION_UNION);
  827. BIND_ENUM_CONSTANT(OPERATION_DIFFERENCE);
  828. BIND_ENUM_CONSTANT(OPERATION_INTERSECTION);
  829. BIND_ENUM_CONSTANT(OPERATION_XOR);
  830. BIND_ENUM_CONSTANT(JOIN_SQUARE);
  831. BIND_ENUM_CONSTANT(JOIN_ROUND);
  832. BIND_ENUM_CONSTANT(JOIN_MITER);
  833. BIND_ENUM_CONSTANT(END_POLYGON);
  834. BIND_ENUM_CONSTANT(END_JOINED);
  835. BIND_ENUM_CONSTANT(END_BUTT);
  836. BIND_ENUM_CONSTANT(END_SQUARE);
  837. BIND_ENUM_CONSTANT(END_ROUND);
  838. }
  839. ////// _Geometry3D //////
  840. _Geometry3D *_Geometry3D::singleton = nullptr;
  841. _Geometry3D *_Geometry3D::get_singleton() {
  842. return singleton;
  843. }
  844. Vector<Plane> _Geometry3D::build_box_planes(const Vector3 &p_extents) {
  845. return Geometry3D::build_box_planes(p_extents);
  846. }
  847. Vector<Plane> _Geometry3D::build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis) {
  848. return Geometry3D::build_cylinder_planes(p_radius, p_height, p_sides, p_axis);
  849. }
  850. Vector<Plane> _Geometry3D::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  851. return Geometry3D::build_capsule_planes(p_radius, p_height, p_sides, p_lats, p_axis);
  852. }
  853. Vector<Vector3> _Geometry3D::get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2) {
  854. Vector3 r1, r2;
  855. Geometry3D::get_closest_points_between_segments(p1, p2, q1, q2, r1, r2);
  856. Vector<Vector3> r;
  857. r.resize(2);
  858. r.set(0, r1);
  859. r.set(1, r2);
  860. return r;
  861. }
  862. Vector3 _Geometry3D::get_closest_point_to_segment(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) {
  863. Vector3 s[2] = { p_a, p_b };
  864. return Geometry3D::get_closest_point_to_segment(p_point, s);
  865. }
  866. Vector3 _Geometry3D::get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) {
  867. Vector3 s[2] = { p_a, p_b };
  868. return Geometry3D::get_closest_point_to_segment_uncapped(p_point, s);
  869. }
  870. Variant _Geometry3D::ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) {
  871. Vector3 res;
  872. if (Geometry3D::ray_intersects_triangle(p_from, p_dir, p_v0, p_v1, p_v2, &res)) {
  873. return res;
  874. } else {
  875. return Variant();
  876. }
  877. }
  878. Variant _Geometry3D::segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) {
  879. Vector3 res;
  880. if (Geometry3D::segment_intersects_triangle(p_from, p_to, p_v0, p_v1, p_v2, &res)) {
  881. return res;
  882. } else {
  883. return Variant();
  884. }
  885. }
  886. Vector<Vector3> _Geometry3D::segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius) {
  887. Vector<Vector3> r;
  888. Vector3 res, norm;
  889. if (!Geometry3D::segment_intersects_sphere(p_from, p_to, p_sphere_pos, p_sphere_radius, &res, &norm)) {
  890. return r;
  891. }
  892. r.resize(2);
  893. r.set(0, res);
  894. r.set(1, norm);
  895. return r;
  896. }
  897. Vector<Vector3> _Geometry3D::segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius) {
  898. Vector<Vector3> r;
  899. Vector3 res, norm;
  900. if (!Geometry3D::segment_intersects_cylinder(p_from, p_to, p_height, p_radius, &res, &norm)) {
  901. return r;
  902. }
  903. r.resize(2);
  904. r.set(0, res);
  905. r.set(1, norm);
  906. return r;
  907. }
  908. Vector<Vector3> _Geometry3D::segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector<Plane> &p_planes) {
  909. Vector<Vector3> r;
  910. Vector3 res, norm;
  911. if (!Geometry3D::segment_intersects_convex(p_from, p_to, p_planes.ptr(), p_planes.size(), &res, &norm)) {
  912. return r;
  913. }
  914. r.resize(2);
  915. r.set(0, res);
  916. r.set(1, norm);
  917. return r;
  918. }
  919. Vector<Vector3> _Geometry3D::clip_polygon(const Vector<Vector3> &p_points, const Plane &p_plane) {
  920. return Geometry3D::clip_polygon(p_points, p_plane);
  921. }
  922. void _Geometry3D::_bind_methods() {
  923. ClassDB::bind_method(D_METHOD("build_box_planes", "extents"), &_Geometry3D::build_box_planes);
  924. ClassDB::bind_method(D_METHOD("build_cylinder_planes", "radius", "height", "sides", "axis"), &_Geometry3D::build_cylinder_planes, DEFVAL(Vector3::AXIS_Z));
  925. ClassDB::bind_method(D_METHOD("build_capsule_planes", "radius", "height", "sides", "lats", "axis"), &_Geometry3D::build_capsule_planes, DEFVAL(Vector3::AXIS_Z));
  926. ClassDB::bind_method(D_METHOD("get_closest_points_between_segments", "p1", "p2", "q1", "q2"), &_Geometry3D::get_closest_points_between_segments);
  927. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment", "point", "s1", "s2"), &_Geometry3D::get_closest_point_to_segment);
  928. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped", "point", "s1", "s2"), &_Geometry3D::get_closest_point_to_segment_uncapped);
  929. ClassDB::bind_method(D_METHOD("ray_intersects_triangle", "from", "dir", "a", "b", "c"), &_Geometry3D::ray_intersects_triangle);
  930. ClassDB::bind_method(D_METHOD("segment_intersects_triangle", "from", "to", "a", "b", "c"), &_Geometry3D::segment_intersects_triangle);
  931. ClassDB::bind_method(D_METHOD("segment_intersects_sphere", "from", "to", "sphere_position", "sphere_radius"), &_Geometry3D::segment_intersects_sphere);
  932. ClassDB::bind_method(D_METHOD("segment_intersects_cylinder", "from", "to", "height", "radius"), &_Geometry3D::segment_intersects_cylinder);
  933. ClassDB::bind_method(D_METHOD("segment_intersects_convex", "from", "to", "planes"), &_Geometry3D::segment_intersects_convex);
  934. ClassDB::bind_method(D_METHOD("clip_polygon", "points", "plane"), &_Geometry3D::clip_polygon);
  935. }
  936. ////// _File //////
  937. Error _File::open_encrypted(const String &p_path, ModeFlags p_mode_flags, const Vector<uint8_t> &p_key) {
  938. Error err = open(p_path, p_mode_flags);
  939. if (err) {
  940. return err;
  941. }
  942. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  943. err = fae->open_and_parse(f, p_key, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ);
  944. if (err) {
  945. memdelete(fae);
  946. close();
  947. return err;
  948. }
  949. f = fae;
  950. return OK;
  951. }
  952. Error _File::open_encrypted_pass(const String &p_path, ModeFlags p_mode_flags, const String &p_pass) {
  953. Error err = open(p_path, p_mode_flags);
  954. if (err) {
  955. return err;
  956. }
  957. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  958. err = fae->open_and_parse_password(f, p_pass, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ);
  959. if (err) {
  960. memdelete(fae);
  961. close();
  962. return err;
  963. }
  964. f = fae;
  965. return OK;
  966. }
  967. Error _File::open_compressed(const String &p_path, ModeFlags p_mode_flags, CompressionMode p_compress_mode) {
  968. FileAccessCompressed *fac = memnew(FileAccessCompressed);
  969. fac->configure("GCPF", (Compression::Mode)p_compress_mode);
  970. Error err = fac->_open(p_path, p_mode_flags);
  971. if (err) {
  972. memdelete(fac);
  973. return err;
  974. }
  975. f = fac;
  976. return OK;
  977. }
  978. Error _File::open(const String &p_path, ModeFlags p_mode_flags) {
  979. close();
  980. Error err;
  981. f = FileAccess::open(p_path, p_mode_flags, &err);
  982. if (f) {
  983. f->set_endian_swap(eswap);
  984. }
  985. return err;
  986. }
  987. void _File::flush() {
  988. ERR_FAIL_COND_MSG(!f, "File must be opened before flushing.");
  989. f->flush();
  990. }
  991. void _File::close() {
  992. if (f) {
  993. memdelete(f);
  994. }
  995. f = nullptr;
  996. }
  997. bool _File::is_open() const {
  998. return f != nullptr;
  999. }
  1000. String _File::get_path() const {
  1001. ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use.");
  1002. return f->get_path();
  1003. }
  1004. String _File::get_path_absolute() const {
  1005. ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use.");
  1006. return f->get_path_absolute();
  1007. }
  1008. void _File::seek(int64_t p_position) {
  1009. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1010. f->seek(p_position);
  1011. }
  1012. void _File::seek_end(int64_t p_position) {
  1013. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1014. f->seek_end(p_position);
  1015. }
  1016. int64_t _File::get_position() const {
  1017. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1018. return f->get_position();
  1019. }
  1020. int64_t _File::get_len() const {
  1021. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1022. return f->get_len();
  1023. }
  1024. bool _File::eof_reached() const {
  1025. ERR_FAIL_COND_V_MSG(!f, false, "File must be opened before use.");
  1026. return f->eof_reached();
  1027. }
  1028. uint8_t _File::get_8() const {
  1029. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1030. return f->get_8();
  1031. }
  1032. uint16_t _File::get_16() const {
  1033. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1034. return f->get_16();
  1035. }
  1036. uint32_t _File::get_32() const {
  1037. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1038. return f->get_32();
  1039. }
  1040. uint64_t _File::get_64() const {
  1041. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1042. return f->get_64();
  1043. }
  1044. float _File::get_float() const {
  1045. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1046. return f->get_float();
  1047. }
  1048. double _File::get_double() const {
  1049. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1050. return f->get_double();
  1051. }
  1052. real_t _File::get_real() const {
  1053. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1054. return f->get_real();
  1055. }
  1056. Vector<uint8_t> _File::get_buffer(int p_length) const {
  1057. Vector<uint8_t> data;
  1058. ERR_FAIL_COND_V_MSG(!f, data, "File must be opened before use.");
  1059. ERR_FAIL_COND_V_MSG(p_length < 0, data, "Length of buffer cannot be smaller than 0.");
  1060. if (p_length == 0) {
  1061. return data;
  1062. }
  1063. Error err = data.resize(p_length);
  1064. ERR_FAIL_COND_V_MSG(err != OK, data, "Can't resize data to " + itos(p_length) + " elements.");
  1065. uint8_t *w = data.ptrw();
  1066. int len = f->get_buffer(&w[0], p_length);
  1067. ERR_FAIL_COND_V(len < 0, Vector<uint8_t>());
  1068. if (len < p_length) {
  1069. data.resize(p_length);
  1070. }
  1071. return data;
  1072. }
  1073. String _File::get_as_text() const {
  1074. ERR_FAIL_COND_V_MSG(!f, String(), "File must be opened before use.");
  1075. String text;
  1076. size_t original_pos = f->get_position();
  1077. f->seek(0);
  1078. String l = get_line();
  1079. while (!eof_reached()) {
  1080. text += l + "\n";
  1081. l = get_line();
  1082. }
  1083. text += l;
  1084. f->seek(original_pos);
  1085. return text;
  1086. }
  1087. String _File::get_md5(const String &p_path) const {
  1088. return FileAccess::get_md5(p_path);
  1089. }
  1090. String _File::get_sha256(const String &p_path) const {
  1091. return FileAccess::get_sha256(p_path);
  1092. }
  1093. String _File::get_line() const {
  1094. ERR_FAIL_COND_V_MSG(!f, String(), "File must be opened before use.");
  1095. return f->get_line();
  1096. }
  1097. Vector<String> _File::get_csv_line(const String &p_delim) const {
  1098. ERR_FAIL_COND_V_MSG(!f, Vector<String>(), "File must be opened before use.");
  1099. return f->get_csv_line(p_delim);
  1100. }
  1101. /**< use this for files WRITTEN in _big_ endian machines (i.e. amiga/mac)
  1102. * It's not about the current CPU type but file formats.
  1103. * These flags get reset to false (little endian) on each open
  1104. */
  1105. void _File::set_endian_swap(bool p_swap) {
  1106. eswap = p_swap;
  1107. if (f) {
  1108. f->set_endian_swap(p_swap);
  1109. }
  1110. }
  1111. bool _File::get_endian_swap() {
  1112. return eswap;
  1113. }
  1114. Error _File::get_error() const {
  1115. if (!f) {
  1116. return ERR_UNCONFIGURED;
  1117. }
  1118. return f->get_error();
  1119. }
  1120. void _File::store_8(uint8_t p_dest) {
  1121. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1122. f->store_8(p_dest);
  1123. }
  1124. void _File::store_16(uint16_t p_dest) {
  1125. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1126. f->store_16(p_dest);
  1127. }
  1128. void _File::store_32(uint32_t p_dest) {
  1129. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1130. f->store_32(p_dest);
  1131. }
  1132. void _File::store_64(uint64_t p_dest) {
  1133. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1134. f->store_64(p_dest);
  1135. }
  1136. void _File::store_float(float p_dest) {
  1137. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1138. f->store_float(p_dest);
  1139. }
  1140. void _File::store_double(double p_dest) {
  1141. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1142. f->store_double(p_dest);
  1143. }
  1144. void _File::store_real(real_t p_real) {
  1145. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1146. f->store_real(p_real);
  1147. }
  1148. void _File::store_string(const String &p_string) {
  1149. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1150. f->store_string(p_string);
  1151. }
  1152. void _File::store_pascal_string(const String &p_string) {
  1153. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1154. f->store_pascal_string(p_string);
  1155. }
  1156. String _File::get_pascal_string() {
  1157. ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use.");
  1158. return f->get_pascal_string();
  1159. }
  1160. void _File::store_line(const String &p_string) {
  1161. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1162. f->store_line(p_string);
  1163. }
  1164. void _File::store_csv_line(const Vector<String> &p_values, const String &p_delim) {
  1165. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1166. f->store_csv_line(p_values, p_delim);
  1167. }
  1168. void _File::store_buffer(const Vector<uint8_t> &p_buffer) {
  1169. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1170. int len = p_buffer.size();
  1171. if (len == 0) {
  1172. return;
  1173. }
  1174. const uint8_t *r = p_buffer.ptr();
  1175. f->store_buffer(&r[0], len);
  1176. }
  1177. bool _File::file_exists(const String &p_name) const {
  1178. return FileAccess::exists(p_name);
  1179. }
  1180. void _File::store_var(const Variant &p_var, bool p_full_objects) {
  1181. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1182. int len;
  1183. Error err = encode_variant(p_var, nullptr, len, p_full_objects);
  1184. ERR_FAIL_COND_MSG(err != OK, "Error when trying to encode Variant.");
  1185. Vector<uint8_t> buff;
  1186. buff.resize(len);
  1187. uint8_t *w = buff.ptrw();
  1188. err = encode_variant(p_var, &w[0], len, p_full_objects);
  1189. ERR_FAIL_COND_MSG(err != OK, "Error when trying to encode Variant.");
  1190. store_32(len);
  1191. store_buffer(buff);
  1192. }
  1193. Variant _File::get_var(bool p_allow_objects) const {
  1194. ERR_FAIL_COND_V_MSG(!f, Variant(), "File must be opened before use.");
  1195. uint32_t len = get_32();
  1196. Vector<uint8_t> buff = get_buffer(len);
  1197. ERR_FAIL_COND_V((uint32_t)buff.size() != len, Variant());
  1198. const uint8_t *r = buff.ptr();
  1199. Variant v;
  1200. Error err = decode_variant(v, &r[0], len, nullptr, p_allow_objects);
  1201. ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to encode Variant.");
  1202. return v;
  1203. }
  1204. uint64_t _File::get_modified_time(const String &p_file) const {
  1205. return FileAccess::get_modified_time(p_file);
  1206. }
  1207. void _File::_bind_methods() {
  1208. ClassDB::bind_method(D_METHOD("open_encrypted", "path", "mode_flags", "key"), &_File::open_encrypted);
  1209. ClassDB::bind_method(D_METHOD("open_encrypted_with_pass", "path", "mode_flags", "pass"), &_File::open_encrypted_pass);
  1210. ClassDB::bind_method(D_METHOD("open_compressed", "path", "mode_flags", "compression_mode"), &_File::open_compressed, DEFVAL(0));
  1211. ClassDB::bind_method(D_METHOD("open", "path", "flags"), &_File::open);
  1212. ClassDB::bind_method(D_METHOD("flush"), &_File::flush);
  1213. ClassDB::bind_method(D_METHOD("close"), &_File::close);
  1214. ClassDB::bind_method(D_METHOD("get_path"), &_File::get_path);
  1215. ClassDB::bind_method(D_METHOD("get_path_absolute"), &_File::get_path_absolute);
  1216. ClassDB::bind_method(D_METHOD("is_open"), &_File::is_open);
  1217. ClassDB::bind_method(D_METHOD("seek", "position"), &_File::seek);
  1218. ClassDB::bind_method(D_METHOD("seek_end", "position"), &_File::seek_end, DEFVAL(0));
  1219. ClassDB::bind_method(D_METHOD("get_position"), &_File::get_position);
  1220. ClassDB::bind_method(D_METHOD("get_len"), &_File::get_len);
  1221. ClassDB::bind_method(D_METHOD("eof_reached"), &_File::eof_reached);
  1222. ClassDB::bind_method(D_METHOD("get_8"), &_File::get_8);
  1223. ClassDB::bind_method(D_METHOD("get_16"), &_File::get_16);
  1224. ClassDB::bind_method(D_METHOD("get_32"), &_File::get_32);
  1225. ClassDB::bind_method(D_METHOD("get_64"), &_File::get_64);
  1226. ClassDB::bind_method(D_METHOD("get_float"), &_File::get_float);
  1227. ClassDB::bind_method(D_METHOD("get_double"), &_File::get_double);
  1228. ClassDB::bind_method(D_METHOD("get_real"), &_File::get_real);
  1229. ClassDB::bind_method(D_METHOD("get_buffer", "len"), &_File::get_buffer);
  1230. ClassDB::bind_method(D_METHOD("get_line"), &_File::get_line);
  1231. ClassDB::bind_method(D_METHOD("get_csv_line", "delim"), &_File::get_csv_line, DEFVAL(","));
  1232. ClassDB::bind_method(D_METHOD("get_as_text"), &_File::get_as_text);
  1233. ClassDB::bind_method(D_METHOD("get_md5", "path"), &_File::get_md5);
  1234. ClassDB::bind_method(D_METHOD("get_sha256", "path"), &_File::get_sha256);
  1235. ClassDB::bind_method(D_METHOD("get_endian_swap"), &_File::get_endian_swap);
  1236. ClassDB::bind_method(D_METHOD("set_endian_swap", "enable"), &_File::set_endian_swap);
  1237. ClassDB::bind_method(D_METHOD("get_error"), &_File::get_error);
  1238. ClassDB::bind_method(D_METHOD("get_var", "allow_objects"), &_File::get_var, DEFVAL(false));
  1239. ClassDB::bind_method(D_METHOD("store_8", "value"), &_File::store_8);
  1240. ClassDB::bind_method(D_METHOD("store_16", "value"), &_File::store_16);
  1241. ClassDB::bind_method(D_METHOD("store_32", "value"), &_File::store_32);
  1242. ClassDB::bind_method(D_METHOD("store_64", "value"), &_File::store_64);
  1243. ClassDB::bind_method(D_METHOD("store_float", "value"), &_File::store_float);
  1244. ClassDB::bind_method(D_METHOD("store_double", "value"), &_File::store_double);
  1245. ClassDB::bind_method(D_METHOD("store_real", "value"), &_File::store_real);
  1246. ClassDB::bind_method(D_METHOD("store_buffer", "buffer"), &_File::store_buffer);
  1247. ClassDB::bind_method(D_METHOD("store_line", "line"), &_File::store_line);
  1248. ClassDB::bind_method(D_METHOD("store_csv_line", "values", "delim"), &_File::store_csv_line, DEFVAL(","));
  1249. ClassDB::bind_method(D_METHOD("store_string", "string"), &_File::store_string);
  1250. ClassDB::bind_method(D_METHOD("store_var", "value", "full_objects"), &_File::store_var, DEFVAL(false));
  1251. ClassDB::bind_method(D_METHOD("store_pascal_string", "string"), &_File::store_pascal_string);
  1252. ClassDB::bind_method(D_METHOD("get_pascal_string"), &_File::get_pascal_string);
  1253. ClassDB::bind_method(D_METHOD("file_exists", "path"), &_File::file_exists);
  1254. ClassDB::bind_method(D_METHOD("get_modified_time", "file"), &_File::get_modified_time);
  1255. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "endian_swap"), "set_endian_swap", "get_endian_swap");
  1256. BIND_ENUM_CONSTANT(READ);
  1257. BIND_ENUM_CONSTANT(WRITE);
  1258. BIND_ENUM_CONSTANT(READ_WRITE);
  1259. BIND_ENUM_CONSTANT(WRITE_READ);
  1260. BIND_ENUM_CONSTANT(COMPRESSION_FASTLZ);
  1261. BIND_ENUM_CONSTANT(COMPRESSION_DEFLATE);
  1262. BIND_ENUM_CONSTANT(COMPRESSION_ZSTD);
  1263. BIND_ENUM_CONSTANT(COMPRESSION_GZIP);
  1264. }
  1265. _File::~_File() {
  1266. if (f) {
  1267. memdelete(f);
  1268. }
  1269. }
  1270. ////// _Directory //////
  1271. Error _Directory::open(const String &p_path) {
  1272. Error err;
  1273. DirAccess *alt = DirAccess::open(p_path, &err);
  1274. if (!alt) {
  1275. return err;
  1276. }
  1277. if (d) {
  1278. memdelete(d);
  1279. }
  1280. d = alt;
  1281. dir_open = true;
  1282. return OK;
  1283. }
  1284. bool _Directory::is_open() const {
  1285. return d && dir_open;
  1286. }
  1287. Error _Directory::list_dir_begin(bool p_skip_navigational, bool p_skip_hidden) {
  1288. ERR_FAIL_COND_V_MSG(!is_open(), ERR_UNCONFIGURED, "Directory must be opened before use.");
  1289. _list_skip_navigational = p_skip_navigational;
  1290. _list_skip_hidden = p_skip_hidden;
  1291. return d->list_dir_begin();
  1292. }
  1293. String _Directory::get_next() {
  1294. ERR_FAIL_COND_V_MSG(!is_open(), "", "Directory must be opened before use.");
  1295. String next = d->get_next();
  1296. while (next != "" && ((_list_skip_navigational && (next == "." || next == "..")) || (_list_skip_hidden && d->current_is_hidden()))) {
  1297. next = d->get_next();
  1298. }
  1299. return next;
  1300. }
  1301. bool _Directory::current_is_dir() const {
  1302. ERR_FAIL_COND_V_MSG(!is_open(), false, "Directory must be opened before use.");
  1303. return d->current_is_dir();
  1304. }
  1305. void _Directory::list_dir_end() {
  1306. ERR_FAIL_COND_MSG(!is_open(), "Directory must be opened before use.");
  1307. d->list_dir_end();
  1308. }
  1309. int _Directory::get_drive_count() {
  1310. ERR_FAIL_COND_V_MSG(!is_open(), 0, "Directory must be opened before use.");
  1311. return d->get_drive_count();
  1312. }
  1313. String _Directory::get_drive(int p_drive) {
  1314. ERR_FAIL_COND_V_MSG(!is_open(), "", "Directory must be opened before use.");
  1315. return d->get_drive(p_drive);
  1316. }
  1317. int _Directory::get_current_drive() {
  1318. ERR_FAIL_COND_V_MSG(!is_open(), 0, "Directory must be opened before use.");
  1319. return d->get_current_drive();
  1320. }
  1321. Error _Directory::change_dir(String p_dir) {
  1322. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory is not configured properly.");
  1323. Error err = d->change_dir(p_dir);
  1324. if (err != OK) {
  1325. return err;
  1326. }
  1327. dir_open = true;
  1328. return OK;
  1329. }
  1330. String _Directory::get_current_dir() {
  1331. ERR_FAIL_COND_V_MSG(!is_open(), "", "Directory must be opened before use.");
  1332. return d->get_current_dir();
  1333. }
  1334. Error _Directory::make_dir(String p_dir) {
  1335. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory is not configured properly.");
  1336. if (!p_dir.is_rel_path()) {
  1337. DirAccess *d = DirAccess::create_for_path(p_dir);
  1338. Error err = d->make_dir(p_dir);
  1339. memdelete(d);
  1340. return err;
  1341. }
  1342. return d->make_dir(p_dir);
  1343. }
  1344. Error _Directory::make_dir_recursive(String p_dir) {
  1345. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory is not configured properly.");
  1346. if (!p_dir.is_rel_path()) {
  1347. DirAccess *d = DirAccess::create_for_path(p_dir);
  1348. Error err = d->make_dir_recursive(p_dir);
  1349. memdelete(d);
  1350. return err;
  1351. }
  1352. return d->make_dir_recursive(p_dir);
  1353. }
  1354. bool _Directory::file_exists(String p_file) {
  1355. ERR_FAIL_COND_V_MSG(!d, false, "Directory is not configured properly.");
  1356. if (!p_file.is_rel_path()) {
  1357. return FileAccess::exists(p_file);
  1358. }
  1359. return d->file_exists(p_file);
  1360. }
  1361. bool _Directory::dir_exists(String p_dir) {
  1362. ERR_FAIL_COND_V_MSG(!d, false, "Directory is not configured properly.");
  1363. if (!p_dir.is_rel_path()) {
  1364. DirAccess *d = DirAccess::create_for_path(p_dir);
  1365. bool exists = d->dir_exists(p_dir);
  1366. memdelete(d);
  1367. return exists;
  1368. }
  1369. return d->dir_exists(p_dir);
  1370. }
  1371. int _Directory::get_space_left() {
  1372. ERR_FAIL_COND_V_MSG(!is_open(), 0, "Directory must be opened before use.");
  1373. return d->get_space_left() / 1024 * 1024; //return value in megabytes, given binding is int
  1374. }
  1375. Error _Directory::copy(String p_from, String p_to) {
  1376. ERR_FAIL_COND_V_MSG(!is_open(), ERR_UNCONFIGURED, "Directory must be opened before use.");
  1377. return d->copy(p_from, p_to);
  1378. }
  1379. Error _Directory::rename(String p_from, String p_to) {
  1380. ERR_FAIL_COND_V_MSG(!is_open(), ERR_UNCONFIGURED, "Directory must be opened before use.");
  1381. if (!p_from.is_rel_path()) {
  1382. DirAccess *d = DirAccess::create_for_path(p_from);
  1383. ERR_FAIL_COND_V_MSG(!d->file_exists(p_from), ERR_DOES_NOT_EXIST, "File does not exist.");
  1384. Error err = d->rename(p_from, p_to);
  1385. memdelete(d);
  1386. return err;
  1387. }
  1388. ERR_FAIL_COND_V_MSG(!d->file_exists(p_from), ERR_DOES_NOT_EXIST, "File does not exist.");
  1389. return d->rename(p_from, p_to);
  1390. }
  1391. Error _Directory::remove(String p_name) {
  1392. ERR_FAIL_COND_V_MSG(!is_open(), ERR_UNCONFIGURED, "Directory must be opened before use.");
  1393. if (!p_name.is_rel_path()) {
  1394. DirAccess *d = DirAccess::create_for_path(p_name);
  1395. Error err = d->remove(p_name);
  1396. memdelete(d);
  1397. return err;
  1398. }
  1399. return d->remove(p_name);
  1400. }
  1401. void _Directory::_bind_methods() {
  1402. ClassDB::bind_method(D_METHOD("open", "path"), &_Directory::open);
  1403. ClassDB::bind_method(D_METHOD("list_dir_begin", "skip_navigational", "skip_hidden"), &_Directory::list_dir_begin, DEFVAL(false), DEFVAL(false));
  1404. ClassDB::bind_method(D_METHOD("get_next"), &_Directory::get_next);
  1405. ClassDB::bind_method(D_METHOD("current_is_dir"), &_Directory::current_is_dir);
  1406. ClassDB::bind_method(D_METHOD("list_dir_end"), &_Directory::list_dir_end);
  1407. ClassDB::bind_method(D_METHOD("get_drive_count"), &_Directory::get_drive_count);
  1408. ClassDB::bind_method(D_METHOD("get_drive", "idx"), &_Directory::get_drive);
  1409. ClassDB::bind_method(D_METHOD("get_current_drive"), &_Directory::get_current_drive);
  1410. ClassDB::bind_method(D_METHOD("change_dir", "todir"), &_Directory::change_dir);
  1411. ClassDB::bind_method(D_METHOD("get_current_dir"), &_Directory::get_current_dir);
  1412. ClassDB::bind_method(D_METHOD("make_dir", "path"), &_Directory::make_dir);
  1413. ClassDB::bind_method(D_METHOD("make_dir_recursive", "path"), &_Directory::make_dir_recursive);
  1414. ClassDB::bind_method(D_METHOD("file_exists", "path"), &_Directory::file_exists);
  1415. ClassDB::bind_method(D_METHOD("dir_exists", "path"), &_Directory::dir_exists);
  1416. //ClassDB::bind_method(D_METHOD("get_modified_time","file"),&_Directory::get_modified_time);
  1417. ClassDB::bind_method(D_METHOD("get_space_left"), &_Directory::get_space_left);
  1418. ClassDB::bind_method(D_METHOD("copy", "from", "to"), &_Directory::copy);
  1419. ClassDB::bind_method(D_METHOD("rename", "from", "to"), &_Directory::rename);
  1420. ClassDB::bind_method(D_METHOD("remove", "path"), &_Directory::remove);
  1421. }
  1422. _Directory::_Directory() {
  1423. d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1424. }
  1425. _Directory::~_Directory() {
  1426. if (d) {
  1427. memdelete(d);
  1428. }
  1429. }
  1430. ////// _Marshalls //////
  1431. _Marshalls *_Marshalls::singleton = nullptr;
  1432. _Marshalls *_Marshalls::get_singleton() {
  1433. return singleton;
  1434. }
  1435. String _Marshalls::variant_to_base64(const Variant &p_var, bool p_full_objects) {
  1436. int len;
  1437. Error err = encode_variant(p_var, nullptr, len, p_full_objects);
  1438. ERR_FAIL_COND_V_MSG(err != OK, "", "Error when trying to encode Variant.");
  1439. Vector<uint8_t> buff;
  1440. buff.resize(len);
  1441. uint8_t *w = buff.ptrw();
  1442. err = encode_variant(p_var, &w[0], len, p_full_objects);
  1443. ERR_FAIL_COND_V_MSG(err != OK, "", "Error when trying to encode Variant.");
  1444. String ret = CryptoCore::b64_encode_str(&w[0], len);
  1445. ERR_FAIL_COND_V(ret == "", ret);
  1446. return ret;
  1447. }
  1448. Variant _Marshalls::base64_to_variant(const String &p_str, bool p_allow_objects) {
  1449. int strlen = p_str.length();
  1450. CharString cstr = p_str.ascii();
  1451. Vector<uint8_t> buf;
  1452. buf.resize(strlen / 4 * 3 + 1);
  1453. uint8_t *w = buf.ptrw();
  1454. size_t len = 0;
  1455. ERR_FAIL_COND_V(CryptoCore::b64_decode(&w[0], buf.size(), &len, (unsigned char *)cstr.get_data(), strlen) != OK, Variant());
  1456. Variant v;
  1457. Error err = decode_variant(v, &w[0], len, nullptr, p_allow_objects);
  1458. ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to decode Variant.");
  1459. return v;
  1460. }
  1461. String _Marshalls::raw_to_base64(const Vector<uint8_t> &p_arr) {
  1462. String ret = CryptoCore::b64_encode_str(p_arr.ptr(), p_arr.size());
  1463. ERR_FAIL_COND_V(ret == "", ret);
  1464. return ret;
  1465. }
  1466. Vector<uint8_t> _Marshalls::base64_to_raw(const String &p_str) {
  1467. int strlen = p_str.length();
  1468. CharString cstr = p_str.ascii();
  1469. size_t arr_len = 0;
  1470. Vector<uint8_t> buf;
  1471. {
  1472. buf.resize(strlen / 4 * 3 + 1);
  1473. uint8_t *w = buf.ptrw();
  1474. ERR_FAIL_COND_V(CryptoCore::b64_decode(&w[0], buf.size(), &arr_len, (unsigned char *)cstr.get_data(), strlen) != OK, Vector<uint8_t>());
  1475. }
  1476. buf.resize(arr_len);
  1477. return buf;
  1478. }
  1479. String _Marshalls::utf8_to_base64(const String &p_str) {
  1480. CharString cstr = p_str.utf8();
  1481. String ret = CryptoCore::b64_encode_str((unsigned char *)cstr.get_data(), cstr.length());
  1482. ERR_FAIL_COND_V(ret == "", ret);
  1483. return ret;
  1484. }
  1485. String _Marshalls::base64_to_utf8(const String &p_str) {
  1486. int strlen = p_str.length();
  1487. CharString cstr = p_str.ascii();
  1488. Vector<uint8_t> buf;
  1489. buf.resize(strlen / 4 * 3 + 1 + 1);
  1490. uint8_t *w = buf.ptrw();
  1491. size_t len = 0;
  1492. ERR_FAIL_COND_V(CryptoCore::b64_decode(&w[0], buf.size(), &len, (unsigned char *)cstr.get_data(), strlen) != OK, String());
  1493. w[len] = 0;
  1494. String ret = String::utf8((char *)&w[0]);
  1495. return ret;
  1496. }
  1497. void _Marshalls::_bind_methods() {
  1498. ClassDB::bind_method(D_METHOD("variant_to_base64", "variant", "full_objects"), &_Marshalls::variant_to_base64, DEFVAL(false));
  1499. ClassDB::bind_method(D_METHOD("base64_to_variant", "base64_str", "allow_objects"), &_Marshalls::base64_to_variant, DEFVAL(false));
  1500. ClassDB::bind_method(D_METHOD("raw_to_base64", "array"), &_Marshalls::raw_to_base64);
  1501. ClassDB::bind_method(D_METHOD("base64_to_raw", "base64_str"), &_Marshalls::base64_to_raw);
  1502. ClassDB::bind_method(D_METHOD("utf8_to_base64", "utf8_str"), &_Marshalls::utf8_to_base64);
  1503. ClassDB::bind_method(D_METHOD("base64_to_utf8", "base64_str"), &_Marshalls::base64_to_utf8);
  1504. }
  1505. ////// _Semaphore //////
  1506. void _Semaphore::wait() {
  1507. semaphore.wait();
  1508. }
  1509. Error _Semaphore::try_wait() {
  1510. return semaphore.try_wait() ? OK : ERR_BUSY;
  1511. }
  1512. void _Semaphore::post() {
  1513. semaphore.post();
  1514. }
  1515. void _Semaphore::_bind_methods() {
  1516. ClassDB::bind_method(D_METHOD("wait"), &_Semaphore::wait);
  1517. ClassDB::bind_method(D_METHOD("try_wait"), &_Semaphore::try_wait);
  1518. ClassDB::bind_method(D_METHOD("post"), &_Semaphore::post);
  1519. }
  1520. ////// _Mutex //////
  1521. void _Mutex::lock() {
  1522. mutex.lock();
  1523. }
  1524. Error _Mutex::try_lock() {
  1525. return mutex.try_lock();
  1526. }
  1527. void _Mutex::unlock() {
  1528. mutex.unlock();
  1529. }
  1530. void _Mutex::_bind_methods() {
  1531. ClassDB::bind_method(D_METHOD("lock"), &_Mutex::lock);
  1532. ClassDB::bind_method(D_METHOD("try_lock"), &_Mutex::try_lock);
  1533. ClassDB::bind_method(D_METHOD("unlock"), &_Mutex::unlock);
  1534. }
  1535. ////// _Thread //////
  1536. void _Thread::_start_func(void *ud) {
  1537. Ref<_Thread> *tud = (Ref<_Thread> *)ud;
  1538. Ref<_Thread> t = *tud;
  1539. memdelete(tud);
  1540. Callable::CallError ce;
  1541. const Variant *arg[1] = { &t->userdata };
  1542. Thread::set_name(t->target_method);
  1543. t->ret = t->target_instance->call(t->target_method, arg, 1, ce);
  1544. if (ce.error != Callable::CallError::CALL_OK) {
  1545. String reason;
  1546. switch (ce.error) {
  1547. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  1548. reason = "Invalid Argument #" + itos(ce.argument);
  1549. } break;
  1550. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
  1551. reason = "Too Many Arguments";
  1552. } break;
  1553. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: {
  1554. reason = "Too Few Arguments";
  1555. } break;
  1556. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  1557. reason = "Method Not Found";
  1558. } break;
  1559. default: {
  1560. }
  1561. }
  1562. ERR_FAIL_MSG("Could not call function '" + t->target_method.operator String() + "' to start thread " + t->get_id() + ": " + reason + ".");
  1563. }
  1564. }
  1565. Error _Thread::start(Object *p_instance, const StringName &p_method, const Variant &p_userdata, Priority p_priority) {
  1566. ERR_FAIL_COND_V_MSG(active.is_set(), ERR_ALREADY_IN_USE, "Thread already started.");
  1567. ERR_FAIL_COND_V(!p_instance, ERR_INVALID_PARAMETER);
  1568. ERR_FAIL_COND_V(p_method == StringName(), ERR_INVALID_PARAMETER);
  1569. ERR_FAIL_INDEX_V(p_priority, PRIORITY_MAX, ERR_INVALID_PARAMETER);
  1570. ret = Variant();
  1571. target_method = p_method;
  1572. target_instance = p_instance;
  1573. userdata = p_userdata;
  1574. active.set();
  1575. Ref<_Thread> *ud = memnew(Ref<_Thread>(this));
  1576. Thread::Settings s;
  1577. s.priority = (Thread::Priority)p_priority;
  1578. thread.start(_start_func, ud, s);
  1579. return OK;
  1580. }
  1581. String _Thread::get_id() const {
  1582. return itos(thread.get_id());
  1583. }
  1584. bool _Thread::is_active() const {
  1585. return active.is_set();
  1586. }
  1587. Variant _Thread::wait_to_finish() {
  1588. ERR_FAIL_COND_V_MSG(!active.is_set(), Variant(), "Thread must be active to wait for its completion.");
  1589. thread.wait_to_finish();
  1590. Variant r = ret;
  1591. active.clear();
  1592. target_method = StringName();
  1593. target_instance = nullptr;
  1594. userdata = Variant();
  1595. return r;
  1596. }
  1597. void _Thread::_bind_methods() {
  1598. ClassDB::bind_method(D_METHOD("start", "instance", "method", "userdata", "priority"), &_Thread::start, DEFVAL(Variant()), DEFVAL(PRIORITY_NORMAL));
  1599. ClassDB::bind_method(D_METHOD("get_id"), &_Thread::get_id);
  1600. ClassDB::bind_method(D_METHOD("is_active"), &_Thread::is_active);
  1601. ClassDB::bind_method(D_METHOD("wait_to_finish"), &_Thread::wait_to_finish);
  1602. BIND_ENUM_CONSTANT(PRIORITY_LOW);
  1603. BIND_ENUM_CONSTANT(PRIORITY_NORMAL);
  1604. BIND_ENUM_CONSTANT(PRIORITY_HIGH);
  1605. }
  1606. ////// _ClassDB //////
  1607. PackedStringArray _ClassDB::get_class_list() const {
  1608. List<StringName> classes;
  1609. ClassDB::get_class_list(&classes);
  1610. PackedStringArray ret;
  1611. ret.resize(classes.size());
  1612. int idx = 0;
  1613. for (List<StringName>::Element *E = classes.front(); E; E = E->next()) {
  1614. ret.set(idx++, E->get());
  1615. }
  1616. return ret;
  1617. }
  1618. PackedStringArray _ClassDB::get_inheriters_from_class(const StringName &p_class) const {
  1619. List<StringName> classes;
  1620. ClassDB::get_inheriters_from_class(p_class, &classes);
  1621. PackedStringArray ret;
  1622. ret.resize(classes.size());
  1623. int idx = 0;
  1624. for (List<StringName>::Element *E = classes.front(); E; E = E->next()) {
  1625. ret.set(idx++, E->get());
  1626. }
  1627. return ret;
  1628. }
  1629. StringName _ClassDB::get_parent_class(const StringName &p_class) const {
  1630. return ClassDB::get_parent_class(p_class);
  1631. }
  1632. bool _ClassDB::class_exists(const StringName &p_class) const {
  1633. return ClassDB::class_exists(p_class);
  1634. }
  1635. bool _ClassDB::is_parent_class(const StringName &p_class, const StringName &p_inherits) const {
  1636. return ClassDB::is_parent_class(p_class, p_inherits);
  1637. }
  1638. bool _ClassDB::can_instance(const StringName &p_class) const {
  1639. return ClassDB::can_instance(p_class);
  1640. }
  1641. Variant _ClassDB::instance(const StringName &p_class) const {
  1642. Object *obj = ClassDB::instance(p_class);
  1643. if (!obj) {
  1644. return Variant();
  1645. }
  1646. Reference *r = Object::cast_to<Reference>(obj);
  1647. if (r) {
  1648. return REF(r);
  1649. } else {
  1650. return obj;
  1651. }
  1652. }
  1653. bool _ClassDB::has_signal(StringName p_class, StringName p_signal) const {
  1654. return ClassDB::has_signal(p_class, p_signal);
  1655. }
  1656. Dictionary _ClassDB::get_signal(StringName p_class, StringName p_signal) const {
  1657. MethodInfo signal;
  1658. if (ClassDB::get_signal(p_class, p_signal, &signal)) {
  1659. return signal.operator Dictionary();
  1660. } else {
  1661. return Dictionary();
  1662. }
  1663. }
  1664. Array _ClassDB::get_signal_list(StringName p_class, bool p_no_inheritance) const {
  1665. List<MethodInfo> signals;
  1666. ClassDB::get_signal_list(p_class, &signals, p_no_inheritance);
  1667. Array ret;
  1668. for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
  1669. ret.push_back(E->get().operator Dictionary());
  1670. }
  1671. return ret;
  1672. }
  1673. Array _ClassDB::get_property_list(StringName p_class, bool p_no_inheritance) const {
  1674. List<PropertyInfo> plist;
  1675. ClassDB::get_property_list(p_class, &plist, p_no_inheritance);
  1676. Array ret;
  1677. for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
  1678. ret.push_back(E->get().operator Dictionary());
  1679. }
  1680. return ret;
  1681. }
  1682. Variant _ClassDB::get_property(Object *p_object, const StringName &p_property) const {
  1683. Variant ret;
  1684. ClassDB::get_property(p_object, p_property, ret);
  1685. return ret;
  1686. }
  1687. Error _ClassDB::set_property(Object *p_object, const StringName &p_property, const Variant &p_value) const {
  1688. Variant ret;
  1689. bool valid;
  1690. if (!ClassDB::set_property(p_object, p_property, p_value, &valid)) {
  1691. return ERR_UNAVAILABLE;
  1692. } else if (!valid) {
  1693. return ERR_INVALID_DATA;
  1694. }
  1695. return OK;
  1696. }
  1697. bool _ClassDB::has_method(StringName p_class, StringName p_method, bool p_no_inheritance) const {
  1698. return ClassDB::has_method(p_class, p_method, p_no_inheritance);
  1699. }
  1700. Array _ClassDB::get_method_list(StringName p_class, bool p_no_inheritance) const {
  1701. List<MethodInfo> methods;
  1702. ClassDB::get_method_list(p_class, &methods, p_no_inheritance);
  1703. Array ret;
  1704. for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
  1705. #ifdef DEBUG_METHODS_ENABLED
  1706. ret.push_back(E->get().operator Dictionary());
  1707. #else
  1708. Dictionary dict;
  1709. dict["name"] = E->get().name;
  1710. ret.push_back(dict);
  1711. #endif
  1712. }
  1713. return ret;
  1714. }
  1715. PackedStringArray _ClassDB::get_integer_constant_list(const StringName &p_class, bool p_no_inheritance) const {
  1716. List<String> constants;
  1717. ClassDB::get_integer_constant_list(p_class, &constants, p_no_inheritance);
  1718. PackedStringArray ret;
  1719. ret.resize(constants.size());
  1720. int idx = 0;
  1721. for (List<String>::Element *E = constants.front(); E; E = E->next()) {
  1722. ret.set(idx++, E->get());
  1723. }
  1724. return ret;
  1725. }
  1726. bool _ClassDB::has_integer_constant(const StringName &p_class, const StringName &p_name) const {
  1727. bool success;
  1728. ClassDB::get_integer_constant(p_class, p_name, &success);
  1729. return success;
  1730. }
  1731. int _ClassDB::get_integer_constant(const StringName &p_class, const StringName &p_name) const {
  1732. bool found;
  1733. int c = ClassDB::get_integer_constant(p_class, p_name, &found);
  1734. ERR_FAIL_COND_V(!found, 0);
  1735. return c;
  1736. }
  1737. StringName _ClassDB::get_category(const StringName &p_node) const {
  1738. return ClassDB::get_category(p_node);
  1739. }
  1740. bool _ClassDB::is_class_enabled(StringName p_class) const {
  1741. return ClassDB::is_class_enabled(p_class);
  1742. }
  1743. void _ClassDB::_bind_methods() {
  1744. ClassDB::bind_method(D_METHOD("get_class_list"), &_ClassDB::get_class_list);
  1745. ClassDB::bind_method(D_METHOD("get_inheriters_from_class", "class"), &_ClassDB::get_inheriters_from_class);
  1746. ClassDB::bind_method(D_METHOD("get_parent_class", "class"), &_ClassDB::get_parent_class);
  1747. ClassDB::bind_method(D_METHOD("class_exists", "class"), &_ClassDB::class_exists);
  1748. ClassDB::bind_method(D_METHOD("is_parent_class", "class", "inherits"), &_ClassDB::is_parent_class);
  1749. ClassDB::bind_method(D_METHOD("can_instance", "class"), &_ClassDB::can_instance);
  1750. ClassDB::bind_method(D_METHOD("instance", "class"), &_ClassDB::instance);
  1751. ClassDB::bind_method(D_METHOD("class_has_signal", "class", "signal"), &_ClassDB::has_signal);
  1752. ClassDB::bind_method(D_METHOD("class_get_signal", "class", "signal"), &_ClassDB::get_signal);
  1753. ClassDB::bind_method(D_METHOD("class_get_signal_list", "class", "no_inheritance"), &_ClassDB::get_signal_list, DEFVAL(false));
  1754. ClassDB::bind_method(D_METHOD("class_get_property_list", "class", "no_inheritance"), &_ClassDB::get_property_list, DEFVAL(false));
  1755. ClassDB::bind_method(D_METHOD("class_get_property", "object", "property"), &_ClassDB::get_property);
  1756. ClassDB::bind_method(D_METHOD("class_set_property", "object", "property", "value"), &_ClassDB::set_property);
  1757. ClassDB::bind_method(D_METHOD("class_has_method", "class", "method", "no_inheritance"), &_ClassDB::has_method, DEFVAL(false));
  1758. ClassDB::bind_method(D_METHOD("class_get_method_list", "class", "no_inheritance"), &_ClassDB::get_method_list, DEFVAL(false));
  1759. ClassDB::bind_method(D_METHOD("class_get_integer_constant_list", "class", "no_inheritance"), &_ClassDB::get_integer_constant_list, DEFVAL(false));
  1760. ClassDB::bind_method(D_METHOD("class_has_integer_constant", "class", "name"), &_ClassDB::has_integer_constant);
  1761. ClassDB::bind_method(D_METHOD("class_get_integer_constant", "class", "name"), &_ClassDB::get_integer_constant);
  1762. ClassDB::bind_method(D_METHOD("class_get_category", "class"), &_ClassDB::get_category);
  1763. ClassDB::bind_method(D_METHOD("is_class_enabled", "class"), &_ClassDB::is_class_enabled);
  1764. }
  1765. ////// _Engine //////
  1766. void _Engine::set_iterations_per_second(int p_ips) {
  1767. Engine::get_singleton()->set_iterations_per_second(p_ips);
  1768. }
  1769. int _Engine::get_iterations_per_second() const {
  1770. return Engine::get_singleton()->get_iterations_per_second();
  1771. }
  1772. void _Engine::set_physics_jitter_fix(float p_threshold) {
  1773. Engine::get_singleton()->set_physics_jitter_fix(p_threshold);
  1774. }
  1775. float _Engine::get_physics_jitter_fix() const {
  1776. return Engine::get_singleton()->get_physics_jitter_fix();
  1777. }
  1778. float _Engine::get_physics_interpolation_fraction() const {
  1779. return Engine::get_singleton()->get_physics_interpolation_fraction();
  1780. }
  1781. void _Engine::set_target_fps(int p_fps) {
  1782. Engine::get_singleton()->set_target_fps(p_fps);
  1783. }
  1784. int _Engine::get_target_fps() const {
  1785. return Engine::get_singleton()->get_target_fps();
  1786. }
  1787. float _Engine::get_frames_per_second() const {
  1788. return Engine::get_singleton()->get_frames_per_second();
  1789. }
  1790. uint64_t _Engine::get_physics_frames() const {
  1791. return Engine::get_singleton()->get_physics_frames();
  1792. }
  1793. uint64_t _Engine::get_process_frames() const {
  1794. return Engine::get_singleton()->get_process_frames();
  1795. }
  1796. void _Engine::set_time_scale(float p_scale) {
  1797. Engine::get_singleton()->set_time_scale(p_scale);
  1798. }
  1799. float _Engine::get_time_scale() {
  1800. return Engine::get_singleton()->get_time_scale();
  1801. }
  1802. int _Engine::get_frames_drawn() {
  1803. return Engine::get_singleton()->get_frames_drawn();
  1804. }
  1805. MainLoop *_Engine::get_main_loop() const {
  1806. //needs to remain in OS, since it's actually OS that interacts with it, but it's better exposed here
  1807. return OS::get_singleton()->get_main_loop();
  1808. }
  1809. Dictionary _Engine::get_version_info() const {
  1810. return Engine::get_singleton()->get_version_info();
  1811. }
  1812. Dictionary _Engine::get_author_info() const {
  1813. return Engine::get_singleton()->get_author_info();
  1814. }
  1815. Array _Engine::get_copyright_info() const {
  1816. return Engine::get_singleton()->get_copyright_info();
  1817. }
  1818. Dictionary _Engine::get_donor_info() const {
  1819. return Engine::get_singleton()->get_donor_info();
  1820. }
  1821. Dictionary _Engine::get_license_info() const {
  1822. return Engine::get_singleton()->get_license_info();
  1823. }
  1824. String _Engine::get_license_text() const {
  1825. return Engine::get_singleton()->get_license_text();
  1826. }
  1827. bool _Engine::is_in_physics_frame() const {
  1828. return Engine::get_singleton()->is_in_physics_frame();
  1829. }
  1830. bool _Engine::has_singleton(const String &p_name) const {
  1831. return Engine::get_singleton()->has_singleton(p_name);
  1832. }
  1833. Object *_Engine::get_singleton_object(const String &p_name) const {
  1834. return Engine::get_singleton()->get_singleton_object(p_name);
  1835. }
  1836. void _Engine::set_editor_hint(bool p_enabled) {
  1837. Engine::get_singleton()->set_editor_hint(p_enabled);
  1838. }
  1839. bool _Engine::is_editor_hint() const {
  1840. return Engine::get_singleton()->is_editor_hint();
  1841. }
  1842. void _Engine::_bind_methods() {
  1843. ClassDB::bind_method(D_METHOD("set_iterations_per_second", "iterations_per_second"), &_Engine::set_iterations_per_second);
  1844. ClassDB::bind_method(D_METHOD("get_iterations_per_second"), &_Engine::get_iterations_per_second);
  1845. ClassDB::bind_method(D_METHOD("set_physics_jitter_fix", "physics_jitter_fix"), &_Engine::set_physics_jitter_fix);
  1846. ClassDB::bind_method(D_METHOD("get_physics_jitter_fix"), &_Engine::get_physics_jitter_fix);
  1847. ClassDB::bind_method(D_METHOD("get_physics_interpolation_fraction"), &_Engine::get_physics_interpolation_fraction);
  1848. ClassDB::bind_method(D_METHOD("set_target_fps", "target_fps"), &_Engine::set_target_fps);
  1849. ClassDB::bind_method(D_METHOD("get_target_fps"), &_Engine::get_target_fps);
  1850. ClassDB::bind_method(D_METHOD("set_time_scale", "time_scale"), &_Engine::set_time_scale);
  1851. ClassDB::bind_method(D_METHOD("get_time_scale"), &_Engine::get_time_scale);
  1852. ClassDB::bind_method(D_METHOD("get_frames_drawn"), &_Engine::get_frames_drawn);
  1853. ClassDB::bind_method(D_METHOD("get_frames_per_second"), &_Engine::get_frames_per_second);
  1854. ClassDB::bind_method(D_METHOD("get_physics_frames"), &_Engine::get_physics_frames);
  1855. ClassDB::bind_method(D_METHOD("get_process_frames"), &_Engine::get_process_frames);
  1856. ClassDB::bind_method(D_METHOD("get_main_loop"), &_Engine::get_main_loop);
  1857. ClassDB::bind_method(D_METHOD("get_version_info"), &_Engine::get_version_info);
  1858. ClassDB::bind_method(D_METHOD("get_author_info"), &_Engine::get_author_info);
  1859. ClassDB::bind_method(D_METHOD("get_copyright_info"), &_Engine::get_copyright_info);
  1860. ClassDB::bind_method(D_METHOD("get_donor_info"), &_Engine::get_donor_info);
  1861. ClassDB::bind_method(D_METHOD("get_license_info"), &_Engine::get_license_info);
  1862. ClassDB::bind_method(D_METHOD("get_license_text"), &_Engine::get_license_text);
  1863. ClassDB::bind_method(D_METHOD("is_in_physics_frame"), &_Engine::is_in_physics_frame);
  1864. ClassDB::bind_method(D_METHOD("has_singleton", "name"), &_Engine::has_singleton);
  1865. ClassDB::bind_method(D_METHOD("get_singleton", "name"), &_Engine::get_singleton_object);
  1866. ClassDB::bind_method(D_METHOD("set_editor_hint", "enabled"), &_Engine::set_editor_hint);
  1867. ClassDB::bind_method(D_METHOD("is_editor_hint"), &_Engine::is_editor_hint);
  1868. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor_hint"), "set_editor_hint", "is_editor_hint");
  1869. ADD_PROPERTY(PropertyInfo(Variant::INT, "iterations_per_second"), "set_iterations_per_second", "get_iterations_per_second");
  1870. ADD_PROPERTY(PropertyInfo(Variant::INT, "target_fps"), "set_target_fps", "get_target_fps");
  1871. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_scale"), "set_time_scale", "get_time_scale");
  1872. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "physics_jitter_fix"), "set_physics_jitter_fix", "get_physics_jitter_fix");
  1873. }
  1874. _Engine *_Engine::singleton = nullptr;
  1875. ////// _JSON //////
  1876. void JSONParseResult::_bind_methods() {
  1877. ClassDB::bind_method(D_METHOD("get_error"), &JSONParseResult::get_error);
  1878. ClassDB::bind_method(D_METHOD("get_error_string"), &JSONParseResult::get_error_string);
  1879. ClassDB::bind_method(D_METHOD("get_error_line"), &JSONParseResult::get_error_line);
  1880. ClassDB::bind_method(D_METHOD("get_result"), &JSONParseResult::get_result);
  1881. ClassDB::bind_method(D_METHOD("set_error", "error"), &JSONParseResult::set_error);
  1882. ClassDB::bind_method(D_METHOD("set_error_string", "error_string"), &JSONParseResult::set_error_string);
  1883. ClassDB::bind_method(D_METHOD("set_error_line", "error_line"), &JSONParseResult::set_error_line);
  1884. ClassDB::bind_method(D_METHOD("set_result", "result"), &JSONParseResult::set_result);
  1885. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "error", PROPERTY_HINT_NONE, "Error", PROPERTY_USAGE_CLASS_IS_ENUM), "set_error", "get_error");
  1886. ADD_PROPERTY(PropertyInfo(Variant::STRING, "error_string"), "set_error_string", "get_error_string");
  1887. ADD_PROPERTY(PropertyInfo(Variant::INT, "error_line"), "set_error_line", "get_error_line");
  1888. ADD_PROPERTY(PropertyInfo(Variant::NIL, "result", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NIL_IS_VARIANT), "set_result", "get_result");
  1889. }
  1890. void JSONParseResult::set_error(Error p_error) {
  1891. error = p_error;
  1892. }
  1893. Error JSONParseResult::get_error() const {
  1894. return error;
  1895. }
  1896. void JSONParseResult::set_error_string(const String &p_error_string) {
  1897. error_string = p_error_string;
  1898. }
  1899. String JSONParseResult::get_error_string() const {
  1900. return error_string;
  1901. }
  1902. void JSONParseResult::set_error_line(int p_error_line) {
  1903. error_line = p_error_line;
  1904. }
  1905. int JSONParseResult::get_error_line() const {
  1906. return error_line;
  1907. }
  1908. void JSONParseResult::set_result(const Variant &p_result) {
  1909. result = p_result;
  1910. }
  1911. Variant JSONParseResult::get_result() const {
  1912. return result;
  1913. }
  1914. void _JSON::_bind_methods() {
  1915. ClassDB::bind_method(D_METHOD("print", "value", "indent", "sort_keys"), &_JSON::print, DEFVAL(String()), DEFVAL(false));
  1916. ClassDB::bind_method(D_METHOD("parse", "json"), &_JSON::parse);
  1917. }
  1918. String _JSON::print(const Variant &p_value, const String &p_indent, bool p_sort_keys) {
  1919. return JSON::print(p_value, p_indent, p_sort_keys);
  1920. }
  1921. Ref<JSONParseResult> _JSON::parse(const String &p_json) {
  1922. Ref<JSONParseResult> result;
  1923. result.instance();
  1924. result->error = JSON::parse(p_json, result->result, result->error_string, result->error_line);
  1925. if (result->error != OK) {
  1926. ERR_PRINT(vformat("Error parsing JSON at line %s: %s", result->error_line, result->error_string));
  1927. }
  1928. return result;
  1929. }
  1930. _JSON *_JSON::singleton = nullptr;
  1931. ////// _EngineDebugger //////
  1932. void _EngineDebugger::_bind_methods() {
  1933. ClassDB::bind_method(D_METHOD("is_active"), &_EngineDebugger::is_active);
  1934. ClassDB::bind_method(D_METHOD("register_profiler", "name", "toggle", "add", "tick"), &_EngineDebugger::register_profiler);
  1935. ClassDB::bind_method(D_METHOD("unregister_profiler", "name"), &_EngineDebugger::unregister_profiler);
  1936. ClassDB::bind_method(D_METHOD("is_profiling", "name"), &_EngineDebugger::is_profiling);
  1937. ClassDB::bind_method(D_METHOD("has_profiler", "name"), &_EngineDebugger::has_profiler);
  1938. ClassDB::bind_method(D_METHOD("profiler_add_frame_data", "name", "data"), &_EngineDebugger::profiler_add_frame_data);
  1939. ClassDB::bind_method(D_METHOD("profiler_enable", "name", "enable", "arguments"), &_EngineDebugger::profiler_enable, DEFVAL(Array()));
  1940. ClassDB::bind_method(D_METHOD("register_message_capture", "name", "callable"), &_EngineDebugger::register_message_capture);
  1941. ClassDB::bind_method(D_METHOD("unregister_message_capture", "name"), &_EngineDebugger::unregister_message_capture);
  1942. ClassDB::bind_method(D_METHOD("has_capture", "name"), &_EngineDebugger::has_capture);
  1943. ClassDB::bind_method(D_METHOD("send_message", "message", "data"), &_EngineDebugger::send_message);
  1944. }
  1945. bool _EngineDebugger::is_active() {
  1946. return EngineDebugger::is_active();
  1947. }
  1948. void _EngineDebugger::register_profiler(const StringName &p_name, const Callable &p_toggle, const Callable &p_add, const Callable &p_tick) {
  1949. ERR_FAIL_COND_MSG(profilers.has(p_name) || has_profiler(p_name), "Profiler already registered: " + p_name);
  1950. profilers.insert(p_name, ProfilerCallable(p_toggle, p_add, p_tick));
  1951. ProfilerCallable &p = profilers[p_name];
  1952. EngineDebugger::Profiler profiler(
  1953. &p,
  1954. &_EngineDebugger::call_toggle,
  1955. &_EngineDebugger::call_add,
  1956. &_EngineDebugger::call_tick);
  1957. EngineDebugger::register_profiler(p_name, profiler);
  1958. }
  1959. void _EngineDebugger::unregister_profiler(const StringName &p_name) {
  1960. ERR_FAIL_COND_MSG(!profilers.has(p_name), "Profiler not registered: " + p_name);
  1961. EngineDebugger::unregister_profiler(p_name);
  1962. profilers.erase(p_name);
  1963. }
  1964. bool _EngineDebugger::_EngineDebugger::is_profiling(const StringName &p_name) {
  1965. return EngineDebugger::is_profiling(p_name);
  1966. }
  1967. bool _EngineDebugger::has_profiler(const StringName &p_name) {
  1968. return EngineDebugger::has_profiler(p_name);
  1969. }
  1970. void _EngineDebugger::profiler_add_frame_data(const StringName &p_name, const Array &p_data) {
  1971. EngineDebugger::profiler_add_frame_data(p_name, p_data);
  1972. }
  1973. void _EngineDebugger::profiler_enable(const StringName &p_name, bool p_enabled, const Array &p_opts) {
  1974. if (EngineDebugger::get_singleton()) {
  1975. EngineDebugger::get_singleton()->profiler_enable(p_name, p_enabled, p_opts);
  1976. }
  1977. }
  1978. void _EngineDebugger::register_message_capture(const StringName &p_name, const Callable &p_callable) {
  1979. ERR_FAIL_COND_MSG(captures.has(p_name) || has_capture(p_name), "Capture already registered: " + p_name);
  1980. captures.insert(p_name, p_callable);
  1981. Callable &c = captures[p_name];
  1982. EngineDebugger::Capture capture(&c, &_EngineDebugger::call_capture);
  1983. EngineDebugger::register_message_capture(p_name, capture);
  1984. }
  1985. void _EngineDebugger::unregister_message_capture(const StringName &p_name) {
  1986. ERR_FAIL_COND_MSG(!captures.has(p_name), "Capture not registered: " + p_name);
  1987. EngineDebugger::unregister_message_capture(p_name);
  1988. captures.erase(p_name);
  1989. }
  1990. bool _EngineDebugger::has_capture(const StringName &p_name) {
  1991. return EngineDebugger::has_capture(p_name);
  1992. }
  1993. void _EngineDebugger::send_message(const String &p_msg, const Array &p_data) {
  1994. ERR_FAIL_COND_MSG(!EngineDebugger::is_active(), "Can't send message. No active debugger");
  1995. EngineDebugger::get_singleton()->send_message(p_msg, p_data);
  1996. }
  1997. void _EngineDebugger::call_toggle(void *p_user, bool p_enable, const Array &p_opts) {
  1998. Callable &toggle = ((ProfilerCallable *)p_user)->callable_toggle;
  1999. if (toggle.is_null()) {
  2000. return;
  2001. }
  2002. Variant enable = p_enable, opts = p_opts;
  2003. const Variant *args[2] = { &enable, &opts };
  2004. Variant retval;
  2005. Callable::CallError err;
  2006. toggle.call(args, 2, retval, err);
  2007. ERR_FAIL_COND_MSG(err.error != Callable::CallError::CALL_OK, "Error calling 'toggle' to callable: " + Variant::get_callable_error_text(toggle, args, 2, err));
  2008. }
  2009. void _EngineDebugger::call_add(void *p_user, const Array &p_data) {
  2010. Callable &add = ((ProfilerCallable *)p_user)->callable_add;
  2011. if (add.is_null()) {
  2012. return;
  2013. }
  2014. Variant data = p_data;
  2015. const Variant *args[1] = { &data };
  2016. Variant retval;
  2017. Callable::CallError err;
  2018. add.call(args, 1, retval, err);
  2019. ERR_FAIL_COND_MSG(err.error != Callable::CallError::CALL_OK, "Error calling 'add' to callable: " + Variant::get_callable_error_text(add, args, 1, err));
  2020. }
  2021. void _EngineDebugger::call_tick(void *p_user, float p_frame_time, float p_idle_time, float p_physics_time, float p_physics_frame_time) {
  2022. Callable &tick = ((ProfilerCallable *)p_user)->callable_tick;
  2023. if (tick.is_null()) {
  2024. return;
  2025. }
  2026. Variant frame_time = p_frame_time, idle_time = p_idle_time, physics_time = p_physics_time, physics_frame_time = p_physics_frame_time;
  2027. const Variant *args[4] = { &frame_time, &idle_time, &physics_time, &physics_frame_time };
  2028. Variant retval;
  2029. Callable::CallError err;
  2030. tick.call(args, 4, retval, err);
  2031. ERR_FAIL_COND_MSG(err.error != Callable::CallError::CALL_OK, "Error calling 'tick' to callable: " + Variant::get_callable_error_text(tick, args, 4, err));
  2032. }
  2033. Error _EngineDebugger::call_capture(void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) {
  2034. Callable &capture = *(Callable *)p_user;
  2035. if (capture.is_null()) {
  2036. return FAILED;
  2037. }
  2038. Variant cmd = p_cmd, data = p_data;
  2039. const Variant *args[2] = { &cmd, &data };
  2040. Variant retval;
  2041. Callable::CallError err;
  2042. capture.call(args, 2, retval, err);
  2043. ERR_FAIL_COND_V_MSG(err.error != Callable::CallError::CALL_OK, FAILED, "Error calling 'capture' to callable: " + Variant::get_callable_error_text(capture, args, 2, err));
  2044. ERR_FAIL_COND_V_MSG(retval.get_type() != Variant::BOOL, FAILED, "Error calling 'capture' to callable: " + String(capture) + ". Return type is not bool.");
  2045. r_captured = retval;
  2046. return OK;
  2047. }
  2048. _EngineDebugger::~_EngineDebugger() {
  2049. for (Map<StringName, Callable>::Element *E = captures.front(); E; E = E->next()) {
  2050. EngineDebugger::unregister_message_capture(E->key());
  2051. }
  2052. captures.clear();
  2053. for (Map<StringName, ProfilerCallable>::Element *E = profilers.front(); E; E = E->next()) {
  2054. EngineDebugger::unregister_profiler(E->key());
  2055. }
  2056. profilers.clear();
  2057. }
  2058. _EngineDebugger *_EngineDebugger::singleton = nullptr;