1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
|
/************************************************************************
*
* Copyright (C) 2009-2025 IRCAD France
* Copyright (C) 2012-2020 IHU Strasbourg
*
* This file is part of Sight.
*
* Sight is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sight is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sight. If not, see <https://www.gnu.org/licenses/>.
*
***********************************************************************/
#include "module/filter/mesh/vtk_mesher.hpp"
#include <core/com/signal.hxx>
#include <core/com/slots.hxx>
#include <core/profiling.hpp>
#include <data/helper/field.hpp>
#include <data/image_series.hpp>
#include <data/mesh.hpp>
#include <data/model_series.hpp>
#include <data/reconstruction.hpp>
#include <data/string.hpp>
#include <io/vtk/helper/mesh.hpp>
#include <io/vtk/vtk.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/thread_pool.hpp>
#include <vtkCommand.h>
#include <vtkConnectivityFilter.h>
#include <vtkDecimatePro.h>
#include <vtkDiscreteFlyingEdges3D.h>
#include <vtkDiscreteMarchingCubes.h>
#include <vtkExecutionTimer.h>
#include <vtkGeometryFilter.h>
#include <vtkImageData.h>
#include <vtkPolyDataMapper.h>
#include <vtkQuadricDecimation.h>
#include <vtkSmartPointer.h>
#include <vtkThreshold.h>
#include <vtkWindowedSincPolyDataFilter.h>
namespace sight::module::filter::mesh
{
//-----------------------------------------------------------------------------
class error_observer final : public vtkCommand
{
public:
//------------------------------------------------------------------------------
[[nodiscard]] static error_observer* New()
{
return new error_observer;
}
//------------------------------------------------------------------------------
[[nodiscard]] std::optional<std::string> get_error() const
{
return m_error_message;
}
//------------------------------------------------------------------------------
void clear()
{
m_error_message = std::nullopt;
}
//------------------------------------------------------------------------------
// NOLINTNEXTLINE(google-runtime-int)
void Execute(vtkObject* vtkNotUsed(caller) /*caller*/, unsigned long _event, void* _calldata) final
{
if(_event == vtkCommand::ErrorEvent)
{
m_error_message = static_cast<char*>(_calldata);
}
}
private:
std::optional<std::string> m_error_message;
};
//-----------------------------------------------------------------------------
vtk_mesher::vtk_mesher() noexcept :
filter(m_signals),
notifier(m_signals),
has_jobs(m_signals)
{
new_signal<signals::empty_t>(signals::COMPLETED);
new_signal<signals::empty_t>(signals::FAILED);
}
//-----------------------------------------------------------------------------
void vtk_mesher::configuring(const config_t& _config)
{
auto mode = _config.get<std::string>("config.<xmlattr>.mode", "add");
if(mode == "add")
{
m_mode = mode_t::ADD;
}
else if(mode == "replace")
{
m_mode = mode_t::REPLACE;
}
else
{
SIGHT_ERROR("Unsupported value for mode config : " << std::quoted(mode));
}
}
//-----------------------------------------------------------------------------
void vtk_mesher::starting()
{
}
//-----------------------------------------------------------------------------
void vtk_mesher::stopping()
{
}
//-----------------------------------------------------------------------------
void vtk_mesher::updating()
{
const auto job = std::make_shared<sight::core::jobs::job>(
"Meshing segmentation",
[this](sight::core::jobs::job& _running_job)
{
FW_PROFILE("mesh");
auto image_series = m_image.lock();
auto model_series = m_model.lock();
if(!image_series || !model_series)
{
std::string msg = "Invalid input/output data for model series reconstruction.";
SIGHT_ERROR(msg);
this->notifier::failure(msg);
this->async_emit(signals::FAILED);
_running_job.done();
return;
}
model_series->series::deep_copy(image_series.get_shared());
model_series->set_dicom_reference(image_series->get_dicom_reference());
// vtk img
auto vtk_image = vtkSmartPointer<vtkImageData>::New();
sight::io::vtk::to_vtk_image(image_series.get_shared(), vtk_image);
_running_job.done_work(1);
post_reconstruction_jobs(vtk_image, model_series.get_shared(), _running_job);
{
this->async_emit(signals::COMPLETED);
}
{
model_series->async_emit(sight::data::object::MODIFIED_SIG);
}
_running_job.done();
});
job->set_cancelable(false);
this->async_emit(has_jobs::signals::JOB_CREATED, core::jobs::base::sptr(job));
job->run().get();
}
//-----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> vtk_mesher::reconstruct(vtkSmartPointer<vtkImageData> _image, int _value)
{
// Initialize filters to be used
vtkNew<error_observer> error_obs;
vtkSmartPointer<vtkPolyDataAlgorithm> contour_filter;
// Contour filter
if(*m_use_flying_edges)
{
vtkSmartPointer<vtkDiscreteFlyingEdges3D> flying_edges = vtkSmartPointer<vtkDiscreteFlyingEdges3D>::New();
flying_edges->ComputeScalarsOn();
flying_edges->ComputeNormalsOn();
// Initialize the contour filter
flying_edges->SetValue(0, _value);
contour_filter = flying_edges;
}
else
{
vtkSmartPointer<vtkDiscreteMarchingCubes> marching_cubes = vtkSmartPointer<vtkDiscreteMarchingCubes>::New();
marching_cubes->ComputeScalarsOn();
marching_cubes->ComputeNormalsOn();
// Initialize the contour filter
marching_cubes->SetValue(0, _value);
contour_filter = marching_cubes;
}
contour_filter->SetInputData(_image);
contour_filter->AddObserver(vtkCommand::ErrorEvent, error_obs);
auto contour_timer = vtkSmartPointer<vtkExecutionTimer>::New();
contour_timer->SetFilter(contour_filter);
// Smooth filter
auto smooth_filter = vtkSmartPointer<vtkWindowedSincPolyDataFilter>::New();
smooth_filter->AddObserver(vtkCommand::ErrorEvent, error_obs);
smooth_filter->SetInputConnection(contour_filter->GetOutputPort());
smooth_filter->SetNumberOfIterations(static_cast<int>(*m_num_iterations));
smooth_filter->SetBoundarySmoothing(static_cast<vtkTypeBool>(*m_boundary_smoothing));
smooth_filter->SetPassBand(*m_pass_band);
smooth_filter->SetEdgeAngle(90);
smooth_filter->SetFeatureEdgeSmoothing(static_cast<vtkTypeBool>(*m_feature_smoothing));
smooth_filter->SetFeatureAngle(*m_feature_angle);
smooth_filter->SetNonManifoldSmoothing(static_cast<vtkTypeBool>(*m_non_manifold_smoothing));
// This improves stability, always on
smooth_filter->NormalizeCoordinatesOn();
auto smooth_timer = vtkSmartPointer<vtkExecutionTimer>::New();
smooth_timer->SetFilter(smooth_filter);
auto decimate_timer = vtkSmartPointer<vtkExecutionTimer>::New();
vtkSmartPointer<vtkPolyDataAlgorithm> last_filter = smooth_filter;
if(*m_reduction > 0)
{
// Decimator (if needed)
if(*m_quadric_reduction)
{
auto decimate_filter = vtkSmartPointer<vtkQuadricDecimation>::New();
decimate_filter->AddObserver(vtkCommand::ErrorEvent, error_obs);
decimate_filter->SetInputConnection(smooth_filter->GetOutputPort());
decimate_filter->SetTargetReduction(std::clamp(static_cast<double>(*m_reduction), 0.0, 100.0) / 100.0);
decimate_filter->VolumePreservationOn();
decimate_timer->SetFilter(decimate_filter);
last_filter = decimate_filter;
}
else
{
auto decimate_filter = vtkSmartPointer<vtkDecimatePro>::New();
decimate_filter->AddObserver(vtkCommand::ErrorEvent, error_obs);
decimate_filter->SetInputConnection(smooth_filter->GetOutputPort());
decimate_filter->SetTargetReduction(std::clamp(static_cast<double>(*m_reduction), 0.0, 100.0) / 100.0);
decimate_filter->SetPreserveTopology(static_cast<vtkTypeBool>(*m_preserve_topology));
decimate_filter->SplittingOn();
decimate_filter->BoundaryVertexDeletionOn();
decimate_timer->SetFilter(decimate_filter);
last_filter = decimate_filter;
}
}
last_filter->Update();
vtkSmartPointer<vtkPolyData> poly_data = last_filter->GetOutput();
SIGHT_INFO(this->get_id() << ": Value: " << _value << "Flying edges: " << std::to_string(*m_use_flying_edges));
SIGHT_INFO(this->get_id() << ": Contour timer: " << contour_timer->GetElapsedWallClockTime() << "s");
SIGHT_INFO(this->get_id() << ": Smooth timer: " << smooth_timer->GetElapsedWallClockTime() << "s");
SIGHT_INFO(this->get_id() << ": Decimate timer: " << decimate_timer->GetElapsedWallClockTime() << "s");
SIGHT_INFO(this->get_id() << ": Number of points: " << poly_data->GetNumberOfPoints());
SIGHT_INFO(this->get_id() << ": Number of cells: " << poly_data->GetNumberOfCells());
// Check for errors
if(auto error = error_obs->get_error(); error.has_value())
{
SIGHT_ERROR(*error);
this->notifier::failure(*error);
this->async_emit(signals::FAILED);
return nullptr;
}
error_obs->clear();
return poly_data;
}
//-----------------------------------------------------------------------------
void vtk_mesher::post_reconstruction_jobs(
vtkSmartPointer<vtkImageData> _image,
sight::data::model_series::sptr _model_series,
sight::core::jobs::job& _running_job
)
{
sight::data::model_series::reconstruction_vector_t recs;
auto config = this->get_config();
if(not config.get_child_optional("config.organ").has_value())
{
sight::service::config_t organ_cfg;
organ_cfg.put("organ.<xmlattr>.value", *m_value);
config.add_child("config", organ_cfg);
}
const auto srv_config = config.get_child("config");
const std::size_t num_organs = srv_config.count("organ");
std::atomic<std::uint64_t> done = 0;
static const std::uint64_t s_DONE_INCREMENT = 100 / (num_organs * 2); // 2 increments per organ
for(const auto& elt : boost::make_iterator_range(srv_config.equal_range("organ")))
{
const auto value = elt.second.get<int>("<xmlattr>.value");
const auto name = elt.second.get<std::string>("<xmlattr>.name", "organ");
const auto type = elt.second.get<std::string>("<xmlattr>.type", "");
const auto color_cfg = elt.second.get<std::string>("<xmlattr>.color", "#ffffffff");
const auto material_cfg = elt.second.get_optional<std::string>("<xmlattr>.material");
const auto uniforms_cfg = elt.second.get_optional<std::string>("<xmlattr>.uniforms");
const auto representation = elt.second.get<std::string>("<xmlattr>.representation", "SURFACE");
const auto split = elt.second.get<bool>("<xmlattr>.split", false);
const auto selected = elt.second.get<bool>("<xmlattr>.selected", false);
// Initialize the contour filter
vtkSmartPointer<vtkPolyData> poly_data = this->reconstruct(_image, value);
auto create_mesh = [&](vtkSmartPointer<vtkPolyData> _poly_data)
{
auto mesh = std::make_shared<sight::data::mesh>();
sight::io::vtk::helper::mesh::from_vtk_mesh(_poly_data, mesh);
auto reconstruction = std::make_shared<sight::data::reconstruction>();
reconstruction->set_organ_name(name);
reconstruction->set_structure_type(type);
reconstruction->set_is_visible(true);
reconstruction->set_mesh(mesh);
auto material = std::make_shared<sight::data::material>();
auto color = std::make_shared<sight::data::color>(color_cfg);
material->set_diffuse(color);
material->set_representation_mode(
sight::data::material::string_to_representation_mode(
representation
)
);
if(selected)
{
material->set_options_mode(sight::data::material::options_t::selected);
}
if(material_cfg.has_value())
{
data::string::sptr material_str = std::make_shared<data::string>();
material_str->set_value(*material_cfg);
data::string::sptr uniforms_str = std::make_shared<data::string>();
uniforms_str->set_value(*uniforms_cfg);
data::helper::field helper(material);
helper.set_field("material", material_str);
helper.set_field("uniforms", uniforms_str);
helper.notify();
}
reconstruction->set_material(material);
reconstruction->set_label(static_cast<std::uint32_t>(value));
recs.push_back(reconstruction);
};
done += s_DONE_INCREMENT;
_running_job.done_work(done);
if(poly_data != nullptr)
{
if(split)
{
auto connectivity_filter = vtkSmartPointer<vtkConnectivityFilter>::New();
connectivity_filter->SetInputData(poly_data);
connectivity_filter->SetExtractionModeToAllRegions();
connectivity_filter->ColorRegionsOn();
connectivity_filter->Update();
for(int i = 0 ; i < connectivity_filter->GetNumberOfExtractedRegions() ; i++)
{
auto threshold_filter = vtkSmartPointer<vtkThreshold>::New();
threshold_filter->SetInputData(connectivity_filter->GetOutput());
threshold_filter->SetLowerThreshold(i);
threshold_filter->SetUpperThreshold(i);
threshold_filter->SetInputArrayToProcess(
0,
0,
0,
vtkDataObject::FIELD_ASSOCIATION_CELLS,
"RegionId"
);
threshold_filter->Update();
auto geometry_filter = vtkSmartPointer<vtkGeometryFilter>::New();
geometry_filter->SetInputData(threshold_filter->GetOutput());
geometry_filter->Update();
vtkSmartPointer<vtkPolyData> region_poly_data = geometry_filter->GetOutput();
create_mesh(region_poly_data);
}
}
else
{
create_mesh(poly_data);
}
}
done += s_DONE_INCREMENT;
_running_job.done_work(done);
}
sight::data::model_series::reconstruction_vector_t out_recs = _model_series->get_reconstruction_db();
if(m_mode == mode_t::REPLACE)
{
out_recs.clear();
}
for(auto& rec : recs)
{
if(rec)
{
out_recs.push_back(rec);
}
}
_model_series->set_reconstruction_db(out_recs);
}
//-------------------------------------------------------------------------
vtk_mesher::connections_t vtk_mesher::auto_connections() const
{
return {
{m_boundary_smoothing, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_non_manifold_smoothing, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_feature_smoothing, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_preserve_topology, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_use_flying_edges, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_value, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_pass_band, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_num_iterations, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_feature_angle, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_reduction, data::object::MODIFIED_SIG, service::slots::UPDATE},
{m_quadric_reduction, data::object::MODIFIED_SIG, service::slots::UPDATE}
};
}
//-----------------------------------------------------------------------------
} // namespace sight::module::filter::mesh
|