core_bind.cpp 82 KB

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