object.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991
  1. /*************************************************************************/
  2. /* object.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "object.h"
  31. #include "core/core_string_names.h"
  32. #include "core/io/resource.h"
  33. #include "core/object/class_db.h"
  34. #include "core/object/message_queue.h"
  35. #include "core/object/script_language.h"
  36. #include "core/os/os.h"
  37. #include "core/string/print_string.h"
  38. #include "core/string/translation.h"
  39. #include "core/variant/typed_array.h"
  40. #ifdef DEBUG_ENABLED
  41. struct _ObjectDebugLock {
  42. Object *obj;
  43. _ObjectDebugLock(Object *p_obj) {
  44. obj = p_obj;
  45. obj->_lock_index.ref();
  46. }
  47. ~_ObjectDebugLock() {
  48. obj->_lock_index.unref();
  49. }
  50. };
  51. #define OBJ_DEBUG_LOCK _ObjectDebugLock _debug_lock(this);
  52. #else
  53. #define OBJ_DEBUG_LOCK
  54. #endif
  55. PropertyInfo::operator Dictionary() const {
  56. Dictionary d;
  57. d["name"] = name;
  58. d["class_name"] = class_name;
  59. d["type"] = type;
  60. d["hint"] = hint;
  61. d["hint_string"] = hint_string;
  62. d["usage"] = usage;
  63. return d;
  64. }
  65. PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) {
  66. PropertyInfo pi;
  67. if (p_dict.has("type")) {
  68. pi.type = Variant::Type(int(p_dict["type"]));
  69. }
  70. if (p_dict.has("name")) {
  71. pi.name = p_dict["name"];
  72. }
  73. if (p_dict.has("class_name")) {
  74. pi.class_name = p_dict["class_name"];
  75. }
  76. if (p_dict.has("hint")) {
  77. pi.hint = PropertyHint(int(p_dict["hint"]));
  78. }
  79. if (p_dict.has("hint_string")) {
  80. pi.hint_string = p_dict["hint_string"];
  81. }
  82. if (p_dict.has("usage")) {
  83. pi.usage = p_dict["usage"];
  84. }
  85. return pi;
  86. }
  87. TypedArray<Dictionary> convert_property_list(const List<PropertyInfo> *p_list) {
  88. TypedArray<Dictionary> va;
  89. for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) {
  90. va.push_back(Dictionary(E->get()));
  91. }
  92. return va;
  93. }
  94. MethodInfo::operator Dictionary() const {
  95. Dictionary d;
  96. d["name"] = name;
  97. d["args"] = convert_property_list(&arguments);
  98. Array da;
  99. for (int i = 0; i < default_arguments.size(); i++) {
  100. da.push_back(default_arguments[i]);
  101. }
  102. d["default_args"] = da;
  103. d["flags"] = flags;
  104. d["id"] = id;
  105. Dictionary r = return_val;
  106. d["return"] = r;
  107. return d;
  108. }
  109. MethodInfo MethodInfo::from_dict(const Dictionary &p_dict) {
  110. MethodInfo mi;
  111. if (p_dict.has("name")) {
  112. mi.name = p_dict["name"];
  113. }
  114. Array args;
  115. if (p_dict.has("args")) {
  116. args = p_dict["args"];
  117. }
  118. for (int i = 0; i < args.size(); i++) {
  119. Dictionary d = args[i];
  120. mi.arguments.push_back(PropertyInfo::from_dict(d));
  121. }
  122. Array defargs;
  123. if (p_dict.has("default_args")) {
  124. defargs = p_dict["default_args"];
  125. }
  126. for (int i = 0; i < defargs.size(); i++) {
  127. mi.default_arguments.push_back(defargs[i]);
  128. }
  129. if (p_dict.has("return")) {
  130. mi.return_val = PropertyInfo::from_dict(p_dict["return"]);
  131. }
  132. if (p_dict.has("flags")) {
  133. mi.flags = p_dict["flags"];
  134. }
  135. return mi;
  136. }
  137. Object::Connection::operator Variant() const {
  138. Dictionary d;
  139. d["signal"] = signal;
  140. d["callable"] = callable;
  141. d["flags"] = flags;
  142. return d;
  143. }
  144. bool Object::Connection::operator<(const Connection &p_conn) const {
  145. if (signal == p_conn.signal) {
  146. return callable < p_conn.callable;
  147. } else {
  148. return signal < p_conn.signal;
  149. }
  150. }
  151. Object::Connection::Connection(const Variant &p_variant) {
  152. Dictionary d = p_variant;
  153. if (d.has("signal")) {
  154. signal = d["signal"];
  155. }
  156. if (d.has("callable")) {
  157. callable = d["callable"];
  158. }
  159. if (d.has("flags")) {
  160. flags = d["flags"];
  161. }
  162. }
  163. bool Object::_predelete() {
  164. _predelete_ok = 1;
  165. notification(NOTIFICATION_PREDELETE, true);
  166. if (_predelete_ok) {
  167. _class_ptr = nullptr; //must restore so destructors can access class ptr correctly
  168. }
  169. return _predelete_ok;
  170. }
  171. void Object::_postinitialize() {
  172. _class_ptr = _get_class_namev();
  173. _initialize_classv();
  174. notification(NOTIFICATION_POSTINITIALIZE);
  175. }
  176. void Object::get_valid_parents_static(List<String> *p_parents) {
  177. }
  178. void Object::_get_valid_parents_static(List<String> *p_parents) {
  179. }
  180. void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid) {
  181. #ifdef TOOLS_ENABLED
  182. _edited = true;
  183. #endif
  184. if (script_instance) {
  185. if (script_instance->set(p_name, p_value)) {
  186. if (r_valid) {
  187. *r_valid = true;
  188. }
  189. return;
  190. }
  191. }
  192. if (_extension && _extension->set) {
  193. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  194. #if defined(__GNUC__) && !defined(__clang__)
  195. #pragma GCC diagnostic push
  196. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  197. #endif
  198. if (_extension->set(_extension_instance, (const GDNativeStringNamePtr)&p_name, (const GDNativeVariantPtr)&p_value)) {
  199. if (r_valid) {
  200. *r_valid = true;
  201. }
  202. return;
  203. }
  204. #if defined(__GNUC__) && !defined(__clang__)
  205. #pragma GCC diagnostic pop
  206. #endif
  207. }
  208. // Try built-in setter.
  209. {
  210. if (ClassDB::set_property(this, p_name, p_value, r_valid)) {
  211. return;
  212. }
  213. }
  214. if (p_name == CoreStringNames::get_singleton()->_script) {
  215. set_script(p_value);
  216. if (r_valid) {
  217. *r_valid = true;
  218. }
  219. return;
  220. } else {
  221. Variant **V = metadata_properties.getptr(p_name);
  222. if (V) {
  223. **V = p_value;
  224. if (r_valid) {
  225. *r_valid = true;
  226. }
  227. return;
  228. } else if (p_name.operator String().begins_with("metadata/")) {
  229. // Must exist, otherwise duplicate() will not work.
  230. set_meta(p_name.operator String().replace_first("metadata/", ""), p_value);
  231. if (r_valid) {
  232. *r_valid = true;
  233. }
  234. return;
  235. }
  236. }
  237. #ifdef TOOLS_ENABLED
  238. if (script_instance) {
  239. bool valid;
  240. script_instance->property_set_fallback(p_name, p_value, &valid);
  241. if (valid) {
  242. if (r_valid) {
  243. *r_valid = true;
  244. }
  245. return;
  246. }
  247. }
  248. #endif
  249. // Something inside the object... :|
  250. bool success = _setv(p_name, p_value);
  251. if (success) {
  252. if (r_valid) {
  253. *r_valid = true;
  254. }
  255. return;
  256. }
  257. if (r_valid) {
  258. *r_valid = false;
  259. }
  260. }
  261. Variant Object::get(const StringName &p_name, bool *r_valid) const {
  262. Variant ret;
  263. if (script_instance) {
  264. if (script_instance->get(p_name, ret)) {
  265. if (r_valid) {
  266. *r_valid = true;
  267. }
  268. return ret;
  269. }
  270. }
  271. if (_extension && _extension->get) {
  272. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  273. #if defined(__GNUC__) && !defined(__clang__)
  274. #pragma GCC diagnostic push
  275. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  276. #endif
  277. if (_extension->get(_extension_instance, (const GDNativeStringNamePtr)&p_name, (GDNativeVariantPtr)&ret)) {
  278. if (r_valid) {
  279. *r_valid = true;
  280. }
  281. return ret;
  282. }
  283. #if defined(__GNUC__) && !defined(__clang__)
  284. #pragma GCC diagnostic pop
  285. #endif
  286. }
  287. // Try built-in getter.
  288. {
  289. if (ClassDB::get_property(const_cast<Object *>(this), p_name, ret)) {
  290. if (r_valid) {
  291. *r_valid = true;
  292. }
  293. return ret;
  294. }
  295. }
  296. if (p_name == CoreStringNames::get_singleton()->_script) {
  297. ret = get_script();
  298. if (r_valid) {
  299. *r_valid = true;
  300. }
  301. return ret;
  302. }
  303. const Variant *const *V = metadata_properties.getptr(p_name);
  304. if (V) {
  305. ret = **V;
  306. if (r_valid) {
  307. *r_valid = true;
  308. }
  309. return ret;
  310. } else {
  311. #ifdef TOOLS_ENABLED
  312. if (script_instance) {
  313. bool valid;
  314. ret = script_instance->property_get_fallback(p_name, &valid);
  315. if (valid) {
  316. if (r_valid) {
  317. *r_valid = true;
  318. }
  319. return ret;
  320. }
  321. }
  322. #endif
  323. // Something inside the object... :|
  324. bool success = _getv(p_name, ret);
  325. if (success) {
  326. if (r_valid) {
  327. *r_valid = true;
  328. }
  329. return ret;
  330. }
  331. if (r_valid) {
  332. *r_valid = false;
  333. }
  334. return Variant();
  335. }
  336. }
  337. void Object::set_indexed(const Vector<StringName> &p_names, const Variant &p_value, bool *r_valid) {
  338. if (p_names.is_empty()) {
  339. if (r_valid) {
  340. *r_valid = false;
  341. }
  342. return;
  343. }
  344. if (p_names.size() == 1) {
  345. set(p_names[0], p_value, r_valid);
  346. return;
  347. }
  348. bool valid = false;
  349. if (!r_valid) {
  350. r_valid = &valid;
  351. }
  352. List<Variant> value_stack;
  353. value_stack.push_back(get(p_names[0], r_valid));
  354. if (!*r_valid) {
  355. value_stack.clear();
  356. return;
  357. }
  358. for (int i = 1; i < p_names.size() - 1; i++) {
  359. value_stack.push_back(value_stack.back()->get().get_named(p_names[i], valid));
  360. if (r_valid) {
  361. *r_valid = valid;
  362. }
  363. if (!valid) {
  364. value_stack.clear();
  365. return;
  366. }
  367. }
  368. value_stack.push_back(p_value); // p_names[p_names.size() - 1]
  369. for (int i = p_names.size() - 1; i > 0; i--) {
  370. value_stack.back()->prev()->get().set_named(p_names[i], value_stack.back()->get(), valid);
  371. value_stack.pop_back();
  372. if (r_valid) {
  373. *r_valid = valid;
  374. }
  375. if (!valid) {
  376. value_stack.clear();
  377. return;
  378. }
  379. }
  380. set(p_names[0], value_stack.back()->get(), r_valid);
  381. value_stack.pop_back();
  382. ERR_FAIL_COND(!value_stack.is_empty());
  383. }
  384. Variant Object::get_indexed(const Vector<StringName> &p_names, bool *r_valid) const {
  385. if (p_names.is_empty()) {
  386. if (r_valid) {
  387. *r_valid = false;
  388. }
  389. return Variant();
  390. }
  391. bool valid = false;
  392. Variant current_value = get(p_names[0], &valid);
  393. for (int i = 1; i < p_names.size(); i++) {
  394. current_value = current_value.get_named(p_names[i], valid);
  395. if (!valid) {
  396. break;
  397. }
  398. }
  399. if (r_valid) {
  400. *r_valid = valid;
  401. }
  402. return current_value;
  403. }
  404. void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) const {
  405. if (script_instance && p_reversed) {
  406. script_instance->get_property_list(p_list);
  407. }
  408. if (_extension) {
  409. const ObjectNativeExtension *current_extension = _extension;
  410. while (current_extension) {
  411. p_list->push_back(PropertyInfo(Variant::NIL, current_extension->class_name, PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY));
  412. ClassDB::get_property_list(current_extension->class_name, p_list, true, this);
  413. current_extension = current_extension->parent;
  414. }
  415. }
  416. if (_extension && _extension->get_property_list) {
  417. uint32_t pcount;
  418. const GDNativePropertyInfo *pinfo = _extension->get_property_list(_extension_instance, &pcount);
  419. for (uint32_t i = 0; i < pcount; i++) {
  420. p_list->push_back(PropertyInfo(pinfo[i]));
  421. }
  422. if (_extension->free_property_list) {
  423. _extension->free_property_list(_extension_instance, pinfo);
  424. }
  425. }
  426. _get_property_listv(p_list, p_reversed);
  427. if (!is_class("Script")) { // can still be set, but this is for user-friendliness
  428. p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT));
  429. }
  430. if (script_instance && !p_reversed) {
  431. script_instance->get_property_list(p_list);
  432. }
  433. for (const KeyValue<StringName, Variant> &K : metadata) {
  434. PropertyInfo pi = PropertyInfo(K.value.get_type(), "metadata/" + K.key.operator String());
  435. if (K.value.get_type() == Variant::OBJECT) {
  436. pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
  437. pi.hint_string = "Resource";
  438. }
  439. p_list->push_back(pi);
  440. }
  441. }
  442. void Object::validate_property(PropertyInfo &p_property) const {
  443. _validate_propertyv(p_property);
  444. }
  445. bool Object::property_can_revert(const StringName &p_name) const {
  446. if (script_instance) {
  447. if (script_instance->property_can_revert(p_name)) {
  448. return true;
  449. }
  450. }
  451. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  452. #if defined(__GNUC__) && !defined(__clang__)
  453. #pragma GCC diagnostic push
  454. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  455. #endif
  456. if (_extension && _extension->property_can_revert) {
  457. if (_extension->property_can_revert(_extension_instance, (const GDNativeStringNamePtr)&p_name)) {
  458. return true;
  459. }
  460. }
  461. #if defined(__GNUC__) && !defined(__clang__)
  462. #pragma GCC diagnostic pop
  463. #endif
  464. return _property_can_revertv(p_name);
  465. }
  466. Variant Object::property_get_revert(const StringName &p_name) const {
  467. Variant ret;
  468. if (script_instance) {
  469. if (script_instance->property_get_revert(p_name, ret)) {
  470. return ret;
  471. }
  472. }
  473. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  474. #if defined(__GNUC__) && !defined(__clang__)
  475. #pragma GCC diagnostic push
  476. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  477. #endif
  478. if (_extension && _extension->property_get_revert) {
  479. if (_extension->property_get_revert(_extension_instance, (const GDNativeStringNamePtr)&p_name, (GDNativeVariantPtr)&ret)) {
  480. return ret;
  481. }
  482. }
  483. #if defined(__GNUC__) && !defined(__clang__)
  484. #pragma GCC diagnostic pop
  485. #endif
  486. if (_property_get_revertv(p_name, ret)) {
  487. return ret;
  488. }
  489. return Variant();
  490. }
  491. void Object::get_method_list(List<MethodInfo> *p_list) const {
  492. ClassDB::get_method_list(get_class_name(), p_list);
  493. if (script_instance) {
  494. script_instance->get_method_list(p_list);
  495. }
  496. }
  497. Variant Object::_call_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  498. if (p_argcount < 1) {
  499. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  500. r_error.argument = 0;
  501. return Variant();
  502. }
  503. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  504. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  505. r_error.argument = 0;
  506. r_error.expected = Variant::STRING_NAME;
  507. return Variant();
  508. }
  509. StringName method = *p_args[0];
  510. return callp(method, &p_args[1], p_argcount - 1, r_error);
  511. }
  512. Variant Object::_call_deferred_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  513. if (p_argcount < 1) {
  514. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  515. r_error.argument = 0;
  516. return Variant();
  517. }
  518. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  519. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  520. r_error.argument = 0;
  521. r_error.expected = Variant::STRING_NAME;
  522. return Variant();
  523. }
  524. r_error.error = Callable::CallError::CALL_OK;
  525. StringName method = *p_args[0];
  526. MessageQueue::get_singleton()->push_callp(get_instance_id(), method, &p_args[1], p_argcount - 1, true);
  527. return Variant();
  528. }
  529. bool Object::has_method(const StringName &p_method) const {
  530. if (p_method == CoreStringNames::get_singleton()->_free) {
  531. return true;
  532. }
  533. if (script_instance && script_instance->has_method(p_method)) {
  534. return true;
  535. }
  536. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  537. return method != nullptr;
  538. }
  539. Variant Object::getvar(const Variant &p_key, bool *r_valid) const {
  540. if (r_valid) {
  541. *r_valid = false;
  542. }
  543. if (p_key.get_type() == Variant::STRING_NAME || p_key.get_type() == Variant::STRING) {
  544. return get(p_key, r_valid);
  545. }
  546. return Variant();
  547. }
  548. void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) {
  549. if (r_valid) {
  550. *r_valid = false;
  551. }
  552. if (p_key.get_type() == Variant::STRING_NAME || p_key.get_type() == Variant::STRING) {
  553. return set(p_key, p_value, r_valid);
  554. }
  555. }
  556. Variant Object::callv(const StringName &p_method, const Array &p_args) {
  557. const Variant **argptrs = nullptr;
  558. if (p_args.size() > 0) {
  559. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_args.size());
  560. for (int i = 0; i < p_args.size(); i++) {
  561. argptrs[i] = &p_args[i];
  562. }
  563. }
  564. Callable::CallError ce;
  565. Variant ret = callp(p_method, argptrs, p_args.size(), ce);
  566. if (ce.error != Callable::CallError::CALL_OK) {
  567. ERR_FAIL_V_MSG(Variant(), "Error calling method from 'callv': " + Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce) + ".");
  568. }
  569. return ret;
  570. }
  571. Variant Object::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  572. r_error.error = Callable::CallError::CALL_OK;
  573. if (p_method == CoreStringNames::get_singleton()->_free) {
  574. //free must be here, before anything, always ready
  575. #ifdef DEBUG_ENABLED
  576. if (p_argcount != 0) {
  577. r_error.argument = 0;
  578. r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
  579. return Variant();
  580. }
  581. if (Object::cast_to<RefCounted>(this)) {
  582. r_error.argument = 0;
  583. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  584. ERR_FAIL_V_MSG(Variant(), "Can't 'free' a reference.");
  585. }
  586. if (_lock_index.get() > 1) {
  587. r_error.argument = 0;
  588. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  589. ERR_FAIL_V_MSG(Variant(), "Object is locked and can't be freed.");
  590. }
  591. #endif
  592. //must be here, must be before everything,
  593. memdelete(this);
  594. r_error.error = Callable::CallError::CALL_OK;
  595. return Variant();
  596. }
  597. Variant ret;
  598. OBJ_DEBUG_LOCK
  599. if (script_instance) {
  600. ret = script_instance->callp(p_method, p_args, p_argcount, r_error);
  601. //force jumptable
  602. switch (r_error.error) {
  603. case Callable::CallError::CALL_OK:
  604. return ret;
  605. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  606. break;
  607. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  608. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  609. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  610. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  611. return ret;
  612. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  613. }
  614. }
  615. }
  616. //extension does not need this, because all methods are registered in MethodBind
  617. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  618. if (method) {
  619. ret = method->call(this, p_args, p_argcount, r_error);
  620. } else {
  621. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  622. }
  623. return ret;
  624. }
  625. Variant Object::call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  626. r_error.error = Callable::CallError::CALL_OK;
  627. if (p_method == CoreStringNames::get_singleton()->_free) {
  628. // Free is not const, so fail.
  629. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  630. return Variant();
  631. }
  632. Variant ret;
  633. OBJ_DEBUG_LOCK
  634. if (script_instance) {
  635. ret = script_instance->call_const(p_method, p_args, p_argcount, r_error);
  636. //force jumptable
  637. switch (r_error.error) {
  638. case Callable::CallError::CALL_OK:
  639. return ret;
  640. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  641. break;
  642. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  643. break;
  644. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  645. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  646. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  647. return ret;
  648. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  649. }
  650. }
  651. }
  652. //extension does not need this, because all methods are registered in MethodBind
  653. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  654. if (method) {
  655. if (!method->is_const()) {
  656. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  657. return ret;
  658. }
  659. ret = method->call(this, p_args, p_argcount, r_error);
  660. } else {
  661. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  662. }
  663. return ret;
  664. }
  665. void Object::notification(int p_notification, bool p_reversed) {
  666. _notificationv(p_notification, p_reversed);
  667. if (script_instance) {
  668. script_instance->notification(p_notification);
  669. }
  670. if (_extension && _extension->notification) {
  671. _extension->notification(_extension_instance, p_notification);
  672. }
  673. }
  674. String Object::to_string() {
  675. if (script_instance) {
  676. bool valid;
  677. String ret = script_instance->to_string(&valid);
  678. if (valid) {
  679. return ret;
  680. }
  681. }
  682. if (_extension && _extension->to_string) {
  683. String ret;
  684. _extension->to_string(_extension_instance, &ret);
  685. return ret;
  686. }
  687. return "<" + get_class() + "#" + itos(get_instance_id()) + ">";
  688. }
  689. void Object::set_script_and_instance(const Variant &p_script, ScriptInstance *p_instance) {
  690. //this function is not meant to be used in any of these ways
  691. ERR_FAIL_COND(p_script.is_null());
  692. ERR_FAIL_COND(!p_instance);
  693. ERR_FAIL_COND(script_instance != nullptr || !script.is_null());
  694. script = p_script;
  695. script_instance = p_instance;
  696. }
  697. void Object::set_script(const Variant &p_script) {
  698. if (script == p_script) {
  699. return;
  700. }
  701. if (script_instance) {
  702. memdelete(script_instance);
  703. script_instance = nullptr;
  704. }
  705. script = p_script;
  706. Ref<Script> s = script;
  707. if (!s.is_null()) {
  708. if (s->can_instantiate()) {
  709. OBJ_DEBUG_LOCK
  710. script_instance = s->instance_create(this);
  711. } else if (Engine::get_singleton()->is_editor_hint()) {
  712. OBJ_DEBUG_LOCK
  713. script_instance = s->placeholder_instance_create(this);
  714. }
  715. }
  716. notify_property_list_changed(); //scripts may add variables, so refresh is desired
  717. emit_signal(CoreStringNames::get_singleton()->script_changed);
  718. }
  719. void Object::set_script_instance(ScriptInstance *p_instance) {
  720. if (script_instance == p_instance) {
  721. return;
  722. }
  723. if (script_instance) {
  724. memdelete(script_instance);
  725. }
  726. script_instance = p_instance;
  727. if (p_instance) {
  728. script = p_instance->get_script();
  729. } else {
  730. script = Variant();
  731. }
  732. }
  733. Variant Object::get_script() const {
  734. return script;
  735. }
  736. bool Object::has_meta(const StringName &p_name) const {
  737. return metadata.has(p_name);
  738. }
  739. void Object::set_meta(const StringName &p_name, const Variant &p_value) {
  740. if (p_value.get_type() == Variant::NIL) {
  741. if (metadata.has(p_name)) {
  742. metadata.erase(p_name);
  743. metadata_properties.erase("metadata/" + p_name.operator String());
  744. notify_property_list_changed();
  745. }
  746. return;
  747. }
  748. HashMap<StringName, Variant>::Iterator E = metadata.find(p_name);
  749. if (E) {
  750. E->value = p_value;
  751. } else {
  752. ERR_FAIL_COND(!p_name.operator String().is_valid_identifier());
  753. Variant *V = &metadata.insert(p_name, p_value)->value;
  754. metadata_properties["metadata/" + p_name.operator String()] = V;
  755. notify_property_list_changed();
  756. }
  757. }
  758. Variant Object::get_meta(const StringName &p_name, const Variant &p_default) const {
  759. if (!metadata.has(p_name)) {
  760. if (p_default != Variant()) {
  761. return p_default;
  762. } else {
  763. ERR_FAIL_V_MSG(Variant(), "The object does not have any 'meta' values with the key '" + p_name + "'.");
  764. }
  765. }
  766. return metadata[p_name];
  767. }
  768. void Object::remove_meta(const StringName &p_name) {
  769. set_meta(p_name, Variant());
  770. }
  771. TypedArray<Dictionary> Object::_get_property_list_bind() const {
  772. List<PropertyInfo> lpi;
  773. get_property_list(&lpi);
  774. return convert_property_list(&lpi);
  775. }
  776. TypedArray<Dictionary> Object::_get_method_list_bind() const {
  777. List<MethodInfo> ml;
  778. get_method_list(&ml);
  779. TypedArray<Dictionary> ret;
  780. for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) {
  781. Dictionary d = E->get();
  782. //va.push_back(d);
  783. ret.push_back(d);
  784. }
  785. return ret;
  786. }
  787. Vector<StringName> Object::_get_meta_list_bind() const {
  788. Vector<StringName> _metaret;
  789. for (const KeyValue<StringName, Variant> &K : metadata) {
  790. _metaret.push_back(K.key);
  791. }
  792. return _metaret;
  793. }
  794. void Object::get_meta_list(List<StringName> *p_list) const {
  795. for (const KeyValue<StringName, Variant> &K : metadata) {
  796. p_list->push_back(K.key);
  797. }
  798. }
  799. void Object::add_user_signal(const MethodInfo &p_signal) {
  800. ERR_FAIL_COND_MSG(p_signal.name.is_empty(), "Signal name cannot be empty.");
  801. ERR_FAIL_COND_MSG(ClassDB::has_signal(get_class_name(), p_signal.name), "User signal's name conflicts with a built-in signal of '" + get_class_name() + "'.");
  802. ERR_FAIL_COND_MSG(signal_map.has(p_signal.name), "Trying to add already existing signal '" + p_signal.name + "'.");
  803. SignalData s;
  804. s.user = p_signal;
  805. signal_map[p_signal.name] = s;
  806. }
  807. bool Object::_has_user_signal(const StringName &p_name) const {
  808. if (!signal_map.has(p_name)) {
  809. return false;
  810. }
  811. return signal_map[p_name].user.name.length() > 0;
  812. }
  813. struct _ObjectSignalDisconnectData {
  814. StringName signal;
  815. Callable callable;
  816. };
  817. Error Object::_emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  818. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  819. ERR_FAIL_COND_V(p_argcount < 1, Error::ERR_INVALID_PARAMETER);
  820. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  821. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  822. r_error.argument = 0;
  823. r_error.expected = Variant::STRING_NAME;
  824. ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING, Error::ERR_INVALID_PARAMETER);
  825. }
  826. r_error.error = Callable::CallError::CALL_OK;
  827. StringName signal = *p_args[0];
  828. const Variant **args = nullptr;
  829. int argc = p_argcount - 1;
  830. if (argc) {
  831. args = &p_args[1];
  832. }
  833. return emit_signalp(signal, args, argc);
  834. }
  835. Error Object::emit_signalp(const StringName &p_name, const Variant **p_args, int p_argcount) {
  836. if (_block_signals) {
  837. return ERR_CANT_ACQUIRE_RESOURCE; //no emit, signals blocked
  838. }
  839. SignalData *s = signal_map.getptr(p_name);
  840. if (!s) {
  841. #ifdef DEBUG_ENABLED
  842. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
  843. //check in script
  844. ERR_FAIL_COND_V_MSG(!signal_is_valid && !script.is_null() && !Ref<Script>(script)->has_script_signal(p_name), ERR_UNAVAILABLE, "Can't emit non-existing signal " + String("\"") + p_name + "\".");
  845. #endif
  846. //not connected? just return
  847. return ERR_UNAVAILABLE;
  848. }
  849. List<_ObjectSignalDisconnectData> disconnect_data;
  850. //copy on write will ensure that disconnecting the signal or even deleting the object will not affect the signal calling.
  851. //this happens automatically and will not change the performance of calling.
  852. //awesome, isn't it?
  853. VMap<Callable, SignalData::Slot> slot_map = s->slot_map;
  854. int ssize = slot_map.size();
  855. OBJ_DEBUG_LOCK
  856. Error err = OK;
  857. for (int i = 0; i < ssize; i++) {
  858. const Connection &c = slot_map.getv(i).conn;
  859. Object *target = c.callable.get_object();
  860. if (!target) {
  861. // Target might have been deleted during signal callback, this is expected and OK.
  862. continue;
  863. }
  864. const Variant **args = p_args;
  865. int argc = p_argcount;
  866. if (c.flags & CONNECT_DEFERRED) {
  867. MessageQueue::get_singleton()->push_callablep(c.callable, args, argc, true);
  868. } else {
  869. Callable::CallError ce;
  870. _emitting = true;
  871. Variant ret;
  872. c.callable.callp(args, argc, ret, ce);
  873. _emitting = false;
  874. if (ce.error != Callable::CallError::CALL_OK) {
  875. #ifdef DEBUG_ENABLED
  876. if (c.flags & CONNECT_PERSIST && Engine::get_singleton()->is_editor_hint() && (script.is_null() || !Ref<Script>(script)->is_tool())) {
  877. continue;
  878. }
  879. #endif
  880. if (ce.error == Callable::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) {
  881. //most likely object is not initialized yet, do not throw error.
  882. } else {
  883. ERR_PRINT("Error calling from signal '" + String(p_name) + "' to callable: " + Variant::get_callable_error_text(c.callable, args, argc, ce) + ".");
  884. err = ERR_METHOD_NOT_FOUND;
  885. }
  886. }
  887. }
  888. bool disconnect = c.flags & CONNECT_ONE_SHOT;
  889. #ifdef TOOLS_ENABLED
  890. if (disconnect && (c.flags & CONNECT_PERSIST) && Engine::get_singleton()->is_editor_hint()) {
  891. //this signal was connected from the editor, and is being edited. just don't disconnect for now
  892. disconnect = false;
  893. }
  894. #endif
  895. if (disconnect) {
  896. _ObjectSignalDisconnectData dd;
  897. dd.signal = p_name;
  898. dd.callable = c.callable;
  899. disconnect_data.push_back(dd);
  900. }
  901. }
  902. while (!disconnect_data.is_empty()) {
  903. const _ObjectSignalDisconnectData &dd = disconnect_data.front()->get();
  904. _disconnect(dd.signal, dd.callable);
  905. disconnect_data.pop_front();
  906. }
  907. return err;
  908. }
  909. void Object::_add_user_signal(const String &p_name, const Array &p_args) {
  910. // this version of add_user_signal is meant to be used from scripts or external apis
  911. // without access to ADD_SIGNAL in bind_methods
  912. // added events are per instance, as opposed to the other ones, which are global
  913. MethodInfo mi;
  914. mi.name = p_name;
  915. for (int i = 0; i < p_args.size(); i++) {
  916. Dictionary d = p_args[i];
  917. PropertyInfo param;
  918. if (d.has("name")) {
  919. param.name = d["name"];
  920. }
  921. if (d.has("type")) {
  922. param.type = (Variant::Type)(int)d["type"];
  923. }
  924. mi.arguments.push_back(param);
  925. }
  926. add_user_signal(mi);
  927. }
  928. TypedArray<Dictionary> Object::_get_signal_list() const {
  929. List<MethodInfo> signal_list;
  930. get_signal_list(&signal_list);
  931. TypedArray<Dictionary> ret;
  932. for (const MethodInfo &E : signal_list) {
  933. ret.push_back(Dictionary(E));
  934. }
  935. return ret;
  936. }
  937. TypedArray<Dictionary> Object::_get_signal_connection_list(const StringName &p_signal) const {
  938. List<Connection> conns;
  939. get_all_signal_connections(&conns);
  940. TypedArray<Dictionary> ret;
  941. for (const Connection &c : conns) {
  942. if (c.signal.get_name() == p_signal) {
  943. ret.push_back(c);
  944. }
  945. }
  946. return ret;
  947. }
  948. TypedArray<Dictionary> Object::_get_incoming_connections() const {
  949. TypedArray<Dictionary> ret;
  950. int connections_amount = connections.size();
  951. for (int idx_conn = 0; idx_conn < connections_amount; idx_conn++) {
  952. ret.push_back(connections[idx_conn]);
  953. }
  954. return ret;
  955. }
  956. bool Object::has_signal(const StringName &p_name) const {
  957. if (!script.is_null()) {
  958. Ref<Script> scr = script;
  959. if (scr.is_valid() && scr->has_script_signal(p_name)) {
  960. return true;
  961. }
  962. }
  963. if (ClassDB::has_signal(get_class_name(), p_name)) {
  964. return true;
  965. }
  966. if (_has_user_signal(p_name)) {
  967. return true;
  968. }
  969. return false;
  970. }
  971. void Object::get_signal_list(List<MethodInfo> *p_signals) const {
  972. if (!script.is_null()) {
  973. Ref<Script> scr = script;
  974. if (scr.is_valid()) {
  975. scr->get_script_signal_list(p_signals);
  976. }
  977. }
  978. ClassDB::get_signal_list(get_class_name(), p_signals);
  979. //find maybe usersignals?
  980. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  981. if (!E.value.user.name.is_empty()) {
  982. //user signal
  983. p_signals->push_back(E.value.user);
  984. }
  985. }
  986. }
  987. void Object::get_all_signal_connections(List<Connection> *p_connections) const {
  988. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  989. const SignalData *s = &E.value;
  990. for (int i = 0; i < s->slot_map.size(); i++) {
  991. p_connections->push_back(s->slot_map.getv(i).conn);
  992. }
  993. }
  994. }
  995. void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const {
  996. const SignalData *s = signal_map.getptr(p_signal);
  997. if (!s) {
  998. return; //nothing
  999. }
  1000. for (int i = 0; i < s->slot_map.size(); i++) {
  1001. p_connections->push_back(s->slot_map.getv(i).conn);
  1002. }
  1003. }
  1004. int Object::get_persistent_signal_connection_count() const {
  1005. int count = 0;
  1006. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1007. const SignalData *s = &E.value;
  1008. for (int i = 0; i < s->slot_map.size(); i++) {
  1009. if (s->slot_map.getv(i).conn.flags & CONNECT_PERSIST) {
  1010. count += 1;
  1011. }
  1012. }
  1013. }
  1014. return count;
  1015. }
  1016. void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
  1017. for (const Connection &E : connections) {
  1018. p_connections->push_back(E);
  1019. }
  1020. }
  1021. Error Object::connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags) {
  1022. ERR_FAIL_COND_V_MSG(p_callable.is_null(), ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "': the provided callable is null.");
  1023. Object *target_object = p_callable.get_object();
  1024. ERR_FAIL_COND_V_MSG(!target_object, ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "' to callable '" + p_callable + "': the callable object is null.");
  1025. SignalData *s = signal_map.getptr(p_signal);
  1026. if (!s) {
  1027. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1028. //check in script
  1029. if (!signal_is_valid && !script.is_null()) {
  1030. if (Ref<Script>(script)->has_script_signal(p_signal)) {
  1031. signal_is_valid = true;
  1032. }
  1033. #ifdef TOOLS_ENABLED
  1034. else {
  1035. //allow connecting signals anyway if script is invalid, see issue #17070
  1036. if (!Ref<Script>(script)->is_valid()) {
  1037. signal_is_valid = true;
  1038. }
  1039. }
  1040. #endif
  1041. }
  1042. ERR_FAIL_COND_V_MSG(!signal_is_valid, ERR_INVALID_PARAMETER, "In Object of type '" + String(get_class()) + "': Attempt to connect nonexistent signal '" + p_signal + "' to callable '" + p_callable + "'.");
  1043. signal_map[p_signal] = SignalData();
  1044. s = &signal_map[p_signal];
  1045. }
  1046. Callable target = p_callable;
  1047. //compare with the base callable, so binds can be ignored
  1048. if (s->slot_map.has(*target.get_base_comparator())) {
  1049. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1050. s->slot_map[*target.get_base_comparator()].reference_count++;
  1051. return OK;
  1052. } else {
  1053. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Signal '" + p_signal + "' is already connected to given callable '" + p_callable + "' in that object.");
  1054. }
  1055. }
  1056. SignalData::Slot slot;
  1057. Connection conn;
  1058. conn.callable = target;
  1059. conn.signal = ::Signal(this, p_signal);
  1060. conn.flags = p_flags;
  1061. slot.conn = conn;
  1062. slot.cE = target_object->connections.push_back(conn);
  1063. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1064. slot.reference_count = 1;
  1065. }
  1066. //use callable version as key, so binds can be ignored
  1067. s->slot_map[*target.get_base_comparator()] = slot;
  1068. return OK;
  1069. }
  1070. bool Object::is_connected(const StringName &p_signal, const Callable &p_callable) const {
  1071. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, "Cannot determine if connected to '" + p_signal + "': the provided callable is null.");
  1072. const SignalData *s = signal_map.getptr(p_signal);
  1073. if (!s) {
  1074. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1075. if (signal_is_valid) {
  1076. return false;
  1077. }
  1078. if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal)) {
  1079. return false;
  1080. }
  1081. ERR_FAIL_V_MSG(false, "Nonexistent signal: " + p_signal + ".");
  1082. }
  1083. Callable target = p_callable;
  1084. return s->slot_map.has(*target.get_base_comparator());
  1085. }
  1086. void Object::disconnect(const StringName &p_signal, const Callable &p_callable) {
  1087. _disconnect(p_signal, p_callable);
  1088. }
  1089. void Object::_disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force) {
  1090. ERR_FAIL_COND_MSG(p_callable.is_null(), "Cannot disconnect from '" + p_signal + "': the provided callable is null.");
  1091. Object *target_object = p_callable.get_object();
  1092. ERR_FAIL_COND_MSG(!target_object, "Cannot disconnect '" + p_signal + "' from callable '" + p_callable + "': the callable object is null.");
  1093. SignalData *s = signal_map.getptr(p_signal);
  1094. if (!s) {
  1095. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal) ||
  1096. (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal));
  1097. ERR_FAIL_COND_MSG(signal_is_valid, "Attempt to disconnect a nonexistent connection from '" + to_string() + "'. Signal: '" + p_signal + "', callable: '" + p_callable + "'.");
  1098. }
  1099. ERR_FAIL_COND_MSG(!s, vformat("Disconnecting nonexistent signal '%s' in %s.", p_signal, to_string()));
  1100. ERR_FAIL_COND_MSG(!s->slot_map.has(*p_callable.get_base_comparator()), "Disconnecting nonexistent signal '" + p_signal + "', callable: " + p_callable + ".");
  1101. SignalData::Slot *slot = &s->slot_map[*p_callable.get_base_comparator()];
  1102. if (!p_force) {
  1103. slot->reference_count--; // by default is zero, if it was not referenced it will go below it
  1104. if (slot->reference_count > 0) {
  1105. return;
  1106. }
  1107. }
  1108. target_object->connections.erase(slot->cE);
  1109. s->slot_map.erase(*p_callable.get_base_comparator());
  1110. if (s->slot_map.is_empty() && ClassDB::has_signal(get_class_name(), p_signal)) {
  1111. //not user signal, delete
  1112. signal_map.erase(p_signal);
  1113. }
  1114. }
  1115. void Object::_set_bind(const StringName &p_set, const Variant &p_value) {
  1116. set(p_set, p_value);
  1117. }
  1118. Variant Object::_get_bind(const StringName &p_name) const {
  1119. return get(p_name);
  1120. }
  1121. void Object::_set_indexed_bind(const NodePath &p_name, const Variant &p_value) {
  1122. set_indexed(p_name.get_as_property_path().get_subnames(), p_value);
  1123. }
  1124. Variant Object::_get_indexed_bind(const NodePath &p_name) const {
  1125. return get_indexed(p_name.get_as_property_path().get_subnames());
  1126. }
  1127. void Object::initialize_class() {
  1128. static bool initialized = false;
  1129. if (initialized) {
  1130. return;
  1131. }
  1132. ClassDB::_add_class<Object>();
  1133. _bind_methods();
  1134. initialized = true;
  1135. }
  1136. String Object::tr(const StringName &p_message, const StringName &p_context) const {
  1137. if (!_can_translate || !TranslationServer::get_singleton()) {
  1138. return p_message;
  1139. }
  1140. return TranslationServer::get_singleton()->translate(p_message, p_context);
  1141. }
  1142. String Object::tr_n(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  1143. if (!_can_translate || !TranslationServer::get_singleton()) {
  1144. // Return message based on English plural rule if translation is not possible.
  1145. if (p_n == 1) {
  1146. return p_message;
  1147. }
  1148. return p_message_plural;
  1149. }
  1150. return TranslationServer::get_singleton()->translate_plural(p_message, p_message_plural, p_n, p_context);
  1151. }
  1152. void Object::_clear_internal_resource_paths(const Variant &p_var) {
  1153. switch (p_var.get_type()) {
  1154. case Variant::OBJECT: {
  1155. Ref<Resource> r = p_var;
  1156. if (!r.is_valid()) {
  1157. return;
  1158. }
  1159. if (!r->is_built_in()) {
  1160. return; //not an internal resource
  1161. }
  1162. Object *object = p_var;
  1163. if (!object) {
  1164. return;
  1165. }
  1166. r->set_path("");
  1167. r->clear_internal_resource_paths();
  1168. } break;
  1169. case Variant::ARRAY: {
  1170. Array a = p_var;
  1171. for (int i = 0; i < a.size(); i++) {
  1172. _clear_internal_resource_paths(a[i]);
  1173. }
  1174. } break;
  1175. case Variant::DICTIONARY: {
  1176. Dictionary d = p_var;
  1177. List<Variant> keys;
  1178. d.get_key_list(&keys);
  1179. for (const Variant &E : keys) {
  1180. _clear_internal_resource_paths(E);
  1181. _clear_internal_resource_paths(d[E]);
  1182. }
  1183. } break;
  1184. default: {
  1185. }
  1186. }
  1187. }
  1188. #ifdef TOOLS_ENABLED
  1189. void Object::editor_set_section_unfold(const String &p_section, bool p_unfolded) {
  1190. set_edited(true);
  1191. if (p_unfolded) {
  1192. editor_section_folding.insert(p_section);
  1193. } else {
  1194. editor_section_folding.erase(p_section);
  1195. }
  1196. }
  1197. bool Object::editor_is_section_unfolded(const String &p_section) {
  1198. return editor_section_folding.has(p_section);
  1199. }
  1200. #endif
  1201. void Object::clear_internal_resource_paths() {
  1202. List<PropertyInfo> pinfo;
  1203. get_property_list(&pinfo);
  1204. for (const PropertyInfo &E : pinfo) {
  1205. _clear_internal_resource_paths(get(E.name));
  1206. }
  1207. }
  1208. void Object::notify_property_list_changed() {
  1209. emit_signal(CoreStringNames::get_singleton()->property_list_changed);
  1210. }
  1211. void Object::_bind_methods() {
  1212. ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class);
  1213. ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class);
  1214. ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
  1215. ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
  1216. ClassDB::bind_method(D_METHOD("set_indexed", "property_path", "value"), &Object::_set_indexed_bind);
  1217. ClassDB::bind_method(D_METHOD("get_indexed", "property_path"), &Object::_get_indexed_bind);
  1218. ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
  1219. ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
  1220. ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
  1221. ClassDB::bind_method(D_METHOD("to_string"), &Object::to_string);
  1222. ClassDB::bind_method(D_METHOD("get_instance_id"), &Object::get_instance_id);
  1223. ClassDB::bind_method(D_METHOD("set_script", "script"), &Object::set_script);
  1224. ClassDB::bind_method(D_METHOD("get_script"), &Object::get_script);
  1225. ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta);
  1226. ClassDB::bind_method(D_METHOD("remove_meta", "name"), &Object::remove_meta);
  1227. ClassDB::bind_method(D_METHOD("get_meta", "name", "default"), &Object::get_meta, DEFVAL(Variant()));
  1228. ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta);
  1229. ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind);
  1230. ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array()));
  1231. ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal);
  1232. {
  1233. MethodInfo mi;
  1234. mi.name = "emit_signal";
  1235. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "signal"));
  1236. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi, varray(), false);
  1237. }
  1238. {
  1239. MethodInfo mi;
  1240. mi.name = "call";
  1241. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1242. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call", &Object::_call_bind, mi);
  1243. }
  1244. {
  1245. MethodInfo mi;
  1246. mi.name = "call_deferred";
  1247. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1248. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi, varray(), false);
  1249. }
  1250. ClassDB::bind_method(D_METHOD("set_deferred", "property", "value"), &Object::set_deferred);
  1251. ClassDB::bind_method(D_METHOD("callv", "method", "arg_array"), &Object::callv);
  1252. ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method);
  1253. ClassDB::bind_method(D_METHOD("has_signal", "signal"), &Object::has_signal);
  1254. ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list);
  1255. ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list);
  1256. ClassDB::bind_method(D_METHOD("get_incoming_connections"), &Object::_get_incoming_connections);
  1257. ClassDB::bind_method(D_METHOD("connect", "signal", "callable", "flags"), &Object::connect, DEFVAL(0));
  1258. ClassDB::bind_method(D_METHOD("disconnect", "signal", "callable"), &Object::disconnect);
  1259. ClassDB::bind_method(D_METHOD("is_connected", "signal", "callable"), &Object::is_connected);
  1260. ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals);
  1261. ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals);
  1262. ClassDB::bind_method(D_METHOD("notify_property_list_changed"), &Object::notify_property_list_changed);
  1263. ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation);
  1264. ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages);
  1265. ClassDB::bind_method(D_METHOD("tr", "message", "context"), &Object::tr, DEFVAL(""));
  1266. ClassDB::bind_method(D_METHOD("tr_n", "message", "plural_message", "n", "context"), &Object::tr_n, DEFVAL(""));
  1267. ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion);
  1268. ClassDB::add_virtual_method("Object", MethodInfo("free"), false);
  1269. ADD_SIGNAL(MethodInfo("script_changed"));
  1270. ADD_SIGNAL(MethodInfo("property_list_changed"));
  1271. #define BIND_OBJ_CORE_METHOD(m_method) \
  1272. ::ClassDB::add_virtual_method(get_class_static(), m_method, true, Vector<String>(), true);
  1273. BIND_OBJ_CORE_METHOD(MethodInfo("_notification", PropertyInfo(Variant::INT, "what")));
  1274. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_set", PropertyInfo(Variant::STRING_NAME, "property"), PropertyInfo(Variant::NIL, "value")));
  1275. #ifdef TOOLS_ENABLED
  1276. MethodInfo miget("_get", PropertyInfo(Variant::STRING_NAME, "property"));
  1277. miget.return_val.name = "Variant";
  1278. miget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1279. BIND_OBJ_CORE_METHOD(miget);
  1280. MethodInfo plget("_get_property_list");
  1281. plget.return_val.type = Variant::ARRAY;
  1282. plget.return_val.hint = PROPERTY_HINT_ARRAY_TYPE;
  1283. plget.return_val.hint_string = "Dictionary";
  1284. BIND_OBJ_CORE_METHOD(plget);
  1285. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_property_can_revert", PropertyInfo(Variant::STRING_NAME, "property")));
  1286. MethodInfo mipgr("_property_get_revert", PropertyInfo(Variant::STRING_NAME, "property"));
  1287. mipgr.return_val.name = "Variant";
  1288. mipgr.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1289. BIND_OBJ_CORE_METHOD(mipgr);
  1290. #endif
  1291. BIND_OBJ_CORE_METHOD(MethodInfo("_init"));
  1292. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::STRING, "_to_string"));
  1293. BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE);
  1294. BIND_CONSTANT(NOTIFICATION_PREDELETE);
  1295. BIND_ENUM_CONSTANT(CONNECT_DEFERRED);
  1296. BIND_ENUM_CONSTANT(CONNECT_PERSIST);
  1297. BIND_ENUM_CONSTANT(CONNECT_ONE_SHOT);
  1298. BIND_ENUM_CONSTANT(CONNECT_REFERENCE_COUNTED);
  1299. }
  1300. void Object::set_deferred(const StringName &p_property, const Variant &p_value) {
  1301. MessageQueue::get_singleton()->push_set(this, p_property, p_value);
  1302. }
  1303. void Object::set_block_signals(bool p_block) {
  1304. _block_signals = p_block;
  1305. }
  1306. bool Object::is_blocking_signals() const {
  1307. return _block_signals;
  1308. }
  1309. void Object::get_translatable_strings(List<String> *p_strings) const {
  1310. List<PropertyInfo> plist;
  1311. get_property_list(&plist);
  1312. for (const PropertyInfo &E : plist) {
  1313. if (!(E.usage & PROPERTY_USAGE_INTERNATIONALIZED)) {
  1314. continue;
  1315. }
  1316. String text = get(E.name);
  1317. if (text.is_empty()) {
  1318. continue;
  1319. }
  1320. p_strings->push_back(text);
  1321. }
  1322. }
  1323. Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const {
  1324. bool valid;
  1325. Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid);
  1326. if (valid) {
  1327. if (r_valid) {
  1328. *r_valid = true;
  1329. }
  1330. return t;
  1331. }
  1332. if (get_script_instance()) {
  1333. return get_script_instance()->get_property_type(p_property, r_valid);
  1334. }
  1335. if (r_valid) {
  1336. *r_valid = false;
  1337. }
  1338. return Variant::NIL;
  1339. }
  1340. Variant::Type Object::get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid) const {
  1341. if (p_path.size() == 0) {
  1342. if (r_valid) {
  1343. *r_valid = false;
  1344. }
  1345. return Variant::NIL;
  1346. }
  1347. bool valid = false;
  1348. Variant::Type t = get_static_property_type(p_path[0], &valid);
  1349. if (!valid) {
  1350. if (r_valid) {
  1351. *r_valid = false;
  1352. }
  1353. return Variant::NIL;
  1354. }
  1355. Callable::CallError ce;
  1356. Variant check;
  1357. Variant::construct(t, check, nullptr, 0, ce);
  1358. for (int i = 1; i < p_path.size(); i++) {
  1359. if (check.get_type() == Variant::OBJECT || check.get_type() == Variant::DICTIONARY || check.get_type() == Variant::ARRAY) {
  1360. // We cannot be sure about the type of properties this type can have
  1361. if (r_valid) {
  1362. *r_valid = false;
  1363. }
  1364. return Variant::NIL;
  1365. }
  1366. check = check.get_named(p_path[i], valid);
  1367. if (!valid) {
  1368. if (r_valid) {
  1369. *r_valid = false;
  1370. }
  1371. return Variant::NIL;
  1372. }
  1373. }
  1374. if (r_valid) {
  1375. *r_valid = true;
  1376. }
  1377. return check.get_type();
  1378. }
  1379. bool Object::is_queued_for_deletion() const {
  1380. return _is_queued_for_deletion;
  1381. }
  1382. #ifdef TOOLS_ENABLED
  1383. void Object::set_edited(bool p_edited) {
  1384. _edited = p_edited;
  1385. _edited_version++;
  1386. }
  1387. bool Object::is_edited() const {
  1388. return _edited;
  1389. }
  1390. uint32_t Object::get_edited_version() const {
  1391. return _edited_version;
  1392. }
  1393. #endif
  1394. void Object::set_instance_binding(void *p_token, void *p_binding, const GDNativeInstanceBindingCallbacks *p_callbacks) {
  1395. // This is only meant to be used on creation by the binder.
  1396. ERR_FAIL_COND(_instance_bindings != nullptr);
  1397. _instance_bindings = (InstanceBinding *)memalloc(sizeof(InstanceBinding));
  1398. _instance_bindings[0].binding = p_binding;
  1399. _instance_bindings[0].free_callback = p_callbacks->free_callback;
  1400. _instance_bindings[0].reference_callback = p_callbacks->reference_callback;
  1401. _instance_bindings[0].token = p_token;
  1402. _instance_binding_count = 1;
  1403. }
  1404. void *Object::get_instance_binding(void *p_token, const GDNativeInstanceBindingCallbacks *p_callbacks) {
  1405. void *binding = nullptr;
  1406. _instance_binding_mutex.lock();
  1407. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1408. if (_instance_bindings[i].token == p_token) {
  1409. binding = _instance_bindings[i].binding;
  1410. break;
  1411. }
  1412. }
  1413. if (unlikely(!binding)) {
  1414. uint32_t current_size = next_power_of_2(_instance_binding_count);
  1415. uint32_t new_size = next_power_of_2(_instance_binding_count + 1);
  1416. if (current_size == 0 || new_size > current_size) {
  1417. _instance_bindings = (InstanceBinding *)memrealloc(_instance_bindings, new_size * sizeof(InstanceBinding));
  1418. }
  1419. _instance_bindings[_instance_binding_count].free_callback = p_callbacks->free_callback;
  1420. _instance_bindings[_instance_binding_count].reference_callback = p_callbacks->reference_callback;
  1421. _instance_bindings[_instance_binding_count].token = p_token;
  1422. binding = p_callbacks->create_callback(p_token, this);
  1423. _instance_bindings[_instance_binding_count].binding = binding;
  1424. _instance_binding_count++;
  1425. }
  1426. _instance_binding_mutex.unlock();
  1427. return binding;
  1428. }
  1429. bool Object::has_instance_binding(void *p_token) {
  1430. bool found = false;
  1431. _instance_binding_mutex.lock();
  1432. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1433. if (_instance_bindings[i].token == p_token) {
  1434. found = true;
  1435. break;
  1436. }
  1437. }
  1438. _instance_binding_mutex.unlock();
  1439. return found;
  1440. }
  1441. void Object::_construct_object(bool p_reference) {
  1442. type_is_reference = p_reference;
  1443. _instance_id = ObjectDB::add_instance(this);
  1444. #ifdef DEBUG_ENABLED
  1445. _lock_index.init(1);
  1446. #endif
  1447. }
  1448. Object::Object(bool p_reference) {
  1449. _construct_object(p_reference);
  1450. }
  1451. Object::Object() {
  1452. _construct_object(false);
  1453. }
  1454. void Object::detach_from_objectdb() {
  1455. if (_instance_id != ObjectID()) {
  1456. ObjectDB::remove_instance(this);
  1457. _instance_id = ObjectID();
  1458. }
  1459. }
  1460. Object::~Object() {
  1461. if (script_instance) {
  1462. memdelete(script_instance);
  1463. }
  1464. script_instance = nullptr;
  1465. if (_extension && _extension->free_instance) {
  1466. _extension->free_instance(_extension->class_userdata, _extension_instance);
  1467. _extension = nullptr;
  1468. _extension_instance = nullptr;
  1469. }
  1470. if (_emitting) {
  1471. //@todo this may need to actually reach the debugger prioritarily somehow because it may crash before
  1472. ERR_PRINT("Object " + to_string() + " was freed or unreferenced while a signal is being emitted from it. Try connecting to the signal using 'CONNECT_DEFERRED' flag, or use queue_free() to free the object (if this object is a Node) to avoid this error and potential crashes.");
  1473. }
  1474. while (signal_map.size()) {
  1475. // Avoid regular iteration so erasing is safe.
  1476. KeyValue<StringName, SignalData> &E = *signal_map.begin();
  1477. SignalData *s = &E.value;
  1478. //brute force disconnect for performance
  1479. int slot_count = s->slot_map.size();
  1480. const VMap<Callable, SignalData::Slot>::Pair *slot_list = s->slot_map.get_array();
  1481. for (int i = 0; i < slot_count; i++) {
  1482. slot_list[i].value.conn.callable.get_object()->connections.erase(slot_list[i].value.cE);
  1483. }
  1484. signal_map.erase(E.key);
  1485. }
  1486. //signals from nodes that connect to this node
  1487. while (connections.size()) {
  1488. Connection c = connections.front()->get();
  1489. c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true);
  1490. }
  1491. if (_instance_id != ObjectID()) {
  1492. ObjectDB::remove_instance(this);
  1493. _instance_id = ObjectID();
  1494. }
  1495. _predelete_ok = 2;
  1496. if (_instance_bindings != nullptr) {
  1497. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1498. if (_instance_bindings[i].free_callback) {
  1499. _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
  1500. }
  1501. }
  1502. memfree(_instance_bindings);
  1503. }
  1504. }
  1505. bool predelete_handler(Object *p_object) {
  1506. return p_object->_predelete();
  1507. }
  1508. void postinitialize_handler(Object *p_object) {
  1509. p_object->_postinitialize();
  1510. }
  1511. void ObjectDB::debug_objects(DebugFunc p_func) {
  1512. spin_lock.lock();
  1513. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1514. if (object_slots[i].validator) {
  1515. p_func(object_slots[i].object);
  1516. count--;
  1517. }
  1518. }
  1519. spin_lock.unlock();
  1520. }
  1521. void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  1522. }
  1523. SpinLock ObjectDB::spin_lock;
  1524. uint32_t ObjectDB::slot_count = 0;
  1525. uint32_t ObjectDB::slot_max = 0;
  1526. ObjectDB::ObjectSlot *ObjectDB::object_slots = nullptr;
  1527. uint64_t ObjectDB::validator_counter = 0;
  1528. int ObjectDB::get_object_count() {
  1529. return slot_count;
  1530. }
  1531. ObjectID ObjectDB::add_instance(Object *p_object) {
  1532. spin_lock.lock();
  1533. if (unlikely(slot_count == slot_max)) {
  1534. CRASH_COND(slot_count == (1 << OBJECTDB_SLOT_MAX_COUNT_BITS));
  1535. uint32_t new_slot_max = slot_max > 0 ? slot_max * 2 : 1;
  1536. object_slots = (ObjectSlot *)memrealloc(object_slots, sizeof(ObjectSlot) * new_slot_max);
  1537. for (uint32_t i = slot_max; i < new_slot_max; i++) {
  1538. object_slots[i].object = nullptr;
  1539. object_slots[i].is_ref_counted = false;
  1540. object_slots[i].next_free = i;
  1541. object_slots[i].validator = 0;
  1542. }
  1543. slot_max = new_slot_max;
  1544. }
  1545. uint32_t slot = object_slots[slot_count].next_free;
  1546. if (object_slots[slot].object != nullptr) {
  1547. spin_lock.unlock();
  1548. ERR_FAIL_COND_V(object_slots[slot].object != nullptr, ObjectID());
  1549. }
  1550. object_slots[slot].object = p_object;
  1551. object_slots[slot].is_ref_counted = p_object->is_ref_counted();
  1552. validator_counter = (validator_counter + 1) & OBJECTDB_VALIDATOR_MASK;
  1553. if (unlikely(validator_counter == 0)) {
  1554. validator_counter = 1;
  1555. }
  1556. object_slots[slot].validator = validator_counter;
  1557. uint64_t id = validator_counter;
  1558. id <<= OBJECTDB_SLOT_MAX_COUNT_BITS;
  1559. id |= uint64_t(slot);
  1560. if (p_object->is_ref_counted()) {
  1561. id |= OBJECTDB_REFERENCE_BIT;
  1562. }
  1563. slot_count++;
  1564. spin_lock.unlock();
  1565. return ObjectID(id);
  1566. }
  1567. void ObjectDB::remove_instance(Object *p_object) {
  1568. uint64_t t = p_object->get_instance_id();
  1569. uint32_t slot = t & OBJECTDB_SLOT_MAX_COUNT_MASK; //slot is always valid on valid object
  1570. spin_lock.lock();
  1571. #ifdef DEBUG_ENABLED
  1572. if (object_slots[slot].object != p_object) {
  1573. spin_lock.unlock();
  1574. ERR_FAIL_COND(object_slots[slot].object != p_object);
  1575. }
  1576. {
  1577. uint64_t validator = (t >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK;
  1578. if (object_slots[slot].validator != validator) {
  1579. spin_lock.unlock();
  1580. ERR_FAIL_COND(object_slots[slot].validator != validator);
  1581. }
  1582. }
  1583. #endif
  1584. //decrease slot count
  1585. slot_count--;
  1586. //set the free slot properly
  1587. object_slots[slot_count].next_free = slot;
  1588. //invalidate, so checks against it fail
  1589. object_slots[slot].validator = 0;
  1590. object_slots[slot].is_ref_counted = false;
  1591. object_slots[slot].object = nullptr;
  1592. spin_lock.unlock();
  1593. }
  1594. void ObjectDB::setup() {
  1595. //nothing to do now
  1596. }
  1597. void ObjectDB::cleanup() {
  1598. if (slot_count > 0) {
  1599. spin_lock.lock();
  1600. WARN_PRINT("ObjectDB instances leaked at exit (run with --verbose for details).");
  1601. if (OS::get_singleton()->is_stdout_verbose()) {
  1602. // Ensure calling the native classes because if a leaked instance has a script
  1603. // that overrides any of those methods, it'd not be OK to call them at this point,
  1604. // now the scripting languages have already been terminated.
  1605. MethodBind *node_get_name = ClassDB::get_method("Node", "get_name");
  1606. MethodBind *resource_get_path = ClassDB::get_method("Resource", "get_path");
  1607. Callable::CallError call_error;
  1608. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1609. if (object_slots[i].validator) {
  1610. Object *obj = object_slots[i].object;
  1611. String extra_info;
  1612. if (obj->is_class("Node")) {
  1613. extra_info = " - Node name: " + String(node_get_name->call(obj, nullptr, 0, call_error));
  1614. }
  1615. if (obj->is_class("Resource")) {
  1616. extra_info = " - Resource path: " + String(resource_get_path->call(obj, nullptr, 0, call_error));
  1617. }
  1618. uint64_t id = uint64_t(i) | (uint64_t(object_slots[i].validator) << OBJECTDB_VALIDATOR_BITS) | (object_slots[i].is_ref_counted ? OBJECTDB_REFERENCE_BIT : 0);
  1619. print_line("Leaked instance: " + String(obj->get_class()) + ":" + itos(id) + extra_info);
  1620. count--;
  1621. }
  1622. }
  1623. print_line("Hint: Leaked instances typically happen when nodes are removed from the scene tree (with `remove_child()`) but not freed (with `free()` or `queue_free()`).");
  1624. }
  1625. spin_lock.unlock();
  1626. }
  1627. if (object_slots) {
  1628. memfree(object_slots);
  1629. }
  1630. }