godot_shape_3d.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271
  1. /**************************************************************************/
  2. /* godot_shape_3d.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "godot_shape_3d.h"
  31. #include "core/io/image.h"
  32. #include "core/math/convex_hull.h"
  33. #include "core/math/geometry_3d.h"
  34. #include "core/templates/sort_array.h"
  35. // GodotHeightMapShape3D is based on Bullet btHeightfieldTerrainShape.
  36. /*
  37. Bullet Continuous Collision Detection and Physics Library
  38. Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
  39. This software is provided 'as-is', without any express or implied warranty.
  40. In no event will the authors be held liable for any damages arising from the use of this software.
  41. Permission is granted to anyone to use this software for any purpose,
  42. including commercial applications, and to alter it and redistribute it freely,
  43. subject to the following restrictions:
  44. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  45. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  46. 3. This notice may not be removed or altered from any source distribution.
  47. */
  48. const double edge_support_threshold = 0.99999998;
  49. const double edge_support_threshold_lower = Math::sqrt(1.0 - edge_support_threshold * edge_support_threshold);
  50. // For a unit normal vector n, the horizontality condition
  51. // sqrt(n.x * n.x + n.z * n.z) > edge_support_threshold
  52. // is equivalent to the condition
  53. // abs(n.y) < edge_support_threshold_lower,
  54. // which is cheaper to test.
  55. const double face_support_threshold = 0.9998;
  56. const double cylinder_edge_support_threshold = 0.999998;
  57. const double cylinder_edge_support_threshold_lower = Math::sqrt(1.0 - cylinder_edge_support_threshold * cylinder_edge_support_threshold);
  58. const double cylinder_face_support_threshold = 0.999;
  59. void GodotShape3D::configure(const AABB &p_aabb) {
  60. aabb = p_aabb;
  61. configured = true;
  62. for (const KeyValue<GodotShapeOwner3D *, int> &E : owners) {
  63. GodotShapeOwner3D *co = const_cast<GodotShapeOwner3D *>(E.key);
  64. co->_shape_changed();
  65. }
  66. }
  67. Vector3 GodotShape3D::get_support(const Vector3 &p_normal) const {
  68. Vector3 res;
  69. int amnt;
  70. FeatureType type;
  71. get_supports(p_normal, 1, &res, amnt, type);
  72. return res;
  73. }
  74. void GodotShape3D::add_owner(GodotShapeOwner3D *p_owner) {
  75. HashMap<GodotShapeOwner3D *, int>::Iterator E = owners.find(p_owner);
  76. if (E) {
  77. E->value++;
  78. } else {
  79. owners[p_owner] = 1;
  80. }
  81. }
  82. void GodotShape3D::remove_owner(GodotShapeOwner3D *p_owner) {
  83. HashMap<GodotShapeOwner3D *, int>::Iterator E = owners.find(p_owner);
  84. ERR_FAIL_COND(!E);
  85. E->value--;
  86. if (E->value == 0) {
  87. owners.remove(E);
  88. }
  89. }
  90. bool GodotShape3D::is_owner(GodotShapeOwner3D *p_owner) const {
  91. return owners.has(p_owner);
  92. }
  93. const HashMap<GodotShapeOwner3D *, int> &GodotShape3D::get_owners() const {
  94. return owners;
  95. }
  96. GodotShape3D::~GodotShape3D() {
  97. ERR_FAIL_COND(owners.size());
  98. }
  99. Plane GodotWorldBoundaryShape3D::get_plane() const {
  100. return plane;
  101. }
  102. void GodotWorldBoundaryShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  103. // gibberish, a plane is infinity
  104. r_min = -1e7;
  105. r_max = 1e7;
  106. }
  107. Vector3 GodotWorldBoundaryShape3D::get_support(const Vector3 &p_normal) const {
  108. return p_normal * 1e15;
  109. }
  110. bool GodotWorldBoundaryShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  111. bool inters = plane.intersects_segment(p_begin, p_end, &r_result);
  112. if (inters) {
  113. r_normal = plane.normal;
  114. }
  115. return inters;
  116. }
  117. bool GodotWorldBoundaryShape3D::intersect_point(const Vector3 &p_point) const {
  118. return plane.distance_to(p_point) < 0;
  119. }
  120. Vector3 GodotWorldBoundaryShape3D::get_closest_point_to(const Vector3 &p_point) const {
  121. if (plane.is_point_over(p_point)) {
  122. return plane.project(p_point);
  123. } else {
  124. return p_point;
  125. }
  126. }
  127. Vector3 GodotWorldBoundaryShape3D::get_moment_of_inertia(real_t p_mass) const {
  128. return Vector3(); // not applicable.
  129. }
  130. void GodotWorldBoundaryShape3D::_setup(const Plane &p_plane) {
  131. plane = p_plane;
  132. configure(AABB(Vector3(-1e15, -1e15, -1e15), Vector3(1e15 * 2, 1e15 * 2, 1e15 * 2)));
  133. }
  134. void GodotWorldBoundaryShape3D::set_data(const Variant &p_data) {
  135. _setup(p_data);
  136. }
  137. Variant GodotWorldBoundaryShape3D::get_data() const {
  138. return plane;
  139. }
  140. GodotWorldBoundaryShape3D::GodotWorldBoundaryShape3D() {
  141. }
  142. //
  143. real_t GodotSeparationRayShape3D::get_length() const {
  144. return length;
  145. }
  146. bool GodotSeparationRayShape3D::get_slide_on_slope() const {
  147. return slide_on_slope;
  148. }
  149. void GodotSeparationRayShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  150. // don't think this will be even used
  151. r_min = 0;
  152. r_max = 1;
  153. }
  154. Vector3 GodotSeparationRayShape3D::get_support(const Vector3 &p_normal) const {
  155. if (p_normal.z > 0) {
  156. return Vector3(0, 0, length);
  157. } else {
  158. return Vector3(0, 0, 0);
  159. }
  160. }
  161. void GodotSeparationRayShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
  162. if (Math::abs(p_normal.z) < edge_support_threshold_lower) {
  163. r_amount = 2;
  164. r_type = FEATURE_EDGE;
  165. r_supports[0] = Vector3(0, 0, 0);
  166. r_supports[1] = Vector3(0, 0, length);
  167. } else if (p_normal.z > 0) {
  168. r_amount = 1;
  169. r_type = FEATURE_POINT;
  170. *r_supports = Vector3(0, 0, length);
  171. } else {
  172. r_amount = 1;
  173. r_type = FEATURE_POINT;
  174. *r_supports = Vector3(0, 0, 0);
  175. }
  176. }
  177. bool GodotSeparationRayShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  178. return false; //simply not possible
  179. }
  180. bool GodotSeparationRayShape3D::intersect_point(const Vector3 &p_point) const {
  181. return false; //simply not possible
  182. }
  183. Vector3 GodotSeparationRayShape3D::get_closest_point_to(const Vector3 &p_point) const {
  184. Vector3 s[2] = {
  185. Vector3(0, 0, 0),
  186. Vector3(0, 0, length)
  187. };
  188. return Geometry3D::get_closest_point_to_segment(p_point, s);
  189. }
  190. Vector3 GodotSeparationRayShape3D::get_moment_of_inertia(real_t p_mass) const {
  191. return Vector3();
  192. }
  193. void GodotSeparationRayShape3D::_setup(real_t p_length, bool p_slide_on_slope) {
  194. length = p_length;
  195. slide_on_slope = p_slide_on_slope;
  196. configure(AABB(Vector3(0, 0, 0), Vector3(0.1, 0.1, length)));
  197. }
  198. void GodotSeparationRayShape3D::set_data(const Variant &p_data) {
  199. Dictionary d = p_data;
  200. _setup(d["length"], d["slide_on_slope"]);
  201. }
  202. Variant GodotSeparationRayShape3D::get_data() const {
  203. Dictionary d;
  204. d["length"] = length;
  205. d["slide_on_slope"] = slide_on_slope;
  206. return d;
  207. }
  208. GodotSeparationRayShape3D::GodotSeparationRayShape3D() {}
  209. /********** SPHERE *************/
  210. real_t GodotSphereShape3D::get_radius() const {
  211. return radius;
  212. }
  213. void GodotSphereShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  214. real_t d = p_normal.dot(p_transform.origin);
  215. // figure out scale at point
  216. Vector3 local_normal = p_transform.basis.xform_inv(p_normal);
  217. real_t scale = local_normal.length();
  218. r_min = d - (radius)*scale;
  219. r_max = d + (radius)*scale;
  220. }
  221. Vector3 GodotSphereShape3D::get_support(const Vector3 &p_normal) const {
  222. return p_normal * radius;
  223. }
  224. void GodotSphereShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
  225. *r_supports = p_normal * radius;
  226. r_amount = 1;
  227. r_type = FEATURE_POINT;
  228. }
  229. bool GodotSphereShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  230. return Geometry3D::segment_intersects_sphere(p_begin, p_end, Vector3(), radius, &r_result, &r_normal);
  231. }
  232. bool GodotSphereShape3D::intersect_point(const Vector3 &p_point) const {
  233. return p_point.length() < radius;
  234. }
  235. Vector3 GodotSphereShape3D::get_closest_point_to(const Vector3 &p_point) const {
  236. Vector3 p = p_point;
  237. real_t l = p.length();
  238. if (l < radius) {
  239. return p_point;
  240. }
  241. return (p / l) * radius;
  242. }
  243. Vector3 GodotSphereShape3D::get_moment_of_inertia(real_t p_mass) const {
  244. real_t s = 0.4 * p_mass * radius * radius;
  245. return Vector3(s, s, s);
  246. }
  247. void GodotSphereShape3D::_setup(real_t p_radius) {
  248. radius = p_radius;
  249. configure(AABB(Vector3(-radius, -radius, -radius), Vector3(radius * 2.0, radius * 2.0, radius * 2.0)));
  250. }
  251. void GodotSphereShape3D::set_data(const Variant &p_data) {
  252. _setup(p_data);
  253. }
  254. Variant GodotSphereShape3D::get_data() const {
  255. return radius;
  256. }
  257. GodotSphereShape3D::GodotSphereShape3D() {}
  258. /********** BOX *************/
  259. void GodotBoxShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  260. // no matter the angle, the box is mirrored anyway
  261. Vector3 local_normal = p_transform.basis.xform_inv(p_normal);
  262. real_t length = local_normal.abs().dot(half_extents);
  263. real_t distance = p_normal.dot(p_transform.origin);
  264. r_min = distance - length;
  265. r_max = distance + length;
  266. }
  267. Vector3 GodotBoxShape3D::get_support(const Vector3 &p_normal) const {
  268. Vector3 point(
  269. (p_normal.x < 0) ? -half_extents.x : half_extents.x,
  270. (p_normal.y < 0) ? -half_extents.y : half_extents.y,
  271. (p_normal.z < 0) ? -half_extents.z : half_extents.z);
  272. return point;
  273. }
  274. void GodotBoxShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
  275. static const int next[3] = { 1, 2, 0 };
  276. static const int next2[3] = { 2, 0, 1 };
  277. for (int i = 0; i < 3; i++) {
  278. Vector3 axis;
  279. axis[i] = 1.0;
  280. real_t dot = p_normal.dot(axis);
  281. if (Math::abs(dot) > face_support_threshold) {
  282. //Vector3 axis_b;
  283. bool neg = dot < 0;
  284. r_amount = 4;
  285. r_type = FEATURE_FACE;
  286. Vector3 point;
  287. point[i] = half_extents[i];
  288. int i_n = next[i];
  289. int i_n2 = next2[i];
  290. static const real_t sign[4][2] = {
  291. { -1.0, 1.0 },
  292. { 1.0, 1.0 },
  293. { 1.0, -1.0 },
  294. { -1.0, -1.0 },
  295. };
  296. for (int j = 0; j < 4; j++) {
  297. point[i_n] = sign[j][0] * half_extents[i_n];
  298. point[i_n2] = sign[j][1] * half_extents[i_n2];
  299. r_supports[j] = neg ? -point : point;
  300. }
  301. if (neg) {
  302. SWAP(r_supports[1], r_supports[2]);
  303. SWAP(r_supports[0], r_supports[3]);
  304. }
  305. return;
  306. }
  307. r_amount = 0;
  308. }
  309. for (int i = 0; i < 3; i++) {
  310. Vector3 axis;
  311. axis[i] = 1.0;
  312. if (Math::abs(p_normal.dot(axis)) < edge_support_threshold_lower) {
  313. r_amount = 2;
  314. r_type = FEATURE_EDGE;
  315. int i_n = next[i];
  316. int i_n2 = next2[i];
  317. Vector3 point = half_extents;
  318. if (p_normal[i_n] < 0) {
  319. point[i_n] = -point[i_n];
  320. }
  321. if (p_normal[i_n2] < 0) {
  322. point[i_n2] = -point[i_n2];
  323. }
  324. r_supports[0] = point;
  325. point[i] = -point[i];
  326. r_supports[1] = point;
  327. return;
  328. }
  329. }
  330. /* USE POINT */
  331. Vector3 point(
  332. (p_normal.x < 0) ? -half_extents.x : half_extents.x,
  333. (p_normal.y < 0) ? -half_extents.y : half_extents.y,
  334. (p_normal.z < 0) ? -half_extents.z : half_extents.z);
  335. r_amount = 1;
  336. r_type = FEATURE_POINT;
  337. r_supports[0] = point;
  338. }
  339. bool GodotBoxShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  340. AABB aabb_ext(-half_extents, half_extents * 2.0);
  341. return aabb_ext.intersects_segment(p_begin, p_end, &r_result, &r_normal);
  342. }
  343. bool GodotBoxShape3D::intersect_point(const Vector3 &p_point) const {
  344. return (Math::abs(p_point.x) < half_extents.x && Math::abs(p_point.y) < half_extents.y && Math::abs(p_point.z) < half_extents.z);
  345. }
  346. Vector3 GodotBoxShape3D::get_closest_point_to(const Vector3 &p_point) const {
  347. int outside = 0;
  348. Vector3 min_point;
  349. for (int i = 0; i < 3; i++) {
  350. if (Math::abs(p_point[i]) > half_extents[i]) {
  351. outside++;
  352. if (outside == 1) {
  353. //use plane if only one side matches
  354. Vector3 n;
  355. n[i] = SIGN(p_point[i]);
  356. Plane p(n, half_extents[i]);
  357. min_point = p.project(p_point);
  358. }
  359. }
  360. }
  361. if (!outside) {
  362. return p_point; //it's inside, don't do anything else
  363. }
  364. if (outside == 1) { //if only above one plane, this plane clearly wins
  365. return min_point;
  366. }
  367. //check segments
  368. real_t min_distance = 1e20;
  369. Vector3 closest_vertex = half_extents * p_point.sign();
  370. Vector3 s[2] = {
  371. closest_vertex,
  372. closest_vertex
  373. };
  374. for (int i = 0; i < 3; i++) {
  375. s[1] = closest_vertex;
  376. s[1][i] = -s[1][i]; //edge
  377. Vector3 closest_edge = Geometry3D::get_closest_point_to_segment(p_point, s);
  378. real_t d = p_point.distance_to(closest_edge);
  379. if (d < min_distance) {
  380. min_point = closest_edge;
  381. min_distance = d;
  382. }
  383. }
  384. return min_point;
  385. }
  386. Vector3 GodotBoxShape3D::get_moment_of_inertia(real_t p_mass) const {
  387. real_t lx = half_extents.x;
  388. real_t ly = half_extents.y;
  389. real_t lz = half_extents.z;
  390. return Vector3((p_mass / 3.0) * (ly * ly + lz * lz), (p_mass / 3.0) * (lx * lx + lz * lz), (p_mass / 3.0) * (lx * lx + ly * ly));
  391. }
  392. void GodotBoxShape3D::_setup(const Vector3 &p_half_extents) {
  393. half_extents = p_half_extents.abs();
  394. configure(AABB(-half_extents, half_extents * 2));
  395. }
  396. void GodotBoxShape3D::set_data(const Variant &p_data) {
  397. _setup(p_data);
  398. }
  399. Variant GodotBoxShape3D::get_data() const {
  400. return half_extents;
  401. }
  402. GodotBoxShape3D::GodotBoxShape3D() {}
  403. /********** CAPSULE *************/
  404. void GodotCapsuleShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  405. Vector3 n = p_transform.basis.xform_inv(p_normal).normalized();
  406. real_t h = height * 0.5 - radius;
  407. n *= radius;
  408. n.y += (n.y > 0) ? h : -h;
  409. r_max = p_normal.dot(p_transform.xform(n));
  410. r_min = p_normal.dot(p_transform.xform(-n));
  411. }
  412. Vector3 GodotCapsuleShape3D::get_support(const Vector3 &p_normal) const {
  413. Vector3 n = p_normal;
  414. real_t h = height * 0.5 - radius;
  415. n *= radius;
  416. n.y += (n.y > 0) ? h : -h;
  417. return n;
  418. }
  419. void GodotCapsuleShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
  420. Vector3 n = p_normal;
  421. real_t d = n.y;
  422. real_t h = height * 0.5 - radius; // half-height of the cylinder part
  423. if (h > 0 && Math::abs(d) < edge_support_threshold_lower) {
  424. // make it flat
  425. n.y = 0.0;
  426. n.normalize();
  427. n *= radius;
  428. r_amount = 2;
  429. r_type = FEATURE_EDGE;
  430. r_supports[0] = n;
  431. r_supports[0].y += h;
  432. r_supports[1] = n;
  433. r_supports[1].y -= h;
  434. } else {
  435. n *= radius;
  436. n.y += (d > 0) ? h : -h;
  437. r_amount = 1;
  438. r_type = FEATURE_POINT;
  439. *r_supports = n;
  440. }
  441. }
  442. bool GodotCapsuleShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  443. Vector3 norm = (p_end - p_begin).normalized();
  444. real_t min_d = 1e20;
  445. Vector3 res, n;
  446. bool collision = false;
  447. Vector3 auxres, auxn;
  448. bool collided;
  449. // test against cylinder and spheres :-|
  450. collided = Geometry3D::segment_intersects_cylinder(p_begin, p_end, height - radius * 2.0, radius, &auxres, &auxn, 1);
  451. if (collided) {
  452. real_t d = norm.dot(auxres);
  453. if (d < min_d) {
  454. min_d = d;
  455. res = auxres;
  456. n = auxn;
  457. collision = true;
  458. }
  459. }
  460. collided = Geometry3D::segment_intersects_sphere(p_begin, p_end, Vector3(0, height * 0.5 - radius, 0), radius, &auxres, &auxn);
  461. if (collided) {
  462. real_t d = norm.dot(auxres);
  463. if (d < min_d) {
  464. min_d = d;
  465. res = auxres;
  466. n = auxn;
  467. collision = true;
  468. }
  469. }
  470. collided = Geometry3D::segment_intersects_sphere(p_begin, p_end, Vector3(0, height * -0.5 + radius, 0), radius, &auxres, &auxn);
  471. if (collided) {
  472. real_t d = norm.dot(auxres);
  473. if (d < min_d) {
  474. min_d = d;
  475. res = auxres;
  476. n = auxn;
  477. collision = true;
  478. }
  479. }
  480. if (collision) {
  481. r_result = res;
  482. r_normal = n;
  483. }
  484. return collision;
  485. }
  486. bool GodotCapsuleShape3D::intersect_point(const Vector3 &p_point) const {
  487. if (Math::abs(p_point.y) < height * 0.5 - radius) {
  488. return Vector3(p_point.x, 0, p_point.z).length() < radius;
  489. } else {
  490. Vector3 p = p_point;
  491. p.y = Math::abs(p.y) - height * 0.5 + radius;
  492. return p.length() < radius;
  493. }
  494. }
  495. Vector3 GodotCapsuleShape3D::get_closest_point_to(const Vector3 &p_point) const {
  496. Vector3 s[2] = {
  497. Vector3(0, -height * 0.5 + radius, 0),
  498. Vector3(0, height * 0.5 - radius, 0),
  499. };
  500. Vector3 p = Geometry3D::get_closest_point_to_segment(p_point, s);
  501. if (p.distance_to(p_point) < radius) {
  502. return p_point;
  503. }
  504. return p + (p_point - p).normalized() * radius;
  505. }
  506. Vector3 GodotCapsuleShape3D::get_moment_of_inertia(real_t p_mass) const {
  507. // use bad AABB approximation
  508. Vector3 extents = get_aabb().size * 0.5;
  509. return Vector3(
  510. (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
  511. (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
  512. (p_mass / 3.0) * (extents.x * extents.x + extents.y * extents.y));
  513. }
  514. void GodotCapsuleShape3D::_setup(real_t p_height, real_t p_radius) {
  515. height = p_height;
  516. radius = p_radius;
  517. configure(AABB(Vector3(-radius, -height * 0.5, -radius), Vector3(radius * 2, height, radius * 2)));
  518. }
  519. void GodotCapsuleShape3D::set_data(const Variant &p_data) {
  520. Dictionary d = p_data;
  521. ERR_FAIL_COND(!d.has("radius"));
  522. ERR_FAIL_COND(!d.has("height"));
  523. _setup(d["height"], d["radius"]);
  524. }
  525. Variant GodotCapsuleShape3D::get_data() const {
  526. Dictionary d;
  527. d["radius"] = radius;
  528. d["height"] = height;
  529. return d;
  530. }
  531. GodotCapsuleShape3D::GodotCapsuleShape3D() {}
  532. /********** CYLINDER *************/
  533. void GodotCylinderShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  534. Vector3 cylinder_axis = p_transform.basis.get_column(1).normalized();
  535. real_t axis_dot = cylinder_axis.dot(p_normal);
  536. Vector3 local_normal = p_transform.basis.xform_inv(p_normal);
  537. real_t scale = local_normal.length();
  538. real_t scaled_radius = radius * scale;
  539. real_t scaled_height = height * scale;
  540. real_t length;
  541. if (Math::abs(axis_dot) > 1.0) {
  542. length = scaled_height * 0.5;
  543. } else {
  544. length = Math::abs(axis_dot * scaled_height * 0.5) + scaled_radius * Math::sqrt(1.0 - axis_dot * axis_dot);
  545. }
  546. real_t distance = p_normal.dot(p_transform.origin);
  547. r_min = distance - length;
  548. r_max = distance + length;
  549. }
  550. Vector3 GodotCylinderShape3D::get_support(const Vector3 &p_normal) const {
  551. Vector3 n = p_normal;
  552. real_t h = (n.y > 0) ? height : -height;
  553. real_t s = Math::sqrt(n.x * n.x + n.z * n.z);
  554. if (Math::is_zero_approx(s)) {
  555. n.x = radius;
  556. n.y = h * 0.5;
  557. n.z = 0.0;
  558. } else {
  559. real_t d = radius / s;
  560. n.x = n.x * d;
  561. n.y = h * 0.5;
  562. n.z = n.z * d;
  563. }
  564. return n;
  565. }
  566. void GodotCylinderShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
  567. real_t d = p_normal.y;
  568. if (Math::abs(d) > cylinder_face_support_threshold) {
  569. real_t h = (d > 0) ? height : -height;
  570. Vector3 n = p_normal;
  571. n.x = 0.0;
  572. n.z = 0.0;
  573. n.y = h * 0.5;
  574. r_amount = 3;
  575. r_type = FEATURE_CIRCLE;
  576. r_supports[0] = n;
  577. r_supports[1] = n;
  578. r_supports[1].x += radius;
  579. r_supports[2] = n;
  580. r_supports[2].z += radius;
  581. } else if (Math::abs(d) < cylinder_edge_support_threshold_lower) {
  582. // make it flat
  583. Vector3 n = p_normal;
  584. n.y = 0.0;
  585. n.normalize();
  586. n *= radius;
  587. r_amount = 2;
  588. r_type = FEATURE_EDGE;
  589. r_supports[0] = n;
  590. r_supports[0].y += height * 0.5;
  591. r_supports[1] = n;
  592. r_supports[1].y -= height * 0.5;
  593. } else {
  594. r_amount = 1;
  595. r_type = FEATURE_POINT;
  596. r_supports[0] = get_support(p_normal);
  597. }
  598. }
  599. bool GodotCylinderShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  600. return Geometry3D::segment_intersects_cylinder(p_begin, p_end, height, radius, &r_result, &r_normal, 1);
  601. }
  602. bool GodotCylinderShape3D::intersect_point(const Vector3 &p_point) const {
  603. if (Math::abs(p_point.y) < height * 0.5) {
  604. return Vector3(p_point.x, 0, p_point.z).length() < radius;
  605. }
  606. return false;
  607. }
  608. Vector3 GodotCylinderShape3D::get_closest_point_to(const Vector3 &p_point) const {
  609. if (Math::absf(p_point.y) > height * 0.5) {
  610. // Project point to top disk.
  611. real_t dir = p_point.y > 0.0 ? 1.0 : -1.0;
  612. Vector3 circle_pos(0.0, dir * height * 0.5, 0.0);
  613. Plane circle_plane(Vector3(0.0, dir, 0.0), circle_pos);
  614. Vector3 proj_point = circle_plane.project(p_point);
  615. // Clip position.
  616. Vector3 delta_point_1 = proj_point - circle_pos;
  617. real_t dist_point_1 = delta_point_1.length_squared();
  618. if (!Math::is_zero_approx(dist_point_1)) {
  619. dist_point_1 = Math::sqrt(dist_point_1);
  620. proj_point = circle_pos + delta_point_1 * MIN(dist_point_1, radius) / dist_point_1;
  621. }
  622. return proj_point;
  623. } else {
  624. Vector3 s[2] = {
  625. Vector3(0, -height * 0.5, 0),
  626. Vector3(0, height * 0.5, 0),
  627. };
  628. Vector3 p = Geometry3D::get_closest_point_to_segment(p_point, s);
  629. if (p.distance_to(p_point) < radius) {
  630. return p_point;
  631. }
  632. return p + (p_point - p).normalized() * radius;
  633. }
  634. }
  635. Vector3 GodotCylinderShape3D::get_moment_of_inertia(real_t p_mass) const {
  636. // use bad AABB approximation
  637. Vector3 extents = get_aabb().size * 0.5;
  638. return Vector3(
  639. (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
  640. (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
  641. (p_mass / 3.0) * (extents.x * extents.x + extents.y * extents.y));
  642. }
  643. void GodotCylinderShape3D::_setup(real_t p_height, real_t p_radius) {
  644. height = p_height;
  645. radius = p_radius;
  646. configure(AABB(Vector3(-radius, -height * 0.5, -radius), Vector3(radius * 2.0, height, radius * 2.0)));
  647. }
  648. void GodotCylinderShape3D::set_data(const Variant &p_data) {
  649. Dictionary d = p_data;
  650. ERR_FAIL_COND(!d.has("radius"));
  651. ERR_FAIL_COND(!d.has("height"));
  652. _setup(d["height"], d["radius"]);
  653. }
  654. Variant GodotCylinderShape3D::get_data() const {
  655. Dictionary d;
  656. d["radius"] = radius;
  657. d["height"] = height;
  658. return d;
  659. }
  660. GodotCylinderShape3D::GodotCylinderShape3D() {}
  661. /********** CONVEX POLYGON *************/
  662. void GodotConvexPolygonShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  663. uint32_t vertex_count = mesh.vertices.size();
  664. if (vertex_count == 0) {
  665. return;
  666. }
  667. const Vector3 *vrts = &mesh.vertices[0];
  668. if (vertex_count > 3 * extreme_vertices.size()) {
  669. // For a large mesh, two calls to get_support() is faster than a full
  670. // scan over all vertices.
  671. Vector3 n = p_transform.basis.xform_inv(p_normal).normalized();
  672. r_min = p_normal.dot(p_transform.xform(get_support(-n)));
  673. r_max = p_normal.dot(p_transform.xform(get_support(n)));
  674. } else {
  675. for (uint32_t i = 0; i < vertex_count; i++) {
  676. real_t d = p_normal.dot(p_transform.xform(vrts[i]));
  677. if (i == 0 || d > r_max) {
  678. r_max = d;
  679. }
  680. if (i == 0 || d < r_min) {
  681. r_min = d;
  682. }
  683. }
  684. }
  685. }
  686. Vector3 GodotConvexPolygonShape3D::get_support(const Vector3 &p_normal) const {
  687. // Skip if there are no vertices in the mesh
  688. if (mesh.vertices.size() == 0) {
  689. return Vector3();
  690. }
  691. // Get the array of vertices
  692. const Vector3 *const vertices_array = mesh.vertices.ptr();
  693. // Start with an initial assumption of the first extreme vertex.
  694. int best_vertex = extreme_vertices[0];
  695. real_t max_support = p_normal.dot(vertices_array[best_vertex]);
  696. // Check the remaining extreme vertices for a better vertex.
  697. for (const int &vert : extreme_vertices) {
  698. real_t s = p_normal.dot(vertices_array[vert]);
  699. if (s > max_support) {
  700. best_vertex = vert;
  701. max_support = s;
  702. }
  703. }
  704. // If we checked all vertices in the mesh then we're done.
  705. if (extreme_vertices.size() == mesh.vertices.size()) {
  706. return vertices_array[best_vertex];
  707. }
  708. // Move along the surface until we reach the true support vertex.
  709. int last_vertex = -1;
  710. while (true) {
  711. int next_vertex = -1;
  712. // Iterate over all the neighbors checking for a better vertex.
  713. for (const int &vert : vertex_neighbors[best_vertex]) {
  714. if (vert != last_vertex) {
  715. real_t s = p_normal.dot(vertices_array[vert]);
  716. if (s > max_support) {
  717. next_vertex = vert;
  718. max_support = s;
  719. break;
  720. }
  721. }
  722. }
  723. // No better vertex found, we have the best
  724. if (next_vertex == -1) {
  725. return vertices_array[best_vertex];
  726. }
  727. // Move to the better vertex and try again
  728. last_vertex = best_vertex;
  729. best_vertex = next_vertex;
  730. }
  731. }
  732. void GodotConvexPolygonShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
  733. const Geometry3D::MeshData::Face *faces = mesh.faces.ptr();
  734. int fc = mesh.faces.size();
  735. const Geometry3D::MeshData::Edge *edges = mesh.edges.ptr();
  736. int ec = mesh.edges.size();
  737. const Vector3 *vertices = mesh.vertices.ptr();
  738. int vc = mesh.vertices.size();
  739. r_amount = 0;
  740. ERR_FAIL_COND_MSG(vc == 0, "Convex polygon shape has no vertices.");
  741. //find vertex first
  742. real_t max = 0;
  743. int vtx = 0;
  744. for (int i = 0; i < vc; i++) {
  745. real_t d = p_normal.dot(vertices[i]);
  746. if (i == 0 || d > max) {
  747. max = d;
  748. vtx = i;
  749. }
  750. }
  751. for (int i = 0; i < fc; i++) {
  752. if (faces[i].plane.normal.dot(p_normal) > face_support_threshold) {
  753. int ic = faces[i].indices.size();
  754. const int *ind = faces[i].indices.ptr();
  755. bool valid = false;
  756. for (int j = 0; j < ic; j++) {
  757. if (ind[j] == vtx) {
  758. valid = true;
  759. break;
  760. }
  761. }
  762. if (!valid) {
  763. continue;
  764. }
  765. int m = MIN(p_max, ic);
  766. for (int j = 0; j < m; j++) {
  767. r_supports[j] = vertices[ind[j]];
  768. }
  769. r_amount = m;
  770. r_type = FEATURE_FACE;
  771. return;
  772. }
  773. }
  774. for (int i = 0; i < ec; i++) {
  775. real_t dot = (vertices[edges[i].vertex_a] - vertices[edges[i].vertex_b]).normalized().dot(p_normal);
  776. dot = ABS(dot);
  777. if (dot < edge_support_threshold_lower && (edges[i].vertex_a == vtx || edges[i].vertex_b == vtx)) {
  778. r_amount = 2;
  779. r_type = FEATURE_EDGE;
  780. r_supports[0] = vertices[edges[i].vertex_a];
  781. r_supports[1] = vertices[edges[i].vertex_b];
  782. return;
  783. }
  784. }
  785. r_supports[0] = vertices[vtx];
  786. r_amount = 1;
  787. r_type = FEATURE_POINT;
  788. }
  789. bool GodotConvexPolygonShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  790. const Geometry3D::MeshData::Face *faces = mesh.faces.ptr();
  791. int fc = mesh.faces.size();
  792. const Vector3 *vertices = mesh.vertices.ptr();
  793. Vector3 n = p_end - p_begin;
  794. real_t min = 1e20;
  795. bool col = false;
  796. for (int i = 0; i < fc; i++) {
  797. if (faces[i].plane.normal.dot(n) > 0) {
  798. continue; //opposing face
  799. }
  800. int ic = faces[i].indices.size();
  801. const int *ind = faces[i].indices.ptr();
  802. for (int j = 1; j < ic - 1; j++) {
  803. Face3 f(vertices[ind[0]], vertices[ind[j]], vertices[ind[j + 1]]);
  804. Vector3 result;
  805. if (f.intersects_segment(p_begin, p_end, &result)) {
  806. real_t d = n.dot(result);
  807. if (d < min) {
  808. min = d;
  809. r_result = result;
  810. r_normal = faces[i].plane.normal;
  811. col = true;
  812. }
  813. break;
  814. }
  815. }
  816. }
  817. return col;
  818. }
  819. bool GodotConvexPolygonShape3D::intersect_point(const Vector3 &p_point) const {
  820. const Geometry3D::MeshData::Face *faces = mesh.faces.ptr();
  821. int fc = mesh.faces.size();
  822. for (int i = 0; i < fc; i++) {
  823. if (faces[i].plane.distance_to(p_point) >= 0) {
  824. return false;
  825. }
  826. }
  827. return true;
  828. }
  829. Vector3 GodotConvexPolygonShape3D::get_closest_point_to(const Vector3 &p_point) const {
  830. const Geometry3D::MeshData::Face *faces = mesh.faces.ptr();
  831. int fc = mesh.faces.size();
  832. const Vector3 *vertices = mesh.vertices.ptr();
  833. bool all_inside = true;
  834. for (int i = 0; i < fc; i++) {
  835. if (!faces[i].plane.is_point_over(p_point)) {
  836. continue;
  837. }
  838. all_inside = false;
  839. bool is_inside = true;
  840. int ic = faces[i].indices.size();
  841. const int *indices = faces[i].indices.ptr();
  842. for (int j = 0; j < ic; j++) {
  843. Vector3 a = vertices[indices[j]];
  844. Vector3 b = vertices[indices[(j + 1) % ic]];
  845. Vector3 n = (a - b).cross(faces[i].plane.normal).normalized();
  846. if (Plane(n, a).is_point_over(p_point)) {
  847. is_inside = false;
  848. break;
  849. }
  850. }
  851. if (is_inside) {
  852. return faces[i].plane.project(p_point);
  853. }
  854. }
  855. if (all_inside) {
  856. return p_point;
  857. }
  858. real_t min_distance = 1e20;
  859. Vector3 min_point;
  860. //check edges
  861. const Geometry3D::MeshData::Edge *edges = mesh.edges.ptr();
  862. int ec = mesh.edges.size();
  863. for (int i = 0; i < ec; i++) {
  864. Vector3 s[2] = {
  865. vertices[edges[i].vertex_a],
  866. vertices[edges[i].vertex_b]
  867. };
  868. Vector3 closest = Geometry3D::get_closest_point_to_segment(p_point, s);
  869. real_t d = closest.distance_to(p_point);
  870. if (d < min_distance) {
  871. min_distance = d;
  872. min_point = closest;
  873. }
  874. }
  875. return min_point;
  876. }
  877. Vector3 GodotConvexPolygonShape3D::get_moment_of_inertia(real_t p_mass) const {
  878. // use bad AABB approximation
  879. Vector3 extents = get_aabb().size * 0.5;
  880. return Vector3(
  881. (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
  882. (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
  883. (p_mass / 3.0) * (extents.x * extents.x + extents.y * extents.y));
  884. }
  885. void GodotConvexPolygonShape3D::_setup(const Vector<Vector3> &p_vertices) {
  886. Error err = ConvexHullComputer::convex_hull(p_vertices, mesh);
  887. if (err != OK) {
  888. ERR_PRINT("Failed to build convex hull");
  889. }
  890. extreme_vertices.resize(0);
  891. vertex_neighbors.resize(0);
  892. AABB _aabb;
  893. for (uint32_t i = 0; i < mesh.vertices.size(); i++) {
  894. if (i == 0) {
  895. _aabb.position = mesh.vertices[i];
  896. } else {
  897. _aabb.expand_to(mesh.vertices[i]);
  898. }
  899. }
  900. configure(_aabb);
  901. // Pre-compute the extreme vertices in 26 directions. This will be used
  902. // to speed up get_support() by letting us quickly get a good guess for
  903. // the support vertex.
  904. for (int x = -1; x < 2; x++) {
  905. for (int y = -1; y < 2; y++) {
  906. for (int z = -1; z < 2; z++) {
  907. if (x != 0 || y != 0 || z != 0) {
  908. Vector3 dir(x, y, z);
  909. dir.normalize();
  910. real_t max_support = 0.0;
  911. int best_vertex = -1;
  912. for (uint32_t i = 0; i < mesh.vertices.size(); i++) {
  913. real_t s = dir.dot(mesh.vertices[i]);
  914. if (best_vertex == -1 || s > max_support) {
  915. best_vertex = i;
  916. max_support = s;
  917. }
  918. }
  919. if (!extreme_vertices.has(best_vertex)) {
  920. extreme_vertices.push_back(best_vertex);
  921. }
  922. }
  923. }
  924. }
  925. }
  926. // Record all the neighbors of each vertex. This is used in get_support().
  927. if (extreme_vertices.size() < mesh.vertices.size()) {
  928. vertex_neighbors.resize(mesh.vertices.size());
  929. for (Geometry3D::MeshData::Edge &edge : mesh.edges) {
  930. vertex_neighbors[edge.vertex_a].push_back(edge.vertex_b);
  931. vertex_neighbors[edge.vertex_b].push_back(edge.vertex_a);
  932. }
  933. }
  934. }
  935. void GodotConvexPolygonShape3D::set_data(const Variant &p_data) {
  936. _setup(p_data);
  937. }
  938. Variant GodotConvexPolygonShape3D::get_data() const {
  939. Vector<Vector3> vertices;
  940. vertices.resize(mesh.vertices.size());
  941. for (uint32_t i = 0; i < mesh.vertices.size(); i++) {
  942. vertices.write[i] = mesh.vertices[i];
  943. }
  944. return vertices;
  945. }
  946. GodotConvexPolygonShape3D::GodotConvexPolygonShape3D() {
  947. }
  948. /********** FACE POLYGON *************/
  949. void GodotFaceShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  950. for (int i = 0; i < 3; i++) {
  951. Vector3 v = p_transform.xform(vertex[i]);
  952. real_t d = p_normal.dot(v);
  953. if (i == 0 || d > r_max) {
  954. r_max = d;
  955. }
  956. if (i == 0 || d < r_min) {
  957. r_min = d;
  958. }
  959. }
  960. }
  961. Vector3 GodotFaceShape3D::get_support(const Vector3 &p_normal) const {
  962. int vert_support_idx = -1;
  963. real_t support_max = 0;
  964. for (int i = 0; i < 3; i++) {
  965. real_t d = p_normal.dot(vertex[i]);
  966. if (i == 0 || d > support_max) {
  967. support_max = d;
  968. vert_support_idx = i;
  969. }
  970. }
  971. return vertex[vert_support_idx];
  972. }
  973. void GodotFaceShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
  974. Vector3 n = p_normal;
  975. /** TEST FACE AS SUPPORT **/
  976. if (Math::abs(normal.dot(n)) > face_support_threshold) {
  977. r_amount = 3;
  978. r_type = FEATURE_FACE;
  979. for (int i = 0; i < 3; i++) {
  980. r_supports[i] = vertex[i];
  981. }
  982. return;
  983. }
  984. /** FIND SUPPORT VERTEX **/
  985. int vert_support_idx = -1;
  986. real_t support_max = 0;
  987. for (int i = 0; i < 3; i++) {
  988. real_t d = n.dot(vertex[i]);
  989. if (i == 0 || d > support_max) {
  990. support_max = d;
  991. vert_support_idx = i;
  992. }
  993. }
  994. /** TEST EDGES AS SUPPORT **/
  995. for (int i = 0; i < 3; i++) {
  996. int nx = (i + 1) % 3;
  997. if (i != vert_support_idx && nx != vert_support_idx) {
  998. continue;
  999. }
  1000. // check if edge is valid as a support
  1001. real_t dot = (vertex[i] - vertex[nx]).normalized().dot(n);
  1002. dot = ABS(dot);
  1003. if (dot < edge_support_threshold_lower) {
  1004. r_amount = 2;
  1005. r_type = FEATURE_EDGE;
  1006. r_supports[0] = vertex[i];
  1007. r_supports[1] = vertex[nx];
  1008. return;
  1009. }
  1010. }
  1011. r_amount = 1;
  1012. r_type = FEATURE_POINT;
  1013. r_supports[0] = vertex[vert_support_idx];
  1014. }
  1015. bool GodotFaceShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  1016. bool c = Geometry3D::segment_intersects_triangle(p_begin, p_end, vertex[0], vertex[1], vertex[2], &r_result);
  1017. if (c) {
  1018. r_normal = Plane(vertex[0], vertex[1], vertex[2]).normal;
  1019. if (r_normal.dot(p_end - p_begin) > 0) {
  1020. if (backface_collision && p_hit_back_faces) {
  1021. r_normal = -r_normal;
  1022. } else {
  1023. c = false;
  1024. }
  1025. }
  1026. }
  1027. return c;
  1028. }
  1029. bool GodotFaceShape3D::intersect_point(const Vector3 &p_point) const {
  1030. return false; //face is flat
  1031. }
  1032. Vector3 GodotFaceShape3D::get_closest_point_to(const Vector3 &p_point) const {
  1033. return Face3(vertex[0], vertex[1], vertex[2]).get_closest_point_to(p_point);
  1034. }
  1035. Vector3 GodotFaceShape3D::get_moment_of_inertia(real_t p_mass) const {
  1036. return Vector3(); // Sorry, but i don't think anyone cares, FaceShape!
  1037. }
  1038. GodotFaceShape3D::GodotFaceShape3D() {
  1039. configure(AABB());
  1040. }
  1041. Vector<Vector3> GodotConcavePolygonShape3D::get_faces() const {
  1042. Vector<Vector3> rfaces;
  1043. rfaces.resize(faces.size() * 3);
  1044. for (int i = 0; i < faces.size(); i++) {
  1045. Face f = faces.get(i);
  1046. for (int j = 0; j < 3; j++) {
  1047. rfaces.set(i * 3 + j, vertices.get(f.indices[j]));
  1048. }
  1049. }
  1050. return rfaces;
  1051. }
  1052. void GodotConcavePolygonShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  1053. int count = vertices.size();
  1054. if (count == 0) {
  1055. r_min = 0;
  1056. r_max = 0;
  1057. return;
  1058. }
  1059. const Vector3 *vptr = vertices.ptr();
  1060. for (int i = 0; i < count; i++) {
  1061. real_t d = p_normal.dot(p_transform.xform(vptr[i]));
  1062. if (i == 0 || d > r_max) {
  1063. r_max = d;
  1064. }
  1065. if (i == 0 || d < r_min) {
  1066. r_min = d;
  1067. }
  1068. }
  1069. }
  1070. Vector3 GodotConcavePolygonShape3D::get_support(const Vector3 &p_normal) const {
  1071. int count = vertices.size();
  1072. if (count == 0) {
  1073. return Vector3();
  1074. }
  1075. const Vector3 *vptr = vertices.ptr();
  1076. Vector3 n = p_normal;
  1077. int vert_support_idx = -1;
  1078. real_t support_max = 0;
  1079. for (int i = 0; i < count; i++) {
  1080. real_t d = n.dot(vptr[i]);
  1081. if (i == 0 || d > support_max) {
  1082. support_max = d;
  1083. vert_support_idx = i;
  1084. }
  1085. }
  1086. return vptr[vert_support_idx];
  1087. }
  1088. void GodotConcavePolygonShape3D::_cull_segment(int p_idx, _SegmentCullParams *p_params) const {
  1089. const BVH *params_bvh = &p_params->bvh[p_idx];
  1090. if (!params_bvh->aabb.intersects_segment(p_params->from, p_params->to)) {
  1091. return;
  1092. }
  1093. if (params_bvh->face_index >= 0) {
  1094. const Face *f = &p_params->faces[params_bvh->face_index];
  1095. GodotFaceShape3D *face = p_params->face;
  1096. face->normal = f->normal;
  1097. face->vertex[0] = p_params->vertices[f->indices[0]];
  1098. face->vertex[1] = p_params->vertices[f->indices[1]];
  1099. face->vertex[2] = p_params->vertices[f->indices[2]];
  1100. Vector3 res;
  1101. Vector3 normal;
  1102. int face_index = params_bvh->face_index;
  1103. if (face->intersect_segment(p_params->from, p_params->to, res, normal, face_index, true)) {
  1104. real_t d = p_params->dir.dot(res) - p_params->dir.dot(p_params->from);
  1105. if ((d > 0) && (d < p_params->min_d)) {
  1106. p_params->min_d = d;
  1107. p_params->result = res;
  1108. p_params->normal = normal;
  1109. p_params->face_index = face_index;
  1110. p_params->collisions++;
  1111. }
  1112. }
  1113. } else {
  1114. if (params_bvh->left >= 0) {
  1115. _cull_segment(params_bvh->left, p_params);
  1116. }
  1117. if (params_bvh->right >= 0) {
  1118. _cull_segment(params_bvh->right, p_params);
  1119. }
  1120. }
  1121. }
  1122. bool GodotConcavePolygonShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  1123. if (faces.size() == 0) {
  1124. return false;
  1125. }
  1126. // unlock data
  1127. const Face *fr = faces.ptr();
  1128. const Vector3 *vr = vertices.ptr();
  1129. const BVH *br = bvh.ptr();
  1130. GodotFaceShape3D face;
  1131. face.backface_collision = backface_collision && p_hit_back_faces;
  1132. _SegmentCullParams params;
  1133. params.from = p_begin;
  1134. params.to = p_end;
  1135. params.dir = (p_end - p_begin).normalized();
  1136. params.faces = fr;
  1137. params.vertices = vr;
  1138. params.bvh = br;
  1139. params.face = &face;
  1140. // cull
  1141. _cull_segment(0, &params);
  1142. if (params.collisions > 0) {
  1143. r_result = params.result;
  1144. r_normal = params.normal;
  1145. r_face_index = params.face_index;
  1146. return true;
  1147. } else {
  1148. return false;
  1149. }
  1150. }
  1151. bool GodotConcavePolygonShape3D::intersect_point(const Vector3 &p_point) const {
  1152. return false; //face is flat
  1153. }
  1154. Vector3 GodotConcavePolygonShape3D::get_closest_point_to(const Vector3 &p_point) const {
  1155. return Vector3();
  1156. }
  1157. bool GodotConcavePolygonShape3D::_cull(int p_idx, _CullParams *p_params) const {
  1158. const BVH *params_bvh = &p_params->bvh[p_idx];
  1159. if (!p_params->aabb.intersects(params_bvh->aabb)) {
  1160. return false;
  1161. }
  1162. if (params_bvh->face_index >= 0) {
  1163. const Face *f = &p_params->faces[params_bvh->face_index];
  1164. GodotFaceShape3D *face = p_params->face;
  1165. face->normal = f->normal;
  1166. face->vertex[0] = p_params->vertices[f->indices[0]];
  1167. face->vertex[1] = p_params->vertices[f->indices[1]];
  1168. face->vertex[2] = p_params->vertices[f->indices[2]];
  1169. if (p_params->callback(p_params->userdata, face)) {
  1170. return true;
  1171. }
  1172. } else {
  1173. if (params_bvh->left >= 0) {
  1174. if (_cull(params_bvh->left, p_params)) {
  1175. return true;
  1176. }
  1177. }
  1178. if (params_bvh->right >= 0) {
  1179. if (_cull(params_bvh->right, p_params)) {
  1180. return true;
  1181. }
  1182. }
  1183. }
  1184. return false;
  1185. }
  1186. void GodotConcavePolygonShape3D::cull(const AABB &p_local_aabb, QueryCallback p_callback, void *p_userdata, bool p_invert_backface_collision) const {
  1187. // make matrix local to concave
  1188. if (faces.size() == 0) {
  1189. return;
  1190. }
  1191. AABB local_aabb = p_local_aabb;
  1192. // unlock data
  1193. const Face *fr = faces.ptr();
  1194. const Vector3 *vr = vertices.ptr();
  1195. const BVH *br = bvh.ptr();
  1196. GodotFaceShape3D face; // use this to send in the callback
  1197. face.backface_collision = backface_collision;
  1198. face.invert_backface_collision = p_invert_backface_collision;
  1199. _CullParams params;
  1200. params.aabb = local_aabb;
  1201. params.face = &face;
  1202. params.faces = fr;
  1203. params.vertices = vr;
  1204. params.bvh = br;
  1205. params.callback = p_callback;
  1206. params.userdata = p_userdata;
  1207. // cull
  1208. _cull(0, &params);
  1209. }
  1210. Vector3 GodotConcavePolygonShape3D::get_moment_of_inertia(real_t p_mass) const {
  1211. // use bad AABB approximation
  1212. Vector3 extents = get_aabb().size * 0.5;
  1213. return Vector3(
  1214. (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
  1215. (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
  1216. (p_mass / 3.0) * (extents.x * extents.x + extents.y * extents.y));
  1217. }
  1218. struct _Volume_BVH_Element {
  1219. AABB aabb;
  1220. Vector3 center;
  1221. int face_index = 0;
  1222. };
  1223. struct _Volume_BVH_CompareX {
  1224. _FORCE_INLINE_ bool operator()(const _Volume_BVH_Element &a, const _Volume_BVH_Element &b) const {
  1225. return a.center.x < b.center.x;
  1226. }
  1227. };
  1228. struct _Volume_BVH_CompareY {
  1229. _FORCE_INLINE_ bool operator()(const _Volume_BVH_Element &a, const _Volume_BVH_Element &b) const {
  1230. return a.center.y < b.center.y;
  1231. }
  1232. };
  1233. struct _Volume_BVH_CompareZ {
  1234. _FORCE_INLINE_ bool operator()(const _Volume_BVH_Element &a, const _Volume_BVH_Element &b) const {
  1235. return a.center.z < b.center.z;
  1236. }
  1237. };
  1238. struct _Volume_BVH {
  1239. AABB aabb;
  1240. _Volume_BVH *left = nullptr;
  1241. _Volume_BVH *right = nullptr;
  1242. int face_index = 0;
  1243. };
  1244. _Volume_BVH *_volume_build_bvh(_Volume_BVH_Element *p_elements, int p_size, int &count) {
  1245. _Volume_BVH *bvh = memnew(_Volume_BVH);
  1246. if (p_size == 1) {
  1247. //leaf
  1248. bvh->aabb = p_elements[0].aabb;
  1249. bvh->left = nullptr;
  1250. bvh->right = nullptr;
  1251. bvh->face_index = p_elements->face_index;
  1252. count++;
  1253. return bvh;
  1254. } else {
  1255. bvh->face_index = -1;
  1256. }
  1257. AABB aabb;
  1258. for (int i = 0; i < p_size; i++) {
  1259. if (i == 0) {
  1260. aabb = p_elements[i].aabb;
  1261. } else {
  1262. aabb.merge_with(p_elements[i].aabb);
  1263. }
  1264. }
  1265. bvh->aabb = aabb;
  1266. switch (aabb.get_longest_axis_index()) {
  1267. case 0: {
  1268. SortArray<_Volume_BVH_Element, _Volume_BVH_CompareX> sort_x;
  1269. sort_x.sort(p_elements, p_size);
  1270. } break;
  1271. case 1: {
  1272. SortArray<_Volume_BVH_Element, _Volume_BVH_CompareY> sort_y;
  1273. sort_y.sort(p_elements, p_size);
  1274. } break;
  1275. case 2: {
  1276. SortArray<_Volume_BVH_Element, _Volume_BVH_CompareZ> sort_z;
  1277. sort_z.sort(p_elements, p_size);
  1278. } break;
  1279. }
  1280. int split = p_size / 2;
  1281. bvh->left = _volume_build_bvh(p_elements, split, count);
  1282. bvh->right = _volume_build_bvh(&p_elements[split], p_size - split, count);
  1283. //printf("branch at %p - %i: %i\n",bvh,count,bvh->face_index);
  1284. count++;
  1285. return bvh;
  1286. }
  1287. void GodotConcavePolygonShape3D::_fill_bvh(_Volume_BVH *p_bvh_tree, BVH *p_bvh_array, int &p_idx) {
  1288. int idx = p_idx;
  1289. p_bvh_array[idx].aabb = p_bvh_tree->aabb;
  1290. p_bvh_array[idx].face_index = p_bvh_tree->face_index;
  1291. //printf("%p - %i: %i(%p) -- %p:%p\n",%p_bvh_array[idx],p_idx,p_bvh_array[i]->face_index,&p_bvh_tree->face_index,p_bvh_tree->left,p_bvh_tree->right);
  1292. if (p_bvh_tree->left) {
  1293. p_bvh_array[idx].left = ++p_idx;
  1294. _fill_bvh(p_bvh_tree->left, p_bvh_array, p_idx);
  1295. } else {
  1296. p_bvh_array[p_idx].left = -1;
  1297. }
  1298. if (p_bvh_tree->right) {
  1299. p_bvh_array[idx].right = ++p_idx;
  1300. _fill_bvh(p_bvh_tree->right, p_bvh_array, p_idx);
  1301. } else {
  1302. p_bvh_array[p_idx].right = -1;
  1303. }
  1304. memdelete(p_bvh_tree);
  1305. }
  1306. void GodotConcavePolygonShape3D::_setup(const Vector<Vector3> &p_faces, bool p_backface_collision) {
  1307. int src_face_count = p_faces.size();
  1308. if (src_face_count == 0) {
  1309. configure(AABB());
  1310. return;
  1311. }
  1312. ERR_FAIL_COND(src_face_count % 3);
  1313. src_face_count /= 3;
  1314. const Vector3 *facesr = p_faces.ptr();
  1315. Vector<_Volume_BVH_Element> bvh_array;
  1316. bvh_array.resize(src_face_count);
  1317. _Volume_BVH_Element *bvh_arrayw = bvh_array.ptrw();
  1318. faces.resize(src_face_count);
  1319. Face *facesw = faces.ptrw();
  1320. vertices.resize(src_face_count * 3);
  1321. Vector3 *verticesw = vertices.ptrw();
  1322. AABB _aabb;
  1323. for (int i = 0; i < src_face_count; i++) {
  1324. Face3 face(facesr[i * 3 + 0], facesr[i * 3 + 1], facesr[i * 3 + 2]);
  1325. bvh_arrayw[i].aabb = face.get_aabb();
  1326. bvh_arrayw[i].center = bvh_arrayw[i].aabb.get_center();
  1327. bvh_arrayw[i].face_index = i;
  1328. facesw[i].indices[0] = i * 3 + 0;
  1329. facesw[i].indices[1] = i * 3 + 1;
  1330. facesw[i].indices[2] = i * 3 + 2;
  1331. facesw[i].normal = face.get_plane().normal;
  1332. verticesw[i * 3 + 0] = face.vertex[0];
  1333. verticesw[i * 3 + 1] = face.vertex[1];
  1334. verticesw[i * 3 + 2] = face.vertex[2];
  1335. if (i == 0) {
  1336. _aabb = bvh_arrayw[i].aabb;
  1337. } else {
  1338. _aabb.merge_with(bvh_arrayw[i].aabb);
  1339. }
  1340. }
  1341. int count = 0;
  1342. _Volume_BVH *bvh_tree = _volume_build_bvh(bvh_arrayw, src_face_count, count);
  1343. bvh.resize(count + 1);
  1344. BVH *bvh_arrayw2 = bvh.ptrw();
  1345. int idx = 0;
  1346. _fill_bvh(bvh_tree, bvh_arrayw2, idx);
  1347. backface_collision = p_backface_collision;
  1348. configure(_aabb); // this type of shape has no margin
  1349. }
  1350. void GodotConcavePolygonShape3D::set_data(const Variant &p_data) {
  1351. Dictionary d = p_data;
  1352. ERR_FAIL_COND(!d.has("faces"));
  1353. _setup(d["faces"], d["backface_collision"]);
  1354. }
  1355. Variant GodotConcavePolygonShape3D::get_data() const {
  1356. Dictionary d;
  1357. d["faces"] = get_faces();
  1358. d["backface_collision"] = backface_collision;
  1359. return d;
  1360. }
  1361. GodotConcavePolygonShape3D::GodotConcavePolygonShape3D() {
  1362. }
  1363. /* HEIGHT MAP SHAPE */
  1364. Vector<real_t> GodotHeightMapShape3D::get_heights() const {
  1365. return heights;
  1366. }
  1367. int GodotHeightMapShape3D::get_width() const {
  1368. return width;
  1369. }
  1370. int GodotHeightMapShape3D::get_depth() const {
  1371. return depth;
  1372. }
  1373. void GodotHeightMapShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
  1374. //not very useful, but not very used either
  1375. p_transform.xform(get_aabb()).project_range_in_plane(Plane(p_normal), r_min, r_max);
  1376. }
  1377. Vector3 GodotHeightMapShape3D::get_support(const Vector3 &p_normal) const {
  1378. //not very useful, but not very used either
  1379. return get_aabb().get_support(p_normal);
  1380. }
  1381. struct _HeightmapSegmentCullParams {
  1382. Vector3 from;
  1383. Vector3 to;
  1384. Vector3 dir;
  1385. Vector3 result;
  1386. Vector3 normal;
  1387. const GodotHeightMapShape3D *heightmap = nullptr;
  1388. GodotFaceShape3D *face = nullptr;
  1389. };
  1390. struct _HeightmapGridCullState {
  1391. real_t length = 0.0;
  1392. real_t length_flat = 0.0;
  1393. real_t dist = 0.0;
  1394. real_t prev_dist = 0.0;
  1395. int x = 0;
  1396. int z = 0;
  1397. };
  1398. _FORCE_INLINE_ bool _heightmap_face_cull_segment(_HeightmapSegmentCullParams &p_params) {
  1399. Vector3 res;
  1400. Vector3 normal;
  1401. int fi = -1;
  1402. if (p_params.face->intersect_segment(p_params.from, p_params.to, res, normal, fi, true)) {
  1403. p_params.result = res;
  1404. p_params.normal = normal;
  1405. return true;
  1406. }
  1407. return false;
  1408. }
  1409. _FORCE_INLINE_ bool _heightmap_cell_cull_segment(_HeightmapSegmentCullParams &p_params, const _HeightmapGridCullState &p_state) {
  1410. // First triangle.
  1411. p_params.heightmap->_get_point(p_state.x, p_state.z, p_params.face->vertex[0]);
  1412. p_params.heightmap->_get_point(p_state.x + 1, p_state.z, p_params.face->vertex[1]);
  1413. p_params.heightmap->_get_point(p_state.x, p_state.z + 1, p_params.face->vertex[2]);
  1414. p_params.face->normal = Plane(p_params.face->vertex[0], p_params.face->vertex[1], p_params.face->vertex[2]).normal;
  1415. if (_heightmap_face_cull_segment(p_params)) {
  1416. return true;
  1417. }
  1418. // Second triangle.
  1419. p_params.face->vertex[0] = p_params.face->vertex[1];
  1420. p_params.heightmap->_get_point(p_state.x + 1, p_state.z + 1, p_params.face->vertex[1]);
  1421. p_params.face->normal = Plane(p_params.face->vertex[0], p_params.face->vertex[1], p_params.face->vertex[2]).normal;
  1422. if (_heightmap_face_cull_segment(p_params)) {
  1423. return true;
  1424. }
  1425. return false;
  1426. }
  1427. _FORCE_INLINE_ bool _heightmap_chunk_cull_segment(_HeightmapSegmentCullParams &p_params, const _HeightmapGridCullState &p_state) {
  1428. const GodotHeightMapShape3D::Range &chunk = p_params.heightmap->_get_bounds_chunk(p_state.x, p_state.z);
  1429. Vector3 enter_pos;
  1430. Vector3 exit_pos;
  1431. if (p_state.length_flat > CMP_EPSILON) {
  1432. real_t flat_to_3d = p_state.length / p_state.length_flat;
  1433. real_t enter_param = p_state.prev_dist * flat_to_3d;
  1434. real_t exit_param = p_state.dist * flat_to_3d;
  1435. enter_pos = p_params.from + p_params.dir * enter_param;
  1436. exit_pos = p_params.from + p_params.dir * exit_param;
  1437. } else {
  1438. // Consider the ray vertical.
  1439. // (though we shouldn't reach this often because there is an early check up-front)
  1440. enter_pos = p_params.from;
  1441. exit_pos = p_params.to;
  1442. }
  1443. // Transform positions to heightmap space.
  1444. enter_pos *= GodotHeightMapShape3D::BOUNDS_CHUNK_SIZE;
  1445. exit_pos *= GodotHeightMapShape3D::BOUNDS_CHUNK_SIZE;
  1446. // We did enter the flat projection of the AABB,
  1447. // but we have to check if we intersect it on the vertical axis.
  1448. if ((enter_pos.y > chunk.max) && (exit_pos.y > chunk.max)) {
  1449. return false;
  1450. }
  1451. if ((enter_pos.y < chunk.min) && (exit_pos.y < chunk.min)) {
  1452. return false;
  1453. }
  1454. return p_params.heightmap->_intersect_grid_segment(_heightmap_cell_cull_segment, enter_pos, exit_pos, p_params.heightmap->width, p_params.heightmap->depth, p_params.heightmap->local_origin, p_params.result, p_params.normal);
  1455. }
  1456. template <typename ProcessFunction>
  1457. bool GodotHeightMapShape3D::_intersect_grid_segment(ProcessFunction &p_process, const Vector3 &p_begin, const Vector3 &p_end, int p_width, int p_depth, const Vector3 &offset, Vector3 &r_point, Vector3 &r_normal) const {
  1458. Vector3 delta = (p_end - p_begin);
  1459. real_t length = delta.length();
  1460. if (length < CMP_EPSILON) {
  1461. return false;
  1462. }
  1463. Vector3 local_begin = p_begin + offset;
  1464. GodotFaceShape3D face;
  1465. face.backface_collision = false;
  1466. _HeightmapSegmentCullParams params;
  1467. params.from = p_begin;
  1468. params.to = p_end;
  1469. params.dir = delta / length;
  1470. params.heightmap = this;
  1471. params.face = &face;
  1472. _HeightmapGridCullState state;
  1473. // Perform grid query from projected ray.
  1474. Vector2 ray_dir_flat(delta.x, delta.z);
  1475. state.length = length;
  1476. state.length_flat = ray_dir_flat.length();
  1477. if (state.length_flat < CMP_EPSILON) {
  1478. ray_dir_flat = Vector2();
  1479. } else {
  1480. ray_dir_flat /= state.length_flat;
  1481. }
  1482. const int x_step = (ray_dir_flat.x > CMP_EPSILON) ? 1 : ((ray_dir_flat.x < -CMP_EPSILON) ? -1 : 0);
  1483. const int z_step = (ray_dir_flat.y > CMP_EPSILON) ? 1 : ((ray_dir_flat.y < -CMP_EPSILON) ? -1 : 0);
  1484. const real_t infinite = 1e20;
  1485. const real_t delta_x = (x_step != 0) ? 1.f / Math::abs(ray_dir_flat.x) : infinite;
  1486. const real_t delta_z = (z_step != 0) ? 1.f / Math::abs(ray_dir_flat.y) : infinite;
  1487. real_t cross_x; // At which value of `param` we will cross a x-axis lane?
  1488. real_t cross_z; // At which value of `param` we will cross a z-axis lane?
  1489. // X initialization.
  1490. if (x_step != 0) {
  1491. if (x_step == 1) {
  1492. cross_x = (Math::ceil(local_begin.x) - local_begin.x) * delta_x;
  1493. } else {
  1494. cross_x = (local_begin.x - Math::floor(local_begin.x)) * delta_x;
  1495. }
  1496. } else {
  1497. cross_x = infinite; // Will never cross on X.
  1498. }
  1499. // Z initialization.
  1500. if (z_step != 0) {
  1501. if (z_step == 1) {
  1502. cross_z = (Math::ceil(local_begin.z) - local_begin.z) * delta_z;
  1503. } else {
  1504. cross_z = (local_begin.z - Math::floor(local_begin.z)) * delta_z;
  1505. }
  1506. } else {
  1507. cross_z = infinite; // Will never cross on Z.
  1508. }
  1509. int x = Math::floor(local_begin.x);
  1510. int z = Math::floor(local_begin.z);
  1511. // Workaround cases where the ray starts at an integer position.
  1512. if (Math::is_zero_approx(cross_x)) {
  1513. cross_x += delta_x;
  1514. // If going backwards, we should ignore the position we would get by the above flooring,
  1515. // because the ray is not heading in that direction.
  1516. if (x_step == -1) {
  1517. x -= 1;
  1518. }
  1519. }
  1520. if (Math::is_zero_approx(cross_z)) {
  1521. cross_z += delta_z;
  1522. if (z_step == -1) {
  1523. z -= 1;
  1524. }
  1525. }
  1526. // Start inside the grid.
  1527. int x_start = MAX(MIN(x, p_width - 2), 0);
  1528. int z_start = MAX(MIN(z, p_depth - 2), 0);
  1529. // Adjust initial cross values.
  1530. cross_x += delta_x * x_step * (x_start - x);
  1531. cross_z += delta_z * z_step * (z_start - z);
  1532. x = x_start;
  1533. z = z_start;
  1534. while (true) {
  1535. state.prev_dist = state.dist;
  1536. state.x = x;
  1537. state.z = z;
  1538. if (cross_x < cross_z) {
  1539. // X lane.
  1540. x += x_step;
  1541. // Assign before advancing the param,
  1542. // to be in sync with the initialization step.
  1543. state.dist = cross_x;
  1544. cross_x += delta_x;
  1545. } else {
  1546. // Z lane.
  1547. z += z_step;
  1548. state.dist = cross_z;
  1549. cross_z += delta_z;
  1550. }
  1551. if (state.dist > state.length_flat) {
  1552. state.dist = state.length_flat;
  1553. if (p_process(params, state)) {
  1554. r_point = params.result;
  1555. r_normal = params.normal;
  1556. return true;
  1557. }
  1558. break;
  1559. }
  1560. if (p_process(params, state)) {
  1561. r_point = params.result;
  1562. r_normal = params.normal;
  1563. return true;
  1564. }
  1565. // Stop when outside the grid.
  1566. if ((x < 0) || (z < 0) || (x >= p_width - 1) || (z >= p_depth - 1)) {
  1567. break;
  1568. }
  1569. }
  1570. return false;
  1571. }
  1572. bool GodotHeightMapShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  1573. if (heights.is_empty()) {
  1574. return false;
  1575. }
  1576. Vector3 local_begin = p_begin + local_origin;
  1577. Vector3 local_end = p_end + local_origin;
  1578. // Quantize the ray begin/end.
  1579. int begin_x = Math::floor(local_begin.x);
  1580. int begin_z = Math::floor(local_begin.z);
  1581. int end_x = Math::floor(local_end.x);
  1582. int end_z = Math::floor(local_end.z);
  1583. if ((begin_x == end_x) && (begin_z == end_z)) {
  1584. // Simple case for rays that don't traverse the grid horizontally.
  1585. // Just perform a test on the given cell.
  1586. GodotFaceShape3D face;
  1587. face.backface_collision = p_hit_back_faces;
  1588. _HeightmapSegmentCullParams params;
  1589. params.from = p_begin;
  1590. params.to = p_end;
  1591. params.dir = (p_end - p_begin).normalized();
  1592. params.heightmap = this;
  1593. params.face = &face;
  1594. _HeightmapGridCullState state;
  1595. state.x = MAX(MIN(begin_x, width - 2), 0);
  1596. state.z = MAX(MIN(begin_z, depth - 2), 0);
  1597. if (_heightmap_cell_cull_segment(params, state)) {
  1598. r_point = params.result;
  1599. r_normal = params.normal;
  1600. return true;
  1601. }
  1602. } else if (bounds_grid.is_empty()) {
  1603. // Process all cells intersecting the flat projection of the ray.
  1604. return _intersect_grid_segment(_heightmap_cell_cull_segment, p_begin, p_end, width, depth, local_origin, r_point, r_normal);
  1605. } else {
  1606. Vector3 ray_diff = (p_end - p_begin);
  1607. real_t length_flat_sqr = ray_diff.x * ray_diff.x + ray_diff.z * ray_diff.z;
  1608. if (length_flat_sqr < BOUNDS_CHUNK_SIZE * BOUNDS_CHUNK_SIZE) {
  1609. // Don't use chunks, the ray is too short in the plane.
  1610. return _intersect_grid_segment(_heightmap_cell_cull_segment, p_begin, p_end, width, depth, local_origin, r_point, r_normal);
  1611. } else {
  1612. // The ray is long, run raycast on a higher-level grid.
  1613. Vector3 bounds_from = p_begin / BOUNDS_CHUNK_SIZE;
  1614. Vector3 bounds_to = p_end / BOUNDS_CHUNK_SIZE;
  1615. Vector3 bounds_offset = local_origin / BOUNDS_CHUNK_SIZE;
  1616. // Plus 1 here to width and depth of the chunk because _intersect_grid_segment() is used by cell level as well,
  1617. // and in _intersect_grid_segment() the loop will exit 1 early because for cell point triangle lookup, it dose x + 1, z + 1 etc for the vertex.
  1618. int bounds_width = bounds_grid_width + 1;
  1619. int bounds_depth = bounds_grid_depth + 1;
  1620. return _intersect_grid_segment(_heightmap_chunk_cull_segment, bounds_from, bounds_to, bounds_width, bounds_depth, bounds_offset, r_point, r_normal);
  1621. }
  1622. }
  1623. return false;
  1624. }
  1625. bool GodotHeightMapShape3D::intersect_point(const Vector3 &p_point) const {
  1626. return false;
  1627. }
  1628. Vector3 GodotHeightMapShape3D::get_closest_point_to(const Vector3 &p_point) const {
  1629. return Vector3();
  1630. }
  1631. void GodotHeightMapShape3D::_get_cell(const Vector3 &p_point, int &r_x, int &r_y, int &r_z) const {
  1632. const AABB &shape_aabb = get_aabb();
  1633. Vector3 pos_local = shape_aabb.position + local_origin;
  1634. Vector3 clamped_point(p_point);
  1635. clamped_point = p_point.clamp(pos_local, pos_local + shape_aabb.size);
  1636. r_x = (clamped_point.x < 0.0) ? (clamped_point.x - 0.5) : (clamped_point.x + 0.5);
  1637. r_y = (clamped_point.y < 0.0) ? (clamped_point.y - 0.5) : (clamped_point.y + 0.5);
  1638. r_z = (clamped_point.z < 0.0) ? (clamped_point.z - 0.5) : (clamped_point.z + 0.5);
  1639. }
  1640. void GodotHeightMapShape3D::cull(const AABB &p_local_aabb, QueryCallback p_callback, void *p_userdata, bool p_invert_backface_collision) const {
  1641. if (heights.is_empty()) {
  1642. return;
  1643. }
  1644. AABB local_aabb = p_local_aabb;
  1645. local_aabb.position += local_origin;
  1646. // Quantize the aabb, and adjust the start/end ranges.
  1647. int aabb_min[3];
  1648. int aabb_max[3];
  1649. _get_cell(local_aabb.position, aabb_min[0], aabb_min[1], aabb_min[2]);
  1650. _get_cell(local_aabb.position + local_aabb.size, aabb_max[0], aabb_max[1], aabb_max[2]);
  1651. // Expand the min/max quantized values.
  1652. // This is to catch the case where the input aabb falls between grid points.
  1653. for (int i = 0; i < 3; ++i) {
  1654. aabb_min[i]--;
  1655. aabb_max[i]++;
  1656. }
  1657. int start_x = MAX(0, aabb_min[0]);
  1658. int end_x = MIN(width - 1, aabb_max[0]);
  1659. int start_z = MAX(0, aabb_min[2]);
  1660. int end_z = MIN(depth - 1, aabb_max[2]);
  1661. GodotFaceShape3D face;
  1662. face.backface_collision = !p_invert_backface_collision;
  1663. face.invert_backface_collision = p_invert_backface_collision;
  1664. for (int z = start_z; z < end_z; z++) {
  1665. for (int x = start_x; x < end_x; x++) {
  1666. // First triangle.
  1667. _get_point(x, z, face.vertex[0]);
  1668. _get_point(x + 1, z, face.vertex[1]);
  1669. _get_point(x, z + 1, face.vertex[2]);
  1670. face.normal = Plane(face.vertex[0], face.vertex[1], face.vertex[2]).normal;
  1671. if (p_callback(p_userdata, &face)) {
  1672. return;
  1673. }
  1674. // Second triangle.
  1675. face.vertex[0] = face.vertex[1];
  1676. _get_point(x + 1, z + 1, face.vertex[1]);
  1677. face.normal = Plane(face.vertex[0], face.vertex[1], face.vertex[2]).normal;
  1678. if (p_callback(p_userdata, &face)) {
  1679. return;
  1680. }
  1681. }
  1682. }
  1683. }
  1684. Vector3 GodotHeightMapShape3D::get_moment_of_inertia(real_t p_mass) const {
  1685. // use bad AABB approximation
  1686. Vector3 extents = get_aabb().size * 0.5;
  1687. return Vector3(
  1688. (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
  1689. (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
  1690. (p_mass / 3.0) * (extents.x * extents.x + extents.y * extents.y));
  1691. }
  1692. void GodotHeightMapShape3D::_build_accelerator() {
  1693. bounds_grid.clear();
  1694. bounds_grid_width = width / BOUNDS_CHUNK_SIZE;
  1695. bounds_grid_depth = depth / BOUNDS_CHUNK_SIZE;
  1696. if (width % BOUNDS_CHUNK_SIZE > 0) {
  1697. ++bounds_grid_width; // In case terrain size isn't dividable by chunk size.
  1698. }
  1699. if (depth % BOUNDS_CHUNK_SIZE > 0) {
  1700. ++bounds_grid_depth;
  1701. }
  1702. uint32_t bound_grid_size = (uint32_t)(bounds_grid_width * bounds_grid_depth);
  1703. if (bound_grid_size < 2) {
  1704. // Grid is empty or just one chunk.
  1705. return;
  1706. }
  1707. bounds_grid.resize(bound_grid_size);
  1708. // Compute min and max height for all chunks.
  1709. for (int cz = 0; cz < bounds_grid_depth; ++cz) {
  1710. int z0 = cz * BOUNDS_CHUNK_SIZE;
  1711. for (int cx = 0; cx < bounds_grid_width; ++cx) {
  1712. int x0 = cx * BOUNDS_CHUNK_SIZE;
  1713. Range r;
  1714. r.min = _get_height(x0, z0);
  1715. r.max = r.min;
  1716. // Compute min and max height for this chunk.
  1717. // We have to include one extra cell to account for neighbors.
  1718. // Here is why:
  1719. // Say we have a flat terrain, and a plateau that fits a chunk perfectly.
  1720. //
  1721. // Left Right
  1722. // 0---0---0---1---1---1
  1723. // | | | | | |
  1724. // 0---0---0---1---1---1
  1725. // | | | | | |
  1726. // 0---0---0---1---1---1
  1727. // x
  1728. //
  1729. // If the AABB for the Left chunk did not share vertices with the Right,
  1730. // then we would fail collision tests at x due to a gap.
  1731. //
  1732. int z_max = MIN(z0 + BOUNDS_CHUNK_SIZE + 1, depth);
  1733. int x_max = MIN(x0 + BOUNDS_CHUNK_SIZE + 1, width);
  1734. for (int z = z0; z < z_max; ++z) {
  1735. for (int x = x0; x < x_max; ++x) {
  1736. real_t height = _get_height(x, z);
  1737. if (height < r.min) {
  1738. r.min = height;
  1739. } else if (height > r.max) {
  1740. r.max = height;
  1741. }
  1742. }
  1743. }
  1744. bounds_grid[cx + cz * bounds_grid_width] = r;
  1745. }
  1746. }
  1747. }
  1748. void GodotHeightMapShape3D::_setup(const Vector<real_t> &p_heights, int p_width, int p_depth, real_t p_min_height, real_t p_max_height) {
  1749. heights = p_heights;
  1750. width = p_width;
  1751. depth = p_depth;
  1752. // Initialize aabb.
  1753. AABB aabb_new;
  1754. aabb_new.position = Vector3(0.0, p_min_height, 0.0);
  1755. aabb_new.size = Vector3(p_width - 1, p_max_height - p_min_height, p_depth - 1);
  1756. // Initialize origin as the aabb center.
  1757. local_origin = aabb_new.position + 0.5 * aabb_new.size;
  1758. local_origin.y = 0.0;
  1759. aabb_new.position -= local_origin;
  1760. _build_accelerator();
  1761. configure(aabb_new);
  1762. }
  1763. void GodotHeightMapShape3D::set_data(const Variant &p_data) {
  1764. ERR_FAIL_COND(p_data.get_type() != Variant::DICTIONARY);
  1765. Dictionary d = p_data;
  1766. ERR_FAIL_COND(!d.has("width"));
  1767. ERR_FAIL_COND(!d.has("depth"));
  1768. ERR_FAIL_COND(!d.has("heights"));
  1769. int width_new = d["width"];
  1770. int depth_new = d["depth"];
  1771. ERR_FAIL_COND(width_new <= 0.0);
  1772. ERR_FAIL_COND(depth_new <= 0.0);
  1773. Variant heights_variant = d["heights"];
  1774. Vector<real_t> heights_buffer;
  1775. #ifdef REAL_T_IS_DOUBLE
  1776. if (heights_variant.get_type() == Variant::PACKED_FLOAT64_ARRAY) {
  1777. #else
  1778. if (heights_variant.get_type() == Variant::PACKED_FLOAT32_ARRAY) {
  1779. #endif
  1780. // Ready-to-use heights can be passed.
  1781. heights_buffer = heights_variant;
  1782. } else if (heights_variant.get_type() == Variant::OBJECT) {
  1783. // If an image is passed, we have to convert it.
  1784. // This would be expensive to do with a script, so it's nice to have it here.
  1785. Ref<Image> image = heights_variant;
  1786. ERR_FAIL_COND(image.is_null());
  1787. ERR_FAIL_COND(image->get_format() != Image::FORMAT_RF);
  1788. PackedByteArray im_data = image->get_data();
  1789. heights_buffer.resize(image->get_width() * image->get_height());
  1790. real_t *w = heights_buffer.ptrw();
  1791. real_t *rp = (real_t *)im_data.ptr();
  1792. for (int i = 0; i < heights_buffer.size(); ++i) {
  1793. w[i] = rp[i];
  1794. }
  1795. } else {
  1796. #ifdef REAL_T_IS_DOUBLE
  1797. ERR_FAIL_MSG("Expected PackedFloat64Array or float Image.");
  1798. #else
  1799. ERR_FAIL_MSG("Expected PackedFloat32Array or float Image.");
  1800. #endif
  1801. }
  1802. // Compute min and max heights or use precomputed values.
  1803. real_t min_height = 0.0;
  1804. real_t max_height = 0.0;
  1805. if (d.has("min_height") && d.has("max_height")) {
  1806. min_height = d["min_height"];
  1807. max_height = d["max_height"];
  1808. } else {
  1809. int heights_size = heights.size();
  1810. for (int i = 0; i < heights_size; ++i) {
  1811. real_t h = heights[i];
  1812. if (h < min_height) {
  1813. min_height = h;
  1814. } else if (h > max_height) {
  1815. max_height = h;
  1816. }
  1817. }
  1818. }
  1819. ERR_FAIL_COND(min_height > max_height);
  1820. ERR_FAIL_COND(heights_buffer.size() != (width_new * depth_new));
  1821. // If specified, min and max height will be used as precomputed values.
  1822. _setup(heights_buffer, width_new, depth_new, min_height, max_height);
  1823. }
  1824. Variant GodotHeightMapShape3D::get_data() const {
  1825. Dictionary d;
  1826. d["width"] = width;
  1827. d["depth"] = depth;
  1828. const AABB &shape_aabb = get_aabb();
  1829. d["min_height"] = shape_aabb.position.y;
  1830. d["max_height"] = shape_aabb.position.y + shape_aabb.size.y;
  1831. d["heights"] = heights;
  1832. return d;
  1833. }
  1834. GodotHeightMapShape3D::GodotHeightMapShape3D() {
  1835. }