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