array.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /*************************************************************************/
  2. /* array.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "array.h"
  31. #include "container_type_validate.h"
  32. #include "core/hashfuncs.h"
  33. #include "core/object.h"
  34. #include "core/script_language.h"
  35. #include "core/variant.h"
  36. #include "core/vector.h"
  37. class ArrayPrivate {
  38. public:
  39. SafeRefCount refcount;
  40. Vector<Variant> array;
  41. ContainerTypeValidate typed;
  42. };
  43. void Array::_ref(const Array &p_from) const {
  44. ArrayPrivate *_fp = p_from._p;
  45. ERR_FAIL_COND(!_fp); // should NOT happen.
  46. if (_fp == _p)
  47. return; // whatever it is, nothing to do here move along
  48. bool success = _fp->refcount.ref();
  49. ERR_FAIL_COND(!success); // should really not happen either
  50. _unref();
  51. _p = p_from._p;
  52. }
  53. void Array::_unref() const {
  54. if (!_p)
  55. return;
  56. if (_p->refcount.unref()) {
  57. memdelete(_p);
  58. }
  59. _p = nullptr;
  60. }
  61. Variant &Array::operator[](int p_idx) {
  62. return _p->array.write[p_idx];
  63. }
  64. const Variant &Array::operator[](int p_idx) const {
  65. return _p->array[p_idx];
  66. }
  67. int Array::size() const {
  68. return _p->array.size();
  69. }
  70. bool Array::empty() const {
  71. return _p->array.empty();
  72. }
  73. void Array::clear() {
  74. _p->array.clear();
  75. }
  76. bool Array::operator==(const Array &p_array) const {
  77. return _p == p_array._p;
  78. }
  79. uint32_t Array::hash() const {
  80. uint32_t h = hash_djb2_one_32(0);
  81. for (int i = 0; i < _p->array.size(); i++) {
  82. h = hash_djb2_one_32(_p->array[i].hash(), h);
  83. }
  84. return h;
  85. }
  86. void Array::_assign(const Array &p_array) {
  87. if (_p->typed.type != Variant::OBJECT && _p->typed.type == p_array._p->typed.type) {
  88. //same type or untyped, just reference, shuold be fine
  89. _ref(p_array);
  90. } else if (_p->typed.type == Variant::NIL) { //from typed to untyped, must copy, but this is cheap anyway
  91. _p->array = p_array._p->array;
  92. } else if (p_array._p->typed.type == Variant::NIL) { //from untyped to typed, must try to check if they are all valid
  93. if (_p->typed.type == Variant::OBJECT) {
  94. //for objects, it needs full validation, either can be converted or fail
  95. for (int i = 0; i < p_array._p->array.size(); i++) {
  96. if (!_p->typed.validate(p_array._p->array[i], "assign")) {
  97. return;
  98. }
  99. }
  100. _p->array = p_array._p->array; //then just copy, which is cheap anyway
  101. } else {
  102. //for non objects, we need to check if there is a valid conversion, which needs to happen one by one, so this is the worst case.
  103. Vector<Variant> new_array;
  104. new_array.resize(p_array._p->array.size());
  105. for (int i = 0; i < p_array._p->array.size(); i++) {
  106. Variant src_val = p_array._p->array[i];
  107. if (src_val.get_type() == _p->typed.type) {
  108. new_array.write[i] = src_val;
  109. } else if (Variant::can_convert_strict(src_val.get_type(), _p->typed.type)) {
  110. Variant *ptr = &src_val;
  111. Callable::CallError ce;
  112. new_array.write[i] = Variant::construct(_p->typed.type, (const Variant **)&ptr, 1, ce, true);
  113. if (ce.error != Callable::CallError::CALL_OK) {
  114. ERR_FAIL_MSG("Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  115. }
  116. } else {
  117. ERR_FAIL_MSG("Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  118. }
  119. }
  120. _p->array = new_array;
  121. }
  122. } else if (_p->typed.can_reference(p_array._p->typed)) { //same type or compatible
  123. _ref(p_array);
  124. } else {
  125. ERR_FAIL_MSG("Assignment of arrays of incompatible types.");
  126. }
  127. }
  128. void Array::operator=(const Array &p_array) {
  129. _assign(p_array);
  130. }
  131. void Array::push_back(const Variant &p_value) {
  132. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_back"));
  133. _p->array.push_back(p_value);
  134. }
  135. Error Array::resize(int p_new_size) {
  136. return _p->array.resize(p_new_size);
  137. }
  138. void Array::insert(int p_pos, const Variant &p_value) {
  139. ERR_FAIL_COND(!_p->typed.validate(p_value, "insert"));
  140. _p->array.insert(p_pos, p_value);
  141. }
  142. void Array::erase(const Variant &p_value) {
  143. ERR_FAIL_COND(!_p->typed.validate(p_value, "erase"));
  144. _p->array.erase(p_value);
  145. }
  146. Variant Array::front() const {
  147. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  148. return operator[](0);
  149. }
  150. Variant Array::back() const {
  151. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  152. return operator[](_p->array.size() - 1);
  153. }
  154. int Array::find(const Variant &p_value, int p_from) const {
  155. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find"), -1);
  156. return _p->array.find(p_value, p_from);
  157. }
  158. int Array::rfind(const Variant &p_value, int p_from) const {
  159. if (_p->array.size() == 0)
  160. return -1;
  161. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "rfind"), -1);
  162. if (p_from < 0) {
  163. // Relative offset from the end
  164. p_from = _p->array.size() + p_from;
  165. }
  166. if (p_from < 0 || p_from >= _p->array.size()) {
  167. // Limit to array boundaries
  168. p_from = _p->array.size() - 1;
  169. }
  170. for (int i = p_from; i >= 0; i--) {
  171. if (_p->array[i] == p_value) {
  172. return i;
  173. }
  174. }
  175. return -1;
  176. }
  177. int Array::find_last(const Variant &p_value) const {
  178. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find_last"), -1);
  179. return rfind(p_value);
  180. }
  181. int Array::count(const Variant &p_value) const {
  182. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "count"), 0);
  183. if (_p->array.size() == 0)
  184. return 0;
  185. int amount = 0;
  186. for (int i = 0; i < _p->array.size(); i++) {
  187. if (_p->array[i] == p_value) {
  188. amount++;
  189. }
  190. }
  191. return amount;
  192. }
  193. bool Array::has(const Variant &p_value) const {
  194. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "use 'has'"), false);
  195. return _p->array.find(p_value, 0) != -1;
  196. }
  197. void Array::remove(int p_pos) {
  198. _p->array.remove(p_pos);
  199. }
  200. void Array::set(int p_idx, const Variant &p_value) {
  201. ERR_FAIL_COND(!_p->typed.validate(p_value, "set"));
  202. operator[](p_idx) = p_value;
  203. }
  204. const Variant &Array::get(int p_idx) const {
  205. return operator[](p_idx);
  206. }
  207. Array Array::duplicate(bool p_deep) const {
  208. Array new_arr;
  209. int element_count = size();
  210. new_arr.resize(element_count);
  211. new_arr._p->typed = _p->typed;
  212. for (int i = 0; i < element_count; i++) {
  213. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  214. }
  215. return new_arr;
  216. }
  217. int Array::_fix_slice_index(int p_index, int p_arr_len, int p_top_mod) {
  218. p_index = CLAMP(p_index, -p_arr_len, p_arr_len + p_top_mod);
  219. if (p_index < 0) {
  220. p_index = (p_index % p_arr_len + p_arr_len) % p_arr_len; // positive modulo
  221. }
  222. return p_index;
  223. }
  224. int Array::_clamp_index(int p_index) const {
  225. return CLAMP(p_index, -size() + 1, size() - 1);
  226. }
  227. #define ARRAY_GET_DEEP(idx, is_deep) is_deep ? get(idx).duplicate(is_deep) : get(idx)
  228. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  229. Array new_arr;
  230. if (empty()) // Don't try to slice empty arrays.
  231. return new_arr;
  232. p_begin = Array::_fix_slice_index(p_begin, size(), -1); // can't start out of range
  233. p_end = Array::_fix_slice_index(p_end, size(), 0);
  234. int x = p_begin;
  235. int new_arr_i = 0;
  236. ERR_FAIL_COND_V(p_step == 0, new_arr);
  237. if (Array::_clamp_index(p_begin) == Array::_clamp_index(p_end)) { // don't include element twice
  238. new_arr.resize(1);
  239. // new_arr[0] = 1;
  240. new_arr[0] = ARRAY_GET_DEEP(Array::_clamp_index(p_begin), p_deep);
  241. return new_arr;
  242. } else {
  243. int element_count = ceil((int)MAX(0, (p_end - p_begin) / p_step)) + 1;
  244. if (element_count == 1) { // delta going in wrong direction to reach end
  245. new_arr.resize(0);
  246. return new_arr;
  247. }
  248. new_arr.resize(element_count);
  249. }
  250. // if going backwards, have to have a different terminating condition
  251. if (p_step < 0) {
  252. while (x >= p_end) {
  253. new_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);
  254. x += p_step;
  255. new_arr_i += 1;
  256. }
  257. } else if (p_step > 0) {
  258. while (x <= p_end) {
  259. new_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);
  260. x += p_step;
  261. new_arr_i += 1;
  262. }
  263. }
  264. return new_arr;
  265. }
  266. struct _ArrayVariantSort {
  267. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  268. bool valid = false;
  269. Variant res;
  270. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  271. if (!valid)
  272. res = false;
  273. return res;
  274. }
  275. };
  276. Array &Array::sort() {
  277. _p->array.sort_custom<_ArrayVariantSort>();
  278. return *this;
  279. }
  280. struct _ArrayVariantSortCustom {
  281. Object *obj;
  282. StringName func;
  283. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  284. const Variant *args[2] = { &p_l, &p_r };
  285. Callable::CallError err;
  286. bool res = obj->call(func, args, 2, err);
  287. if (err.error != Callable::CallError::CALL_OK)
  288. res = false;
  289. return res;
  290. }
  291. };
  292. Array &Array::sort_custom(Object *p_obj, const StringName &p_function) {
  293. ERR_FAIL_NULL_V(p_obj, *this);
  294. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  295. avs.compare.obj = p_obj;
  296. avs.compare.func = p_function;
  297. avs.sort(_p->array.ptrw(), _p->array.size());
  298. return *this;
  299. }
  300. void Array::shuffle() {
  301. const int n = _p->array.size();
  302. if (n < 2)
  303. return;
  304. Variant *data = _p->array.ptrw();
  305. for (int i = n - 1; i >= 1; i--) {
  306. const int j = Math::rand() % (i + 1);
  307. const Variant tmp = data[j];
  308. data[j] = data[i];
  309. data[i] = tmp;
  310. }
  311. }
  312. template <typename Less>
  313. _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
  314. int lo = 0;
  315. int hi = p_array.size();
  316. if (p_before) {
  317. while (lo < hi) {
  318. const int mid = (lo + hi) / 2;
  319. if (p_less(p_array.get(mid), p_value)) {
  320. lo = mid + 1;
  321. } else {
  322. hi = mid;
  323. }
  324. }
  325. } else {
  326. while (lo < hi) {
  327. const int mid = (lo + hi) / 2;
  328. if (p_less(p_value, p_array.get(mid))) {
  329. hi = mid;
  330. } else {
  331. lo = mid + 1;
  332. }
  333. }
  334. }
  335. return lo;
  336. }
  337. int Array::bsearch(const Variant &p_value, bool p_before) {
  338. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "binary search"), -1);
  339. return bisect(_p->array, p_value, p_before, _ArrayVariantSort());
  340. }
  341. int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {
  342. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "custom binary search"), -1);
  343. ERR_FAIL_NULL_V(p_obj, 0);
  344. _ArrayVariantSortCustom less;
  345. less.obj = p_obj;
  346. less.func = p_function;
  347. return bisect(_p->array, p_value, p_before, less);
  348. }
  349. Array &Array::invert() {
  350. _p->array.invert();
  351. return *this;
  352. }
  353. void Array::push_front(const Variant &p_value) {
  354. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_front"));
  355. _p->array.insert(0, p_value);
  356. }
  357. Variant Array::pop_back() {
  358. if (!_p->array.empty()) {
  359. int n = _p->array.size() - 1;
  360. Variant ret = _p->array.get(n);
  361. _p->array.resize(n);
  362. return ret;
  363. }
  364. return Variant();
  365. }
  366. Variant Array::pop_front() {
  367. if (!_p->array.empty()) {
  368. Variant ret = _p->array.get(0);
  369. _p->array.remove(0);
  370. return ret;
  371. }
  372. return Variant();
  373. }
  374. Variant Array::min() const {
  375. Variant minval;
  376. for (int i = 0; i < size(); i++) {
  377. if (i == 0) {
  378. minval = get(i);
  379. } else {
  380. bool valid;
  381. Variant ret;
  382. Variant test = get(i);
  383. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  384. if (!valid) {
  385. return Variant(); //not a valid comparison
  386. }
  387. if (bool(ret)) {
  388. //is less
  389. minval = test;
  390. }
  391. }
  392. }
  393. return minval;
  394. }
  395. Variant Array::max() const {
  396. Variant maxval;
  397. for (int i = 0; i < size(); i++) {
  398. if (i == 0) {
  399. maxval = get(i);
  400. } else {
  401. bool valid;
  402. Variant ret;
  403. Variant test = get(i);
  404. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  405. if (!valid) {
  406. return Variant(); //not a valid comparison
  407. }
  408. if (bool(ret)) {
  409. //is less
  410. maxval = test;
  411. }
  412. }
  413. }
  414. return maxval;
  415. }
  416. const void *Array::id() const {
  417. return _p->array.ptr();
  418. }
  419. Array::Array(const Array &p_from, uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  420. _p = memnew(ArrayPrivate);
  421. _p->refcount.init();
  422. set_typed(p_type, p_class_name, p_script);
  423. _assign(p_from);
  424. }
  425. void Array::set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  426. ERR_FAIL_COND_MSG(_p->array.size() > 0, "Type can only be set when array is empty.");
  427. ERR_FAIL_COND_MSG(_p->refcount.get() > 1, "Type can only be set when array has no more than one user.");
  428. ERR_FAIL_COND_MSG(_p->typed.type != Variant::NIL, "Type can only be set once.");
  429. ERR_FAIL_COND_MSG(p_class_name != StringName() && p_type != Variant::OBJECT, "Class names can only be set for type OBJECT");
  430. Ref<Script> script = p_script;
  431. ERR_FAIL_COND_MSG(script.is_valid() && p_class_name == StringName(), "Script class can only be set together with base class name");
  432. _p->typed.type = Variant::Type(p_type);
  433. _p->typed.class_name = p_class_name;
  434. _p->typed.script = script;
  435. _p->typed.where = "TypedArray";
  436. }
  437. Array::Array(const Array &p_from) {
  438. _p = nullptr;
  439. _ref(p_from);
  440. }
  441. Array::Array() {
  442. _p = memnew(ArrayPrivate);
  443. _p->refcount.init();
  444. }
  445. Array::~Array() {
  446. _unref();
  447. }