Backup commit

This commit is contained in:
iasonmanolas 2022-09-14 13:04:05 +02:00
parent 01dff95f9d
commit 266aca08c2
14 changed files with 6146 additions and 5829 deletions

View File

@ -45,7 +45,8 @@ target_include_directories(${PROJECT_NAME} PUBLIC ${DRMSimulationModelDir})
#add_compile_definitions(DLIB_DEFINED)
## polyscope
#if(NOT TARGET polyscope AND ${USE_POLYSCOPE})
if(#[[NOT TARGET polyscope AND]] ${USE_POLYSCOPE})
message("Using polyscope")
FetchContent_Declare(polyscope
GIT_REPOSITORY https://github.com/nmwsharp/polyscope.git
GIT_TAG master
@ -55,7 +56,7 @@ target_include_directories(${PROJECT_NAME} PUBLIC ${DRMSimulationModelDir})
# target_include_directories(${PROJECT_NAME} PUBLIC ${polyscope_SOURCE_DIR}/deps/imgui)
target_sources(${PROJECT_NAME} PUBLIC ${polyscope_SOURCE_DIR}/deps/imgui/imgui/misc/cpp/imgui_stdlib.h ${polyscope_SOURCE_DIR}/deps/imgui/imgui/misc/cpp/imgui_stdlib.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC polyscope)
#endif()
endif()
#if(NOT TARGET polyscope AND ${USE_POLYSCOPE})
# set(POLYSCOPE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/polyscope)
# download_project(PROJ POLYSCOPE
@ -149,8 +150,9 @@ add_subdirectory(${ARMADILLO_SOURCE_DIR} ${ARMADILLO_BIN_DIR})
target_include_directories(${PROJECT_NAME} PUBLIC ${ARMADILLO_SOURCE_DIR}/include)
add_compile_definitions(ARMA_DONT_USE_WRAPPER)
target_link_libraries(${PROJECT_NAME} PUBLIC "/home/iason/Coding/Libraries/armadillo/build/libarmadillo.a" #[[blas lapack]])
find_package(Armadillo REQUIRED)
target_link_libraries(${PROJECT_NAME} PUBLIC ${ARMADILLO_LIBRARIES})
#find_package(Armadillo REQUIRED)
#target_link_libraries(${PROJECT_NAME} PUBLIC ${ARMADILLO_LIBRARIES})
#if(NOT TARGET ThreedBeamFEA)
#FetchContent_Declare(armadillo
# GIT_REPOSITORY https://gitlab.com/conradsnicta/armadillo-code.git
@ -203,7 +205,7 @@ add_compile_definitions(USE_ENSMALLEN)
# LINK_FLAGS "${CHRONO_LINKER_FLAGS}")
#include_directories(${CHRONO_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME} PUBLIC ${CHRONO_LIBRARIES})
#target_include_directories(${PROJECT_NAME} PUBLIC "/home/iason/Coding/Libraries/chrono-7.0.3/src" #[[${CHRONO_INCLUDE_DIRS}]] #[["/home/iason/Coding/Libraries/chrono-7.0.3/src"]] #[["/usr/include/irrlicht"]] )
target_include_directories(${PROJECT_NAME} PUBLIC "/home/iason/Coding/Libraries/chrono-7.0.3/src" #[[${CHRONO_INCLUDE_DIRS}]] #[["/home/iason/Coding/Libraries/chrono-7.0.3/src"]] #[["/usr/include/irrlicht"]] )
#target_link_directories(${PROJECT_NAME} PRIVATE "/home/iason/Coding/build/external dependencies/CHRONO-src/build/RelWithDebInfo/lib")
#target_link_libraries(${PROJECT_NAME} PUBLIC "/home/iason/Coding/build/external dependencies/CHRONO-src/build/RelWithDebInfo/lib/libChronoEngine.a")
target_link_libraries(${PROJECT_NAME} PUBLIC "/home/iason/Coding/Libraries/chrono-7.0.3/build/Release/lib/libChronoEngine.a")
@ -252,11 +254,12 @@ if(NOT TARGET tbb_static AND NOT TARGET tbb)
# option(TBB_BUILD_TESTS "Build TBB tests and enable testing infrastructure" OFF)
# add_subdirectory(${TBB_SOURCE_DIR} ${TBB_BINARY_DIR})
#link_directories(${TBB_BINARY_DIR})
message("Using tbb")
FetchContent_Declare(tbb
GIT_REPOSITORY https://github.com/wjakob/tbb.git
GIT_TAG master
)
FetchContent_MakeAvailable(tbb)
# target_link_libraries(${PROJECT_NAME} PRIVATE tbb_static)
target_link_libraries(${PROJECT_NAME} PRIVATE tbb)
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE tbb_static)

View File

@ -106,6 +106,33 @@ void ChronosEulerSimulationModel::parseForces(
}
}
void ChronosEulerSimulationModel::parseForcedDisplacements(
const std::shared_ptr<const SimulationJob>& pJob,
const std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>>&
edgeMeshVertsToChronoNodes,
chrono::ChSystemSMC& my_system) {
assert(!edgeMeshVertsToChronoNodes.empty());
ChState x;
ChStateDelta v;
double t;
for (const std::pair<VertexIndex, Eigen::Vector3d>& forcedDisplacement :
pJob->nodalForcedDisplacements) {
assert(false);
std::cerr << "Forced displacements dont work" << std::endl;
// std::terminate();
const int& constrainedVi = forcedDisplacement.first;
ChVector<double> displacementVector(
pJob->nodalForcedDisplacements.at(constrainedVi));
const std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>& constrainedChronoNode =
edgeMeshVertsToChronoNodes[constrainedVi];
constrainedChronoNode->NodeIntStateGather(0, x, 0, v, t);
std::cout << "state rows:" << x.rows() << std::endl;
std::cout << "state cols:" << x.cols() << std::endl;
// x = x + displacementVector;
constrainedChronoNode->NodeIntStateScatter(0, x, 0, v, t);
}
}
void ChronosEulerSimulationModel::parseConstrainedVertices(
const std::shared_ptr<const SimulationJob>& pJob,
const std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>>&
@ -120,30 +147,17 @@ void ChronosEulerSimulationModel::parseConstrainedVertices(
auto truss = chrono_types::make_shared<ChBody>();
truss->SetBodyFixed(true);
my_system.Add(truss);
const auto& constrainedChronoNode =
const std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>& constrainedChronoNode =
edgeMeshVertsToChronoNodes[constrainedVi];
// Create a constraint at the end of the beam
auto constr_a = chrono_types::make_shared<ChLinkMateGeneric>();
constr_a->SetConstrainedCoords(
auto constraint = chrono_types::make_shared<ChLinkMateGeneric>();
constraint->SetConstrainedCoords(
constrainedDoF.contains(0), constrainedDoF.contains(1),
constrainedDoF.contains(2), constrainedDoF.contains(3),
constrainedDoF.contains(4), constrainedDoF.contains(5));
constr_a->Initialize(constrainedChronoNode, truss, false,
constraint->Initialize(constrainedChronoNode, truss, false,
constrainedChronoNode->Frame(),
constrainedChronoNode->Frame());
// const auto frameNode = constrainedChronoNode->Frame();
my_system.Add(constr_a);
// edgeMeshVertsToChronoNodes[constrainedVi]->SetFixed(true);
// if (vertexIsFullyConstrained) {
// } else {
// std::cerr << "Currently only rigid vertices are handled." <<
// std::endl;
// // SimulationResults simulationResults;
// // simulationResults.converged = false;
// // assert(false);
// // return simulationResults;
// }
my_system.Add(constraint);
}
}
@ -177,6 +191,7 @@ SimulationResults ChronosEulerSimulationModel::executeSimulation(
// -1));
// my_system.SetTimestepperType(chrono::ChTimestepper::Type::EULER_IMPLICIT_LINEARIZED);
// parse forces
parseForcedDisplacements(pJob, edgeMeshVertsToChronoNodes, my_system);
parseForces(mesh_chronos, edgeMeshVertsToChronoNodes,
pJob->nodalExternalForces);
// parse constrained vertices
@ -198,20 +213,29 @@ SimulationResults ChronosEulerSimulationModel::executeSimulation(
auto solver = chrono_types::make_shared<ChSolverMINRES>();
my_system.SetSolver(solver);
// solver->SetMaxIterations(1e5);
// solver->SetTolerance(1e-12);
solver->SetMaxIterations(1e5);
solver->EnableWarmStart(
true); // IMPORTANT for convergence when using EULER_IMPLICIT_LINEARIZED
solver->EnableDiagonalPreconditioner(true);
my_system.SetSolverForceTolerance(1e-9);
solver->SetVerbose(false);
// solver->SetTolerance(1e-15);
my_system.SetSolverForceTolerance(1e-15);
SimulationResults simulationResults;
//#ifdef POLYSCOPE_DEFINED
// solver->SetVerbose(true);
// // edgeMeshVertsToChronoNodes[10]->Frame().Move({0, 0, 1e-1});
// simulationResults.converged = my_system.DoEntireKinematics(5e2);
//// edgeMeshVertsToChronoNodes[10]->SetForce({0, 0, 1e6});
//#else
solver->SetVerbose(false);
if (settings.analysisType == Settings::AnalysisType::Linear) {
simulationResults.converged = my_system.DoStaticLinear();
// simulationResults.converged = my_system.DoStaticRelaxing();
} else {
simulationResults.converged = my_system.DoStaticNonlinear();
// simulationResults.converged = my_system.DoStaticRelaxing();
}
//#endif
if (!simulationResults.converged) {
std::cerr << "Simulation failed" << std::endl;
assert(false);

View File

@ -11,32 +11,41 @@ class ChNodeFEAxyzrot;
} // namespace fea
} // namespace chrono
class ChronosEulerSimulationModel : public SimulationModel
{
class ChronosEulerSimulationModel : public SimulationModel {
std::shared_ptr<chrono::fea::ChMesh> mesh_chronos;
std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>> edgeMeshVertsToChronoNodes;
std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>>
edgeMeshVertsToChronoNodes;
static void parseConstrainedVertices(
const std::shared_ptr<const SimulationJob>& pJob,
const std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>> &edgeMeshVertsToChronoNodes,
const std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>>&
edgeMeshVertsToChronoNodes,
chrono::ChSystemSMC& my_system);
static void parseForces(
const std::shared_ptr<chrono::fea::ChMesh>& mesh_chronos,
const std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>> &edgeMeshVertsToChronoNodes,
const std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>>&
edgeMeshVertsToChronoNodes,
const std::unordered_map<VertexIndex, Vector6d>& nodalExternalForces);
static void parseForcedDisplacements(
const std::shared_ptr<const SimulationJob>& pJob,
const std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>>&
edgeMeshVertsToChronoNodes,
chrono::ChSystemSMC& my_system);
public:
ChronosEulerSimulationModel();
SimulationResults executeSimulation(const std::shared_ptr<SimulationJob> &pJob) override;
SimulationResults executeSimulation(
const std::shared_ptr<SimulationJob>& pJob) override;
void setStructure(const std::shared_ptr<SimulationEdgeMesh>& pMesh) override;
static std::shared_ptr<chrono::fea::ChMesh> convertToChronosMesh_Euler(
const std::shared_ptr<SimulationEdgeMesh>& pMesh,
std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>> &edgeMeshVertsToChronosNodes);
std::vector<std::shared_ptr<chrono::fea::ChNodeFEAxyzrot>>&
edgeMeshVertsToChronosNodes);
inline const static std::string label{"Chronos_Euler"};
struct Settings
{
struct Settings {
enum AnalysisType { Linear = 0, NonLinear };
AnalysisType analysisType{NonLinear};
};

View File

@ -1,297 +0,0 @@
#ifndef POLYMESH_HPP
#define POLYMESH_HPP
#include "mesh.hpp"
#include "utilities.hpp"
#include "vcg/complex/complex.h"
#include <filesystem>
#include <wrap/io_trimesh/export_obj.h>
#include <wrap/io_trimesh/export_ply.h>
#include <wrap/io_trimesh/import.h>
#ifdef POLYSCOPE_DEFINED
#include <polyscope/surface_mesh.h>
#endif
class PFace;
class PVertex;
class PEdge;
struct PUsedTypes : public vcg::UsedTypes<vcg::Use<PVertex>::AsVertexType,
vcg::Use<PFace>::AsFaceType,
vcg::Use<PEdge>::AsEdgeType>
{};
class PVertex : public vcg::Vertex<PUsedTypes,
vcg::vertex::Coord3d,
vcg::vertex::Normal3d,
vcg::vertex::Mark,
vcg::vertex::Qualityf,
vcg::vertex::BitFlags,
vcg::vertex::VFAdj,
vcg::vertex::VEAdj>
{};
class PEdge : public vcg::Edge<PUsedTypes,
vcg::edge::VertexRef,
vcg::edge::BitFlags,
vcg::edge::EEAdj,
vcg::edge::EFAdj,
vcg::edge::VEAdj,
vcg::edge::EVAdj>
{};
class PFace : public vcg::Face<PUsedTypes,
vcg::face::PolyInfo // this is necessary if you use component in
// vcg/simplex/face/component_polygon.h
// It says "this class is a polygon and the memory for its components
// (e.g. pointer to its vertices will be allocated dynamically")
,
// vcg::face::FHAdj,
vcg::face::PVFAdj,
vcg::face::PFEAdj,
vcg::face::PFVAdj,
vcg::face::PVFAdj,
// vcg::face::PVFAdj,
vcg::face::PFFAdj // Pointer to edge-adjacent face (just like FFAdj )
,
vcg::face::BitFlags // bit flags
,
vcg::face::Qualityf // quality
,
vcg::face::Normal3f // normal
,
vcg::face::Color4b>
{};
class VCGPolyMesh
: public vcg::tri::TriMesh<std::vector<PVertex>, std::vector<PFace>, std::vector<PEdge>>,
public Mesh
{
public:
virtual bool load(const std::filesystem::__cxx11::path &meshFilePath) override
{
int mask;
vcg::tri::io::Importer<VCGPolyMesh>::LoadMask(meshFilePath.c_str(), mask);
int error = vcg::tri::io::Importer<VCGPolyMesh>::Open(*this, meshFilePath.c_str(), mask);
if (error != 0) {
std::cerr << "Could not load polygonal mesh:" << meshFilePath << std::endl;
return false;
}
vcg::tri::UpdateTopology<VCGPolyMesh>::FaceFace(*this);
vcg::tri::UpdateTopology<VCGPolyMesh>::VertexEdge(*this);
vcg::tri::UpdateTopology<VCGPolyMesh>::VertexFace(*this);
vcg::tri::UpdateNormal<VCGPolyMesh>::PerVertexNormalized(*this);
vcg::tri::Clean<VCGPolyMesh>::RemoveUnreferencedVertex(*this);
//finally remove valence 1 vertices on the border
// vcg::PolygonalAlgorithm<PolyMeshType>::RemoveValence2Vertices(dual);
return true;
}
// // vcg::tri::io::ImporterOBJ<VCGPolyMesh>::Open();
// // unsigned int mask = 0;
// // mask |= nanoply::NanoPlyWrapper<VCGPolyMesh>::IO_VERTCOORD;
// // mask |= nanoply::NanoPlyWrapper<VCGPolyMesh>::IO_VERTNORMAL;
// // mask |= nanoply::NanoPlyWrapper<VCGPolyMesh>::IO_VERTCOLOR;
// // mask |= nanoply::NanoPlyWrapper<VCGPolyMesh>::IO_EDGEINDEX;
// // mask |= nanoply::NanoPlyWrapper<VCGPolyMesh>::IO_FACEINDEX;
// // if (nanoply::NanoPlyWrapper<VCGPolyMesh>::LoadModel(
// // std::filesystem::absolute(filename).c_str(), *this, mask) !=
// // 0) {
// // std::cout << "Could not load tri mesh" << std::endl;
// // }
// }
Eigen::MatrixX3d getVertices() const
{
Eigen::MatrixX3d vertices(VN(), 3);
for (size_t vi = 0; vi < VN(); vi++) {
VCGPolyMesh::CoordType vertexCoordinates = vert[vi].cP();
vertices.row(vi) = vertexCoordinates.ToEigenVector<Eigen::Vector3d>();
}
return vertices;
}
std::vector<std::vector<int>> getFaces() const
{
std::vector<std::vector<int>> faces(FN());
for (const VCGPolyMesh::FaceType &f : this->face) {
const int fi = vcg::tri::Index<VCGPolyMesh>(*this, f);
for (size_t vi = 0; vi < f.VN(); vi++) {
const size_t viGlobal = vcg::tri::Index<VCGPolyMesh>(*this, f.cV(vi));
faces[fi].push_back(viGlobal);
}
}
return faces;
}
// bool load(const std::filesystem::__cxx11::path &meshFilePath)
// {
// const std::string extension = ".ply";
// std::filesystem::path filePath = meshFilePath;
// assert(std::filesystem::path(filePath).extension().string() == extension);
// unsigned int mask = 0;
// mask |= vcg::tri::io::Mask::IOM_VERTCOORD;
// mask |= vcg::tri::io::Mask::IOM_VERTNORMAL;
// mask |= vcg::tri::io::Mask::IOM_FACEINDEX;
// mask |= vcg::tri::io::Mask::IOM_FACECOLOR;
// if (vcg::tri::io::Importer<VCGPolyMesh>::Open(*this, filePath.c_str()) != 0) {
// return false;
// }
// label = meshFilePath.filename();
// return true;
// }
bool save(const std::filesystem::__cxx11::path &meshFilePath = std::filesystem::path()) override
{
if (meshFilePath.extension() == ".obj") {
return saveOBJ(meshFilePath);
} else if (meshFilePath.extension() == ".ply") {
return savePLY(meshFilePath);
}
return false;
}
bool saveOBJ(const std::filesystem::path &objFilePath = std::filesystem::path())
{
const std::string extension = ".obj";
std::filesystem::path filePath = objFilePath;
if (filePath.empty()) {
filePath = std::filesystem::current_path().append(getLabel() + extension).string();
} else if (std::filesystem::is_directory(std::filesystem::path(objFilePath))) {
filePath = std::filesystem::path(objFilePath).append(getLabel() + extension).string();
}
assert(std::filesystem::path(filePath).extension().string() == extension);
unsigned int mask = 0;
mask |= vcg::tri::io::Mask::IOM_VERTCOORD;
mask |= vcg::tri::io::Mask::IOM_VERTNORMAL;
mask |= vcg::tri::io::Mask::IOM_FACEINDEX;
mask |= vcg::tri::io::Mask::IOM_FACECOLOR;
if (vcg::tri::io::ExporterOBJ<VCGPolyMesh>::Save(*this, filePath.string().c_str(), mask) != 0) {
return false;
}
return true;
}
bool savePLY(const std::filesystem::path &objFilePath = std::filesystem::path())
{
const std::string extension = ".ply";
std::filesystem::path filePath = objFilePath;
if (filePath.empty()) {
filePath = std::filesystem::current_path().append(getLabel() + extension).string();
} else if (std::filesystem::is_directory(std::filesystem::path(objFilePath))) {
filePath = std::filesystem::path(objFilePath).append(getLabel() + extension).string();
}
assert(std::filesystem::path(filePath).extension().string() == extension);
unsigned int mask = 0;
mask |= vcg::tri::io::Mask::IOM_VERTCOORD;
mask |= vcg::tri::io::Mask::IOM_VERTNORMAL;
mask |= vcg::tri::io::Mask::IOM_FACEINDEX;
mask |= vcg::tri::io::Mask::IOM_FACECOLOR;
if (vcg::tri::io::ExporterPLY<VCGPolyMesh>::Save(*this, filePath.string().c_str(), mask, false) != 0) {
return false;
}
return true;
}
#ifdef POLYSCOPE_DEFINED
polyscope::SurfaceMesh *registerForDrawing(
const std::optional<std::array<double, 3>> &desiredColor = std::nullopt,
const bool &shouldEnable = true)
{
auto vertices = getVertices();
auto faces = getFaces();
PolyscopeInterface::init();
polyscope::SurfaceMesh *polyscopeHandle_mesh = polyscope::registerSurfaceMesh(label,
vertices,
faces);
const double drawingRadius = 0.002;
polyscopeHandle_mesh->setEnabled(shouldEnable);
polyscopeHandle_mesh->setEdgeWidth(drawingRadius);
if (desiredColor.has_value()) {
const glm::vec3 desiredColor_glm(desiredColor.value()[0],
desiredColor.value()[1],
desiredColor.value()[2]);
polyscopeHandle_mesh->setSurfaceColor(desiredColor_glm);
}
return polyscopeHandle_mesh;
}
#endif
void moveToCenter()
{
CoordType centerOfMass(0, 0, 0);
for (int vi = 0; vi < VN(); vi++) {
centerOfMass += vert[vi].cP();
}
centerOfMass /= VN();
vcg::tri::UpdatePosition<VCGPolyMesh>::Translate(*this, -centerOfMass);
}
/*
* Returns the average distance from the center of each edge to the center of its face over the whole mesh
* */
double getAverageFaceRadius() const
{
double averageFaceRadius = 0;
for (int fi = 0; fi < FN(); fi++) {
const VCGPolyMesh::FaceType &f = face[fi];
CoordType centerOfFace(0, 0, 0);
for (int vi = 0; vi < f.VN(); vi++) {
centerOfFace = centerOfFace + f.cP(vi);
}
centerOfFace /= f.VN();
double faceRadius = 0;
// for (int face_ei = 0; face_ei < f.EN(); face_ei++) {
// std::cout << "fi:" << getIndex(f) << std::endl;
// auto vps = f.FVp(0);
// auto vpe = vps;
for (int i = 0; i < f.VN(); i++) {
faceRadius += vcg::Distance(centerOfFace, (f.cP0(i) + f.cP1(i)) / 2);
}
// }
const int faceEdges = f.VN(); //NOTE: When does this not hold?
faceRadius /= faceEdges;
averageFaceRadius += faceRadius;
}
averageFaceRadius /= FN();
return averageFaceRadius;
}
bool copy(VCGPolyMesh &copyFrom)
{
vcg::tri::Append<VCGPolyMesh, VCGPolyMesh>::MeshCopy(*this, copyFrom);
label = copyFrom.getLabel();
// eigenEdges = mesh.getEigenEdges();
// if (eigenEdges.rows() == 0) {
// getEdges(eigenEdges);
// }
// eigenVertices = mesh.getEigenVertices();
// if (eigenVertices.rows() == 0) {
// getVertices();
// }
vcg::tri::UpdateTopology<VCGPolyMesh>::VertexEdge(*this);
vcg::tri::UpdateTopology<VCGPolyMesh>::VertexFace(*this);
vcg::tri::UpdateTopology<VCGPolyMesh>::FaceFace(*this);
vcg::tri::UpdateTopology<VCGPolyMesh>::AllocateEdge(*this);
vcg::tri::UpdateTopology<VCGPolyMesh>::EdgeEdge(*this);
// vcg::tri::UpdateTopology<VCGPolyMesh>::VertexFace(*this);
return true;
}
VCGPolyMesh(VCGPolyMesh &copyFrom) { copy(copyFrom); }
VCGPolyMesh() {}
template<typename MeshElement>
size_t getIndex(const MeshElement &meshElement) const
{
return vcg::tri::Index<VCGPolyMesh>(*this, meshElement);
}
};
using ConstVCGPolyMesh = VCGPolyMesh;
#endif // POLYMESH_HPP

View File

@ -1,121 +1,45 @@
#include "reducedmodelevaluator.hpp"
#include <execution>
#include <filesystem>
#include "hexagonremesher.hpp"
#include "reducedmodel.hpp"
#include "reducedmodeloptimizer.hpp"
#include "simulationmodelfactory.hpp"
#include "trianglepatterngeometry.hpp"
#include <execution>
#include <filesystem>
using FullPatternVertexIndex = VertexIndex;
using ReducedPatternVertexIndex = VertexIndex;
using PatternVertexIndex = VertexIndex;
using ReducedModelVertexIndex = VertexIndex;
ReducedModelEvaluator::ReducedModelEvaluator()
{
ReducedModelEvaluator::ReducedModelEvaluator() {
pTileIntoSurface = [&]() {
std::istringstream inputStream_tileIntoTriSurface(tileIntoSurfaceFileContent);
std::istringstream inputStream_tileIntoTriSurface(
tileIntoSurfaceFileContent);
VCGTriMesh tileInto_triMesh;
const bool surfaceLoadSuccessfull = tileInto_triMesh.load(inputStream_tileIntoTriSurface);
const bool surfaceLoadSuccessfull =
tileInto_triMesh.load(inputStream_tileIntoTriSurface);
tileInto_triMesh.setLabel("instantMeshes_plane_34");
assert(surfaceLoadSuccessfull);
return PolygonalRemeshing::remeshWithPolygons(tileInto_triMesh);
}();
}
//double ReducedModelEvaluator::evaluateOptimizationSettings(
// const ReducedModelOptimization::Settings &optimizationSettings,
// const std::vector<std::shared_ptr<PatternGeometry>> &pPatterns,
// std::vector<ReducedModelEvaluator::Results> &patternEvaluationResults)
//{
// assert(!pPatterns.empty());
// double optimizationError = 0;
// auto start = std::chrono::high_resolution_clock::now();
// std::vector<double> averageNormalizedError(pPatterns.size(), 0);
// patternEvaluationResults.clear();
// patternEvaluationResults.resize(pPatterns.size());
// std::for_each(
// // std::execution::par_unseq,
// pPatterns.begin(),
// pPatterns.end(),
// [&](const std::shared_ptr<ConstPatternGeometry> &pPattern) {
// // std::cout << "Optimizing " << pPattern->getLabel() << std::endl;
// ReducedModelOptimization::Results optimizationResults;
// ReducedModelOptimizer optimizer;
// optimizer.optimize(*pPattern, optimizationSettings, optimizationResults);
// const auto evaluationResults
// = ReducedModelEvaluator::evaluateReducedModel(optimizationResults,
// tileIntoSurfaceFilePath,
// scenariosDirPath,
// fullPatternTessellatedResultsDirPath);
// const double averageNormalizedErrorOfPattern
// = std::reduce(evaluationResults.distances_normalizedDrm2reduced.begin(),
// evaluationResults.distances_normalizedDrm2reduced.end())
// / evaluationResults.distances_normalizedDrm2reduced.size();
// const int patternIndex = &pPattern - &patterns[0];
// averageNormalizedError[patternIndex] = averageNormalizedErrorOfPattern;
// patternsEvaluationResults[patternIndex] = evaluationResults;
// });
// const double strategyAverageNormalizedError = std::reduce(std::execution::par_unseq,
// averageNormalizedError.begin(),
// averageNormalizedError.end())
// / pPointers.size();
// const auto totalDuration_min = std::chrono::duration_cast<std::chrono::seconds>(
// std::chrono::high_resolution_clock::now() - start)
// .count()
// / 60.0;
// std::cout << "Optimized pattern(s) in:" << totalDuration_min << " minutes." << std::endl;
// std::cout << "Average time per pattern:" << totalDuration_min / patternsPointers.size()
// << " minutes." << std::endl;
// std::cout << "Objective value:" << strategyAverageNormalizedError << std::endl;
// return strategyAverageNormalizedError;
// // std::cout << "After:" << ++numberOfOptimizationRoundsExecuted << " iterations." << std::endl;
//}
ReducedModelEvaluator::Results ReducedModelEvaluator::evaluateReducedModel(
ReducedModelOptimization::Results &optimizationResult)
{
const std::filesystem::path scenariosDirectoryPath
= "/home/iason/Coding/Projects/Approximating shapes with flat "
ReducedModelOptimization::Results& optimizationResult) {
const std::filesystem::path scenariosDirectoryPath =
"/home/iason/Coding/Projects/Approximating shapes with flat "
"patterns/ReducedModelEvaluator/Scenarios";
const std::filesystem::path fullPatternTessellatedResultsDirectoryPath
= "/home/iason/Coding/Projects/Approximating shapes with flat "
const std::filesystem::path fullPatternTessellatedResultsDirectoryPath =
"/home/iason/Coding/Projects/Approximating shapes with flat "
"patterns/ReducedModelEvaluator/TessellatedResults";
return evaluateReducedModel(optimizationResult,
scenariosDirectoryPath,
return evaluateReducedModel(optimizationResult, scenariosDirectoryPath,
fullPatternTessellatedResultsDirectoryPath);
}
//void ReducedModelEvaluator::printResults(const Results &evaluationResults,
// const std::string &resultsLabel,
// const std::filesystem::path &resultsOutputPath)
//{
// const bool outputPathIsDirectory = !resultsOutputPath.empty()
// && !resultsOutputPath.has_extension();
// const bool outputPathIsFile = !resultsOutputPath.empty() && resultsOutputPath.has_extension();
// assert(outputPathIsDirectory && outputPathIsFile);
// if (outputPathIsDirectory) {
// std::filesystem::create_directories(resultsOutputPath);
// }
//#else
// std::filesystem::path csvOutputFilePath;
// bool shouldOverwrite = false;
// if (outputPathIsDirectory) {
// csvOutputFilePath = std::filesystem::path(resultsOutputPath)
// .append("distances_" + resultsLabel + ".csv")
// .string();
// shouldOverwrite = true;
// } else if (outputPathIsFile) {
// csvOutputFilePath = resultsOutputPath;
// }
// csvFile csvOutput(csvOutputFilePath, shouldOverwrite);
// printResults(evaluationResults, resultsLabel, csvOutput);
//}
void ReducedModelEvaluator::printResults(const Results& evaluationResults,
const std::string &resultsLabel)
{
const std::string& resultsLabel) {
csvFile csvOutputToCout({}, true);
Settings exportSettings;
exportSettings.exportingDirection = Vertical;
@ -126,13 +50,10 @@ void ReducedModelEvaluator::printResults(const Results &evaluationResults,
void ReducedModelEvaluator::printResults(const Results& evaluationResults,
const Settings& settings,
csvFile &csvOutput)
{
csvFile& csvOutput) {
if (settings.shouldWriteHeader) {
csvOutput << csvExportingDataStrings[settings.exportingData];
printHeader(settings, csvOutput);
// csvOutput << "Average error";
// csvOutput<<"Cumulative error";
csvOutput << endrow;
}
if (!settings.resultsLabel.empty()) {
@ -145,13 +66,15 @@ void ReducedModelEvaluator::printResults(const Results &evaluationResults,
}
}
void ReducedModelEvaluator::printHeader(const Settings &settings, csvFile &csvOutput)
{
void ReducedModelEvaluator::printHeader(const Settings& settings,
csvFile& csvOutput) {
if (settings.exportingDirection == Horizontal) {
// csvOutput << "Job label";
for (int jobIndex = 0; jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
for (int jobIndex = 0;
jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
jobIndex++) {
const std::string &jobLabel = ReducedModelEvaluator::scenariosTestSetLabels[jobIndex];
const std::string& jobLabel =
ReducedModelEvaluator::scenariosTestSetLabels[jobIndex];
csvOutput << jobLabel;
}
} else {
@ -161,20 +84,20 @@ void ReducedModelEvaluator::printHeader(const Settings &settings, csvFile &csvOu
}
}
void ReducedModelEvaluator::printResultsHorizontally(const Results &evaluationResults,
csvFile &csvOutput)
{
void ReducedModelEvaluator::printResultsHorizontally(
const Results& evaluationResults,
csvFile& csvOutput) {
// print header
// print raw error
constexpr bool shouldPrintRawError = false;
if (shouldPrintRawError) {
// csvOutput << "drm2Reduced";
double sumOfFull2Reduced = 0;
int numOfNonEvaluatedScenarios = 0;
for (int jobIndex = 0; jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
for (int jobIndex = 0;
jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
jobIndex++) {
const double &distance_fullDrmToReduced = evaluationResults
.distances_drm2reduced[jobIndex];
const double& distance_fullDrmToReduced =
evaluationResults.distances_drm2reduced[jobIndex];
if (distance_fullDrmToReduced == -1) {
csvOutput << "notEvaluated";
numOfNonEvaluatedScenarios++;
@ -183,19 +106,14 @@ void ReducedModelEvaluator::printResultsHorizontally(const Results &evaluationRe
sumOfFull2Reduced += distance_fullDrmToReduced;
}
}
// const int numOfEvaluatedScenarios = ReducedModelEvaluator::scenariosTestSetLabels.size()
// - numOfNonEvaluatedScenarios;
// const double averageDistance_full2Reduced = sumOfFull2Reduced / numOfEvaluatedScenarios;
// csvOutput << averageDistance_full2Reduced;
// csvOutput << endrow;
}
// print normalized error
// csvOutput << "norm_drm2Reduced";
double sumOfNormalizedFull2Reduced = 0;
for (int jobIndex = 0; jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
for (int jobIndex = 0;
jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
jobIndex++) {
const double &distance_normalizedFullDrmToReduced
= evaluationResults.distances_normalizedDrm2reduced[jobIndex];
const double& distance_normalizedFullDrmToReduced =
evaluationResults.distances_normalizedDrm2reduced[jobIndex];
if (distance_normalizedFullDrmToReduced == -1) {
csvOutput << "notEvaluated";
} else {
@ -203,15 +121,11 @@ void ReducedModelEvaluator::printResultsHorizontally(const Results &evaluationRe
sumOfNormalizedFull2Reduced += distance_normalizedFullDrmToReduced;
}
}
// const double averageDistance_normalizedFull2Reduced = sumOfNormalizedFull2Reduced
// / numOfEvaluatedScenarios;
// csvOutput << averageDistance_normalizedFull2Reduced;
// csvOutput << endrow;
}
void ReducedModelEvaluator::printResultsVertically(const Results &evaluationResults,
csvFile &csvOutput)
{
void ReducedModelEvaluator::printResultsVertically(
const Results& evaluationResults,
csvFile& csvOutput) {
#ifdef POLYSCOPE_DEFINED
csvOutput << "pattern2Reduced"
<< "norm_pattern2Reduced";
@ -225,13 +139,16 @@ void ReducedModelEvaluator::printResultsVertically(const Results &evaluationResu
double sumOfFull2Reduced = 0;
double sumOfNormalizedFull2Reduced = 0;
int numOfNonEvaluatedScenarios = 0;
for (int jobIndex = 0; jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
for (int jobIndex = 0;
jobIndex < ReducedModelEvaluator::scenariosTestSetLabels.size();
jobIndex++) {
const double &distance_fullDrmToReduced = evaluationResults.distances_drm2reduced[jobIndex];
const double &distance_normalizedFullDrmToReduced
= evaluationResults.distances_normalizedDrm2reduced[jobIndex];
const double& distance_fullDrmToReduced =
evaluationResults.distances_drm2reduced[jobIndex];
const double& distance_normalizedFullDrmToReduced =
evaluationResults.distances_normalizedDrm2reduced[jobIndex];
#ifndef POLYSCOPE_DEFINED
const std::string &jobLabel = ReducedModelEvaluator::scenariosTestSetLabels[jobIndex];
const std::string& jobLabel =
ReducedModelEvaluator::scenariosTestSetLabels[jobIndex];
csvOutput << jobLabel;
#endif
if (distance_fullDrmToReduced == -1) {
@ -239,22 +156,25 @@ void ReducedModelEvaluator::printResultsVertically(const Results &evaluationResu
<< "notEvaluated";
numOfNonEvaluatedScenarios++;
} else {
csvOutput << distance_fullDrmToReduced << distance_normalizedFullDrmToReduced;
csvOutput << distance_fullDrmToReduced
<< distance_normalizedFullDrmToReduced;
sumOfFull2Reduced += distance_fullDrmToReduced;
sumOfNormalizedFull2Reduced += distance_normalizedFullDrmToReduced;
}
csvOutput << endrow;
// sumOfNormalizedFull2Reduced += distance_normalizedFullDrmToReduced;
}
const int numOfEvaluatedScenarios = ReducedModelEvaluator::scenariosTestSetLabels.size()
- numOfNonEvaluatedScenarios;
const double averageDistance_full2Reduced = sumOfFull2Reduced / numOfEvaluatedScenarios;
const double averageDistance_normalizedFull2Reduced = sumOfNormalizedFull2Reduced
/ numOfEvaluatedScenarios;
const int numOfEvaluatedScenarios =
ReducedModelEvaluator::scenariosTestSetLabels.size() -
numOfNonEvaluatedScenarios;
const double averageDistance_full2Reduced =
sumOfFull2Reduced / numOfEvaluatedScenarios;
const double averageDistance_normalizedFull2Reduced =
sumOfNormalizedFull2Reduced / numOfEvaluatedScenarios;
#ifndef POLYSCOPE_DEFINED
csvOutput << "Average error";
#endif
csvOutput << averageDistance_full2Reduced << averageDistance_normalizedFull2Reduced;
csvOutput << averageDistance_full2Reduced
<< averageDistance_normalizedFull2Reduced;
csvOutput << endrow;
#ifndef POLYSCOPE_DEFINED
csvOutput << "Cumulative error";
@ -264,106 +184,67 @@ void ReducedModelEvaluator::printResultsVertically(const Results &evaluationResu
csvOutput << endrow;
}
//void ReducedModelEvaluator::createFullAndReducedPatternTessellations(){
//}
//ReducedModelEvaluator::Results ReducedModelEvaluator::evaluateReducedModel(
// std::vector<ReducedModelOptimization::Results> &optimizationResults,
// const std::filesystem::path &tileInto_triMesh_filePath,
// const std::filesystem::path &scenariosDirectoryPath,
// // const std::filesystem::path &reducedPatternFilePath,
// const std::filesystem::path &fullPatternTessellatedResultsDirectoryPath)
//{
// //Load surface
// std::shared_ptr<VCGPolyMesh> pTileIntoSurface = [&]() {
// VCGTriMesh tileInto_triMesh;
// const bool surfaceLoadSuccessfull = tileInto_triMesh.load(tileInto_triMesh_filePath);
// assert(surfaceLoadSuccessfull);
// return PolygonalRemeshing::remeshWithPolygons(tileInto_triMesh);
// }();
// const double optimizedBaseTriangleHeight = vcg::Distance(optimizationResult.baseTriangle.cP(0),
// (optimizationResult.baseTriangle.cP(1)
// + optimizationResult.baseTriangle.cP(
// 2))
// / 2);
// pTileIntoSurface->moveToCenter();
// const double scaleFactor = optimizedBaseTriangleHeight
// / pTileIntoSurface->getAverageFaceRadius();
// vcg::tri::UpdatePosition<VCGPolyMesh>::Scale(*pTileIntoSurface, scaleFactor);
// //Tile full pattern into surface
//}
ReducedModelEvaluator::Results ReducedModelEvaluator::evaluateReducedModel(
ReducedModelOptimization::Results& optimizationResult,
const std::filesystem::path& scenariosDirectoryPath,
const std::filesystem::path &fullPatternTessellatedResultsDirectoryPath)
{
// const double optimizedBaseTriangleHeight = vcg::Distance(optimizationResult.baseTriangle.cP(0),
// (optimizationResult.baseTriangle.cP(1)
// + optimizationResult.baseTriangle.cP(
// 2))
// / 2);
const std::filesystem::path& patternTessellatedResultsDirectoryPath) {
// Apply optimization results to the reduced model
ReducedModel reducedModel;
reducedModel.deleteDanglingVertices();
std::unordered_map<std::string, double> optimalXVariables_set(
optimizationResult.optimalXNameValuePairs.begin(),
optimizationResult.optimalXNameValuePairs.end());
reducedModel.updateBaseTriangleGeometry_R(optimalXVariables_set.at("R"));
reducedModel.updateBaseTriangleGeometry_theta(
optimalXVariables_set.at("Theta"));
// reducedModel.registerForDrawing();
// Scale tile-into surface
pTileIntoSurface->moveToCenter();
const double scaleFactor = optimizationResult.settings.targetBaseTriangleSize
/ pTileIntoSurface->getAverageFaceRadius();
const double scaleFactor =
optimizationResult.settings.targetBaseTriangleSize /
pTileIntoSurface->getAverageFaceRadius();
vcg::tri::UpdatePosition<VCGPolyMesh>::Scale(*pTileIntoSurface, scaleFactor);
// tileIntoSurface.registerForDrawing();
// polyscope::show();
#ifdef POLYSCOPE_DEFINED
pTileIntoSurface->registerForDrawing(color_tileIntoSurface);
#endif
// Tile full pattern into surface
std::vector<PatternGeometry> fullPatterns(1);
fullPatterns[0].copy(optimizationResult.baseTriangleFullPattern);
//// Base triangle pattern might contain dangling vertices.Remove those
fullPatterns[0].interfaceNodeIndex = 3;
fullPatterns[0].deleteDanglingVertices();
std::vector<PatternGeometry> patterns(1);
patterns[0].copy(optimizationResult.baseTrianglePattern);
patterns[0].interfaceNodeIndex = 3;
patterns[0].deleteDanglingVertices();
std::vector<int> perSurfaceFacePatternIndices(pTileIntoSurface->FN(), 0);
std::vector<std::vector<size_t>> perPatternIndexTiledFullPatternEdgeIndices;
std::vector<size_t> tileIntoEdgeToTiledFullVi;
std::shared_ptr<PatternGeometry> pTiledFullPattern
= PatternGeometry::tilePattern(fullPatterns,
{},
*pTileIntoSurface,
std::shared_ptr<PatternGeometry> pTilled_pattern =
PatternGeometry::tilePattern(patterns, {}, *pTileIntoSurface,
perSurfaceFacePatternIndices,
tileIntoEdgeToTiledFullVi,
perPatternIndexTiledFullPatternEdgeIndices);
pTiledFullPattern->setLabel("Tiled_full_patterns");
// pTiledFullPattern->registerForDrawing();
//Tile reduced pattern into surface
ReducedModel reducedModel;
reducedModel.deleteDanglingVertices();
std::unordered_map<std::string, double>
optimalXVariables_set(optimizationResult.optimalXNameValuePairs.begin(),
optimizationResult.optimalXNameValuePairs.end());
reducedModel.updateBaseTriangleGeometry_R(optimalXVariables_set.at("R"));
reducedModel.updateBaseTriangleGeometry_theta(optimalXVariables_set.at("Theta"));
// const auto reducedPatternBaseTriangle = reducedModel.computeBaseTriangle();
// ReducedModelOptimization::Results::applyOptimizationResults_reducedModel_nonFanned(
// optimizationResult, reducedPatternBaseTriangle, reducedModel);
pTilled_pattern->setLabel("Tilled_pattern");
std::vector<PatternGeometry> reducedPatterns(1);
reducedPatterns[0].copy(reducedModel);
std::vector<std::vector<size_t>> perPatternIndexTiledReducedPatternEdgeIndices;
// Tile reduced pattern into surface
std::vector<PatternGeometry> reducedModels(1);
reducedModels[0].copy(reducedModel);
std::vector<std::vector<size_t>>
perPatternIndexTiledReducedPatternEdgeIndices;
std::vector<size_t> tileIntoEdgeToTiledReducedVi;
std::shared_ptr<PatternGeometry> pTiledReducedPattern
= PatternGeometry::tilePattern(reducedPatterns,
{0},
*pTileIntoSurface,
perSurfaceFacePatternIndices,
std::shared_ptr<PatternGeometry> pTilled_reducedModel =
PatternGeometry::tilePattern(
reducedModels, {0}, *pTileIntoSurface, perSurfaceFacePatternIndices,
tileIntoEdgeToTiledReducedVi,
perPatternIndexTiledReducedPatternEdgeIndices);
pTiledReducedPattern->setLabel("Tiled_reduced_patterns");
#ifdef POLYSCOPE_DEFINED
pTiledReducedPattern->registerForDrawing();
#endif
pTilled_reducedModel->setLabel("Tilled_reduced_model");
std::unordered_map<FullPatternVertexIndex, ReducedPatternVertexIndex>
std::unordered_map<PatternVertexIndex, ReducedModelVertexIndex>
fullToReducedViMap; // of only the common vertices
std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>
reducedToFullViMap; // of only the common vertices
for (int ei = 0; ei < pTileIntoSurface->EN(); ei++) {
fullToReducedViMap[tileIntoEdgeToTiledFullVi[ei]] = tileIntoEdgeToTiledReducedVi[ei];
fullToReducedViMap[tileIntoEdgeToTiledFullVi[ei]] =
tileIntoEdgeToTiledReducedVi[ei];
}
constructInverseMap(fullToReducedViMap, reducedToFullViMap);
@ -377,121 +258,148 @@ ReducedModelEvaluator::Results ReducedModelEvaluator::evaluateReducedModel(
// Create simulation meshes
////Tessellated full pattern simulation mesh
std::shared_ptr<SimulationMesh> pTiledFullPattern_simulationMesh;
pTiledFullPattern_simulationMesh = std::make_shared<SimulationMesh>(*pTiledFullPattern);
//NOTE: Those should be derived from the optimization results instead of hardcoding them
// const double beamWidth = optimizationResult.settings.patternBeamDimensions.getWidth();
// const double beamHeight = optimizationResult.settings.patternBeamDimensions.getHeight();
pTiledFullPattern_simulationMesh->setBeamCrossSection(
optimizationResult.settings.patternBeamDimensions);
if (optimizationResult.fullPatternYoungsModulus == 0) {
std::shared_ptr<SimulationEdgeMesh> pSimulationEdgeMesh_tilledPattern =
std::make_shared<SimulationEdgeMesh>(*pTilled_pattern);
pSimulationEdgeMesh_tilledPattern->setBeamCrossSection(
optimizationResult.settings.beamDimensions_pattern);
if (optimizationResult.settings.youngsModulus_pattern == 0) {
std::cerr << "Full pattern's young modulus not found." << std::endl;
std::terminate();
}
pTiledFullPattern_simulationMesh->setBeamMaterial(0.3,
optimizationResult.fullPatternYoungsModulus);
pTiledFullPattern_simulationMesh->reset();
pSimulationEdgeMesh_tilledPattern->setBeamMaterial(
0.3, optimizationResult.settings.youngsModulus_pattern);
pSimulationEdgeMesh_tilledPattern->reset();
// optimizationResult.draw();
#ifdef POLYSCOPE_DEFINED
pSimulationEdgeMesh_tilledPattern->registerForDrawing(
color_tesselatedPatterns);
#endif
////Tessellated reduced pattern simulation mesh
std::shared_ptr<SimulationMesh> pTiledReducedPattern_simulationMesh;
pTiledReducedPattern_simulationMesh = std::make_shared<SimulationMesh>(*pTiledReducedPattern);
const std::vector<size_t> &tiledPatternElementIndicesForReducedPattern
= perPatternIndexTiledReducedPatternEdgeIndices[0];
std::shared_ptr<SimulationEdgeMesh> pSimulationEdgeMesh_tilledReducedModel;
pSimulationEdgeMesh_tilledReducedModel =
std::make_shared<SimulationEdgeMesh>(*pTilled_reducedModel);
ReducedModelOptimization::Results::applyOptimizationResults_elements(
optimizationResult, pTiledReducedPattern_simulationMesh);
// pTiledReducedPattern_simulationMesh->reset();
optimizationResult, pSimulationEdgeMesh_tilledReducedModel);
pSimulationEdgeMesh_tilledReducedModel->reset();
#ifdef POLYSCOPE_DEFINED
pSimulationEdgeMesh_tilledReducedModel->registerForDrawing(
color_tesselatedReducedModels);
polyscope::show();
#endif
Results evaluationResults;
evaluationResults.distances_drm2reduced.fill(-1);
evaluationResults.distances_normalizedDrm2reduced.fill(-1);
DRMSimulationModel::Settings drmSimulationSettings;
drmSimulationSettings.totalExternalForcesNormPercentageTermination = 1e-3;
// drmSimulationSettings.threshold_residualToExternalForcesNorm = 1e-3;
// drmSimulationSettings.load(drmSettingsFilePath);
drmSimulationSettings.beVerbose = true;
drmSimulationSettings.maxDRMIterations = 5e6;
drmSimulationSettings.debugModeStep = 100000;
drmSimulationSettings.translationalKineticEnergyThreshold = 1e-15;
drmSimulationSettings.linearGuessForceScaleFactor = 0.8;
drmSimulationSettings.viscousDampingFactor = 7e-3;
drmSimulationSettings.xi = 0.9999;
// drmSimulationSettings.Dtini = 5.86;
drmSimulationSettings.gamma = 0.25;
drmSimulationSettings.threshold_totalTranslationalKineticEnergy = 1e-14;
// drmSimulationSettings.threshold_currentToFirstPeakTranslationalKineticEnergy
// =
// 1e-10;
drmSimulationSettings.threshold_averageResidualToExternalForcesNorm = 1e-5;
// drmSimulationSettings.linearGuessForceScaleFactor = 0.8;
// drmSimulationSettings.viscousDampingFactor = 7e-3;
// drmSimulationSettings.xi = 0.9999;
// drmSimulationSettings.gamma = 0.25;
#ifdef POLYSCOPE_DEFINED
// drmSimulationSettings.shouldDraw = true;
drmSimulationSettings.shouldCreatePlots = true;
drmSimulationSettings.shouldCreatePlots = false;
constexpr bool shouldDrawScenarioResults = true;
if (shouldDrawScenarioResults) {
pSimulationEdgeMesh_tilledPattern->registerForDrawing(
ReducedModelOptimization::Colors::patternInitial);
}
#endif
constexpr bool shouldRerunFullPatternSimulation = false;
const std::string &simulationModelLabel = optimizationResult.settings.simulationModelLabel;
// for (int jobIndex = 0; jobIndex < scenariosTestSetLabels.size(); jobIndex++) {
const std::string& simulationModelLabel_pattern =
optimizationResult.settings.simulationModelLabel_groundTruth;
const std::string& simulationModelLabel_reducedModel =
optimizationResult.settings.simulationModelLabel_reducedModel;
const bool shouldRerunFullPatternSimulation = [&]() {
// if (simulationModelLabel_pattern == DRMSimulationModel::label) {
return false;
// }
// return true;
}();
std::for_each(
//#ifndef POLYSCOPE_DEFINED
#ifndef POLYSCOPE_DEFINED
std::execution::par_unseq,
//#endif
scenariosTestSetLabels.begin(),
scenariosTestSetLabels.end(),
#endif
scenariosTestSetLabels.begin(), scenariosTestSetLabels.end(),
[&](const std::string& jobLabel) {
// check if reduced model scenario exists
// const std::string &jobLabel = scenariosTestSetLabels[jobIndex];
const std::filesystem::path tiledReducedPatternJobFilePath
= std::filesystem::path(scenariosDirectoryPath)
// const std::string &jobLabel =
// scenariosTestSetLabels[jobIndex];
const std::filesystem::path tiledReducedPatternJobFilePath =
std::filesystem::path(scenariosDirectoryPath)
.append(pTileIntoSurface->getLabel())
.append(jobLabel)
.append("ReducedJob")
.append(SimulationJob::jsonDefaultFileName);
if (!std::filesystem::exists(tiledReducedPatternJobFilePath)) {
std::cerr << "Scenario " << jobLabel
<< " not found in:" << tiledReducedPatternJobFilePath << std::endl;
<< " not found in:" << tiledReducedPatternJobFilePath
<< std::endl;
// continue; //if not move on to the next scenario
return;
}
// Map the reduced job to the job on the pattern tessellation
// set jobs
std::shared_ptr<SimulationJob> pJob_tiledReducedPattern;
pJob_tiledReducedPattern = std::make_shared<SimulationJob>(SimulationJob());
pJob_tiledReducedPattern->load(tiledReducedPatternJobFilePath, false);
pJob_tiledReducedPattern->pMesh = pTiledReducedPattern_simulationMesh;
std::shared_ptr<SimulationJob> pJob_tiledFullPattern;
pJob_tiledFullPattern = std::make_shared<SimulationJob>(SimulationJob());
pJob_tiledFullPattern->pMesh = pTiledFullPattern_simulationMesh;
pJob_tiledReducedPattern->remap(reducedToFullViMap, *pJob_tiledFullPattern);
std::shared_ptr<SimulationJob> pJob_tiledReducedModel;
pJob_tiledReducedModel =
std::make_shared<SimulationJob>(SimulationJob());
pJob_tiledReducedModel->load(tiledReducedPatternJobFilePath, false);
pJob_tiledReducedModel->pMesh = pSimulationEdgeMesh_tilledReducedModel;
std::shared_ptr<SimulationJob> pJob_tilledPattern;
pJob_tilledPattern = std::make_shared<SimulationJob>(SimulationJob());
pJob_tilledPattern->pMesh = pSimulationEdgeMesh_tilledPattern;
pJob_tiledReducedModel->remap(reducedToFullViMap, *pJob_tilledPattern);
// pJob_tiledReducedPattern->registerForDrawing(pTiledReducedPattern->getLabel());
// pJob_tiledFullPattern->registerForDrawing(pTiledFullPattern->getLabel());
// polyscope::show();
const std::filesystem::path surfaceFolderPath
= std::filesystem::path(fullPatternTessellatedResultsDirectoryPath)
.append(simulationModelLabel + "_" + pTileIntoSurface->getLabel());
const std::string scenarioLabel = pJob_tiledFullPattern->getLabel();
const std::filesystem::path scenarioDirectoryPath
= std::filesystem::path(surfaceFolderPath).append(scenarioLabel);
const std::filesystem::path surfaceFolderPath =
std::filesystem::path(patternTessellatedResultsDirectoryPath)
.append(simulationModelLabel_pattern + "_" +
pTileIntoSurface->getLabel());
const std::string scenarioLabel = pJob_tilledPattern->getLabel();
const std::filesystem::path scenarioDirectoryPath =
std::filesystem::path(surfaceFolderPath).append(scenarioLabel);
// Save reduced job
constexpr bool exportReducedJob = false;
if (exportReducedJob) {
const std::filesystem::path reducedJobDirectoryPath
= std::filesystem::path(scenarioDirectoryPath).append("ReducedJob");
const std::filesystem::path reducedJobDirectoryPath =
std::filesystem::path(scenarioDirectoryPath).append("ReducedJob");
std::filesystem::create_directories(reducedJobDirectoryPath);
pJob_tiledReducedPattern->save(reducedJobDirectoryPath);
pJob_tiledReducedModel->save(reducedJobDirectoryPath);
}
//Check if the drm simulation of the full pattern has already been computed
// Check if the drm simulation of the full pattern has already been
// computed
////Full
const std::string& patternLabel = [&]() {
const std::string patternLabel = optimizationResult.baseTriangleFullPattern
.getLabel();
const std::string patternLabel =
optimizationResult.baseTrianglePattern.getLabel();
if (patternLabel.find("_") == std::string::npos) {
return std::to_string(optimizationResult.baseTriangleFullPattern.EN()) + "_"
+ patternLabel;
return std::to_string(optimizationResult.baseTrianglePattern.EN()) +
"_" + patternLabel;
} else {
return patternLabel;
}
}();
const auto tilledPatternResultsFolderPath = std::filesystem::path(scenarioDirectoryPath)
const auto tilledPatternResultsFolderPath =
std::filesystem::path(scenarioDirectoryPath)
.append(patternLabel)
.append("Results");
if (shouldRerunFullPatternSimulation
&& std::filesystem::exists(tilledPatternResultsFolderPath)) {
if (shouldRerunFullPatternSimulation &&
std::filesystem::exists(tilledPatternResultsFolderPath)) {
std::filesystem::remove_all(tilledPatternResultsFolderPath);
}
const std::filesystem::path fullPatternJobFolderPath = std::filesystem::path(
scenarioDirectoryPath)
const std::filesystem::path fullPatternJobFolderPath =
std::filesystem::path(scenarioDirectoryPath)
.append(patternLabel)
.append("SimulationJob");
SimulationResults simulationResults_tilledPattern;
@ -500,30 +408,32 @@ ReducedModelEvaluator::Results ReducedModelEvaluator::evaluateReducedModel(
assert(std::filesystem::exists(fullPatternJobFolderPath));
simulationResults_tilledPattern.load(tilledPatternResultsFolderPath,
fullPatternJobFolderPath);
//#ifdef POLYSCOPE_DEFINED
// std::array<double, 3> resultsColor({28.0, 99.0, 227.0});
// simulationResults_tiledFullPattern_drm.registerForDrawing(resultsColor);
#ifdef POLYSCOPE_DEFINED
simulationResults_tilledPattern.registerForDrawing(
color_tesselatedPatterns);
// std::ifstream ifs("CameraSettings.json");
// nlohmann::json json;
// ifs >> json;
// polyscope::view::setCameraFromJson(json.dump(), false);
// // polyscope::show();
// const std::string cameraJson = polyscope::view::getCameraJson();
// std::filesystem::path jsonFilePath("CameraSettings.json");
// std::ofstream jsonFile_cameraSettings(jsonFilePath.string());
// jsonFile_cameraSettings << cameraJson;
// jsonFile_cameraSettings.close();
// std::filesystem::create_directories("screenshots");
// const std::string screenshotOutputFilePath
// = (std::filesystem::current_path()
// .append("screenshots")
// .append(optimizationResult.label + "_" + pJob_tiledFullPattern->getLabel()))
// .string()
// + ".png";
// // std::cout << "Saving image to:" << screenshotOutputFilePath << std::endl;
// polyscope::screenshot(screenshotOutputFilePath, false);
// simulationResults_tiledFullPattern_drm.unregister();
//#endif
polyscope::show();
const std::string cameraJson = polyscope::view::getCameraJson();
std::filesystem::path jsonFilePath("CameraSettings.json");
std::ofstream jsonFile_cameraSettings(jsonFilePath.string());
jsonFile_cameraSettings << cameraJson;
jsonFile_cameraSettings.close();
std::filesystem::create_directories("screenshots");
const std::string screenshotOutputFilePath =
(std::filesystem::current_path()
.append("screenshots")
.append(optimizationResult.label + "_" +
pJob_tilledPattern->getLabel()))
.string() +
".png";
std::cout << "Saving image to:" << screenshotOutputFilePath
<< std::endl;
polyscope::screenshot(screenshotOutputFilePath, false);
simulationResults_tilledPattern.unregister();
#endif
simulationResults_tilledPattern.converged = true;
} else {
@ -532,22 +442,22 @@ ReducedModelEvaluator::Results ReducedModelEvaluator::evaluateReducedModel(
// Full
std::cout << "Executing:" << jobLabel << std::endl;
SimulationModelFactory factory;
std::unique_ptr<SimulationModel> pTilledPatternSimulationModel = factory.create(
simulationModelLabel);
//TODO: since the drm simulation model does not have a common interface with the rest of simulation models I need to cast it in order to pass simulation settings. Fix it by removing the SimulationSettings argument
if (simulationModelLabel == DRMSimulationModel::label) {
simulationResults_tilledPattern = static_cast<DRMSimulationModel *>(
std::unique_ptr<SimulationModel> pTilledPatternSimulationModel =
factory.create(simulationModelLabel_pattern);
// TODO: since the drm simulation model does not have a common
// interface with the rest of simulation models I need to cast it in
// order to pass simulation settings. Fix it by removing the
// SimulationSettings argument
if (simulationModelLabel_pattern == DRMSimulationModel::label) {
simulationResults_tilledPattern =
static_cast<DRMSimulationModel*>(
pTilledPatternSimulationModel.get())
->executeSimulation(pJob_tiledFullPattern,
->executeSimulation(pJob_tilledPattern,
drmSimulationSettings);
} else if (simulationModelLabel == ChronosEulerSimulationModel::label) {
simulationResults_tilledPattern
= pTilledPatternSimulationModel->executeSimulation(pJob_tiledFullPattern);
} else {
std::cerr << "Simulation model used for computing the optimization results was "
"not recognized"
<< std::endl;
std::terminate();
simulationResults_tilledPattern =
pTilledPatternSimulationModel->executeSimulation(
pJob_tilledPattern);
}
}
if (!simulationResults_tilledPattern.converged) {
@ -557,37 +467,65 @@ ReducedModelEvaluator::Results ReducedModelEvaluator::evaluateReducedModel(
return;
}
std::filesystem::create_directories(tilledPatternResultsFolderPath);
const std::filesystem::path drmResultsOutputPath
= std::filesystem::path(scenarioDirectoryPath).append(patternLabel);
const std::filesystem::path drmResultsOutputPath =
std::filesystem::path(scenarioDirectoryPath).append(patternLabel);
simulationResults_tilledPattern.save(drmResultsOutputPath);
LinearSimulationModel linearSimulationModel;
SimulationResults simulationResults_tiledReducedModel
= linearSimulationModel.executeSimulation(pJob_tiledReducedPattern);
// LinearSimulationModel linearSimulationModel;
SimulationModelFactory factory;
std::unique_ptr<SimulationModel> pSimulationModel_tilledReducedModel =
factory.create(simulationModelLabel_reducedModel);
SimulationResults simulationResults_tiledReducedModel =
pSimulationModel_tilledReducedModel->executeSimulation(
pJob_tiledReducedModel);
// ChronosEulerNonLinearSimulationModel
// debug_chronosNonLinearSimulationModel;
// const auto debug_chronosResults =
// debug_chronosNonLinearSimulationModel.executeSimulation(
// pJob_tilledPattern);
// LinearSimulationModel debug_linearSimulationModel;
// const auto debug_linearSimResults =
// debug_linearSimulationModel.executeSimulation(pJob_tilledPattern);
#ifdef POLYSCOPE_DEFINED
simulationResults_tiledReducedModel.registerForDrawing();
simulationResults_tilledPattern.registerForDrawing();
if (shouldDrawScenarioResults) {
simulationResults_tiledReducedModel.registerForDrawing(
ReducedModelOptimization::Colors::reducedDeformed, true,
simulationResults_tilledPattern.pJob->pMesh
->getBeamDimensions()[0]
.getDrawingRadius());
simulationResults_tilledPattern.registerForDrawing(
ReducedModelOptimization::Colors::patternDeformed);
// debug_chronosResults.registerForDrawing();
// debug_linearSimResults.registerForDrawing();
polyscope::show();
// debug_linearSimResults.unregister();
simulationResults_tiledReducedModel.unregister();
simulationResults_tilledPattern.unregister();
// debug_chronosResults.unregister();
}
#endif
// compute the full2reduced distance
const double distance_patternToReduced
= simulationResults_tilledPattern
.computeDistance(simulationResults_tiledReducedModel, fullToReducedViMap);
const double distance_patternToReduced =
simulationResults_tilledPattern.computeDistance(
simulationResults_tiledReducedModel, fullToReducedViMap);
double distance_patternSumOfAllVerts = 0;
for (std::pair<size_t, size_t> fullToReducedPair : fullToReducedViMap) {
distance_patternSumOfAllVerts += simulationResults_tilledPattern
distance_patternSumOfAllVerts +=
simulationResults_tilledPattern
.displacements[fullToReducedPair.first]
.getTranslation()
.norm();
}
const double distance_normalizedPatternToReduced = distance_patternToReduced
/ distance_patternSumOfAllVerts;
const double distance_normalizedPatternToReduced =
distance_patternToReduced / distance_patternSumOfAllVerts;
const int jobIndex = &jobLabel - &scenariosTestSetLabels[0];
evaluationResults.distances_drm2reduced[jobIndex] = distance_patternToReduced;
evaluationResults.distances_normalizedDrm2reduced[jobIndex]
= distance_normalizedPatternToReduced;
evaluationResults.distances_drm2reduced[jobIndex] =
distance_patternToReduced;
evaluationResults.distances_normalizedDrm2reduced[jobIndex] =
distance_normalizedPatternToReduced;
});
return evaluationResults;

View File

@ -2,9 +2,9 @@
#define REDUCEDMODELEVALUATOR_HPP
#include "reducedmodeloptimizer_structs.hpp"
#include "utilities.hpp"
class ReducedModelEvaluator
{
class ReducedModelEvaluator {
public:
enum CSVExportingDirection { Vertical = 0, Horizontal };
enum CSVExportingData {
@ -14,9 +14,9 @@ public:
NumberOfDataTypes
};
inline static std::array<std::string, NumberOfDataTypes>
csvExportingDataStrings{"raw_drm2Reduced", "norm_drm2Reduced", "raw_and_norm_drm2Reduced"};
struct Settings
{
csvExportingDataStrings{"raw_drm2Reduced", "norm_drm2Reduced",
"raw_and_norm_drm2Reduced"};
struct Settings {
CSVExportingDirection exportingDirection{Horizontal};
CSVExportingData exportingData{norm_drm2Reduced};
bool shouldWriteHeader{true};
@ -24,11 +24,12 @@ public:
};
inline static constexpr int NumberOfEvaluationScenarios{22};
struct Results
{
struct Results {
std::array<double, NumberOfEvaluationScenarios> distances_drm2reduced;
std::array<double, NumberOfEvaluationScenarios> distances_normalizedDrm2reduced;
std::array<std::string, NumberOfEvaluationScenarios> evaluationScenarioLabels;
std::array<double, NumberOfEvaluationScenarios>
distances_normalizedDrm2reduced;
std::array<std::string, NumberOfEvaluationScenarios>
evaluationScenarioLabels;
};
ReducedModelEvaluator();
Results evaluateReducedModel(
@ -36,40 +37,35 @@ public:
const std::filesystem::path& scenariosDirectoryPath,
// const std::filesystem::path &reducedPatternFilePath,
const std::filesystem::path& fullPatternTessellatedResultsDirectoryPath);
Results evaluateReducedModel(ReducedModelOptimization::Results &optimizationResult);
static void printResultsVertically(const ReducedModelEvaluator::Results &evaluationResults,
Results evaluateReducedModel(
ReducedModelOptimization::Results& optimizationResult);
static void printResultsVertically(
const ReducedModelEvaluator::Results& evaluationResults,
csvFile& csvOutput);
static void printResults(const ReducedModelEvaluator::Results &evaluationResults,
static void printResults(
const ReducedModelEvaluator::Results& evaluationResults,
const std::string& resultsLabel);
inline static std::array<std::string, NumberOfEvaluationScenarios> scenariosTestSetLabels{
"22Hex_randomBending0",
"22Hex_randomBending1",
inline static std::array<std::string, NumberOfEvaluationScenarios>
scenariosTestSetLabels{
"22Hex_randomBending0", "22Hex_randomBending1",
"22Hex_randomBending2",
// "22Hex_randomBending3",
"22Hex_randomBending4",
"22Hex_randomBending5",
"22Hex_randomBending4", "22Hex_randomBending5",
// "22Hex_randomBending6",
// "22Hex_randomBending7",
"22Hex_randomBending8",
"22Hex_randomBending9",
"22Hex_randomBending10",
"22Hex_randomBending11",
"22Hex_randomBending8", "22Hex_randomBending9",
"22Hex_randomBending10", "22Hex_randomBending11",
"22Hex_randomBending12",
// "22Hex_randomBending13",
// "22Hex_randomBending14",
// "22Hex_randomBending15",
"22Hex_randomBending16",
"22Hex_randomBending17",
"22Hex_randomBending18",
"22Hex_randomBending19",
"22Hex_randomBending16", "22Hex_randomBending17",
"22Hex_randomBending18", "22Hex_randomBending19",
// "22Hex_randomBending20",
"22Hex_bending_0.005N",
"22Hex_bending_0.01N",
"22Hex_bending_0.03N",
"22Hex_bending_0.005N", "22Hex_bending_0.01N", "22Hex_bending_0.03N",
// "22Hex_bending_0.05N",
"22Hex_pullOppositeVerts_0.05N",
"22Hex_pullOppositeVerts_0.1N",
"22Hex_pullOppositeVerts_0.05N", "22Hex_pullOppositeVerts_0.1N",
// "22Hex_pullOppositeVerts_0.3N",
//#ifdef POLYSCOPE_DEFINED
// "22Hex_shear_2N",
@ -82,12 +78,11 @@ public:
// "notUsed_22Hex_axial_10N",
// "notUsed_22Hex_axial_20N",
//#endif
"22Hex_cylinder_0.05N",
"22Hex_cylinder_0.1N",
"22Hex_s_0.05N",
"22Hex_cylinder_0.05N", "22Hex_cylinder_0.1N", "22Hex_s_0.05N",
// "22Hex_s_0.1N"
};
static void printResultsHorizontally(const Results &evaluationResults, csvFile &csvOutput);
static void printResultsHorizontally(const Results& evaluationResults,
csvFile& csvOutput);
static void printResults(const Results& evaluationResults,
const Settings& settings,
csvFile& csvOutput);
@ -95,8 +90,17 @@ public:
// static double evaluateOptimizationSettings(
// const ReducedModelOptimization::Settings &optimizationSettings,
// const std::vector<std::shared_ptr<PatternGeometry>> &pPatterns,
// std::vector<ReducedModelEvaluator::Results> &patternEvaluationResults);
// std::vector<ReducedModelEvaluator::Results>
// &patternEvaluationResults);
std::shared_ptr<VCGPolyMesh> pTileIntoSurface;
ReducedModelOptimization::Colors::RGBColor color_tesselatedPatterns{
24.0 / 255, 23.0 / 255, 23.0 / 255};
ReducedModelOptimization::Colors::RGBColor color_tesselatedReducedModels{
67.0 / 255, 160.00 / 255, 232.0 / 255};
ReducedModelOptimization::Colors::RGBColor color_tileIntoSurface{
222 / 255.0, 235 / 255.0, 255 / 255.0};
ReducedModelOptimization::Colors::RGBColor interfaceNodes_color{
63.0 / 255, 85.0 / 255, 42.0 / 255};
inline static constexpr char* tileIntoSurfaceFileContent = R"~(OFF
46 66 0
-0.0745923 0.03573945 0

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +1,17 @@
#ifndef REDUCEDMODELOPTIMIZER_HPP
#define REDUCEDMODELOPTIMIZER_HPP
#include "chronoseulersimulationmodel.hpp"
#include "csvfile.hpp"
//#include "csvfile.hpp"
#include "drmsimulationmodel.hpp"
#include "edgemesh.hpp"
#include "linearsimulationmodel.hpp"
#ifdef POLYSCOPE_DEFINED
#include "matplot/matplot.h"
#endif
#include <Eigen/Dense>
#include "reducedmodel.hpp"
#include "reducedmodeloptimizer_structs.hpp"
#include "simulationmesh.hpp"
#include <Eigen/Dense>
#ifdef DLIB_DEFINED
#include <dlib/global_optimization.h>
#include <dlib/optimization.h>
@ -21,32 +20,32 @@
#ifdef POLYSCOPE_DEFINED
#include "polyscope/color_management.h"
#endif // POLYSCOPE_DEFINED
using FullPatternVertexIndex = VertexIndex;
using ReducedPatternVertexIndex = VertexIndex;
using PatternVertexIndex = VertexIndex;
using ReducedModelVertexIndex = VertexIndex;
class ReducedModelOptimizer
{
class ReducedModelOptimizer {
public:
struct OptimizationState
{
struct OptimizationState {
std::vector<SimulationResults> fullPatternResults;
std::vector<double> translationalDisplacementNormalizationValues;
std::vector<double> rotationalDisplacementNormalizationValues;
std::vector<std::shared_ptr<SimulationJob>> fullPatternSimulationJobs;
std::vector<std::shared_ptr<SimulationJob>> reducedPatternSimulationJobs;
std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
std::vector<std::shared_ptr<SimulationJob>> pSimulationJobs_pattern;
std::vector<std::shared_ptr<SimulationJob>> simulationJobs_reducedModel;
std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>
reducedToFullInterfaceViMap;
std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>
fullPatternOppositeInterfaceViPairs;
matplot::line_handle gPlotHandle;
std::vector<size_t> objectiveValueHistory_iteration;
std::vector<double> objectiveValueHistory;
std::vector<double> plotColors;
std::array<double,
ReducedModelOptimization::OptimizationParameterIndex::NumberOfOptimizationVariables>
ReducedModelOptimization::OptimizationParameterIndex::
NumberOfOptimizationVariables>
parametersInitialValue;
std::array<double,
ReducedModelOptimization::OptimizationParameterIndex::NumberOfOptimizationVariables>
ReducedModelOptimization::OptimizationParameterIndex::
NumberOfOptimizationVariables>
optimizationInitialValue;
std::vector<int> simulationScenarioIndices;
double minY{DBL_MAX};
@ -54,50 +53,51 @@ public:
int numOfSimulationCrashes{false};
int numberOfFunctionCalls{0};
// Variables for finding the full pattern simulation forces
std::shared_ptr<SimulationMesh> pFullPatternSimulationMesh;
std::shared_ptr<SimulationEdgeMesh> pFullPatternSimulationEdgeMesh;
std::array<std::function<void(const double& newValue,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>,
std::shared_ptr<SimulationEdgeMesh>&
pReducedPatternSimulationEdgeMesh)>,
7>
functions_updateReducedPatternParameter;
std::vector<double> xMin;
std::vector<double> xMax;
std::vector<double> scenarioWeights;
std::vector<ReducedModelOptimization::Settings::ObjectiveWeights> objectiveWeights;
std::vector<ReducedModelOptimization::Settings::ObjectiveWeights>
objectiveWeights;
std::string simulationModelLabel_reducedModel;
};
private:
OptimizationState optimizationState;
vcg::Triangle3<double> baseTriangle;
std::function<void(const double &,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>> &,
std::function<void(
const double&,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&,
SimulationJob&)>
constructScenarioFunction;
std::shared_ptr<SimulationMesh> m_pReducedModelSimulationMesh;
std::shared_ptr<SimulationMesh> m_pFullPatternSimulationMesh;
std::unordered_map<FullPatternVertexIndex, ReducedPatternVertexIndex>
std::shared_ptr<SimulationEdgeMesh> m_pReducedModelSimulationEdgeMesh;
std::shared_ptr<SimulationEdgeMesh> m_pSimulationEdgeMesh_pattern;
std::unordered_map<PatternVertexIndex, ReducedModelVertexIndex>
m_fullToReducedInterfaceViMap;
std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>
m_fullPatternOppositeInterfaceViPairs;
std::unordered_map<size_t, size_t> nodeToSlot;
std::unordered_map<size_t, std::unordered_set<size_t>> slotToNode;
std::string optimizationNotes;
std::array<std::function<void(
std::array<
std::function<void(
const double&,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>> &,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&,
SimulationJob&)>,
ReducedModelOptimization::NumberOfBaseSimulationScenarios>
constructBaseScenarioFunctions;
std::vector<bool> scenarioIsSymmetrical;
int fullPatternNumberOfEdges;
constexpr static double youngsModulus{1 * 1e9};
constexpr static double defaultBeamWidth{0.002};
constexpr static double defaultBeamHeight{0.002};
std::string fullPatternLabel;
// ReducedModelOptimization::Settings optimizationSettings;
public:
struct FunctionEvaluation
{
struct FunctionEvaluation {
FunctionEvaluation() = default;
FunctionEvaluation(const std::vector<double>& x, double y) : x(x), y(y) {}
@ -117,18 +117,24 @@ public:
// };
// inline constexpr static ParameterLabels parameterLabels();
inline static std::array<std::string, ReducedModelOptimization::NumberOfOptimizationVariables>
inline static std::array<
std::string,
ReducedModelOptimization::NumberOfOptimizationVariables>
parameterLabels = {"E", "A", "I2", "I3", "J", "Theta", "R"};
constexpr static std::array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
constexpr static std::
array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
simulationScenariosResolution = {12, 12, 22, 22, 22, 22};
constexpr static std::array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
// simulationScenariosResolution = {2, 2, 2, 22, 22, 22};
constexpr static std::
array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
baseScenarioWeights = {1, 1, 2, 2, 2};
inline static int totalNumberOfSimulationScenarios
= std::accumulate(simulationScenariosResolution.begin(),
inline static int totalNumberOfSimulationScenarios =
std::accumulate(simulationScenariosResolution.begin(),
simulationScenariosResolution.end(),
0);
inline static int fanSize{6};
inline static double initialHexagonSize{0.3};
inline static int fanCardinality{6};
inline static double initialValue_R{0.3};
inline static double initialValue_theta{0};
int interfaceNodeIndex;
double operator()(const Eigen::VectorXd& x, Eigen::VectorXd&) const;
@ -138,128 +144,145 @@ public:
const std::unordered_map<size_t, size_t>& fullToReducedMap,
SimulationJob& simulationJobOfReducedModel);
SimulationJob getReducedSimulationJob(const SimulationJob &fullModelSimulationJob);
SimulationJob getReducedSimulationJob(
const SimulationJob& fullModelSimulationJob);
static void runSimulation(const std::string &filename, std::vector<double> &x);
static void runSimulation(const std::string& filename,
std::vector<double>& x);
static std::vector<std::shared_ptr<SimulationJob>> createFullPatternSimulationJobs(
const std::shared_ptr<SimulationMesh> &pMesh,
const std::unordered_map<size_t, size_t> &fullPatternOppositeInterfaceViMap);
static std::vector<std::shared_ptr<SimulationJob>>
createFullPatternSimulationJobs(
const std::shared_ptr<SimulationEdgeMesh>& pMesh,
const std::unordered_map<size_t, size_t>&
fullPatternOppositeInterfaceViMap);
static void createSimulationMeshes(
static void createSimulationEdgeMeshes(
PatternGeometry& pattern,
PatternGeometry& reducedModel,
const RectangularBeamDimensions &beamDimensions,
std::shared_ptr<SimulationMesh> &pFullPatternSimulationMesh,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh);
void computeMaps(const std::unordered_map<size_t, std::unordered_set<size_t>> &slotToNode,
const ReducedModelOptimization::Settings& optimizationSettings,
std::shared_ptr<SimulationEdgeMesh>& pFullPatternSimulationEdgeMesh,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh);
void computeMaps(
const std::unordered_map<size_t, std::unordered_set<size_t>>& slotToNode,
PatternGeometry& fullPattern,
ReducedModel& reducedPattern,
std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap,
std::unordered_map<FullPatternVertexIndex, ReducedPatternVertexIndex>
&fullToReducedInterfaceViMap,
std::vector<std::pair<FullPatternVertexIndex, ReducedPatternVertexIndex>>
&fullPatternOppositeInterfaceViMap);
std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap,
std::unordered_map<PatternVertexIndex, ReducedModelVertexIndex>&
fullToReducedInterfaceViMap,
std::vector<std::pair<PatternVertexIndex, ReducedModelVertexIndex>>&
fullPatternOppositeInterfaceViMap);
static void visualizeResults(
const std::vector<std::shared_ptr<SimulationJob>> &fullPatternSimulationJobs,
const std::vector<std::shared_ptr<SimulationJob>> &reducedPatternSimulationJobs,
const std::vector<ReducedModelOptimization::BaseSimulationScenario> &simulationScenarios,
const std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap);
const std::vector<std::shared_ptr<SimulationJob>>&
fullPatternSimulationJobs,
const std::vector<std::shared_ptr<SimulationJob>>&
reducedPatternSimulationJobs,
const std::vector<ReducedModelOptimization::BaseSimulationScenario>&
simulationScenarios,
const std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap);
static void registerResultsForDrawing(
const std::shared_ptr<SimulationJob>& pFullPatternSimulationJob,
const std::shared_ptr<SimulationJob>& pReducedPatternSimulationJob,
const std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap);
const std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap);
static double computeRawTranslationalError(
const std::vector<Vector6d>& fullPatternDisplacements,
const std::vector<Vector6d>& reducedPatternDisplacements,
const std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap);
const std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap);
static double computeDisplacementError(
const std::vector<Vector6d>& fullPatternDisplacements,
const std::vector<Vector6d>& reducedPatternDisplacements,
const std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap,
const std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap,
const double& normalizationFactor);
static double computeRawRotationalError(
const std::vector<Eigen::Quaterniond>& rotatedQuaternion_fullPattern,
const std::vector<Eigen::Quaterniond>& rotatedQuaternion_reducedPattern,
const std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap);
const std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap);
static double computeRotationalError(const std::vector<Eigen::Quaterniond> &rotatedQuaternion_fullPattern,
static double computeRotationalError(
const std::vector<Eigen::Quaterniond>& rotatedQuaternion_fullPattern,
const std::vector<Eigen::Quaterniond>& rotatedQuaternion_reducedPattern,
const std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap,
const std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap,
const double& normalizationFactor);
static double computeError(
const SimulationResults& simulationResults_fullPattern,
const SimulationResults& simulationResults_reducedPattern,
const std::unordered_map<ReducedPatternVertexIndex, FullPatternVertexIndex>
&reducedToFullInterfaceViMap,
const std::unordered_map<ReducedModelVertexIndex, PatternVertexIndex>&
reducedToFullInterfaceViMap,
const double& normalizationFactor_translationalDisplacement,
const double& normalizationFactor_rotationalDisplacement,
const double& scenarioWeight,
const ReducedModelOptimization::Settings::ObjectiveWeights &objectiveWeights);
const ReducedModelOptimization::Settings::ObjectiveWeights&
objectiveWeights);
static void constructAxialSimulationScenario(
const double& forceMagnitude,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
&oppositeInterfaceViPairs,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&
oppositeInterfaceViPairs,
SimulationJob& job);
static void constructShearSimulationScenario(
const double& forceMagnitude,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
&oppositeInterfaceViPairs,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&
oppositeInterfaceViPairs,
SimulationJob& job);
static void constructBendingSimulationScenario(
const double& forceMagnitude,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
&oppositeInterfaceViPairs,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&
oppositeInterfaceViPairs,
SimulationJob& job);
static void constructDomeSimulationScenario(
const double& forceMagnitude,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
&oppositeInterfaceViPairs,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&
oppositeInterfaceViPairs,
SimulationJob& job);
static void constructSaddleSimulationScenario(
const double& forceMagnitude,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
&oppositeInterfaceViPairs,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&
oppositeInterfaceViPairs,
SimulationJob& job);
static void constructSSimulationScenario(
const double& forceMagnitude,
const std::vector<std::pair<FullPatternVertexIndex, FullPatternVertexIndex>>
&oppositeInterfaceViPairs,
const std::vector<std::pair<PatternVertexIndex, PatternVertexIndex>>&
oppositeInterfaceViPairs,
SimulationJob& job);
static std::function<void(const std::vector<double> &x,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
static std::function<void(
const std::vector<double>& x,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
function_updateReducedPattern;
static std::function<void(const double &newE,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
static std::function<void(
const double& newE,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
function_updateReducedPattern_material_E;
static std::function<void(const double &newA,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
static std::function<void(
const double& newA,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
function_updateReducedPattern_material_A;
static std::function<void(const double &newI,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
static std::function<void(
const double& newI,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
function_updateReducedPattern_material_I;
static std::function<void(const double &newI2,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
static std::function<void(
const double& newI2,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
function_updateReducedPattern_material_I2;
static std::function<void(const double &newI3,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
static std::function<void(
const double& newI3,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
function_updateReducedPattern_material_I3;
static std::function<void(const double &newJ,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
static std::function<void(
const double& newJ,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
function_updateReducedPattern_material_J;
static double objective(const std::vector<double>& x);
void initializeUpdateReducedPatternFunctions();
@ -272,15 +295,17 @@ public:
void optimize(ConstPatternGeometry& fullPattern,
ReducedModelOptimization::Settings& optimizationSettings,
ReducedModelOptimization::Results& optimizationResults);
static double objective(const std::vector<double> &x,
static double objective(
const std::vector<double>& x,
ReducedModelOptimizer::OptimizationState& optimizationState);
private:
void optimize(
ReducedModelOptimization::Settings& optimizationSettings,
ReducedModelOptimization::Results& results,
const std::vector<ReducedModelOptimization::BaseSimulationScenario> &simulationScenarios
= std::vector<ReducedModelOptimization::BaseSimulationScenario>(
const std::vector<ReducedModelOptimization::BaseSimulationScenario>&
simulationScenarios =
std::vector<ReducedModelOptimization::BaseSimulationScenario>(
{ReducedModelOptimization::Axial,
ReducedModelOptimization::Shear,
ReducedModelOptimization::Bending,
@ -288,7 +313,8 @@ private:
ReducedModelOptimization::Saddle,
ReducedModelOptimization::S}));
void initializePatterns(PatternGeometry &fullPattern,
void initializePatterns(
PatternGeometry& fullPattern,
ReducedModel& reducedModel,
const ReducedModelOptimization::Settings& optimizationSettings);
static void computeDesiredReducedModelDisplacements(
@ -298,17 +324,16 @@ private:
void runOptimization(const ReducedModelOptimization::Settings& settings,
ReducedModelOptimization::Results& results);
void computeMaps(PatternGeometry& fullModel, ReducedModel& reducedModel);
void createSimulationMeshes(PatternGeometry &fullModel,
void createSimulationEdgeMeshes(
PatternGeometry& fullModel,
PatternGeometry& reducedModel,
const RectangularBeamDimensions &beamDimensions);
const ReducedModelOptimization::Settings& optimizationSettings);
void initializeOptimizationParameters(
const std::shared_ptr<SimulationMesh> &mesh,
const std::shared_ptr<SimulationEdgeMesh>& mesh,
const std::array<ReducedModelOptimization::xRange,
ReducedModelOptimization::NumberOfOptimizationVariables>
&optimizationParamters);
ReducedModelOptimization::NumberOfOptimizationVariables>&
optimizationParamters);
ChronosEulerSimulationModel patternSimulator;
LinearSimulationModel reducedModelSimulator;
void computeObjectiveValueNormalizationFactors(
const ReducedModelOptimization::Settings& optimizationSettings);
@ -323,43 +348,53 @@ private:
#endif
std::array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
computeFullPatternMaxSimulationForces(
const std::vector<ReducedModelOptimization::BaseSimulationScenario>
&desiredBaseSimulationScenario) const;
const std::vector<ReducedModelOptimization::BaseSimulationScenario>&
desiredBaseSimulationScenario) const;
std::vector<std::shared_ptr<SimulationJob>> createFullPatternSimulationJobs(
const std::shared_ptr<SimulationMesh> &pMesh,
const std::array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
&baseScenarioMaxForceMagnitudes) const;
const std::shared_ptr<SimulationEdgeMesh>& pMesh,
const std::array<
double,
ReducedModelOptimization::NumberOfBaseSimulationScenarios>&
baseScenarioMaxForceMagnitudes) const;
std::array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
getFullPatternMaxSimulationForces(
const std::vector<ReducedModelOptimization::BaseSimulationScenario>
&desiredBaseSimulationScenarioIndices,
const std::vector<ReducedModelOptimization::BaseSimulationScenario>&
desiredBaseSimulationScenarioIndices,
const std::filesystem::path& intermediateResultsDirectoryPath,
const bool& recomputeForceMagnitudes);
std::array<double, ReducedModelOptimization::NumberOfBaseSimulationScenarios>
getFullPatternMaxSimulationForces();
void computeScenarioWeights(
const std::vector<ReducedModelOptimization::BaseSimulationScenario> &baseSimulationScenarios,
const std::vector<ReducedModelOptimization::BaseSimulationScenario>&
baseSimulationScenarios,
const ReducedModelOptimization::Settings& optimizationSettings);
};
inline std::function<void(const double &newE,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
inline std::function<void(
const double& newE,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
ReducedModelOptimizer::function_updateReducedPattern_material_E;
inline std::function<void(const double &newA,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
inline std::function<void(
const double& newA,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
ReducedModelOptimizer::function_updateReducedPattern_material_A;
inline std::function<void(const double &newI,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
inline std::function<void(
const double& newI,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
ReducedModelOptimizer::function_updateReducedPattern_material_I;
inline std::function<void(const double &newI2,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
inline std::function<void(
const double& newI2,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
ReducedModelOptimizer::function_updateReducedPattern_material_I2;
inline std::function<void(const double &newI3,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
inline std::function<void(
const double& newI3,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
ReducedModelOptimizer::function_updateReducedPattern_material_I3;
inline std::function<void(const double &newJ,
std::shared_ptr<SimulationMesh> &pReducedPatternSimulationMesh)>
inline std::function<void(
const double& newJ,
std::shared_ptr<SimulationEdgeMesh>& pReducedPatternSimulationEdgeMesh)>
ReducedModelOptimizer::function_updateReducedPattern_material_J;
inline std::function<void(const std::vector<double> &x, std::shared_ptr<SimulationMesh> &m)>
inline std::function<void(const std::vector<double>& x,
std::shared_ptr<SimulationEdgeMesh>& m)>
ReducedModelOptimizer::function_updateReducedPattern;
extern ReducedModelOptimizer::OptimizationState global;

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,13 @@
#include "topologyenumerator.hpp"
#include <math.h>
#include <algorithm>
#include <boost/graph/biconnected_components.hpp>
#include <iostream>
#include <math.h>
#include <numeric>
#include <thread>
#include <unordered_set>
const bool debugIsOn{false};
const bool debugIsOn{true};
const bool savePlyFiles{true};
// size_t binomialCoefficient(size_t n, size_t m) {
@ -34,8 +35,7 @@ const bool savePlyFiles{true};
// .string());
//}
size_t TopologyEnumerator::getEdgeIndex(size_t ni0, size_t ni1) const
{
size_t TopologyEnumerator::getEdgeIndex(size_t ni0, size_t ni1) const {
if (ni1 <= ni0) {
std::swap(ni0, ni1);
}
@ -46,30 +46,35 @@ size_t TopologyEnumerator::getEdgeIndex(size_t ni0, size_t ni1) const
TopologyEnumerator::TopologyEnumerator() {}
void TopologyEnumerator::computeValidPatterns(const std::vector<size_t> &reducedNumberOfNodesPerSlot,
void TopologyEnumerator::computeValidPatterns(
const std::vector<size_t>& reducedNumberOfNodesPerSlot,
const std::string& desiredResultsPath,
const int &numberOfDesiredEdges)
{
const int& numberOfDesiredEdges) {
assert(reducedNumberOfNodesPerSlot.size() == 5);
assert(reducedNumberOfNodesPerSlot[0] == 0 || reducedNumberOfNodesPerSlot[0] == 1);
assert(reducedNumberOfNodesPerSlot[1] == 0 || reducedNumberOfNodesPerSlot[1] == 1);
std::vector<size_t> numberOfNodesPerSlot{reducedNumberOfNodesPerSlot[0],
reducedNumberOfNodesPerSlot[1],
reducedNumberOfNodesPerSlot[1],
reducedNumberOfNodesPerSlot[2],
reducedNumberOfNodesPerSlot[3],
reducedNumberOfNodesPerSlot[2],
assert(reducedNumberOfNodesPerSlot[0] == 0 ||
reducedNumberOfNodesPerSlot[0] == 1);
assert(reducedNumberOfNodesPerSlot[1] == 0 ||
reducedNumberOfNodesPerSlot[1] == 1);
std::vector<size_t> numberOfNodesPerSlot{
reducedNumberOfNodesPerSlot[0], reducedNumberOfNodesPerSlot[1],
reducedNumberOfNodesPerSlot[1], reducedNumberOfNodesPerSlot[2],
reducedNumberOfNodesPerSlot[3], reducedNumberOfNodesPerSlot[2],
reducedNumberOfNodesPerSlot[4]};
// Generate an edge mesh wih all possible edges
numberOfNodes = std::accumulate(numberOfNodesPerSlot.begin(), numberOfNodesPerSlot.end(), 0);
const size_t numberOfAllPossibleEdges = numberOfNodes * (numberOfNodes - 1) / 2;
numberOfNodes = std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.end(), 0);
const size_t numberOfAllPossibleEdges =
numberOfNodes * (numberOfNodes - 1) / 2;
std::vector<vcg::Point2i> allPossibleEdges(numberOfAllPossibleEdges);
const int& n = numberOfNodes;
for (size_t edgeIndex = 0; edgeIndex < numberOfAllPossibleEdges; edgeIndex++) {
const int ni0 = n - 2
- std::floor(std::sqrt(-8 * edgeIndex + 4 * n * (n - 1) - 7) / 2.0 - 0.5);
const int ni1 = edgeIndex + ni0 + 1 - n * (n - 1) / 2 + (n - ni0) * ((n - ni0) - 1) / 2;
for (size_t edgeIndex = 0; edgeIndex < numberOfAllPossibleEdges;
edgeIndex++) {
const int ni0 =
n - 2 -
std::floor(std::sqrt(-8 * edgeIndex + 4 * n * (n - 1) - 7) / 2.0 - 0.5);
const int ni1 =
edgeIndex + ni0 + 1 - n * (n - 1) / 2 + (n - ni0) * ((n - ni0) - 1) / 2;
allPossibleEdges[edgeIndex] = vcg::Point2i(ni0, ni1);
}
PatternGeometry patternGeometryAllEdges;
@ -88,13 +93,15 @@ void TopologyEnumerator::computeValidPatterns(const std::vector<size_t> &reduced
std::string elemID;
if (numberOfNodesPerSlotIndex == 0 || numberOfNodesPerSlotIndex == 1) {
elemID = "v";
} else if (numberOfNodesPerSlotIndex == 2 || numberOfNodesPerSlotIndex == 3) {
} else if (numberOfNodesPerSlotIndex == 2 ||
numberOfNodesPerSlotIndex == 3) {
elemID = "e";
} else {
elemID = "c";
}
setupString += std::to_string(reducedNumberOfNodesPerSlot[numberOfNodesPerSlotIndex])
+ elemID + "_";
setupString +=
std::to_string(reducedNumberOfNodesPerSlot[numberOfNodesPerSlotIndex]) +
elemID + "_";
}
setupString += std::to_string(PatternGeometry().getFanSize()) + "fan";
if (debugIsOn) {
@ -105,34 +112,39 @@ void TopologyEnumerator::computeValidPatterns(const std::vector<size_t> &reduced
std::filesystem::create_directory(resultsPath);
if (debugIsOn) {
patternGeometryAllEdges.save(
std::filesystem::path(resultsPath).append("allPossibleEdges.ply").string());
patternGeometryAllEdges.save(std::filesystem::path(resultsPath)
.append("allPossibleEdges.ply")
.string());
}
// statistics.numberOfPossibleEdges = numberOfAllPossibleEdges;
std::vector<vcg::Point2i> validEdges = getValidEdges(numberOfNodesPerSlot,
resultsPath,
patternGeometryAllEdges,
std::vector<vcg::Point2i> validEdges =
getValidEdges(numberOfNodesPerSlot, resultsPath, patternGeometryAllEdges,
allPossibleEdges);
PatternGeometry patternAllValidEdges;
patternAllValidEdges.add(patternGeometryAllEdges.computeVertices(), validEdges);
patternAllValidEdges.add(patternGeometryAllEdges.computeVertices(),
validEdges);
if (debugIsOn) {
// Export all valid edges in a ply
patternAllValidEdges.save(
std::filesystem::path(resultsPath).append("allValidEdges.ply").string());
patternAllValidEdges.save(std::filesystem::path(resultsPath)
.append("allValidEdges.ply")
.string());
}
// statistics.numberOfValidEdges = validEdges.size();
// Find pairs of intersecting edges
const std::unordered_map<size_t, std::unordered_set<size_t>> intersectingEdges
= patternAllValidEdges.getIntersectingEdges(statistics.numberOfIntersectingEdgePairs);
const std::unordered_map<size_t, std::unordered_set<size_t>>
intersectingEdges = patternAllValidEdges.getIntersectingEdges(
statistics.numberOfIntersectingEdgePairs);
if (debugIsOn) {
auto intersectingEdgesPath = std::filesystem::path(resultsPath)
.append("All_intersecting_edge_pairs");
std::filesystem::create_directory(intersectingEdgesPath);
// Export intersecting pairs in ply files
for (auto mapIt = intersectingEdges.begin(); mapIt != intersectingEdges.end(); mapIt++) {
for (auto setIt = mapIt->second.begin(); setIt != mapIt->second.end(); setIt++) {
for (auto mapIt = intersectingEdges.begin();
mapIt != intersectingEdges.end(); mapIt++) {
for (auto setIt = mapIt->second.begin(); setIt != mapIt->second.end();
setIt++) {
PatternGeometry intersectingEdgePair;
const size_t ei0 = mapIt->first;
const size_t ei1 = *setIt;
@ -145,15 +157,16 @@ void TopologyEnumerator::computeValidPatterns(const std::vector<size_t> &reduced
patternGeometryAllEdges.computeVertices()[validEdges[ei1][0]],
patternGeometryAllEdges.computeVertices()[validEdges[ei1][1]]);
intersectingEdgePair.save(std::filesystem::path(intersectingEdgesPath)
.append(std::to_string(mapIt->first) + "_"
+ std::to_string(*setIt) + ".ply")
.append(std::to_string(mapIt->first) +
"_" + std::to_string(*setIt) +
".ply")
.string());
}
}
}
const std::unordered_set<VertexIndex> interfaceNodes = patternGeometryAllEdges.getInterfaceNodes(
numberOfNodesPerSlot);
const std::unordered_set<VertexIndex> interfaceNodes =
patternGeometryAllEdges.getInterfaceNodes(numberOfNodesPerSlot);
// assert(validEdges.size() == allPossibleEdges.size() -
// coincideEdges.size() -
@ -174,9 +187,10 @@ void TopologyEnumerator::computeValidPatterns(const std::vector<size_t> &reduced
// std::filesystem::path(resultsPath).append("patterns.patt"));
// }
if (numberOfDesiredEdges == -1) {
for (size_t numberOfEdges = 2; numberOfEdges <= validEdges.size(); numberOfEdges++) {
std::cout << "Computing " + setupString << " with " << numberOfEdges << " edges."
<< std::endl;
for (size_t numberOfEdges = 2; numberOfEdges <= validEdges.size();
numberOfEdges++) {
std::cout << "Computing " + setupString << " with " << numberOfEdges
<< " edges." << std::endl;
auto perEdgeResultPath = std::filesystem::path(resultsPath)
.append(std::to_string(numberOfEdges));
@ -189,19 +203,16 @@ void TopologyEnumerator::computeValidPatterns(const std::vector<size_t> &reduced
// }
}
std::filesystem::create_directory(perEdgeResultPath);
computeValidPatterns(numberOfNodesPerSlot,
numberOfEdges,
computeValidPatterns(numberOfNodesPerSlot, numberOfEdges,
perEdgeResultPath,
patternGeometryAllEdges.computeVertices(),
intersectingEdges,
validEdges,
interfaceNodes);
intersectingEdges, validEdges, interfaceNodes);
statistics.print(setupString, perEdgeResultPath);
statistics.reset();
}
} else {
std::cout << "Computing " + setupString << " with " << numberOfDesiredEdges << " edges."
<< std::endl;
std::cout << "Computing " + setupString << " with " << numberOfDesiredEdges
<< " edges." << std::endl;
auto perEdgeResultPath = std::filesystem::path(resultsPath)
.append(std::to_string(numberOfDesiredEdges));
@ -210,22 +221,19 @@ void TopologyEnumerator::computeValidPatterns(const std::vector<size_t> &reduced
std::filesystem::remove_all(perEdgeResultPath);
}
std::filesystem::create_directory(perEdgeResultPath);
computeValidPatterns(numberOfNodesPerSlot,
numberOfDesiredEdges,
computeValidPatterns(numberOfNodesPerSlot, numberOfDesiredEdges,
perEdgeResultPath,
patternGeometryAllEdges.computeVertices(),
intersectingEdges,
validEdges,
interfaceNodes);
intersectingEdges, validEdges, interfaceNodes);
statistics.print(setupString, perEdgeResultPath);
}
}
void TopologyEnumerator::computeEdgeNodes(const std::vector<size_t> &numberOfNodesPerSlot,
void TopologyEnumerator::computeEdgeNodes(
const std::vector<size_t>& numberOfNodesPerSlot,
std::vector<size_t>& nodesEdge0,
std::vector<size_t>& nodesEdge1,
std::vector<size_t> &nodesEdge2)
{
std::vector<size_t>& nodesEdge2) {
// Create vectors holding the node indices of each pattern node of each
// triangle edge
size_t nodeIndex = 0;
@ -238,18 +246,21 @@ void TopologyEnumerator::computeEdgeNodes(const std::vector<size_t> &numberOfNod
nodesEdge2.push_back(nodeIndex++);
if (numberOfNodesPerSlot[3] != 0) {
for (size_t edgeNodeIndex = 0; edgeNodeIndex < numberOfNodesPerSlot[3]; edgeNodeIndex++) {
for (size_t edgeNodeIndex = 0; edgeNodeIndex < numberOfNodesPerSlot[3];
edgeNodeIndex++) {
nodesEdge0.push_back(nodeIndex++);
}
}
if (numberOfNodesPerSlot[4] != 0) {
for (size_t edgeNodeIndex = 0; edgeNodeIndex < numberOfNodesPerSlot[4]; edgeNodeIndex++) {
for (size_t edgeNodeIndex = 0; edgeNodeIndex < numberOfNodesPerSlot[4];
edgeNodeIndex++) {
nodesEdge1.push_back(nodeIndex++);
}
}
if (numberOfNodesPerSlot[5] != 0) {
for (size_t edgeNodeIndex = 0; edgeNodeIndex < numberOfNodesPerSlot[5]; edgeNodeIndex++) {
for (size_t edgeNodeIndex = 0; edgeNodeIndex < numberOfNodesPerSlot[5];
edgeNodeIndex++) {
nodesEdge2.push_back(nodeIndex++);
}
}
@ -265,8 +276,7 @@ void TopologyEnumerator::computeEdgeNodes(const std::vector<size_t> &numberOfNod
}
std::unordered_set<size_t> TopologyEnumerator::computeCoincideEdges(
const std::vector<size_t> &numberOfNodesPerSlot)
{
const std::vector<size_t>& numberOfNodesPerSlot) {
/*
* A coincide edge is defined as an edge connection between two nodes that lay
* on a triangle edge and which have another node in between
@ -279,12 +289,11 @@ std::unordered_set<size_t> TopologyEnumerator::computeCoincideEdges(
std::vector<size_t> coincideEdges0 = getCoincideEdges(nodesEdge0);
std::vector<size_t> coincideEdges1 = getCoincideEdges(nodesEdge1);
std::vector<size_t> coincideEdges2 = getCoincideEdges(nodesEdge2);
std::unordered_set<size_t> coincideEdges{coincideEdges0.begin(), coincideEdges0.end()};
std::copy(coincideEdges1.begin(),
coincideEdges1.end(),
std::unordered_set<size_t> coincideEdges{coincideEdges0.begin(),
coincideEdges0.end()};
std::copy(coincideEdges1.begin(), coincideEdges1.end(),
std::inserter(coincideEdges, coincideEdges.end()));
std::copy(coincideEdges2.begin(),
coincideEdges2.end(),
std::copy(coincideEdges2.begin(), coincideEdges2.end(),
std::inserter(coincideEdges, coincideEdges.end()));
if (numberOfNodesPerSlot[0] && numberOfNodesPerSlot[1]) {
@ -300,8 +309,7 @@ std::unordered_set<size_t> TopologyEnumerator::computeCoincideEdges(
}
std::unordered_set<size_t> TopologyEnumerator::computeDuplicateEdges(
const std::vector<size_t> &numberOfNodesPerSlot)
{
const std::vector<size_t>& numberOfNodesPerSlot) {
/*
* A duplicate edges are all edges the "right" edge since due to rotational
* symmetry "left" edge=="right" edge
@ -312,7 +320,8 @@ std::unordered_set<size_t> TopologyEnumerator::computeDuplicateEdges(
std::vector<size_t> nodesEdge2; // right edge
computeEdgeNodes(numberOfNodesPerSlot, nodesEdge0, nodesEdge1, nodesEdge2);
if (numberOfNodesPerSlot[5]) {
for (size_t edge2NodeIndex = 0; edge2NodeIndex < nodesEdge2.size() - 1; edge2NodeIndex++) {
for (size_t edge2NodeIndex = 0; edge2NodeIndex < nodesEdge2.size() - 1;
edge2NodeIndex++) {
const size_t nodeIndex = nodesEdge2[edge2NodeIndex];
const size_t nextNodeIndex = nodesEdge2[edge2NodeIndex + 1];
duplicateEdges.insert(getEdgeIndex(nodeIndex, nextNodeIndex));
@ -326,15 +335,17 @@ std::vector<vcg::Point2i> TopologyEnumerator::getValidEdges(
const std::vector<size_t>& numberOfNodesPerSlot,
const std::filesystem::path& resultsPath,
const PatternGeometry& patternGeometryAllEdges,
const std::vector<vcg::Point2i> &allPossibleEdges)
{
std::unordered_set<size_t> coincideEdges = computeCoincideEdges(numberOfNodesPerSlot);
const std::vector<vcg::Point2i>& allPossibleEdges) {
std::unordered_set<size_t> coincideEdges =
computeCoincideEdges(numberOfNodesPerSlot);
// Export each coincide edge into a ply file
if (!coincideEdges.empty() && debugIsOn) {
auto coincideEdgesPath = std::filesystem::path(resultsPath).append("Coincide_edges");
auto coincideEdgesPath =
std::filesystem::path(resultsPath).append("Coincide_edges");
std::filesystem::create_directories(coincideEdgesPath);
for (auto coincideEdgeIndex : coincideEdges) {
PatternGeometry::EdgeType e = patternGeometryAllEdges.edge[coincideEdgeIndex];
PatternGeometry::EdgeType e =
patternGeometryAllEdges.edge[coincideEdgeIndex];
PatternGeometry singleEdgeMesh;
vcg::Point3d p0 = e.cP(0);
vcg::Point3d p1 = e.cP(1);
@ -345,34 +356,40 @@ std::vector<vcg::Point2i> TopologyEnumerator::getValidEdges(
singleEdgeMesh.add(std::vector<vcg::Point2i>{vcg::Point2i{0, 1}});
singleEdgeMesh.save(std::filesystem::path(coincideEdgesPath)
.append(std::to_string(coincideEdgeIndex))
.string()
+ ".ply");
.string() +
".ply");
}
}
statistics.numberOfCoincideEdges = coincideEdges.size();
// Compute duplicate edges
std::unordered_set<size_t> duplicateEdges = computeDuplicateEdges(numberOfNodesPerSlot);
std::unordered_set<size_t> duplicateEdges =
computeDuplicateEdges(numberOfNodesPerSlot);
if (!duplicateEdges.empty() && debugIsOn) {
// Export duplicate edges in a single ply file
auto duplicateEdgesPath = std::filesystem::path(resultsPath).append("duplicate");
auto duplicateEdgesPath =
std::filesystem::path(resultsPath).append("duplicate");
std::filesystem::create_directory(duplicateEdgesPath);
PatternGeometry patternDuplicateEdges;
for (auto duplicateEdgeIndex : duplicateEdges) {
PatternGeometry::EdgeType e = patternGeometryAllEdges.edge[duplicateEdgeIndex];
PatternGeometry::EdgeType e =
patternGeometryAllEdges.edge[duplicateEdgeIndex];
vcg::Point3d p0 = e.cP(0);
vcg::Point3d p1 = e.cP(1);
vcg::tri::Allocator<PatternGeometry>::AddEdge(patternDuplicateEdges, p0, p1);
vcg::tri::Allocator<PatternGeometry>::AddEdge(patternDuplicateEdges, p0,
p1);
}
patternDuplicateEdges.save(
std::filesystem::path(duplicateEdgesPath).append("duplicateEdges.ply").string());
patternDuplicateEdges.save(std::filesystem::path(duplicateEdgesPath)
.append("duplicateEdges.ply")
.string());
}
statistics.numberOfDuplicateEdges = duplicateEdges.size();
// Create the set of all possible edges without coincide and duplicate edges
std::vector<vcg::Point2i> validEdges;
for (size_t edgeIndex = 0; edgeIndex < allPossibleEdges.size(); edgeIndex++) {
if (coincideEdges.count(edgeIndex) == 0 && duplicateEdges.count(edgeIndex) == 0) {
if (coincideEdges.count(edgeIndex) == 0 &&
duplicateEdges.count(edgeIndex) == 0) {
validEdges.push_back(allPossibleEdges[edgeIndex]);
}
}
@ -382,15 +399,18 @@ std::vector<vcg::Point2i> TopologyEnumerator::getValidEdges(
void TopologyEnumerator::exportPattern(const std::filesystem::path& saveToPath,
PatternGeometry& patternGeometry,
const bool saveTilledPattern) const
{
const bool saveTilledPattern) const {
const std::string patternName = patternGeometry.getLabel();
std::filesystem::create_directory(saveToPath);
patternGeometry.save(std::filesystem::path(saveToPath).append(patternName).string() + ".ply");
patternGeometry.save(
std::filesystem::path(saveToPath).append(patternName).string() + ".ply");
if (saveTilledPattern) {
PatternGeometry tiledPatternGeometry = PatternGeometry::createTile(patternGeometry);
tiledPatternGeometry.save(
std::filesystem::path(saveToPath).append(patternName + "_tiled").string() + ".ply");
PatternGeometry tiledPatternGeometry =
PatternGeometry::createTile(patternGeometry);
tiledPatternGeometry.save(std::filesystem::path(saveToPath)
.append(patternName + "_tiled")
.string() +
".ply");
}
}
@ -399,10 +419,10 @@ void TopologyEnumerator::computeValidPatterns(
const size_t& numberOfDesiredEdges,
const std::filesystem::path& resultsPath,
const std::vector<vcg::Point3d>& allVertices,
const std::unordered_map<size_t, std::unordered_set<size_t>> &intersectingEdges,
const std::unordered_map<size_t, std::unordered_set<size_t>>&
intersectingEdges,
const std::vector<vcg::Point2i>& validEdges,
const std::unordered_set<VertexIndex> &interfaceNodes)
{
const std::unordered_set<VertexIndex>& interfaceNodes) {
assert(numberOfNodesPerSlot.size() == 7);
// Iterate over all patterns which have numberOfDesiredEdges edges from
// from the validEdges Identify patterns that contain dangling edges
@ -414,27 +434,33 @@ void TopologyEnumerator::computeValidPatterns(
assert(enoughValidEdgesExist);
// Create pattern result paths
const auto validPatternsPath = std::filesystem::path(resultsPath).append("Valid");
const bool validPathCreatedSuccesfully = std::filesystem::create_directories(validPatternsPath);
assert(validPathCreatedSuccesfully && std::filesystem::exists(validPatternsPath));
const auto validPatternsPath =
std::filesystem::path(resultsPath).append("Valid");
const bool validPathCreatedSuccesfully =
std::filesystem::create_directories(validPatternsPath);
assert(validPathCreatedSuccesfully &&
std::filesystem::exists(validPatternsPath));
// std::ofstream validPatternsFileStream;
// validPatternsFileStream.open(
// validPatternsPath.append("patterns.patt").string());
const std::string compressedPatternsFilePath
= std::filesystem::path(validPatternsPath).append("patterns.patt").string();
const std::string compressedPatternsFilePath =
std::filesystem::path(validPatternsPath).append("patterns.patt").string();
PatternIO::PatternSet patternSet;
patternSet.nodes = allVertices;
const int patternSetBufferSize = 10000;
const size_t numberOfPatterns = PatternGeometry::binomialCoefficient(validEdges.size(),
numberOfDesiredEdges);
const size_t numberOfPatterns = PatternGeometry::binomialCoefficient(
validEdges.size(), numberOfDesiredEdges);
statistics.numberOfPatterns = numberOfPatterns;
// Initialize pattern binary representation
std::string patternBinaryRepresentation;
patternBinaryRepresentation = std::string(numberOfDesiredEdges, '1');
patternBinaryRepresentation += std::string(validEdges.size() - numberOfDesiredEdges, '0');
std::sort(patternBinaryRepresentation.begin(), patternBinaryRepresentation.end());
patternBinaryRepresentation +=
std::string(validEdges.size() - numberOfDesiredEdges, '0');
std::sort(patternBinaryRepresentation.begin(),
patternBinaryRepresentation.end());
/*TODO: Performance could be improved by changing the patternGeometry with
* respect to the previous one. Maybe I could xor the binaryRepresentation
* to the previous one.*/
@ -445,8 +471,8 @@ void TopologyEnumerator::computeValidPatterns(
constexpr bool saveCompressedFormat = false;
do {
patternIndex++;
const std::string patternName = std::to_string(numberOfDesiredEdges) + "_"
+ std::to_string(patternIndex);
const std::string patternName = std::to_string(numberOfDesiredEdges) + "_" +
std::to_string(patternIndex);
// std::cout << "Pattern name:" + patternBinaryRepresentation <<
// std::endl; isValidPattern(patternBinaryRepresentation, validEdges,
// numberOfDesiredEdges);
@ -454,7 +480,8 @@ void TopologyEnumerator::computeValidPatterns(
// Compute the pattern edges from the binary representation
std::vector<vcg::Point2i> patternEdges(numberOfDesiredEdges);
size_t patternEdgeIndex = 0;
for (size_t validEdgeIndex = 0; validEdgeIndex < patternBinaryRepresentation.size();
for (size_t validEdgeIndex = 0;
validEdgeIndex < patternBinaryRepresentation.size();
validEdgeIndex++) {
if (patternBinaryRepresentation[validEdgeIndex] == '1') {
assert(patternEdgeIndex < numberOfDesiredEdges);
@ -462,96 +489,124 @@ void TopologyEnumerator::computeValidPatterns(
}
}
// DEBUG: Export only part of the pattern set
// if (statistics.numberOfValidPatterns > 1e4) {
// break;
// }
// const bool patternContainsCentroid =
// std::find_if(patternEdges.begin(), patternEdges.end(),
// [](const vcg::Point2i& edge) {
// if (edge[0] == 0 || edge[1] == 0) {
// return true;
// }
// return false;
// }) != patternEdges.end();
// if (!patternContainsCentroid) {
// continue;
// }
PatternGeometry patternGeometry;
patternGeometry.add(allVertices, patternEdges);
patternGeometry.setLabel(patternName);
#ifdef POLYSCOPE_DEFINED
// 1st example
// const bool shouldBreak = patternBinaryRepresentation == "00100000100100000"; //398
// const bool shouldBreak = patternBinaryRepresentation == "10000010101110110";//13036
// const bool shouldBreak = patternBinaryRepresentation == "00010111000010100"; //2481
// const bool shouldBreak = patternBinaryRepresentation == "10000101100110010"; //12116
// const bool shouldBreak = patternBinaryRepresentation == "10010111000000110"; //13915
// const bool shouldBreak =
// patternIndex == 1970494; // 398 const bool shouldBreak =
// patternBinaryRepresentation == "10000010101110110";//13036 const
// bool shouldBreak = patternBinaryRepresentation ==
// "00010111000010100"; //2481 const bool shouldBreak =
// patternBinaryRepresentation == "10000101100110010"; //12116 const
// bool shouldBreak = patternBinaryRepresentation ==
// "10010111000000110"; //13915
// 2nd example
// const bool shouldBreak = patternBinaryRepresentation == "00001011100010011"; //7_1203
// const bool shouldBreak = patternBinaryRepresentation == "00110001100100111"; //4865
// const bool shouldBreak = patternBinaryRepresentation == "00010000101000110"; //1380
// const bool shouldBreak = patternBinaryRepresentation == "00000010100010111"; //268
// const bool shouldBreak = patternBinaryRepresentation ==
// "00001011100010011"; //7_1203 const bool shouldBreak =
// patternBinaryRepresentation == "00110001100100111"; //4865 const
// bool shouldBreak = patternBinaryRepresentation ==
// "00010000101000110"; //1380 const bool shouldBreak =
// patternBinaryRepresentation == "00000010100010111"; //268
// 3rd
// const bool shouldBreak = patternBinaryRepresentation == "10011011100000010"; //14272
// const bool shouldBreak = patternBinaryRepresentation == "10000111100110110"; //11877
// const bool shouldBreak = patternBinaryRepresentation == "00001011100010011"; //1203
// const bool shouldBreak = patternBinaryRepresentation == "00010101000110000"; //12117
// const bool shouldBreak = patternBinaryRepresentation ==
// "10011011100000010"; //14272 const bool shouldBreak =
// patternBinaryRepresentation == "10000111100110110"; //11877 const
// bool shouldBreak = patternBinaryRepresentation ==
// "00001011100010011"; //1203 const bool shouldBreak =
// patternBinaryRepresentation == "00010101000110000"; //12117
// const bool shouldBreak = patternBinaryRepresentation == "10000101100110100"; //12117
// const bool shouldBreak = patternBinaryRepresentation ==
// "10000101100110100"; //12117
// std::thread drawingThread([&]() {
// if (shouldBreak) {
// patternGeometry.registerForDrawing();
// polyscope::show();
// patternGeometry.unregister();
// }
// });
#endif
// Check if pattern contains intersecting edges
const bool isInterfaceConnected = patternGeometry.isInterfaceConnected(interfaceNodes);
const bool isInterfaceConnected =
patternGeometry.isInterfaceConnected(interfaceNodes);
// Export the tiled ply file if it contains intersecting edges
if (!isInterfaceConnected) {
// create the tiled geometry of the pattern
statistics.numberOfPatternViolatingInterfaceEnforcement++;
if (debugIsOn) {
if (savePlyFiles) {
exportPattern(std::filesystem::path(resultsPath).append("InterfaceEnforcement"),
patternGeometry,
exportTilledPattern);
}
} else {
continue; // should be uncommented in order to improve performance
}
}
// Check if pattern contains intersecting edges
const bool patternContainsIntersectingEdges
= patternGeometry.hasIntersectingEdges(patternBinaryRepresentation, intersectingEdges);
// Export the tiled ply file if it contains intersecting edges
if (patternContainsIntersectingEdges) {
// create the tiled geometry of the pattern
statistics.numberOfPatternsWithIntersectingEdges++;
if (debugIsOn) {
if (savePlyFiles) {
exportPattern(std::filesystem::path(resultsPath).append("Intersecting"),
patternGeometry,
exportTilledPattern);
}
} else {
continue; // should be uncommented in order to improve performance
}
}
// const bool shouldBreak = numberOfDesiredEdges == 4 && patternIndex == 53;
const bool tiledPatternHasEdgesWithAngleSmallerThanThreshold
= patternGeometry.hasAngleSmallerThanThreshold(numberOfNodesPerSlot, 15);
if (tiledPatternHasEdgesWithAngleSmallerThanThreshold) {
statistics.numberOfPatternsViolatingAngleThreshold++;
if (debugIsOn /*|| savePlyFiles*/) {
if (savePlyFiles) {
exportPattern(std::filesystem::path(resultsPath)
.append("ExceedingAngleThreshold"),
patternGeometry,
exportTilledPattern);
exportPattern(
std::filesystem::path(resultsPath).append("InterfaceEnforcement"),
patternGeometry, exportTilledPattern);
}
} else {
continue;
}
}
const bool tiledPatternHasNodeWithValenceGreaterThanDesired
= patternGeometry.hasValenceGreaterThan(numberOfNodesPerSlot, 6);
// Check if pattern contains intersecting edges
const bool patternContainsIntersectingEdges =
patternGeometry.hasIntersectingEdges(patternBinaryRepresentation,
intersectingEdges);
// Export the tiled ply file if it contains intersecting edges
if (patternContainsIntersectingEdges) {
// create the tiled geometry of the pattern
statistics.numberOfPatternsWithIntersectingEdges++;
if (debugIsOn) {
if (savePlyFiles) {
exportPattern(
std::filesystem::path(resultsPath).append("Intersecting"),
patternGeometry, exportTilledPattern);
}
} else {
continue;
}
}
// const bool shouldBreak = numberOfDesiredEdges == 4 && patternIndex
// == 53;
const bool tiledPatternHasEdgesWithAngleSmallerThanThreshold =
patternGeometry.hasAngleSmallerThanThreshold(numberOfNodesPerSlot, 15);
if (tiledPatternHasEdgesWithAngleSmallerThanThreshold) {
statistics.numberOfPatternsViolatingAngleThreshold++;
if (debugIsOn /*|| savePlyFiles*/) {
if (savePlyFiles) {
exportPattern(std::filesystem::path(resultsPath)
.append("ExceedingAngleThreshold"),
patternGeometry, exportTilledPattern);
}
} else {
continue;
}
}
const bool tiledPatternHasNodeWithValenceGreaterThanDesired =
patternGeometry.hasValenceGreaterThan(numberOfNodesPerSlot, 6);
if (tiledPatternHasNodeWithValenceGreaterThanDesired) {
statistics.numberOfPatternsViolatingValenceThreshold++;
if (debugIsOn) {
if (savePlyFiles) {
auto highValencePath = std::filesystem::path(resultsPath)
.append("HighValencePatterns");
auto highValencePath =
std::filesystem::path(resultsPath).append("HighValencePatterns");
exportPattern(highValencePath, patternGeometry, exportTilledPattern);
}
} else {
@ -563,35 +618,42 @@ void TopologyEnumerator::computeValidPatterns(
const bool tiledPatternHasDanglingEdges = patternGeometry.hasDanglingEdges(
numberOfNodesPerSlot); // marks the nodes with valence>=1
// Create the tiled geometry of the pattern
const bool hasFloatingComponents = !patternGeometry.isFullyConnectedWhenFanned();
const bool hasFloatingComponents =
!patternGeometry.isFullyConnectedWhenFanned();
PatternGeometry fanPatternGeometry = PatternGeometry::createFan(patternGeometry);
PatternGeometry fanPatternGeometry =
PatternGeometry::createFan(patternGeometry);
const int interfaceNodeVi = 3;
std::vector<PatternGeometry::EdgeType*> connectedEdges;
vcg::edge::VEStarVE(&fanPatternGeometry.vert[interfaceNodeVi], connectedEdges);
vcg::edge::VEStarVE(&fanPatternGeometry.vert[interfaceNodeVi],
connectedEdges);
if (!connectedEdges.empty()) {
for (int i = 1; i < 6; i++) {
vcg::tri::Allocator<PatternGeometry>::AddEdge(fanPatternGeometry,
interfaceNodeVi
+ (i - 1) * patternGeometry.VN(),
interfaceNodeVi
+ i * patternGeometry.VN());
vcg::tri::Allocator<PatternGeometry>::AddEdge(
fanPatternGeometry,
interfaceNodeVi + (i - 1) * patternGeometry.VN(),
interfaceNodeVi + i * patternGeometry.VN());
}
}
vcg::tri::Clean<PatternGeometry>::MergeCloseVertex(fanPatternGeometry, 0.0000005);
vcg::tri::Allocator<PatternGeometry>::CompactEveryVector(fanPatternGeometry);
vcg::tri::Clean<PatternGeometry>::MergeCloseVertex(fanPatternGeometry,
0.0000005);
vcg::tri::Allocator<PatternGeometry>::CompactEveryVector(
fanPatternGeometry);
vcg::tri::UpdateTopology<PatternGeometry>::VertexEdge(fanPatternGeometry);
vcg::tri::UpdateTopology<PatternGeometry>::EdgeEdge(fanPatternGeometry);
// for (PatternGeometry::VertexType &v : tilledPatternGeometry.vert) {
// for (PatternGeometry::VertexType &v : tilledPatternGeometry.vert)
// {
// std::vector<PatternGeometry::EdgeType *> connectedEdges;
// vcg::edge::VEStarVE(&v, connectedEdges);
// if (connectedEdges.size() == 1) {
// vcg::tri::Allocator<PatternGeometry>::DeleteVertex(tilledPatternGeometry, v);
// vcg::tri::Allocator<PatternGeometry>::DeleteVertex(tilledPatternGeometry,
// v);
// vcg::tri::Allocator<PatternGeometry>::DeleteEdge(tilledPatternGeometry,
// *connectedEdges[0]);
// }
// }
// // vcg::tri::Allocator<PatternGeometry>::CompactEveryVector(tilledPatternGeometry);
// //
// vcg::tri::Allocator<PatternGeometry>::CompactEveryVector(tilledPatternGeometry);
// fanPatternGeometry.updateEigenEdgeAndVertices();
BoostGraph fanPatternGraph(fanPatternGeometry.VN());
@ -608,21 +670,28 @@ void TopologyEnumerator::computeValidPatterns(
// std::cout << std::endl;
std::vector<vertex_t> articulationPoints;
boost::articulation_points(fanPatternGraph, std::back_inserter(articulationPoints));
boost::articulation_points(fanPatternGraph,
std::back_inserter(articulationPoints));
const bool hasArticulationPoints = !articulationPoints.empty();
// if (!hasArticulationPoints && tiledPatternHasDanglingEdges) {
// PatternGeometry tilledPatternGeometry = PatternGeometry::createTile(patternGeometry);
// PatternGeometry tilledPatternGeometry =
// PatternGeometry::createTile(patternGeometry);
// tilledPatternGeometry.updateEigenEdgeAndVertices();
// tilledPatternGeometry.registerForDrawing();
// // ->addNodeColorQuantity("de_noAp_tilled", fanVertexColors)
// // ->addNodeColorQuantity("de_noAp_tilled",
// fanVertexColors)
// // ->setEnabled(true);
// polyscope::show();
// tilledPatternGeometry.unregister();
// }
// if (hasArticulationPoints && !tiledPatternHasDanglingEdges/*&& !patternContainsIntersectingEdges
// if (hasArticulationPoints && !tiledPatternHasDanglingEdges/*&&
// !patternContainsIntersectingEdges
// && !hasFloatingComponents
// && !tiledPatternHasNodeWithValenceGreaterThanDesired
// && !tiledPatternHasEdgesWithAngleSmallerThanThreshold*/) {
// &&
// !tiledPatternHasNodeWithValenceGreaterThanDesired
// &&
// !tiledPatternHasEdgesWithAngleSmallerThanThreshold*/)
// {
// for (PatternGeometry::VertexType &v : patternGeometry.vert) {
// v.C() = vcg::Color4b::Yellow;
// }
@ -632,15 +701,20 @@ void TopologyEnumerator::computeValidPatterns(
// continue;
// }
// // std::cout << articulationPointVi << " ";
// patternGeometry.vert[articulationPointVi].C() = vcg::Color4b::Red;
// patternGeometry.vert[articulationPointVi].C() =
// vcg::Color4b::Red;
// }
// PatternGeometry tilledPatternGeometry = PatternGeometry::createTile(patternGeometry);
// PatternGeometry tilledPatternGeometry =
// PatternGeometry::createTile(patternGeometry);
// // std::cout << std::endl;
// std::vector<glm::vec3> fanVertexColors(tilledPatternGeometry.VN(), glm::vec3(0, 0, 1));
// for (const PatternGeometry::VertexType &v : tilledPatternGeometry.vert) {
// const auto vColor = glm::vec3(v.cC()[0] / 255, v.cC()[1] / 255, v.cC()[2] / 255);
// const auto vi = tilledPatternGeometry.getIndex(v);
// fanVertexColors[vi] = vColor;
// std::vector<glm::vec3>
// fanVertexColors(tilledPatternGeometry.VN(), glm::vec3(0, 0,
// 1)); for (const PatternGeometry::VertexType &v :
// tilledPatternGeometry.vert) {
// const auto vColor = glm::vec3(v.cC()[0] / 255, v.cC()[1] /
// 255, v.cC()[2] / 255); const auto vi =
// tilledPatternGeometry.getIndex(v); fanVertexColors[vi] =
// vColor;
// }
// tilledPatternGeometry.updateEigenEdgeAndVertices();
// tilledPatternGeometry.registerForDrawing()
@ -657,8 +731,10 @@ void TopologyEnumerator::computeValidPatterns(
statistics.numberOfPatternsWithADanglingEdgeOrNode++;
if (debugIsOn) {
if (savePlyFiles) {
auto danglingEdgesPath = std::filesystem::path(resultsPath).append("Dangling");
exportPattern(danglingEdgesPath, patternGeometry, exportTilledPattern);
auto danglingEdgesPath =
std::filesystem::path(resultsPath).append("Dangling");
exportPattern(danglingEdgesPath, patternGeometry,
exportTilledPattern);
}
} else {
continue;
@ -669,22 +745,23 @@ void TopologyEnumerator::computeValidPatterns(
statistics.numberOfPatternsWithMoreThanASingleCC++;
if (debugIsOn) {
if (savePlyFiles) {
auto moreThanOneCCPath = std::filesystem::path(resultsPath)
.append("MoreThanOneCC");
auto moreThanOneCCPath =
std::filesystem::path(resultsPath).append("MoreThanOneCC");
std::filesystem::create_directory(moreThanOneCCPath);
patternGeometry.save(
std::filesystem::path(moreThanOneCCPath).append(patternName).string()
+ ".ply");
patternGeometry.save(std::filesystem::path(moreThanOneCCPath)
.append(patternName)
.string() +
".ply");
PatternGeometry tiledPatternGeometry = PatternGeometry::createTile(
patternGeometry); // the marked nodes of hasDanglingEdges are
std::vector<std::pair<int, PatternGeometry::EdgePointer>> eCC;
vcg::tri::Clean<PatternGeometry>::edgeMeshConnectedComponents(tiledPatternGeometry,
eCC);
vcg::tri::UpdateFlags<PatternGeometry>::EdgeClear(tiledPatternGeometry);
vcg::tri::Clean<PatternGeometry>::edgeMeshConnectedComponents(
tiledPatternGeometry, eCC);
vcg::tri::UpdateFlags<PatternGeometry>::EdgeClear(
tiledPatternGeometry);
const size_t numberOfCC_edgeBased = eCC.size();
std::sort(eCC.begin(),
eCC.end(),
std::sort(eCC.begin(), eCC.end(),
[](const std::pair<int, PatternGeometry::EdgePointer>& a,
const std::pair<int, PatternGeometry::EdgePointer>& b) {
return a.first > b.first;
@ -706,12 +783,10 @@ void TopologyEnumerator::computeValidPatterns(
stack.push(vei.E());
tiledPatternGeometry
.vert[tiledPatternGeometry.getIndex(vei.V1())]
.C()
= vcg::Color4b::Blue;
.C() = vcg::Color4b::Blue;
tiledPatternGeometry
.vert[tiledPatternGeometry.getIndex(vei.V0())]
.C()
= vcg::Color4b::Blue;
.C() = vcg::Color4b::Blue;
colorsRegistered++;
}
++vei;
@ -724,8 +799,8 @@ void TopologyEnumerator::computeValidPatterns(
if (exportTilledPattern) {
tiledPatternGeometry.save(std::filesystem::path(moreThanOneCCPath)
.append(patternName + "_tiled")
.string()
+ ".ply");
.string() +
".ply");
}
}
} else {
@ -737,35 +812,40 @@ void TopologyEnumerator::computeValidPatterns(
statistics.numberOfPatternsWithArticulationPoints++;
if (debugIsOn) {
if (savePlyFiles) {
auto articulationPointsPath = std::filesystem::path(resultsPath)
.append("ArticulationPoints");
exportPattern(articulationPointsPath, patternGeometry, exportTilledPattern);
auto articulationPointsPath =
std::filesystem::path(resultsPath).append("ArticulationPoints");
exportPattern(articulationPointsPath, patternGeometry,
exportTilledPattern);
}
} else {
continue;
}
}
const bool isValidPattern = !patternContainsIntersectingEdges
&& isInterfaceConnected
const bool isValidPattern =
!patternContainsIntersectingEdges &&
isInterfaceConnected
/*&& !tiledPatternHasDanglingEdges*/
&& !hasFloatingComponents && !hasArticulationPoints
&& !tiledPatternHasNodeWithValenceGreaterThanDesired
&& !tiledPatternHasEdgesWithAngleSmallerThanThreshold;
&& !hasFloatingComponents && !hasArticulationPoints &&
!tiledPatternHasNodeWithValenceGreaterThanDesired &&
!tiledPatternHasEdgesWithAngleSmallerThanThreshold;
// if (!hasArticulationPoints && !patternContainsIntersectingEdges
// && !tiledPatternHasDanglingEdges && !hasFloatingComponents
// && !tiledPatternHasNodeWithValenceGreaterThanDesired
// && tiledPatternHasEdgesWithAngleSmallerThanThreshold && numberOfDesiredEdges > 4) {
// std::cout << "Pattern found:" << patternName << std::endl;
// && tiledPatternHasEdgesWithAngleSmallerThanThreshold &&
// numberOfDesiredEdges > 4) { std::cout << "Pattern found:" <<
// patternName << std::endl;
// patternGeometry.registerForDrawing();
// polyscope::show();
// patternGeometry.unregister();
// }
if (isValidPattern) {
// if(patternName=='2055'){
// PatternGeometry tiledPatternGeometry = PatternGeometry::createTile(
// patternGeometry); // the marked nodes of hasDanglingEdges are
// tiledPatternGeometry.registerForDrawing(std::array<double, 3>{0, 0, 1});
// PatternGeometry tiledPatternGeometry =
// PatternGeometry::createTile(
// patternGeometry); // the marked nodes of
// hasDanglingEdges are
// tiledPatternGeometry.registerForDrawing(RGBColor{0, 0, 1});
// polyscope::show();
// tiledPatternGeometry.unregister();
// }
@ -789,6 +869,10 @@ void TopologyEnumerator::computeValidPatterns(
}
}
// if (drawingThread.joinable()) {
// drawingThread.join();
// }
// assert(vcg_tiledPatternHasDangling == tiledPatternHasDanglingEdges);
} while (std::next_permutation(patternBinaryRepresentation.begin(),
patternBinaryRepresentation.end()));
@ -805,16 +889,15 @@ void TopologyEnumerator::computeValidPatterns(
}
std::vector<size_t> TopologyEnumerator::getCoincideEdges(
const std::vector<size_t> &edgeNodeIndices) const
{
const std::vector<size_t>& edgeNodeIndices) const {
std::vector<size_t> coincideEdges;
if (edgeNodeIndices.size() < 3)
return coincideEdges;
for (size_t edgeNodeIndex = 0; edgeNodeIndex < edgeNodeIndices.size() - 2; edgeNodeIndex++) {
for (size_t edgeNodeIndex = 0; edgeNodeIndex < edgeNodeIndices.size() - 2;
edgeNodeIndex++) {
const size_t& firstNodeIndex = edgeNodeIndices[edgeNodeIndex];
for (size_t secondEdgeNodeIndex = edgeNodeIndex + 2;
secondEdgeNodeIndex < edgeNodeIndices.size();
secondEdgeNodeIndex++) {
secondEdgeNodeIndex < edgeNodeIndices.size(); secondEdgeNodeIndex++) {
const size_t& secondNodeIndex = edgeNodeIndices[secondEdgeNodeIndex];
coincideEdges.push_back(getEdgeIndex(firstNodeIndex, secondNodeIndex));
}
@ -822,9 +905,9 @@ std::vector<size_t> TopologyEnumerator::getCoincideEdges(
return coincideEdges;
}
bool TopologyEnumerator::isValidPattern(const std::string &patternBinaryRepresentation,
bool TopologyEnumerator::isValidPattern(
const std::string& patternBinaryRepresentation,
const std::vector<vcg::Point2i>& validEdges,
const size_t &numberOfDesiredEdges) const
{
const size_t& numberOfDesiredEdges) const {
return true;
}

View File

@ -1,12 +1,12 @@
#include "trianglepatterngeometry.hpp"
#include "trianglepattterntopology.hpp"
#include <algorithm>
#include <iterator>
#include <numeric>
#include <vcg/complex/algorithms/update/position.h>
#include <vcg/simplex/edge/topology.h>
#include <vcg/space/intersection2.h>
#include <wrap/io_trimesh/export.h>
#include <algorithm>
#include <iterator>
#include <numeric>
#include "trianglepattterntopology.hpp"
/* include the support for half edges */
#include <vcg/complex/algorithms/update/halfedge_indexed.h>
@ -72,14 +72,17 @@ size_t PatternGeometry::computeTiledValence(
return 0;
}
size_t PatternGeometry::getFanSize() const { return fanSize; }
size_t PatternGeometry::getFanSize() const {
return fanSize;
}
double PatternGeometry::getTriangleEdgeSize() const { return triangleEdgeSize; }
double PatternGeometry::getTriangleEdgeSize() const {
return triangleEdgeSize;
}
PatternGeometry::PatternGeometry() {}
std::vector<vcg::Point3d> PatternGeometry::computeVertices() const
{
std::vector<vcg::Point3d> PatternGeometry::computeVertices() const {
std::vector<VCGEdgeMesh::CoordType> verts(VN());
for (size_t vi = 0; vi < VN(); vi++) {
verts[vi] = vert[vi].cP();
@ -87,8 +90,7 @@ std::vector<vcg::Point3d> PatternGeometry::computeVertices() const
return verts;
}
PatternGeometry PatternGeometry::createTile(PatternGeometry &pattern)
{
PatternGeometry PatternGeometry::createTile(PatternGeometry& pattern) {
const size_t fanSize = PatternGeometry().getFanSize();
PatternGeometry fan(createFan(pattern));
PatternGeometry tile(fan);
@ -141,13 +143,11 @@ PatternGeometry PatternGeometry::createFan(PatternGeometry &pattern) {
return fan;
}
void PatternGeometry::updateBaseTriangle()
{
void PatternGeometry::updateBaseTriangle() {
baseTriangle = computeBaseTriangle();
}
PatternGeometry::PatternGeometry(PatternGeometry &other)
{
PatternGeometry::PatternGeometry(PatternGeometry& other) {
vcg::tri::Append<PatternGeometry, PatternGeometry>::MeshCopy(*this, other);
this->vertices = other.computeVertices();
baseTriangle = other.getBaseTriangle();
@ -156,8 +156,7 @@ PatternGeometry::PatternGeometry(PatternGeometry &other)
vcg::tri::UpdateTopology<PatternGeometry>::EdgeEdge(*this);
}
bool PatternGeometry::load(const std::filesystem::__cxx11::path &meshFilePath)
{
bool PatternGeometry::load(const std::filesystem::__cxx11::path& meshFilePath) {
if (!VCGEdgeMesh::load(meshFilePath)) {
return false;
}
@ -190,8 +189,7 @@ void PatternGeometry::add(const std::vector<vcg::Point2i> &edges) {
}
void PatternGeometry::add(const std::vector<vcg::Point3d>& vertices,
const std::vector<vcg::Point2i> &edges)
{
const std::vector<vcg::Point2i>& edges) {
add(vertices);
add(edges);
updateEigenEdgeAndVertices();
@ -209,9 +207,9 @@ void PatternGeometry::add(const std::vector<size_t> &numberOfNodesPerSlot,
}
std::vector<vcg::Point3d> PatternGeometry::constructVertexVector(
const std::vector<size_t> &numberOfNodesPerSlot, const size_t &fanSize,
const std::vector<size_t>& numberOfNodesPerSlot,
const size_t& fanSize,
const double& triangleEdgeSize) {
std::vector<vcg::Point3d> vertices;
const double centerAngle = 2 * M_PI / fanSize;
const double triangleHeight =
@ -244,7 +242,6 @@ std::vector<vcg::Point3d> PatternGeometry::constructVertexVector(
const vcg::Point3d edgeVector0(triangleV1 - triangleV0);
for (size_t vertexIndex = 0; vertexIndex < numberOfNodesPerSlot[3];
vertexIndex++) {
// vertices[std::accumulate(numberOfNodesPerSlot.begin(),
// numberOfNodesPerSlot.begin() + 2, 0) +
// vertexIndex] =
@ -260,7 +257,6 @@ std::vector<vcg::Point3d> PatternGeometry::constructVertexVector(
const vcg::Point3d edgeVector1(triangleV2 - triangleV1);
for (size_t vertexIndex = 0; vertexIndex < numberOfNodesPerSlot[4];
vertexIndex++) {
// vertices[std::accumulate(numberOfNodesPerSlot.begin(),
// numberOfNodesPerSlot.begin() + 3, 0) +
// vertexIndex] =
@ -313,32 +309,34 @@ void PatternGeometry::constructNodeToTiledValenceMap(
}
std::vector<VectorType> PatternGeometry::getEdgeVectorsWithVertexAsOrigin(
std::vector<EdgePointer> &edgePointers, const int &vi)
{
std::vector<EdgePointer>& edgePointers,
const int& vi) {
std::vector<VectorType> incidentElementsVectors(edgePointers.size());
for (int incidentElementsIndex = 0; incidentElementsIndex < edgePointers.size();
incidentElementsIndex++) {
assert(vi == getIndex(edgePointers[incidentElementsIndex]->cV(0))
|| vi == getIndex(edgePointers[incidentElementsIndex]->cV(1)));
for (int incidentElementsIndex = 0;
incidentElementsIndex < edgePointers.size(); incidentElementsIndex++) {
assert(vi == getIndex(edgePointers[incidentElementsIndex]->cV(0)) ||
vi == getIndex(edgePointers[incidentElementsIndex]->cV(1)));
incidentElementsVectors[incidentElementsIndex]
= vi == getIndex(edgePointers[incidentElementsIndex]->cV(0))
? edgePointers[incidentElementsIndex]->cP(1)
- edgePointers[incidentElementsIndex]->cP(0)
: edgePointers[incidentElementsIndex]->cP(0)
- edgePointers[incidentElementsIndex]->cP(1);
incidentElementsVectors[incidentElementsIndex] =
vi == getIndex(edgePointers[incidentElementsIndex]->cV(0))
? edgePointers[incidentElementsIndex]->cP(1) -
edgePointers[incidentElementsIndex]->cP(0)
: edgePointers[incidentElementsIndex]->cP(0) -
edgePointers[incidentElementsIndex]->cP(1);
}
return incidentElementsVectors;
}
bool PatternGeometry::hasAngleSmallerThanThreshold(const std::vector<size_t> &numberOfNodesPerSlot,
const double &angleThreshold_degrees)
{
bool PatternGeometry::hasAngleSmallerThanThreshold(
const std::vector<size_t>& numberOfNodesPerSlot,
const double& angleThreshold_degrees,
const bool shouldBreak) {
assert(numberOfNodesPerSlot.size() == 7);
// Initialize helping structs
if (nodeToSlotMap.empty()) {
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot, nodeToSlotMap);
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot,
nodeToSlotMap);
}
if (correspondingNode.empty()) {
constructCorrespondingNodeMap(numberOfNodesPerSlot);
@ -349,11 +347,13 @@ bool PatternGeometry::hasAngleSmallerThanThreshold(const std::vector<size_t> &nu
// const double theta2 = vcg::math::ToDeg(vcg::Point2d(0, 1).Angle());
// const double theta3 = vcg::math::ToDeg(vcg::Point2d(-1, 1).Angle());
// const double theta4 = vcg::math::ToDeg(vcg::Point2d(-1, 0).Angle());
// const double theta5 = vcg::math::ToDeg(vcg::Point2d(-1, -1).Angle() + 2 * M_PI);
// const double theta6 = vcg::math::ToDeg(vcg::Point2d(0, -1).Angle() + 2 * M_PI);
// const double theta7 = vcg::math::ToDeg(vcg::Point2d(1, -1).Angle() + 2 * M_PI);
// const double theta5 = vcg::math::ToDeg(vcg::Point2d(-1, -1).Angle() + 2
// * M_PI); const double theta6 = vcg::math::ToDeg(vcg::Point2d(0,
// -1).Angle() + 2 * M_PI); const double theta7 =
// vcg::math::ToDeg(vcg::Point2d(1, -1).Angle() + 2 * M_PI);
// std::set<double> test{theta0, theta1, theta2, theta3, theta4, theta5, theta6, theta7};
// std::set<double> test{theta0, theta1, theta2, theta3, theta4, theta5,
// theta6, theta7};
bool hasAngleSmallerThan = false;
// find tiled incident edges for each node
@ -366,127 +366,152 @@ bool PatternGeometry::hasAngleSmallerThanThreshold(const std::vector<size_t> &nu
if (numberOfIncidentEdges == 0) {
continue;
}
std::vector<VectorType> incidentEdgeVectors
= getEdgeVectorsWithVertexAsOrigin(incidentElementPointers, vi);
std::vector<VectorType> incidentEdgeVectors =
getEdgeVectorsWithVertexAsOrigin(incidentElementPointers, vi);
std::vector<VectorType> tiledIncidentVectors = incidentEdgeVectors;
const size_t slotIndex = nodeToSlotMap[vi];
if (slotIndex == 2) {
//NOTE:I assume that base triangle slots 1,2(bottom triangle nodes) are not used
std::cerr
<< "Slot of bottom base triangle nodes detected.This case is not handled.Exiting.."
// NOTE:I assume that base triangle slots 1,2(bottom triangle nodes) are
// not used
std::cerr << "Slot of bottom base triangle nodes detected.This case is "
"not handled.Exiting.."
<< std::endl;
std::terminate();
} else if (slotIndex == 3 || slotIndex == 5) {
// NOTE: I don't need to check both triangle edges
std::vector<PatternGeometry::EdgePointer> correspondingVertexIncidentElementPointers;
std::vector<PatternGeometry::EdgePointer>
correspondingVertexIncidentElementPointers;
vcg::edge::VEStarVE(&vert[correspondingNode[vi]],
correspondingVertexIncidentElementPointers);
std::vector<VectorType> correspondingVertexIncidentVectors
= getEdgeVectorsWithVertexAsOrigin(correspondingVertexIncidentElementPointers,
std::vector<VectorType> correspondingVertexIncidentVectors =
getEdgeVectorsWithVertexAsOrigin(
correspondingVertexIncidentElementPointers,
correspondingNode[vi]);
// const CoordType &correspondingVertexPosition = vert[correspondingNode[vi]].cP();
// const CoordType &correspondingVertexPosition =
// vert[correspondingNode[vi]].cP();
vcg::Matrix33d R;
if (slotIndex == 3) {
R = vcg::RotationMatrix(vcg::Point3d(0, 0, 1), vcg::math::ToRad(-360.0 / fanSize));
R = vcg::RotationMatrix(vcg::Point3d(0, 0, 1),
vcg::math::ToRad(-360.0 / fanSize));
} else {
R = vcg::RotationMatrix(vcg::Point3d(0, 0, 1), vcg::math::ToRad(360.0 / fanSize));
R = vcg::RotationMatrix(vcg::Point3d(0, 0, 1),
vcg::math::ToRad(360.0 / fanSize));
}
// const CoordType &correspondingVertexPosition_rotated = vert[vi].cP();
std::transform(
correspondingVertexIncidentVectors.begin(),
// const CoordType &correspondingVertexPosition_rotated =
// vert[vi].cP();
std::transform(correspondingVertexIncidentVectors.begin(),
correspondingVertexIncidentVectors.end(),
correspondingVertexIncidentVectors.begin(),
[&](const VectorType& v) {
// CoordType rotatedTarget = v * R;
// v = rotatedTarget - correspondingVertexPosition_rotated;
// CoordType rotatedTarget
// = v * R; v =
// rotatedTarget -
// correspondingVertexPosition_rotated;
return R * v;
});
tiledIncidentVectors.insert(tiledIncidentVectors.end(),
correspondingVertexIncidentVectors.begin(),
correspondingVertexIncidentVectors.end());
} else if (slotIndex == 4) {
std::vector<VectorType> reversedIncidentElementVectors(incidentEdgeVectors.size());
std::transform(incidentEdgeVectors.begin(),
incidentEdgeVectors.end(),
std::vector<VectorType> reversedIncidentElementVectors(
incidentEdgeVectors.size());
std::transform(incidentEdgeVectors.begin(), incidentEdgeVectors.end(),
reversedIncidentElementVectors.begin(),
[&](const VectorType& v) { return -v; });
//NOTE: for checking the angles not all opposite incident element vectors are needed but rather the two "extreme" ones of slot 4
//here I simply add them all
// NOTE: for checking the angles not all opposite incident element vectors
// are needed but rather the two "extreme" ones of slot 4 here I simply
// add them all
tiledIncidentVectors.insert(tiledIncidentVectors.end(),
reversedIncidentElementVectors.begin(),
reversedIncidentElementVectors.end());
}
// if (shouldBreak) {
// std::vector<std::array<double, 3>> edgePoints;
// for (int tiledVectorIndex = 0; tiledVectorIndex < tiledIncidentVectors.size();
// for (int tiledVectorIndex = 0;
// tiledVectorIndex < tiledIncidentVectors.size();
// tiledVectorIndex++) {
// edgePoints.push_back(
// std::array<double, 3>{vert[vi].cP()[0], vert[vi].cP()[1], vert[vi].cP()[2]});
// edgePoints.push_back(
// std::array<double, 3>{(vert[vi].cP() + tiledIncidentVectors[tiledVectorIndex])[0],
// (vert[vi].cP() + tiledIncidentVectors[tiledVectorIndex])[1],
// (vert[vi].cP() + tiledIncidentVectors[tiledVectorIndex])[2]});
// edgePoints.push_back(std::array<double, 3>{
// vert[vi].cP()[0], vert[vi].cP()[1], vert[vi].cP()[2]});
// edgePoints.push_back(std::array<double, 3>{
// (vert[vi].cP() +
// tiledIncidentVectors[tiledVectorIndex])[0], (vert[vi].cP()
// + tiledIncidentVectors[tiledVectorIndex])[1],
// (vert[vi].cP() +
// tiledIncidentVectors[tiledVectorIndex])[2]});
// }
// polyscope::init();
// polyscope::registerCurveNetworkLine("temp", edgePoints);
// polyscope::removeStructure("temp");
// polyscope::registerCurveNetworkLine("vi:" + std::to_string(vi),
// edgePoints);
// polyscope::show();
// polyscope::removeStructure("vi:" + std::to_string(vi));
// }
if (tiledIncidentVectors.size() == 1) {
continue;
}
std::vector<double> thetaAnglesOfIncidentVectors(tiledIncidentVectors.size());
std::transform(tiledIncidentVectors.begin(),
tiledIncidentVectors.end(),
std::vector<double> thetaAnglesOfIncidentVectors(
tiledIncidentVectors.size());
std::transform(
tiledIncidentVectors.begin(), tiledIncidentVectors.end(),
thetaAnglesOfIncidentVectors.begin(),
[](const VectorType& v) { return vcg::Point2d(v[0], v[1]).Angle(); });
// sort them using theta angles
std::sort(thetaAnglesOfIncidentVectors.begin(), thetaAnglesOfIncidentVectors.end());
// polyscope::show();
std::sort(thetaAnglesOfIncidentVectors.begin(),
thetaAnglesOfIncidentVectors.end());
// std::vector<double> angles_theta(thetaAnglesOfIncidentVectors);
// for (double &theta_rad : angles_theta) {
// theta_rad = vcg::math::ToDeg(theta_rad);
// }
//find nodes that contain incident edges with relative angles less than the threshold
// find nodes that contain incident edges with relative angles less than the
// threshold
const double angleThreshold_rad = vcg::math::ToRad(angleThreshold_degrees);
for (int thetaAngleIndex = 0; thetaAngleIndex < thetaAnglesOfIncidentVectors.size();
for (int thetaAngleIndex = 0;
thetaAngleIndex < thetaAnglesOfIncidentVectors.size();
thetaAngleIndex++) {
const auto &va_theta
= thetaAnglesOfIncidentVectors[(thetaAngleIndex + 1)
% thetaAnglesOfIncidentVectors.size()];
const auto& va_theta =
thetaAnglesOfIncidentVectors[(thetaAngleIndex + 1) %
thetaAnglesOfIncidentVectors.size()];
const auto& vb_theta = thetaAnglesOfIncidentVectors[thetaAngleIndex];
// const auto &va
// = tiledIncidentVectors[(thetaAngleIndex + 1) % thetaAnglesOfIncidentVectors.size()];
// = tiledIncidentVectors[(thetaAngleIndex + 1) %
// thetaAnglesOfIncidentVectors.size()];
// const auto &vb = tiledIncidentVectors[thetaAngleIndex];
const double absAngleDifference = std::abs(va_theta - vb_theta);
// const double debug_difDegOtherway = vcg::math::ToDeg(
// std::acos((va * vb) / (va.Norm() * vb.Norm())));
// const double debug_diffDeg = vcg::math::ToDeg(absAngleDifference);
// const double debug_diffDeg =
// vcg::math::ToDeg(absAngleDifference);
if (absAngleDifference < angleThreshold_rad
/*&& absAngleDifference > vcg::math::ToRad(0.01)*/) {
// std::cout << "Found angDiff:" << absAngleDifference << std::endl;
// vert[vi].C() = vcg::Color4b::Magenta;
// std::cout << "Found angDiff:" << absAngleDifference <<
// std::endl; vert[vi].C() = vcg::Color4b::Magenta;
// hasAngleSmallerThan = true;
return true;
}
}
const double firstLastPairAngleDiff = std::abs(
thetaAnglesOfIncidentVectors[0]
- thetaAnglesOfIncidentVectors[thetaAnglesOfIncidentVectors.size() - 1]);
if (firstLastPairAngleDiff < angleThreshold_rad && firstLastPairAngleDiff > 0.01) {
thetaAnglesOfIncidentVectors[0] -
thetaAnglesOfIncidentVectors[thetaAnglesOfIncidentVectors.size() - 1]);
if (firstLastPairAngleDiff < angleThreshold_rad &&
firstLastPairAngleDiff > 0.01) {
return true;
}
}
return false;
}
bool PatternGeometry::hasValenceGreaterThan(const std::vector<size_t> &numberOfNodesPerSlot,
const size_t &valenceThreshold)
{
bool PatternGeometry::hasValenceGreaterThan(
const std::vector<size_t>& numberOfNodesPerSlot,
const size_t& valenceThreshold) {
// Initialize helping structs
if (nodeToSlotMap.empty()) {
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot, nodeToSlotMap);
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot,
nodeToSlotMap);
}
if (correspondingNode.empty()) {
constructCorrespondingNodeMap(numberOfNodesPerSlot);
@ -511,7 +536,8 @@ bool PatternGeometry::hasDanglingEdges(
const std::vector<size_t>& numberOfNodesPerSlot) {
// Initialize helping structs
if (nodeToSlotMap.empty()) {
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot, nodeToSlotMap);
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot,
nodeToSlotMap);
}
if (correspondingNode.empty()) {
constructCorrespondingNodeMap(numberOfNodesPerSlot);
@ -545,7 +571,6 @@ bool PatternGeometry::hasUntiledDanglingEdges() {
const size_t nodeValence = connectedEdges.size();
if (nodeValence == 1) {
if (vert[vi].C().operator==(vcg::Color4b(vcg::Color4b::Red))) {
} else {
vert[vi].C() = vcg::Color4b::Blue;
}
@ -557,10 +582,10 @@ bool PatternGeometry::hasUntiledDanglingEdges() {
// TODO: The function expects that the numberOfNodesPerSlot follows a specific
// format and that the vertex container was populated in a particular order.
void PatternGeometry::constructCorrespondingNodeMap(const std::vector<size_t> &numberOfNodesPerSlot)
{
assert(vn != 0 && !nodeToSlotMap.empty() && correspondingNode.empty()
&& numberOfNodesPerSlot.size() == 7);
void PatternGeometry::constructCorrespondingNodeMap(
const std::vector<size_t>& numberOfNodesPerSlot) {
assert(vn != 0 && !nodeToSlotMap.empty() && correspondingNode.empty() &&
numberOfNodesPerSlot.size() == 7);
for (size_t nodeIndex = 0; nodeIndex < vn; nodeIndex++) {
const size_t slotIndex = nodeToSlotMap[nodeIndex];
@ -569,33 +594,32 @@ void PatternGeometry::constructCorrespondingNodeMap(const std::vector<size_t> &n
} else if (slotIndex == 2) {
correspondingNode[nodeIndex] = nodeIndex - 1;
} else if (slotIndex == 3) {
const size_t numberOfNodesBefore = nodeIndex
- std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.begin() + 3,
0);
correspondingNode[nodeIndex] = std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.begin() + 6,
0)
- 1 - numberOfNodesBefore;
const size_t numberOfNodesBefore =
nodeIndex - std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.begin() + 3, 0);
correspondingNode[nodeIndex] =
std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.begin() + 6, 0) -
1 - numberOfNodesBefore;
} else if (slotIndex == 5) {
const size_t numberOfNodesAfter = std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.begin() + 6,
0)
- 1 - nodeIndex;
correspondingNode[nodeIndex] = numberOfNodesAfter
+ std::accumulate(numberOfNodesPerSlot.begin(),
const size_t numberOfNodesAfter =
std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.begin() + 6, 0) -
1 - nodeIndex;
correspondingNode[nodeIndex] =
numberOfNodesAfter + std::accumulate(numberOfNodesPerSlot.begin(),
numberOfNodesPerSlot.begin() + 3,
0);
}
}
}
bool PatternGeometry::isFullyConnectedWhenFanned()
{
bool PatternGeometry::isFullyConnectedWhenFanned() {
assert(vn != 0 /* && !correspondingNode.empty()*/);
// TrianglePatternGeometry copyOfPattern(*this);
// // If bottom interface nodes have a valence of zero there definetely more than
// // If bottom interface nodes have a valence of zero there definetely more
// than
// // a single cc
// bool bottomInterfaceIsConnected = false;
// for (size_t nodeIndex = 0; nodeIndex < vn; nodeIndex++) {
@ -620,7 +644,8 @@ bool PatternGeometry::isFullyConnectedWhenFanned()
vcg::tri::UpdateTopology<PatternGeometry>::VertexEdge(fanedPattern);
vcg::tri::UpdateTopology<PatternGeometry>::EdgeEdge(fanedPattern);
std::vector<std::pair<int, PatternGeometry::EdgePointer>> eCC;
vcg::tri::Clean<PatternGeometry>::edgeMeshConnectedComponents(fanedPattern, eCC);
vcg::tri::Clean<PatternGeometry>::edgeMeshConnectedComponents(fanedPattern,
eCC);
const bool sideInterfaceIsConnected = 1 == eCC.size();
if (!sideInterfaceIsConnected) {
@ -699,14 +724,15 @@ bool PatternGeometry::isFullyConnectedWhenFanned()
bool PatternGeometry::hasIntersectingEdges(
const std::string& patternBinaryRepresentation,
const std::unordered_map<size_t, std::unordered_set<size_t>>
&intersectingEdges) {
const std::unordered_map<size_t, std::unordered_set<size_t>>&
intersectingEdges) {
bool containsIntersectingEdges = false;
for (size_t validEdgeIndex = 0;
validEdgeIndex < patternBinaryRepresentation.size(); validEdgeIndex++) {
if (patternBinaryRepresentation[validEdgeIndex] == '1'
&& intersectingEdges.contains(validEdgeIndex)) {
for (auto edgeIndexIt = intersectingEdges.find(validEdgeIndex)->second.begin();
if (patternBinaryRepresentation[validEdgeIndex] == '1' &&
intersectingEdges.contains(validEdgeIndex)) {
for (auto edgeIndexIt =
intersectingEdges.find(validEdgeIndex)->second.begin();
edgeIndexIt != intersectingEdges.find(validEdgeIndex)->second.end();
edgeIndexIt++) {
if (patternBinaryRepresentation[*edgeIndexIt] == '1') {
@ -777,8 +803,7 @@ PatternGeometry::getIntersectingEdges(
}
PatternGeometry::PatternGeometry(const std::filesystem::path& patternFilePath,
bool addNormalsIfAbsent)
{
bool addNormalsIfAbsent) {
if (!std::filesystem::exists(std::filesystem::path(patternFilePath))) {
assert(false);
std::cerr << "No flat pattern with name " << patternFilePath << std::endl;
@ -800,18 +825,15 @@ PatternGeometry::PatternGeometry(const std::filesystem::path &patternFilePath,
updateEigenEdgeAndVertices();
}
double PatternGeometry::computeBaseTriangleHeight() const
{
double PatternGeometry::computeBaseTriangleHeight() const {
return vcg::Distance(vert[0].cP(), vert[interfaceNodeIndex].cP());
}
void PatternGeometry::updateBaseTriangleHeight()
{
void PatternGeometry::updateBaseTriangleHeight() {
baseTriangleHeight = computeBaseTriangleHeight();
}
void PatternGeometry::deleteDanglingVertices()
{
void PatternGeometry::deleteDanglingVertices() {
vcg::tri::Allocator<VCGEdgeMesh>::PointerUpdater<VertexPointer> pu;
VCGEdgeMesh::deleteDanglingVertices(pu);
if (!pu.remap.empty()) {
@ -820,18 +842,15 @@ void PatternGeometry::deleteDanglingVertices()
}
void PatternGeometry::deleteDanglingVertices(
vcg::tri::Allocator<VCGEdgeMesh>::PointerUpdater<VertexPointer> &pu)
{
vcg::tri::Allocator<VCGEdgeMesh>::PointerUpdater<VertexPointer>& pu) {
VCGEdgeMesh::deleteDanglingVertices(pu);
}
vcg::Triangle3<double> PatternGeometry::getBaseTriangle() const
{
vcg::Triangle3<double> PatternGeometry::getBaseTriangle() const {
return baseTriangle;
}
void PatternGeometry::addNormals()
{
void PatternGeometry::addNormals() {
bool normalsAreAbsent = vert[0].cN().Norm() < 0.000001;
if (normalsAreAbsent) {
for (auto& v : vert) {
@ -840,16 +859,16 @@ void PatternGeometry::addNormals()
}
}
vcg::Triangle3<double> PatternGeometry::computeBaseTriangle() const
{
vcg::Triangle3<double> PatternGeometry::computeBaseTriangle() const {
const double baseTriangleHeight = computeBaseTriangleHeight();
double bottomEdgeHalfSize = baseTriangleHeight / std::tan(M_PI / 3);
CoordType patternCoord0 = vert[0].cP();
CoordType patternBottomRight = vert[interfaceNodeIndex].cP()
+ CoordType(bottomEdgeHalfSize, 0, 0);
CoordType patternBottomLeft = vert[interfaceNodeIndex].cP()
- CoordType(bottomEdgeHalfSize, 0, 0);
return vcg::Triangle3<double>(patternCoord0, patternBottomLeft, patternBottomRight);
CoordType patternBottomRight =
vert[interfaceNodeIndex].cP() + CoordType(bottomEdgeHalfSize, 0, 0);
CoordType patternBottomLeft =
vert[interfaceNodeIndex].cP() - CoordType(bottomEdgeHalfSize, 0, 0);
return vcg::Triangle3<double>(patternCoord0, patternBottomLeft,
patternBottomRight);
}
PatternGeometry::PatternGeometry(
@ -864,30 +883,32 @@ PatternGeometry::PatternGeometry(
updateEigenEdgeAndVertices();
}
//TODO: refactor such that it takes as an input a single pattern and tiles into the desired faces without requiring the each face will contain a single pattern
// TODO: refactor such that it takes as an input a single pattern and tiles into
// the desired faces without requiring the each face will contain a single
// pattern
std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
std::vector<ConstPatternGeometry>& patterns,
const std::vector<int>& connectToNeighborsVi,
const VCGPolyMesh& tileInto,
const std::vector<int>& perSurfaceFacePatternIndices,
std::vector<size_t>& tileIntoEdgesToTiledVi,
std::vector<std::vector<size_t>> &perPatternIndexToTiledPatternEdgeIndex)
{
std::vector<std::vector<size_t>>& perPatternIndexToTiledPatternEdgeIndex) {
perPatternIndexToTiledPatternEdgeIndex.resize(patterns.size());
std::shared_ptr<PatternGeometry> pTiledPattern(new PatternGeometry);
std::vector<std::vector<int>> tileIntoEdgeToInterfaceVi(
tileInto.EN()); //ith element contains all the interface nodes that lay on the ith edge of tileInto
tileInto.EN()); // ith element contains all the interface nodes that lay
// on the ith edge of tileInto
// Compute the barycentric coords of the verts in the base triangle pattern
std::vector<std::vector<CoordType>> barycentricCoordinates(patterns.size());
for (size_t patternIndex = 0; patternIndex < patterns.size(); patternIndex++) {
for (size_t patternIndex = 0; patternIndex < patterns.size();
patternIndex++) {
const PatternGeometry& pattern = patterns[patternIndex];
const vcg::Triangle3<double>& baseTriangle = pattern.getBaseTriangle();
barycentricCoordinates[patternIndex].resize(pattern.VN());
for (int vi = 0; vi < pattern.VN(); vi++) {
CoordType barycentricCoords_vi;
vcg::InterpolationParameters<vcg::Triangle3<double>, double>(baseTriangle,
pattern.vert[vi].cP(),
barycentricCoords_vi);
vcg::InterpolationParameters<vcg::Triangle3<double>, double>(
baseTriangle, pattern.vert[vi].cP(), barycentricCoords_vi);
barycentricCoordinates[patternIndex][vi] = barycentricCoords_vi;
}
}
@ -905,8 +926,7 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
centerOfFace = centerOfFace + f.cP(vi);
}
centerOfFace /= f.VN();
vcg::tri::Allocator<VCGTriMesh>::AddVertex(tileIntoEdgeMesh,
centerOfFace,
vcg::tri::Allocator<VCGTriMesh>::AddVertex(tileIntoEdgeMesh, centerOfFace,
vcg::Color4b::Yellow);
std::vector<int> firstInFanConnectToNeighbor_vi(connectToNeighborsVi);
@ -918,16 +938,17 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
for (size_t vi = 0; vi < f.VN(); vi++) {
auto ep = f.FEp(vi);
assert(vcg::tri::IsValidPointer(tileInto, ep));
std::vector<vcg::Point3d> meshTrianglePoints{centerOfFace,
f.cP(vi),
vi + 1 == f.VN() ? f.cP(0) : f.cP(vi + 1)};
// std::vector<vcg::Point3d> meshTrianglePoints{centerOfFace, ep->cP(0), ep->cP(1)};
auto fit = vcg::tri::Allocator<VCGTriMesh>::AddFace(tileIntoEdgeMesh,
meshTrianglePoints[0],
meshTrianglePoints[1],
std::vector<vcg::Point3d> meshTrianglePoints{
centerOfFace, f.cP(vi), vi + 1 == f.VN() ? f.cP(0) : f.cP(vi + 1)};
// std::vector<vcg::Point3d> meshTrianglePoints{centerOfFace,
// ep->cP(0), ep->cP(1)};
auto fit = vcg::tri::Allocator<VCGTriMesh>::AddFace(
tileIntoEdgeMesh, meshTrianglePoints[0], meshTrianglePoints[1],
meshTrianglePoints[2]);
// CoordType faceNormal = ((meshTrianglePoints[1] - meshTrianglePoints[0])
// ^ (meshTrianglePoints[2] - meshTrianglePoints[0]))
// CoordType faceNormal = ((meshTrianglePoints[1] -
// meshTrianglePoints[0])
// ^ (meshTrianglePoints[2] -
// meshTrianglePoints[0]))
// .Normalize();
// TODO: in planar surfaces I should compute the face of triangle
CoordType faceNormal = f.cN();
@ -938,12 +959,16 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
// pattern.registerForDrawing();
// polyscope::show();
// pattern.unregister();
//Transform the base triangle nodes to the mesh triangle using barycentric coords
// Transform the base triangle nodes to the mesh triangle using
// barycentric coords
for (int vi = 0; vi < transformedPattern.VN(); vi++) {
transformedPattern.vert[vi].P() = CoordType(
meshTrianglePoints[0] * barycentricCoordinates[patternIndex][vi][0]
+ meshTrianglePoints[1] * barycentricCoordinates[patternIndex][vi][1]
+ meshTrianglePoints[2] * barycentricCoordinates[patternIndex][vi][2]);
transformedPattern.vert[vi].P() =
CoordType(meshTrianglePoints[0] *
barycentricCoordinates[patternIndex][vi][0] +
meshTrianglePoints[1] *
barycentricCoordinates[patternIndex][vi][1] +
meshTrianglePoints[2] *
barycentricCoordinates[patternIndex][vi][2]);
}
for (VertexType& v : transformedPattern.vert) {
@ -951,18 +976,19 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
}
vcg::tri::Append<PatternGeometry, PatternGeometry>::Remap remap;
vcg::tri::Append<PatternGeometry, PatternGeometry>::Mesh(*pTiledPattern,
transformedPattern,
remap);
vcg::tri::Append<PatternGeometry, PatternGeometry>::Mesh(
*pTiledPattern, transformedPattern, remap);
for (size_t ei = 0; ei < pattern.EN(); ei++) {
perPatternIndexToTiledPatternEdgeIndex[patternIndex].push_back(remap.edge[ei]);
perPatternIndexToTiledPatternEdgeIndex[patternIndex].push_back(
remap.edge[ei]);
}
// pTiledPattern->registerForDrawing();
// pTiledPattern->markVertices({remap.vert[pattern.interfaceNodeIndex]});
// polyscope::show();
// pTiledPattern->unregister();
const size_t ei = tileInto.getIndex(ep);
tileIntoEdgeToInterfaceVi[ei].push_back(remap.vert[pattern.interfaceNodeIndex]);
tileIntoEdgeToInterfaceVi[ei].push_back(
remap.vert[pattern.interfaceNodeIndex]);
// Add edges for connecting the desired vertices
if (!connectToNeighborsVi.empty()) {
if (vi + 1 == f.VN()) {
@ -972,8 +998,8 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
auto eIt = vcg::tri::Allocator<PatternGeometry>::AddEdge(
*pTiledPattern,
firstInFanConnectToNeighbor_vi[connectToNeighborIndex],
pTiledPattern->VN() - pattern.VN()
+ connectToNeighborsVi[connectToNeighborIndex]);
pTiledPattern->VN() - pattern.VN() +
connectToNeighborsVi[connectToNeighborIndex]);
perPatternIndexToTiledPatternEdgeIndex[patternIndex].push_back(
pTiledPattern->getIndex(*eIt));
}
@ -984,10 +1010,10 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
connectToNeighborIndex++) {
auto eIt = vcg::tri::Allocator<PatternGeometry>::AddEdge(
*pTiledPattern,
pTiledPattern->VN() - 2 * pattern.VN()
+ connectToNeighborsVi[connectToNeighborIndex],
pTiledPattern->VN() - pattern.VN()
+ connectToNeighborsVi[connectToNeighborIndex]);
pTiledPattern->VN() - 2 * pattern.VN() +
connectToNeighborsVi[connectToNeighborIndex],
pTiledPattern->VN() - pattern.VN() +
connectToNeighborsVi[connectToNeighborIndex]);
perPatternIndexToTiledPatternEdgeIndex[patternIndex].push_back(
pTiledPattern->getIndex(*eIt));
}
@ -999,7 +1025,8 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
vcg::tri::Allocator<VCGEdgeMesh>::PointerUpdater<EdgePointer> pu_edges;
pTiledPattern->removeDuplicateVertices(pu_vertices, pu_edges);
// Update perPattern
// for (std::vector<size_t> &tiledPatternEdges : perPatternIndexToTiledPatternEdgeIndex) {
// for (std::vector<size_t> &tiledPatternEdges :
// perPatternIndexToTiledPatternEdgeIndex) {
// for (size_t &ei : tiledPatternEdges) {
// ei = pu_edges.remap[ei];
// }
@ -1012,11 +1039,10 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
// tiledPatternEdges.erase(end, tiledPatternEdges.end());
// }
const size_t sumOfEdgeIndices = std::accumulate(perPatternIndexToTiledPatternEdgeIndex.begin(),
perPatternIndexToTiledPatternEdgeIndex.end(),
0,
[](const size_t &sum,
const std::vector<size_t> &v) {
const size_t sumOfEdgeIndices =
std::accumulate(perPatternIndexToTiledPatternEdgeIndex.begin(),
perPatternIndexToTiledPatternEdgeIndex.end(), 0,
[](const size_t& sum, const std::vector<size_t>& v) {
return sum + v.size();
});
@ -1032,10 +1058,11 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
}
assert(interfaceVis.size() == 1 || interfaceVis.size() == 2);
assert(
interfaceVis.size() == 1
|| (interfaceVis.size() == 2
&& (pu_vertices.remap[interfaceVis[0]] == std::numeric_limits<size_t>::max()
|| pu_vertices.remap[interfaceVis[1]] == std::numeric_limits<size_t>::max())));
interfaceVis.size() == 1 ||
(interfaceVis.size() == 2 && (pu_vertices.remap[interfaceVis[0]] ==
std::numeric_limits<size_t>::max() ||
pu_vertices.remap[interfaceVis[1]] ==
std::numeric_limits<size_t>::max())));
tileIntoEdgesToTiledVi[ei] = pu_vertices.remap[interfaceVis[0]];
}
@ -1046,8 +1073,7 @@ std::shared_ptr<PatternGeometry> PatternGeometry::tilePattern(
return pTiledPattern;
}
bool PatternGeometry::createHoneycombAtom()
{
bool PatternGeometry::createHoneycombAtom() {
VCGEdgeMesh honeycombQuarter;
const VCGEdgeMesh::CoordType n(0, 0, 1);
const double H = 0.2;
@ -1055,38 +1081,38 @@ bool PatternGeometry::createHoneycombAtom()
const double width = 0.2;
const double theta = 70;
const double dy = tan(vcg::math::ToRad(90 - theta)) * width / 2;
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(honeycombQuarter,
VCGEdgeMesh::CoordType(0, height / 2, 0),
n);
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(honeycombQuarter,
VCGEdgeMesh::CoordType(0, H / 2 - dy, 0),
n);
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(honeycombQuarter,
VCGEdgeMesh::CoordType(width / 2, H / 2, 0),
n);
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(honeycombQuarter,
VCGEdgeMesh::CoordType(width / 2, 0, 0),
n);
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(
honeycombQuarter, VCGEdgeMesh::CoordType(0, height / 2, 0), n);
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(
honeycombQuarter, VCGEdgeMesh::CoordType(0, H / 2 - dy, 0), n);
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(
honeycombQuarter, VCGEdgeMesh::CoordType(width / 2, H / 2, 0), n);
vcg::tri::Allocator<VCGEdgeMesh>::AddVertex(
honeycombQuarter, VCGEdgeMesh::CoordType(width / 2, 0, 0), n);
vcg::tri::Allocator<VCGEdgeMesh>::AddEdge(honeycombQuarter, 0, 1);
vcg::tri::Allocator<VCGEdgeMesh>::AddEdge(honeycombQuarter, 1, 2);
vcg::tri::Allocator<VCGEdgeMesh>::AddEdge(honeycombQuarter, 2, 3);
VCGEdgeMesh honeycombAtom;
// Top right
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::MeshCopy(honeycombAtom, honeycombQuarter);
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::MeshCopy(honeycombAtom,
honeycombQuarter);
// Bottom right
vcg::Matrix44d rotM;
rotM.SetRotateDeg(180, vcg::Point3d(1, 0, 0));
vcg::tri::UpdatePosition<VCGEdgeMesh>::Matrix(honeycombQuarter, rotM);
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::Mesh(honeycombAtom, honeycombQuarter);
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::Mesh(honeycombAtom,
honeycombQuarter);
// Bottom left
rotM.SetRotateDeg(180, vcg::Point3d(0, 1, 0));
vcg::tri::UpdatePosition<VCGEdgeMesh>::Matrix(honeycombQuarter, rotM);
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::Mesh(honeycombAtom, honeycombQuarter);
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::Mesh(honeycombAtom,
honeycombQuarter);
// Top left
rotM.SetRotateDeg(180, vcg::Point3d(1, 0, 0));
vcg::tri::UpdatePosition<VCGEdgeMesh>::Matrix(honeycombQuarter, rotM);
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::Mesh(honeycombAtom, honeycombQuarter);
vcg::tri::Append<VCGEdgeMesh, VCGEdgeMesh>::Mesh(honeycombAtom,
honeycombQuarter);
for (VertexType& v : honeycombAtom.vert) {
v.P()[2] = 0;
@ -1095,51 +1121,51 @@ bool PatternGeometry::createHoneycombAtom()
return true;
}
void PatternGeometry::copy(PatternGeometry &copyFrom)
{
void PatternGeometry::copy(PatternGeometry& copyFrom) {
VCGEdgeMesh::copy(copyFrom);
baseTriangleHeight = copyFrom.getBaseTriangleHeight();
baseTriangle = copyFrom.getBaseTriangle();
interfaceNodeIndex = copyFrom.interfaceNodeIndex;
}
void PatternGeometry::scale(const double &desiredBaseTriangleCentralEdgeSize)
{
void PatternGeometry::scale(const double& desiredBaseTriangleCentralEdgeSize) {
const double baseTriangleCentralEdgeSize = getBaseTriangleHeight();
const double scaleRatio = desiredBaseTriangleCentralEdgeSize / baseTriangleCentralEdgeSize;
const double scaleRatio =
desiredBaseTriangleCentralEdgeSize / baseTriangleCentralEdgeSize;
vcg::tri::UpdatePosition<VCGEdgeMesh>::Scale(*this, scaleRatio);
baseTriangle = computeBaseTriangle();
baseTriangleHeight = computeBaseTriangleHeight();
const double debug_baseTriHeight = vcg::Distance(baseTriangle.cP(0),
(baseTriangle.cP(1) + baseTriangle.cP(2)) / 2);
assert(std::abs(desiredBaseTriangleCentralEdgeSize - baseTriangleHeight) < 1e-10);
const double debug_baseTriHeight = vcg::Distance(
baseTriangle.cP(0), (baseTriangle.cP(1) + baseTriangle.cP(2)) / 2);
assert(std::abs(desiredBaseTriangleCentralEdgeSize - baseTriangleHeight) <
1e-10);
int i = 0;
i++;
}
void PatternGeometry::createFan(const size_t &fanSize)
{
void PatternGeometry::createFan(const size_t& fanSize) {
PatternGeometry rotatedPattern;
vcg::tri::Append<PatternGeometry, PatternGeometry>::MeshCopy(rotatedPattern, *this);
vcg::tri::Append<PatternGeometry, PatternGeometry>::MeshCopy(rotatedPattern,
*this);
for (int rotationCounter = 1; rotationCounter < fanSize; rotationCounter++) {
vcg::Matrix44d R;
auto rotationAxis = vcg::Point3d(0, 0, 1);
R.SetRotateDeg(360.0 / fanSize, rotationAxis);
vcg::tri::UpdatePosition<PatternGeometry>::Matrix(rotatedPattern, R);
vcg::tri::Append<PatternGeometry, PatternGeometry>::Mesh(*this, rotatedPattern);
vcg::tri::Append<PatternGeometry, PatternGeometry>::Mesh(*this,
rotatedPattern);
// Add edges for connecting the desired vertices
removeDuplicateVertices();
updateEigenEdgeAndVertices();
}
}
double PatternGeometry::getBaseTriangleHeight() const
{
double PatternGeometry::getBaseTriangleHeight() const {
return baseTriangleHeight;
}
bool PatternGeometry::isInterfaceConnected(const std::unordered_set<VertexIndex> &interfaceNodes)
{
bool PatternGeometry::isInterfaceConnected(
const std::unordered_set<VertexIndex>& interfaceNodes) {
std::unordered_set<VertexIndex> interfaceNodesConnected;
for (int ei = 0; ei < EN(); ei++) {
@ -1147,7 +1173,8 @@ bool PatternGeometry::isInterfaceConnected(const std::unordered_set<VertexIndex>
const int evi1 = getIndex(edge[ei].cV(1));
if (interfaceNodes.contains(evi0) && !interfaceNodes.contains(evi1)) {
interfaceNodesConnected.insert(evi0);
} else if (!interfaceNodes.contains(evi0) && interfaceNodes.contains(evi1)) {
} else if (!interfaceNodes.contains(evi0) &&
interfaceNodes.contains(evi1)) {
interfaceNodesConnected.insert(evi1);
}
}
@ -1159,10 +1186,10 @@ bool PatternGeometry::isInterfaceConnected(const std::unordered_set<VertexIndex>
}
std::unordered_set<VertexIndex> PatternGeometry::getInterfaceNodes(
const std::vector<size_t> &numberOfNodesPerSlot)
{
const std::vector<size_t>& numberOfNodesPerSlot) {
if (nodeToSlotMap.empty()) {
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot, nodeToSlotMap);
FlatPatternTopology::constructNodeToSlotMap(numberOfNodesPerSlot,
nodeToSlotMap);
}
std::unordered_set<VertexIndex> interfaceNodes;
for (std::pair<VertexIndex, size_t> viSlotPair : nodeToSlotMap) {

View File

@ -1,20 +1,19 @@
#ifndef FLATPATTERNGEOMETRY_HPP
#define FLATPATTERNGEOMETRY_HPP
#include "edgemesh.hpp"
#include <string>
#include <unordered_map>
#include <unordered_set>
#include "vcgtrimesh.hpp"
#include "edgemesh.hpp"
#include "polymesh.hpp"
#include "vcgtrimesh.hpp"
class PatternGeometry;
using ConstPatternGeometry = PatternGeometry;
class PatternGeometry : public VCGEdgeMesh
{
class PatternGeometry : public VCGEdgeMesh {
private:
size_t
computeTiledValence(const size_t &nodeIndex,
size_t computeTiledValence(
const size_t& nodeIndex,
const std::vector<size_t>& numberOfNodesPerSlot) const;
size_t getNodeValence(const size_t& nodeIndex) const;
size_t getNodeSlot(const size_t& nodeIndex) const;
@ -30,12 +29,14 @@ private:
std::unordered_map<size_t, size_t> nodeTiledValence;
vcg::Triangle3<double> baseTriangle;
void
constructCorrespondingNodeMap(const std::vector<size_t> &numberOfNodesPerSlot);
void constructCorrespondingNodeMap(
const std::vector<size_t>& numberOfNodesPerSlot);
void constructNodeToTiledValenceMap(const std::vector<size_t> &numberOfNodesPerSlot);
void constructNodeToTiledValenceMap(
const std::vector<size_t>& numberOfNodesPerSlot);
std::vector<VectorType> getEdgeVectorsWithVertexAsOrigin(std::vector<EdgePointer> &edgePointers,
std::vector<VectorType> getEdgeVectorsWithVertexAsOrigin(
std::vector<EdgePointer>& edgePointers,
const int& vi);
public:
@ -49,8 +50,10 @@ private:
bool load(const std::filesystem::path& meshFilePath) override;
void add(const std::vector<vcg::Point3d>& vertices);
void add(const std::vector<vcg::Point2i>& edges);
void add(const std::vector<vcg::Point3d> &vertices, const std::vector<vcg::Point2i> &edges);
void add(const std::vector<size_t> &numberOfNodesPerSlot, const std::vector<vcg::Point2i> &edges);
void add(const std::vector<vcg::Point3d>& vertices,
const std::vector<vcg::Point2i>& edges);
void add(const std::vector<size_t>& numberOfNodesPerSlot,
const std::vector<vcg::Point2i>& edges);
static std::vector<vcg::Point3d> constructVertexVector(
const std::vector<size_t>& numberOfNodesPerSlot,
const size_t& fanSize,
@ -66,8 +69,7 @@ private:
std::unordered_map<size_t, std::unordered_set<size_t>> getIntersectingEdges(
size_t& numberOfIntersectingEdgePairs) const;
static size_t binomialCoefficient(size_t n, size_t m)
{
static size_t binomialCoefficient(size_t n, size_t m) {
assert(n >= m);
return tgamma(n + 1) / (tgamma(m + 1) * tgamma(n - m + 1));
}
@ -75,8 +77,8 @@ private:
bool hasIntersectingEdges(
const std::string& patternBinaryRepresentation,
const std::unordered_map<size_t, std::unordered_set<size_t>>
&intersectingEdges);
const std::unordered_map<size_t, std::unordered_set<size_t>>&
intersectingEdges);
bool isPatternValid();
size_t getFanSize() const;
void add(const std::vector<vcg::Point2d>& vertices,
@ -84,7 +86,8 @@ private:
PatternGeometry(const std::vector<size_t>& numberOfNodesPerSlot,
const std::vector<vcg::Point2i>& edges);
PatternGeometry(const std::filesystem::path &patternFilePath, bool addNormalsIfAbsent = true);
PatternGeometry(const std::filesystem::path& patternFilePath,
bool addNormalsIfAbsent = true);
bool createHoneycombAtom();
void copy(PatternGeometry& copyFrom);
@ -102,20 +105,26 @@ private:
double computeBaseTriangleHeight() const;
void updateBaseTriangleHeight();
// PatternGeometry(const std::vector<vcg::Point2d> &vertices, const std::vector<vcg::Point2i> &edges);
// static std::shared_ptr<PatternGeometry> tilePattern(
// PatternGeometry(const std::vector<vcg::Point2d> &vertices, const
// std::vector<vcg::Point2i> &edges); static std::shared_ptr<PatternGeometry>
// tilePattern(
// std::vector<PatternGeometry> &pattern,
// const std::vector<int> &connectToNeighborsVi,
// const VCGPolyMesh &tileInto,
// std::vector<int> &tileIntoEdgesToTiledVi,
// std::vector<std::vector<size_t>> &perPatternEdges);
virtual void createFan(/*const std::vector<int> &connectToNeighborsVi = std::vector<int>(),*/
virtual void createFan(/*const std::vector<int> &connectToNeighborsVi =
std::vector<int>(),*/
const size_t& fanSize = 6);
int interfaceNodeIndex{3}; //TODO: Fix this. This should be automatically computed
bool hasAngleSmallerThanThreshold(const std::vector<size_t> &numberOfNodesPerSlot,
const double &angleThreshold_degrees);
int interfaceNodeIndex{
3}; // TODO: Fix this. This should be automatically computed
bool hasAngleSmallerThanThreshold(
const std::vector<size_t>& numberOfNodesPerSlot,
const double& angleThreshold_degrees,
const bool shouldBreak = false);
vcg::Triangle3<double> getBaseTriangle() const;
static std::shared_ptr<PatternGeometry> tilePattern(PatternGeometry &pattern,
static std::shared_ptr<PatternGeometry> tilePattern(
PatternGeometry& pattern,
const std::vector<int>& connectToNeighborsVi,
const VCGPolyMesh& tileInto,
std::vector<int>& tileIntoEdgesToTiledVi);
@ -126,11 +135,14 @@ private:
const std::vector<int>& perSurfaceFacePatternIndices,
std::vector<size_t>& tileIntoEdgesToTiledVi,
std::vector<std::vector<size_t>>& perPatternIndexTiledPatternEdgeIndex);
std::unordered_set<VertexIndex> getInterfaceNodes(const std::vector<size_t> &numberOfNodesPerSlot);
bool isInterfaceConnected(const std::unordered_set<VertexIndex> &interfaceNodes);
std::unordered_set<VertexIndex> getInterfaceNodes(
const std::vector<size_t>& numberOfNodesPerSlot);
bool isInterfaceConnected(
const std::unordered_set<VertexIndex>& interfaceNodes);
void deleteDanglingVertices() override;
void deleteDanglingVertices(
vcg::tri::Allocator<VCGEdgeMesh>::PointerUpdater<VertexPointer> &pu) override;
vcg::tri::Allocator<VCGEdgeMesh>::PointerUpdater<VertexPointer>& pu)
override;
};
#endif // FLATPATTERNGEOMETRY_HPP

View File

@ -121,8 +121,7 @@ bool VCGTriMesh::save(const std::string plyFilename)
#ifdef POLYSCOPE_DEFINED
polyscope::SurfaceMesh *VCGTriMesh::registerForDrawing(
const std::optional<std::array<double, 3>> &desiredColor, const bool &shouldEnable) const
polyscope::SurfaceMesh *VCGTriMesh::registerForDrawing(const std::optional<std::array<float, 3> > &desiredColor, const bool &shouldEnable) const
{
auto vertices = getVertices();
auto faces = getFaces();

View File

@ -1,8 +1,8 @@
#ifndef VCGTRIMESH_HPP
#define VCGTRIMESH_HPP
#include "mesh.hpp"
#include <vcg/complex/complex.h>
#include <optional>
#include "mesh.hpp"
#ifdef POLYSCOPE_DEFINED
#include <polyscope/surface_mesh.h>
@ -22,20 +22,21 @@ class VCGTriMeshVertex : public vcg::Vertex<VCGTriMeshUsedTypes,
vcg::vertex::Color4b,
vcg::vertex::VFAdj,
vcg::vertex::Qualityd,
vcg::vertex::VEAdj>
{};
class VCGTriMeshFace
: public vcg::Face<VCGTriMeshUsedTypes, vcg::face::FFAdj, vcg::face::VFAdj,
vcg::face::VertexRef, vcg::face::BitFlags,
vcg::vertex::VEAdj> {};
class VCGTriMeshFace : public vcg::Face<VCGTriMeshUsedTypes,
vcg::face::FFAdj,
vcg::face::VFAdj,
vcg::face::VertexRef,
vcg::face::BitFlags,
vcg::face::Normal3d> {};
class VCGTriMeshEdge : public vcg::Edge<VCGTriMeshUsedTypes, vcg::edge::VertexRef, vcg::edge::VEAdj>
{};
class VCGTriMeshEdge : public vcg::Edge<VCGTriMeshUsedTypes,
vcg::edge::VertexRef,
vcg::edge::VEAdj> {};
class VCGTriMesh : public vcg::tri::TriMesh<std::vector<VCGTriMeshVertex>,
std::vector<VCGTriMeshFace>,
std::vector<VCGTriMeshEdge>>,
public Mesh
{
public Mesh {
public:
VCGTriMesh();
VCGTriMesh(const std::string& filename);
@ -44,13 +45,14 @@ public:
Eigen::MatrixX3d getVertices() const;
Eigen::MatrixX3i getFaces() const;
bool save(const std::string plyFilename);
template <typename MeshElement> size_t getIndex(const MeshElement &element) {
template <typename MeshElement>
size_t getIndex(const MeshElement& element) {
return vcg::tri::Index<VCGTriMesh>(*this, element);
}
#ifdef POLYSCOPE_DEFINED
polyscope::SurfaceMesh* registerForDrawing(
const std::optional<std::array<double, 3>> &desiredColor = std::nullopt,
const std::optional<std::array<float, 3>>& desiredColor = std::nullopt,
const bool& shouldEnable = true) const;
#endif
Eigen::MatrixX2i getEdges() const;