array2d.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. #include "pocketpy/interpreter/array2d.h"
  2. #include "pocketpy/interpreter/vm.h"
  3. #include "pocketpy/pocketpy.h"
  4. #include <limits.h>
  5. static bool c11_array2d_like_is_valid(c11_array2d_like* self, unsigned int col, unsigned int row) {
  6. return col < self->n_cols && row < self->n_rows;
  7. }
  8. static py_Ref c11_array2d__get(c11_array2d* self, int col, int row) {
  9. return self->data + row * self->header.n_cols + col;
  10. }
  11. static bool c11_array2d__set(c11_array2d* self, int col, int row, py_Ref value) {
  12. self->data[row * self->header.n_cols + col] = *value;
  13. return true;
  14. }
  15. c11_array2d* py_newarray2d(py_OutRef out, int n_cols, int n_rows) {
  16. int numel = n_cols * n_rows;
  17. c11_array2d* ud = py_newobject(out, tp_array2d, numel, sizeof(c11_array2d));
  18. ud->header.n_cols = n_cols;
  19. ud->header.n_rows = n_rows;
  20. ud->header.numel = numel;
  21. ud->header.f_get = (py_Ref(*)(c11_array2d_like*, int, int))c11_array2d__get;
  22. ud->header.f_set = (bool (*)(c11_array2d_like*, int, int, py_Ref))c11_array2d__set;
  23. ud->data = py_getslot(out, 0);
  24. return ud;
  25. }
  26. /* array2d_like bindings */
  27. static bool array2d_like_n_cols(int argc, py_Ref argv) {
  28. PY_CHECK_ARGC(1);
  29. c11_array2d_like* self = py_touserdata(argv);
  30. py_newint(py_retval(), self->n_cols);
  31. return true;
  32. }
  33. static bool array2d_like_n_rows(int argc, py_Ref argv) {
  34. PY_CHECK_ARGC(1);
  35. c11_array2d_like* self = py_touserdata(argv);
  36. py_newint(py_retval(), self->n_rows);
  37. return true;
  38. }
  39. static bool array2d_like_shape(int argc, py_Ref argv) {
  40. PY_CHECK_ARGC(1);
  41. c11_array2d_like* self = py_touserdata(argv);
  42. c11_vec2i shape;
  43. shape.x = self->n_cols;
  44. shape.y = self->n_rows;
  45. py_newvec2i(py_retval(), shape);
  46. return true;
  47. }
  48. static bool array2d_like_numel(int argc, py_Ref argv) {
  49. PY_CHECK_ARGC(1);
  50. c11_array2d_like* self = py_touserdata(argv);
  51. py_newint(py_retval(), self->numel);
  52. return true;
  53. }
  54. static bool array2d_like_is_valid(int argc, py_Ref argv) {
  55. c11_array2d_like* self = py_touserdata(argv);
  56. int col, row;
  57. if(argc == 2) {
  58. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  59. c11_vec2i pos = py_tovec2i(py_arg(1));
  60. col = pos.x;
  61. row = pos.y;
  62. } else if(argc == 3) {
  63. PY_CHECK_ARG_TYPE(1, tp_int);
  64. PY_CHECK_ARG_TYPE(2, tp_int);
  65. col = py_toint(py_arg(1));
  66. row = py_toint(py_arg(2));
  67. } else {
  68. return TypeError("is_valid() expected 2 or 3 arguments");
  69. }
  70. py_newbool(py_retval(), c11_array2d_like_is_valid(self, col, row));
  71. return true;
  72. }
  73. static bool array2d_like_get(int argc, py_Ref argv) {
  74. PY_CHECK_ARG_TYPE(1, tp_int);
  75. PY_CHECK_ARG_TYPE(2, tp_int);
  76. py_Ref default_;
  77. c11_array2d_like* self = py_touserdata(argv);
  78. if(argc == 3) {
  79. default_ = py_None();
  80. } else if(argc == 4) {
  81. default_ = py_arg(3);
  82. } else {
  83. return TypeError("get() expected 2 or 3 arguments");
  84. }
  85. int col = py_toint(py_arg(1));
  86. int row = py_toint(py_arg(2));
  87. if(c11_array2d_like_is_valid(self, col, row)) {
  88. py_assign(py_retval(), self->f_get(self, col, row));
  89. } else {
  90. py_assign(py_retval(), default_);
  91. }
  92. return true;
  93. }
  94. static bool array2d_like_render(int argc, py_Ref argv) {
  95. PY_CHECK_ARGC(1);
  96. c11_sbuf buf;
  97. c11_sbuf__ctor(&buf);
  98. c11_array2d_like* self = py_touserdata(argv);
  99. for(int j = 0; j < self->n_rows; j++) {
  100. for(int i = 0; i < self->n_cols; i++) {
  101. py_Ref item = self->f_get(self, i, j);
  102. if(!py_str(item)) return false;
  103. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  104. }
  105. if(j < self->n_rows - 1) c11_sbuf__write_char(&buf, '\n');
  106. }
  107. c11_sbuf__py_submit(&buf, py_retval());
  108. return true;
  109. }
  110. static bool array2d_like_all(int argc, py_Ref argv) {
  111. PY_CHECK_ARGC(1);
  112. c11_array2d_like* self = py_touserdata(argv);
  113. for(int j = 0; j < self->n_rows; j++) {
  114. for(int i = 0; i < self->n_cols; i++) {
  115. py_Ref item = self->f_get(self, i, j);
  116. if(!py_checkbool(item)) return false;
  117. if(!py_tobool(item)) {
  118. py_newbool(py_retval(), false);
  119. return true;
  120. }
  121. }
  122. }
  123. py_newbool(py_retval(), true);
  124. return true;
  125. }
  126. static bool array2d_like_any(int argc, py_Ref argv) {
  127. PY_CHECK_ARGC(1);
  128. c11_array2d_like* self = py_touserdata(argv);
  129. for(int j = 0; j < self->n_rows; j++) {
  130. for(int i = 0; i < self->n_cols; i++) {
  131. py_Ref item = self->f_get(self, i, j);
  132. if(!py_checkbool(item)) return false;
  133. if(py_tobool(item)) {
  134. py_newbool(py_retval(), true);
  135. return true;
  136. }
  137. }
  138. }
  139. py_newbool(py_retval(), false);
  140. return true;
  141. }
  142. static bool array2d_like_map(int argc, py_Ref argv) {
  143. // def map(self, f: Callable[[T], Any]) -> 'array2d': ...
  144. PY_CHECK_ARGC(2);
  145. c11_array2d_like* self = py_touserdata(argv);
  146. py_Ref f = py_arg(1);
  147. c11_array2d* res = py_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  148. for(int j = 0; j < self->n_rows; j++) {
  149. for(int i = 0; i < self->n_cols; i++) {
  150. py_Ref item = self->f_get(self, i, j);
  151. if(!py_call(f, 1, item)) return false;
  152. res->data[j * self->n_cols + i] = *py_retval();
  153. }
  154. }
  155. py_assign(py_retval(), py_peek(-1));
  156. py_pop();
  157. return true;
  158. }
  159. static bool array2d_like_apply(int argc, py_Ref argv) {
  160. // def apply_(self, f: Callable[[T], T]) -> None: ...
  161. PY_CHECK_ARGC(2);
  162. c11_array2d_like* self = py_touserdata(argv);
  163. py_Ref f = py_arg(1);
  164. for(int j = 0; j < self->n_rows; j++) {
  165. for(int i = 0; i < self->n_cols; i++) {
  166. py_Ref item = self->f_get(self, i, j);
  167. if(!py_call(f, 1, item)) return false;
  168. bool ok = self->f_set(self, i, j, py_retval());
  169. if(!ok) return false;
  170. }
  171. }
  172. py_newnone(py_retval());
  173. return true;
  174. }
  175. static bool array2d_like_copy(int argc, py_Ref argv) {
  176. // def copy(self) -> 'array2d': ...
  177. PY_CHECK_ARGC(1);
  178. c11_array2d_like* self = py_touserdata(argv);
  179. c11_array2d* res = py_newarray2d(py_retval(), self->n_cols, self->n_rows);
  180. for(int j = 0; j < self->n_rows; j++) {
  181. for(int i = 0; i < self->n_cols; i++) {
  182. py_Ref item = self->f_get(self, i, j);
  183. res->data[j * self->n_cols + i] = *item;
  184. }
  185. }
  186. return true;
  187. }
  188. static bool array2d_like_tolist(int argc, py_Ref argv) {
  189. PY_CHECK_ARGC(1);
  190. c11_array2d_like* self = py_touserdata(argv);
  191. py_newlistn(py_retval(), self->n_rows);
  192. for(int j = 0; j < self->n_rows; j++) {
  193. py_Ref row_j = py_list_getitem(py_retval(), j);
  194. py_newlistn(row_j, self->n_cols);
  195. for(int i = 0; i < self->n_cols; i++) {
  196. py_Ref item = self->f_get(self, i, j);
  197. py_list_setitem(row_j, i, item);
  198. }
  199. }
  200. return true;
  201. }
  202. static bool _check_same_shape(int colA, int rowA, int colB, int rowB) {
  203. if(colA != colB || rowA != rowB) {
  204. const char* fmt = "expected the same shape: (%d, %d) != (%d, %d)";
  205. return ValueError(fmt, colA, rowA, colB, rowB);
  206. }
  207. return true;
  208. }
  209. static bool _array2d_like_check_same_shape(c11_array2d_like* self, c11_array2d_like* other) {
  210. return _check_same_shape(self->n_cols, self->n_rows, other->n_cols, other->n_rows);
  211. }
  212. static bool array2d_like__eq__(int argc, py_Ref argv) {
  213. PY_CHECK_ARGC(2);
  214. c11_array2d_like* self = py_touserdata(argv);
  215. c11_array2d* res = py_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  216. if(py_isinstance(py_arg(1), tp_array2d_like)) {
  217. c11_array2d_like* other = py_touserdata(py_arg(1));
  218. if(!_array2d_like_check_same_shape(self, other)) return false;
  219. for(int j = 0; j < self->n_rows; j++) {
  220. for(int i = 0; i < self->n_cols; i++) {
  221. py_Ref lhs = self->f_get(self, i, j);
  222. py_Ref rhs = other->f_get(other, i, j);
  223. int code = py_equal(lhs, rhs);
  224. if(code == -1) return false;
  225. py_newbool(&res->data[j * self->n_cols + i], (bool)code);
  226. }
  227. }
  228. } else {
  229. // broadcast
  230. for(int j = 0; j < self->n_rows; j++) {
  231. for(int i = 0; i < self->n_cols; i++) {
  232. py_Ref lhs = self->f_get(self, i, j);
  233. int code = py_equal(lhs, py_arg(1));
  234. if(code == -1) return false;
  235. py_newbool(&res->data[j * self->n_cols + i], (bool)code);
  236. }
  237. }
  238. }
  239. py_assign(py_retval(), py_peek(-1));
  240. py_pop();
  241. return true;
  242. }
  243. static bool array2d_like__ne__(int argc, py_Ref argv) {
  244. bool ok = array2d_like__eq__(argc, argv);
  245. if(!ok) return false;
  246. assert(py_istype(py_retval(), tp_array2d));
  247. c11_array2d* res = py_touserdata(py_retval());
  248. py_TValue* data = res->data;
  249. for(int i = 0; i < res->header.numel; i++) {
  250. assert(py_isbool(&data[i]));
  251. py_newbool(&data[i], !py_tobool(&data[i]));
  252. }
  253. return true;
  254. }
  255. static bool array2d_like__iter__(int argc, py_Ref argv) {
  256. PY_CHECK_ARGC(1);
  257. c11_array2d_like* self = py_touserdata(argv);
  258. c11_array2d_like_iterator* ud =
  259. py_newobject(py_retval(), tp_array2d_like_iterator, 1, sizeof(c11_array2d_like_iterator));
  260. py_setslot(py_retval(), 0, argv); // keep the array alive
  261. ud->array = self;
  262. ud->j = 0;
  263. ud->i = 0;
  264. return true;
  265. }
  266. static bool array2d_like__repr__(int argc, py_Ref argv) {
  267. PY_CHECK_ARGC(1);
  268. c11_array2d_like* self = py_touserdata(argv);
  269. char buf[256];
  270. snprintf(buf,
  271. sizeof(buf),
  272. "%s(%d, %d)",
  273. py_tpname(py_typeof(argv)),
  274. self->n_cols,
  275. self->n_rows);
  276. py_newstr(py_retval(), buf);
  277. return true;
  278. }
  279. #define HANDLE_SLICE() \
  280. int start_col, stop_col, step_col; \
  281. int start_row, stop_row, step_row; \
  282. if(!pk__parse_int_slice(x, self->n_cols, &start_col, &stop_col, &step_col)) return false; \
  283. if(!pk__parse_int_slice(y, self->n_rows, &start_row, &stop_row, &step_row)) return false; \
  284. if(step_col != 1 || step_row != 1) return ValueError("slice step must be 1"); \
  285. int slice_width = stop_col - start_col; \
  286. int slice_height = stop_row - start_row;
  287. static bool _array2d_like_IndexError(c11_array2d_like* self, int col, int row) {
  288. return IndexError("(%d, %d) is not a valid index of array2d_like(%d, %d)",
  289. col,
  290. row,
  291. self->n_cols,
  292. self->n_rows);
  293. }
  294. static py_Ref c11_array2d_view__get(c11_array2d_view* self, int col, int row) {
  295. return self->f_get(self->ctx, col + self->origin.x, row + self->origin.y);
  296. }
  297. static bool c11_array2d_view__set(c11_array2d_view* self, int col, int row, py_Ref value) {
  298. return self->f_set(self->ctx, col + self->origin.x, row + self->origin.y, value);
  299. }
  300. static c11_array2d_view* _array2d_view__new(py_OutRef out,
  301. py_Ref keepalive,
  302. int start_col,
  303. int start_row,
  304. int width,
  305. int height) {
  306. c11_array2d_view* res = py_newobject(out, tp_array2d_view, 1, sizeof(c11_array2d_view));
  307. if(width <= 0 || height <= 0) {
  308. ValueError("width and height must be positive");
  309. return NULL;
  310. }
  311. res->header.n_cols = width;
  312. res->header.n_rows = height;
  313. res->header.numel = width * height;
  314. res->header.f_get = (py_Ref(*)(c11_array2d_like*, int, int))c11_array2d_view__get;
  315. res->header.f_set = (bool (*)(c11_array2d_like*, int, int, py_Ref))c11_array2d_view__set;
  316. res->origin.x = start_col;
  317. res->origin.y = start_row;
  318. py_setslot(out, 0, keepalive);
  319. return res;
  320. }
  321. static bool _array2d_view(py_OutRef out,
  322. py_Ref keepalive,
  323. c11_array2d_like* array,
  324. int start_col,
  325. int start_row,
  326. int width,
  327. int height) {
  328. c11_array2d_view* res = _array2d_view__new(out, keepalive, start_col, start_row, width, height);
  329. if(res == NULL) return false;
  330. res->ctx = array;
  331. res->f_get = (py_Ref(*)(void*, int, int))array->f_get;
  332. res->f_set = (bool (*)(void*, int, int, py_Ref))array->f_set;
  333. return true;
  334. }
  335. static bool _chunked_array2d_view(py_OutRef out,
  336. py_Ref keepalive,
  337. c11_chunked_array2d* array,
  338. int start_col,
  339. int start_row,
  340. int width,
  341. int height) {
  342. c11_array2d_view* res = _array2d_view__new(out, keepalive, start_col, start_row, width, height);
  343. if(res == NULL) return false;
  344. res->ctx = array;
  345. res->f_get = (py_Ref(*)(void*, int, int))c11_chunked_array2d__get;
  346. res->f_set = (bool (*)(void*, int, int, py_Ref))c11_chunked_array2d__set;
  347. return true;
  348. }
  349. static bool array2d_like__getitem__(int argc, py_Ref argv) {
  350. PY_CHECK_ARGC(2);
  351. c11_array2d_like* self = py_touserdata(argv);
  352. if(argv[1].type == tp_vec2i) {
  353. c11_vec2i pos = py_tovec2i(&argv[1]);
  354. if(c11_array2d_like_is_valid(self, pos.x, pos.y)) {
  355. py_assign(py_retval(), self->f_get(self, pos.x, pos.y));
  356. return true;
  357. }
  358. return _array2d_like_IndexError(self, pos.x, pos.y);
  359. }
  360. if(py_isinstance(&argv[1], tp_array2d_like)) {
  361. c11_array2d_like* mask = py_touserdata(&argv[1]);
  362. if(!_array2d_like_check_same_shape(self, mask)) return false;
  363. py_newlist(py_retval());
  364. for(int j = 0; j < self->n_rows; j++) {
  365. for(int i = 0; i < self->n_cols; i++) {
  366. py_Ref item = self->f_get(self, i, j);
  367. py_Ref cond = mask->f_get(mask, i, j);
  368. if(!py_checkbool(cond)) return false;
  369. if(py_tobool(cond)) py_list_append(py_retval(), item);
  370. }
  371. }
  372. return true;
  373. }
  374. PY_CHECK_ARG_TYPE(1, tp_tuple);
  375. if(py_tuple_len(&argv[1]) != 2) return TypeError("expected a tuple of 2 elements");
  376. py_Ref x = py_tuple_getitem(&argv[1], 0);
  377. py_Ref y = py_tuple_getitem(&argv[1], 1);
  378. if(py_isint(x) && py_isint(y)) {
  379. int col = py_toint(x);
  380. int row = py_toint(y);
  381. if(c11_array2d_like_is_valid(self, col, row)) {
  382. py_assign(py_retval(), self->f_get(self, col, row));
  383. return true;
  384. }
  385. return _array2d_like_IndexError(self, col, row);
  386. }
  387. if(py_istype(x, tp_slice) && py_istype(y, tp_slice)) {
  388. HANDLE_SLICE();
  389. return _array2d_view(py_retval(),
  390. argv,
  391. self,
  392. start_col,
  393. start_row,
  394. slice_width,
  395. slice_height);
  396. }
  397. return TypeError("expected `tuple[int, int]` or `tuple[slice, slice]`");
  398. }
  399. static bool array2d_like__setitem__(int argc, py_Ref argv) {
  400. PY_CHECK_ARGC(3);
  401. c11_array2d_like* self = py_touserdata(argv);
  402. py_Ref value = &argv[2];
  403. if(argv[1].type == tp_vec2i) {
  404. c11_vec2i pos = py_tovec2i(&argv[1]);
  405. if(c11_array2d_like_is_valid(self, pos.x, pos.y)) {
  406. bool ok = self->f_set(self, pos.x, pos.y, value);
  407. if(!ok) return false;
  408. py_newnone(py_retval());
  409. return true;
  410. }
  411. return _array2d_like_IndexError(self, pos.x, pos.y);
  412. }
  413. if(py_isinstance(&argv[1], tp_array2d_like)) {
  414. c11_array2d_like* mask = py_touserdata(&argv[1]);
  415. if(!_array2d_like_check_same_shape(self, mask)) return false;
  416. for(int j = 0; j < self->n_rows; j++) {
  417. for(int i = 0; i < self->n_cols; i++) {
  418. py_Ref cond = mask->f_get(mask, i, j);
  419. if(!py_checkbool(cond)) return false;
  420. if(py_tobool(cond)) {
  421. bool ok = self->f_set(self, i, j, value);
  422. if(!ok) return false;
  423. }
  424. }
  425. }
  426. py_newnone(py_retval());
  427. return true;
  428. }
  429. PY_CHECK_ARG_TYPE(1, tp_tuple);
  430. if(py_tuple_len(py_arg(1)) != 2) return TypeError("expected a tuple of 2 elements");
  431. py_Ref x = py_tuple_getitem(py_arg(1), 0);
  432. py_Ref y = py_tuple_getitem(py_arg(1), 1);
  433. if(py_isint(x) && py_isint(y)) {
  434. int col = py_toint(x);
  435. int row = py_toint(y);
  436. if(c11_array2d_like_is_valid(self, col, row)) {
  437. bool ok = self->f_set(self, col, row, value);
  438. if(!ok) return false;
  439. py_newnone(py_retval());
  440. return true;
  441. }
  442. return _array2d_like_IndexError(self, col, row);
  443. }
  444. if(py_istype(x, tp_slice) && py_istype(y, tp_slice)) {
  445. HANDLE_SLICE();
  446. if(py_isinstance(value, tp_array2d_like)) {
  447. c11_array2d_like* values = py_touserdata(value);
  448. if(!_check_same_shape(slice_width, slice_height, values->n_cols, values->n_rows))
  449. return false;
  450. for(int j = 0; j < slice_height; j++) {
  451. for(int i = 0; i < slice_width; i++) {
  452. py_Ref item = values->f_get(values, i, j);
  453. bool ok = self->f_set(self, start_col + i, start_row + j, item);
  454. if(!ok) return false;
  455. }
  456. }
  457. } else {
  458. for(int j = 0; j < slice_height; j++) {
  459. for(int i = 0; i < slice_width; i++) {
  460. bool ok = self->f_set(self, start_col + i, start_row + j, value);
  461. if(!ok) return false;
  462. }
  463. }
  464. }
  465. py_newnone(py_retval());
  466. return true;
  467. }
  468. return TypeError("expected `tuple[int, int]` or `tuple[slice, slice]");
  469. }
  470. // count(self, value: T) -> int
  471. static bool array2d_like_count(int argc, py_Ref argv) {
  472. PY_CHECK_ARGC(2);
  473. c11_array2d_like* self = py_touserdata(argv);
  474. int count = 0;
  475. for(int j = 0; j < self->n_rows; j++) {
  476. for(int i = 0; i < self->n_cols; i++) {
  477. int code = py_equal(self->f_get(self, i, j), py_arg(1));
  478. if(code == -1) return false;
  479. count += code;
  480. }
  481. }
  482. py_newint(py_retval(), count);
  483. return true;
  484. }
  485. // get_bounding_rect(self, value: T) -> tuple[int, int, int, int]
  486. static bool array2d_like_get_bounding_rect(int argc, py_Ref argv) {
  487. PY_CHECK_ARGC(2);
  488. c11_array2d_like* self = py_touserdata(argv);
  489. py_Ref value = py_arg(1);
  490. int left = self->n_cols;
  491. int top = self->n_rows;
  492. int right = 0;
  493. int bottom = 0;
  494. for(int j = 0; j < self->n_rows; j++) {
  495. for(int i = 0; i < self->n_cols; i++) {
  496. py_Ref item = self->f_get(self, i, j);
  497. int res = py_equal(item, value);
  498. if(res == -1) return false;
  499. if(res == 1) {
  500. left = c11__min(left, i);
  501. top = c11__min(top, j);
  502. right = c11__max(right, i);
  503. bottom = c11__max(bottom, j);
  504. }
  505. }
  506. }
  507. int width = right - left + 1;
  508. int height = bottom - top + 1;
  509. if(width <= 0 || height <= 0) {
  510. return ValueError("value not found");
  511. } else {
  512. py_newtuple(py_retval(), 4);
  513. py_TValue* data = py_tuple_data(py_retval());
  514. py_newint(&data[0], left);
  515. py_newint(&data[1], top);
  516. py_newint(&data[2], width);
  517. py_newint(&data[3], height);
  518. }
  519. return true;
  520. }
  521. // count_neighbors(self, value: T, neighborhood: Neighborhood) -> array2d[int]
  522. static bool array2d_like_count_neighbors(int argc, py_Ref argv) {
  523. PY_CHECK_ARGC(3);
  524. c11_array2d_like* self = py_touserdata(argv);
  525. c11_array2d* res = py_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  526. py_Ref value = py_arg(1);
  527. const char* neighborhood = py_tostr(py_arg(2));
  528. const static c11_vec2i Moore[] = {
  529. {{-1, -1}},
  530. {{0, -1}},
  531. {{1, -1}},
  532. {{-1, 0}},
  533. {{1, 0}},
  534. {{-1, 1}},
  535. {{0, 1}},
  536. {{1, 1}},
  537. };
  538. const static c11_vec2i von_Neumann[] = {
  539. {{0, -1}},
  540. {{-1, 0}},
  541. {{1, 0}},
  542. {{0, 1}},
  543. };
  544. const c11_vec2i* offsets;
  545. int n_offsets;
  546. if(strcmp(neighborhood, "Moore") == 0) {
  547. offsets = Moore;
  548. n_offsets = c11__count_array(Moore);
  549. } else if(strcmp(neighborhood, "von Neumann") == 0) {
  550. offsets = von_Neumann;
  551. n_offsets = c11__count_array(von_Neumann);
  552. } else {
  553. return ValueError("neighborhood must be 'Moore' or 'von Neumann'");
  554. }
  555. for(int j = 0; j < self->n_rows; j++) {
  556. for(int i = 0; i < self->n_cols; i++) {
  557. py_i64 count = 0;
  558. for(int k = 0; k < n_offsets; k++) {
  559. int x = i + offsets[k].x;
  560. int y = j + offsets[k].y;
  561. if(x >= 0 && x < self->n_cols && y >= 0 && y < self->n_rows) {
  562. py_Ref item = self->f_get(self, x, y);
  563. int code = py_equal(item, value);
  564. if(code == -1) return false;
  565. count += code;
  566. }
  567. }
  568. py_newint(c11_array2d__get(res, i, j), count);
  569. }
  570. }
  571. py_assign(py_retval(), py_peek(-1));
  572. py_pop();
  573. return true;
  574. }
  575. // convolve(self: array2d_like[int], kernel: array2d_like[int], padding: int) -> array2d[int]
  576. static bool array2d_like_convolve(int argc, py_Ref argv) {
  577. PY_CHECK_ARGC(3);
  578. if(!py_checkinstance(&argv[1], tp_array2d_like)) return false;
  579. PY_CHECK_ARG_TYPE(2, tp_int);
  580. c11_array2d_like* self = py_touserdata(&argv[0]);
  581. c11_array2d_like* kernel = py_touserdata(&argv[1]);
  582. int padding = py_toint(py_arg(2));
  583. if(kernel->n_cols != kernel->n_rows) return ValueError("kernel must be square");
  584. int ksize = kernel->n_cols;
  585. if(ksize % 2 == 0) return ValueError("kernel size must be odd");
  586. int ksize_half = ksize / 2;
  587. c11_array2d* res = py_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  588. for(int j = 0; j < self->n_rows; j++) {
  589. for(int i = 0; i < self->n_cols; i++) {
  590. py_i64 sum = 0;
  591. for(int jj = 0; jj < ksize; jj++) {
  592. for(int ii = 0; ii < ksize; ii++) {
  593. int x = i + ii - ksize_half;
  594. int y = j + jj - ksize_half;
  595. py_i64 _0, _1;
  596. if(x < 0 || x >= self->n_cols || y < 0 || y >= self->n_rows) {
  597. _0 = padding;
  598. } else {
  599. py_Ref item = self->f_get(self, x, y);
  600. if(!py_checkint(item)) return false;
  601. _0 = py_toint(item);
  602. }
  603. py_Ref kitem = kernel->f_get(kernel, ii, jj);
  604. if(!py_checkint(kitem)) return false;
  605. _1 = py_toint(kitem);
  606. sum += _0 * _1;
  607. }
  608. }
  609. py_newint(c11_array2d__get(res, i, j), sum);
  610. }
  611. }
  612. py_assign(py_retval(), py_peek(-1));
  613. py_pop();
  614. return true;
  615. }
  616. #undef HANDLE_SLICE
  617. static void register_array2d_like(py_Ref mod) {
  618. py_Type type = py_newtype("array2d_like", tp_object, mod, NULL);
  619. assert(type == tp_array2d_like);
  620. py_bindproperty(type, "n_cols", array2d_like_n_cols, NULL);
  621. py_bindproperty(type, "n_rows", array2d_like_n_rows, NULL);
  622. py_bindproperty(type, "width", array2d_like_n_cols, NULL);
  623. py_bindproperty(type, "height", array2d_like_n_rows, NULL);
  624. py_bindproperty(type, "shape", array2d_like_shape, NULL);
  625. py_bindproperty(type, "numel", array2d_like_numel, NULL);
  626. py_bindmethod(type, "is_valid", array2d_like_is_valid);
  627. py_bindmethod(type, "get", array2d_like_get);
  628. py_bindmethod(type, "render", array2d_like_render);
  629. py_bindmethod(type, "all", array2d_like_all);
  630. py_bindmethod(type, "any", array2d_like_any);
  631. py_bindmethod(type, "map", array2d_like_map);
  632. py_bindmethod(type, "apply", array2d_like_apply);
  633. py_bindmethod(type, "copy", array2d_like_copy);
  634. py_bindmethod(type, "tolist", array2d_like_tolist);
  635. py_bindmagic(type, __eq__, array2d_like__eq__);
  636. py_bindmagic(type, __ne__, array2d_like__ne__);
  637. py_bindmagic(type, __iter__, array2d_like__iter__);
  638. py_bindmagic(type, __repr__, array2d_like__repr__);
  639. py_bindmagic(type, __getitem__, array2d_like__getitem__);
  640. py_bindmagic(type, __setitem__, array2d_like__setitem__);
  641. py_bindmethod(type, "count", array2d_like_count);
  642. py_bindmethod(type, "get_bounding_rect", array2d_like_get_bounding_rect);
  643. py_bindmethod(type, "count_neighbors", array2d_like_count_neighbors);
  644. py_bindmethod(type, "convolve", array2d_like_convolve);
  645. const char* scc =
  646. "\ndef get_connected_components(self, value: T, neighborhood: Neighborhood) -> tuple[array2d[int], int]:\n from collections import deque\n from linalg import vec2i\n\n DIRS = [vec2i.LEFT, vec2i.RIGHT, vec2i.UP, vec2i.DOWN]\n assert neighborhood in ['Moore', 'von Neumann']\n\n if neighborhood == 'Moore':\n DIRS.extend([\n vec2i.LEFT+vec2i.UP,\n vec2i.RIGHT+vec2i.UP,\n vec2i.LEFT+vec2i.DOWN,\n vec2i.RIGHT+vec2i.DOWN\n ])\n\n visited = array2d[int](self.width, self.height, default=0)\n queue = deque()\n count = 0\n for y in range(self.height):\n for x in range(self.width):\n if visited[x, y] or self[x, y] != value:\n continue\n count += 1\n queue.append((x, y))\n visited[x, y] = count\n while queue:\n cx, cy = queue.popleft()\n for dx, dy in DIRS:\n nx, ny = cx+dx, cy+dy\n if self.is_valid(nx, ny) and not visited[nx, ny] and self[nx, ny] == value:\n queue.append((nx, ny))\n visited[nx, ny] = count\n return visited, count\n\narray2d_like.get_connected_components = get_connected_components\ndel get_connected_components\n";
  647. if(!py_exec(scc, "array2d.py", EXEC_MODE, mod)) {
  648. py_printexc();
  649. c11__abort("failed to execute array2d.py");
  650. }
  651. }
  652. static bool array2d_like_iterator__next__(int argc, py_Ref argv) {
  653. PY_CHECK_ARGC(1);
  654. c11_array2d_like_iterator* self = py_touserdata(argv);
  655. if(self->j >= self->array->n_rows) return StopIteration();
  656. py_newtuple(py_retval(), 2);
  657. py_TValue* data = py_tuple_data(py_retval());
  658. py_newvec2i(&data[0],
  659. (c11_vec2i){
  660. {self->i, self->j}
  661. });
  662. py_assign(&data[1], self->array->f_get(self->array, self->i, self->j));
  663. self->i++;
  664. if(self->i >= self->array->n_cols) {
  665. self->i = 0;
  666. self->j++;
  667. }
  668. return true;
  669. }
  670. static void register_array2d_like_iterator(py_Ref mod) {
  671. py_Type type = py_newtype("array2d_like_iterator", tp_object, mod, NULL);
  672. assert(type == tp_array2d_like_iterator);
  673. py_bindmagic(type, __iter__, pk_wrapper__self);
  674. py_bindmagic(type, __next__, array2d_like_iterator__next__);
  675. }
  676. static bool array2d__new__(int argc, py_Ref argv) {
  677. // __new__(cls, n_cols: int, n_rows: int, default: Callable[[vec2i], T] = None)
  678. py_Ref default_ = py_arg(3);
  679. PY_CHECK_ARG_TYPE(0, tp_type);
  680. PY_CHECK_ARG_TYPE(1, tp_int);
  681. PY_CHECK_ARG_TYPE(2, tp_int);
  682. int n_cols = argv[1]._i64;
  683. int n_rows = argv[2]._i64;
  684. if(n_cols <= 0 || n_rows <= 0) return ValueError("array2d() expected positive dimensions");
  685. c11_array2d* ud = py_newarray2d(py_pushtmp(), n_cols, n_rows);
  686. // setup initial values
  687. if(py_callable(default_)) {
  688. for(int j = 0; j < n_rows; j++) {
  689. for(int i = 0; i < n_cols; i++) {
  690. py_TValue tmp;
  691. py_newvec2i(&tmp,
  692. (c11_vec2i){
  693. {i, j}
  694. });
  695. if(!py_call(default_, 1, &tmp)) return false;
  696. ud->data[j * n_cols + i] = *py_retval();
  697. }
  698. }
  699. } else {
  700. for(int i = 0; i < ud->header.numel; i++) {
  701. ud->data[i] = *default_;
  702. }
  703. }
  704. py_assign(py_retval(), py_peek(-1));
  705. py_pop();
  706. return true;
  707. }
  708. // fromlist(data: list[list[T]]) -> array2d[T]
  709. static bool array2d_fromlist_STATIC(int argc, py_Ref argv) {
  710. PY_CHECK_ARGC(1);
  711. if(!py_checktype(argv, tp_list)) return false;
  712. int n_rows = py_list_len(argv);
  713. if(n_rows == 0) return ValueError("fromlist() expected a non-empty list");
  714. int n_cols = -1;
  715. for(int j = 0; j < n_rows; j++) {
  716. py_Ref row_j = py_list_getitem(argv, j);
  717. if(!py_checktype(row_j, tp_list)) return false;
  718. int n_cols_j = py_list_len(row_j);
  719. if(n_cols == -1) {
  720. if(n_cols_j == 0) return ValueError("fromlist() expected a non-empty list");
  721. n_cols = n_cols_j;
  722. } else if(n_cols != n_cols_j) {
  723. return ValueError("fromlist() expected a list of lists with the same length");
  724. }
  725. }
  726. c11_array2d* res = py_newarray2d(py_retval(), n_cols, n_rows);
  727. for(int j = 0; j < n_rows; j++) {
  728. py_Ref row_j = py_list_getitem(argv, j);
  729. for(int i = 0; i < n_cols; i++) {
  730. c11_array2d__set(res, i, j, py_list_getitem(row_j, i));
  731. }
  732. }
  733. return true;
  734. }
  735. static void register_array2d(py_Ref mod) {
  736. py_Type type = py_newtype("array2d", tp_array2d_like, mod, NULL);
  737. assert(type == tp_array2d);
  738. py_bind(py_tpobject(type),
  739. "__new__(cls, n_cols: int, n_rows: int, default=None)",
  740. array2d__new__);
  741. py_bindstaticmethod(type, "fromlist", array2d_fromlist_STATIC);
  742. }
  743. static bool array2d_view_origin(int argc, py_Ref argv) {
  744. PY_CHECK_ARGC(1);
  745. c11_array2d_view* self = py_touserdata(argv);
  746. py_newvec2i(py_retval(), self->origin);
  747. return true;
  748. }
  749. static void register_array2d_view(py_Ref mod) {
  750. py_Type type = py_newtype("array2d_view", tp_array2d_like, mod, NULL);
  751. assert(type == tp_array2d_view);
  752. py_bindproperty(type, "origin", array2d_view_origin, NULL);
  753. }
  754. /* chunked_array2d */
  755. #define SMALLMAP_T__SOURCE
  756. #define K c11_vec2i
  757. #define V py_TValue*
  758. #define NAME c11_chunked_array2d_chunks
  759. #define less(a, b) (a._i64 < b._i64)
  760. #define equal(a, b) (a._i64 == b._i64)
  761. #include "pocketpy/xmacros/smallmap.h"
  762. #undef SMALLMAP_T__SOURCE
  763. static py_TValue* c11_chunked_array2d__new_chunk(c11_chunked_array2d* self, c11_vec2i pos) {
  764. #ifndef NDEBUG
  765. bool exists = c11_chunked_array2d_chunks__contains(&self->chunks, pos);
  766. assert(!exists);
  767. #endif
  768. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  769. py_TValue* data = PK_MALLOC(sizeof(py_TValue) * chunk_numel);
  770. if(!py_isnone(&self->context_builder)) {
  771. py_newvec2i(&data[0], pos);
  772. bool ok = py_call(&self->context_builder, 1, &data[0]);
  773. if(!ok) return NULL;
  774. data[0] = *py_retval();
  775. } else {
  776. data[0] = *py_None();
  777. }
  778. memset(&data[1], 0, sizeof(py_TValue) * (chunk_numel - 1));
  779. c11_chunked_array2d_chunks__set(&self->chunks, pos, data);
  780. self->last_visited.key = pos;
  781. self->last_visited.value = data;
  782. return data;
  783. }
  784. static void c11_chunked_array2d__world_to_chunk(c11_chunked_array2d* self,
  785. int col,
  786. int row,
  787. c11_vec2i* chunk_pos,
  788. c11_vec2i* local_pos) {
  789. if(col >= 0) {
  790. chunk_pos->x = col >> self->chunk_size_log2;
  791. local_pos->x = col & self->chunk_size_mask;
  792. } else {
  793. chunk_pos->x = -((-col) >> self->chunk_size_log2);
  794. local_pos->x = (-col) & self->chunk_size_mask;
  795. }
  796. if(row >= 0) {
  797. chunk_pos->y = row >> self->chunk_size_log2;
  798. local_pos->y = row & self->chunk_size_mask;
  799. } else {
  800. chunk_pos->y = -((-row) >> self->chunk_size_log2);
  801. local_pos->y = (-row) & self->chunk_size_mask;
  802. }
  803. }
  804. static py_TValue* c11_chunked_array2d__parse_col_row(c11_chunked_array2d* self,
  805. int col,
  806. int row,
  807. c11_vec2i* chunk_pos,
  808. c11_vec2i* local_pos) {
  809. c11_chunked_array2d__world_to_chunk(self, col, row, chunk_pos, local_pos);
  810. py_TValue* data;
  811. if(self->last_visited.value != NULL && chunk_pos->_i64 == self->last_visited.key._i64) {
  812. data = self->last_visited.value;
  813. } else {
  814. data = c11_chunked_array2d_chunks__get(&self->chunks, *chunk_pos, NULL);
  815. }
  816. if(data != NULL) {
  817. self->last_visited.key = *chunk_pos;
  818. self->last_visited.value = data;
  819. }
  820. return data;
  821. }
  822. py_Ref c11_chunked_array2d__get(c11_chunked_array2d* self, int col, int row) {
  823. c11_vec2i chunk_pos, local_pos;
  824. py_TValue* data = c11_chunked_array2d__parse_col_row(self, col, row, &chunk_pos, &local_pos);
  825. if(data == NULL) return &self->default_T;
  826. py_Ref retval = &data[1 + local_pos.y * self->chunk_size + local_pos.x];
  827. if(py_isnil(retval)) return &self->default_T;
  828. return retval;
  829. }
  830. bool c11_chunked_array2d__set(c11_chunked_array2d* self, int col, int row, py_Ref value) {
  831. c11_vec2i chunk_pos, local_pos;
  832. py_TValue* data = c11_chunked_array2d__parse_col_row(self, col, row, &chunk_pos, &local_pos);
  833. if(data == NULL) {
  834. data = c11_chunked_array2d__new_chunk(self, chunk_pos);
  835. if(data == NULL) return false;
  836. }
  837. data[1 + local_pos.y * self->chunk_size + local_pos.x] = *value;
  838. return true;
  839. }
  840. static void c11_chunked_array2d__del(c11_chunked_array2d* self, int col, int row) {
  841. c11_vec2i chunk_pos, local_pos;
  842. py_TValue* data = c11_chunked_array2d__parse_col_row(self, col, row, &chunk_pos, &local_pos);
  843. if(data != NULL) data[1 + local_pos.y * self->chunk_size + local_pos.x] = *py_NIL();
  844. }
  845. static bool chunked_array2d__new__(int argc, py_Ref argv) {
  846. py_Type cls = py_totype(argv);
  847. py_newobject(py_retval(), cls, 0, sizeof(c11_chunked_array2d));
  848. return true;
  849. }
  850. static bool chunked_array2d__init__(int argc, py_Ref argv) {
  851. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  852. PY_CHECK_ARG_TYPE(1, tp_int);
  853. int chunk_size = py_toint(&argv[1]);
  854. self->default_T = argv[2];
  855. self->context_builder = argv[3];
  856. c11_chunked_array2d_chunks__ctor(&self->chunks);
  857. self->chunk_size = chunk_size;
  858. switch(chunk_size) {
  859. case 2: self->chunk_size_log2 = 1; break;
  860. case 4: self->chunk_size_log2 = 2; break;
  861. case 8: self->chunk_size_log2 = 3; break;
  862. case 16: self->chunk_size_log2 = 4; break;
  863. case 32: self->chunk_size_log2 = 5; break;
  864. case 64: self->chunk_size_log2 = 6; break;
  865. case 128: self->chunk_size_log2 = 7; break;
  866. case 256: self->chunk_size_log2 = 8; break;
  867. case 512: self->chunk_size_log2 = 9; break;
  868. case 1024: self->chunk_size_log2 = 10; break;
  869. case 2048: self->chunk_size_log2 = 11; break;
  870. case 4096: self->chunk_size_log2 = 12; break;
  871. default: return ValueError("invalid chunk_size: %d", chunk_size);
  872. }
  873. self->chunk_size_mask = chunk_size - 1;
  874. memset(&self->last_visited, 0, sizeof(c11_chunked_array2d_chunks_KV));
  875. py_newnone(py_retval());
  876. return true;
  877. }
  878. static bool chunked_array2d__chunk_size(int argc, py_Ref argv) {
  879. c11_chunked_array2d* self = py_touserdata(argv);
  880. py_newint(py_retval(), self->chunk_size);
  881. return true;
  882. }
  883. static bool chunked_array2d__getitem__(int argc, py_Ref argv) {
  884. PY_CHECK_ARGC(2);
  885. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  886. c11_chunked_array2d* self = py_touserdata(argv);
  887. c11_vec2i pos = py_tovec2i(&argv[1]);
  888. py_Ref res = c11_chunked_array2d__get(self, pos.x, pos.y);
  889. py_assign(py_retval(), res);
  890. return true;
  891. }
  892. static bool chunked_array2d__setitem__(int argc, py_Ref argv) {
  893. PY_CHECK_ARGC(3);
  894. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  895. c11_chunked_array2d* self = py_touserdata(argv);
  896. c11_vec2i pos = py_tovec2i(&argv[1]);
  897. bool ok = c11_chunked_array2d__set(self, pos.x, pos.y, &argv[2]);
  898. if(!ok) return false;
  899. py_newnone(py_retval());
  900. return true;
  901. }
  902. static bool chunked_array2d__delitem__(int argc, py_Ref argv) {
  903. PY_CHECK_ARGC(2);
  904. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  905. c11_chunked_array2d* self = py_touserdata(argv);
  906. c11_vec2i pos = py_tovec2i(&argv[1]);
  907. c11_chunked_array2d__del(self, pos.x, pos.y);
  908. py_newnone(py_retval());
  909. return true;
  910. }
  911. static bool chunked_array2d__iter__(int argc, py_Ref argv) {
  912. PY_CHECK_ARGC(1);
  913. c11_chunked_array2d* self = py_touserdata(argv);
  914. py_newtuple(py_retval(), self->chunks.length);
  915. for(int i = 0; i < self->chunks.length; i++) {
  916. py_TValue* data = c11__getitem(c11_chunked_array2d_chunks_KV, &self->chunks, i).value;
  917. py_tuple_setitem(py_retval(), i, &data[0]);
  918. }
  919. return py_iter(py_retval());
  920. }
  921. static bool chunked_array2d__clear(int argc, py_Ref argv) {
  922. c11_chunked_array2d* self = py_touserdata(argv);
  923. c11_chunked_array2d_chunks__clear(&self->chunks);
  924. self->last_visited.value = NULL;
  925. py_newnone(py_retval());
  926. return true;
  927. }
  928. static bool chunked_array2d__world_to_chunk(int argc, py_Ref argv) {
  929. PY_CHECK_ARGC(2);
  930. PY_CHECK_ARG_TYPE(1, tp_vec2);
  931. c11_chunked_array2d* self = py_touserdata(argv);
  932. c11_vec2i pos = py_tovec2i(&argv[1]);
  933. c11_vec2i chunk_pos, local_pos;
  934. c11_chunked_array2d__world_to_chunk(self, pos.x, pos.y, &chunk_pos, &local_pos);
  935. py_newtuple(py_retval(), 2);
  936. py_TValue* data = py_tuple_data(py_retval());
  937. py_newvec2i(&data[0], chunk_pos);
  938. py_newvec2i(&data[1], local_pos);
  939. return true;
  940. }
  941. static bool chunked_array2d__add_chunk(int argc, py_Ref argv) {
  942. PY_CHECK_ARGC(2);
  943. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  944. c11_chunked_array2d* self = py_touserdata(argv);
  945. c11_vec2i pos = py_tovec2i(&argv[1]);
  946. py_TValue* data = c11_chunked_array2d__new_chunk(self, pos);
  947. if(data == NULL) return false;
  948. py_assign(py_retval(), &data[0]); // context
  949. return true;
  950. }
  951. static bool chunked_array2d__remove_chunk(int argc, py_Ref argv) {
  952. PY_CHECK_ARGC(2);
  953. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  954. c11_chunked_array2d* self = py_touserdata(argv);
  955. c11_vec2i pos = py_tovec2i(&argv[1]);
  956. bool ok = c11_chunked_array2d_chunks__del(&self->chunks, pos);
  957. self->last_visited.value = NULL;
  958. py_newbool(py_retval(), ok);
  959. return true;
  960. }
  961. static bool chunked_array2d__get_context(int argc, py_Ref argv) {
  962. PY_CHECK_ARGC(2);
  963. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  964. c11_chunked_array2d* self = py_touserdata(argv);
  965. c11_vec2i pos = py_tovec2i(&argv[1]);
  966. py_TValue* data = c11_chunked_array2d_chunks__get(&self->chunks, pos, NULL);
  967. if(data == NULL) {
  968. py_newnone(py_retval());
  969. } else {
  970. py_assign(py_retval(), &data[0]);
  971. }
  972. return true;
  973. }
  974. void c11_chunked_array2d__dtor(c11_chunked_array2d* self) {
  975. c11__foreach(c11_chunked_array2d_chunks_KV, &self->chunks, p_kv) PK_FREE(p_kv->value);
  976. c11_chunked_array2d_chunks__dtor(&self->chunks);
  977. }
  978. static void c11_chunked_array2d__mark(void* ud) {
  979. c11_chunked_array2d* self = ud;
  980. pk__mark_value(&self->default_T);
  981. pk__mark_value(&self->context_builder);
  982. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  983. for(int i = 0; i < self->chunks.length; i++) {
  984. py_TValue* data = c11__getitem(c11_chunked_array2d_chunks_KV, &self->chunks, i).value;
  985. for(int j = 0; j < chunk_numel; j++) {
  986. pk__mark_value(data + j);
  987. }
  988. }
  989. }
  990. static bool chunked_array2d_view(int argc, py_Ref argv) {
  991. PY_CHECK_ARGC(1);
  992. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  993. if(self->chunks.length == 0) { return ValueError("chunked_array2d is empty"); }
  994. int min_chunk_x = INT_MAX;
  995. int min_chunk_y = INT_MAX;
  996. int max_chunk_x = INT_MIN;
  997. int max_chunk_y = INT_MIN;
  998. for(int i = 0; i < self->chunks.length; i++) {
  999. c11_vec2i chunk_pos = c11__getitem(c11_chunked_array2d_chunks_KV, &self->chunks, i).key;
  1000. min_chunk_x = c11__min(min_chunk_x, chunk_pos.x);
  1001. min_chunk_y = c11__min(min_chunk_y, chunk_pos.y);
  1002. max_chunk_x = c11__max(max_chunk_x, chunk_pos.x);
  1003. max_chunk_y = c11__max(max_chunk_y, chunk_pos.y);
  1004. }
  1005. int start_col = min_chunk_x << self->chunk_size_log2;
  1006. int start_row = min_chunk_y << self->chunk_size_log2;
  1007. int width = (max_chunk_x - min_chunk_x + 1) * self->chunk_size;
  1008. int height = (max_chunk_y - min_chunk_y + 1) * self->chunk_size;
  1009. return _chunked_array2d_view(py_retval(), argv, self, start_col, start_row, width, height);
  1010. }
  1011. static bool chunked_array2d_view_rect(int argc, py_Ref argv) {
  1012. PY_CHECK_ARGC(4);
  1013. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1014. PY_CHECK_ARG_TYPE(2, tp_int);
  1015. PY_CHECK_ARG_TYPE(3, tp_int);
  1016. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  1017. c11_vec2i pos = py_tovec2i(&argv[1]);
  1018. int width = py_toint(&argv[2]);
  1019. int height = py_toint(&argv[3]);
  1020. return _chunked_array2d_view(py_retval(), argv, self, pos.x, pos.y, width, height);
  1021. }
  1022. static bool chunked_array2d_view_chunk(int argc, py_Ref argv) {
  1023. PY_CHECK_ARGC(2);
  1024. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1025. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  1026. c11_vec2i chunk_pos = py_tovec2i(&argv[1]);
  1027. int start_col = chunk_pos.x << self->chunk_size_log2;
  1028. int start_row = chunk_pos.y << self->chunk_size_log2;
  1029. return _chunked_array2d_view(py_retval(),
  1030. argv,
  1031. self,
  1032. start_col,
  1033. start_row,
  1034. self->chunk_size,
  1035. self->chunk_size);
  1036. }
  1037. static bool chunked_array2d_view_chunks(int argc, py_Ref argv) {
  1038. PY_CHECK_ARGC(4);
  1039. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1040. PY_CHECK_ARG_TYPE(2, tp_int);
  1041. PY_CHECK_ARG_TYPE(3, tp_int);
  1042. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  1043. c11_vec2i chunk_pos = py_tovec2i(&argv[1]);
  1044. int width = py_toint(&argv[2]) * self->chunk_size;
  1045. int height = py_toint(&argv[3]) * self->chunk_size;
  1046. int start_col = chunk_pos.x << self->chunk_size_log2;
  1047. int start_row = chunk_pos.y << self->chunk_size_log2;
  1048. return _chunked_array2d_view(py_retval(), argv, self, start_col, start_row, width, height);
  1049. }
  1050. static void register_chunked_array2d(py_Ref mod) {
  1051. py_Type type =
  1052. py_newtype("chunked_array2d", tp_object, mod, (py_Dtor)c11_chunked_array2d__dtor);
  1053. pk__tp_set_marker(type, c11_chunked_array2d__mark);
  1054. assert(type == tp_chunked_array2d);
  1055. py_bind(py_tpobject(type), "__new__(cls, *args, **kwargs)", chunked_array2d__new__);
  1056. py_bind(py_tpobject(type),
  1057. "__init__(self, chunk_size, default=None, context_builder=None)",
  1058. chunked_array2d__init__);
  1059. py_bindproperty(type, "chunk_size", chunked_array2d__chunk_size, NULL);
  1060. py_bindmagic(type, __getitem__, chunked_array2d__getitem__);
  1061. py_bindmagic(type, __setitem__, chunked_array2d__setitem__);
  1062. py_bindmagic(type, __delitem__, chunked_array2d__delitem__);
  1063. py_bindmagic(type, __iter__, chunked_array2d__iter__);
  1064. py_bindmethod(type, "clear", chunked_array2d__clear);
  1065. py_bindmethod(type, "world_to_chunk", chunked_array2d__world_to_chunk);
  1066. py_bindmethod(type, "add_chunk", chunked_array2d__add_chunk);
  1067. py_bindmethod(type, "remove_chunk", chunked_array2d__remove_chunk);
  1068. py_bindmethod(type, "get_context", chunked_array2d__get_context);
  1069. py_bindmethod(type, "view", chunked_array2d_view);
  1070. py_bindmethod(type, "view_rect", chunked_array2d_view_rect);
  1071. py_bindmethod(type, "view_chunk", chunked_array2d_view_chunk);
  1072. py_bindmethod(type, "view_chunks", chunked_array2d_view_chunks);
  1073. }
  1074. void pk__add_module_array2d() {
  1075. py_GlobalRef mod = py_newmodule("array2d");
  1076. register_array2d_like(mod);
  1077. register_array2d_like_iterator(mod);
  1078. register_array2d(mod);
  1079. register_array2d_view(mod);
  1080. register_chunked_array2d(mod);
  1081. }