object.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  1. /**************************************************************************/
  2. /* object.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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/extension/gdextension_manager.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_server.h"
  39. #include "core/variant/typed_array.h"
  40. #ifdef DEBUG_ENABLED
  41. struct _ObjectDebugLock {
  42. ObjectID obj_id;
  43. _ObjectDebugLock(Object *p_obj) {
  44. obj_id = p_obj->get_instance_id();
  45. p_obj->_lock_index.ref();
  46. }
  47. ~_ObjectDebugLock() {
  48. Object *obj_ptr = ObjectDB::get_instance(obj_id);
  49. if (likely(obj_ptr)) {
  50. obj_ptr->_lock_index.unref();
  51. }
  52. }
  53. };
  54. #define OBJ_DEBUG_LOCK _ObjectDebugLock _debug_lock(this);
  55. #else
  56. #define OBJ_DEBUG_LOCK
  57. #endif
  58. struct _ObjectSignalLock {
  59. Mutex *mutex;
  60. _ObjectSignalLock(const Object *const p_obj) {
  61. mutex = p_obj->signal_mutex;
  62. if (mutex) {
  63. mutex->lock();
  64. }
  65. }
  66. ~_ObjectSignalLock() {
  67. if (mutex) {
  68. mutex->unlock();
  69. }
  70. }
  71. };
  72. #define OBJ_SIGNAL_LOCK _ObjectSignalLock _signal_lock(this);
  73. PropertyInfo::operator Dictionary() const {
  74. Dictionary d;
  75. d["name"] = name;
  76. d["class_name"] = class_name;
  77. d["type"] = type;
  78. d["hint"] = hint;
  79. d["hint_string"] = hint_string;
  80. d["usage"] = usage;
  81. return d;
  82. }
  83. PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) {
  84. PropertyInfo pi;
  85. if (p_dict.has("type")) {
  86. pi.type = Variant::Type(int(p_dict["type"]));
  87. }
  88. if (p_dict.has("name")) {
  89. pi.name = p_dict["name"];
  90. }
  91. if (p_dict.has("class_name")) {
  92. pi.class_name = p_dict["class_name"];
  93. }
  94. if (p_dict.has("hint")) {
  95. pi.hint = PropertyHint(int(p_dict["hint"]));
  96. }
  97. if (p_dict.has("hint_string")) {
  98. pi.hint_string = p_dict["hint_string"];
  99. }
  100. if (p_dict.has("usage")) {
  101. pi.usage = p_dict["usage"];
  102. }
  103. return pi;
  104. }
  105. TypedArray<Dictionary> convert_property_list(const List<PropertyInfo> *p_list) {
  106. TypedArray<Dictionary> va;
  107. for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) {
  108. va.push_back(Dictionary(E->get()));
  109. }
  110. return va;
  111. }
  112. TypedArray<Dictionary> convert_property_list(const Vector<PropertyInfo> &p_vector) {
  113. TypedArray<Dictionary> va;
  114. for (const PropertyInfo &E : p_vector) {
  115. va.push_back(Dictionary(E));
  116. }
  117. return va;
  118. }
  119. MethodInfo::operator Dictionary() const {
  120. Dictionary d;
  121. d["name"] = name;
  122. d["args"] = convert_property_list(arguments);
  123. Array da;
  124. for (int i = 0; i < default_arguments.size(); i++) {
  125. da.push_back(default_arguments[i]);
  126. }
  127. d["default_args"] = da;
  128. d["flags"] = flags;
  129. d["id"] = id;
  130. Dictionary r = return_val;
  131. d["return"] = r;
  132. return d;
  133. }
  134. MethodInfo MethodInfo::from_dict(const Dictionary &p_dict) {
  135. MethodInfo mi;
  136. if (p_dict.has("name")) {
  137. mi.name = p_dict["name"];
  138. }
  139. Array args;
  140. if (p_dict.has("args")) {
  141. args = p_dict["args"];
  142. }
  143. for (const Variant &arg : args) {
  144. Dictionary d = arg;
  145. mi.arguments.push_back(PropertyInfo::from_dict(d));
  146. }
  147. Array defargs;
  148. if (p_dict.has("default_args")) {
  149. defargs = p_dict["default_args"];
  150. }
  151. for (const Variant &defarg : defargs) {
  152. mi.default_arguments.push_back(defarg);
  153. }
  154. if (p_dict.has("return")) {
  155. mi.return_val = PropertyInfo::from_dict(p_dict["return"]);
  156. }
  157. if (p_dict.has("flags")) {
  158. mi.flags = p_dict["flags"];
  159. }
  160. return mi;
  161. }
  162. uint32_t MethodInfo::get_compatibility_hash() const {
  163. bool has_return = (return_val.type != Variant::NIL) || (return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT);
  164. uint32_t hash = hash_murmur3_one_32(has_return);
  165. hash = hash_murmur3_one_32(arguments.size(), hash);
  166. if (has_return) {
  167. hash = hash_murmur3_one_32(return_val.type, hash);
  168. if (return_val.class_name != StringName()) {
  169. hash = hash_murmur3_one_32(return_val.class_name.hash(), hash);
  170. }
  171. }
  172. for (const PropertyInfo &arg : arguments) {
  173. hash = hash_murmur3_one_32(arg.type, hash);
  174. if (arg.class_name != StringName()) {
  175. hash = hash_murmur3_one_32(arg.class_name.hash(), hash);
  176. }
  177. }
  178. hash = hash_murmur3_one_32(default_arguments.size(), hash);
  179. for (const Variant &v : default_arguments) {
  180. hash = hash_murmur3_one_32(v.hash(), hash);
  181. }
  182. hash = hash_murmur3_one_32(flags & METHOD_FLAG_CONST ? 1 : 0, hash);
  183. hash = hash_murmur3_one_32(flags & METHOD_FLAG_VARARG ? 1 : 0, hash);
  184. return hash_fmix32(hash);
  185. }
  186. Object::Connection::operator Variant() const {
  187. Dictionary d;
  188. d["signal"] = signal;
  189. d["callable"] = callable;
  190. d["flags"] = flags;
  191. return d;
  192. }
  193. void ObjectGDExtension::create_gdtype() {
  194. ERR_FAIL_COND(gdtype);
  195. gdtype = memnew(GDType(ClassDB::get_gdtype(parent_class_name), class_name));
  196. }
  197. void ObjectGDExtension::destroy_gdtype() {
  198. ERR_FAIL_COND(!gdtype);
  199. memdelete(const_cast<GDType *>(gdtype));
  200. gdtype = nullptr;
  201. }
  202. ObjectGDExtension::~ObjectGDExtension() {
  203. if (gdtype) {
  204. memdelete(const_cast<GDType *>(gdtype));
  205. }
  206. }
  207. bool Object::Connection::operator<(const Connection &p_conn) const {
  208. if (signal == p_conn.signal) {
  209. return callable < p_conn.callable;
  210. } else {
  211. return signal < p_conn.signal;
  212. }
  213. }
  214. Object::Connection::Connection(const Variant &p_variant) {
  215. Dictionary d = p_variant;
  216. if (d.has("signal")) {
  217. signal = d["signal"];
  218. }
  219. if (d.has("callable")) {
  220. callable = d["callable"];
  221. }
  222. if (d.has("flags")) {
  223. flags = d["flags"];
  224. }
  225. }
  226. bool Object::_predelete() {
  227. _predelete_ok = true;
  228. notification(NOTIFICATION_PREDELETE, true);
  229. if (!_predelete_ok) {
  230. return false;
  231. }
  232. _gdtype_ptr = nullptr; // Must restore, so constructors/destructors have proper class name access at each stage.
  233. notification(NOTIFICATION_PREDELETE_CLEANUP, true);
  234. // Destruction order starts with the most derived class, and progresses towards the base Object class:
  235. // Script subclasses -> GDExtension subclasses -> C++ subclasses -> Object
  236. if (script_instance) {
  237. memdelete(script_instance);
  238. }
  239. script_instance = nullptr;
  240. if (_extension) {
  241. #ifdef TOOLS_ENABLED
  242. if (_extension->untrack_instance) {
  243. _extension->untrack_instance(_extension->tracking_userdata, this);
  244. }
  245. #endif
  246. if (_extension->free_instance) {
  247. _extension->free_instance(_extension->class_userdata, _extension_instance);
  248. }
  249. _extension = nullptr;
  250. _extension_instance = nullptr;
  251. // _gdtype_ptr = nullptr; // The pointer already set to nullptr above, no need to do it again.
  252. }
  253. #ifdef TOOLS_ENABLED
  254. else if (_instance_bindings != nullptr) {
  255. Engine *engine = Engine::get_singleton();
  256. GDExtensionManager *gdextension_manager = GDExtensionManager::get_singleton();
  257. if (engine && gdextension_manager && engine->is_extension_reloading_enabled()) {
  258. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  259. gdextension_manager->untrack_instance_binding(_instance_bindings[i].token, this);
  260. }
  261. }
  262. }
  263. #endif
  264. return true;
  265. }
  266. void Object::cancel_free() {
  267. _predelete_ok = false;
  268. }
  269. void Object::_initialize() {
  270. // Cache the class name in the object for quick reference.
  271. _gdtype_ptr = &_get_typev();
  272. _initialize_classv();
  273. }
  274. void Object::_postinitialize() {
  275. if (_uses_signal_mutex()) {
  276. signal_mutex = memnew(Mutex);
  277. }
  278. notification(NOTIFICATION_POSTINITIALIZE);
  279. }
  280. void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid) {
  281. #ifdef TOOLS_ENABLED
  282. _edited = true;
  283. #endif
  284. if (script_instance) {
  285. if (script_instance->set(p_name, p_value)) {
  286. if (r_valid) {
  287. *r_valid = true;
  288. }
  289. return;
  290. }
  291. }
  292. if (_extension && _extension->set) {
  293. if (_extension->set(_extension_instance, (GDExtensionConstStringNamePtr)&p_name, (GDExtensionConstVariantPtr)&p_value)) {
  294. if (r_valid) {
  295. *r_valid = true;
  296. }
  297. return;
  298. }
  299. }
  300. // Try built-in setter.
  301. {
  302. if (ClassDB::set_property(this, p_name, p_value, r_valid)) {
  303. return;
  304. }
  305. }
  306. if (p_name == CoreStringName(script)) {
  307. set_script(p_value);
  308. if (r_valid) {
  309. *r_valid = true;
  310. }
  311. return;
  312. } else {
  313. Variant **V = metadata_properties.getptr(p_name);
  314. if (V) {
  315. **V = p_value;
  316. if (r_valid) {
  317. *r_valid = true;
  318. }
  319. return;
  320. } else if (p_name.operator String().begins_with("metadata/")) {
  321. // Must exist, otherwise duplicate() will not work.
  322. set_meta(p_name.operator String().replace_first("metadata/", ""), p_value);
  323. if (r_valid) {
  324. *r_valid = true;
  325. }
  326. return;
  327. }
  328. }
  329. #ifdef TOOLS_ENABLED
  330. if (script_instance) {
  331. bool valid;
  332. script_instance->property_set_fallback(p_name, p_value, &valid);
  333. if (valid) {
  334. if (r_valid) {
  335. *r_valid = true;
  336. }
  337. return;
  338. }
  339. }
  340. #endif
  341. // Something inside the object... :|
  342. bool success = _setv(p_name, p_value);
  343. if (success) {
  344. if (r_valid) {
  345. *r_valid = true;
  346. }
  347. return;
  348. }
  349. if (r_valid) {
  350. *r_valid = false;
  351. }
  352. }
  353. Variant Object::get(const StringName &p_name, bool *r_valid) const {
  354. Variant ret;
  355. if (script_instance) {
  356. if (script_instance->get(p_name, ret)) {
  357. if (r_valid) {
  358. *r_valid = true;
  359. }
  360. return ret;
  361. }
  362. }
  363. if (_extension && _extension->get) {
  364. if (_extension->get(_extension_instance, (GDExtensionConstStringNamePtr)&p_name, (GDExtensionVariantPtr)&ret)) {
  365. if (r_valid) {
  366. *r_valid = true;
  367. }
  368. return ret;
  369. }
  370. }
  371. // Try built-in getter.
  372. {
  373. if (ClassDB::get_property(const_cast<Object *>(this), p_name, ret)) {
  374. if (r_valid) {
  375. *r_valid = true;
  376. }
  377. return ret;
  378. }
  379. }
  380. if (p_name == CoreStringName(script)) {
  381. ret = get_script();
  382. if (r_valid) {
  383. *r_valid = true;
  384. }
  385. return ret;
  386. }
  387. const Variant *const *V = metadata_properties.getptr(p_name);
  388. if (V) {
  389. ret = **V;
  390. if (r_valid) {
  391. *r_valid = true;
  392. }
  393. return ret;
  394. } else {
  395. #ifdef TOOLS_ENABLED
  396. if (script_instance) {
  397. bool valid;
  398. ret = script_instance->property_get_fallback(p_name, &valid);
  399. if (valid) {
  400. if (r_valid) {
  401. *r_valid = true;
  402. }
  403. return ret;
  404. }
  405. }
  406. #endif
  407. // Something inside the object... :|
  408. bool success = _getv(p_name, ret);
  409. if (success) {
  410. if (r_valid) {
  411. *r_valid = true;
  412. }
  413. return ret;
  414. }
  415. if (r_valid) {
  416. *r_valid = false;
  417. }
  418. return Variant();
  419. }
  420. }
  421. void Object::set_indexed(const Vector<StringName> &p_names, const Variant &p_value, bool *r_valid) {
  422. if (p_names.is_empty()) {
  423. if (r_valid) {
  424. *r_valid = false;
  425. }
  426. return;
  427. }
  428. if (p_names.size() == 1) {
  429. set(p_names[0], p_value, r_valid);
  430. return;
  431. }
  432. bool valid = false;
  433. if (!r_valid) {
  434. r_valid = &valid;
  435. }
  436. List<Variant> value_stack;
  437. value_stack.push_back(get(p_names[0], r_valid));
  438. if (!*r_valid) {
  439. value_stack.clear();
  440. return;
  441. }
  442. for (int i = 1; i < p_names.size() - 1; i++) {
  443. value_stack.push_back(value_stack.back()->get().get_named(p_names[i], valid));
  444. if (r_valid) {
  445. *r_valid = valid;
  446. }
  447. if (!valid) {
  448. value_stack.clear();
  449. return;
  450. }
  451. }
  452. value_stack.push_back(p_value); // p_names[p_names.size() - 1]
  453. for (int i = p_names.size() - 1; i > 0; i--) {
  454. value_stack.back()->prev()->get().set_named(p_names[i], value_stack.back()->get(), valid);
  455. value_stack.pop_back();
  456. if (r_valid) {
  457. *r_valid = valid;
  458. }
  459. if (!valid) {
  460. value_stack.clear();
  461. return;
  462. }
  463. }
  464. set(p_names[0], value_stack.back()->get(), r_valid);
  465. value_stack.pop_back();
  466. ERR_FAIL_COND(!value_stack.is_empty());
  467. }
  468. Variant Object::get_indexed(const Vector<StringName> &p_names, bool *r_valid) const {
  469. if (p_names.is_empty()) {
  470. if (r_valid) {
  471. *r_valid = false;
  472. }
  473. return Variant();
  474. }
  475. bool valid = false;
  476. Variant current_value = get(p_names[0], &valid);
  477. for (int i = 1; i < p_names.size(); i++) {
  478. current_value = current_value.get_named(p_names[i], valid);
  479. if (!valid) {
  480. break;
  481. }
  482. }
  483. if (r_valid) {
  484. *r_valid = valid;
  485. }
  486. return current_value;
  487. }
  488. void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) const {
  489. if (script_instance && p_reversed) {
  490. script_instance->get_property_list(p_list);
  491. }
  492. if (_extension) {
  493. const ObjectGDExtension *current_extension = _extension;
  494. while (current_extension) {
  495. p_list->push_back(PropertyInfo(Variant::NIL, current_extension->class_name, PROPERTY_HINT_NONE, current_extension->class_name, PROPERTY_USAGE_CATEGORY));
  496. ClassDB::get_property_list(current_extension->class_name, p_list, true, this);
  497. if (current_extension->get_property_list) {
  498. #ifdef TOOLS_ENABLED
  499. // If this is a placeholder, we can't call into the GDExtension on the parent class,
  500. // because we don't have a real instance of the class to give it.
  501. if (likely(!_extension->is_placeholder)) {
  502. #endif
  503. uint32_t pcount;
  504. const GDExtensionPropertyInfo *pinfo = current_extension->get_property_list(_extension_instance, &pcount);
  505. for (uint32_t i = 0; i < pcount; i++) {
  506. p_list->push_back(PropertyInfo(pinfo[i]));
  507. }
  508. if (current_extension->free_property_list2) {
  509. current_extension->free_property_list2(_extension_instance, pinfo, pcount);
  510. }
  511. #ifndef DISABLE_DEPRECATED
  512. else if (current_extension->free_property_list) {
  513. current_extension->free_property_list(_extension_instance, pinfo);
  514. }
  515. #endif // DISABLE_DEPRECATED
  516. #ifdef TOOLS_ENABLED
  517. }
  518. #endif
  519. }
  520. current_extension = current_extension->parent;
  521. }
  522. }
  523. _get_property_listv(p_list, p_reversed);
  524. if (!is_class("Script")) { // can still be set, but this is for user-friendliness
  525. p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NEVER_DUPLICATE));
  526. }
  527. if (script_instance && !p_reversed) {
  528. script_instance->get_property_list(p_list);
  529. }
  530. for (const KeyValue<StringName, Variant> &K : metadata) {
  531. PropertyInfo pi = PropertyInfo(K.value.get_type(), "metadata/" + K.key.operator String());
  532. if (K.value.get_type() == Variant::OBJECT) {
  533. pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
  534. Object *obj = K.value;
  535. if (Object::cast_to<Script>(obj)) {
  536. pi.hint_string = "Script";
  537. pi.usage |= PROPERTY_USAGE_NEVER_DUPLICATE;
  538. } else {
  539. pi.hint_string = "Resource";
  540. }
  541. }
  542. p_list->push_back(pi);
  543. }
  544. }
  545. void Object::validate_property(PropertyInfo &p_property) const {
  546. _validate_propertyv(p_property);
  547. if (_extension && _extension->validate_property) {
  548. // GDExtension uses a StringName rather than a String for property name.
  549. StringName prop_name = p_property.name;
  550. GDExtensionPropertyInfo gdext_prop = {
  551. (GDExtensionVariantType)p_property.type,
  552. &prop_name,
  553. &p_property.class_name,
  554. (uint32_t)p_property.hint,
  555. &p_property.hint_string,
  556. p_property.usage,
  557. };
  558. if (_extension->validate_property(_extension_instance, &gdext_prop)) {
  559. p_property.type = (Variant::Type)gdext_prop.type;
  560. p_property.name = *reinterpret_cast<StringName *>(gdext_prop.name);
  561. p_property.class_name = *reinterpret_cast<StringName *>(gdext_prop.class_name);
  562. p_property.hint = (PropertyHint)gdext_prop.hint;
  563. p_property.hint_string = *reinterpret_cast<String *>(gdext_prop.hint_string);
  564. p_property.usage = gdext_prop.usage;
  565. };
  566. }
  567. if (script_instance) { // Call it last to allow user altering already validated properties.
  568. script_instance->validate_property(p_property);
  569. }
  570. }
  571. bool Object::property_can_revert(const StringName &p_name) const {
  572. if (script_instance) {
  573. if (script_instance->property_can_revert(p_name)) {
  574. return true;
  575. }
  576. }
  577. if (_extension && _extension->property_can_revert) {
  578. if (_extension->property_can_revert(_extension_instance, (GDExtensionConstStringNamePtr)&p_name)) {
  579. return true;
  580. }
  581. }
  582. return _property_can_revertv(p_name);
  583. }
  584. Variant Object::property_get_revert(const StringName &p_name) const {
  585. Variant ret;
  586. if (script_instance) {
  587. if (script_instance->property_get_revert(p_name, ret)) {
  588. return ret;
  589. }
  590. }
  591. if (_extension && _extension->property_get_revert) {
  592. if (_extension->property_get_revert(_extension_instance, (GDExtensionConstStringNamePtr)&p_name, (GDExtensionVariantPtr)&ret)) {
  593. return ret;
  594. }
  595. }
  596. if (_property_get_revertv(p_name, ret)) {
  597. return ret;
  598. }
  599. return Variant();
  600. }
  601. void Object::get_method_list(List<MethodInfo> *p_list) const {
  602. ClassDB::get_method_list(get_class_name(), p_list);
  603. if (script_instance) {
  604. script_instance->get_method_list(p_list);
  605. }
  606. }
  607. Variant Object::_call_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  608. if (p_argcount < 1) {
  609. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  610. r_error.expected = 1;
  611. return Variant();
  612. }
  613. if (!p_args[0]->is_string()) {
  614. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  615. r_error.argument = 0;
  616. r_error.expected = Variant::STRING_NAME;
  617. return Variant();
  618. }
  619. StringName method = *p_args[0];
  620. return callp(method, &p_args[1], p_argcount - 1, r_error);
  621. }
  622. Variant Object::_call_deferred_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  623. if (p_argcount < 1) {
  624. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  625. r_error.expected = 1;
  626. return Variant();
  627. }
  628. if (!p_args[0]->is_string()) {
  629. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  630. r_error.argument = 0;
  631. r_error.expected = Variant::STRING_NAME;
  632. return Variant();
  633. }
  634. r_error.error = Callable::CallError::CALL_OK;
  635. StringName method = *p_args[0];
  636. MessageQueue::get_singleton()->push_callp(get_instance_id(), method, &p_args[1], p_argcount - 1, true);
  637. return Variant();
  638. }
  639. bool Object::has_method(const StringName &p_method) const {
  640. if (p_method == CoreStringName(free_)) {
  641. return true;
  642. }
  643. if (script_instance && script_instance->has_method(p_method)) {
  644. return true;
  645. }
  646. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  647. if (method != nullptr) {
  648. return true;
  649. }
  650. const Script *scr = Object::cast_to<Script>(this);
  651. if (scr != nullptr) {
  652. return scr->has_static_method(p_method);
  653. }
  654. return false;
  655. }
  656. int Object::_get_method_argument_count_bind(const StringName &p_method) const {
  657. return get_method_argument_count(p_method);
  658. }
  659. int Object::get_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
  660. if (p_method == CoreStringName(free_)) {
  661. if (r_is_valid) {
  662. *r_is_valid = true;
  663. }
  664. return 0;
  665. }
  666. if (script_instance) {
  667. bool valid = false;
  668. int ret = script_instance->get_method_argument_count(p_method, &valid);
  669. if (valid) {
  670. if (r_is_valid) {
  671. *r_is_valid = true;
  672. }
  673. return ret;
  674. }
  675. }
  676. {
  677. bool valid = false;
  678. int ret = ClassDB::get_method_argument_count(get_class_name(), p_method, &valid);
  679. if (valid) {
  680. if (r_is_valid) {
  681. *r_is_valid = true;
  682. }
  683. return ret;
  684. }
  685. }
  686. const Script *scr = Object::cast_to<Script>(this);
  687. while (scr != nullptr) {
  688. bool valid = false;
  689. int ret = scr->get_script_method_argument_count(p_method, &valid);
  690. if (valid) {
  691. if (r_is_valid) {
  692. *r_is_valid = true;
  693. }
  694. return ret;
  695. }
  696. scr = scr->get_base_script().ptr();
  697. }
  698. if (r_is_valid) {
  699. *r_is_valid = false;
  700. }
  701. return 0;
  702. }
  703. Variant Object::getvar(const Variant &p_key, bool *r_valid) const {
  704. if (r_valid) {
  705. *r_valid = false;
  706. }
  707. if (p_key.is_string()) {
  708. return get(p_key, r_valid);
  709. }
  710. return Variant();
  711. }
  712. void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) {
  713. if (r_valid) {
  714. *r_valid = false;
  715. }
  716. if (p_key.is_string()) {
  717. return set(p_key, p_value, r_valid);
  718. }
  719. }
  720. Variant Object::callv(const StringName &p_method, const Array &p_args) {
  721. const Variant **argptrs = nullptr;
  722. if (p_args.size() > 0) {
  723. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_args.size());
  724. for (int i = 0; i < p_args.size(); i++) {
  725. argptrs[i] = &p_args[i];
  726. }
  727. }
  728. Callable::CallError ce;
  729. const Variant ret = callp(p_method, argptrs, p_args.size(), ce);
  730. if (ce.error != Callable::CallError::CALL_OK) {
  731. ERR_FAIL_V_MSG(Variant(), vformat("Error calling method from 'callv': %s.", Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce)));
  732. }
  733. return ret;
  734. }
  735. Variant Object::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  736. r_error.error = Callable::CallError::CALL_OK;
  737. if (p_method == CoreStringName(free_)) {
  738. //free must be here, before anything, always ready
  739. #ifdef DEBUG_ENABLED
  740. if (p_argcount != 0) {
  741. r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
  742. r_error.expected = 0;
  743. return Variant();
  744. }
  745. if (is_ref_counted()) {
  746. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  747. ERR_FAIL_V_MSG(Variant(), "Can't free a RefCounted object.");
  748. }
  749. if (_lock_index.get() > 1) {
  750. r_error.argument = 0;
  751. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  752. ERR_FAIL_V_MSG(Variant(), "Object is locked and can't be freed.");
  753. }
  754. #endif
  755. //must be here, must be before everything,
  756. memdelete(this);
  757. r_error.error = Callable::CallError::CALL_OK;
  758. return Variant();
  759. }
  760. Variant ret;
  761. OBJ_DEBUG_LOCK
  762. if (script_instance) {
  763. ret = script_instance->callp(p_method, p_args, p_argcount, r_error);
  764. // Force jump table.
  765. switch (r_error.error) {
  766. case Callable::CallError::CALL_OK:
  767. return ret;
  768. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  769. break;
  770. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  771. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  772. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  773. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  774. return ret;
  775. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  776. }
  777. }
  778. }
  779. //extension does not need this, because all methods are registered in MethodBind
  780. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  781. if (method) {
  782. ret = method->call(this, p_args, p_argcount, r_error);
  783. } else {
  784. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  785. }
  786. return ret;
  787. }
  788. Variant Object::call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  789. r_error.error = Callable::CallError::CALL_OK;
  790. if (p_method == CoreStringName(free_)) {
  791. // Free is not const, so fail.
  792. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  793. return Variant();
  794. }
  795. Variant ret;
  796. OBJ_DEBUG_LOCK
  797. if (script_instance) {
  798. ret = script_instance->call_const(p_method, p_args, p_argcount, r_error);
  799. //force jumptable
  800. switch (r_error.error) {
  801. case Callable::CallError::CALL_OK:
  802. return ret;
  803. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  804. break;
  805. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  806. break;
  807. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  808. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  809. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  810. return ret;
  811. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  812. }
  813. }
  814. }
  815. //extension does not need this, because all methods are registered in MethodBind
  816. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  817. if (method) {
  818. if (!method->is_const()) {
  819. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  820. return ret;
  821. }
  822. ret = method->call(this, p_args, p_argcount, r_error);
  823. } else {
  824. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  825. }
  826. return ret;
  827. }
  828. void Object::_gdvirtual_init_method_ptr(uint32_t p_compat_hash, void *&r_fn_ptr, const StringName &p_fn_name, bool p_compat) const {
  829. r_fn_ptr = nullptr;
  830. if (_extension->get_virtual_call_data2 && _extension->call_virtual_with_data) {
  831. r_fn_ptr = _extension->get_virtual_call_data2(_extension->class_userdata, &p_fn_name, p_compat_hash);
  832. } else if (_extension->get_virtual2) {
  833. r_fn_ptr = (void *)_extension->get_virtual2(_extension->class_userdata, &p_fn_name, p_compat_hash);
  834. #ifndef DISABLE_DEPRECATED
  835. } else if (p_compat || ClassDB::get_virtual_method_compatibility_hashes(get_class_name(), p_fn_name).size() == 0) {
  836. if (_extension->get_virtual_call_data && _extension->call_virtual_with_data) {
  837. r_fn_ptr = _extension->get_virtual_call_data(_extension->class_userdata, &p_fn_name);
  838. } else if (_extension->get_virtual) {
  839. r_fn_ptr = (void *)_extension->get_virtual(_extension->class_userdata, &p_fn_name);
  840. }
  841. #endif
  842. }
  843. #ifdef TOOLS_ENABLED
  844. if (_extension->reloadable) {
  845. VirtualMethodTracker *tracker = memnew(VirtualMethodTracker);
  846. tracker->method = (void **)&r_fn_ptr;
  847. tracker->next = virtual_method_list;
  848. virtual_method_list = tracker;
  849. }
  850. #endif
  851. if (r_fn_ptr == nullptr) {
  852. r_fn_ptr = reinterpret_cast<void *>(_INVALID_GDVIRTUAL_FUNC_ADDR);
  853. }
  854. }
  855. void Object::_notification_forward(int p_notification) {
  856. // Notify classes starting with Object and ending with most derived subclass.
  857. // e.g. Object -> Node -> Node3D
  858. _notification_forwardv(p_notification);
  859. if (_extension) {
  860. if (_extension->notification2) {
  861. _extension->notification2(_extension_instance, p_notification, static_cast<GDExtensionBool>(false));
  862. #ifndef DISABLE_DEPRECATED
  863. } else if (_extension->notification) {
  864. _extension->notification(_extension_instance, p_notification);
  865. #endif // DISABLE_DEPRECATED
  866. }
  867. }
  868. if (script_instance) {
  869. script_instance->notification(p_notification, false);
  870. }
  871. }
  872. void Object::_notification_backward(int p_notification) {
  873. if (script_instance) {
  874. script_instance->notification(p_notification, true);
  875. }
  876. if (_extension) {
  877. if (_extension->notification2) {
  878. _extension->notification2(_extension_instance, p_notification, static_cast<GDExtensionBool>(true));
  879. #ifndef DISABLE_DEPRECATED
  880. } else if (_extension->notification) {
  881. _extension->notification(_extension_instance, p_notification);
  882. #endif // DISABLE_DEPRECATED
  883. }
  884. }
  885. // Notify classes starting with most derived subclass and ending in Object.
  886. // e.g. Node3D -> Node -> Object
  887. _notification_backwardv(p_notification);
  888. }
  889. String Object::to_string() {
  890. // Keep this method in sync with `Node::to_string`.
  891. if (script_instance) {
  892. bool valid;
  893. String ret = script_instance->to_string(&valid);
  894. if (valid) {
  895. return ret;
  896. }
  897. }
  898. if (_extension && _extension->to_string) {
  899. String ret;
  900. GDExtensionBool is_valid;
  901. _extension->to_string(_extension_instance, &is_valid, &ret);
  902. if (is_valid) {
  903. return ret;
  904. }
  905. }
  906. return _to_string();
  907. }
  908. void Object::set_script(const Variant &p_script) {
  909. if (get_script() == p_script) {
  910. return;
  911. }
  912. Ref<Script> s = p_script;
  913. if (!p_script.is_null()) {
  914. ERR_FAIL_COND_MSG(s.is_null(), "Cannot set object script. Parameter should be null or a reference to a valid script.");
  915. ERR_FAIL_COND_MSG(s->is_abstract(), vformat("Cannot set object script. Script '%s' should not be abstract.", s->get_path()));
  916. }
  917. if (script_instance) {
  918. memdelete(script_instance);
  919. script_instance = nullptr;
  920. }
  921. if (s.is_valid()) {
  922. if (s->can_instantiate()) {
  923. OBJ_DEBUG_LOCK
  924. script_instance = s->instance_create(this);
  925. } else if (Engine::get_singleton()->is_editor_hint()) {
  926. OBJ_DEBUG_LOCK
  927. script_instance = s->placeholder_instance_create(this);
  928. }
  929. }
  930. notify_property_list_changed(); //scripts may add variables, so refresh is desired
  931. emit_signal(CoreStringName(script_changed));
  932. }
  933. void Object::set_script_instance(ScriptInstance *p_instance) {
  934. if (script_instance == p_instance) {
  935. return;
  936. }
  937. if (script_instance) {
  938. memdelete(script_instance);
  939. }
  940. script_instance = p_instance;
  941. }
  942. Variant Object::get_script() const {
  943. return script_instance ? Variant(script_instance->get_script()) : Variant();
  944. }
  945. bool Object::has_meta(const StringName &p_name) const {
  946. return metadata.has(p_name);
  947. }
  948. void Object::set_meta(const StringName &p_name, const Variant &p_value) {
  949. if (p_value.get_type() == Variant::NIL) {
  950. if (metadata.has(p_name)) {
  951. metadata.erase(p_name);
  952. const String &sname = p_name;
  953. metadata_properties.erase("metadata/" + sname);
  954. if (!sname.begins_with("_")) {
  955. // Metadata starting with _ don't show up in the inspector, so no need to update.
  956. notify_property_list_changed();
  957. }
  958. }
  959. return;
  960. }
  961. HashMap<StringName, Variant>::Iterator E = metadata.find(p_name);
  962. if (E) {
  963. E->value = p_value;
  964. } else {
  965. ERR_FAIL_COND_MSG(!p_name.operator String().is_valid_ascii_identifier(), vformat("Invalid metadata identifier: '%s'.", p_name));
  966. Variant *V = &metadata.insert(p_name, p_value)->value;
  967. const String &sname = p_name;
  968. metadata_properties["metadata/" + sname] = V;
  969. if (!sname.begins_with("_")) {
  970. notify_property_list_changed();
  971. }
  972. }
  973. }
  974. Variant Object::get_meta(const StringName &p_name, const Variant &p_default) const {
  975. if (!metadata.has(p_name)) {
  976. if (p_default != Variant()) {
  977. return p_default;
  978. } else {
  979. ERR_FAIL_V_MSG(Variant(), vformat("The object does not have any 'meta' values with the key '%s'.", p_name));
  980. }
  981. }
  982. return metadata[p_name];
  983. }
  984. void Object::remove_meta(const StringName &p_name) {
  985. set_meta(p_name, Variant());
  986. }
  987. void Object::merge_meta_from(const Object *p_src) {
  988. List<StringName> meta_keys;
  989. p_src->get_meta_list(&meta_keys);
  990. for (const StringName &key : meta_keys) {
  991. set_meta(key, p_src->get_meta(key));
  992. }
  993. }
  994. TypedArray<Dictionary> Object::_get_property_list_bind() const {
  995. List<PropertyInfo> lpi;
  996. get_property_list(&lpi);
  997. return convert_property_list(&lpi);
  998. }
  999. TypedArray<Dictionary> Object::_get_method_list_bind() const {
  1000. List<MethodInfo> ml;
  1001. get_method_list(&ml);
  1002. TypedArray<Dictionary> ret;
  1003. for (const MethodInfo &mi : ml) {
  1004. Dictionary d = mi;
  1005. //va.push_back(d);
  1006. ret.push_back(d);
  1007. }
  1008. return ret;
  1009. }
  1010. TypedArray<StringName> Object::_get_meta_list_bind() const {
  1011. TypedArray<StringName> _metaret;
  1012. for (const KeyValue<StringName, Variant> &K : metadata) {
  1013. _metaret.push_back(K.key);
  1014. }
  1015. return _metaret;
  1016. }
  1017. void Object::get_meta_list(List<StringName> *p_list) const {
  1018. for (const KeyValue<StringName, Variant> &K : metadata) {
  1019. p_list->push_back(K.key);
  1020. }
  1021. }
  1022. void Object::add_user_signal(const MethodInfo &p_signal) {
  1023. ERR_FAIL_COND_MSG(p_signal.name.is_empty(), "Signal name cannot be empty.");
  1024. ERR_FAIL_COND_MSG(ClassDB::has_signal(get_class_name(), p_signal.name), vformat("User signal's name conflicts with a built-in signal of '%s'.", get_class_name()));
  1025. OBJ_SIGNAL_LOCK
  1026. ERR_FAIL_COND_MSG(signal_map.has(p_signal.name), vformat("Trying to add already existing signal '%s'.", p_signal.name));
  1027. SignalData s;
  1028. s.user = p_signal;
  1029. signal_map[p_signal.name] = s;
  1030. }
  1031. bool Object::_has_user_signal(const StringName &p_name) const {
  1032. OBJ_SIGNAL_LOCK
  1033. if (!signal_map.has(p_name)) {
  1034. return false;
  1035. }
  1036. return signal_map[p_name].user.name.length() > 0;
  1037. }
  1038. void Object::_remove_user_signal(const StringName &p_name) {
  1039. OBJ_SIGNAL_LOCK
  1040. SignalData *s = signal_map.getptr(p_name);
  1041. ERR_FAIL_NULL_MSG(s, "Provided signal does not exist.");
  1042. ERR_FAIL_COND_MSG(!s->removable, "Signal is not removable (not added with add_user_signal).");
  1043. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1044. Object *target = slot_kv.key.get_object();
  1045. if (likely(target)) {
  1046. target->connections.erase(slot_kv.value.cE);
  1047. }
  1048. }
  1049. signal_map.erase(p_name);
  1050. }
  1051. Error Object::_emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1052. if (unlikely(p_argcount < 1)) {
  1053. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  1054. r_error.expected = 1;
  1055. ERR_FAIL_V(Error::ERR_INVALID_PARAMETER);
  1056. }
  1057. if (unlikely(!p_args[0]->is_string())) {
  1058. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  1059. r_error.argument = 0;
  1060. r_error.expected = Variant::STRING_NAME;
  1061. ERR_FAIL_V(Error::ERR_INVALID_PARAMETER);
  1062. }
  1063. r_error.error = Callable::CallError::CALL_OK;
  1064. StringName signal = *p_args[0];
  1065. const Variant **args = nullptr;
  1066. int argc = p_argcount - 1;
  1067. if (argc) {
  1068. args = &p_args[1];
  1069. }
  1070. return emit_signalp(signal, args, argc);
  1071. }
  1072. Error Object::emit_signalp(const StringName &p_name, const Variant **p_args, int p_argcount) {
  1073. if (_block_signals) {
  1074. return ERR_CANT_ACQUIRE_RESOURCE; //no emit, signals blocked
  1075. }
  1076. constexpr int MAX_SLOTS_ON_STACK = 5;
  1077. // Don't default initialize the Callable objects on the stack, just reserve the space - we'll memnew_placement() them later.
  1078. alignas(Callable) uint8_t slot_callable_stack[sizeof(Callable) * MAX_SLOTS_ON_STACK];
  1079. uint32_t slot_flags_stack[MAX_SLOTS_ON_STACK];
  1080. Callable *slot_callables = (Callable *)slot_callable_stack;
  1081. uint32_t *slot_flags = slot_flags_stack;
  1082. uint32_t slot_count = 0;
  1083. {
  1084. OBJ_SIGNAL_LOCK
  1085. SignalData *s = signal_map.getptr(p_name);
  1086. if (!s) {
  1087. #ifdef DEBUG_ENABLED
  1088. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
  1089. //check in script
  1090. ERR_FAIL_COND_V_MSG(!signal_is_valid && script_instance && !script_instance->get_script()->has_script_signal(p_name), ERR_UNAVAILABLE, vformat("Can't emit non-existing signal \"%s\".", p_name));
  1091. #endif
  1092. //not connected? just return
  1093. return ERR_UNAVAILABLE;
  1094. }
  1095. if (s->slot_map.size() > MAX_SLOTS_ON_STACK) {
  1096. slot_callables = (Callable *)memalloc(sizeof(Callable) * s->slot_map.size());
  1097. slot_flags = (uint32_t *)memalloc(sizeof(uint32_t) * s->slot_map.size());
  1098. }
  1099. // Ensure that disconnecting the signal or even deleting the object
  1100. // will not affect the signal calling.
  1101. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1102. memnew_placement(&slot_callables[slot_count], Callable(slot_kv.value.conn.callable));
  1103. slot_flags[slot_count] = slot_kv.value.conn.flags;
  1104. ++slot_count;
  1105. }
  1106. DEV_ASSERT(slot_count == s->slot_map.size());
  1107. // Disconnect all one-shot connections before emitting to prevent recursion.
  1108. for (uint32_t i = 0; i < slot_count; ++i) {
  1109. bool disconnect = slot_flags[i] & CONNECT_ONE_SHOT;
  1110. #ifdef TOOLS_ENABLED
  1111. if (disconnect && (slot_flags[i] & CONNECT_PERSIST) && Engine::get_singleton()->is_editor_hint()) {
  1112. // This signal was connected from the editor, and is being edited. Just don't disconnect for now.
  1113. disconnect = false;
  1114. }
  1115. #endif
  1116. if (disconnect) {
  1117. _disconnect(p_name, slot_callables[i]);
  1118. }
  1119. }
  1120. }
  1121. OBJ_DEBUG_LOCK
  1122. // If this is a ref-counted object, prevent it from being destroyed during signal
  1123. // emission, which is needed in certain edge cases; e.g., GH-73889 and GH-109471.
  1124. // Moreover, since signals can be emitted from constructors (classic example being
  1125. // notify_property_list_changed), we must be careful not to do the ref init ourselves,
  1126. // which would lead to the object being destroyed at the end of this function.
  1127. bool pending_unref = Object::cast_to<RefCounted>(this) ? ((RefCounted *)this)->reference() : false;
  1128. Error err = OK;
  1129. Vector<const Variant *> append_source_mem;
  1130. Variant source = this;
  1131. for (uint32_t i = 0; i < slot_count; ++i) {
  1132. const Callable &callable = slot_callables[i];
  1133. const uint32_t &flags = slot_flags[i];
  1134. if (!callable.is_valid()) {
  1135. // Target might have been deleted during signal callback, this is expected and OK.
  1136. continue;
  1137. }
  1138. const Variant **args = p_args;
  1139. int argc = p_argcount;
  1140. if (flags & CONNECT_APPEND_SOURCE_OBJECT) {
  1141. // Source is being appended regardless of unbinds.
  1142. // Implemented by inserting before the first to-be-unbinded arg.
  1143. int source_index = p_argcount - callable.get_unbound_arguments_count();
  1144. if (source_index >= 0) {
  1145. append_source_mem.resize(p_argcount + 1);
  1146. const Variant **args_mem = append_source_mem.ptrw();
  1147. for (int j = 0; j < source_index; j++) {
  1148. args_mem[j] = p_args[j];
  1149. }
  1150. args_mem[source_index] = &source;
  1151. for (int j = source_index; j < p_argcount; j++) {
  1152. args_mem[j + 1] = p_args[j];
  1153. }
  1154. args = args_mem;
  1155. argc = p_argcount + 1;
  1156. } else {
  1157. // More args unbound than provided, call will fail.
  1158. // Since appended source is non-unbindable, the error
  1159. // about too many unbinds should be correct as is.
  1160. }
  1161. }
  1162. if (flags & CONNECT_DEFERRED) {
  1163. MessageQueue::get_singleton()->push_callablep(callable, args, argc, true);
  1164. } else {
  1165. Callable::CallError ce;
  1166. _emitting = true;
  1167. Variant ret;
  1168. callable.callp(args, argc, ret, ce);
  1169. _emitting = false;
  1170. if (ce.error != Callable::CallError::CALL_OK) {
  1171. Object *target = callable.get_object();
  1172. #ifdef DEBUG_ENABLED
  1173. if (target && flags & CONNECT_PERSIST && Engine::get_singleton()->is_editor_hint()) {
  1174. Ref<Script> other_scr = target->get_script();
  1175. if (other_scr.is_valid() && !other_scr->is_tool()) {
  1176. // Trying to call not-tool method in editor, just ignore it.
  1177. continue;
  1178. }
  1179. }
  1180. #endif
  1181. if (ce.error == Callable::CallError::CALL_ERROR_INVALID_METHOD && target && !ClassDB::class_exists(target->get_class_name())) {
  1182. // Most likely object is not initialized yet, do not throw error.
  1183. } else {
  1184. ERR_PRINT(vformat("Error calling from signal '%s' to callable: %s.", String(p_name), Variant::get_callable_error_text(callable, args, argc, ce)));
  1185. err = ERR_METHOD_NOT_FOUND;
  1186. }
  1187. }
  1188. }
  1189. }
  1190. for (uint32_t i = 0; i < slot_count; ++i) {
  1191. slot_callables[i].~Callable();
  1192. }
  1193. if (slot_callables != (Callable *)slot_callable_stack) {
  1194. memfree(slot_callables);
  1195. memfree(slot_flags);
  1196. }
  1197. if (pending_unref) {
  1198. // We have to do the same Ref<T> would do. We can't just use Ref<T>
  1199. // because it would do the init ref logic, which is something this function
  1200. // shouldn't do, as explained above.
  1201. if (((RefCounted *)this)->unreference()) {
  1202. memdelete(this);
  1203. }
  1204. }
  1205. return err;
  1206. }
  1207. void Object::_reset_gdtype() const {
  1208. if (_extension) {
  1209. // Set to extension's type.
  1210. _gdtype_ptr = _extension->gdtype;
  1211. } else {
  1212. // Reset to internal type.
  1213. _gdtype_ptr = &_get_typev();
  1214. }
  1215. }
  1216. void Object::_add_user_signal(const String &p_name, const Array &p_args) {
  1217. // this version of add_user_signal is meant to be used from scripts or external apis
  1218. // without access to ADD_SIGNAL in bind_methods
  1219. // added events are per instance, as opposed to the other ones, which are global
  1220. OBJ_SIGNAL_LOCK
  1221. MethodInfo mi;
  1222. mi.name = p_name;
  1223. for (const Variant &arg : p_args) {
  1224. Dictionary d = arg;
  1225. PropertyInfo param;
  1226. if (d.has("name")) {
  1227. param.name = d["name"];
  1228. }
  1229. if (d.has("type")) {
  1230. param.type = (Variant::Type)(int)d["type"];
  1231. }
  1232. mi.arguments.push_back(param);
  1233. }
  1234. add_user_signal(mi);
  1235. if (signal_map.has(p_name)) {
  1236. signal_map.getptr(p_name)->removable = true;
  1237. }
  1238. }
  1239. TypedArray<Dictionary> Object::_get_signal_list() const {
  1240. List<MethodInfo> signal_list;
  1241. get_signal_list(&signal_list);
  1242. TypedArray<Dictionary> ret;
  1243. for (const MethodInfo &E : signal_list) {
  1244. ret.push_back(Dictionary(E));
  1245. }
  1246. return ret;
  1247. }
  1248. TypedArray<Dictionary> Object::_get_signal_connection_list(const StringName &p_signal) const {
  1249. List<Connection> conns;
  1250. get_all_signal_connections(&conns);
  1251. TypedArray<Dictionary> ret;
  1252. for (const Connection &c : conns) {
  1253. if (c.signal.get_name() == p_signal) {
  1254. ret.push_back(c);
  1255. }
  1256. }
  1257. return ret;
  1258. }
  1259. TypedArray<Dictionary> Object::_get_incoming_connections() const {
  1260. TypedArray<Dictionary> ret;
  1261. for (const Object::Connection &connection : connections) {
  1262. ret.push_back(connection);
  1263. }
  1264. return ret;
  1265. }
  1266. bool Object::has_signal(const StringName &p_name) const {
  1267. if (script_instance && script_instance->get_script()->has_script_signal(p_name)) {
  1268. return true;
  1269. }
  1270. if (ClassDB::has_signal(get_class_name(), p_name)) {
  1271. return true;
  1272. }
  1273. if (_has_user_signal(p_name)) {
  1274. return true;
  1275. }
  1276. return false;
  1277. }
  1278. void Object::get_signal_list(List<MethodInfo> *p_signals) const {
  1279. OBJ_SIGNAL_LOCK
  1280. if (script_instance) {
  1281. script_instance->get_script()->get_script_signal_list(p_signals);
  1282. }
  1283. ClassDB::get_signal_list(get_class_name(), p_signals);
  1284. //find maybe usersignals?
  1285. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1286. if (!E.value.user.name.is_empty()) {
  1287. //user signal
  1288. p_signals->push_back(E.value.user);
  1289. }
  1290. }
  1291. }
  1292. void Object::get_all_signal_connections(List<Connection> *p_connections) const {
  1293. OBJ_SIGNAL_LOCK
  1294. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1295. const SignalData *s = &E.value;
  1296. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1297. p_connections->push_back(slot_kv.value.conn);
  1298. }
  1299. }
  1300. }
  1301. void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const {
  1302. OBJ_SIGNAL_LOCK
  1303. const SignalData *s = signal_map.getptr(p_signal);
  1304. if (!s) {
  1305. return; //nothing
  1306. }
  1307. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1308. p_connections->push_back(slot_kv.value.conn);
  1309. }
  1310. }
  1311. int Object::get_persistent_signal_connection_count() const {
  1312. OBJ_SIGNAL_LOCK
  1313. int count = 0;
  1314. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1315. const SignalData *s = &E.value;
  1316. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1317. if (slot_kv.value.conn.flags & CONNECT_PERSIST) {
  1318. count += 1;
  1319. }
  1320. }
  1321. }
  1322. return count;
  1323. }
  1324. uint32_t Object::get_signal_connection_flags(const StringName &p_name, const Callable &p_callable) const {
  1325. OBJ_SIGNAL_LOCK
  1326. const SignalData *signal_data = signal_map.getptr(p_name);
  1327. if (signal_data) {
  1328. const SignalData::Slot *slot = signal_data->slot_map.getptr(p_callable);
  1329. if (slot) {
  1330. return slot->conn.flags;
  1331. }
  1332. }
  1333. return 0;
  1334. }
  1335. void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
  1336. OBJ_SIGNAL_LOCK
  1337. for (const Connection &E : connections) {
  1338. p_connections->push_back(E);
  1339. }
  1340. }
  1341. Error Object::connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags) {
  1342. ERR_FAIL_COND_V_MSG(p_callable.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot connect to '%s': the provided callable is null.", p_signal));
  1343. OBJ_SIGNAL_LOCK
  1344. if (p_callable.is_standard()) {
  1345. // FIXME: This branch should probably removed in favor of the `is_valid()` branch, but there exist some classes
  1346. // that call `connect()` before they are fully registered with ClassDB. Until all such classes can be found
  1347. // and registered soon enough this branch is needed to allow `connect()` to succeed.
  1348. ERR_FAIL_NULL_V_MSG(p_callable.get_object(), ERR_INVALID_PARAMETER, vformat("Cannot connect to '%s' to callable '%s': the callable object is null.", p_signal, p_callable));
  1349. } else {
  1350. ERR_FAIL_COND_V_MSG(!p_callable.is_valid(), ERR_INVALID_PARAMETER, vformat("Cannot connect to '%s': the provided callable is not valid: '%s'.", p_signal, p_callable));
  1351. }
  1352. SignalData *s = signal_map.getptr(p_signal);
  1353. if (!s) {
  1354. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1355. //check in script
  1356. if (!signal_is_valid && script_instance) {
  1357. if (script_instance->get_script()->has_script_signal(p_signal)) {
  1358. signal_is_valid = true;
  1359. }
  1360. #ifdef TOOLS_ENABLED
  1361. else {
  1362. //allow connecting signals anyway if script is invalid, see issue #17070
  1363. if (!script_instance->get_script()->is_valid()) {
  1364. signal_is_valid = true;
  1365. }
  1366. }
  1367. #endif
  1368. }
  1369. ERR_FAIL_COND_V_MSG(!signal_is_valid, ERR_INVALID_PARAMETER, vformat("In Object of type '%s': Attempt to connect nonexistent signal '%s' to callable '%s'.", String(get_class()), p_signal, p_callable));
  1370. signal_map[p_signal] = SignalData();
  1371. s = &signal_map[p_signal];
  1372. }
  1373. //compare with the base callable, so binds can be ignored
  1374. if (s->slot_map.has(*p_callable.get_base_comparator())) {
  1375. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1376. s->slot_map[*p_callable.get_base_comparator()].reference_count++;
  1377. return OK;
  1378. } else {
  1379. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("Signal '%s' is already connected to given callable '%s' in that object.", p_signal, p_callable));
  1380. }
  1381. }
  1382. Object *target_object = p_callable.get_object();
  1383. SignalData::Slot slot;
  1384. Connection conn;
  1385. conn.callable = p_callable;
  1386. conn.signal = ::Signal(this, p_signal);
  1387. conn.flags = p_flags;
  1388. slot.conn = conn;
  1389. if (target_object) {
  1390. slot.cE = target_object->connections.push_back(conn);
  1391. }
  1392. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1393. slot.reference_count = 1;
  1394. }
  1395. //use callable version as key, so binds can be ignored
  1396. s->slot_map[*p_callable.get_base_comparator()] = slot;
  1397. return OK;
  1398. }
  1399. bool Object::is_connected(const StringName &p_signal, const Callable &p_callable) const {
  1400. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, vformat("Cannot determine if connected to '%s': the provided callable is null.", p_signal)); // Should use `is_null`, see note in `connect` about the use of `is_valid`.
  1401. OBJ_SIGNAL_LOCK
  1402. const SignalData *s = signal_map.getptr(p_signal);
  1403. if (!s) {
  1404. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1405. if (signal_is_valid) {
  1406. return false;
  1407. }
  1408. if (script_instance && script_instance->get_script()->has_script_signal(p_signal)) {
  1409. return false;
  1410. }
  1411. ERR_FAIL_V_MSG(false, vformat("Nonexistent signal: '%s'.", p_signal));
  1412. }
  1413. return s->slot_map.has(*p_callable.get_base_comparator());
  1414. }
  1415. bool Object::has_connections(const StringName &p_signal) const {
  1416. OBJ_SIGNAL_LOCK
  1417. const SignalData *s = signal_map.getptr(p_signal);
  1418. if (!s) {
  1419. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1420. if (signal_is_valid) {
  1421. return false;
  1422. }
  1423. if (script_instance && script_instance->get_script()->has_script_signal(p_signal)) {
  1424. return false;
  1425. }
  1426. ERR_FAIL_V_MSG(false, vformat("Nonexistent signal: '%s'.", p_signal));
  1427. }
  1428. return !s->slot_map.is_empty();
  1429. }
  1430. void Object::disconnect(const StringName &p_signal, const Callable &p_callable) {
  1431. _disconnect(p_signal, p_callable);
  1432. }
  1433. bool Object::_disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force) {
  1434. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, vformat("Cannot disconnect from '%s': the provided callable is null.", p_signal)); // Should use `is_null`, see note in `connect` about the use of `is_valid`.
  1435. OBJ_SIGNAL_LOCK
  1436. SignalData *s = signal_map.getptr(p_signal);
  1437. if (!s) {
  1438. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal) ||
  1439. (script_instance && script_instance->get_script()->has_script_signal(p_signal));
  1440. ERR_FAIL_COND_V_MSG(signal_is_valid, false, vformat("Attempt to disconnect a nonexistent connection from '%s'. Signal: '%s', callable: '%s'.", to_string(), p_signal, p_callable));
  1441. }
  1442. ERR_FAIL_NULL_V_MSG(s, false, vformat("Disconnecting nonexistent signal '%s' in '%s'.", p_signal, to_string()));
  1443. ERR_FAIL_COND_V_MSG(!s->slot_map.has(*p_callable.get_base_comparator()), false, vformat("Attempt to disconnect a nonexistent connection from '%s'. Signal: '%s', callable: '%s'.", to_string(), p_signal, p_callable));
  1444. SignalData::Slot *slot = &s->slot_map[*p_callable.get_base_comparator()];
  1445. if (!p_force) {
  1446. slot->reference_count--; // by default is zero, if it was not referenced it will go below it
  1447. if (slot->reference_count > 0) {
  1448. return false;
  1449. }
  1450. }
  1451. if (slot->cE) {
  1452. Object *target_object = p_callable.get_object();
  1453. if (target_object) {
  1454. target_object->connections.erase(slot->cE);
  1455. }
  1456. }
  1457. s->slot_map.erase(*p_callable.get_base_comparator());
  1458. if (s->slot_map.is_empty() && ClassDB::has_signal(get_class_name(), p_signal)) {
  1459. //not user signal, delete
  1460. signal_map.erase(p_signal);
  1461. }
  1462. return true;
  1463. }
  1464. bool Object::_uses_signal_mutex() const {
  1465. return true;
  1466. }
  1467. String Object::_get_locale() const {
  1468. TranslationServer *ts = TranslationServer::get_singleton();
  1469. const StringName domain_name = get_translation_domain();
  1470. if (ts->has_domain(domain_name)) {
  1471. const Ref<TranslationDomain> domain = ts->get_or_add_domain(domain_name);
  1472. const String &overridden = domain->get_locale_override();
  1473. if (!overridden.is_empty()) {
  1474. return overridden;
  1475. }
  1476. }
  1477. return ts->get_locale();
  1478. }
  1479. void Object::_set_bind(const StringName &p_set, const Variant &p_value) {
  1480. set(p_set, p_value);
  1481. }
  1482. Variant Object::_get_bind(const StringName &p_name) const {
  1483. return get(p_name);
  1484. }
  1485. void Object::_set_indexed_bind(const NodePath &p_name, const Variant &p_value) {
  1486. set_indexed(p_name.get_as_property_path().get_subnames(), p_value);
  1487. }
  1488. Variant Object::_get_indexed_bind(const NodePath &p_name) const {
  1489. return get_indexed(p_name.get_as_property_path().get_subnames());
  1490. }
  1491. void Object::initialize_class() {
  1492. static bool initialized = false;
  1493. if (initialized) {
  1494. return;
  1495. }
  1496. _add_class_to_classdb(get_gdtype_static(), nullptr);
  1497. _bind_methods();
  1498. _bind_compatibility_methods();
  1499. initialized = true;
  1500. }
  1501. StringName Object::get_translation_domain() const {
  1502. return _translation_domain;
  1503. }
  1504. void Object::set_translation_domain(const StringName &p_domain) {
  1505. _translation_domain = p_domain;
  1506. }
  1507. String Object::tr(const StringName &p_message, const StringName &p_context) const {
  1508. if (!_can_translate || !TranslationServer::get_singleton()) {
  1509. return p_message;
  1510. }
  1511. const Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_or_add_domain(get_translation_domain());
  1512. return domain->translate(p_message, p_context);
  1513. }
  1514. String Object::tr_n(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  1515. if (!_can_translate || !TranslationServer::get_singleton()) {
  1516. // Return message based on English plural rule if translation is not possible.
  1517. if (p_n == 1) {
  1518. return p_message;
  1519. }
  1520. return p_message_plural;
  1521. }
  1522. const Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_or_add_domain(get_translation_domain());
  1523. return domain->translate_plural(p_message, p_message_plural, p_n, p_context);
  1524. }
  1525. void Object::_clear_internal_resource_paths(const Variant &p_var) {
  1526. switch (p_var.get_type()) {
  1527. case Variant::OBJECT: {
  1528. Ref<Resource> r = p_var;
  1529. if (r.is_null()) {
  1530. return;
  1531. }
  1532. if (!r->is_built_in()) {
  1533. return; //not an internal resource
  1534. }
  1535. Object *object = p_var;
  1536. if (!object) {
  1537. return;
  1538. }
  1539. r->set_path("");
  1540. r->clear_internal_resource_paths();
  1541. } break;
  1542. case Variant::ARRAY: {
  1543. Array a = p_var;
  1544. for (const Variant &var : a) {
  1545. _clear_internal_resource_paths(var);
  1546. }
  1547. } break;
  1548. case Variant::DICTIONARY: {
  1549. Dictionary d = p_var;
  1550. for (const KeyValue<Variant, Variant> &kv : d) {
  1551. _clear_internal_resource_paths(kv.key);
  1552. _clear_internal_resource_paths(kv.value);
  1553. }
  1554. } break;
  1555. default: {
  1556. }
  1557. }
  1558. }
  1559. void Object::_add_class_to_classdb(const GDType &p_type, const GDType *p_inherits) {
  1560. ClassDB::_add_class(p_type, p_inherits);
  1561. }
  1562. void Object::_get_property_list_from_classdb(const StringName &p_class, List<PropertyInfo> *p_list, bool p_no_inheritance, const Object *p_validator) {
  1563. ClassDB::get_property_list(p_class, p_list, p_no_inheritance, p_validator);
  1564. }
  1565. #ifdef TOOLS_ENABLED
  1566. void Object::editor_set_section_unfold(const String &p_section, bool p_unfolded, bool p_initializing) {
  1567. if (!p_initializing) {
  1568. set_edited(true);
  1569. }
  1570. if (p_unfolded) {
  1571. editor_section_folding.insert(p_section);
  1572. } else {
  1573. editor_section_folding.erase(p_section);
  1574. }
  1575. }
  1576. bool Object::editor_is_section_unfolded(const String &p_section) {
  1577. return editor_section_folding.has(p_section);
  1578. }
  1579. #endif
  1580. void Object::clear_internal_resource_paths() {
  1581. List<PropertyInfo> pinfo;
  1582. get_property_list(&pinfo);
  1583. for (const PropertyInfo &E : pinfo) {
  1584. _clear_internal_resource_paths(get(E.name));
  1585. }
  1586. }
  1587. void Object::notify_property_list_changed() {
  1588. emit_signal(CoreStringName(property_list_changed));
  1589. }
  1590. String Object::_to_string() {
  1591. return "<" + get_class() + "#" + itos(get_instance_id()) + ">";
  1592. }
  1593. void Object::_bind_methods() {
  1594. ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class);
  1595. ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class);
  1596. ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
  1597. ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
  1598. ClassDB::bind_method(D_METHOD("set_indexed", "property_path", "value"), &Object::_set_indexed_bind);
  1599. ClassDB::bind_method(D_METHOD("get_indexed", "property_path"), &Object::_get_indexed_bind);
  1600. ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
  1601. ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
  1602. ClassDB::bind_method(D_METHOD("property_can_revert", "property"), &Object::property_can_revert);
  1603. ClassDB::bind_method(D_METHOD("property_get_revert", "property"), &Object::property_get_revert);
  1604. ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
  1605. ClassDB::bind_method(D_METHOD("to_string"), &Object::to_string);
  1606. ClassDB::bind_method(D_METHOD("get_instance_id"), &Object::get_instance_id);
  1607. ClassDB::bind_method(D_METHOD("set_script", "script"), &Object::set_script);
  1608. ClassDB::bind_method(D_METHOD("get_script"), &Object::get_script);
  1609. ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta);
  1610. ClassDB::bind_method(D_METHOD("remove_meta", "name"), &Object::remove_meta);
  1611. ClassDB::bind_method(D_METHOD("get_meta", "name", "default"), &Object::get_meta, DEFVAL(Variant()));
  1612. ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta);
  1613. ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind);
  1614. ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array()));
  1615. ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal);
  1616. ClassDB::bind_method(D_METHOD("remove_user_signal", "signal"), &Object::_remove_user_signal);
  1617. {
  1618. MethodInfo mi;
  1619. mi.name = "emit_signal";
  1620. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "signal"));
  1621. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi, varray(), false);
  1622. }
  1623. {
  1624. MethodInfo mi;
  1625. mi.name = "call";
  1626. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1627. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call", &Object::_call_bind, mi);
  1628. }
  1629. {
  1630. MethodInfo mi;
  1631. mi.name = "call_deferred";
  1632. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1633. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi, varray(), false);
  1634. }
  1635. ClassDB::bind_method(D_METHOD("set_deferred", "property", "value"), &Object::set_deferred);
  1636. ClassDB::bind_method(D_METHOD("callv", "method", "arg_array"), &Object::callv);
  1637. ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method);
  1638. ClassDB::bind_method(D_METHOD("get_method_argument_count", "method"), &Object::_get_method_argument_count_bind);
  1639. ClassDB::bind_method(D_METHOD("has_signal", "signal"), &Object::has_signal);
  1640. ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list);
  1641. ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list);
  1642. ClassDB::bind_method(D_METHOD("get_incoming_connections"), &Object::_get_incoming_connections);
  1643. ClassDB::bind_method(D_METHOD("connect", "signal", "callable", "flags"), &Object::connect, DEFVAL(0));
  1644. ClassDB::bind_method(D_METHOD("disconnect", "signal", "callable"), &Object::disconnect);
  1645. ClassDB::bind_method(D_METHOD("is_connected", "signal", "callable"), &Object::is_connected);
  1646. ClassDB::bind_method(D_METHOD("has_connections", "signal"), &Object::has_connections);
  1647. ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals);
  1648. ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals);
  1649. ClassDB::bind_method(D_METHOD("notify_property_list_changed"), &Object::notify_property_list_changed);
  1650. ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation);
  1651. ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages);
  1652. ClassDB::bind_method(D_METHOD("tr", "message", "context"), &Object::tr, DEFVAL(StringName()));
  1653. ClassDB::bind_method(D_METHOD("tr_n", "message", "plural_message", "n", "context"), &Object::tr_n, DEFVAL(StringName()));
  1654. ClassDB::bind_method(D_METHOD("get_translation_domain"), &Object::get_translation_domain);
  1655. ClassDB::bind_method(D_METHOD("set_translation_domain", "domain"), &Object::set_translation_domain);
  1656. ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion);
  1657. ClassDB::bind_method(D_METHOD("cancel_free"), &Object::cancel_free);
  1658. ClassDB::add_virtual_method("Object", MethodInfo("free"), false);
  1659. ADD_SIGNAL(MethodInfo("script_changed"));
  1660. ADD_SIGNAL(MethodInfo("property_list_changed"));
  1661. #define BIND_OBJ_CORE_METHOD(m_method) \
  1662. ::ClassDB::add_virtual_method(get_class_static(), m_method, true, Vector<String>(), true);
  1663. BIND_OBJ_CORE_METHOD(MethodInfo("_init"));
  1664. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::STRING, "_to_string"));
  1665. {
  1666. MethodInfo mi("_notification");
  1667. mi.arguments.push_back(PropertyInfo(Variant::INT, "what"));
  1668. mi.arguments_metadata.push_back(GodotTypeInfo::Metadata::METADATA_INT_IS_INT32);
  1669. BIND_OBJ_CORE_METHOD(mi);
  1670. }
  1671. {
  1672. MethodInfo mi("_set");
  1673. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "property"));
  1674. mi.arguments.push_back(PropertyInfo(Variant::NIL, "value", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
  1675. mi.return_val.type = Variant::BOOL;
  1676. BIND_OBJ_CORE_METHOD(mi);
  1677. }
  1678. #ifdef TOOLS_ENABLED
  1679. {
  1680. MethodInfo mi("_get");
  1681. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "property"));
  1682. mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1683. BIND_OBJ_CORE_METHOD(mi);
  1684. }
  1685. {
  1686. MethodInfo mi("_get_property_list");
  1687. mi.return_val.type = Variant::ARRAY;
  1688. mi.return_val.hint = PROPERTY_HINT_ARRAY_TYPE;
  1689. mi.return_val.hint_string = "Dictionary";
  1690. BIND_OBJ_CORE_METHOD(mi);
  1691. }
  1692. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::NIL, "_validate_property", PropertyInfo(Variant::DICTIONARY, "property")));
  1693. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_property_can_revert", PropertyInfo(Variant::STRING_NAME, "property")));
  1694. {
  1695. MethodInfo mi("_property_get_revert");
  1696. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "property"));
  1697. mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1698. BIND_OBJ_CORE_METHOD(mi);
  1699. }
  1700. // These are actually `Variant` methods, but that doesn't matter since scripts can't inherit built-in types.
  1701. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_iter_init", PropertyInfo(Variant::ARRAY, "iter")));
  1702. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_iter_next", PropertyInfo(Variant::ARRAY, "iter")));
  1703. {
  1704. MethodInfo mi("_iter_get");
  1705. mi.arguments.push_back(PropertyInfo(Variant::NIL, "iter", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
  1706. mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1707. BIND_OBJ_CORE_METHOD(mi);
  1708. }
  1709. #endif
  1710. BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE);
  1711. BIND_CONSTANT(NOTIFICATION_PREDELETE);
  1712. BIND_CONSTANT(NOTIFICATION_EXTENSION_RELOADED);
  1713. BIND_ENUM_CONSTANT(CONNECT_DEFERRED);
  1714. BIND_ENUM_CONSTANT(CONNECT_PERSIST);
  1715. BIND_ENUM_CONSTANT(CONNECT_ONE_SHOT);
  1716. BIND_ENUM_CONSTANT(CONNECT_REFERENCE_COUNTED);
  1717. BIND_ENUM_CONSTANT(CONNECT_APPEND_SOURCE_OBJECT);
  1718. }
  1719. void Object::set_deferred(const StringName &p_property, const Variant &p_value) {
  1720. MessageQueue::get_singleton()->push_set(this, p_property, p_value);
  1721. }
  1722. void Object::set_block_signals(bool p_block) {
  1723. _block_signals = p_block;
  1724. }
  1725. bool Object::is_blocking_signals() const {
  1726. return _block_signals;
  1727. }
  1728. Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const {
  1729. bool valid;
  1730. Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid);
  1731. if (valid) {
  1732. if (r_valid) {
  1733. *r_valid = true;
  1734. }
  1735. return t;
  1736. }
  1737. if (get_script_instance()) {
  1738. return get_script_instance()->get_property_type(p_property, r_valid);
  1739. }
  1740. if (r_valid) {
  1741. *r_valid = false;
  1742. }
  1743. return Variant::NIL;
  1744. }
  1745. Variant::Type Object::get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid) const {
  1746. if (p_path.is_empty()) {
  1747. if (r_valid) {
  1748. *r_valid = false;
  1749. }
  1750. return Variant::NIL;
  1751. }
  1752. bool valid = false;
  1753. Variant::Type t = get_static_property_type(p_path[0], &valid);
  1754. if (!valid) {
  1755. if (r_valid) {
  1756. *r_valid = false;
  1757. }
  1758. return Variant::NIL;
  1759. }
  1760. Callable::CallError ce;
  1761. Variant check;
  1762. Variant::construct(t, check, nullptr, 0, ce);
  1763. for (int i = 1; i < p_path.size(); i++) {
  1764. if (check.get_type() == Variant::OBJECT || check.get_type() == Variant::DICTIONARY || check.get_type() == Variant::ARRAY) {
  1765. // We cannot be sure about the type of properties this type can have
  1766. if (r_valid) {
  1767. *r_valid = false;
  1768. }
  1769. return Variant::NIL;
  1770. }
  1771. check = check.get_named(p_path[i], valid);
  1772. if (!valid) {
  1773. if (r_valid) {
  1774. *r_valid = false;
  1775. }
  1776. return Variant::NIL;
  1777. }
  1778. }
  1779. if (r_valid) {
  1780. *r_valid = true;
  1781. }
  1782. return check.get_type();
  1783. }
  1784. bool Object::is_queued_for_deletion() const {
  1785. return _is_queued_for_deletion;
  1786. }
  1787. #ifdef TOOLS_ENABLED
  1788. void Object::set_edited(bool p_edited) {
  1789. _edited = p_edited;
  1790. _edited_version++;
  1791. }
  1792. bool Object::is_edited() const {
  1793. return _edited;
  1794. }
  1795. uint32_t Object::get_edited_version() const {
  1796. return _edited_version;
  1797. }
  1798. #endif
  1799. const GDType &Object::get_gdtype() const {
  1800. if (unlikely(!_gdtype_ptr)) {
  1801. // While class is initializing / deinitializing, constructors and destructors
  1802. // need access to the proper type at the proper stage.
  1803. return _get_typev();
  1804. }
  1805. return *_gdtype_ptr;
  1806. }
  1807. bool Object::is_class(const String &p_class) const {
  1808. for (const StringName &name : get_gdtype().get_name_hierarchy()) {
  1809. if (name == p_class) {
  1810. return true;
  1811. }
  1812. }
  1813. return false;
  1814. }
  1815. const StringName &Object::get_class_name() const {
  1816. return get_gdtype().get_name();
  1817. }
  1818. StringName Object::get_class_name_for_extension(const GDExtension *p_library) const {
  1819. #ifdef TOOLS_ENABLED
  1820. // If this is the library this extension comes from and it's a placeholder, we
  1821. // have to return the closest native parent's class name, so that it doesn't try to
  1822. // use this like the real object.
  1823. if (unlikely(_extension && _extension->library == p_library && _extension->is_placeholder)) {
  1824. return get_class_name();
  1825. }
  1826. #endif
  1827. // Only return the class name per the extension if it matches the given p_library.
  1828. if (_extension && _extension->library == p_library) {
  1829. return _extension->class_name;
  1830. }
  1831. // Extensions only have wrapper classes for classes exposed in ClassDB.
  1832. const StringName &class_name = get_class_name();
  1833. if (ClassDB::is_class_exposed(class_name)) {
  1834. return class_name;
  1835. }
  1836. // Find the nearest parent class that's exposed.
  1837. StringName parent_class = ClassDB::get_parent_class(class_name);
  1838. while (parent_class != StringName()) {
  1839. if (ClassDB::is_class_exposed(parent_class)) {
  1840. return parent_class;
  1841. }
  1842. parent_class = ClassDB::get_parent_class(parent_class);
  1843. }
  1844. return SNAME("Object");
  1845. }
  1846. void Object::set_instance_binding(void *p_token, void *p_binding, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1847. // This is only meant to be used on creation by the binder, but we also
  1848. // need to account for reloading (where the 'binding' will be cleared).
  1849. ERR_FAIL_COND(_instance_bindings != nullptr && _instance_bindings[0].binding != nullptr);
  1850. if (_instance_bindings == nullptr) {
  1851. _instance_bindings = (InstanceBinding *)memalloc(sizeof(InstanceBinding));
  1852. _instance_binding_count = 1;
  1853. }
  1854. _instance_bindings[0].binding = p_binding;
  1855. _instance_bindings[0].free_callback = p_callbacks->free_callback;
  1856. _instance_bindings[0].reference_callback = p_callbacks->reference_callback;
  1857. _instance_bindings[0].token = p_token;
  1858. }
  1859. void *Object::get_instance_binding(void *p_token, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1860. void *binding = nullptr;
  1861. MutexLock instance_binding_lock(_instance_binding_mutex);
  1862. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1863. if (_instance_bindings[i].token == p_token) {
  1864. binding = _instance_bindings[i].binding;
  1865. break;
  1866. }
  1867. }
  1868. if (unlikely(!binding && p_callbacks)) {
  1869. uint32_t current_size = next_power_of_2(_instance_binding_count);
  1870. uint32_t new_size = next_power_of_2(_instance_binding_count + 1);
  1871. if (current_size == 0 || new_size > current_size) {
  1872. _instance_bindings = (InstanceBinding *)memrealloc(_instance_bindings, new_size * sizeof(InstanceBinding));
  1873. }
  1874. _instance_bindings[_instance_binding_count].free_callback = p_callbacks->free_callback;
  1875. _instance_bindings[_instance_binding_count].reference_callback = p_callbacks->reference_callback;
  1876. _instance_bindings[_instance_binding_count].token = p_token;
  1877. binding = p_callbacks->create_callback(p_token, this);
  1878. _instance_bindings[_instance_binding_count].binding = binding;
  1879. #ifdef TOOLS_ENABLED
  1880. if (!_extension && Engine::get_singleton()->is_extension_reloading_enabled()) {
  1881. GDExtensionManager::get_singleton()->track_instance_binding(p_token, this);
  1882. }
  1883. #endif
  1884. _instance_binding_count++;
  1885. }
  1886. return binding;
  1887. }
  1888. bool Object::has_instance_binding(void *p_token) {
  1889. bool found = false;
  1890. MutexLock instance_binding_lock(_instance_binding_mutex);
  1891. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1892. if (_instance_bindings[i].token == p_token) {
  1893. found = true;
  1894. break;
  1895. }
  1896. }
  1897. return found;
  1898. }
  1899. void Object::free_instance_binding(void *p_token) {
  1900. bool found = false;
  1901. MutexLock instance_binding_lock(_instance_binding_mutex);
  1902. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1903. if (!found && _instance_bindings[i].token == p_token) {
  1904. if (_instance_bindings[i].free_callback) {
  1905. _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
  1906. }
  1907. found = true;
  1908. }
  1909. if (found) {
  1910. if (i + 1 < _instance_binding_count) {
  1911. _instance_bindings[i] = _instance_bindings[i + 1];
  1912. } else {
  1913. _instance_bindings[i] = { nullptr };
  1914. }
  1915. }
  1916. }
  1917. if (found) {
  1918. _instance_binding_count--;
  1919. }
  1920. }
  1921. #ifdef TOOLS_ENABLED
  1922. void Object::clear_internal_extension() {
  1923. ERR_FAIL_NULL(_extension);
  1924. // Free the instance inside the GDExtension.
  1925. if (_extension->free_instance) {
  1926. _extension->free_instance(_extension->class_userdata, _extension_instance);
  1927. }
  1928. _extension = nullptr;
  1929. _extension_instance = nullptr;
  1930. // Reset GDType to internal type.
  1931. _gdtype_ptr = &_get_typev();
  1932. // Clear the instance bindings.
  1933. _instance_binding_mutex.lock();
  1934. if (_instance_bindings) {
  1935. if (_instance_bindings[0].free_callback) {
  1936. _instance_bindings[0].free_callback(_instance_bindings[0].token, this, _instance_bindings[0].binding);
  1937. }
  1938. _instance_bindings[0].binding = nullptr;
  1939. _instance_bindings[0].token = nullptr;
  1940. _instance_bindings[0].free_callback = nullptr;
  1941. _instance_bindings[0].reference_callback = nullptr;
  1942. }
  1943. _instance_binding_mutex.unlock();
  1944. // Clear the virtual methods.
  1945. while (virtual_method_list) {
  1946. (*virtual_method_list->method) = nullptr;
  1947. virtual_method_list = virtual_method_list->next;
  1948. }
  1949. }
  1950. void Object::reset_internal_extension(ObjectGDExtension *p_extension) {
  1951. ERR_FAIL_COND(_extension != nullptr);
  1952. if (p_extension) {
  1953. _extension_instance = p_extension->recreate_instance ? p_extension->recreate_instance(p_extension->class_userdata, (GDExtensionObjectPtr)this) : nullptr;
  1954. ERR_FAIL_NULL_MSG(_extension_instance, "Unable to recreate GDExtension instance - does this extension support hot reloading?");
  1955. _extension = p_extension;
  1956. _gdtype_ptr = p_extension->gdtype;
  1957. }
  1958. }
  1959. #endif
  1960. void Object::_construct_object(bool p_reference) {
  1961. _block_signals = false;
  1962. _can_translate = true;
  1963. _emitting = false;
  1964. _is_queued_for_deletion = false;
  1965. _predelete_ok = false;
  1966. // ObjectDB::add_instance relies on AncestralClass::REF_COUNTED
  1967. // being already set in the case of references.
  1968. _ancestry = p_reference ? (uint32_t)AncestralClass::REF_COUNTED : 0;
  1969. _instance_id = ObjectDB::add_instance(this);
  1970. #ifdef TOOLS_ENABLED
  1971. _edited = false;
  1972. #endif
  1973. #ifdef DEBUG_ENABLED
  1974. _lock_index.init(1);
  1975. #endif
  1976. }
  1977. Object::Object(bool p_reference) {
  1978. _construct_object(p_reference);
  1979. }
  1980. Object::Object() {
  1981. _construct_object(false);
  1982. }
  1983. void Object::detach_from_objectdb() {
  1984. if (_instance_id != ObjectID()) {
  1985. ObjectDB::remove_instance(this);
  1986. _instance_id = ObjectID();
  1987. }
  1988. }
  1989. void Object::assign_type_static(GDType **type_ptr, const char *p_name, const GDType *super_type) {
  1990. static BinaryMutex _mutex;
  1991. MutexLock lock(_mutex);
  1992. GDType *type = *type_ptr;
  1993. if (type) {
  1994. // Assigned while we were waiting.
  1995. return;
  1996. }
  1997. type = memnew(GDType(super_type, StringName(p_name)));
  1998. *type_ptr = type;
  1999. ClassDB::gdtype_autorelease_pool.push_back(type_ptr);
  2000. }
  2001. Object::~Object() {
  2002. if (_emitting) {
  2003. //@todo this may need to actually reach the debugger prioritarily somehow because it may crash before
  2004. ERR_PRINT(vformat("Object '%s' 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.", to_string()));
  2005. }
  2006. {
  2007. OBJ_SIGNAL_LOCK
  2008. // Drop all connections to the signals of this object.
  2009. while (signal_map.size()) {
  2010. // Avoid regular iteration so erasing is safe.
  2011. KeyValue<StringName, SignalData> &E = *signal_map.begin();
  2012. SignalData *s = &E.value;
  2013. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  2014. Object *target = slot_kv.value.conn.callable.get_object();
  2015. if (likely(target)) {
  2016. target->connections.erase(slot_kv.value.cE);
  2017. }
  2018. }
  2019. signal_map.erase(E.key);
  2020. }
  2021. // Disconnect signals that connect to this object.
  2022. while (connections.size()) {
  2023. Connection c = connections.front()->get();
  2024. Object *obj = c.callable.get_object();
  2025. bool disconnected = false;
  2026. if (likely(obj)) {
  2027. disconnected = c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true);
  2028. }
  2029. if (unlikely(!disconnected)) {
  2030. // If the disconnect has failed, abandon the connection to avoid getting trapped in an infinite loop here.
  2031. connections.pop_front();
  2032. }
  2033. }
  2034. }
  2035. if (_instance_id != ObjectID()) {
  2036. ObjectDB::remove_instance(this);
  2037. _instance_id = ObjectID();
  2038. }
  2039. _predelete_ok = true;
  2040. if (_instance_bindings != nullptr) {
  2041. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  2042. if (_instance_bindings[i].free_callback) {
  2043. _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
  2044. }
  2045. }
  2046. memfree(_instance_bindings);
  2047. }
  2048. if (signal_mutex) {
  2049. memdelete(signal_mutex);
  2050. }
  2051. }
  2052. bool predelete_handler(Object *p_object) {
  2053. return p_object->_predelete();
  2054. }
  2055. void postinitialize_handler(Object *p_object) {
  2056. p_object->_initialize();
  2057. p_object->_postinitialize();
  2058. }
  2059. void ObjectDB::debug_objects(DebugFunc p_func, void *p_user_data) {
  2060. spin_lock.lock();
  2061. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  2062. if (object_slots[i].validator) {
  2063. p_func(object_slots[i].object, p_user_data);
  2064. count--;
  2065. }
  2066. }
  2067. spin_lock.unlock();
  2068. }
  2069. #ifdef TOOLS_ENABLED
  2070. void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  2071. const String pf = p_function;
  2072. if (p_idx == 0) {
  2073. if (pf == "connect" || pf == "is_connected" || pf == "disconnect" || pf == "emit_signal" || pf == "has_signal") {
  2074. List<MethodInfo> signals;
  2075. get_signal_list(&signals);
  2076. for (const MethodInfo &E : signals) {
  2077. r_options->push_back(E.name.quote());
  2078. }
  2079. } else if (pf == "call" || pf == "call_deferred" || pf == "callv" || pf == "has_method") {
  2080. List<MethodInfo> methods;
  2081. get_method_list(&methods);
  2082. for (const MethodInfo &E : methods) {
  2083. if (E.name.begins_with("_") && !(E.flags & METHOD_FLAG_VIRTUAL)) {
  2084. continue;
  2085. }
  2086. r_options->push_back(E.name.quote());
  2087. }
  2088. } else if (pf == "set" || pf == "set_deferred" || pf == "get") {
  2089. List<PropertyInfo> properties;
  2090. get_property_list(&properties);
  2091. for (const PropertyInfo &E : properties) {
  2092. if (E.usage & PROPERTY_USAGE_DEFAULT && !(E.usage & PROPERTY_USAGE_INTERNAL)) {
  2093. r_options->push_back(E.name.quote());
  2094. }
  2095. }
  2096. } else if (pf == "set_meta" || pf == "get_meta" || pf == "has_meta" || pf == "remove_meta") {
  2097. for (const KeyValue<StringName, Variant> &K : metadata) {
  2098. r_options->push_back(String(K.key).quote());
  2099. }
  2100. }
  2101. } else if (p_idx == 2) {
  2102. if (pf == "connect") {
  2103. // Ideally, the constants should be inferred by the parameter.
  2104. // But a parameter's PropertyInfo does not store the enum they come from, so this will do for now.
  2105. List<StringName> constants;
  2106. ClassDB::get_enum_constants("Object", "ConnectFlags", &constants);
  2107. for (const StringName &E : constants) {
  2108. r_options->push_back(String(E));
  2109. }
  2110. }
  2111. }
  2112. }
  2113. #endif
  2114. SpinLock ObjectDB::spin_lock;
  2115. uint32_t ObjectDB::slot_count = 0;
  2116. uint32_t ObjectDB::slot_max = 0;
  2117. ObjectDB::ObjectSlot *ObjectDB::object_slots = nullptr;
  2118. uint64_t ObjectDB::validator_counter = 0;
  2119. int ObjectDB::get_object_count() {
  2120. return slot_count;
  2121. }
  2122. ObjectID ObjectDB::add_instance(Object *p_object) {
  2123. spin_lock.lock();
  2124. if (unlikely(slot_count == slot_max)) {
  2125. CRASH_COND(slot_count == (1 << OBJECTDB_SLOT_MAX_COUNT_BITS));
  2126. uint32_t new_slot_max = slot_max > 0 ? slot_max * 2 : 1;
  2127. object_slots = (ObjectSlot *)memrealloc(object_slots, sizeof(ObjectSlot) * new_slot_max);
  2128. for (uint32_t i = slot_max; i < new_slot_max; i++) {
  2129. object_slots[i].object = nullptr;
  2130. object_slots[i].is_ref_counted = false;
  2131. object_slots[i].next_free = i;
  2132. object_slots[i].validator = 0;
  2133. }
  2134. slot_max = new_slot_max;
  2135. }
  2136. uint32_t slot = object_slots[slot_count].next_free;
  2137. if (object_slots[slot].object != nullptr) {
  2138. spin_lock.unlock();
  2139. ERR_FAIL_COND_V(object_slots[slot].object != nullptr, ObjectID());
  2140. }
  2141. object_slots[slot].object = p_object;
  2142. object_slots[slot].is_ref_counted = p_object->is_ref_counted();
  2143. validator_counter = (validator_counter + 1) & OBJECTDB_VALIDATOR_MASK;
  2144. if (unlikely(validator_counter == 0)) {
  2145. validator_counter = 1;
  2146. }
  2147. object_slots[slot].validator = validator_counter;
  2148. uint64_t id = validator_counter;
  2149. id <<= OBJECTDB_SLOT_MAX_COUNT_BITS;
  2150. id |= uint64_t(slot);
  2151. if (p_object->is_ref_counted()) {
  2152. id |= OBJECTDB_REFERENCE_BIT;
  2153. }
  2154. slot_count++;
  2155. spin_lock.unlock();
  2156. return ObjectID(id);
  2157. }
  2158. void ObjectDB::remove_instance(Object *p_object) {
  2159. uint64_t t = p_object->get_instance_id();
  2160. uint32_t slot = t & OBJECTDB_SLOT_MAX_COUNT_MASK; //slot is always valid on valid object
  2161. spin_lock.lock();
  2162. #ifdef DEBUG_ENABLED
  2163. if (object_slots[slot].object != p_object) {
  2164. spin_lock.unlock();
  2165. ERR_FAIL_COND(object_slots[slot].object != p_object);
  2166. }
  2167. {
  2168. uint64_t validator = (t >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK;
  2169. if (object_slots[slot].validator != validator) {
  2170. spin_lock.unlock();
  2171. ERR_FAIL_COND(object_slots[slot].validator != validator);
  2172. }
  2173. }
  2174. #endif
  2175. //decrease slot count
  2176. slot_count--;
  2177. //set the free slot properly
  2178. object_slots[slot_count].next_free = slot;
  2179. //invalidate, so checks against it fail
  2180. object_slots[slot].validator = 0;
  2181. object_slots[slot].is_ref_counted = false;
  2182. object_slots[slot].object = nullptr;
  2183. spin_lock.unlock();
  2184. }
  2185. void ObjectDB::setup() {
  2186. //nothing to do now
  2187. }
  2188. void ObjectDB::cleanup() {
  2189. spin_lock.lock();
  2190. if (slot_count > 0) {
  2191. WARN_PRINT("ObjectDB instances leaked at exit (run with --verbose for details).");
  2192. if (OS::get_singleton()->is_stdout_verbose()) {
  2193. // Ensure calling the native classes because if a leaked instance has a script
  2194. // that overrides any of those methods, it'd not be OK to call them at this point,
  2195. // now the scripting languages have already been terminated.
  2196. MethodBind *node_get_path = ClassDB::get_method("Node", "get_path");
  2197. MethodBind *resource_get_path = ClassDB::get_method("Resource", "get_path");
  2198. Callable::CallError call_error;
  2199. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  2200. if (object_slots[i].validator) {
  2201. Object *obj = object_slots[i].object;
  2202. String extra_info;
  2203. if (obj->is_class("Node")) {
  2204. extra_info = " - Node path: " + String(node_get_path->call(obj, nullptr, 0, call_error));
  2205. }
  2206. if (obj->is_class("Resource")) {
  2207. extra_info = " - Resource path: " + String(resource_get_path->call(obj, nullptr, 0, call_error));
  2208. }
  2209. if (obj->is_class("RefCounted")) {
  2210. extra_info = " - Reference count: " + itos((static_cast<RefCounted *>(obj))->get_reference_count());
  2211. }
  2212. uint64_t id = uint64_t(i) | (uint64_t(object_slots[i].validator) << OBJECTDB_SLOT_MAX_COUNT_BITS) | (object_slots[i].is_ref_counted ? OBJECTDB_REFERENCE_BIT : 0);
  2213. DEV_ASSERT(id == (uint64_t)obj->get_instance_id()); // We could just use the id from the object, but this check may help catching memory corruption catastrophes.
  2214. print_line("Leaked instance: " + String(obj->get_class()) + ":" + uitos(id) + extra_info);
  2215. count--;
  2216. }
  2217. }
  2218. 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()`).");
  2219. }
  2220. }
  2221. if (object_slots) {
  2222. memfree(object_slots);
  2223. }
  2224. spin_lock.unlock();
  2225. }