surface_tool.cpp 41 KB

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