#include "grass_mesh.h" #include #include "heightmap_genlayer.h" using namespace godot; void GrassMesh::_bind_methods() { } void GrassMesh::_ready(){ } void GrassMesh::GenerateMesh(uint32_t count, Ref mesh,HeightmapChunk* chunk,uint32_t size){ this->size = size; instanceCount = count; MultiMesh* multiMesh = memnew(MultiMesh); multiMesh->set_transform_format(MultiMesh::TransformFormat::TRANSFORM_3D); multiMesh->set_instance_count(instanceCount); multiMesh->set_mesh(mesh); set_multimesh(multiMesh); UpdateMesh(chunk); } void GrassMesh::UpdateMesh(HeightmapChunk* chunk){ const float_t posRand = 2.0f; Ref multiMesh = get_multimesh(); uint32_t side = std::sqrt(instanceCount); // multiMesh->set_instance_transform(0,Transform3D(Basis(),Vector3(0,0,0))); // UtilityFunctions::print("side " ,side, " size " , size); for(uint32_t i = 0; i < side; i++){ for(uint32_t j = 0; j < side; j++){ Basis basis; basis.rotate(Vector3i(0,std::rand()/(float)RAND_MAX*2.0f*3.14f,0)); uint32_t index = i*side + j; float_t x = i/(float)side * size; float_t y = j/(float)side * size; int32_t x_int = x; int32_t y_int = y; float_t x_cell = x - (float_t)x_int + ((std::rand()/(float)RAND_MAX)) * posRand; float_t y_cell = y - (float_t)y_int + ((std::rand()/(float)RAND_MAX)) * posRand; // https://codeplea.com/triangular-interpolation // ^^^optimizing a basic trinagle interpolation // v0 ------ v3 // | \ | // | \ | // | \ | // v1 ------ v2 // Wv0 = ((Yv1 - Yv2) * (Px - Xv2) + (Xv2 - Xv1) * (Py - Yv2)) / area // Wv1 = ((Yv2 - Yv0) * (Px - Xv2) + (Xv0 - Xv2) * (Py - Yv2)) / area // Wv2 = 1 - Wv0 - Wv1 // Wv0 = (0 * (Px - Xv2) + 1 * (Py - Yv2)) / area // Wv1 = (1 * (Px - Xv2) + -1 * (Py - Yv2)) / area // Wv2 = 1 - Wv0 - Wv1 // Wv0 = ((Yv2 - Yv3) * (Px - Xv3) + (Xv3 - Xv2) * (Py - Yv3)) / area // Wv2 = ((Yv3 - Yv0) * (Px - Xv3) + (Xv0 - Xv3) * (Py - Yv3)) / area // Wv3 = 1 - Wv0 - Wv2 // Wv0 = (1 * (Px - Xv3) + 0 * (Py - Yv3)) / area // Wv2 = (0 * (Px - Xv3) + -1 * (Py - Yv3)) / area // Wv3 = 1 - Wv0 - Wv2 float_t w0 = 0; float_t w1 = 0; float_t w2 = 0; float_t w3 = 0; float_t height = 0; if(x_int < size && y_int < size){ if(y_cell - x_cell >= 0){ w0 = -(y_cell-1); w1 = -((x_cell-1) - (y_cell-1)); w2 = 1 - w0 - w1; height = chunk->GetLocalCell(Vector2i(x_int,y_int+1)) * w1 + chunk->GetLocalCell(Vector2i(x_int+1,y_int+1)) * w2 + chunk->GetLocalCell(Vector2i(x_int,y_int)) * w0; }else{ w0 = -(x_cell-1); w2 = ( y_cell); w3 = 1 - w0 - w2; height = chunk->GetLocalCell(Vector2i(x_int+1,y)) * w3 + chunk->GetLocalCell(Vector2i(x_int+1,y_int+1)) * w2 + chunk->GetLocalCell(Vector2i(x_int,y_int)) * w0; } } multiMesh->set_instance_transform(index,Transform3D(basis,Vector3(x,height,y))); } } }