array.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. for (int i = 0; i < p_array._p->array.size(); i++) {
  94. if (!_p->typed.validate(p_array._p->array[i], "assign")) {
  95. return;
  96. }
  97. }
  98. _p->array = p_array._p->array; //then just copy, which is cheap anyway
  99. } else if (_p->typed.can_reference(p_array._p->typed)) { //same type or compatible
  100. _ref(p_array);
  101. } else {
  102. ERR_FAIL_MSG("Assignment of arrays of incompatible types.");
  103. }
  104. }
  105. void Array::operator=(const Array &p_array) {
  106. _assign(p_array);
  107. }
  108. void Array::push_back(const Variant &p_value) {
  109. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_back"));
  110. _p->array.push_back(p_value);
  111. }
  112. Error Array::resize(int p_new_size) {
  113. return _p->array.resize(p_new_size);
  114. }
  115. void Array::insert(int p_pos, const Variant &p_value) {
  116. ERR_FAIL_COND(!_p->typed.validate(p_value, "insert"));
  117. _p->array.insert(p_pos, p_value);
  118. }
  119. void Array::erase(const Variant &p_value) {
  120. ERR_FAIL_COND(!_p->typed.validate(p_value, "erase"));
  121. _p->array.erase(p_value);
  122. }
  123. Variant Array::front() const {
  124. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  125. return operator[](0);
  126. }
  127. Variant Array::back() const {
  128. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  129. return operator[](_p->array.size() - 1);
  130. }
  131. int Array::find(const Variant &p_value, int p_from) const {
  132. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find"), -1);
  133. return _p->array.find(p_value, p_from);
  134. }
  135. int Array::rfind(const Variant &p_value, int p_from) const {
  136. if (_p->array.size() == 0)
  137. return -1;
  138. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "rfind"), -1);
  139. if (p_from < 0) {
  140. // Relative offset from the end
  141. p_from = _p->array.size() + p_from;
  142. }
  143. if (p_from < 0 || p_from >= _p->array.size()) {
  144. // Limit to array boundaries
  145. p_from = _p->array.size() - 1;
  146. }
  147. for (int i = p_from; i >= 0; i--) {
  148. if (_p->array[i] == p_value) {
  149. return i;
  150. }
  151. }
  152. return -1;
  153. }
  154. int Array::find_last(const Variant &p_value) const {
  155. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find_last"), -1);
  156. return rfind(p_value);
  157. }
  158. int Array::count(const Variant &p_value) const {
  159. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "count"), 0);
  160. if (_p->array.size() == 0)
  161. return 0;
  162. int amount = 0;
  163. for (int i = 0; i < _p->array.size(); i++) {
  164. if (_p->array[i] == p_value) {
  165. amount++;
  166. }
  167. }
  168. return amount;
  169. }
  170. bool Array::has(const Variant &p_value) const {
  171. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "use 'has'"), false);
  172. return _p->array.find(p_value, 0) != -1;
  173. }
  174. void Array::remove(int p_pos) {
  175. _p->array.remove(p_pos);
  176. }
  177. void Array::set(int p_idx, const Variant &p_value) {
  178. ERR_FAIL_COND(!_p->typed.validate(p_value, "set"));
  179. operator[](p_idx) = p_value;
  180. }
  181. const Variant &Array::get(int p_idx) const {
  182. return operator[](p_idx);
  183. }
  184. Array Array::duplicate(bool p_deep) const {
  185. Array new_arr;
  186. int element_count = size();
  187. new_arr.resize(element_count);
  188. new_arr._p->typed = _p->typed;
  189. for (int i = 0; i < element_count; i++) {
  190. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  191. }
  192. return new_arr;
  193. }
  194. int Array::_fix_slice_index(int p_index, int p_arr_len, int p_top_mod) {
  195. p_index = CLAMP(p_index, -p_arr_len, p_arr_len + p_top_mod);
  196. if (p_index < 0) {
  197. p_index = (p_index % p_arr_len + p_arr_len) % p_arr_len; // positive modulo
  198. }
  199. return p_index;
  200. }
  201. int Array::_clamp_index(int p_index) const {
  202. return CLAMP(p_index, -size() + 1, size() - 1);
  203. }
  204. #define ARRAY_GET_DEEP(idx, is_deep) is_deep ? get(idx).duplicate(is_deep) : get(idx)
  205. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  206. Array new_arr;
  207. if (empty()) // Don't try to slice empty arrays.
  208. return new_arr;
  209. p_begin = Array::_fix_slice_index(p_begin, size(), -1); // can't start out of range
  210. p_end = Array::_fix_slice_index(p_end, size(), 0);
  211. int x = p_begin;
  212. int new_arr_i = 0;
  213. ERR_FAIL_COND_V(p_step == 0, new_arr);
  214. if (Array::_clamp_index(p_begin) == Array::_clamp_index(p_end)) { // don't include element twice
  215. new_arr.resize(1);
  216. // new_arr[0] = 1;
  217. new_arr[0] = ARRAY_GET_DEEP(Array::_clamp_index(p_begin), p_deep);
  218. return new_arr;
  219. } else {
  220. int element_count = ceil((int)MAX(0, (p_end - p_begin) / p_step)) + 1;
  221. if (element_count == 1) { // delta going in wrong direction to reach end
  222. new_arr.resize(0);
  223. return new_arr;
  224. }
  225. new_arr.resize(element_count);
  226. }
  227. // if going backwards, have to have a different terminating condition
  228. if (p_step < 0) {
  229. while (x >= p_end) {
  230. new_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);
  231. x += p_step;
  232. new_arr_i += 1;
  233. }
  234. } else if (p_step > 0) {
  235. while (x <= p_end) {
  236. new_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);
  237. x += p_step;
  238. new_arr_i += 1;
  239. }
  240. }
  241. return new_arr;
  242. }
  243. struct _ArrayVariantSort {
  244. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  245. bool valid = false;
  246. Variant res;
  247. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  248. if (!valid)
  249. res = false;
  250. return res;
  251. }
  252. };
  253. Array &Array::sort() {
  254. _p->array.sort_custom<_ArrayVariantSort>();
  255. return *this;
  256. }
  257. struct _ArrayVariantSortCustom {
  258. Object *obj;
  259. StringName func;
  260. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  261. const Variant *args[2] = { &p_l, &p_r };
  262. Callable::CallError err;
  263. bool res = obj->call(func, args, 2, err);
  264. if (err.error != Callable::CallError::CALL_OK)
  265. res = false;
  266. return res;
  267. }
  268. };
  269. Array &Array::sort_custom(Object *p_obj, const StringName &p_function) {
  270. ERR_FAIL_NULL_V(p_obj, *this);
  271. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  272. avs.compare.obj = p_obj;
  273. avs.compare.func = p_function;
  274. avs.sort(_p->array.ptrw(), _p->array.size());
  275. return *this;
  276. }
  277. void Array::shuffle() {
  278. const int n = _p->array.size();
  279. if (n < 2)
  280. return;
  281. Variant *data = _p->array.ptrw();
  282. for (int i = n - 1; i >= 1; i--) {
  283. const int j = Math::rand() % (i + 1);
  284. const Variant tmp = data[j];
  285. data[j] = data[i];
  286. data[i] = tmp;
  287. }
  288. }
  289. template <typename Less>
  290. _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
  291. int lo = 0;
  292. int hi = p_array.size();
  293. if (p_before) {
  294. while (lo < hi) {
  295. const int mid = (lo + hi) / 2;
  296. if (p_less(p_array.get(mid), p_value)) {
  297. lo = mid + 1;
  298. } else {
  299. hi = mid;
  300. }
  301. }
  302. } else {
  303. while (lo < hi) {
  304. const int mid = (lo + hi) / 2;
  305. if (p_less(p_value, p_array.get(mid))) {
  306. hi = mid;
  307. } else {
  308. lo = mid + 1;
  309. }
  310. }
  311. }
  312. return lo;
  313. }
  314. int Array::bsearch(const Variant &p_value, bool p_before) {
  315. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "binary search"), -1);
  316. return bisect(_p->array, p_value, p_before, _ArrayVariantSort());
  317. }
  318. int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {
  319. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "custom binary search"), -1);
  320. ERR_FAIL_NULL_V(p_obj, 0);
  321. _ArrayVariantSortCustom less;
  322. less.obj = p_obj;
  323. less.func = p_function;
  324. return bisect(_p->array, p_value, p_before, less);
  325. }
  326. Array &Array::invert() {
  327. _p->array.invert();
  328. return *this;
  329. }
  330. void Array::push_front(const Variant &p_value) {
  331. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_front"));
  332. _p->array.insert(0, p_value);
  333. }
  334. Variant Array::pop_back() {
  335. if (!_p->array.empty()) {
  336. int n = _p->array.size() - 1;
  337. Variant ret = _p->array.get(n);
  338. _p->array.resize(n);
  339. return ret;
  340. }
  341. return Variant();
  342. }
  343. Variant Array::pop_front() {
  344. if (!_p->array.empty()) {
  345. Variant ret = _p->array.get(0);
  346. _p->array.remove(0);
  347. return ret;
  348. }
  349. return Variant();
  350. }
  351. Variant Array::min() const {
  352. Variant minval;
  353. for (int i = 0; i < size(); i++) {
  354. if (i == 0) {
  355. minval = get(i);
  356. } else {
  357. bool valid;
  358. Variant ret;
  359. Variant test = get(i);
  360. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  361. if (!valid) {
  362. return Variant(); //not a valid comparison
  363. }
  364. if (bool(ret)) {
  365. //is less
  366. minval = test;
  367. }
  368. }
  369. }
  370. return minval;
  371. }
  372. Variant Array::max() const {
  373. Variant maxval;
  374. for (int i = 0; i < size(); i++) {
  375. if (i == 0) {
  376. maxval = get(i);
  377. } else {
  378. bool valid;
  379. Variant ret;
  380. Variant test = get(i);
  381. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  382. if (!valid) {
  383. return Variant(); //not a valid comparison
  384. }
  385. if (bool(ret)) {
  386. //is less
  387. maxval = test;
  388. }
  389. }
  390. }
  391. return maxval;
  392. }
  393. const void *Array::id() const {
  394. return _p->array.ptr();
  395. }
  396. Array::Array(const Array &p_from, uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  397. _p = memnew(ArrayPrivate);
  398. _p->refcount.init();
  399. set_typed(p_type, p_class_name, p_script);
  400. _assign(p_from);
  401. }
  402. void Array::set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  403. ERR_FAIL_COND_MSG(_p->array.size() > 0, "Type can only be set when array is empty.");
  404. ERR_FAIL_COND_MSG(_p->refcount.get() > 1, "Type can only be set when array has no more than one user.");
  405. ERR_FAIL_COND_MSG(_p->typed.type != Variant::NIL, "Type can only be set once.");
  406. ERR_FAIL_COND_MSG(p_class_name != StringName() && p_type != Variant::OBJECT, "Class names can only be set for type OBJECT");
  407. Ref<Script> script = p_script;
  408. ERR_FAIL_COND_MSG(script.is_valid() && p_class_name == StringName(), "Script class can only be set together with base class name");
  409. _p->typed.type = Variant::Type(p_type);
  410. _p->typed.class_name = p_class_name;
  411. _p->typed.script = script;
  412. _p->typed.where = "TypedArray";
  413. }
  414. Array::Array(const Array &p_from) {
  415. _p = nullptr;
  416. _ref(p_from);
  417. }
  418. Array::Array() {
  419. _p = memnew(ArrayPrivate);
  420. _p->refcount.init();
  421. }
  422. Array::~Array() {
  423. _unref();
  424. }