mesh_instance.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. /**************************************************************************/
  2. /* mesh_instance.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "mesh_instance.h"
  31. #include "collision_shape.h"
  32. #include "core/core_string_names.h"
  33. #include "core/project_settings.h"
  34. #include "physics_body.h"
  35. #include "scene/resources/material.h"
  36. #include "scene/scene_string_names.h"
  37. #include "servers/visual/visual_server_globals.h"
  38. #include "skeleton.h"
  39. bool MeshInstance::_set(const StringName &p_name, const Variant &p_value) {
  40. //this is not _too_ bad performance wise, really. it only arrives here if the property was not set anywhere else.
  41. //add to it that it's probably found on first call to _set anyway.
  42. if (!get_instance().is_valid()) {
  43. return false;
  44. }
  45. Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
  46. if (E) {
  47. E->get().value = p_value;
  48. VisualServer::get_singleton()->instance_set_blend_shape_weight(get_instance(), E->get().idx, E->get().value);
  49. return true;
  50. }
  51. if (p_name.operator String().begins_with("material/")) {
  52. int idx = p_name.operator String().get_slicec('/', 1).to_int();
  53. if (idx >= materials.size() || idx < 0) {
  54. return false;
  55. }
  56. set_surface_material(idx, p_value);
  57. return true;
  58. }
  59. return false;
  60. }
  61. bool MeshInstance::_get(const StringName &p_name, Variant &r_ret) const {
  62. if (!get_instance().is_valid()) {
  63. return false;
  64. }
  65. const Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
  66. if (E) {
  67. r_ret = E->get().value;
  68. return true;
  69. }
  70. if (p_name.operator String().begins_with("material/")) {
  71. int idx = p_name.operator String().get_slicec('/', 1).to_int();
  72. if (idx >= materials.size() || idx < 0) {
  73. return false;
  74. }
  75. r_ret = materials[idx];
  76. return true;
  77. }
  78. return false;
  79. }
  80. void MeshInstance::_get_property_list(List<PropertyInfo> *p_list) const {
  81. List<String> ls;
  82. for (const Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.front(); E; E = E->next()) {
  83. ls.push_back(E->key());
  84. }
  85. ls.sort();
  86. for (List<String>::Element *E = ls.front(); E; E = E->next()) {
  87. p_list->push_back(PropertyInfo(Variant::REAL, E->get(), PROPERTY_HINT_RANGE, "-1,1,0.00001"));
  88. }
  89. if (mesh.is_valid()) {
  90. for (int i = 0; i < mesh->get_surface_count(); i++) {
  91. p_list->push_back(PropertyInfo(Variant::OBJECT, vformat("%s/%d", PNAME("material"), i), PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,SpatialMaterial"));
  92. }
  93. }
  94. }
  95. void MeshInstance::set_mesh(const Ref<Mesh> &p_mesh) {
  96. if (mesh == p_mesh) {
  97. return;
  98. }
  99. if (mesh.is_valid()) {
  100. mesh->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed);
  101. }
  102. if (skin_ref.is_valid() && mesh.is_valid() && _is_software_skinning_enabled() && is_visible_in_tree()) {
  103. ERR_FAIL_COND(!skin_ref->get_skeleton_node());
  104. skin_ref->get_skeleton_node()->disconnect("skeleton_updated", this, "_update_skinning");
  105. }
  106. if (software_skinning) {
  107. memdelete(software_skinning);
  108. software_skinning = nullptr;
  109. }
  110. mesh = p_mesh;
  111. blend_shape_tracks.clear();
  112. if (mesh.is_valid()) {
  113. for (int i = 0; i < mesh->get_blend_shape_count(); i++) {
  114. BlendShapeTrack mt;
  115. mt.idx = i;
  116. mt.value = 0;
  117. blend_shape_tracks["blend_shapes/" + String(mesh->get_blend_shape_name(i))] = mt;
  118. }
  119. mesh->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed);
  120. materials.resize(mesh->get_surface_count());
  121. _initialize_skinning(false, false);
  122. } else {
  123. set_base(RID());
  124. }
  125. update_gizmo();
  126. _change_notify();
  127. }
  128. Ref<Mesh> MeshInstance::get_mesh() const {
  129. return mesh;
  130. }
  131. void MeshInstance::_resolve_skeleton_path() {
  132. Ref<SkinReference> new_skin_reference;
  133. if (!skeleton_path.is_empty()) {
  134. Skeleton *skeleton = Object::cast_to<Skeleton>(get_node(skeleton_path));
  135. if (skeleton) {
  136. new_skin_reference = skeleton->register_skin(skin_internal);
  137. if (skin_internal.is_null()) {
  138. //a skin was created for us
  139. skin_internal = new_skin_reference->get_skin();
  140. _change_notify();
  141. }
  142. }
  143. }
  144. if (skin_ref.is_valid() && mesh.is_valid() && _is_software_skinning_enabled() && is_visible_in_tree()) {
  145. ERR_FAIL_COND(!skin_ref->get_skeleton_node());
  146. skin_ref->get_skeleton_node()->disconnect("skeleton_updated", this, "_update_skinning");
  147. }
  148. skin_ref = new_skin_reference;
  149. software_skinning_flags &= ~SoftwareSkinning::FLAG_BONES_READY;
  150. _initialize_skinning();
  151. }
  152. bool MeshInstance::_is_global_software_skinning_enabled() {
  153. // Check if forced in project settings.
  154. if (GLOBAL_GET("rendering/quality/skinning/force_software_skinning")) {
  155. return true;
  156. }
  157. // Check if enabled in project settings.
  158. if (!GLOBAL_GET("rendering/quality/skinning/software_skinning_fallback")) {
  159. return false;
  160. }
  161. // Check if requested by renderer settings.
  162. return VSG::storage->has_os_feature("skinning_fallback");
  163. }
  164. bool MeshInstance::_is_software_skinning_enabled() const {
  165. // Using static local variable which will be initialized only once,
  166. // so _is_global_software_skinning_enabled can be only called once on first use.
  167. static bool global_software_skinning = _is_global_software_skinning_enabled();
  168. return global_software_skinning;
  169. }
  170. void MeshInstance::_initialize_skinning(bool p_force_reset, bool p_call_attach_skeleton) {
  171. if (mesh.is_null()) {
  172. return;
  173. }
  174. VisualServer *visual_server = VisualServer::get_singleton();
  175. bool update_mesh = false;
  176. if (skin_ref.is_valid()) {
  177. if (_is_software_skinning_enabled()) {
  178. if (is_visible_in_tree()) {
  179. ERR_FAIL_COND(!skin_ref->get_skeleton_node());
  180. if (!skin_ref->get_skeleton_node()->is_connected("skeleton_updated", this, "_update_skinning")) {
  181. skin_ref->get_skeleton_node()->connect("skeleton_updated", this, "_update_skinning");
  182. }
  183. }
  184. if (p_force_reset && software_skinning) {
  185. memdelete(software_skinning);
  186. software_skinning = nullptr;
  187. }
  188. if (!software_skinning) {
  189. software_skinning = memnew(SoftwareSkinning);
  190. if (mesh->get_blend_shape_count() > 0) {
  191. ERR_PRINT("Blend shapes are not supported for software skinning.");
  192. }
  193. Ref<ArrayMesh> software_mesh;
  194. software_mesh.instance();
  195. RID mesh_rid = software_mesh->get_rid();
  196. // Initialize mesh for dynamic update.
  197. int surface_count = mesh->get_surface_count();
  198. software_skinning->surface_data.resize(surface_count);
  199. for (int surface_index = 0; surface_index < surface_count; ++surface_index) {
  200. ERR_CONTINUE(Mesh::PRIMITIVE_TRIANGLES != mesh->surface_get_primitive_type(surface_index));
  201. SoftwareSkinning::SurfaceData &surface_data = software_skinning->surface_data[surface_index];
  202. surface_data.transform_tangents = false;
  203. surface_data.ensure_correct_normals = false;
  204. uint32_t format = mesh->surface_get_format(surface_index);
  205. ERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_VERTEX));
  206. ERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_BONES));
  207. ERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_WEIGHTS));
  208. format |= Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE;
  209. format &= ~Mesh::ARRAY_COMPRESS_VERTEX;
  210. format &= ~Mesh::ARRAY_COMPRESS_WEIGHTS;
  211. format &= ~Mesh::ARRAY_FLAG_USE_16_BIT_BONES;
  212. Array write_arrays = mesh->surface_get_arrays(surface_index);
  213. Array read_arrays;
  214. read_arrays.resize(Mesh::ARRAY_MAX);
  215. read_arrays[Mesh::ARRAY_VERTEX] = write_arrays[Mesh::ARRAY_VERTEX];
  216. read_arrays[Mesh::ARRAY_BONES] = write_arrays[Mesh::ARRAY_BONES];
  217. read_arrays[Mesh::ARRAY_WEIGHTS] = write_arrays[Mesh::ARRAY_WEIGHTS];
  218. write_arrays[Mesh::ARRAY_BONES] = Variant();
  219. write_arrays[Mesh::ARRAY_WEIGHTS] = Variant();
  220. if (software_skinning_flags & SoftwareSkinning::FLAG_TRANSFORM_NORMALS) {
  221. ERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_NORMAL));
  222. format &= ~Mesh::ARRAY_COMPRESS_NORMAL;
  223. read_arrays[Mesh::ARRAY_NORMAL] = write_arrays[Mesh::ARRAY_NORMAL];
  224. Ref<Material> mat = get_active_material(surface_index);
  225. if (mat.is_valid()) {
  226. Ref<SpatialMaterial> spatial_mat = mat;
  227. if (spatial_mat.is_valid()) {
  228. // Spatial material, check from material settings.
  229. surface_data.transform_tangents = spatial_mat->get_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING);
  230. surface_data.ensure_correct_normals = spatial_mat->get_flag(SpatialMaterial::FLAG_ENSURE_CORRECT_NORMALS);
  231. } else {
  232. // Custom shader, must check for compiled flags.
  233. surface_data.transform_tangents = VSG::storage->material_uses_tangents(mat->get_rid());
  234. surface_data.ensure_correct_normals = VSG::storage->material_uses_ensure_correct_normals(mat->get_rid());
  235. }
  236. }
  237. if (surface_data.transform_tangents) {
  238. ERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_TANGENT));
  239. format &= ~Mesh::ARRAY_COMPRESS_TANGENT;
  240. read_arrays[Mesh::ARRAY_TANGENT] = write_arrays[Mesh::ARRAY_TANGENT];
  241. }
  242. }
  243. // 1. Temporarily add surface with bone data to create the read buffer.
  244. software_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, read_arrays, Array(), format);
  245. PoolByteArray buffer_read = visual_server->mesh_surface_get_array(mesh_rid, surface_index);
  246. surface_data.source_buffer.append_array(buffer_read);
  247. surface_data.source_format = software_mesh->surface_get_format(surface_index);
  248. software_mesh->surface_remove(surface_index);
  249. // 2. Create the surface again without the bone data for the write buffer.
  250. software_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, write_arrays, Array(), format);
  251. Ref<Material> material = mesh->surface_get_material(surface_index);
  252. software_mesh->surface_set_material(surface_index, material);
  253. surface_data.buffer = visual_server->mesh_surface_get_array(mesh_rid, surface_index);
  254. surface_data.buffer_write = surface_data.buffer.write();
  255. }
  256. software_skinning->mesh_instance = software_mesh;
  257. update_mesh = true;
  258. }
  259. if (p_call_attach_skeleton) {
  260. visual_server->instance_attach_skeleton(get_instance(), RID());
  261. }
  262. if (is_visible_in_tree() && (software_skinning_flags & SoftwareSkinning::FLAG_BONES_READY)) {
  263. // Initialize from current skeleton pose.
  264. _update_skinning();
  265. }
  266. } else {
  267. ERR_FAIL_COND(!skin_ref->get_skeleton_node());
  268. if (skin_ref->get_skeleton_node()->is_connected("skeleton_updated", this, "_update_skinning")) {
  269. skin_ref->get_skeleton_node()->disconnect("skeleton_updated", this, "_update_skinning");
  270. }
  271. if (p_call_attach_skeleton) {
  272. visual_server->instance_attach_skeleton(get_instance(), skin_ref->get_skeleton());
  273. }
  274. if (software_skinning) {
  275. memdelete(software_skinning);
  276. software_skinning = nullptr;
  277. update_mesh = true;
  278. }
  279. }
  280. } else {
  281. if (p_call_attach_skeleton) {
  282. visual_server->instance_attach_skeleton(get_instance(), RID());
  283. }
  284. if (software_skinning) {
  285. memdelete(software_skinning);
  286. software_skinning = nullptr;
  287. update_mesh = true;
  288. }
  289. }
  290. RID render_mesh = software_skinning ? software_skinning->mesh_instance->get_rid() : mesh->get_rid();
  291. if (update_mesh || (render_mesh != get_base())) {
  292. set_base(render_mesh);
  293. // Update instance materials after switching mesh.
  294. int surface_count = mesh->get_surface_count();
  295. for (int surface_index = 0; surface_index < surface_count; ++surface_index) {
  296. if (materials[surface_index].is_valid()) {
  297. visual_server->instance_set_surface_material(get_instance(), surface_index, materials[surface_index]->get_rid());
  298. }
  299. }
  300. }
  301. }
  302. void MeshInstance::_update_skinning() {
  303. ERR_FAIL_COND(!_is_software_skinning_enabled());
  304. #if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED)
  305. ERR_FAIL_COND(!is_visible_in_tree());
  306. #else
  307. ERR_FAIL_COND(!is_visible());
  308. #endif
  309. ERR_FAIL_COND(!software_skinning);
  310. Ref<Mesh> software_skinning_mesh = software_skinning->mesh_instance;
  311. ERR_FAIL_COND(!software_skinning_mesh.is_valid());
  312. RID mesh_rid = software_skinning_mesh->get_rid();
  313. ERR_FAIL_COND(!mesh_rid.is_valid());
  314. ERR_FAIL_COND(!mesh.is_valid());
  315. RID source_mesh_rid = mesh->get_rid();
  316. ERR_FAIL_COND(!source_mesh_rid.is_valid());
  317. ERR_FAIL_COND(skin_ref.is_null());
  318. RID skeleton = skin_ref->get_skeleton();
  319. ERR_FAIL_COND(!skeleton.is_valid());
  320. Vector3 aabb_min = Vector3(FLT_MAX, FLT_MAX, FLT_MAX);
  321. Vector3 aabb_max = Vector3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
  322. VisualServer *visual_server = VisualServer::get_singleton();
  323. // Prepare bone transforms.
  324. const int num_bones = visual_server->skeleton_get_bone_count(skeleton);
  325. ERR_FAIL_COND(num_bones <= 0);
  326. Transform *bone_transforms = (Transform *)alloca(sizeof(Transform) * num_bones);
  327. for (int bone_index = 0; bone_index < num_bones; ++bone_index) {
  328. bone_transforms[bone_index] = visual_server->skeleton_bone_get_transform(skeleton, bone_index);
  329. }
  330. // Apply skinning.
  331. int surface_count = software_skinning_mesh->get_surface_count();
  332. for (int surface_index = 0; surface_index < surface_count; ++surface_index) {
  333. ERR_CONTINUE((uint32_t)surface_index >= software_skinning->surface_data.size());
  334. const SoftwareSkinning::SurfaceData &surface_data = software_skinning->surface_data[surface_index];
  335. const bool transform_tangents = surface_data.transform_tangents;
  336. const bool ensure_correct_normals = surface_data.ensure_correct_normals;
  337. const uint32_t format_write = software_skinning_mesh->surface_get_format(surface_index);
  338. const int vertex_count_write = software_skinning_mesh->surface_get_array_len(surface_index);
  339. const int index_count_write = software_skinning_mesh->surface_get_array_index_len(surface_index);
  340. uint32_t array_offsets_write[Mesh::ARRAY_MAX];
  341. uint32_t array_strides_write[Mesh::ARRAY_MAX];
  342. visual_server->mesh_surface_make_offsets_from_format(format_write, vertex_count_write, index_count_write, array_offsets_write, array_strides_write);
  343. ERR_FAIL_COND(array_strides_write[Mesh::ARRAY_VERTEX] != array_strides_write[Mesh::ARRAY_NORMAL]);
  344. const uint32_t stride_write = array_strides_write[Mesh::ARRAY_VERTEX];
  345. const uint32_t offset_vertices_write = array_offsets_write[Mesh::ARRAY_VERTEX];
  346. const uint32_t offset_normals_write = array_offsets_write[Mesh::ARRAY_NORMAL];
  347. const uint32_t offset_tangents_write = array_offsets_write[Mesh::ARRAY_TANGENT];
  348. PoolByteArray buffer_source = surface_data.source_buffer;
  349. PoolByteArray::Read buffer_read = buffer_source.read();
  350. const uint32_t format_read = surface_data.source_format;
  351. ERR_CONTINUE(0 == (format_read & Mesh::ARRAY_FORMAT_BONES));
  352. ERR_CONTINUE(0 == (format_read & Mesh::ARRAY_FORMAT_WEIGHTS));
  353. const int vertex_count = mesh->surface_get_array_len(surface_index);
  354. const int index_count = mesh->surface_get_array_index_len(surface_index);
  355. ERR_CONTINUE(vertex_count != vertex_count_write);
  356. uint32_t array_offsets[Mesh::ARRAY_MAX];
  357. uint32_t array_strides[Mesh::ARRAY_MAX];
  358. visual_server->mesh_surface_make_offsets_from_format(format_read, vertex_count, index_count, array_offsets, array_strides);
  359. ERR_FAIL_COND(array_strides[Mesh::ARRAY_VERTEX] != array_strides[Mesh::ARRAY_NORMAL]);
  360. const uint32_t stride = array_strides[Mesh::ARRAY_VERTEX];
  361. const uint32_t offset_vertices = array_offsets[Mesh::ARRAY_VERTEX];
  362. const uint32_t offset_normals = array_offsets[Mesh::ARRAY_NORMAL];
  363. const uint32_t offset_tangents = array_offsets[Mesh::ARRAY_TANGENT];
  364. const uint32_t offset_bones = array_offsets[Mesh::ARRAY_BONES];
  365. const uint32_t offset_weights = array_offsets[Mesh::ARRAY_WEIGHTS];
  366. PoolByteArray buffer = surface_data.buffer;
  367. PoolByteArray::Write buffer_write = surface_data.buffer_write;
  368. for (int vertex_index = 0; vertex_index < vertex_count; ++vertex_index) {
  369. const uint32_t vertex_offset = vertex_index * stride;
  370. const uint32_t vertex_offset_write = vertex_index * stride_write;
  371. float bone_weights[4];
  372. const float *weight_ptr = (const float *)(buffer_read.ptr() + offset_weights + vertex_offset);
  373. bone_weights[0] = weight_ptr[0];
  374. bone_weights[1] = weight_ptr[1];
  375. bone_weights[2] = weight_ptr[2];
  376. bone_weights[3] = weight_ptr[3];
  377. const uint8_t *bones_ptr = buffer_read.ptr() + offset_bones + vertex_offset;
  378. const int b0 = bones_ptr[0];
  379. const int b1 = bones_ptr[1];
  380. const int b2 = bones_ptr[2];
  381. const int b3 = bones_ptr[3];
  382. Transform transform;
  383. transform.origin =
  384. bone_weights[0] * bone_transforms[b0].origin +
  385. bone_weights[1] * bone_transforms[b1].origin +
  386. bone_weights[2] * bone_transforms[b2].origin +
  387. bone_weights[3] * bone_transforms[b3].origin;
  388. transform.basis =
  389. bone_transforms[b0].basis * bone_weights[0] +
  390. bone_transforms[b1].basis * bone_weights[1] +
  391. bone_transforms[b2].basis * bone_weights[2] +
  392. bone_transforms[b3].basis * bone_weights[3];
  393. const Vector3 &vertex_read = (const Vector3 &)buffer_read[vertex_offset + offset_vertices];
  394. Vector3 &vertex = (Vector3 &)buffer_write[vertex_offset_write + offset_vertices_write];
  395. vertex = transform.xform(vertex_read);
  396. if (software_skinning_flags & SoftwareSkinning::FLAG_TRANSFORM_NORMALS) {
  397. if (ensure_correct_normals) {
  398. transform.basis.invert();
  399. transform.basis.transpose();
  400. }
  401. const Vector3 &normal_read = (const Vector3 &)buffer_read[vertex_offset + offset_normals];
  402. Vector3 &normal = (Vector3 &)buffer_write[vertex_offset_write + offset_normals_write];
  403. normal = transform.basis.xform(normal_read);
  404. if (transform_tangents) {
  405. const Vector3 &tangent_read = (const Vector3 &)buffer_read[vertex_offset + offset_tangents];
  406. Vector3 &tangent = (Vector3 &)buffer_write[vertex_offset_write + offset_tangents_write];
  407. tangent = transform.basis.xform(tangent_read);
  408. }
  409. }
  410. aabb_min.x = MIN(aabb_min.x, vertex.x);
  411. aabb_min.y = MIN(aabb_min.y, vertex.y);
  412. aabb_min.z = MIN(aabb_min.z, vertex.z);
  413. aabb_max.x = MAX(aabb_max.x, vertex.x);
  414. aabb_max.y = MAX(aabb_max.y, vertex.y);
  415. aabb_max.z = MAX(aabb_max.z, vertex.z);
  416. }
  417. visual_server->mesh_surface_update_region(mesh_rid, surface_index, 0, buffer);
  418. }
  419. visual_server->mesh_set_custom_aabb(mesh_rid, AABB(aabb_min, aabb_max - aabb_min));
  420. software_skinning_flags |= SoftwareSkinning::FLAG_BONES_READY;
  421. }
  422. void MeshInstance::set_skin(const Ref<Skin> &p_skin) {
  423. skin_internal = p_skin;
  424. skin = p_skin;
  425. if (!is_inside_tree()) {
  426. return;
  427. }
  428. _resolve_skeleton_path();
  429. }
  430. Ref<Skin> MeshInstance::get_skin() const {
  431. return skin;
  432. }
  433. void MeshInstance::set_skeleton_path(const NodePath &p_skeleton) {
  434. skeleton_path = p_skeleton;
  435. if (!is_inside_tree()) {
  436. return;
  437. }
  438. _resolve_skeleton_path();
  439. }
  440. NodePath MeshInstance::get_skeleton_path() {
  441. return skeleton_path;
  442. }
  443. AABB MeshInstance::get_aabb() const {
  444. if (!mesh.is_null()) {
  445. return mesh->get_aabb();
  446. }
  447. return AABB();
  448. }
  449. PoolVector<Face3> MeshInstance::get_faces(uint32_t p_usage_flags) const {
  450. if (!(p_usage_flags & (FACES_SOLID | FACES_ENCLOSING))) {
  451. return PoolVector<Face3>();
  452. }
  453. if (mesh.is_null()) {
  454. return PoolVector<Face3>();
  455. }
  456. return mesh->get_faces();
  457. }
  458. Node *MeshInstance::create_trimesh_collision_node() {
  459. if (mesh.is_null()) {
  460. return nullptr;
  461. }
  462. Ref<Shape> shape = mesh->create_trimesh_shape();
  463. if (shape.is_null()) {
  464. return nullptr;
  465. }
  466. StaticBody *static_body = memnew(StaticBody);
  467. CollisionShape *cshape = memnew(CollisionShape);
  468. cshape->set_shape(shape);
  469. static_body->add_child(cshape);
  470. return static_body;
  471. }
  472. void MeshInstance::create_trimesh_collision() {
  473. StaticBody *static_body = Object::cast_to<StaticBody>(create_trimesh_collision_node());
  474. ERR_FAIL_COND(!static_body);
  475. static_body->set_name(String(get_name()) + "_col");
  476. add_child(static_body);
  477. if (get_owner()) {
  478. CollisionShape *cshape = Object::cast_to<CollisionShape>(static_body->get_child(0));
  479. static_body->set_owner(get_owner());
  480. cshape->set_owner(get_owner());
  481. }
  482. }
  483. Node *MeshInstance::create_multiple_convex_collisions_node() {
  484. if (mesh.is_null()) {
  485. return nullptr;
  486. }
  487. Vector<Ref<Shape>> shapes = mesh->convex_decompose();
  488. if (!shapes.size()) {
  489. return nullptr;
  490. }
  491. StaticBody *static_body = memnew(StaticBody);
  492. for (int i = 0; i < shapes.size(); i++) {
  493. CollisionShape *cshape = memnew(CollisionShape);
  494. cshape->set_shape(shapes[i]);
  495. static_body->add_child(cshape);
  496. }
  497. return static_body;
  498. }
  499. void MeshInstance::create_multiple_convex_collisions() {
  500. StaticBody *static_body = Object::cast_to<StaticBody>(create_multiple_convex_collisions_node());
  501. ERR_FAIL_COND(!static_body);
  502. static_body->set_name(String(get_name()) + "_col");
  503. add_child(static_body);
  504. if (get_owner()) {
  505. static_body->set_owner(get_owner());
  506. int count = static_body->get_child_count();
  507. for (int i = 0; i < count; i++) {
  508. CollisionShape *cshape = Object::cast_to<CollisionShape>(static_body->get_child(i));
  509. cshape->set_owner(get_owner());
  510. }
  511. }
  512. }
  513. Node *MeshInstance::create_convex_collision_node(bool p_clean, bool p_simplify) {
  514. if (mesh.is_null()) {
  515. return nullptr;
  516. }
  517. Ref<Shape> shape = mesh->create_convex_shape(p_clean, p_simplify);
  518. if (shape.is_null()) {
  519. return nullptr;
  520. }
  521. StaticBody *static_body = memnew(StaticBody);
  522. CollisionShape *cshape = memnew(CollisionShape);
  523. cshape->set_shape(shape);
  524. static_body->add_child(cshape);
  525. return static_body;
  526. }
  527. void MeshInstance::create_convex_collision(bool p_clean, bool p_simplify) {
  528. StaticBody *static_body = Object::cast_to<StaticBody>(create_convex_collision_node(p_clean, p_simplify));
  529. ERR_FAIL_COND(!static_body);
  530. static_body->set_name(String(get_name()) + "_col");
  531. add_child(static_body);
  532. if (get_owner()) {
  533. CollisionShape *cshape = Object::cast_to<CollisionShape>(static_body->get_child(0));
  534. static_body->set_owner(get_owner());
  535. cshape->set_owner(get_owner());
  536. }
  537. }
  538. void MeshInstance::_notification(int p_what) {
  539. if (p_what == NOTIFICATION_ENTER_TREE) {
  540. _resolve_skeleton_path();
  541. }
  542. if (p_what == NOTIFICATION_TRANSLATION_CHANGED) {
  543. if (mesh.is_valid()) {
  544. mesh->notification(NOTIFICATION_TRANSLATION_CHANGED);
  545. }
  546. }
  547. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  548. if (skin_ref.is_valid() && mesh.is_valid() && _is_software_skinning_enabled()) {
  549. ERR_FAIL_COND(!skin_ref->get_skeleton_node());
  550. if (is_visible_in_tree()) {
  551. skin_ref->get_skeleton_node()->connect("skeleton_updated", this, "_update_skinning");
  552. } else {
  553. skin_ref->get_skeleton_node()->disconnect("skeleton_updated", this, "_update_skinning");
  554. }
  555. }
  556. }
  557. }
  558. int MeshInstance::get_surface_material_count() const {
  559. return materials.size();
  560. }
  561. void MeshInstance::set_surface_material(int p_surface, const Ref<Material> &p_material) {
  562. ERR_FAIL_INDEX(p_surface, materials.size());
  563. materials.write[p_surface] = p_material;
  564. if (materials[p_surface].is_valid()) {
  565. VS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, materials[p_surface]->get_rid());
  566. } else {
  567. VS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, RID());
  568. }
  569. if (software_skinning) {
  570. _initialize_skinning(true);
  571. }
  572. }
  573. Ref<Material> MeshInstance::get_surface_material(int p_surface) const {
  574. ERR_FAIL_INDEX_V(p_surface, materials.size(), Ref<Material>());
  575. return materials[p_surface];
  576. }
  577. Ref<Material> MeshInstance::get_active_material(int p_surface) const {
  578. Ref<Material> material_override = get_material_override();
  579. if (material_override.is_valid()) {
  580. return material_override;
  581. }
  582. Ref<Material> surface_material = get_surface_material(p_surface);
  583. if (surface_material.is_valid()) {
  584. return surface_material;
  585. }
  586. Ref<Mesh> mesh = get_mesh();
  587. if (mesh.is_valid()) {
  588. return mesh->surface_get_material(p_surface);
  589. }
  590. return Ref<Material>();
  591. }
  592. void MeshInstance::set_material_override(const Ref<Material> &p_material) {
  593. if (p_material == get_material_override()) {
  594. return;
  595. }
  596. GeometryInstance::set_material_override(p_material);
  597. if (software_skinning) {
  598. _initialize_skinning(true);
  599. }
  600. }
  601. void MeshInstance::set_material_overlay(const Ref<Material> &p_material) {
  602. if (p_material == get_material_overlay()) {
  603. return;
  604. }
  605. GeometryInstance::set_material_overlay(p_material);
  606. }
  607. void MeshInstance::set_software_skinning_transform_normals(bool p_enabled) {
  608. if (p_enabled == is_software_skinning_transform_normals_enabled()) {
  609. return;
  610. }
  611. if (p_enabled) {
  612. software_skinning_flags |= SoftwareSkinning::FLAG_TRANSFORM_NORMALS;
  613. } else {
  614. software_skinning_flags &= ~SoftwareSkinning::FLAG_TRANSFORM_NORMALS;
  615. }
  616. if (software_skinning) {
  617. _initialize_skinning(true);
  618. }
  619. }
  620. bool MeshInstance::is_software_skinning_transform_normals_enabled() const {
  621. return 0 != (software_skinning_flags & SoftwareSkinning::FLAG_TRANSFORM_NORMALS);
  622. }
  623. void MeshInstance::_mesh_changed() {
  624. ERR_FAIL_COND(mesh.is_null());
  625. materials.resize(mesh->get_surface_count());
  626. if (software_skinning) {
  627. _initialize_skinning(true);
  628. }
  629. }
  630. void MeshInstance::create_debug_tangents() {
  631. Vector<Vector3> lines;
  632. Vector<Color> colors;
  633. Ref<Mesh> mesh = get_mesh();
  634. if (!mesh.is_valid()) {
  635. return;
  636. }
  637. for (int i = 0; i < mesh->get_surface_count(); i++) {
  638. Array arrays = mesh->surface_get_arrays(i);
  639. Vector<Vector3> verts = arrays[Mesh::ARRAY_VERTEX];
  640. Vector<Vector3> norms = arrays[Mesh::ARRAY_NORMAL];
  641. if (norms.size() == 0) {
  642. continue;
  643. }
  644. Vector<float> tangents = arrays[Mesh::ARRAY_TANGENT];
  645. if (tangents.size() == 0) {
  646. continue;
  647. }
  648. for (int j = 0; j < verts.size(); j++) {
  649. Vector3 v = verts[j];
  650. Vector3 n = norms[j];
  651. Vector3 t = Vector3(tangents[j * 4 + 0], tangents[j * 4 + 1], tangents[j * 4 + 2]);
  652. Vector3 b = (n.cross(t)).normalized() * tangents[j * 4 + 3];
  653. lines.push_back(v); //normal
  654. colors.push_back(Color(0, 0, 1)); //color
  655. lines.push_back(v + n * 0.04); //normal
  656. colors.push_back(Color(0, 0, 1)); //color
  657. lines.push_back(v); //tangent
  658. colors.push_back(Color(1, 0, 0)); //color
  659. lines.push_back(v + t * 0.04); //tangent
  660. colors.push_back(Color(1, 0, 0)); //color
  661. lines.push_back(v); //binormal
  662. colors.push_back(Color(0, 1, 0)); //color
  663. lines.push_back(v + b * 0.04); //binormal
  664. colors.push_back(Color(0, 1, 0)); //color
  665. }
  666. }
  667. if (lines.size()) {
  668. Ref<SpatialMaterial> sm;
  669. sm.instance();
  670. sm->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  671. sm->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  672. sm->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  673. Ref<ArrayMesh> am;
  674. am.instance();
  675. Array a;
  676. a.resize(Mesh::ARRAY_MAX);
  677. a[Mesh::ARRAY_VERTEX] = lines;
  678. a[Mesh::ARRAY_COLOR] = colors;
  679. am->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, a);
  680. am->surface_set_material(0, sm);
  681. MeshInstance *mi = memnew(MeshInstance);
  682. mi->set_mesh(am);
  683. mi->set_name("DebugTangents");
  684. add_child(mi);
  685. #ifdef TOOLS_ENABLED
  686. if (is_inside_tree() && this == get_tree()->get_edited_scene_root()) {
  687. mi->set_owner(this);
  688. } else {
  689. mi->set_owner(get_owner());
  690. }
  691. #endif
  692. }
  693. }
  694. bool MeshInstance::merge_meshes(Vector<Variant> p_list, bool p_use_global_space, bool p_check_compatibility) {
  695. // bound function only support variants, so we need to convert to a list of MeshInstances
  696. Vector<MeshInstance *> mis;
  697. for (int n = 0; n < p_list.size(); n++) {
  698. MeshInstance *mi = Object::cast_to<MeshInstance>(p_list[n]);
  699. if (mi) {
  700. if (mi != this) {
  701. mis.push_back(mi);
  702. } else {
  703. ERR_PRINT("Destination MeshInstance cannot be a source.");
  704. }
  705. } else {
  706. ERR_PRINT("Only MeshInstances can be merged.");
  707. }
  708. }
  709. ERR_FAIL_COND_V(!mis.size(), "Array contains no MeshInstances");
  710. return _merge_meshes(mis, p_use_global_space, p_check_compatibility);
  711. }
  712. bool MeshInstance::is_mergeable_with(Node *p_other) const {
  713. const MeshInstance *mi = Object::cast_to<MeshInstance>(p_other);
  714. if (mi) {
  715. return _is_mergeable_with(*mi);
  716. }
  717. return false;
  718. }
  719. bool MeshInstance::_is_mergeable_with(const MeshInstance &p_other) const {
  720. if (!get_mesh().is_valid() || !p_other.get_mesh().is_valid()) {
  721. return false;
  722. }
  723. if (!get_allow_merging() || !p_other.get_allow_merging()) {
  724. return false;
  725. }
  726. // various settings that must match
  727. if (get_material_overlay() != p_other.get_material_overlay()) {
  728. return false;
  729. }
  730. if (get_material_override() != p_other.get_material_override()) {
  731. return false;
  732. }
  733. if (get_cast_shadows_setting() != p_other.get_cast_shadows_setting()) {
  734. return false;
  735. }
  736. if (get_flag(FLAG_USE_BAKED_LIGHT) != p_other.get_flag(FLAG_USE_BAKED_LIGHT)) {
  737. return false;
  738. }
  739. if (is_visible() != p_other.is_visible()) {
  740. return false;
  741. }
  742. Ref<Mesh> rmesh_a = get_mesh();
  743. Ref<Mesh> rmesh_b = p_other.get_mesh();
  744. int num_surfaces = rmesh_a->get_surface_count();
  745. if (num_surfaces != rmesh_b->get_surface_count()) {
  746. return false;
  747. }
  748. for (int n = 0; n < num_surfaces; n++) {
  749. // materials must match
  750. if (get_active_material(n) != p_other.get_active_material(n)) {
  751. return false;
  752. }
  753. // formats must match
  754. uint32_t format_a = rmesh_a->surface_get_format(n);
  755. uint32_t format_b = rmesh_b->surface_get_format(n);
  756. if (format_a != format_b) {
  757. return false;
  758. }
  759. }
  760. // NOTE : These three commented out sections below are more conservative
  761. // checks for whether to allow mesh merging. I am not absolutely sure a priori
  762. // how conservative we need to be, so we can further enable this if testing
  763. // shows they are required.
  764. // if (get_surface_material_count() != p_other.get_surface_material_count()) {
  765. // return false;
  766. // }
  767. // for (int n = 0; n < get_surface_material_count(); n++) {
  768. // if (get_surface_material(n) != p_other.get_surface_material(n)) {
  769. // return false;
  770. // }
  771. // }
  772. // test only allow identical meshes
  773. // if (get_mesh() != p_other.get_mesh()) {
  774. // return false;
  775. // }
  776. return true;
  777. }
  778. void MeshInstance::_merge_into_mesh_data(const MeshInstance &p_mi, const Transform &p_dest_tr_inv, int p_surface_id, LocalVector<Vector3> &r_verts, LocalVector<Vector3> &r_norms, LocalVector<real_t> &r_tangents, LocalVector<Color> &r_colors, LocalVector<Vector2> &r_uvs, LocalVector<Vector2> &r_uv2s, LocalVector<int> &r_inds) {
  779. _merge_log("\t\t\tmesh data from " + p_mi.get_name());
  780. // get the mesh verts in local space
  781. Ref<Mesh> rmesh = p_mi.get_mesh();
  782. if (rmesh->get_surface_count() <= p_surface_id) {
  783. return;
  784. }
  785. Array arrays = rmesh->surface_get_arrays(p_surface_id);
  786. LocalVector<Vector3> verts = PoolVector<Vector3>(arrays[VS::ARRAY_VERTEX]);
  787. if (!verts.size()) {
  788. // early out if there are no vertices, no point in doing anything else
  789. return;
  790. }
  791. LocalVector<Vector3> normals = PoolVector<Vector3>(arrays[VS::ARRAY_NORMAL]);
  792. LocalVector<real_t> tangents = PoolVector<real_t>(arrays[VS::ARRAY_TANGENT]);
  793. LocalVector<Color> colors = PoolVector<Color>(arrays[VS::ARRAY_COLOR]);
  794. LocalVector<Vector2> uvs = PoolVector<Vector2>(arrays[VS::ARRAY_TEX_UV]);
  795. LocalVector<Vector2> uv2s = PoolVector<Vector2>(arrays[VS::ARRAY_TEX_UV2]);
  796. LocalVector<int> indices = PoolVector<int>(arrays[VS::ARRAY_INDEX]);
  797. // The attributes present must match the first mesh for the attributes
  798. // to remain in sync. Here we reject meshes with different attributes.
  799. // We could alternatively invent missing attributes.
  800. // This should hopefully be already caught by the mesh_format, but is included just in case here.
  801. // Don't perform these checks on the first Mesh, the first Mesh is a master
  802. // and determines the attributes we want to be present.
  803. if (r_verts.size() != 0) {
  804. if ((bool)r_norms.size() != (bool)normals.size()) {
  805. ERR_FAIL_MSG("Attribute mismatch with first Mesh (Normals), ignoring surface.");
  806. }
  807. if ((bool)r_tangents.size() != (bool)tangents.size()) {
  808. ERR_FAIL_MSG("Attribute mismatch with first Mesh (Tangents), ignoring surface.");
  809. }
  810. if ((bool)r_colors.size() != (bool)colors.size()) {
  811. ERR_FAIL_MSG("Attribute mismatch with first Mesh (Colors), ignoring surface.");
  812. }
  813. if ((bool)r_uvs.size() != (bool)uvs.size()) {
  814. ERR_FAIL_MSG("Attribute mismatch with first Mesh (UVs), ignoring surface.");
  815. }
  816. if ((bool)r_uv2s.size() != (bool)uv2s.size()) {
  817. ERR_FAIL_MSG("Attribute mismatch with first Mesh (UV2s), ignoring surface.");
  818. }
  819. }
  820. // The checking for valid triangles should be on WORLD SPACE vertices,
  821. // NOT model space
  822. // special case, if no indices, create some
  823. int num_indices_before = indices.size();
  824. if (!_ensure_indices_valid(indices, verts)) {
  825. _merge_log("\tignoring INVALID TRIANGLES (duplicate indices or zero area triangle) detected in " + p_mi.get_name() + ", num inds before / after " + itos(num_indices_before) + " / " + itos(indices.size()));
  826. }
  827. // the first index of this mesh is offset from the verts we already have stored in the merged mesh
  828. int starting_index = r_verts.size();
  829. // transform verts to world space
  830. Transform tr = p_mi.get_global_transform();
  831. // But relative to the destination transform.
  832. // This can either be identity (when the destination is global space),
  833. // or the global transform of the owner MeshInstance (if using local space is selected).
  834. tr = p_dest_tr_inv * tr;
  835. // to transform normals
  836. Basis normal_basis = tr.basis.inverse();
  837. normal_basis.transpose();
  838. int num_verts = verts.size();
  839. // verts
  840. DEV_ASSERT(num_verts > 0);
  841. int first_vert = r_verts.size();
  842. r_verts.resize(first_vert + num_verts);
  843. Vector3 *dest_verts = &r_verts[first_vert];
  844. for (int n = 0; n < num_verts; n++) {
  845. Vector3 pt_world = tr.xform(verts[n]);
  846. *dest_verts++ = pt_world;
  847. }
  848. // normals
  849. if (normals.size()) {
  850. int first_norm = r_norms.size();
  851. r_norms.resize(first_norm + num_verts);
  852. Vector3 *dest_norms = &r_norms[first_norm];
  853. for (int n = 0; n < num_verts; n++) {
  854. Vector3 pt_norm = normal_basis.xform(normals[n]);
  855. pt_norm.normalize();
  856. *dest_norms++ = pt_norm;
  857. }
  858. }
  859. // tangents
  860. if (tangents.size()) {
  861. int first_tang = r_tangents.size();
  862. r_tangents.resize(first_tang + (num_verts * 4));
  863. real_t *dest_tangents = &r_tangents[first_tang];
  864. for (int n = 0; n < num_verts; n++) {
  865. int tstart = n * 4;
  866. Vector3 pt_tangent = Vector3(tangents[tstart], tangents[tstart + 1], tangents[tstart + 2]);
  867. real_t fourth = tangents[tstart + 3];
  868. pt_tangent = normal_basis.xform(pt_tangent);
  869. pt_tangent.normalize();
  870. *dest_tangents++ = pt_tangent.x;
  871. *dest_tangents++ = pt_tangent.y;
  872. *dest_tangents++ = pt_tangent.z;
  873. *dest_tangents++ = fourth;
  874. }
  875. }
  876. // colors
  877. if (colors.size()) {
  878. int first_col = r_colors.size();
  879. r_colors.resize(first_col + num_verts);
  880. Color *dest_colors = &r_colors[first_col];
  881. for (int n = 0; n < num_verts; n++) {
  882. *dest_colors++ = colors[n];
  883. }
  884. }
  885. // uvs
  886. if (uvs.size()) {
  887. int first_uv = r_uvs.size();
  888. r_uvs.resize(first_uv + num_verts);
  889. Vector2 *dest_uvs = &r_uvs[first_uv];
  890. for (int n = 0; n < num_verts; n++) {
  891. *dest_uvs++ = uvs[n];
  892. }
  893. }
  894. // uv2s
  895. if (uv2s.size()) {
  896. int first_uv2 = r_uv2s.size();
  897. r_uv2s.resize(first_uv2 + num_verts);
  898. Vector2 *dest_uv2s = &r_uv2s[first_uv2];
  899. for (int n = 0; n < num_verts; n++) {
  900. *dest_uv2s++ = uv2s[n];
  901. }
  902. }
  903. // indices
  904. if (indices.size()) {
  905. int first_ind = r_inds.size();
  906. r_inds.resize(first_ind + indices.size());
  907. int *dest_inds = &r_inds[first_ind];
  908. for (unsigned int n = 0; n < indices.size(); n++) {
  909. int ind = indices[n] + starting_index;
  910. *dest_inds++ = ind;
  911. }
  912. }
  913. }
  914. bool MeshInstance::_ensure_indices_valid(LocalVector<int> &r_indices, const PoolVector<Vector3> &p_verts) const {
  915. // no indices? create some
  916. if (!r_indices.size()) {
  917. _merge_log("\t\t\t\tindices are blank, creating...");
  918. // indices are blank!! let's create some, assuming the mesh is using triangles
  919. r_indices.resize(p_verts.size());
  920. // this is assuming each triangle vertex is unique
  921. for (unsigned int n = 0; n < r_indices.size(); n++) {
  922. r_indices[n] = n;
  923. }
  924. }
  925. if (!_check_for_valid_indices(r_indices, p_verts, nullptr)) {
  926. LocalVector<int> new_inds;
  927. _check_for_valid_indices(r_indices, p_verts, &new_inds);
  928. // copy the new indices
  929. r_indices = new_inds;
  930. return false;
  931. }
  932. return true;
  933. }
  934. // check for invalid tris, or make a list of the valid triangles, depending on whether r_inds is set
  935. bool MeshInstance::_check_for_valid_indices(const LocalVector<int> &p_inds, const PoolVector<Vector3> &p_verts, LocalVector<int> *r_inds) const {
  936. int nTris = p_inds.size();
  937. nTris /= 3;
  938. int indCount = 0;
  939. for (int t = 0; t < nTris; t++) {
  940. int i0 = p_inds[indCount++];
  941. int i1 = p_inds[indCount++];
  942. int i2 = p_inds[indCount++];
  943. bool ok = true;
  944. // if the indices are the same, the triangle is invalid
  945. if (i0 == i1) {
  946. ok = false;
  947. }
  948. if (i1 == i2) {
  949. ok = false;
  950. }
  951. if (i0 == i2) {
  952. ok = false;
  953. }
  954. // check positions
  955. if (ok) {
  956. // vertex positions
  957. const Vector3 &p0 = p_verts[i0];
  958. const Vector3 &p1 = p_verts[i1];
  959. const Vector3 &p2 = p_verts[i2];
  960. // if the area is zero, the triangle is invalid (and will crash xatlas if we use it)
  961. if (_triangle_is_degenerate(p0, p1, p2, 0.00001)) {
  962. _merge_log("\t\tdetected zero area triangle, ignoring");
  963. ok = false;
  964. }
  965. }
  966. if (ok) {
  967. // if the triangle is ok, we will output it if we are outputting
  968. if (r_inds) {
  969. r_inds->push_back(i0);
  970. r_inds->push_back(i1);
  971. r_inds->push_back(i2);
  972. }
  973. } else {
  974. // if triangle not ok, return failed check if we are not outputting
  975. if (!r_inds) {
  976. return false;
  977. }
  978. }
  979. }
  980. return true;
  981. }
  982. bool MeshInstance::_triangle_is_degenerate(const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_c, real_t p_epsilon) const {
  983. // not interested in the actual area, but numerical stability
  984. Vector3 edge1 = p_b - p_a;
  985. Vector3 edge2 = p_c - p_a;
  986. // for numerical stability keep these values reasonably high
  987. edge1 *= 1024.0;
  988. edge2 *= 1024.0;
  989. Vector3 vec = edge1.cross(edge2);
  990. real_t sl = vec.length_squared();
  991. if (sl <= p_epsilon) {
  992. return true;
  993. }
  994. return false;
  995. }
  996. // If p_check_compatibility is set to false you MUST have performed a prior check using
  997. // is_mergeable_with, otherwise you could get mismatching surface formats leading to graphical errors etc.
  998. bool MeshInstance::_merge_meshes(Vector<MeshInstance *> p_list, bool p_use_global_space, bool p_check_compatibility) {
  999. if (p_list.size() < 1) {
  1000. // should not happen but just in case
  1001. return false;
  1002. }
  1003. // use the first mesh instance to get common data like number of surfaces
  1004. const MeshInstance *first = p_list[0];
  1005. // Mesh compatibility checking. This is relatively expensive, so if done already (e.g. in Room system)
  1006. // this step can be avoided.
  1007. LocalVector<bool> compat_list;
  1008. if (p_check_compatibility) {
  1009. compat_list.resize(p_list.size());
  1010. for (int n = 0; n < p_list.size(); n++) {
  1011. compat_list[n] = false;
  1012. }
  1013. compat_list[0] = true;
  1014. for (uint32_t n = 1; n < compat_list.size(); n++) {
  1015. compat_list[n] = first->_is_mergeable_with(*p_list[n]);
  1016. if (compat_list[n] == false) {
  1017. WARN_PRINT("MeshInstance " + p_list[n]->get_name() + " is incompatible for merging with " + first->get_name() + ", ignoring.");
  1018. }
  1019. }
  1020. }
  1021. Ref<ArrayMesh> am;
  1022. am.instance();
  1023. // If we want a local space result, we need the world space transform of this MeshInstance
  1024. // available to back transform verts from world space.
  1025. Transform dest_tr_inv;
  1026. if (!p_use_global_space) {
  1027. if (is_inside_tree()) {
  1028. dest_tr_inv = get_global_transform();
  1029. dest_tr_inv.affine_invert();
  1030. } else {
  1031. WARN_PRINT("MeshInstance must be inside tree to merge using local space, falling back to global space.");
  1032. }
  1033. }
  1034. for (int s = 0; s < first->get_mesh()->get_surface_count(); s++) {
  1035. LocalVector<Vector3> verts;
  1036. LocalVector<Vector3> normals;
  1037. LocalVector<real_t> tangents;
  1038. LocalVector<Color> colors;
  1039. LocalVector<Vector2> uvs;
  1040. LocalVector<Vector2> uv2s;
  1041. LocalVector<int> inds;
  1042. for (int n = 0; n < p_list.size(); n++) {
  1043. // Ignore if the mesh is incompatible
  1044. if (p_check_compatibility && (!compat_list[n])) {
  1045. continue;
  1046. }
  1047. _merge_into_mesh_data(*p_list[n], dest_tr_inv, s, verts, normals, tangents, colors, uvs, uv2s, inds);
  1048. } // for n through source meshes
  1049. if (!verts.size()) {
  1050. WARN_PRINT_ONCE("No vertices for surface");
  1051. }
  1052. // sanity check on the indices
  1053. for (unsigned int n = 0; n < inds.size(); n++) {
  1054. int i = inds[n];
  1055. if ((unsigned int)i >= verts.size()) {
  1056. WARN_PRINT_ONCE("Mesh index out of range, invalid mesh, aborting");
  1057. return false;
  1058. }
  1059. }
  1060. Array arr;
  1061. arr.resize(Mesh::ARRAY_MAX);
  1062. arr[Mesh::ARRAY_VERTEX] = PoolVector<Vector3>(verts);
  1063. if (normals.size()) {
  1064. arr[Mesh::ARRAY_NORMAL] = PoolVector<Vector3>(normals);
  1065. }
  1066. if (tangents.size()) {
  1067. arr[Mesh::ARRAY_TANGENT] = PoolVector<real_t>(tangents);
  1068. }
  1069. if (colors.size()) {
  1070. arr[Mesh::ARRAY_COLOR] = PoolVector<Color>(colors);
  1071. }
  1072. if (uvs.size()) {
  1073. arr[Mesh::ARRAY_TEX_UV] = PoolVector<Vector2>(uvs);
  1074. }
  1075. if (uv2s.size()) {
  1076. arr[Mesh::ARRAY_TEX_UV2] = PoolVector<Vector2>(uv2s);
  1077. }
  1078. arr[Mesh::ARRAY_INDEX] = PoolVector<int>(inds);
  1079. am->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr, Array(), Mesh::ARRAY_COMPRESS_DEFAULT);
  1080. } // for s through surfaces
  1081. // set all the surfaces on the mesh
  1082. set_mesh(am);
  1083. // set merged materials
  1084. int num_surfaces = first->get_mesh()->get_surface_count();
  1085. for (int n = 0; n < num_surfaces; n++) {
  1086. set_surface_material(n, first->get_active_material(n));
  1087. }
  1088. // set some properties to match the merged meshes
  1089. set_material_overlay(first->get_material_overlay());
  1090. set_material_override(first->get_material_override());
  1091. set_cast_shadows_setting(first->get_cast_shadows_setting());
  1092. set_flag(FLAG_USE_BAKED_LIGHT, first->get_flag(FLAG_USE_BAKED_LIGHT));
  1093. return true;
  1094. }
  1095. void MeshInstance::_merge_log(String p_string) const {
  1096. print_verbose(p_string);
  1097. }
  1098. void MeshInstance::_bind_methods() {
  1099. ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &MeshInstance::set_mesh);
  1100. ClassDB::bind_method(D_METHOD("get_mesh"), &MeshInstance::get_mesh);
  1101. ClassDB::bind_method(D_METHOD("set_skeleton_path", "skeleton_path"), &MeshInstance::set_skeleton_path);
  1102. ClassDB::bind_method(D_METHOD("get_skeleton_path"), &MeshInstance::get_skeleton_path);
  1103. ClassDB::bind_method(D_METHOD("set_skin", "skin"), &MeshInstance::set_skin);
  1104. ClassDB::bind_method(D_METHOD("get_skin"), &MeshInstance::get_skin);
  1105. ClassDB::bind_method(D_METHOD("get_surface_material_count"), &MeshInstance::get_surface_material_count);
  1106. ClassDB::bind_method(D_METHOD("set_surface_material", "surface", "material"), &MeshInstance::set_surface_material);
  1107. ClassDB::bind_method(D_METHOD("get_surface_material", "surface"), &MeshInstance::get_surface_material);
  1108. ClassDB::bind_method(D_METHOD("get_active_material", "surface"), &MeshInstance::get_active_material);
  1109. ClassDB::bind_method(D_METHOD("set_software_skinning_transform_normals", "enabled"), &MeshInstance::set_software_skinning_transform_normals);
  1110. ClassDB::bind_method(D_METHOD("is_software_skinning_transform_normals_enabled"), &MeshInstance::is_software_skinning_transform_normals_enabled);
  1111. ClassDB::bind_method(D_METHOD("create_trimesh_collision"), &MeshInstance::create_trimesh_collision);
  1112. ClassDB::set_method_flags("MeshInstance", "create_trimesh_collision", METHOD_FLAGS_DEFAULT);
  1113. ClassDB::bind_method(D_METHOD("create_multiple_convex_collisions"), &MeshInstance::create_multiple_convex_collisions);
  1114. ClassDB::set_method_flags("MeshInstance", "create_multiple_convex_collisions", METHOD_FLAGS_DEFAULT);
  1115. ClassDB::bind_method(D_METHOD("create_convex_collision", "clean", "simplify"), &MeshInstance::create_convex_collision, DEFVAL(true), DEFVAL(false));
  1116. ClassDB::set_method_flags("MeshInstance", "create_convex_collision", METHOD_FLAGS_DEFAULT);
  1117. ClassDB::bind_method(D_METHOD("_mesh_changed"), &MeshInstance::_mesh_changed);
  1118. ClassDB::bind_method(D_METHOD("_update_skinning"), &MeshInstance::_update_skinning);
  1119. ClassDB::bind_method(D_METHOD("create_debug_tangents"), &MeshInstance::create_debug_tangents);
  1120. ClassDB::set_method_flags("MeshInstance", "create_debug_tangents", METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  1121. ClassDB::bind_method(D_METHOD("is_mergeable_with", "other_mesh_instance"), &MeshInstance::is_mergeable_with);
  1122. ClassDB::bind_method(D_METHOD("merge_meshes", "mesh_instances", "use_global_space", "check_compatibility"), &MeshInstance::merge_meshes, DEFVAL(Vector<Variant>()), DEFVAL(false), DEFVAL(true));
  1123. ClassDB::set_method_flags("MeshInstance", "merge_meshes", METHOD_FLAGS_DEFAULT);
  1124. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh");
  1125. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "skin", PROPERTY_HINT_RESOURCE_TYPE, "Skin"), "set_skin", "get_skin");
  1126. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "skeleton", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Skeleton"), "set_skeleton_path", "get_skeleton_path");
  1127. ADD_GROUP("Software Skinning", "software_skinning");
  1128. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "software_skinning_transform_normals"), "set_software_skinning_transform_normals", "is_software_skinning_transform_normals_enabled");
  1129. }
  1130. MeshInstance::MeshInstance() {
  1131. skeleton_path = NodePath("..");
  1132. software_skinning = nullptr;
  1133. software_skinning_flags = SoftwareSkinning::FLAG_TRANSFORM_NORMALS;
  1134. }
  1135. MeshInstance::~MeshInstance() {
  1136. if (software_skinning) {
  1137. memdelete(software_skinning);
  1138. software_skinning = nullptr;
  1139. }
  1140. }