linalg.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. #include "pocketpy/linalg.h"
  2. namespace pkpy{
  3. #define BIND_VEC_VEC_OP(D, name, op) \
  4. vm->bind##name(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  5. Vec##D& self = _CAST(Vec##D&, _0); \
  6. Vec##D& other = CAST(Vec##D&, _1); \
  7. return VAR(self op other); \
  8. });
  9. #define BIND_VEC_FLOAT_OP(D, name, op) \
  10. vm->bind##name(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  11. Vec##D& self = _CAST(Vec##D&, _0); \
  12. f64 other = CAST(f64, _1); \
  13. return VAR(self op other); \
  14. });
  15. #define BIND_VEC_FUNCTION_0(D, name) \
  16. vm->bind_method<0>(type, #name, [](VM* vm, ArgsView args){ \
  17. Vec##D& self = _CAST(Vec##D&, args[0]); \
  18. return VAR(self.name()); \
  19. });
  20. #define BIND_VEC_FUNCTION_1(D, name) \
  21. vm->bind_method<1>(type, #name, [](VM* vm, ArgsView args){ \
  22. Vec##D& self = _CAST(Vec##D&, args[0]); \
  23. Vec##D& other = CAST(Vec##D&, args[1]); \
  24. return VAR(self.name(other)); \
  25. });
  26. #define BIND_VEC_MUL_OP(D) \
  27. vm->bind__mul__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  28. Vec##D& self = _CAST(Vec##D&, _0); \
  29. if(is_type(_1, Vec##D::_type(vm))){ \
  30. Vec##D& other = _CAST(Vec##D&, _1); \
  31. return VAR(self * other); \
  32. } \
  33. f64 other = CAST(f64, _1); \
  34. return VAR(self * other); \
  35. }); \
  36. vm->bind_method<1>(type, "__rmul__", [](VM* vm, ArgsView args){ \
  37. Vec##D& self = _CAST(Vec##D&, args[0]); \
  38. f64 other = CAST(f64, args[1]); \
  39. return VAR(self * other); \
  40. }); \
  41. vm->bind__truediv__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  42. Vec##D& self = _CAST(Vec##D&, _0); \
  43. f64 other = CAST(f64, _1); \
  44. return VAR(self / other); \
  45. });
  46. #define BIND_VEC_GETITEM(D) \
  47. vm->bind__getitem__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj, PyObject* index){ \
  48. Vec##D& self = _CAST(Vec##D&, obj); \
  49. i64 i = CAST(i64, index); \
  50. if(i < 0 || i >= D) vm->IndexError("index out of range"); \
  51. float* v = &self.x; \
  52. return VAR(v[i]); \
  53. });
  54. // https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector2.cs#L289
  55. static Vec2 SmoothDamp(Vec2 current, Vec2 target, Vec2& currentVelocity, float smoothTime, float maxSpeed, float deltaTime)
  56. {
  57. // Based on Game Programming Gems 4 Chapter 1.10
  58. smoothTime = std::max(0.0001F, smoothTime);
  59. float omega = 2.0F / smoothTime;
  60. float x = omega * deltaTime;
  61. float exp = 1.0F / (1.0F + x + 0.48F * x * x + 0.235F * x * x * x);
  62. float change_x = current.x - target.x;
  63. float change_y = current.y - target.y;
  64. Vec2 originalTo = target;
  65. // Clamp maximum speed
  66. float maxChange = maxSpeed * smoothTime;
  67. float maxChangeSq = maxChange * maxChange;
  68. float sqDist = change_x * change_x + change_y * change_y;
  69. if (sqDist > maxChangeSq)
  70. {
  71. float mag = std::sqrt(sqDist);
  72. change_x = change_x / mag * maxChange;
  73. change_y = change_y / mag * maxChange;
  74. }
  75. target.x = current.x - change_x;
  76. target.y = current.y - change_y;
  77. float temp_x = (currentVelocity.x + omega * change_x) * deltaTime;
  78. float temp_y = (currentVelocity.y + omega * change_y) * deltaTime;
  79. currentVelocity.x = (currentVelocity.x - omega * temp_x) * exp;
  80. currentVelocity.y = (currentVelocity.y - omega * temp_y) * exp;
  81. float output_x = target.x + (change_x + temp_x) * exp;
  82. float output_y = target.y + (change_y + temp_y) * exp;
  83. // Prevent overshooting
  84. float origMinusCurrent_x = originalTo.x - current.x;
  85. float origMinusCurrent_y = originalTo.y - current.y;
  86. float outMinusOrig_x = output_x - originalTo.x;
  87. float outMinusOrig_y = output_y - originalTo.y;
  88. if (origMinusCurrent_x * outMinusOrig_x + origMinusCurrent_y * outMinusOrig_y > 0)
  89. {
  90. output_x = originalTo.x;
  91. output_y = originalTo.y;
  92. currentVelocity.x = (output_x - originalTo.x) / deltaTime;
  93. currentVelocity.y = (output_y - originalTo.y) / deltaTime;
  94. }
  95. return Vec2(output_x, output_y);
  96. }
  97. void Vec2::_register(VM* vm, PyObject* mod, PyObject* type){
  98. PY_STRUCT_LIKE(Vec2)
  99. vm->bind_constructor<3>(type, [](VM* vm, ArgsView args){
  100. float x = CAST_F(args[1]);
  101. float y = CAST_F(args[2]);
  102. return vm->heap.gcnew<Vec2>(PK_OBJ_GET(Type, args[0]), Vec2(x, y));
  103. });
  104. // @staticmethod
  105. vm->bind(type, "smooth_damp(current: vec2, target: vec2, current_velocity_: vec2, smooth_time: float, max_speed: float, delta_time: float) -> vec2", [](VM* vm, ArgsView args){
  106. Vec2 current = CAST(Vec2, args[0]);
  107. Vec2 target = CAST(Vec2, args[1]);
  108. Vec2& current_velocity_ = CAST(Vec2&, args[2]);
  109. float smooth_time = CAST_F(args[3]);
  110. float max_speed = CAST_F(args[4]);
  111. float delta_time = CAST_F(args[5]);
  112. Vec2 ret = SmoothDamp(current, target, current_velocity_, smooth_time, max_speed, delta_time);
  113. return VAR(ret);
  114. }, {}, BindType::STATICMETHOD);
  115. // @staticmethod
  116. vm->bind(type, "angle(__from: vec2, __to: vec2) -> float", [](VM* vm, ArgsView args){
  117. Vec2 __from = CAST(Vec2, args[0]);
  118. Vec2 __to = CAST(Vec2, args[1]);
  119. float val = atan2f(__to.y, __to.x) - atan2f(__from.y, __from.x);
  120. const float PI = 3.1415926535897932384f;
  121. if(val > PI) val -= 2*PI;
  122. if(val < -PI) val += 2*PI;
  123. return VAR(val);
  124. }, {}, BindType::STATICMETHOD);
  125. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  126. Vec2 self = _CAST(Vec2&, obj);
  127. SStream ss;
  128. ss.setprecision(3);
  129. ss << "vec2(" << self.x << ", " << self.y << ")";
  130. return VAR(ss.str());
  131. });
  132. vm->bind_method<1>(type, "rotate", [](VM* vm, ArgsView args){
  133. Vec2 self = _CAST(Vec2&, args[0]);
  134. float radian = CAST(f64, args[1]);
  135. return VAR_T(Vec2, self.rotate(radian));
  136. });
  137. vm->bind_method<1>(type, "rotate_", [](VM* vm, ArgsView args){
  138. Vec2& self = _CAST(Vec2&, args[0]);
  139. float radian = CAST(f64, args[1]);
  140. self = self.rotate(radian);
  141. return vm->None;
  142. });
  143. PY_FIELD(Vec2, "x", _, x)
  144. PY_FIELD(Vec2, "y", _, y)
  145. BIND_VEC_VEC_OP(2, __add__, +)
  146. BIND_VEC_VEC_OP(2, __sub__, -)
  147. BIND_VEC_MUL_OP(2)
  148. BIND_VEC_FLOAT_OP(2, __truediv__, /)
  149. BIND_VEC_FUNCTION_1(2, dot)
  150. BIND_VEC_FUNCTION_1(2, cross)
  151. BIND_VEC_FUNCTION_1(2, copy_)
  152. BIND_VEC_FUNCTION_0(2, length)
  153. BIND_VEC_FUNCTION_0(2, length_squared)
  154. BIND_VEC_FUNCTION_0(2, normalize)
  155. BIND_VEC_FUNCTION_0(2, normalize_)
  156. BIND_VEC_GETITEM(2)
  157. }
  158. void Vec3::_register(VM* vm, PyObject* mod, PyObject* type){
  159. PY_STRUCT_LIKE(Vec3)
  160. vm->bind_constructor<4>(type, [](VM* vm, ArgsView args){
  161. float x = CAST_F(args[1]);
  162. float y = CAST_F(args[2]);
  163. float z = CAST_F(args[3]);
  164. return vm->heap.gcnew<Vec3>(PK_OBJ_GET(Type, args[0]), Vec3(x, y, z));
  165. });
  166. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  167. Vec3 self = _CAST(Vec3&, obj);
  168. SStream ss;
  169. ss.setprecision(3);
  170. ss << "vec3(" << self.x << ", " << self.y << ", " << self.z << ")";
  171. return VAR(ss.str());
  172. });
  173. PY_FIELD(Vec3, "x", _, x)
  174. PY_FIELD(Vec3, "y", _, y)
  175. PY_FIELD(Vec3, "z", _, z)
  176. BIND_VEC_VEC_OP(3, __add__, +)
  177. BIND_VEC_VEC_OP(3, __sub__, -)
  178. BIND_VEC_MUL_OP(3)
  179. BIND_VEC_FUNCTION_1(3, dot)
  180. BIND_VEC_FUNCTION_1(3, cross)
  181. BIND_VEC_FUNCTION_1(3, copy_)
  182. BIND_VEC_FUNCTION_0(3, length)
  183. BIND_VEC_FUNCTION_0(3, length_squared)
  184. BIND_VEC_FUNCTION_0(3, normalize)
  185. BIND_VEC_FUNCTION_0(3, normalize_)
  186. BIND_VEC_GETITEM(3)
  187. }
  188. void Vec4::_register(VM* vm, PyObject* mod, PyObject* type){
  189. PY_STRUCT_LIKE(Vec4)
  190. vm->bind_constructor<1+4>(type, [](VM* vm, ArgsView args){
  191. float x = CAST_F(args[1]);
  192. float y = CAST_F(args[2]);
  193. float z = CAST_F(args[3]);
  194. float w = CAST_F(args[4]);
  195. return vm->heap.gcnew<Vec4>(PK_OBJ_GET(Type, args[0]), Vec4(x, y, z, w));
  196. });
  197. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  198. Vec4 self = _CAST(Vec4&, obj);
  199. SStream ss;
  200. ss.setprecision(3);
  201. ss << "vec4(" << self.x << ", " << self.y << ", " << self.z << ", " << self.w << ")";
  202. return VAR(ss.str());
  203. });
  204. PY_FIELD(Vec4, "x", _, x)
  205. PY_FIELD(Vec4, "y", _, y)
  206. PY_FIELD(Vec4, "z", _, z)
  207. PY_FIELD(Vec4, "w", _, w)
  208. BIND_VEC_VEC_OP(4, __add__, +)
  209. BIND_VEC_VEC_OP(4, __sub__, -)
  210. BIND_VEC_MUL_OP(4)
  211. BIND_VEC_FUNCTION_1(4, dot)
  212. BIND_VEC_FUNCTION_1(4, copy_)
  213. BIND_VEC_FUNCTION_0(4, length)
  214. BIND_VEC_FUNCTION_0(4, length_squared)
  215. BIND_VEC_FUNCTION_0(4, normalize)
  216. BIND_VEC_FUNCTION_0(4, normalize_)
  217. BIND_VEC_GETITEM(4)
  218. }
  219. #undef BIND_VEC_VEC_OP
  220. #undef BIND_VEC_MUL_OP
  221. #undef BIND_VEC_FUNCTION_0
  222. #undef BIND_VEC_FUNCTION_1
  223. #undef BIND_VEC_GETITEM
  224. void Mat3x3::_register(VM* vm, PyObject* mod, PyObject* type){
  225. PY_STRUCT_LIKE(Mat3x3)
  226. vm->bind_constructor<-1>(type, [](VM* vm, ArgsView args){
  227. if(args.size() == 1+0) return vm->heap.gcnew<Mat3x3>(PK_OBJ_GET(Type, args[0]), Mat3x3::zeros());
  228. if(args.size() == 1+1){
  229. const List& list = CAST(List&, args[1]);
  230. if(list.size() != 9) vm->TypeError("Mat3x3.__new__ takes a list of 9 floats");
  231. Mat3x3 mat;
  232. for(int i=0; i<9; i++) mat.v[i] = CAST_F(list[i]);
  233. return vm->heap.gcnew<Mat3x3>(PK_OBJ_GET(Type, args[0]), mat);
  234. }
  235. if(args.size() == 1+9){
  236. Mat3x3 mat;
  237. for(int i=0; i<9; i++) mat.v[i] = CAST_F(args[1+i]);
  238. return vm->heap.gcnew<Mat3x3>(PK_OBJ_GET(Type, args[0]), mat);
  239. }
  240. vm->TypeError(_S("Mat3x3.__new__ takes 0 or 1 or 9 arguments, got ", args.size()-1));
  241. return vm->None;
  242. });
  243. vm->bind_method<1>(type, "copy_", [](VM* vm, ArgsView args){
  244. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  245. const Mat3x3& other = CAST(Mat3x3&, args[1]);
  246. self = other;
  247. return vm->None;
  248. });
  249. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  250. const Mat3x3& self = _CAST(Mat3x3&, obj);
  251. SStream ss;
  252. ss.setprecision(3);
  253. ss << "mat3x3([" << self._11 << ", " << self._12 << ", " << self._13 << ",\n";
  254. ss << " " << self._21 << ", " << self._22 << ", " << self._23 << ",\n";
  255. ss << " " << self._31 << ", " << self._32 << ", " << self._33 << "])";
  256. return VAR(ss.str());
  257. });
  258. vm->bind__getitem__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj, PyObject* index){
  259. Mat3x3& self = _CAST(Mat3x3&, obj);
  260. Tuple& t = CAST(Tuple&, index);
  261. if(t.size() != 2){
  262. vm->TypeError("Mat3x3.__getitem__ takes a tuple of 2 integers");
  263. }
  264. i64 i = CAST(i64, t[0]);
  265. i64 j = CAST(i64, t[1]);
  266. if(i < 0 || i >= 3 || j < 0 || j >= 3){
  267. vm->IndexError("index out of range");
  268. }
  269. return VAR(self.m[i][j]);
  270. });
  271. vm->bind__setitem__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj, PyObject* index, PyObject* value){
  272. Mat3x3& self = _CAST(Mat3x3&, obj);
  273. const Tuple& t = CAST(Tuple&, index);
  274. if(t.size() != 2){
  275. vm->TypeError("Mat3x3.__setitem__ takes a tuple of 2 integers");
  276. }
  277. i64 i = CAST(i64, t[0]);
  278. i64 j = CAST(i64, t[1]);
  279. if(i < 0 || i >= 3 || j < 0 || j >= 3){
  280. vm->IndexError("index out of range");
  281. }
  282. self.m[i][j] = CAST_F(value);
  283. });
  284. PY_FIELD(Mat3x3, "_11", _, _11)
  285. PY_FIELD(Mat3x3, "_12", _, _12)
  286. PY_FIELD(Mat3x3, "_13", _, _13)
  287. PY_FIELD(Mat3x3, "_21", _, _21)
  288. PY_FIELD(Mat3x3, "_22", _, _22)
  289. PY_FIELD(Mat3x3, "_23", _, _23)
  290. PY_FIELD(Mat3x3, "_31", _, _31)
  291. PY_FIELD(Mat3x3, "_32", _, _32)
  292. PY_FIELD(Mat3x3, "_33", _, _33)
  293. vm->bind__add__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  294. Mat3x3& self = _CAST(Mat3x3&, _0);
  295. Mat3x3& other = CAST(Mat3x3&, _1);
  296. return VAR_T(Mat3x3, self + other);
  297. });
  298. vm->bind__sub__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  299. Mat3x3& self = _CAST(Mat3x3&, _0);
  300. Mat3x3& other = CAST(Mat3x3&, _1);
  301. return VAR_T(Mat3x3, self - other);
  302. });
  303. vm->bind__mul__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  304. Mat3x3& self = _CAST(Mat3x3&, _0);
  305. f64 other = CAST_F(_1);
  306. return VAR_T(Mat3x3, self * other);
  307. });
  308. vm->bind_method<1>(type, "__rmul__", [](VM* vm, ArgsView args){
  309. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  310. f64 other = CAST_F(args[1]);
  311. return VAR_T(Mat3x3, self * other);
  312. });
  313. vm->bind__truediv__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  314. Mat3x3& self = _CAST(Mat3x3&, _0);
  315. f64 other = CAST_F(_1);
  316. return VAR_T(Mat3x3, self / other);
  317. });
  318. vm->bind__matmul__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  319. Mat3x3& self = _CAST(Mat3x3&, _0);
  320. if(is_type(_1, Mat3x3::_type(vm))){
  321. const Mat3x3& other = _CAST(Mat3x3&, _1);
  322. return VAR_T(Mat3x3, self.matmul(other));
  323. }
  324. if(is_type(_1, Vec3::_type(vm))){
  325. const Vec3& other = _CAST(Vec3&, _1);
  326. return VAR_T(Vec3, self.matmul(other));
  327. }
  328. return vm->NotImplemented;
  329. });
  330. vm->bind(type, "matmul(self, other: mat3x3, out: mat3x3 = None)", [](VM* vm, ArgsView args){
  331. const Mat3x3& self = _CAST(Mat3x3&, args[0]);
  332. const Mat3x3& other = CAST(Mat3x3&, args[1]);
  333. if(args[2] == vm->None){
  334. return VAR_T(Mat3x3, self.matmul(other));
  335. }else{
  336. Mat3x3& out = CAST(Mat3x3&, args[2]);
  337. out = self.matmul(other);
  338. return vm->None;
  339. }
  340. });
  341. vm->bind_method<0>(type, "determinant", [](VM* vm, ArgsView args){
  342. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  343. return VAR(self.determinant());
  344. });
  345. vm->bind_method<0>(type, "transpose", [](VM* vm, ArgsView args){
  346. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  347. return VAR_T(Mat3x3, self.transpose());
  348. });
  349. vm->bind__invert__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  350. Mat3x3& self = _CAST(Mat3x3&, obj);
  351. Mat3x3 ret;
  352. bool ok = self.inverse(ret);
  353. if(!ok) vm->ValueError("matrix is not invertible");
  354. return VAR_T(Mat3x3, ret);
  355. });
  356. vm->bind_method<0>(type, "invert", [](VM* vm, ArgsView args){
  357. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  358. Mat3x3 ret;
  359. bool ok = self.inverse(ret);
  360. if(!ok) vm->ValueError("matrix is not invertible");
  361. return VAR_T(Mat3x3, ret);
  362. });
  363. vm->bind_method<0>(type, "invert_", [](VM* vm, ArgsView args){
  364. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  365. Mat3x3 ret;
  366. bool ok = self.inverse(ret);
  367. if(!ok) vm->ValueError("matrix is not invertible");
  368. self = ret;
  369. return vm->None;
  370. });
  371. vm->bind_method<0>(type, "transpose_", [](VM* vm, ArgsView args){
  372. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  373. self = self.transpose();
  374. return vm->None;
  375. });
  376. // @staticmethod
  377. vm->bind(type, "zeros()", [](VM* vm, ArgsView args){
  378. return VAR_T(Mat3x3, Mat3x3::zeros());
  379. }, {}, BindType::STATICMETHOD);
  380. // @staticmethod
  381. vm->bind(type, "ones()", [](VM* vm, ArgsView args){
  382. return VAR_T(Mat3x3, Mat3x3::ones());
  383. }, {}, BindType::STATICMETHOD);
  384. // @staticmethod
  385. vm->bind(type, "identity()", [](VM* vm, ArgsView args){
  386. return VAR_T(Mat3x3, Mat3x3::identity());
  387. }, {}, BindType::STATICMETHOD);
  388. /*************** affine transformations ***************/
  389. // @staticmethod
  390. vm->bind(type, "trs(t: vec2, r: float, s: vec2)", [](VM* vm, ArgsView args){
  391. Vec2 t = CAST(Vec2, args[0]);
  392. f64 r = CAST_F(args[1]);
  393. Vec2 s = CAST(Vec2, args[2]);
  394. return VAR_T(Mat3x3, Mat3x3::trs(t, r, s));
  395. }, {}, BindType::STATICMETHOD);
  396. vm->bind(type, "copy_trs_(self, t: vec2, r: float, s: vec2)", [](VM* vm, ArgsView args){
  397. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  398. Vec2 t = CAST(Vec2, args[1]);
  399. f64 r = CAST_F(args[2]);
  400. Vec2 s = CAST(Vec2, args[3]);
  401. self = Mat3x3::trs(t, r, s);
  402. return vm->None;
  403. });
  404. vm->bind(type, "copy_t_(self, t: vec2)", [](VM* vm, ArgsView args){
  405. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  406. Vec2 t = CAST(Vec2, args[1]);
  407. self = Mat3x3::trs(t, self._r(), self._s());
  408. return vm->None;
  409. });
  410. vm->bind(type, "copy_r_(self, r: float)", [](VM* vm, ArgsView args){
  411. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  412. f64 r = CAST_F(args[1]);
  413. self = Mat3x3::trs(self._t(), r, self._s());
  414. return vm->None;
  415. });
  416. vm->bind(type, "copy_s_(self, s: vec2)", [](VM* vm, ArgsView args){
  417. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  418. Vec2 s = CAST(Vec2, args[1]);
  419. self = Mat3x3::trs(self._t(), self._r(), s);
  420. return vm->None;
  421. });
  422. vm->bind_method<0>(type, "is_affine", [](VM* vm, ArgsView args){
  423. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  424. return VAR(self.is_affine());
  425. });
  426. vm->bind_method<0>(type, "_t", [](VM* vm, ArgsView args){
  427. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  428. return VAR_T(Vec2, self._t());
  429. });
  430. vm->bind_method<0>(type, "_r", [](VM* vm, ArgsView args){
  431. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  432. return VAR(self._r());
  433. });
  434. vm->bind_method<0>(type, "_s", [](VM* vm, ArgsView args){
  435. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  436. return VAR_T(Vec2, self._s());
  437. });
  438. vm->bind_method<1>(type, "transform_point", [](VM* vm, ArgsView args){
  439. const Mat3x3& self = _CAST(Mat3x3&, args[0]);
  440. Vec2 v = CAST(Vec2, args[1]);
  441. Vec2 res = Vec2(self._11 * v.x + self._12 * v.y + self._13, self._21 * v.x + self._22 * v.y + self._23);
  442. return VAR_T(Vec2, res);
  443. });
  444. vm->bind_method<1>(type, "transform_vector", [](VM* vm, ArgsView args){
  445. const Mat3x3& self = _CAST(Mat3x3&, args[0]);
  446. Vec2 v = CAST(Vec2, args[1]);
  447. Vec2 res = Vec2(self._11 * v.x + self._12 * v.y, self._21 * v.x + self._22 * v.y);
  448. return VAR_T(Vec2, res);
  449. });
  450. }
  451. void add_module_linalg(VM* vm){
  452. PyObject* linalg = vm->new_module("linalg");
  453. Vec2::register_class(vm, linalg);
  454. Vec3::register_class(vm, linalg);
  455. Vec4::register_class(vm, linalg);
  456. Mat3x3::register_class(vm, linalg);
  457. PyObject* float_p = vm->_modules["c"]->attr("float_p");
  458. linalg->attr().set("vec2_p", float_p);
  459. linalg->attr().set("vec3_p", float_p);
  460. linalg->attr().set("vec4_p", float_p);
  461. linalg->attr().set("mat3x3_p", float_p);
  462. }
  463. /////////////// mat3x3 ///////////////
  464. Mat3x3::Mat3x3() {}
  465. Mat3x3::Mat3x3(float _11, float _12, float _13,
  466. float _21, float _22, float _23,
  467. float _31, float _32, float _33)
  468. : _11(_11), _12(_12), _13(_13)
  469. , _21(_21), _22(_22), _23(_23)
  470. , _31(_31), _32(_32), _33(_33) {}
  471. Mat3x3 Mat3x3::zeros(){
  472. return Mat3x3(0, 0, 0, 0, 0, 0, 0, 0, 0);
  473. }
  474. Mat3x3 Mat3x3::ones(){
  475. return Mat3x3(1, 1, 1, 1, 1, 1, 1, 1, 1);
  476. }
  477. Mat3x3 Mat3x3::identity(){
  478. return Mat3x3(1, 0, 0, 0, 1, 0, 0, 0, 1);
  479. }
  480. Mat3x3 Mat3x3::operator+(const Mat3x3& other) const{
  481. Mat3x3 ret;
  482. for (int i=0; i<9; ++i) ret.v[i] = v[i] + other.v[i];
  483. return ret;
  484. }
  485. Mat3x3 Mat3x3::operator-(const Mat3x3& other) const{
  486. Mat3x3 ret;
  487. for (int i=0; i<9; ++i) ret.v[i] = v[i] - other.v[i];
  488. return ret;
  489. }
  490. Mat3x3 Mat3x3::operator*(float scalar) const{
  491. Mat3x3 ret;
  492. for (int i=0; i<9; ++i) ret.v[i] = v[i] * scalar;
  493. return ret;
  494. }
  495. Mat3x3 Mat3x3::operator/(float scalar) const{
  496. Mat3x3 ret;
  497. for (int i=0; i<9; ++i) ret.v[i] = v[i] / scalar;
  498. return ret;
  499. }
  500. bool Mat3x3::operator==(const Mat3x3& other) const{
  501. for (int i=0; i<9; ++i){
  502. if (!isclose(v[i], other.v[i])) return false;
  503. }
  504. return true;
  505. }
  506. bool Mat3x3::operator!=(const Mat3x3& other) const{
  507. for (int i=0; i<9; ++i){
  508. if (!isclose(v[i], other.v[i])) return true;
  509. }
  510. return false;
  511. }
  512. Mat3x3 Mat3x3::matmul(const Mat3x3& other) const{
  513. Mat3x3 out;
  514. out._11 = _11 * other._11 + _12 * other._21 + _13 * other._31;
  515. out._12 = _11 * other._12 + _12 * other._22 + _13 * other._32;
  516. out._13 = _11 * other._13 + _12 * other._23 + _13 * other._33;
  517. out._21 = _21 * other._11 + _22 * other._21 + _23 * other._31;
  518. out._22 = _21 * other._12 + _22 * other._22 + _23 * other._32;
  519. out._23 = _21 * other._13 + _22 * other._23 + _23 * other._33;
  520. out._31 = _31 * other._11 + _32 * other._21 + _33 * other._31;
  521. out._32 = _31 * other._12 + _32 * other._22 + _33 * other._32;
  522. out._33 = _31 * other._13 + _32 * other._23 + _33 * other._33;
  523. return out;
  524. }
  525. Vec3 Mat3x3::matmul(const Vec3& other) const{
  526. Vec3 out;
  527. out.x = _11 * other.x + _12 * other.y + _13 * other.z;
  528. out.y = _21 * other.x + _22 * other.y + _23 * other.z;
  529. out.z = _31 * other.x + _32 * other.y + _33 * other.z;
  530. return out;
  531. }
  532. float Mat3x3::determinant() const{
  533. return _11 * _22 * _33 + _12 * _23 * _31 + _13 * _21 * _32
  534. - _11 * _23 * _32 - _12 * _21 * _33 - _13 * _22 * _31;
  535. }
  536. Mat3x3 Mat3x3::transpose() const{
  537. Mat3x3 ret;
  538. ret._11 = _11; ret._12 = _21; ret._13 = _31;
  539. ret._21 = _12; ret._22 = _22; ret._23 = _32;
  540. ret._31 = _13; ret._32 = _23; ret._33 = _33;
  541. return ret;
  542. }
  543. bool Mat3x3::inverse(Mat3x3& out) const{
  544. float det = determinant();
  545. if (isclose(det, 0)) return false;
  546. float inv_det = 1.0f / det;
  547. out._11 = (_22 * _33 - _23 * _32) * inv_det;
  548. out._12 = (_13 * _32 - _12 * _33) * inv_det;
  549. out._13 = (_12 * _23 - _13 * _22) * inv_det;
  550. out._21 = (_23 * _31 - _21 * _33) * inv_det;
  551. out._22 = (_11 * _33 - _13 * _31) * inv_det;
  552. out._23 = (_13 * _21 - _11 * _23) * inv_det;
  553. out._31 = (_21 * _32 - _22 * _31) * inv_det;
  554. out._32 = (_12 * _31 - _11 * _32) * inv_det;
  555. out._33 = (_11 * _22 - _12 * _21) * inv_det;
  556. return true;
  557. }
  558. Mat3x3 Mat3x3::trs(Vec2 t, float radian, Vec2 s){
  559. float cr = cosf(radian);
  560. float sr = sinf(radian);
  561. return Mat3x3(s.x * cr, -s.y * sr, t.x,
  562. s.x * sr, s.y * cr, t.y,
  563. 0.0f, 0.0f, 1.0f);
  564. }
  565. bool Mat3x3::is_affine() const{
  566. float det = _11 * _22 - _12 * _21;
  567. if(isclose(det, 0)) return false;
  568. return _31 == 0.0f && _32 == 0.0f && _33 == 1.0f;
  569. }
  570. Vec2 Mat3x3::_t() const { return Vec2(_13, _23); }
  571. float Mat3x3::_r() const { return atan2f(_21, _11); }
  572. Vec2 Mat3x3::_s() const {
  573. return Vec2(
  574. sqrtf(_11 * _11 + _21 * _21),
  575. sqrtf(_12 * _12 + _22 * _22)
  576. );
  577. }
  578. } // namespace pkpy