mesh.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  1. /**************************************************************************/
  2. /* mesh.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 "mesh.h"
  31. #include "core/crypto/crypto_core.h"
  32. #include "core/local_vector.h"
  33. #include "core/math/convex_hull.h"
  34. #include "core/pair.h"
  35. #include "scene/resources/concave_polygon_shape.h"
  36. #include "scene/resources/convex_polygon_shape.h"
  37. #include "surface_tool.h"
  38. #include <stdlib.h>
  39. Mesh::ConvexDecompositionFunc Mesh::convex_decomposition_function = nullptr;
  40. Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
  41. if (triangle_mesh.is_valid()) {
  42. return triangle_mesh;
  43. }
  44. int facecount = 0;
  45. for (int i = 0; i < get_surface_count(); i++) {
  46. if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES) {
  47. continue;
  48. }
  49. if (surface_get_format(i) & ARRAY_FORMAT_INDEX) {
  50. facecount += surface_get_array_index_len(i);
  51. } else {
  52. facecount += surface_get_array_len(i);
  53. }
  54. }
  55. if (facecount == 0 || (facecount % 3) != 0) {
  56. return triangle_mesh;
  57. }
  58. PoolVector<Vector3> faces;
  59. faces.resize(facecount);
  60. PoolVector<Vector3>::Write facesw = faces.write();
  61. int widx = 0;
  62. for (int i = 0; i < get_surface_count(); i++) {
  63. if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES) {
  64. continue;
  65. }
  66. Array a = surface_get_arrays(i);
  67. ERR_FAIL_COND_V(a.empty(), Ref<TriangleMesh>());
  68. int vc = surface_get_array_len(i);
  69. PoolVector<Vector3> vertices = a[ARRAY_VERTEX];
  70. PoolVector<Vector3>::Read vr = vertices.read();
  71. if (surface_get_format(i) & ARRAY_FORMAT_INDEX) {
  72. int ic = surface_get_array_index_len(i);
  73. PoolVector<int> indices = a[ARRAY_INDEX];
  74. PoolVector<int>::Read ir = indices.read();
  75. for (int j = 0; j < ic; j++) {
  76. int index = ir[j];
  77. facesw[widx++] = vr[index];
  78. }
  79. } else {
  80. for (int j = 0; j < vc; j++) {
  81. facesw[widx++] = vr[j];
  82. }
  83. }
  84. }
  85. facesw.release();
  86. triangle_mesh = Ref<TriangleMesh>(memnew(TriangleMesh));
  87. triangle_mesh->create(faces);
  88. return triangle_mesh;
  89. }
  90. void Mesh::generate_debug_mesh_lines(Vector<Vector3> &r_lines) {
  91. if (debug_lines.size() > 0) {
  92. r_lines = debug_lines;
  93. return;
  94. }
  95. Ref<TriangleMesh> tm = generate_triangle_mesh();
  96. if (tm.is_null()) {
  97. return;
  98. }
  99. PoolVector<int> triangle_indices;
  100. tm->get_indices(&triangle_indices);
  101. const int triangles_num = tm->get_triangles().size();
  102. PoolVector<Vector3> vertices = tm->get_vertices();
  103. debug_lines.resize(tm->get_triangles().size() * 6); // 3 lines x 2 points each line
  104. PoolVector<int>::Read ind_r = triangle_indices.read();
  105. PoolVector<Vector3>::Read ver_r = vertices.read();
  106. for (int j = 0, x = 0, i = 0; i < triangles_num; j += 6, x += 3, ++i) {
  107. // Triangle line 1
  108. debug_lines.write[j + 0] = ver_r[ind_r[x + 0]];
  109. debug_lines.write[j + 1] = ver_r[ind_r[x + 1]];
  110. // Triangle line 2
  111. debug_lines.write[j + 2] = ver_r[ind_r[x + 1]];
  112. debug_lines.write[j + 3] = ver_r[ind_r[x + 2]];
  113. // Triangle line 3
  114. debug_lines.write[j + 4] = ver_r[ind_r[x + 2]];
  115. debug_lines.write[j + 5] = ver_r[ind_r[x + 0]];
  116. }
  117. r_lines = debug_lines;
  118. }
  119. void Mesh::generate_debug_mesh_indices(Vector<Vector3> &r_points) {
  120. Ref<TriangleMesh> tm = generate_triangle_mesh();
  121. if (tm.is_null()) {
  122. return;
  123. }
  124. PoolVector<Vector3> vertices = tm->get_vertices();
  125. int vertices_size = vertices.size();
  126. r_points.resize(vertices_size);
  127. for (int i = 0; i < vertices_size; ++i) {
  128. r_points.write[i] = vertices[i];
  129. }
  130. }
  131. bool Mesh::surface_is_softbody_friendly(int p_idx) const {
  132. const uint32_t surface_format = surface_get_format(p_idx);
  133. return (surface_format & Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE && (!(surface_format & Mesh::ARRAY_COMPRESS_VERTEX)) && (!(surface_format & Mesh::ARRAY_COMPRESS_NORMAL)));
  134. }
  135. PoolVector<Face3> Mesh::get_faces() const {
  136. Ref<TriangleMesh> tm = generate_triangle_mesh();
  137. if (tm.is_valid()) {
  138. return tm->get_faces();
  139. }
  140. return PoolVector<Face3>();
  141. }
  142. Ref<Shape> Mesh::create_convex_shape(bool p_clean, bool p_simplify) const {
  143. if (p_simplify) {
  144. Vector<Ref<Shape>> decomposed = convex_decompose(1);
  145. if (decomposed.size() == 1) {
  146. return decomposed[0];
  147. } else {
  148. ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");
  149. }
  150. }
  151. PoolVector<Vector3> vertices;
  152. for (int i = 0; i < get_surface_count(); i++) {
  153. Array a = surface_get_arrays(i);
  154. ERR_FAIL_COND_V(a.empty(), Ref<ConvexPolygonShape>());
  155. PoolVector<Vector3> v = a[ARRAY_VERTEX];
  156. vertices.append_array(v);
  157. }
  158. Ref<ConvexPolygonShape> shape = memnew(ConvexPolygonShape);
  159. if (p_clean) {
  160. Geometry::MeshData md;
  161. Error err = ConvexHullComputer::convex_hull(vertices, md);
  162. if (err == OK) {
  163. int vertex_count = md.vertices.size();
  164. vertices.resize(vertex_count);
  165. {
  166. PoolVector<Vector3>::Write w = vertices.write();
  167. for (int idx = 0; idx < vertex_count; ++idx) {
  168. w[idx] = md.vertices[idx];
  169. }
  170. }
  171. } else {
  172. ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");
  173. }
  174. }
  175. shape->set_points(vertices);
  176. return shape;
  177. }
  178. Ref<Shape> Mesh::create_trimesh_shape() const {
  179. PoolVector<Face3> faces = get_faces();
  180. if (faces.size() == 0) {
  181. return Ref<Shape>();
  182. }
  183. PoolVector<Vector3> face_points;
  184. face_points.resize(faces.size() * 3);
  185. for (int i = 0; i < face_points.size(); i += 3) {
  186. Face3 f = faces.get(i / 3);
  187. face_points.set(i, f.vertex[0]);
  188. face_points.set(i + 1, f.vertex[1]);
  189. face_points.set(i + 2, f.vertex[2]);
  190. }
  191. Ref<ConcavePolygonShape> shape = memnew(ConcavePolygonShape);
  192. shape->set_faces(face_points);
  193. return shape;
  194. }
  195. Ref<Mesh> Mesh::create_outline(float p_margin) const {
  196. Array arrays;
  197. int index_accum = 0;
  198. for (int i = 0; i < get_surface_count(); i++) {
  199. if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES) {
  200. continue;
  201. }
  202. Array a = surface_get_arrays(i);
  203. ERR_FAIL_COND_V(a.empty(), Ref<ArrayMesh>());
  204. if (i == 0) {
  205. arrays = a;
  206. PoolVector<Vector3> v = a[ARRAY_VERTEX];
  207. index_accum += v.size();
  208. } else {
  209. int vcount = 0;
  210. for (int j = 0; j < arrays.size(); j++) {
  211. if (arrays[j].get_type() == Variant::NIL || a[j].get_type() == Variant::NIL) {
  212. //mismatch, do not use
  213. arrays[j] = Variant();
  214. continue;
  215. }
  216. switch (j) {
  217. case ARRAY_VERTEX:
  218. case ARRAY_NORMAL: {
  219. PoolVector<Vector3> dst = arrays[j];
  220. PoolVector<Vector3> src = a[j];
  221. if (j == ARRAY_VERTEX) {
  222. vcount = src.size();
  223. }
  224. if (dst.size() == 0 || src.size() == 0) {
  225. arrays[j] = Variant();
  226. continue;
  227. }
  228. dst.append_array(src);
  229. arrays[j] = dst;
  230. } break;
  231. case ARRAY_TANGENT:
  232. case ARRAY_BONES:
  233. case ARRAY_WEIGHTS: {
  234. PoolVector<real_t> dst = arrays[j];
  235. PoolVector<real_t> src = a[j];
  236. if (dst.size() == 0 || src.size() == 0) {
  237. arrays[j] = Variant();
  238. continue;
  239. }
  240. dst.append_array(src);
  241. arrays[j] = dst;
  242. } break;
  243. case ARRAY_COLOR: {
  244. PoolVector<Color> dst = arrays[j];
  245. PoolVector<Color> src = a[j];
  246. if (dst.size() == 0 || src.size() == 0) {
  247. arrays[j] = Variant();
  248. continue;
  249. }
  250. dst.append_array(src);
  251. arrays[j] = dst;
  252. } break;
  253. case ARRAY_TEX_UV:
  254. case ARRAY_TEX_UV2: {
  255. PoolVector<Vector2> dst = arrays[j];
  256. PoolVector<Vector2> src = a[j];
  257. if (dst.size() == 0 || src.size() == 0) {
  258. arrays[j] = Variant();
  259. continue;
  260. }
  261. dst.append_array(src);
  262. arrays[j] = dst;
  263. } break;
  264. case ARRAY_INDEX: {
  265. PoolVector<int> dst = arrays[j];
  266. PoolVector<int> src = a[j];
  267. if (dst.size() == 0 || src.size() == 0) {
  268. arrays[j] = Variant();
  269. continue;
  270. }
  271. {
  272. int ss = src.size();
  273. PoolVector<int>::Write w = src.write();
  274. for (int k = 0; k < ss; k++) {
  275. w[k] += index_accum;
  276. }
  277. }
  278. dst.append_array(src);
  279. arrays[j] = dst;
  280. index_accum += vcount;
  281. } break;
  282. }
  283. }
  284. }
  285. }
  286. ERR_FAIL_COND_V(arrays.size() != ARRAY_MAX, Ref<ArrayMesh>());
  287. {
  288. PoolVector<int>::Write ir;
  289. PoolVector<int> indices = arrays[ARRAY_INDEX];
  290. bool has_indices = false;
  291. PoolVector<Vector3> vertices = arrays[ARRAY_VERTEX];
  292. int vc = vertices.size();
  293. ERR_FAIL_COND_V(!vc, Ref<ArrayMesh>());
  294. PoolVector<Vector3>::Write r = vertices.write();
  295. if (indices.size()) {
  296. ERR_FAIL_COND_V(indices.size() % 3 != 0, Ref<ArrayMesh>());
  297. vc = indices.size();
  298. ir = indices.write();
  299. has_indices = true;
  300. }
  301. Map<Vector3, Vector3> normal_accum;
  302. //fill normals with triangle normals
  303. for (int i = 0; i < vc; i += 3) {
  304. Vector3 t[3];
  305. if (has_indices) {
  306. t[0] = r[ir[i + 0]];
  307. t[1] = r[ir[i + 1]];
  308. t[2] = r[ir[i + 2]];
  309. } else {
  310. t[0] = r[i + 0];
  311. t[1] = r[i + 1];
  312. t[2] = r[i + 2];
  313. }
  314. Vector3 n = Plane(t[0], t[1], t[2]).normal;
  315. for (int j = 0; j < 3; j++) {
  316. Map<Vector3, Vector3>::Element *E = normal_accum.find(t[j]);
  317. if (!E) {
  318. normal_accum[t[j]] = n;
  319. } else {
  320. float d = n.dot(E->get());
  321. if (d < 1.0) {
  322. E->get() += n * (1.0 - d);
  323. }
  324. //E->get()+=n;
  325. }
  326. }
  327. }
  328. //normalize
  329. for (Map<Vector3, Vector3>::Element *E = normal_accum.front(); E; E = E->next()) {
  330. E->get().normalize();
  331. }
  332. //displace normals
  333. int vc2 = vertices.size();
  334. for (int i = 0; i < vc2; i++) {
  335. Vector3 t = r[i];
  336. Map<Vector3, Vector3>::Element *E = normal_accum.find(t);
  337. ERR_CONTINUE(!E);
  338. t += E->get() * p_margin;
  339. r[i] = t;
  340. }
  341. r.release();
  342. arrays[ARRAY_VERTEX] = vertices;
  343. if (!has_indices) {
  344. PoolVector<int> new_indices;
  345. new_indices.resize(vertices.size());
  346. PoolVector<int>::Write iw = new_indices.write();
  347. for (int j = 0; j < vc2; j += 3) {
  348. iw[j] = j;
  349. iw[j + 1] = j + 2;
  350. iw[j + 2] = j + 1;
  351. }
  352. iw.release();
  353. arrays[ARRAY_INDEX] = new_indices;
  354. } else {
  355. for (int j = 0; j < vc; j += 3) {
  356. SWAP(ir[j + 1], ir[j + 2]);
  357. }
  358. ir.release();
  359. arrays[ARRAY_INDEX] = indices;
  360. }
  361. }
  362. Ref<ArrayMesh> newmesh = memnew(ArrayMesh);
  363. newmesh->add_surface_from_arrays(PRIMITIVE_TRIANGLES, arrays);
  364. return newmesh;
  365. }
  366. void Mesh::set_lightmap_size_hint(const Vector2 &p_size) {
  367. lightmap_size_hint = p_size;
  368. }
  369. Size2 Mesh::get_lightmap_size_hint() const {
  370. return lightmap_size_hint;
  371. }
  372. void Mesh::_bind_methods() {
  373. ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &Mesh::set_lightmap_size_hint);
  374. ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &Mesh::get_lightmap_size_hint);
  375. ClassDB::bind_method(D_METHOD("get_aabb"), &Mesh::get_aabb);
  376. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "lightmap_size_hint"), "set_lightmap_size_hint", "get_lightmap_size_hint");
  377. ClassDB::bind_method(D_METHOD("get_surface_count"), &Mesh::get_surface_count);
  378. ClassDB::bind_method(D_METHOD("surface_get_arrays", "surf_idx"), &Mesh::surface_get_arrays);
  379. ClassDB::bind_method(D_METHOD("surface_get_blend_shape_arrays", "surf_idx"), &Mesh::surface_get_blend_shape_arrays);
  380. ClassDB::bind_method(D_METHOD("surface_set_material", "surf_idx", "material"), &Mesh::surface_set_material);
  381. ClassDB::bind_method(D_METHOD("surface_get_material", "surf_idx"), &Mesh::surface_get_material);
  382. BIND_ENUM_CONSTANT(PRIMITIVE_POINTS);
  383. BIND_ENUM_CONSTANT(PRIMITIVE_LINES);
  384. BIND_ENUM_CONSTANT(PRIMITIVE_LINE_STRIP);
  385. BIND_ENUM_CONSTANT(PRIMITIVE_LINE_LOOP);
  386. BIND_ENUM_CONSTANT(PRIMITIVE_TRIANGLES);
  387. BIND_ENUM_CONSTANT(PRIMITIVE_TRIANGLE_STRIP);
  388. BIND_ENUM_CONSTANT(PRIMITIVE_TRIANGLE_FAN);
  389. BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_NORMALIZED);
  390. BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_RELATIVE);
  391. BIND_ENUM_CONSTANT(ARRAY_FORMAT_VERTEX);
  392. BIND_ENUM_CONSTANT(ARRAY_FORMAT_NORMAL);
  393. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TANGENT);
  394. BIND_ENUM_CONSTANT(ARRAY_FORMAT_COLOR);
  395. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV);
  396. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV2);
  397. BIND_ENUM_CONSTANT(ARRAY_FORMAT_BONES);
  398. BIND_ENUM_CONSTANT(ARRAY_FORMAT_WEIGHTS);
  399. BIND_ENUM_CONSTANT(ARRAY_FORMAT_INDEX);
  400. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_BASE);
  401. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_VERTEX);
  402. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_NORMAL);
  403. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_TANGENT);
  404. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_COLOR);
  405. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_TEX_UV);
  406. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_TEX_UV2);
  407. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_BONES);
  408. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_WEIGHTS);
  409. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_INDEX);
  410. BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_2D_VERTICES);
  411. BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_16_BIT_BONES);
  412. BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_OCTAHEDRAL_COMPRESSION);
  413. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_DEFAULT);
  414. BIND_ENUM_CONSTANT(ARRAY_VERTEX);
  415. BIND_ENUM_CONSTANT(ARRAY_NORMAL);
  416. BIND_ENUM_CONSTANT(ARRAY_TANGENT);
  417. BIND_ENUM_CONSTANT(ARRAY_COLOR);
  418. BIND_ENUM_CONSTANT(ARRAY_TEX_UV);
  419. BIND_ENUM_CONSTANT(ARRAY_TEX_UV2);
  420. BIND_ENUM_CONSTANT(ARRAY_BONES);
  421. BIND_ENUM_CONSTANT(ARRAY_WEIGHTS);
  422. BIND_ENUM_CONSTANT(ARRAY_INDEX);
  423. BIND_ENUM_CONSTANT(ARRAY_MAX);
  424. }
  425. void Mesh::clear_cache() const {
  426. triangle_mesh.unref();
  427. debug_lines.clear();
  428. }
  429. Vector<Ref<Shape>> Mesh::convex_decompose(int p_max_convex_hulls) const {
  430. ERR_FAIL_COND_V(!convex_decomposition_function, Vector<Ref<Shape>>());
  431. Ref<TriangleMesh> tm = generate_triangle_mesh();
  432. ERR_FAIL_COND_V(!tm.is_valid(), Vector<Ref<Shape>>());
  433. const PoolVector<TriangleMesh::Triangle> &triangles = tm->get_triangles();
  434. int triangle_count = triangles.size();
  435. PoolVector<uint32_t> indices;
  436. {
  437. indices.resize(triangle_count * 3);
  438. PoolVector<uint32_t>::Write w = indices.write();
  439. PoolVector<TriangleMesh::Triangle>::Read triangles_read = triangles.read();
  440. for (int i = 0; i < triangle_count; i++) {
  441. for (int j = 0; j < 3; j++) {
  442. w[i * 3 + j] = triangles_read[i].indices[j];
  443. }
  444. }
  445. }
  446. const PoolVector<Vector3> &vertices = tm->get_vertices();
  447. int vertex_count = vertices.size();
  448. Vector<PoolVector<Vector3>> decomposed = convex_decomposition_function((real_t *)vertices.read().ptr(), vertex_count, indices.read().ptr(), triangle_count, p_max_convex_hulls, nullptr);
  449. Vector<Ref<Shape>> ret;
  450. for (int i = 0; i < decomposed.size(); i++) {
  451. Ref<ConvexPolygonShape> shape;
  452. shape.instance();
  453. shape->set_points(decomposed[i]);
  454. ret.push_back(shape);
  455. }
  456. return ret;
  457. }
  458. Mesh::Mesh() {
  459. }
  460. bool ArrayMesh::_set(const StringName &p_name, const Variant &p_value) {
  461. String sname = p_name;
  462. if (p_name == "blend_shape/names") {
  463. PoolVector<String> sk = p_value;
  464. int sz = sk.size();
  465. PoolVector<String>::Read r = sk.read();
  466. for (int i = 0; i < sz; i++) {
  467. add_blend_shape(r[i]);
  468. }
  469. return true;
  470. }
  471. if (p_name == "blend_shape/mode") {
  472. set_blend_shape_mode(BlendShapeMode(int(p_value)));
  473. return true;
  474. }
  475. if (sname.begins_with("surface_")) {
  476. int sl = sname.find("/");
  477. if (sl == -1) {
  478. return false;
  479. }
  480. int idx = sname.substr(8, sl - 8).to_int() - 1;
  481. String what = sname.get_slicec('/', 1);
  482. if (what == "material") {
  483. surface_set_material(idx, p_value);
  484. } else if (what == "name") {
  485. surface_set_name(idx, p_value);
  486. }
  487. return true;
  488. }
  489. if (!sname.begins_with("surfaces")) {
  490. return false;
  491. }
  492. int idx = sname.get_slicec('/', 1).to_int();
  493. String what = sname.get_slicec('/', 2);
  494. if (idx == surfaces.size()) {
  495. //create
  496. Dictionary d = p_value;
  497. ERR_FAIL_COND_V(!d.has("primitive"), false);
  498. if (d.has("arrays")) {
  499. //old format
  500. ERR_FAIL_COND_V(!d.has("morph_arrays"), false);
  501. add_surface_from_arrays(PrimitiveType(int(d["primitive"])), d["arrays"], d["morph_arrays"]);
  502. } else if (d.has("array_data")) {
  503. PoolVector<uint8_t> array_data = d["array_data"];
  504. PoolVector<uint8_t> array_index_data;
  505. if (d.has("array_index_data")) {
  506. array_index_data = d["array_index_data"];
  507. }
  508. ERR_FAIL_COND_V(!d.has("format"), false);
  509. uint32_t format = d["format"];
  510. uint32_t primitive = d["primitive"];
  511. ERR_FAIL_COND_V(!d.has("vertex_count"), false);
  512. int vertex_count = d["vertex_count"];
  513. int index_count = 0;
  514. if (d.has("index_count")) {
  515. index_count = d["index_count"];
  516. }
  517. Vector<PoolVector<uint8_t>> blend_shapes;
  518. if (d.has("blend_shape_data")) {
  519. Array blend_shape_data = d["blend_shape_data"];
  520. for (int i = 0; i < blend_shape_data.size(); i++) {
  521. PoolVector<uint8_t> shape = blend_shape_data[i];
  522. blend_shapes.push_back(shape);
  523. }
  524. }
  525. ERR_FAIL_COND_V(!d.has("aabb"), false);
  526. AABB aabb = d["aabb"];
  527. Vector<AABB> bone_aabb;
  528. if (d.has("skeleton_aabb")) {
  529. Array baabb = d["skeleton_aabb"];
  530. bone_aabb.resize(baabb.size());
  531. for (int i = 0; i < baabb.size(); i++) {
  532. bone_aabb.write[i] = baabb[i];
  533. }
  534. }
  535. add_surface(format, PrimitiveType(primitive), array_data, vertex_count, array_index_data, index_count, aabb, blend_shapes, bone_aabb);
  536. } else {
  537. ERR_FAIL_V(false);
  538. }
  539. if (d.has("material")) {
  540. surface_set_material(idx, d["material"]);
  541. }
  542. if (d.has("name")) {
  543. surface_set_name(idx, d["name"]);
  544. }
  545. return true;
  546. }
  547. return false;
  548. }
  549. bool ArrayMesh::_get(const StringName &p_name, Variant &r_ret) const {
  550. if (_is_generated()) {
  551. return false;
  552. }
  553. String sname = p_name;
  554. if (p_name == "blend_shape/names") {
  555. PoolVector<String> sk;
  556. for (int i = 0; i < blend_shapes.size(); i++) {
  557. sk.push_back(blend_shapes[i]);
  558. }
  559. r_ret = sk;
  560. return true;
  561. } else if (p_name == "blend_shape/mode") {
  562. r_ret = get_blend_shape_mode();
  563. return true;
  564. } else if (sname.begins_with("surface_")) {
  565. int sl = sname.find("/");
  566. if (sl == -1) {
  567. return false;
  568. }
  569. int idx = sname.substr(8, sl - 8).to_int() - 1;
  570. String what = sname.get_slicec('/', 1);
  571. if (what == "material") {
  572. r_ret = surface_get_material(idx);
  573. } else if (what == "name") {
  574. r_ret = surface_get_name(idx);
  575. }
  576. return true;
  577. } else if (!sname.begins_with("surfaces")) {
  578. return false;
  579. }
  580. int idx = sname.get_slicec('/', 1).to_int();
  581. ERR_FAIL_INDEX_V(idx, surfaces.size(), false);
  582. Dictionary d;
  583. d["array_data"] = VS::get_singleton()->mesh_surface_get_array(mesh, idx);
  584. d["vertex_count"] = VS::get_singleton()->mesh_surface_get_array_len(mesh, idx);
  585. d["array_index_data"] = VS::get_singleton()->mesh_surface_get_index_array(mesh, idx);
  586. d["index_count"] = VS::get_singleton()->mesh_surface_get_array_index_len(mesh, idx);
  587. d["primitive"] = VS::get_singleton()->mesh_surface_get_primitive_type(mesh, idx);
  588. d["format"] = VS::get_singleton()->mesh_surface_get_format(mesh, idx);
  589. d["aabb"] = VS::get_singleton()->mesh_surface_get_aabb(mesh, idx);
  590. Vector<AABB> skel_aabb = VS::get_singleton()->mesh_surface_get_skeleton_aabb(mesh, idx);
  591. Array arr;
  592. arr.resize(skel_aabb.size());
  593. for (int i = 0; i < skel_aabb.size(); i++) {
  594. arr[i] = skel_aabb[i];
  595. }
  596. d["skeleton_aabb"] = arr;
  597. Vector<PoolVector<uint8_t>> blend_shape_data = VS::get_singleton()->mesh_surface_get_blend_shapes(mesh, idx);
  598. Array md;
  599. for (int i = 0; i < blend_shape_data.size(); i++) {
  600. md.push_back(blend_shape_data[i]);
  601. }
  602. d["blend_shape_data"] = md;
  603. Ref<Material> m = surface_get_material(idx);
  604. if (m.is_valid()) {
  605. d["material"] = m;
  606. }
  607. String n = surface_get_name(idx);
  608. if (n != "") {
  609. d["name"] = n;
  610. }
  611. r_ret = d;
  612. return true;
  613. }
  614. void ArrayMesh::_get_property_list(List<PropertyInfo> *p_list) const {
  615. if (_is_generated()) {
  616. return;
  617. }
  618. if (blend_shapes.size()) {
  619. p_list->push_back(PropertyInfo(Variant::POOL_STRING_ARRAY, "blend_shape/names", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  620. p_list->push_back(PropertyInfo(Variant::INT, "blend_shape/mode", PROPERTY_HINT_ENUM, "Normalized,Relative"));
  621. }
  622. for (int i = 0; i < surfaces.size(); i++) {
  623. p_list->push_back(PropertyInfo(Variant::DICTIONARY, "surfaces/" + itos(i), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  624. p_list->push_back(PropertyInfo(Variant::STRING, "surface_" + itos(i + 1) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
  625. if (surfaces[i].is_2d) {
  626. p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,CanvasItemMaterial", PROPERTY_USAGE_EDITOR));
  627. } else {
  628. p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,SpatialMaterial", PROPERTY_USAGE_EDITOR));
  629. }
  630. }
  631. }
  632. void ArrayMesh::_recompute_aabb() {
  633. // regenerate AABB
  634. aabb = AABB();
  635. for (int i = 0; i < surfaces.size(); i++) {
  636. if (i == 0) {
  637. aabb = surfaces[i].aabb;
  638. } else {
  639. aabb.merge_with(surfaces[i].aabb);
  640. }
  641. }
  642. }
  643. void ArrayMesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<PoolVector<uint8_t>> &p_blend_shapes, const Vector<AABB> &p_bone_aabbs) {
  644. Surface s;
  645. s.aabb = p_aabb;
  646. s.is_2d = p_format & ARRAY_FLAG_USE_2D_VERTICES;
  647. surfaces.push_back(s);
  648. _recompute_aabb();
  649. VisualServer::get_singleton()->mesh_add_surface(mesh, p_format, (VS::PrimitiveType)p_primitive, p_array, p_vertex_count, p_index_array, p_index_count, p_aabb, p_blend_shapes, p_bone_aabbs);
  650. }
  651. void ArrayMesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, uint32_t p_flags) {
  652. ERR_FAIL_COND(p_arrays.size() != ARRAY_MAX);
  653. Surface s;
  654. VisualServer::get_singleton()->mesh_add_surface_from_arrays(mesh, (VisualServer::PrimitiveType)p_primitive, p_arrays, p_blend_shapes, p_flags);
  655. /* make aABB? */ {
  656. Variant arr = p_arrays[ARRAY_VERTEX];
  657. PoolVector<Vector3> vertices = arr;
  658. int len = vertices.size();
  659. ERR_FAIL_COND(len == 0);
  660. PoolVector<Vector3>::Read r = vertices.read();
  661. const Vector3 *vtx = r.ptr();
  662. // check AABB
  663. AABB aabb;
  664. for (int i = 0; i < len; i++) {
  665. if (i == 0) {
  666. aabb.position = vtx[i];
  667. } else {
  668. aabb.expand_to(vtx[i]);
  669. }
  670. }
  671. s.aabb = aabb;
  672. s.is_2d = arr.get_type() == Variant::POOL_VECTOR2_ARRAY;
  673. surfaces.push_back(s);
  674. _recompute_aabb();
  675. }
  676. clear_cache();
  677. _change_notify();
  678. emit_changed();
  679. }
  680. Array ArrayMesh::surface_get_arrays(int p_surface) const {
  681. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  682. return VisualServer::get_singleton()->mesh_surface_get_arrays(mesh, p_surface);
  683. }
  684. Array ArrayMesh::surface_get_blend_shape_arrays(int p_surface) const {
  685. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  686. return VisualServer::get_singleton()->mesh_surface_get_blend_shape_arrays(mesh, p_surface);
  687. }
  688. int ArrayMesh::get_surface_count() const {
  689. return surfaces.size();
  690. }
  691. void ArrayMesh::add_blend_shape(const StringName &p_name) {
  692. ERR_FAIL_COND_MSG(surfaces.size(), "Can't add a shape key count if surfaces are already created.");
  693. StringName name = p_name;
  694. if (blend_shapes.find(name) != -1) {
  695. int count = 2;
  696. do {
  697. name = String(p_name) + " " + itos(count);
  698. count++;
  699. } while (blend_shapes.find(name) != -1);
  700. }
  701. blend_shapes.push_back(name);
  702. VS::get_singleton()->mesh_set_blend_shape_count(mesh, blend_shapes.size());
  703. }
  704. int ArrayMesh::get_blend_shape_count() const {
  705. return blend_shapes.size();
  706. }
  707. StringName ArrayMesh::get_blend_shape_name(int p_index) const {
  708. ERR_FAIL_INDEX_V(p_index, blend_shapes.size(), StringName());
  709. return blend_shapes[p_index];
  710. }
  711. void ArrayMesh::set_blend_shape_name(int p_index, const StringName &p_name) {
  712. ERR_FAIL_INDEX(p_index, blend_shapes.size());
  713. StringName name = p_name;
  714. int found = blend_shapes.find(name);
  715. if (found != -1 && found != p_index) {
  716. int count = 2;
  717. do {
  718. name = String(p_name) + " " + itos(count);
  719. count++;
  720. } while (blend_shapes.find(name) != -1);
  721. }
  722. blend_shapes.write[p_index] = name;
  723. }
  724. void ArrayMesh::clear_blend_shapes() {
  725. ERR_FAIL_COND_MSG(surfaces.size(), "Can't set shape key count if surfaces are already created.");
  726. blend_shapes.clear();
  727. }
  728. void ArrayMesh::set_blend_shape_mode(BlendShapeMode p_mode) {
  729. blend_shape_mode = p_mode;
  730. VS::get_singleton()->mesh_set_blend_shape_mode(mesh, (VS::BlendShapeMode)p_mode);
  731. }
  732. ArrayMesh::BlendShapeMode ArrayMesh::get_blend_shape_mode() const {
  733. return blend_shape_mode;
  734. }
  735. void ArrayMesh::surface_remove(int p_idx) {
  736. ERR_FAIL_INDEX(p_idx, surfaces.size());
  737. VisualServer::get_singleton()->mesh_remove_surface(mesh, p_idx);
  738. surfaces.remove(p_idx);
  739. clear_cache();
  740. _recompute_aabb();
  741. _change_notify();
  742. emit_changed();
  743. }
  744. int ArrayMesh::surface_get_array_len(int p_idx) const {
  745. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
  746. return VisualServer::get_singleton()->mesh_surface_get_array_len(mesh, p_idx);
  747. }
  748. int ArrayMesh::surface_get_array_index_len(int p_idx) const {
  749. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
  750. return VisualServer::get_singleton()->mesh_surface_get_array_index_len(mesh, p_idx);
  751. }
  752. uint32_t ArrayMesh::surface_get_format(int p_idx) const {
  753. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), 0);
  754. return VisualServer::get_singleton()->mesh_surface_get_format(mesh, p_idx);
  755. }
  756. ArrayMesh::PrimitiveType ArrayMesh::surface_get_primitive_type(int p_idx) const {
  757. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), PRIMITIVE_LINES);
  758. return (PrimitiveType)VisualServer::get_singleton()->mesh_surface_get_primitive_type(mesh, p_idx);
  759. }
  760. void ArrayMesh::surface_set_material(int p_idx, const Ref<Material> &p_material) {
  761. ERR_FAIL_INDEX(p_idx, surfaces.size());
  762. if (surfaces[p_idx].material == p_material) {
  763. return;
  764. }
  765. surfaces.write[p_idx].material = p_material;
  766. VisualServer::get_singleton()->mesh_surface_set_material(mesh, p_idx, p_material.is_null() ? RID() : p_material->get_rid());
  767. _change_notify("material");
  768. emit_changed();
  769. }
  770. int ArrayMesh::surface_find_by_name(const String &p_name) const {
  771. for (int i = 0; i < surfaces.size(); i++) {
  772. if (surfaces[i].name == p_name) {
  773. return i;
  774. }
  775. }
  776. return -1;
  777. }
  778. void ArrayMesh::surface_set_name(int p_idx, const String &p_name) {
  779. ERR_FAIL_INDEX(p_idx, surfaces.size());
  780. surfaces.write[p_idx].name = p_name;
  781. emit_changed();
  782. }
  783. String ArrayMesh::surface_get_name(int p_idx) const {
  784. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), String());
  785. return surfaces[p_idx].name;
  786. }
  787. void ArrayMesh::surface_update_region(int p_surface, int p_offset, const PoolVector<uint8_t> &p_data) {
  788. ERR_FAIL_INDEX(p_surface, surfaces.size());
  789. VS::get_singleton()->mesh_surface_update_region(mesh, p_surface, p_offset, p_data);
  790. emit_changed();
  791. }
  792. void ArrayMesh::surface_set_custom_aabb(int p_idx, const AABB &p_aabb) {
  793. ERR_FAIL_INDEX(p_idx, surfaces.size());
  794. surfaces.write[p_idx].aabb = p_aabb;
  795. // set custom aabb too?
  796. emit_changed();
  797. }
  798. Ref<Material> ArrayMesh::surface_get_material(int p_idx) const {
  799. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), Ref<Material>());
  800. return surfaces[p_idx].material;
  801. }
  802. void ArrayMesh::add_surface_from_mesh_data(const Geometry::MeshData &p_mesh_data) {
  803. VisualServer::get_singleton()->mesh_add_surface_from_mesh_data(mesh, p_mesh_data);
  804. AABB aabb;
  805. for (int i = 0; i < p_mesh_data.vertices.size(); i++) {
  806. if (i == 0) {
  807. aabb.position = p_mesh_data.vertices[i];
  808. } else {
  809. aabb.expand_to(p_mesh_data.vertices[i]);
  810. }
  811. }
  812. Surface s;
  813. s.aabb = aabb;
  814. if (surfaces.size() == 0) {
  815. aabb = s.aabb;
  816. } else {
  817. aabb.merge_with(s.aabb);
  818. }
  819. clear_cache();
  820. surfaces.push_back(s);
  821. _change_notify();
  822. emit_changed();
  823. }
  824. RID ArrayMesh::get_rid() const {
  825. return mesh;
  826. }
  827. AABB ArrayMesh::get_aabb() const {
  828. return aabb;
  829. }
  830. void ArrayMesh::clear_surfaces() {
  831. if (!mesh.is_valid()) {
  832. return;
  833. }
  834. VS::get_singleton()->mesh_clear(mesh);
  835. surfaces.clear();
  836. aabb = AABB();
  837. }
  838. void ArrayMesh::set_custom_aabb(const AABB &p_custom) {
  839. custom_aabb = p_custom;
  840. VS::get_singleton()->mesh_set_custom_aabb(mesh, custom_aabb);
  841. emit_changed();
  842. }
  843. AABB ArrayMesh::get_custom_aabb() const {
  844. return custom_aabb;
  845. }
  846. void ArrayMesh::regen_normalmaps() {
  847. Vector<Ref<SurfaceTool>> surfs;
  848. for (int i = 0; i < get_surface_count(); i++) {
  849. Ref<SurfaceTool> st = memnew(SurfaceTool);
  850. st->create_from(Ref<ArrayMesh>(this), i);
  851. surfs.push_back(st);
  852. }
  853. while (get_surface_count()) {
  854. surface_remove(0);
  855. }
  856. for (int i = 0; i < surfs.size(); i++) {
  857. surfs.write[i]->generate_tangents();
  858. surfs.write[i]->commit(Ref<ArrayMesh>(this));
  859. }
  860. }
  861. //dirty hack
  862. bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) = nullptr;
  863. struct ArrayMeshLightmapSurface {
  864. Ref<Material> material;
  865. Vector<SurfaceTool::Vertex> vertices;
  866. Mesh::PrimitiveType primitive;
  867. uint32_t format;
  868. };
  869. Error ArrayMesh::lightmap_unwrap(const Transform &p_base_transform, float p_texel_size) {
  870. int *cache_data = nullptr;
  871. unsigned int cache_size = 0;
  872. bool use_cache = false; // Don't use cache
  873. return lightmap_unwrap_cached(cache_data, cache_size, use_cache, p_base_transform, p_texel_size);
  874. }
  875. Error ArrayMesh::lightmap_unwrap_cached(int *&r_cache_data, unsigned int &r_cache_size, bool &r_used_cache, const Transform &p_base_transform, float p_texel_size) {
  876. ERR_FAIL_COND_V(!array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
  877. ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
  878. ERR_FAIL_COND_V_MSG(p_texel_size <= 0.0f, ERR_PARAMETER_RANGE_ERROR, "Texel size must be greater than 0.");
  879. LocalVector<float> vertices;
  880. LocalVector<float> normals;
  881. LocalVector<int> indices;
  882. LocalVector<int> face_materials;
  883. LocalVector<float> uv;
  884. LocalVector<Pair<int, int>> uv_indices;
  885. Vector<ArrayMeshLightmapSurface> lightmap_surfaces;
  886. // Keep only the scale
  887. Basis basis = p_base_transform.get_basis();
  888. Vector3 scale = Vector3(basis.get_axis(0).length(), basis.get_axis(1).length(), basis.get_axis(2).length());
  889. Transform transform;
  890. transform.scale(scale);
  891. Basis normal_basis = transform.basis.inverse().transposed();
  892. for (int i = 0; i < get_surface_count(); i++) {
  893. ArrayMeshLightmapSurface s;
  894. s.primitive = surface_get_primitive_type(i);
  895. ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
  896. s.format = surface_get_format(i);
  897. ERR_FAIL_COND_V_MSG(!(s.format & ARRAY_FORMAT_NORMAL), ERR_UNAVAILABLE, "Normals are required for lightmap unwrap.");
  898. Array arrays = surface_get_arrays(i);
  899. s.material = surface_get_material(i);
  900. s.vertices = SurfaceTool::create_vertex_array_from_triangle_arrays(arrays);
  901. PoolVector<Vector3> rvertices = arrays[Mesh::ARRAY_VERTEX];
  902. int vc = rvertices.size();
  903. PoolVector<Vector3>::Read r = rvertices.read();
  904. PoolVector<Vector3> rnormals = arrays[Mesh::ARRAY_NORMAL];
  905. PoolVector<Vector3>::Read rn = rnormals.read();
  906. int vertex_ofs = vertices.size() / 3;
  907. vertices.resize((vertex_ofs + vc) * 3);
  908. normals.resize((vertex_ofs + vc) * 3);
  909. uv_indices.resize(vertex_ofs + vc);
  910. for (int j = 0; j < vc; j++) {
  911. Vector3 v = transform.xform(r[j]);
  912. Vector3 n = normal_basis.xform(rn[j]).normalized();
  913. vertices[(j + vertex_ofs) * 3 + 0] = v.x;
  914. vertices[(j + vertex_ofs) * 3 + 1] = v.y;
  915. vertices[(j + vertex_ofs) * 3 + 2] = v.z;
  916. normals[(j + vertex_ofs) * 3 + 0] = n.x;
  917. normals[(j + vertex_ofs) * 3 + 1] = n.y;
  918. normals[(j + vertex_ofs) * 3 + 2] = n.z;
  919. uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
  920. }
  921. PoolVector<int> rindices = arrays[Mesh::ARRAY_INDEX];
  922. int ic = rindices.size();
  923. float eps = 1.19209290e-7F; // Taken from xatlas.h
  924. if (ic == 0) {
  925. for (int j = 0; j < vc / 3; j++) {
  926. Vector3 p0 = transform.xform(r[j * 3 + 0]);
  927. Vector3 p1 = transform.xform(r[j * 3 + 1]);
  928. Vector3 p2 = transform.xform(r[j * 3 + 2]);
  929. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  930. continue;
  931. }
  932. indices.push_back(vertex_ofs + j * 3 + 0);
  933. indices.push_back(vertex_ofs + j * 3 + 1);
  934. indices.push_back(vertex_ofs + j * 3 + 2);
  935. face_materials.push_back(i);
  936. }
  937. } else {
  938. PoolVector<int>::Read ri = rindices.read();
  939. for (int j = 0; j < ic / 3; j++) {
  940. Vector3 p0 = transform.xform(r[ri[j * 3 + 0]]);
  941. Vector3 p1 = transform.xform(r[ri[j * 3 + 1]]);
  942. Vector3 p2 = transform.xform(r[ri[j * 3 + 2]]);
  943. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  944. continue;
  945. }
  946. indices.push_back(vertex_ofs + ri[j * 3 + 0]);
  947. indices.push_back(vertex_ofs + ri[j * 3 + 1]);
  948. indices.push_back(vertex_ofs + ri[j * 3 + 2]);
  949. face_materials.push_back(i);
  950. }
  951. }
  952. lightmap_surfaces.push_back(s);
  953. }
  954. CryptoCore::MD5Context ctx;
  955. ctx.start();
  956. ctx.update((unsigned char *)&p_texel_size, sizeof(float));
  957. ctx.update((unsigned char *)indices.ptr(), sizeof(int) * indices.size());
  958. ctx.update((unsigned char *)face_materials.ptr(), sizeof(int) * face_materials.size());
  959. ctx.update((unsigned char *)vertices.ptr(), sizeof(float) * vertices.size());
  960. ctx.update((unsigned char *)normals.ptr(), sizeof(float) * normals.size());
  961. unsigned char hash[16];
  962. ctx.finish(hash);
  963. bool cached = false;
  964. unsigned int cache_idx = 0;
  965. if (r_used_cache && r_cache_data) {
  966. //Check if hash is in cache data
  967. int *cache_data = r_cache_data;
  968. int n_entries = cache_data[0];
  969. unsigned int r_idx = 1;
  970. for (int i = 0; i < n_entries; ++i) {
  971. if (memcmp(&cache_data[r_idx], hash, 16) == 0) {
  972. cached = true;
  973. cache_idx = r_idx;
  974. break;
  975. }
  976. r_idx += 4; // hash
  977. r_idx += 2; // size hint
  978. int vertex_count = cache_data[r_idx];
  979. r_idx += 1; // vertex count
  980. r_idx += vertex_count; // vertex
  981. r_idx += vertex_count * 2; // uvs
  982. int index_count = cache_data[r_idx];
  983. r_idx += 1; // index count
  984. r_idx += index_count; // indices
  985. }
  986. }
  987. //unwrap
  988. float *gen_uvs;
  989. int *gen_vertices;
  990. int *gen_indices;
  991. int gen_vertex_count;
  992. int gen_index_count;
  993. int size_x;
  994. int size_y;
  995. if (r_used_cache && cached) {
  996. int *cache_data = r_cache_data;
  997. // Return cache data pointer to the caller
  998. r_cache_data = &cache_data[cache_idx];
  999. cache_idx += 4;
  1000. // Load size
  1001. size_x = ((int *)cache_data)[cache_idx];
  1002. size_y = ((int *)cache_data)[cache_idx + 1];
  1003. cache_idx += 2;
  1004. // Load vertices
  1005. gen_vertex_count = cache_data[cache_idx];
  1006. cache_idx++;
  1007. gen_vertices = &cache_data[cache_idx];
  1008. cache_idx += gen_vertex_count;
  1009. // Load UVs
  1010. gen_uvs = (float *)&cache_data[cache_idx];
  1011. cache_idx += gen_vertex_count * 2;
  1012. // Load indices
  1013. gen_index_count = cache_data[cache_idx];
  1014. cache_idx++;
  1015. gen_indices = &cache_data[cache_idx];
  1016. // Return cache data size to the caller
  1017. r_cache_size = sizeof(int) * (4 + 2 + 1 + gen_vertex_count + (gen_vertex_count * 2) + 1 + gen_index_count); // hash + size hint + vertex_count + vertices + uvs + index_count + indices
  1018. r_used_cache = true;
  1019. }
  1020. if (!cached) {
  1021. bool ok = array_mesh_lightmap_unwrap_callback(p_texel_size, vertices.ptr(), normals.ptr(), vertices.size() / 3, indices.ptr(), face_materials.ptr(), indices.size(), &gen_uvs, &gen_vertices, &gen_vertex_count, &gen_indices, &gen_index_count, &size_x, &size_y);
  1022. if (!ok) {
  1023. return ERR_CANT_CREATE;
  1024. }
  1025. if (r_used_cache) {
  1026. unsigned int new_cache_size = 4 + 2 + 1 + gen_vertex_count + (gen_vertex_count * 2) + 1 + gen_index_count; // hash + size hint + vertex_count + vertices + uvs + index_count + indices
  1027. new_cache_size *= sizeof(int);
  1028. int *new_cache_data = (int *)memalloc(new_cache_size);
  1029. unsigned int new_cache_idx = 0;
  1030. // hash
  1031. memcpy(&new_cache_data[new_cache_idx], hash, 16);
  1032. new_cache_idx += 4;
  1033. // size hint
  1034. new_cache_data[new_cache_idx] = size_x;
  1035. new_cache_data[new_cache_idx + 1] = size_y;
  1036. new_cache_idx += 2;
  1037. // vertex count
  1038. new_cache_data[new_cache_idx] = gen_vertex_count;
  1039. new_cache_idx++;
  1040. // vertices
  1041. memcpy(&new_cache_data[new_cache_idx], gen_vertices, sizeof(int) * gen_vertex_count);
  1042. new_cache_idx += gen_vertex_count;
  1043. // uvs
  1044. memcpy(&new_cache_data[new_cache_idx], gen_uvs, sizeof(float) * gen_vertex_count * 2);
  1045. new_cache_idx += gen_vertex_count * 2;
  1046. // index count
  1047. new_cache_data[new_cache_idx] = gen_index_count;
  1048. new_cache_idx++;
  1049. // indices
  1050. memcpy(&new_cache_data[new_cache_idx], gen_indices, sizeof(int) * gen_index_count);
  1051. new_cache_idx += gen_index_count;
  1052. // Return cache data to the caller
  1053. r_cache_data = new_cache_data;
  1054. r_cache_size = new_cache_size;
  1055. r_used_cache = false;
  1056. }
  1057. }
  1058. //remove surfaces
  1059. while (get_surface_count()) {
  1060. surface_remove(0);
  1061. }
  1062. //create surfacetools for each surface..
  1063. LocalVector<Ref<SurfaceTool>> surfaces_tools;
  1064. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  1065. Ref<SurfaceTool> st;
  1066. st.instance();
  1067. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  1068. st->set_material(lightmap_surfaces[i].material);
  1069. surfaces_tools.push_back(st); //stay there
  1070. }
  1071. print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
  1072. //go through all indices
  1073. for (int i = 0; i < gen_index_count; i += 3) {
  1074. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
  1075. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
  1076. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
  1077. ERR_FAIL_COND_V(uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 1]]].first || uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 2]]].first, ERR_BUG);
  1078. int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
  1079. for (int j = 0; j < 3; j++) {
  1080. SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
  1081. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_COLOR) {
  1082. surfaces_tools[surface]->add_color(v.color);
  1083. }
  1084. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_TEX_UV) {
  1085. surfaces_tools[surface]->add_uv(v.uv);
  1086. }
  1087. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_NORMAL) {
  1088. surfaces_tools[surface]->add_normal(v.normal);
  1089. }
  1090. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_TANGENT) {
  1091. Plane t;
  1092. t.normal = v.tangent;
  1093. t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
  1094. surfaces_tools[surface]->add_tangent(t);
  1095. }
  1096. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_BONES) {
  1097. surfaces_tools[surface]->add_bones(v.bones);
  1098. }
  1099. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_WEIGHTS) {
  1100. surfaces_tools[surface]->add_weights(v.weights);
  1101. }
  1102. Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
  1103. surfaces_tools[surface]->add_uv2(uv2);
  1104. surfaces_tools[surface]->add_vertex(v.vertex);
  1105. }
  1106. }
  1107. //generate surfaces
  1108. for (unsigned int i = 0; i < surfaces_tools.size(); i++) {
  1109. surfaces_tools[i]->index();
  1110. surfaces_tools[i]->commit(Ref<ArrayMesh>((ArrayMesh *)this), lightmap_surfaces[i].format);
  1111. }
  1112. set_lightmap_size_hint(Size2(size_x, size_y));
  1113. if (!cached) {
  1114. //free stuff
  1115. ::free(gen_vertices);
  1116. ::free(gen_indices);
  1117. ::free(gen_uvs);
  1118. }
  1119. return OK;
  1120. }
  1121. void ArrayMesh::_bind_methods() {
  1122. ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ArrayMesh::add_blend_shape);
  1123. ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ArrayMesh::get_blend_shape_count);
  1124. ClassDB::bind_method(D_METHOD("get_blend_shape_name", "index"), &ArrayMesh::get_blend_shape_name);
  1125. ClassDB::bind_method(D_METHOD("set_blend_shape_name", "index", "name"), &ArrayMesh::set_blend_shape_name);
  1126. ClassDB::bind_method(D_METHOD("clear_blend_shapes"), &ArrayMesh::clear_blend_shapes);
  1127. ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ArrayMesh::set_blend_shape_mode);
  1128. ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ArrayMesh::get_blend_shape_mode);
  1129. ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "compress_flags"), &ArrayMesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(ARRAY_COMPRESS_DEFAULT));
  1130. ClassDB::bind_method(D_METHOD("clear_surfaces"), &ArrayMesh::clear_surfaces);
  1131. ClassDB::bind_method(D_METHOD("surface_remove", "surf_idx"), &ArrayMesh::surface_remove);
  1132. ClassDB::bind_method(D_METHOD("surface_update_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_region);
  1133. ClassDB::bind_method(D_METHOD("surface_get_array_len", "surf_idx"), &ArrayMesh::surface_get_array_len);
  1134. ClassDB::bind_method(D_METHOD("surface_get_array_index_len", "surf_idx"), &ArrayMesh::surface_get_array_index_len);
  1135. ClassDB::bind_method(D_METHOD("surface_get_format", "surf_idx"), &ArrayMesh::surface_get_format);
  1136. ClassDB::bind_method(D_METHOD("surface_get_primitive_type", "surf_idx"), &ArrayMesh::surface_get_primitive_type);
  1137. ClassDB::bind_method(D_METHOD("surface_find_by_name", "name"), &ArrayMesh::surface_find_by_name);
  1138. ClassDB::bind_method(D_METHOD("surface_set_name", "surf_idx", "name"), &ArrayMesh::surface_set_name);
  1139. ClassDB::bind_method(D_METHOD("surface_get_name", "surf_idx"), &ArrayMesh::surface_get_name);
  1140. ClassDB::bind_method(D_METHOD("create_trimesh_shape"), &ArrayMesh::create_trimesh_shape);
  1141. ClassDB::bind_method(D_METHOD("create_convex_shape", "clean", "simplify"), &ArrayMesh::create_convex_shape, DEFVAL(true), DEFVAL(false));
  1142. ClassDB::bind_method(D_METHOD("create_outline", "margin"), &ArrayMesh::create_outline);
  1143. ClassDB::bind_method(D_METHOD("regen_normalmaps"), &ArrayMesh::regen_normalmaps);
  1144. ClassDB::set_method_flags(get_class_static(), _scs_create("regen_normalmaps"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  1145. ClassDB::bind_method(D_METHOD("lightmap_unwrap", "transform", "texel_size"), &ArrayMesh::lightmap_unwrap);
  1146. ClassDB::set_method_flags(get_class_static(), _scs_create("lightmap_unwrap"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  1147. ClassDB::bind_method(D_METHOD("get_faces"), &ArrayMesh::get_faces);
  1148. ClassDB::bind_method(D_METHOD("generate_triangle_mesh"), &ArrayMesh::generate_triangle_mesh);
  1149. ClassDB::bind_method(D_METHOD("set_custom_aabb", "aabb"), &ArrayMesh::set_custom_aabb);
  1150. ClassDB::bind_method(D_METHOD("get_custom_aabb"), &ArrayMesh::get_custom_aabb);
  1151. ADD_PROPERTY(PropertyInfo(Variant::INT, "blend_shape_mode", PROPERTY_HINT_ENUM, "Normalized,Relative", PROPERTY_USAGE_NOEDITOR), "set_blend_shape_mode", "get_blend_shape_mode");
  1152. ADD_PROPERTY(PropertyInfo(Variant::AABB, "custom_aabb", PROPERTY_HINT_NONE, ""), "set_custom_aabb", "get_custom_aabb");
  1153. BIND_CONSTANT(NO_INDEX_ARRAY);
  1154. BIND_CONSTANT(ARRAY_WEIGHTS_SIZE);
  1155. BIND_ENUM_CONSTANT(ARRAY_VERTEX);
  1156. BIND_ENUM_CONSTANT(ARRAY_NORMAL);
  1157. BIND_ENUM_CONSTANT(ARRAY_TANGENT);
  1158. BIND_ENUM_CONSTANT(ARRAY_COLOR);
  1159. BIND_ENUM_CONSTANT(ARRAY_TEX_UV);
  1160. BIND_ENUM_CONSTANT(ARRAY_TEX_UV2);
  1161. BIND_ENUM_CONSTANT(ARRAY_BONES);
  1162. BIND_ENUM_CONSTANT(ARRAY_WEIGHTS);
  1163. BIND_ENUM_CONSTANT(ARRAY_INDEX);
  1164. BIND_ENUM_CONSTANT(ARRAY_MAX);
  1165. BIND_ENUM_CONSTANT(ARRAY_FORMAT_VERTEX);
  1166. BIND_ENUM_CONSTANT(ARRAY_FORMAT_NORMAL);
  1167. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TANGENT);
  1168. BIND_ENUM_CONSTANT(ARRAY_FORMAT_COLOR);
  1169. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV);
  1170. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV2);
  1171. BIND_ENUM_CONSTANT(ARRAY_FORMAT_BONES);
  1172. BIND_ENUM_CONSTANT(ARRAY_FORMAT_WEIGHTS);
  1173. BIND_ENUM_CONSTANT(ARRAY_FORMAT_INDEX);
  1174. }
  1175. void ArrayMesh::reload_from_file() {
  1176. VisualServer::get_singleton()->mesh_clear(mesh);
  1177. surfaces.clear();
  1178. clear_blend_shapes();
  1179. clear_cache();
  1180. Resource::reload_from_file();
  1181. _change_notify();
  1182. }
  1183. ArrayMesh::ArrayMesh() {
  1184. mesh = RID_PRIME(VisualServer::get_singleton()->mesh_create());
  1185. blend_shape_mode = BLEND_SHAPE_MODE_RELATIVE;
  1186. }
  1187. ArrayMesh::~ArrayMesh() {
  1188. VisualServer::get_singleton()->free(mesh);
  1189. }