surface_tool.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. /**************************************************************************/
  2. /* surface_tool.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 "surface_tool.h"
  31. #define EQ_VERTEX_DIST 0.00001
  32. SurfaceTool::OptimizeVertexCacheFunc SurfaceTool::optimize_vertex_cache_func = nullptr;
  33. SurfaceTool::SimplifyFunc SurfaceTool::simplify_func = nullptr;
  34. SurfaceTool::SimplifyWithAttribFunc SurfaceTool::simplify_with_attrib_func = nullptr;
  35. SurfaceTool::SimplifyScaleFunc SurfaceTool::simplify_scale_func = nullptr;
  36. SurfaceTool::SimplifySloppyFunc SurfaceTool::simplify_sloppy_func = nullptr;
  37. SurfaceTool::GenerateRemapFunc SurfaceTool::generate_remap_func = nullptr;
  38. SurfaceTool::RemapVertexFunc SurfaceTool::remap_vertex_func = nullptr;
  39. SurfaceTool::RemapIndexFunc SurfaceTool::remap_index_func = nullptr;
  40. void SurfaceTool::strip_mesh_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
  41. ERR_FAIL_COND_MSG(!generate_remap_func || !remap_vertex_func || !remap_index_func, "Meshoptimizer library is not initialized.");
  42. Vector<uint32_t> remap;
  43. remap.resize(r_vertices.size());
  44. uint32_t new_vertex_count = generate_remap_func(remap.ptrw(), (unsigned int *)r_indices.ptr(), r_indices.size(), r_vertices.ptr(), r_vertices.size(), sizeof(Vector3));
  45. remap_vertex_func(r_vertices.ptrw(), r_vertices.ptr(), r_vertices.size(), sizeof(Vector3), remap.ptr());
  46. r_vertices.resize(new_vertex_count);
  47. remap_index_func((unsigned int *)r_indices.ptrw(), (unsigned int *)r_indices.ptr(), r_indices.size(), remap.ptr());
  48. HashMap<const int *, bool, TriangleHasher, TriangleHasher> found_triangles;
  49. int *idx_ptr = r_indices.ptrw();
  50. int filtered_indices_count = 0;
  51. for (int i = 0; i < r_indices.size() / 3; i++) {
  52. const int *tri = idx_ptr + (i * 3);
  53. if (tri[0] == tri[1] || tri[1] == tri[2] || tri[2] == tri[0]) {
  54. continue;
  55. }
  56. if (found_triangles.has(tri)) {
  57. continue;
  58. }
  59. if (i != filtered_indices_count) {
  60. memcpy(idx_ptr + (filtered_indices_count * 3), tri, sizeof(int) * 3);
  61. }
  62. found_triangles[tri] = true;
  63. filtered_indices_count++;
  64. }
  65. r_indices.resize(filtered_indices_count * 3);
  66. }
  67. bool SurfaceTool::Vertex::operator==(const Vertex &p_vertex) const {
  68. if (vertex != p_vertex.vertex) {
  69. return false;
  70. }
  71. if (uv != p_vertex.uv) {
  72. return false;
  73. }
  74. if (uv2 != p_vertex.uv2) {
  75. return false;
  76. }
  77. if (normal != p_vertex.normal) {
  78. return false;
  79. }
  80. if (binormal != p_vertex.binormal) {
  81. return false;
  82. }
  83. if (color != p_vertex.color) {
  84. return false;
  85. }
  86. if (bones.size() != p_vertex.bones.size()) {
  87. return false;
  88. }
  89. for (int i = 0; i < bones.size(); i++) {
  90. if (bones[i] != p_vertex.bones[i]) {
  91. return false;
  92. }
  93. }
  94. for (int i = 0; i < weights.size(); i++) {
  95. if (weights[i] != p_vertex.weights[i]) {
  96. return false;
  97. }
  98. }
  99. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  100. if (custom[i] != p_vertex.custom[i]) {
  101. return false;
  102. }
  103. }
  104. if (smooth_group != p_vertex.smooth_group) {
  105. return false;
  106. }
  107. return true;
  108. }
  109. uint32_t SurfaceTool::VertexHasher::hash(const Vertex &p_vtx) {
  110. uint32_t h = hash_djb2_buffer((const uint8_t *)&p_vtx.vertex, sizeof(real_t) * 3);
  111. h = hash_djb2_buffer((const uint8_t *)&p_vtx.normal, sizeof(real_t) * 3, h);
  112. h = hash_djb2_buffer((const uint8_t *)&p_vtx.binormal, sizeof(real_t) * 3, h);
  113. h = hash_djb2_buffer((const uint8_t *)&p_vtx.tangent, sizeof(real_t) * 3, h);
  114. h = hash_djb2_buffer((const uint8_t *)&p_vtx.uv, sizeof(real_t) * 2, h);
  115. h = hash_djb2_buffer((const uint8_t *)&p_vtx.uv2, sizeof(real_t) * 2, h);
  116. h = hash_djb2_buffer((const uint8_t *)&p_vtx.color, sizeof(real_t) * 4, h);
  117. h = hash_djb2_buffer((const uint8_t *)p_vtx.bones.ptr(), p_vtx.bones.size() * sizeof(int), h);
  118. h = hash_djb2_buffer((const uint8_t *)p_vtx.weights.ptr(), p_vtx.weights.size() * sizeof(float), h);
  119. h = hash_djb2_buffer((const uint8_t *)&p_vtx.custom[0], sizeof(Color) * RS::ARRAY_CUSTOM_COUNT, h);
  120. h = hash_murmur3_one_32(p_vtx.smooth_group, h);
  121. h = hash_fmix32(h);
  122. return h;
  123. }
  124. bool SurfaceTool::SmoothGroupVertex::operator==(const SmoothGroupVertex &p_vertex) const {
  125. if (vertex != p_vertex.vertex) {
  126. return false;
  127. }
  128. if (smooth_group != p_vertex.smooth_group) {
  129. return false;
  130. }
  131. return true;
  132. }
  133. uint32_t SurfaceTool::SmoothGroupVertexHasher::hash(const SmoothGroupVertex &p_vtx) {
  134. uint32_t h = hash_djb2_buffer((const uint8_t *)&p_vtx.vertex, sizeof(real_t) * 3);
  135. h = hash_murmur3_one_32(p_vtx.smooth_group, h);
  136. h = hash_fmix32(h);
  137. return h;
  138. }
  139. uint32_t SurfaceTool::TriangleHasher::hash(const int *p_triangle) {
  140. int t0 = p_triangle[0];
  141. int t1 = p_triangle[1];
  142. int t2 = p_triangle[2];
  143. if (t0 > t1) {
  144. SWAP(t0, t1);
  145. }
  146. if (t1 > t2) {
  147. SWAP(t1, t2);
  148. }
  149. if (t0 > t1) {
  150. SWAP(t0, t1);
  151. }
  152. return (t0 * 73856093) ^ (t1 * 19349663) ^ (t2 * 83492791);
  153. }
  154. bool SurfaceTool::TriangleHasher::compare(const int *p_lhs, const int *p_rhs) {
  155. int r0 = p_rhs[0];
  156. int r1 = p_rhs[1];
  157. int r2 = p_rhs[2];
  158. if (r0 > r1) {
  159. SWAP(r0, r1);
  160. }
  161. if (r1 > r2) {
  162. SWAP(r1, r2);
  163. }
  164. if (r0 > r1) {
  165. SWAP(r0, r1);
  166. }
  167. int l0 = p_lhs[0];
  168. int l1 = p_lhs[1];
  169. int l2 = p_lhs[2];
  170. if (l0 > l1) {
  171. SWAP(l0, l1);
  172. }
  173. if (l1 > l2) {
  174. SWAP(l1, l2);
  175. }
  176. if (l0 > l1) {
  177. SWAP(l0, l1);
  178. }
  179. return l0 == r0 && l1 == r1 && l2 == r2;
  180. }
  181. void SurfaceTool::begin(Mesh::PrimitiveType p_primitive) {
  182. clear();
  183. primitive = p_primitive;
  184. begun = true;
  185. first = true;
  186. }
  187. void SurfaceTool::add_vertex(const Vector3 &p_vertex) {
  188. ERR_FAIL_COND(!begun);
  189. Vertex vtx;
  190. vtx.vertex = p_vertex;
  191. vtx.color = last_color;
  192. vtx.normal = last_normal;
  193. vtx.uv = last_uv;
  194. vtx.uv2 = last_uv2;
  195. vtx.weights = last_weights;
  196. vtx.bones = last_bones;
  197. vtx.tangent = last_tangent.normal;
  198. vtx.binormal = last_normal.cross(last_tangent.normal).normalized() * last_tangent.d;
  199. vtx.smooth_group = last_smooth_group;
  200. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  201. vtx.custom[i] = last_custom[i];
  202. }
  203. const int expected_vertices = skin_weights == SKIN_8_WEIGHTS ? 8 : 4;
  204. if ((format & Mesh::ARRAY_FORMAT_WEIGHTS || format & Mesh::ARRAY_FORMAT_BONES) && (vtx.weights.size() != expected_vertices || vtx.bones.size() != expected_vertices)) {
  205. //ensure vertices are the expected amount
  206. ERR_FAIL_COND(vtx.weights.size() != vtx.bones.size());
  207. if (vtx.weights.size() < expected_vertices) {
  208. //less than required, fill
  209. for (int i = vtx.weights.size(); i < expected_vertices; i++) {
  210. vtx.weights.push_back(0);
  211. vtx.bones.push_back(0);
  212. }
  213. } else if (vtx.weights.size() > expected_vertices) {
  214. //more than required, sort, cap and normalize.
  215. Vector<WeightSort> weights;
  216. for (int i = 0; i < vtx.weights.size(); i++) {
  217. WeightSort ws;
  218. ws.index = vtx.bones[i];
  219. ws.weight = vtx.weights[i];
  220. weights.push_back(ws);
  221. }
  222. //sort
  223. weights.sort();
  224. //cap
  225. weights.resize(expected_vertices);
  226. //renormalize
  227. float total = 0.0;
  228. for (int i = 0; i < expected_vertices; i++) {
  229. total += weights[i].weight;
  230. }
  231. vtx.weights.resize(expected_vertices);
  232. vtx.bones.resize(expected_vertices);
  233. for (int i = 0; i < expected_vertices; i++) {
  234. if (total > 0) {
  235. vtx.weights.write[i] = weights[i].weight / total;
  236. } else {
  237. vtx.weights.write[i] = 0;
  238. }
  239. vtx.bones.write[i] = weights[i].index;
  240. }
  241. }
  242. }
  243. vertex_array.push_back(vtx);
  244. first = false;
  245. format |= Mesh::ARRAY_FORMAT_VERTEX;
  246. }
  247. void SurfaceTool::set_color(Color p_color) {
  248. ERR_FAIL_COND(!begun);
  249. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_COLOR));
  250. format |= Mesh::ARRAY_FORMAT_COLOR;
  251. last_color = p_color;
  252. }
  253. void SurfaceTool::set_normal(const Vector3 &p_normal) {
  254. ERR_FAIL_COND(!begun);
  255. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_NORMAL));
  256. format |= Mesh::ARRAY_FORMAT_NORMAL;
  257. last_normal = p_normal;
  258. }
  259. void SurfaceTool::set_tangent(const Plane &p_tangent) {
  260. ERR_FAIL_COND(!begun);
  261. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TANGENT));
  262. format |= Mesh::ARRAY_FORMAT_TANGENT;
  263. last_tangent = p_tangent;
  264. }
  265. void SurfaceTool::set_uv(const Vector2 &p_uv) {
  266. ERR_FAIL_COND(!begun);
  267. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV));
  268. format |= Mesh::ARRAY_FORMAT_TEX_UV;
  269. last_uv = p_uv;
  270. }
  271. void SurfaceTool::set_uv2(const Vector2 &p_uv2) {
  272. ERR_FAIL_COND(!begun);
  273. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV2));
  274. format |= Mesh::ARRAY_FORMAT_TEX_UV2;
  275. last_uv2 = p_uv2;
  276. }
  277. void SurfaceTool::set_custom(int p_channel_index, const Color &p_custom) {
  278. ERR_FAIL_INDEX(p_channel_index, RS::ARRAY_CUSTOM_COUNT);
  279. ERR_FAIL_COND(!begun);
  280. ERR_FAIL_COND(last_custom_format[p_channel_index] == CUSTOM_MAX);
  281. static const uint32_t mask[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0, Mesh::ARRAY_FORMAT_CUSTOM1, Mesh::ARRAY_FORMAT_CUSTOM2, Mesh::ARRAY_FORMAT_CUSTOM3 };
  282. ERR_FAIL_COND(!first && !(format & mask[p_channel_index]));
  283. if (first) {
  284. format |= mask[p_channel_index];
  285. }
  286. last_custom[p_channel_index] = p_custom;
  287. }
  288. void SurfaceTool::set_bones(const Vector<int> &p_bones) {
  289. ERR_FAIL_COND(!begun);
  290. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_BONES));
  291. format |= Mesh::ARRAY_FORMAT_BONES;
  292. if (skin_weights == SKIN_8_WEIGHTS) {
  293. format |= Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  294. }
  295. last_bones = p_bones;
  296. }
  297. void SurfaceTool::set_weights(const Vector<float> &p_weights) {
  298. ERR_FAIL_COND(!begun);
  299. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_WEIGHTS));
  300. format |= Mesh::ARRAY_FORMAT_WEIGHTS;
  301. if (skin_weights == SKIN_8_WEIGHTS) {
  302. format |= Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  303. }
  304. last_weights = p_weights;
  305. }
  306. void SurfaceTool::set_smooth_group(uint32_t p_group) {
  307. last_smooth_group = p_group;
  308. }
  309. void SurfaceTool::add_triangle_fan(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uvs, const Vector<Color> &p_colors, const Vector<Vector2> &p_uv2s, const Vector<Vector3> &p_normals, const Vector<Plane> &p_tangents) {
  310. ERR_FAIL_COND(!begun);
  311. ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
  312. ERR_FAIL_COND(p_vertices.size() < 3);
  313. #define ADD_POINT(n) \
  314. { \
  315. if (p_colors.size() > n) \
  316. set_color(p_colors[n]); \
  317. if (p_uvs.size() > n) \
  318. set_uv(p_uvs[n]); \
  319. if (p_uv2s.size() > n) \
  320. set_uv2(p_uv2s[n]); \
  321. if (p_normals.size() > n) \
  322. set_normal(p_normals[n]); \
  323. if (p_tangents.size() > n) \
  324. set_tangent(p_tangents[n]); \
  325. add_vertex(p_vertices[n]); \
  326. }
  327. for (int i = 0; i < p_vertices.size() - 2; i++) {
  328. ADD_POINT(0);
  329. ADD_POINT(i + 1);
  330. ADD_POINT(i + 2);
  331. }
  332. #undef ADD_POINT
  333. }
  334. void SurfaceTool::add_index(int p_index) {
  335. ERR_FAIL_COND(!begun);
  336. ERR_FAIL_COND(p_index < 0);
  337. format |= Mesh::ARRAY_FORMAT_INDEX;
  338. index_array.push_back(p_index);
  339. }
  340. Array SurfaceTool::commit_to_arrays() {
  341. int varr_len = vertex_array.size();
  342. Array a;
  343. a.resize(Mesh::ARRAY_MAX);
  344. for (int i = 0; i < Mesh::ARRAY_MAX; i++) {
  345. if (!(format & (1 << i))) {
  346. continue; //not in format
  347. }
  348. switch (i) {
  349. case Mesh::ARRAY_VERTEX:
  350. case Mesh::ARRAY_NORMAL: {
  351. Vector<Vector3> array;
  352. array.resize(varr_len);
  353. Vector3 *w = array.ptrw();
  354. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  355. const Vertex &v = vertex_array[idx];
  356. switch (i) {
  357. case Mesh::ARRAY_VERTEX: {
  358. w[idx] = v.vertex;
  359. } break;
  360. case Mesh::ARRAY_NORMAL: {
  361. w[idx] = v.normal;
  362. } break;
  363. }
  364. }
  365. a[i] = array;
  366. } break;
  367. case Mesh::ARRAY_TEX_UV:
  368. case Mesh::ARRAY_TEX_UV2: {
  369. Vector<Vector2> array;
  370. array.resize(varr_len);
  371. Vector2 *w = array.ptrw();
  372. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  373. const Vertex &v = vertex_array[idx];
  374. switch (i) {
  375. case Mesh::ARRAY_TEX_UV: {
  376. w[idx] = v.uv;
  377. } break;
  378. case Mesh::ARRAY_TEX_UV2: {
  379. w[idx] = v.uv2;
  380. } break;
  381. }
  382. }
  383. a[i] = array;
  384. } break;
  385. case Mesh::ARRAY_TANGENT: {
  386. Vector<float> array;
  387. array.resize(varr_len * 4);
  388. float *w = array.ptrw();
  389. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  390. const Vertex &v = vertex_array[idx];
  391. w[idx * 4 + 0] = v.tangent.x;
  392. w[idx * 4 + 1] = v.tangent.y;
  393. w[idx * 4 + 2] = v.tangent.z;
  394. //float d = v.tangent.dot(v.binormal,v.normal);
  395. float d = v.binormal.dot(v.normal.cross(v.tangent));
  396. w[idx * 4 + 3] = d < 0 ? -1 : 1;
  397. }
  398. a[i] = array;
  399. } break;
  400. case Mesh::ARRAY_COLOR: {
  401. Vector<Color> array;
  402. array.resize(varr_len);
  403. Color *w = array.ptrw();
  404. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  405. const Vertex &v = vertex_array[idx];
  406. w[idx] = v.color;
  407. }
  408. a[i] = array;
  409. } break;
  410. case Mesh::ARRAY_CUSTOM0:
  411. case Mesh::ARRAY_CUSTOM1:
  412. case Mesh::ARRAY_CUSTOM2:
  413. case Mesh::ARRAY_CUSTOM3: {
  414. int fmt = i - Mesh::ARRAY_CUSTOM0;
  415. switch (last_custom_format[fmt]) {
  416. case CUSTOM_RGBA8_UNORM: {
  417. Vector<uint8_t> array;
  418. array.resize(varr_len * 4);
  419. uint8_t *w = array.ptrw();
  420. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  421. const Vertex &v = vertex_array[idx];
  422. const Color &c = v.custom[fmt];
  423. w[idx * 4 + 0] = CLAMP(int32_t(c.r * 255.0), 0, 255);
  424. w[idx * 4 + 1] = CLAMP(int32_t(c.g * 255.0), 0, 255);
  425. w[idx * 4 + 2] = CLAMP(int32_t(c.b * 255.0), 0, 255);
  426. w[idx * 4 + 3] = CLAMP(int32_t(c.a * 255.0), 0, 255);
  427. }
  428. a[i] = array;
  429. } break;
  430. case CUSTOM_RGBA8_SNORM: {
  431. Vector<uint8_t> array;
  432. array.resize(varr_len * 4);
  433. uint8_t *w = array.ptrw();
  434. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  435. const Vertex &v = vertex_array[idx];
  436. const Color &c = v.custom[fmt];
  437. w[idx * 4 + 0] = uint8_t(int8_t(CLAMP(int32_t(c.r * 127.0), -128, 127)));
  438. w[idx * 4 + 1] = uint8_t(int8_t(CLAMP(int32_t(c.g * 127.0), -128, 127)));
  439. w[idx * 4 + 2] = uint8_t(int8_t(CLAMP(int32_t(c.b * 127.0), -128, 127)));
  440. w[idx * 4 + 3] = uint8_t(int8_t(CLAMP(int32_t(c.a * 127.0), -128, 127)));
  441. }
  442. a[i] = array;
  443. } break;
  444. case CUSTOM_RG_HALF: {
  445. Vector<uint8_t> array;
  446. array.resize(varr_len * 4);
  447. uint16_t *w = (uint16_t *)array.ptrw();
  448. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  449. const Vertex &v = vertex_array[idx];
  450. const Color &c = v.custom[fmt];
  451. w[idx * 2 + 0] = Math::make_half_float(c.r);
  452. w[idx * 2 + 1] = Math::make_half_float(c.g);
  453. }
  454. a[i] = array;
  455. } break;
  456. case CUSTOM_RGBA_HALF: {
  457. Vector<uint8_t> array;
  458. array.resize(varr_len * 8);
  459. uint16_t *w = (uint16_t *)array.ptrw();
  460. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  461. const Vertex &v = vertex_array[idx];
  462. const Color &c = v.custom[fmt];
  463. w[idx * 4 + 0] = Math::make_half_float(c.r);
  464. w[idx * 4 + 1] = Math::make_half_float(c.g);
  465. w[idx * 4 + 2] = Math::make_half_float(c.b);
  466. w[idx * 4 + 3] = Math::make_half_float(c.a);
  467. }
  468. a[i] = array;
  469. } break;
  470. case CUSTOM_R_FLOAT: {
  471. Vector<float> array;
  472. array.resize(varr_len);
  473. float *w = (float *)array.ptrw();
  474. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  475. const Vertex &v = vertex_array[idx];
  476. const Color &c = v.custom[fmt];
  477. w[idx] = c.r;
  478. }
  479. a[i] = array;
  480. } break;
  481. case CUSTOM_RG_FLOAT: {
  482. Vector<float> array;
  483. array.resize(varr_len * 2);
  484. float *w = (float *)array.ptrw();
  485. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  486. const Vertex &v = vertex_array[idx];
  487. const Color &c = v.custom[fmt];
  488. w[idx * 2 + 0] = c.r;
  489. w[idx * 2 + 1] = c.g;
  490. }
  491. a[i] = array;
  492. } break;
  493. case CUSTOM_RGB_FLOAT: {
  494. Vector<float> array;
  495. array.resize(varr_len * 3);
  496. float *w = (float *)array.ptrw();
  497. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  498. const Vertex &v = vertex_array[idx];
  499. const Color &c = v.custom[fmt];
  500. w[idx * 3 + 0] = c.r;
  501. w[idx * 3 + 1] = c.g;
  502. w[idx * 3 + 2] = c.b;
  503. }
  504. a[i] = array;
  505. } break;
  506. case CUSTOM_RGBA_FLOAT: {
  507. Vector<float> array;
  508. array.resize(varr_len * 4);
  509. float *w = (float *)array.ptrw();
  510. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  511. const Vertex &v = vertex_array[idx];
  512. const Color &c = v.custom[fmt];
  513. w[idx * 4 + 0] = c.r;
  514. w[idx * 4 + 1] = c.g;
  515. w[idx * 4 + 2] = c.b;
  516. w[idx * 4 + 3] = c.a;
  517. }
  518. a[i] = array;
  519. } break;
  520. default: {
  521. } //unreachable but compiler warning anyway
  522. }
  523. } break;
  524. case Mesh::ARRAY_BONES: {
  525. int count = skin_weights == SKIN_8_WEIGHTS ? 8 : 4;
  526. Vector<int> array;
  527. array.resize(varr_len * count);
  528. array.fill(0);
  529. int *w = array.ptrw();
  530. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  531. const Vertex &v = vertex_array[idx];
  532. if (v.bones.size() != count) {
  533. ERR_PRINT_ONCE(vformat("Invalid bones size %d vs count %d", v.bones.size(), count));
  534. continue;
  535. }
  536. for (int j = 0; j < count; j++) {
  537. w[idx * count + j] = v.bones[j];
  538. }
  539. }
  540. a[i] = array;
  541. } break;
  542. case Mesh::ARRAY_WEIGHTS: {
  543. Vector<float> array;
  544. int count = skin_weights == SKIN_8_WEIGHTS ? 8 : 4;
  545. array.resize(varr_len * count);
  546. array.fill(0.0f);
  547. float *w = array.ptrw();
  548. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  549. const Vertex &v = vertex_array[idx];
  550. if (v.weights.size() != count) {
  551. ERR_PRINT_ONCE(vformat("Invalid weight size %d vs count %d", v.weights.size(), count));
  552. continue;
  553. }
  554. for (int j = 0; j < count; j++) {
  555. w[idx * count + j] = v.weights[j];
  556. }
  557. }
  558. a[i] = array;
  559. } break;
  560. case Mesh::ARRAY_INDEX: {
  561. ERR_CONTINUE(index_array.size() == 0);
  562. Vector<int> array;
  563. array.resize(index_array.size());
  564. int *w = array.ptrw();
  565. for (uint32_t idx = 0; idx < index_array.size(); idx++) {
  566. w[idx] = index_array[idx];
  567. }
  568. a[i] = array;
  569. } break;
  570. default: {
  571. }
  572. }
  573. }
  574. return a;
  575. }
  576. Ref<ArrayMesh> SurfaceTool::commit(const Ref<ArrayMesh> &p_existing, uint32_t p_compress_flags) {
  577. Ref<ArrayMesh> mesh;
  578. if (p_existing.is_valid()) {
  579. mesh = p_existing;
  580. } else {
  581. mesh.instantiate();
  582. }
  583. int varr_len = vertex_array.size();
  584. if (varr_len == 0) {
  585. return mesh;
  586. }
  587. int surface = mesh->get_surface_count();
  588. Array a = commit_to_arrays();
  589. uint32_t compress_flags = (p_compress_flags >> RS::ARRAY_COMPRESS_FLAGS_BASE) << RS::ARRAY_COMPRESS_FLAGS_BASE;
  590. static const uint32_t shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };
  591. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  592. if (last_custom_format[i] != CUSTOM_MAX) {
  593. compress_flags |= last_custom_format[i] << shift[i];
  594. }
  595. }
  596. mesh->add_surface_from_arrays(primitive, a, Array(), Dictionary(), compress_flags);
  597. if (material.is_valid()) {
  598. mesh->surface_set_material(surface, material);
  599. }
  600. return mesh;
  601. }
  602. void SurfaceTool::index() {
  603. if (index_array.size()) {
  604. return; //already indexed
  605. }
  606. HashMap<Vertex, int, VertexHasher> indices;
  607. LocalVector<Vertex> old_vertex_array = vertex_array;
  608. vertex_array.clear();
  609. for (const Vertex &vertex : old_vertex_array) {
  610. int *idxptr = indices.getptr(vertex);
  611. int idx;
  612. if (!idxptr) {
  613. idx = indices.size();
  614. vertex_array.push_back(vertex);
  615. indices[vertex] = idx;
  616. } else {
  617. idx = *idxptr;
  618. }
  619. index_array.push_back(idx);
  620. }
  621. format |= Mesh::ARRAY_FORMAT_INDEX;
  622. }
  623. void SurfaceTool::deindex() {
  624. if (index_array.size() == 0) {
  625. return; //nothing to deindex
  626. }
  627. LocalVector<Vertex> old_vertex_array = vertex_array;
  628. vertex_array.clear();
  629. for (const int &index : index_array) {
  630. ERR_FAIL_COND(uint32_t(index) >= old_vertex_array.size());
  631. vertex_array.push_back(old_vertex_array[index]);
  632. }
  633. format &= ~Mesh::ARRAY_FORMAT_INDEX;
  634. index_array.clear();
  635. }
  636. void SurfaceTool::_create_list(const Ref<Mesh> &p_existing, int p_surface, LocalVector<Vertex> *r_vertex, LocalVector<int> *r_index, uint32_t &lformat) {
  637. ERR_FAIL_NULL_MSG(p_existing, "First argument in SurfaceTool::_create_list() must be a valid object of type Mesh");
  638. Array arr = p_existing->surface_get_arrays(p_surface);
  639. ERR_FAIL_COND(arr.size() != RS::ARRAY_MAX);
  640. _create_list_from_arrays(arr, r_vertex, r_index, lformat);
  641. }
  642. static const uint32_t custom_mask[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0, Mesh::ARRAY_FORMAT_CUSTOM1, Mesh::ARRAY_FORMAT_CUSTOM2, Mesh::ARRAY_FORMAT_CUSTOM3 };
  643. static const uint32_t custom_shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };
  644. void SurfaceTool::create_vertex_array_from_triangle_arrays(const Array &p_arrays, LocalVector<SurfaceTool::Vertex> &ret, uint32_t *r_format) {
  645. ret.clear();
  646. Vector<Vector3> varr = p_arrays[RS::ARRAY_VERTEX];
  647. Vector<Vector3> narr = p_arrays[RS::ARRAY_NORMAL];
  648. Vector<float> tarr = p_arrays[RS::ARRAY_TANGENT];
  649. Vector<Color> carr = p_arrays[RS::ARRAY_COLOR];
  650. Vector<Vector2> uvarr = p_arrays[RS::ARRAY_TEX_UV];
  651. Vector<Vector2> uv2arr = p_arrays[RS::ARRAY_TEX_UV2];
  652. Vector<int> barr = p_arrays[RS::ARRAY_BONES];
  653. Vector<float> warr = p_arrays[RS::ARRAY_WEIGHTS];
  654. Vector<float> custom_float[RS::ARRAY_CUSTOM_COUNT];
  655. int vc = varr.size();
  656. if (vc == 0) {
  657. if (r_format) {
  658. *r_format = 0;
  659. }
  660. return;
  661. }
  662. int lformat = 0;
  663. if (varr.size()) {
  664. lformat |= RS::ARRAY_FORMAT_VERTEX;
  665. }
  666. if (narr.size()) {
  667. lformat |= RS::ARRAY_FORMAT_NORMAL;
  668. }
  669. if (tarr.size()) {
  670. lformat |= RS::ARRAY_FORMAT_TANGENT;
  671. }
  672. if (carr.size()) {
  673. lformat |= RS::ARRAY_FORMAT_COLOR;
  674. }
  675. if (uvarr.size()) {
  676. lformat |= RS::ARRAY_FORMAT_TEX_UV;
  677. }
  678. if (uv2arr.size()) {
  679. lformat |= RS::ARRAY_FORMAT_TEX_UV2;
  680. }
  681. int wcount = 0;
  682. if (barr.size() && warr.size()) {
  683. lformat |= RS::ARRAY_FORMAT_BONES;
  684. lformat |= RS::ARRAY_FORMAT_WEIGHTS;
  685. wcount = barr.size() / varr.size();
  686. if (wcount == 8) {
  687. lformat |= RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  688. }
  689. }
  690. if (warr.size()) {
  691. lformat |= RS::ARRAY_FORMAT_WEIGHTS;
  692. }
  693. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  694. ERR_CONTINUE_MSG(p_arrays[RS::ARRAY_CUSTOM0 + i].get_type() == Variant::PACKED_BYTE_ARRAY, "Extracting Byte/Half formats is not supported");
  695. if (p_arrays[RS::ARRAY_CUSTOM0 + i].get_type() == Variant::PACKED_FLOAT32_ARRAY) {
  696. lformat |= custom_mask[i];
  697. custom_float[i] = p_arrays[RS::ARRAY_CUSTOM0 + i];
  698. int fmt = custom_float[i].size() / varr.size();
  699. if (fmt == 1) {
  700. lformat |= CUSTOM_R_FLOAT << custom_shift[i];
  701. } else if (fmt == 2) {
  702. lformat |= CUSTOM_RG_FLOAT << custom_shift[i];
  703. } else if (fmt == 3) {
  704. lformat |= CUSTOM_RGB_FLOAT << custom_shift[i];
  705. } else if (fmt == 4) {
  706. lformat |= CUSTOM_RGBA_FLOAT << custom_shift[i];
  707. }
  708. }
  709. }
  710. for (int i = 0; i < vc; i++) {
  711. Vertex v;
  712. if (lformat & RS::ARRAY_FORMAT_VERTEX) {
  713. v.vertex = varr[i];
  714. }
  715. if (lformat & RS::ARRAY_FORMAT_NORMAL) {
  716. v.normal = narr[i];
  717. }
  718. if (lformat & RS::ARRAY_FORMAT_TANGENT) {
  719. Plane p(tarr[i * 4 + 0], tarr[i * 4 + 1], tarr[i * 4 + 2], tarr[i * 4 + 3]);
  720. v.tangent = p.normal;
  721. v.binormal = p.normal.cross(v.tangent).normalized() * p.d;
  722. }
  723. if (lformat & RS::ARRAY_FORMAT_COLOR) {
  724. v.color = carr[i];
  725. }
  726. if (lformat & RS::ARRAY_FORMAT_TEX_UV) {
  727. v.uv = uvarr[i];
  728. }
  729. if (lformat & RS::ARRAY_FORMAT_TEX_UV2) {
  730. v.uv2 = uv2arr[i];
  731. }
  732. if (lformat & RS::ARRAY_FORMAT_BONES) {
  733. Vector<int> b;
  734. b.resize(wcount);
  735. for (int j = 0; j < wcount; j++) {
  736. b.write[j] = barr[i * wcount + j];
  737. }
  738. v.bones = b;
  739. }
  740. if (lformat & RS::ARRAY_FORMAT_WEIGHTS) {
  741. Vector<float> w;
  742. w.resize(wcount);
  743. for (int j = 0; j < wcount; j++) {
  744. w.write[j] = warr[i * wcount + j];
  745. }
  746. v.weights = w;
  747. }
  748. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  749. if (lformat & custom_mask[j]) {
  750. int cc = custom_float[j].size() / varr.size();
  751. for (int k = 0; k < cc; k++) {
  752. v.custom[j][k] = custom_float[j][i * cc + k];
  753. }
  754. }
  755. }
  756. ret.push_back(v);
  757. }
  758. if (r_format) {
  759. *r_format = lformat;
  760. }
  761. }
  762. void SurfaceTool::_create_list_from_arrays(Array arr, LocalVector<Vertex> *r_vertex, LocalVector<int> *r_index, uint32_t &lformat) {
  763. create_vertex_array_from_triangle_arrays(arr, *r_vertex, &lformat);
  764. ERR_FAIL_COND(r_vertex->size() == 0);
  765. //indices
  766. r_index->clear();
  767. Vector<int> idx = arr[RS::ARRAY_INDEX];
  768. int is = idx.size();
  769. if (is) {
  770. lformat |= RS::ARRAY_FORMAT_INDEX;
  771. const int *iarr = idx.ptr();
  772. for (int i = 0; i < is; i++) {
  773. r_index->push_back(iarr[i]);
  774. }
  775. }
  776. }
  777. void SurfaceTool::create_from_triangle_arrays(const Array &p_arrays) {
  778. clear();
  779. primitive = Mesh::PRIMITIVE_TRIANGLES;
  780. _create_list_from_arrays(p_arrays, &vertex_array, &index_array, format);
  781. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  782. if (format & custom_mask[j]) {
  783. last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  784. }
  785. }
  786. }
  787. void SurfaceTool::create_from(const Ref<Mesh> &p_existing, int p_surface) {
  788. ERR_FAIL_NULL_MSG(p_existing, "First argument in SurfaceTool::create_from() must be a valid object of type Mesh");
  789. clear();
  790. primitive = p_existing->surface_get_primitive_type(p_surface);
  791. _create_list(p_existing, p_surface, &vertex_array, &index_array, format);
  792. material = p_existing->surface_get_material(p_surface);
  793. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  794. if (format & custom_mask[j]) {
  795. last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  796. }
  797. }
  798. }
  799. void SurfaceTool::create_from_blend_shape(const Ref<Mesh> &p_existing, int p_surface, const String &p_blend_shape_name) {
  800. ERR_FAIL_NULL_MSG(p_existing, "First argument in SurfaceTool::create_from_blend_shape() must be a valid object of type Mesh");
  801. clear();
  802. primitive = p_existing->surface_get_primitive_type(p_surface);
  803. Array arr = p_existing->surface_get_blend_shape_arrays(p_surface);
  804. Array blend_shape_names;
  805. int32_t shape_idx = -1;
  806. for (int32_t i = 0; i < p_existing->get_blend_shape_count(); i++) {
  807. String name = p_existing->get_blend_shape_name(i);
  808. if (name == p_blend_shape_name) {
  809. shape_idx = i;
  810. break;
  811. }
  812. }
  813. ERR_FAIL_COND(shape_idx == -1);
  814. ERR_FAIL_COND(shape_idx >= arr.size());
  815. Array mesh = arr[shape_idx];
  816. ERR_FAIL_COND(mesh.size() != RS::ARRAY_MAX);
  817. _create_list_from_arrays(arr[shape_idx], &vertex_array, &index_array, format);
  818. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  819. if (format & custom_mask[j]) {
  820. last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  821. }
  822. }
  823. }
  824. void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const Transform3D &p_xform) {
  825. ERR_FAIL_NULL_MSG(p_existing, "First argument in SurfaceTool::append_from() must be a valid object of type Mesh");
  826. if (vertex_array.size() == 0) {
  827. primitive = p_existing->surface_get_primitive_type(p_surface);
  828. format = 0;
  829. }
  830. uint32_t nformat = 0;
  831. LocalVector<Vertex> nvertices;
  832. LocalVector<int> nindices;
  833. _create_list(p_existing, p_surface, &nvertices, &nindices, nformat);
  834. format |= nformat;
  835. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  836. if (format & custom_mask[j]) {
  837. CustomFormat new_format = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  838. last_custom_format[j] = new_format;
  839. }
  840. }
  841. int vfrom = vertex_array.size();
  842. for (Vertex &v : nvertices) {
  843. v.vertex = p_xform.xform(v.vertex);
  844. if (nformat & RS::ARRAY_FORMAT_NORMAL) {
  845. v.normal = p_xform.basis.xform(v.normal);
  846. }
  847. if (nformat & RS::ARRAY_FORMAT_TANGENT) {
  848. v.tangent = p_xform.basis.xform(v.tangent);
  849. v.binormal = p_xform.basis.xform(v.binormal);
  850. }
  851. vertex_array.push_back(v);
  852. }
  853. for (const int &index : nindices) {
  854. int dst_index = index + vfrom;
  855. index_array.push_back(dst_index);
  856. }
  857. if (index_array.size() % 3) {
  858. WARN_PRINT("SurfaceTool: Index array not a multiple of 3.");
  859. }
  860. }
  861. //mikktspace callbacks
  862. namespace {
  863. struct TangentGenerationContextUserData {
  864. LocalVector<SurfaceTool::Vertex> *vertices;
  865. LocalVector<int> *indices;
  866. };
  867. } // namespace
  868. int SurfaceTool::mikktGetNumFaces(const SMikkTSpaceContext *pContext) {
  869. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  870. if (triangle_data.indices->size() > 0) {
  871. return triangle_data.indices->size() / 3;
  872. } else {
  873. return triangle_data.vertices->size() / 3;
  874. }
  875. }
  876. int SurfaceTool::mikktGetNumVerticesOfFace(const SMikkTSpaceContext *pContext, const int iFace) {
  877. return 3; //always 3
  878. }
  879. void SurfaceTool::mikktGetPosition(const SMikkTSpaceContext *pContext, float fvPosOut[], const int iFace, const int iVert) {
  880. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  881. Vector3 v;
  882. if (triangle_data.indices->size() > 0) {
  883. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  884. if (index < triangle_data.vertices->size()) {
  885. v = triangle_data.vertices->operator[](index).vertex;
  886. }
  887. } else {
  888. v = triangle_data.vertices->operator[](iFace * 3 + iVert).vertex;
  889. }
  890. fvPosOut[0] = v.x;
  891. fvPosOut[1] = v.y;
  892. fvPosOut[2] = v.z;
  893. }
  894. void SurfaceTool::mikktGetNormal(const SMikkTSpaceContext *pContext, float fvNormOut[], const int iFace, const int iVert) {
  895. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  896. Vector3 v;
  897. if (triangle_data.indices->size() > 0) {
  898. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  899. if (index < triangle_data.vertices->size()) {
  900. v = triangle_data.vertices->operator[](index).normal;
  901. }
  902. } else {
  903. v = triangle_data.vertices->operator[](iFace * 3 + iVert).normal;
  904. }
  905. fvNormOut[0] = v.x;
  906. fvNormOut[1] = v.y;
  907. fvNormOut[2] = v.z;
  908. }
  909. void SurfaceTool::mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTexcOut[], const int iFace, const int iVert) {
  910. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  911. Vector2 v;
  912. if (triangle_data.indices->size() > 0) {
  913. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  914. if (index < triangle_data.vertices->size()) {
  915. v = triangle_data.vertices->operator[](index).uv;
  916. }
  917. } else {
  918. v = triangle_data.vertices->operator[](iFace * 3 + iVert).uv;
  919. }
  920. fvTexcOut[0] = v.x;
  921. fvTexcOut[1] = v.y;
  922. }
  923. void SurfaceTool::mikktSetTSpaceDefault(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT,
  924. const tbool bIsOrientationPreserving, const int iFace, const int iVert) {
  925. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  926. Vertex *vtx = nullptr;
  927. if (triangle_data.indices->size() > 0) {
  928. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  929. if (index < triangle_data.vertices->size()) {
  930. vtx = &triangle_data.vertices->operator[](index);
  931. }
  932. } else {
  933. vtx = &triangle_data.vertices->operator[](iFace * 3 + iVert);
  934. }
  935. if (vtx != nullptr) {
  936. vtx->tangent = Vector3(fvTangent[0], fvTangent[1], fvTangent[2]);
  937. vtx->binormal = Vector3(-fvBiTangent[0], -fvBiTangent[1], -fvBiTangent[2]); // for some reason these are reversed, something with the coordinate system in Godot
  938. }
  939. }
  940. void SurfaceTool::generate_tangents() {
  941. ERR_FAIL_COND(!(format & Mesh::ARRAY_FORMAT_TEX_UV));
  942. ERR_FAIL_COND(!(format & Mesh::ARRAY_FORMAT_NORMAL));
  943. SMikkTSpaceInterface mkif;
  944. mkif.m_getNormal = mikktGetNormal;
  945. mkif.m_getNumFaces = mikktGetNumFaces;
  946. mkif.m_getNumVerticesOfFace = mikktGetNumVerticesOfFace;
  947. mkif.m_getPosition = mikktGetPosition;
  948. mkif.m_getTexCoord = mikktGetTexCoord;
  949. mkif.m_setTSpace = mikktSetTSpaceDefault;
  950. mkif.m_setTSpaceBasic = nullptr;
  951. SMikkTSpaceContext msc;
  952. msc.m_pInterface = &mkif;
  953. TangentGenerationContextUserData triangle_data;
  954. triangle_data.vertices = &vertex_array;
  955. for (Vertex &vertex : vertex_array) {
  956. vertex.binormal = Vector3();
  957. vertex.tangent = Vector3();
  958. }
  959. triangle_data.indices = &index_array;
  960. msc.m_pUserData = &triangle_data;
  961. bool res = genTangSpaceDefault(&msc);
  962. ERR_FAIL_COND(!res);
  963. format |= Mesh::ARRAY_FORMAT_TANGENT;
  964. }
  965. void SurfaceTool::generate_normals(bool p_flip) {
  966. ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
  967. bool was_indexed = index_array.size();
  968. deindex();
  969. ERR_FAIL_COND((vertex_array.size() % 3) != 0);
  970. HashMap<SmoothGroupVertex, Vector3, SmoothGroupVertexHasher> smooth_hash;
  971. for (uint32_t vi = 0; vi < vertex_array.size(); vi += 3) {
  972. Vertex *v = &vertex_array[vi];
  973. Vector3 normal;
  974. if (!p_flip) {
  975. normal = Plane(v[0].vertex, v[1].vertex, v[2].vertex).normal;
  976. } else {
  977. normal = Plane(v[2].vertex, v[1].vertex, v[0].vertex).normal;
  978. }
  979. for (int i = 0; i < 3; i++) {
  980. // Add face normal to smooth vertex influence if vertex is member of a smoothing group
  981. if (v[i].smooth_group != UINT32_MAX) {
  982. Vector3 *lv = smooth_hash.getptr(v[i]);
  983. if (!lv) {
  984. smooth_hash.insert(v[i], normal);
  985. } else {
  986. (*lv) += normal;
  987. }
  988. } else {
  989. v[i].normal = normal;
  990. }
  991. }
  992. }
  993. for (Vertex &vertex : vertex_array) {
  994. if (vertex.smooth_group != UINT32_MAX) {
  995. Vector3 *lv = smooth_hash.getptr(vertex);
  996. if (!lv) {
  997. vertex.normal = Vector3();
  998. } else {
  999. vertex.normal = lv->normalized();
  1000. }
  1001. }
  1002. }
  1003. format |= Mesh::ARRAY_FORMAT_NORMAL;
  1004. if (was_indexed) {
  1005. index();
  1006. }
  1007. }
  1008. void SurfaceTool::set_material(const Ref<Material> &p_material) {
  1009. material = p_material;
  1010. }
  1011. Ref<Material> SurfaceTool::get_material() const {
  1012. return material;
  1013. }
  1014. void SurfaceTool::clear() {
  1015. begun = false;
  1016. primitive = Mesh::PRIMITIVE_LINES;
  1017. format = 0;
  1018. last_bones.clear();
  1019. last_weights.clear();
  1020. index_array.clear();
  1021. vertex_array.clear();
  1022. material.unref();
  1023. last_smooth_group = 0;
  1024. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  1025. last_custom_format[i] = CUSTOM_MAX;
  1026. }
  1027. skin_weights = SKIN_4_WEIGHTS;
  1028. }
  1029. void SurfaceTool::set_skin_weight_count(SkinWeightCount p_weights) {
  1030. ERR_FAIL_COND(begun);
  1031. skin_weights = p_weights;
  1032. }
  1033. SurfaceTool::SkinWeightCount SurfaceTool::get_skin_weight_count() const {
  1034. return skin_weights;
  1035. }
  1036. void SurfaceTool::set_custom_format(int p_channel_index, CustomFormat p_format) {
  1037. ERR_FAIL_INDEX(p_channel_index, RS::ARRAY_CUSTOM_COUNT);
  1038. ERR_FAIL_COND(!begun);
  1039. ERR_FAIL_INDEX(p_format, CUSTOM_MAX + 1);
  1040. last_custom_format[p_channel_index] = p_format;
  1041. }
  1042. Mesh::PrimitiveType SurfaceTool::get_primitive_type() const {
  1043. return primitive;
  1044. }
  1045. SurfaceTool::CustomFormat SurfaceTool::get_custom_format(int p_channel_index) const {
  1046. ERR_FAIL_INDEX_V(p_channel_index, RS::ARRAY_CUSTOM_COUNT, CUSTOM_MAX);
  1047. return last_custom_format[p_channel_index];
  1048. }
  1049. void SurfaceTool::optimize_indices_for_cache() {
  1050. ERR_FAIL_COND(optimize_vertex_cache_func == nullptr);
  1051. ERR_FAIL_COND(index_array.size() == 0);
  1052. ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
  1053. ERR_FAIL_COND(index_array.size() % 3 != 0);
  1054. LocalVector old_index_array = index_array;
  1055. memset(index_array.ptr(), 0, index_array.size() * sizeof(int));
  1056. optimize_vertex_cache_func((unsigned int *)index_array.ptr(), (unsigned int *)old_index_array.ptr(), old_index_array.size(), vertex_array.size());
  1057. }
  1058. AABB SurfaceTool::get_aabb() const {
  1059. ERR_FAIL_COND_V(vertex_array.size() == 0, AABB());
  1060. AABB aabb;
  1061. for (uint32_t i = 0; i < vertex_array.size(); i++) {
  1062. if (i == 0) {
  1063. aabb.position = vertex_array[i].vertex;
  1064. } else {
  1065. aabb.expand_to(vertex_array[i].vertex);
  1066. }
  1067. }
  1068. return aabb;
  1069. }
  1070. Vector<int> SurfaceTool::generate_lod(float p_threshold, int p_target_index_count) {
  1071. Vector<int> lod;
  1072. ERR_FAIL_COND_V(simplify_func == nullptr, lod);
  1073. ERR_FAIL_COND_V(p_target_index_count < 0, lod);
  1074. ERR_FAIL_COND_V(vertex_array.size() == 0, lod);
  1075. ERR_FAIL_COND_V(index_array.size() == 0, lod);
  1076. ERR_FAIL_COND_V(index_array.size() % 3 != 0, lod);
  1077. ERR_FAIL_COND_V(index_array.size() < (unsigned int)p_target_index_count, lod);
  1078. lod.resize(index_array.size());
  1079. LocalVector<float> vertices; //uses floats
  1080. vertices.resize(vertex_array.size() * 3);
  1081. for (uint32_t i = 0; i < vertex_array.size(); i++) {
  1082. vertices[i * 3 + 0] = vertex_array[i].vertex.x;
  1083. vertices[i * 3 + 1] = vertex_array[i].vertex.y;
  1084. vertices[i * 3 + 2] = vertex_array[i].vertex.z;
  1085. }
  1086. float error;
  1087. const int simplify_options = SIMPLIFY_LOCK_BORDER;
  1088. uint32_t index_count = simplify_func((unsigned int *)lod.ptrw(), (unsigned int *)index_array.ptr(), index_array.size(), vertices.ptr(), vertex_array.size(), sizeof(float) * 3, p_target_index_count, p_threshold, simplify_options, &error);
  1089. ERR_FAIL_COND_V(index_count == 0, lod);
  1090. lod.resize(index_count);
  1091. return lod;
  1092. }
  1093. void SurfaceTool::_bind_methods() {
  1094. ClassDB::bind_method(D_METHOD("set_skin_weight_count", "count"), &SurfaceTool::set_skin_weight_count);
  1095. ClassDB::bind_method(D_METHOD("get_skin_weight_count"), &SurfaceTool::get_skin_weight_count);
  1096. ClassDB::bind_method(D_METHOD("set_custom_format", "channel_index", "format"), &SurfaceTool::set_custom_format);
  1097. ClassDB::bind_method(D_METHOD("get_custom_format", "channel_index"), &SurfaceTool::get_custom_format);
  1098. ClassDB::bind_method(D_METHOD("begin", "primitive"), &SurfaceTool::begin);
  1099. ClassDB::bind_method(D_METHOD("add_vertex", "vertex"), &SurfaceTool::add_vertex);
  1100. ClassDB::bind_method(D_METHOD("set_color", "color"), &SurfaceTool::set_color);
  1101. ClassDB::bind_method(D_METHOD("set_normal", "normal"), &SurfaceTool::set_normal);
  1102. ClassDB::bind_method(D_METHOD("set_tangent", "tangent"), &SurfaceTool::set_tangent);
  1103. ClassDB::bind_method(D_METHOD("set_uv", "uv"), &SurfaceTool::set_uv);
  1104. ClassDB::bind_method(D_METHOD("set_uv2", "uv2"), &SurfaceTool::set_uv2);
  1105. ClassDB::bind_method(D_METHOD("set_bones", "bones"), &SurfaceTool::set_bones);
  1106. ClassDB::bind_method(D_METHOD("set_weights", "weights"), &SurfaceTool::set_weights);
  1107. ClassDB::bind_method(D_METHOD("set_custom", "channel_index", "custom_color"), &SurfaceTool::set_custom);
  1108. ClassDB::bind_method(D_METHOD("set_smooth_group", "index"), &SurfaceTool::set_smooth_group);
  1109. ClassDB::bind_method(D_METHOD("add_triangle_fan", "vertices", "uvs", "colors", "uv2s", "normals", "tangents"), &SurfaceTool::add_triangle_fan, DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Color>()), DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Vector3>()), DEFVAL(Vector<Plane>()));
  1110. ClassDB::bind_method(D_METHOD("add_index", "index"), &SurfaceTool::add_index);
  1111. ClassDB::bind_method(D_METHOD("index"), &SurfaceTool::index);
  1112. ClassDB::bind_method(D_METHOD("deindex"), &SurfaceTool::deindex);
  1113. ClassDB::bind_method(D_METHOD("generate_normals", "flip"), &SurfaceTool::generate_normals, DEFVAL(false));
  1114. ClassDB::bind_method(D_METHOD("generate_tangents"), &SurfaceTool::generate_tangents);
  1115. ClassDB::bind_method(D_METHOD("optimize_indices_for_cache"), &SurfaceTool::optimize_indices_for_cache);
  1116. ClassDB::bind_method(D_METHOD("get_aabb"), &SurfaceTool::get_aabb);
  1117. ClassDB::bind_method(D_METHOD("generate_lod", "nd_threshold", "target_index_count"), &SurfaceTool::generate_lod, DEFVAL(3));
  1118. ClassDB::bind_method(D_METHOD("set_material", "material"), &SurfaceTool::set_material);
  1119. ClassDB::bind_method(D_METHOD("get_primitive_type"), &SurfaceTool::get_primitive_type);
  1120. ClassDB::bind_method(D_METHOD("clear"), &SurfaceTool::clear);
  1121. ClassDB::bind_method(D_METHOD("create_from", "existing", "surface"), &SurfaceTool::create_from);
  1122. ClassDB::bind_method(D_METHOD("create_from_blend_shape", "existing", "surface", "blend_shape"), &SurfaceTool::create_from_blend_shape);
  1123. ClassDB::bind_method(D_METHOD("append_from", "existing", "surface", "transform"), &SurfaceTool::append_from);
  1124. ClassDB::bind_method(D_METHOD("commit", "existing", "flags"), &SurfaceTool::commit, DEFVAL(Variant()), DEFVAL(0));
  1125. ClassDB::bind_method(D_METHOD("commit_to_arrays"), &SurfaceTool::commit_to_arrays);
  1126. BIND_ENUM_CONSTANT(CUSTOM_RGBA8_UNORM);
  1127. BIND_ENUM_CONSTANT(CUSTOM_RGBA8_SNORM);
  1128. BIND_ENUM_CONSTANT(CUSTOM_RG_HALF);
  1129. BIND_ENUM_CONSTANT(CUSTOM_RGBA_HALF);
  1130. BIND_ENUM_CONSTANT(CUSTOM_R_FLOAT);
  1131. BIND_ENUM_CONSTANT(CUSTOM_RG_FLOAT);
  1132. BIND_ENUM_CONSTANT(CUSTOM_RGB_FLOAT);
  1133. BIND_ENUM_CONSTANT(CUSTOM_RGBA_FLOAT);
  1134. BIND_ENUM_CONSTANT(CUSTOM_MAX);
  1135. BIND_ENUM_CONSTANT(SKIN_4_WEIGHTS);
  1136. BIND_ENUM_CONSTANT(SKIN_8_WEIGHTS);
  1137. }
  1138. SurfaceTool::SurfaceTool() {
  1139. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  1140. last_custom_format[i] = CUSTOM_MAX;
  1141. }
  1142. }