• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmc-dev / openmc / 29891551345

22 Jul 2026 04:37AM UTC coverage: 81.403% (+0.07%) from 81.336%
29891551345

Pull #3965

github

web-flow
Merge a5acbdae5 into 852f92780
Pull Request #3965: MGXS Bootstrapping

18382 of 26608 branches covered (69.08%)

Branch coverage included in aggregate %.

91 of 91 new or added lines in 5 files covered. (100.0%)

328 existing lines in 4 files now uncovered.

59946 of 69614 relevant lines covered (86.11%)

49161457.77 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.71
/src/plot.cpp
1
#include "openmc/plot.h"
2

3
#include <algorithm>
4
#include <cmath>
5
#include <cstdio>
6
#include <fstream>
7
#include <sstream>
8

9
#include "openmc/tensor.h"
10
#include <fmt/core.h>
11
#include <fmt/ostream.h>
12
#ifdef USE_LIBPNG
13
#include <png.h>
14
#endif
15

16
#include "openmc/cell.h"
17
#include "openmc/constants.h"
18
#include "openmc/container_util.h"
19
#include "openmc/dagmc.h"
20
#include "openmc/error.h"
21
#include "openmc/file_utils.h"
22
#include "openmc/geometry.h"
23
#include "openmc/hdf5_interface.h"
24
#include "openmc/material.h"
25
#include "openmc/mesh.h"
26
#include "openmc/message_passing.h"
27
#include "openmc/openmp_interface.h"
28
#include "openmc/output.h"
29
#include "openmc/particle.h"
30
#include "openmc/progress_bar.h"
31
#include "openmc/random_lcg.h"
32
#include "openmc/settings.h"
33
#include "openmc/simulation.h"
34
#include "openmc/string_utils.h"
35
#include "openmc/tallies/filter.h"
36

37
namespace openmc {
38

39
//==============================================================================
40
// Constants
41
//==============================================================================
42

43
constexpr int PLOT_LEVEL_LOWEST {-1}; //!< lower bound on plot universe level
44
constexpr int32_t NOT_FOUND {-2};
45
constexpr int32_t OVERLAP {-3};
46

47
IdData::IdData(size_t h_res, size_t v_res, bool /*include_filter*/)
4,873✔
48
  : data_({v_res, h_res, 3}, NOT_FOUND)
4,873✔
49
{}
4,873✔
50

51
void IdData::set_value(size_t y, size_t x, const Particle& p, int level,
35,403,192✔
52
  Filter* /*filter*/, FilterMatch* /*match*/)
53
{
54
  // set cell data
55
  if (p.n_coord() <= level) {
35,403,192!
UNCOV
56
    data_(y, x, 0) = NOT_FOUND;
×
57
    data_(y, x, 1) = NOT_FOUND;
×
58
  } else {
59
    data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
35,403,192!
60
    data_(y, x, 1) = level == p.n_coord() - 1
35,403,192✔
61
                       ? p.cell_instance()
35,403,192!
UNCOV
62
                       : cell_instance_at_level(p, level);
×
63
  }
64

65
  // set material data
66
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
35,403,192✔
67
  if (p.material() == MATERIAL_VOID) {
35,403,192✔
68
    data_(y, x, 2) = MATERIAL_VOID;
27,301,736✔
69
  } else if (c->type_ == Fill::MATERIAL) {
8,101,456!
70
    Material* m = model::materials.at(p.material()).get();
8,101,456✔
71
    data_(y, x, 2) = m->id_;
8,101,456✔
72
  }
73
}
35,403,192✔
74

75
void IdData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
28,248✔
76
{
77
  for (size_t k = 0; k < data_.shape(2); ++k)
225,984!
78
    data_(y, x, k) = OVERLAP;
84,744✔
79
}
28,248✔
80

UNCOV
81
PropertyData::PropertyData(size_t h_res, size_t v_res, bool /*include_filter*/)
×
82
  : data_({v_res, h_res, 2}, NOT_FOUND)
×
83
{}
×
84

UNCOV
85
void PropertyData::set_value(size_t y, size_t x, const Particle& p, int level,
×
86
  Filter* /*filter*/, FilterMatch* /*match*/)
87
{
UNCOV
88
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
×
89
  data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN;
×
90
  data_(y, x, 1) = c->density(p.cell_instance());
×
91
}
×
92

UNCOV
93
void PropertyData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
×
94
{
UNCOV
95
  data_(y, x) = OVERLAP;
×
96
}
×
97

98
//==============================================================================
99
// RasterData implementation
100
//==============================================================================
101

102
RasterData::RasterData(size_t h_res, size_t v_res, bool include_filter)
432✔
103
  : id_data_({v_res, h_res, include_filter ? 4u : 3u}, NOT_FOUND),
842✔
104
    property_data_({v_res, h_res, 2}, static_cast<double>(NOT_FOUND)),
432✔
105
    include_filter_(include_filter)
432✔
106
{}
432✔
107

108
void RasterData::set_value(size_t y, size_t x, const Particle& p, int level,
3,747,753✔
109
  Filter* filter, FilterMatch* match)
110
{
111
  // set cell data
112
  if (p.n_coord() <= level) {
3,747,753!
UNCOV
113
    id_data_(y, x, 0) = NOT_FOUND;
×
114
    id_data_(y, x, 1) = NOT_FOUND;
×
115
  } else {
116
    id_data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
3,747,753!
117
    id_data_(y, x, 1) = level == p.n_coord() - 1
3,747,753✔
118
                          ? p.cell_instance()
3,747,753!
UNCOV
119
                          : cell_instance_at_level(p, level);
×
120
  }
121

122
  // set material data
123
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
3,747,753✔
124
  if (p.material() == MATERIAL_VOID) {
3,747,753✔
125
    id_data_(y, x, 2) = MATERIAL_VOID;
2,548,124✔
126
  } else if (c->type_ == Fill::MATERIAL) {
1,199,629!
127
    Material* m = model::materials.at(p.material()).get();
1,199,629✔
128
    id_data_(y, x, 2) = m->id_;
1,199,629✔
129
  }
130

131
  // set filter index (only if filter is being used)
132
  if (include_filter_ && filter) {
3,747,753!
133
    filter->get_all_bins(p, TallyEstimator::COLLISION, *match);
55,000✔
134
    if (match->bins_.empty()) {
55,000!
UNCOV
135
      id_data_(y, x, 3) = -1;
×
136
    } else {
137
      id_data_(y, x, 3) = match->bins_[0];
55,000✔
138
    }
139
    match->bins_.clear();
55,000!
140
    match->weights_.clear();
55,000!
141
  }
142

143
  // set temperature (in K)
144
  property_data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN;
3,747,753✔
145

146
  // set density (g/cm³)
147
  if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) {
3,747,753!
148
    Material* m = model::materials.at(p.material()).get();
1,199,629✔
149
    property_data_(y, x, 1) = c->density(p.cell_instance());
1,199,629✔
150
  }
151
}
3,747,753✔
152

153
void RasterData::set_overlap(size_t y, size_t x, int overlap_idx)
365,772✔
154
{
155
  // Set cell, instance, and material to OVERLAP, but preserve filter bin for
156
  // tally plotting. Cell encodes the overlap index as a negative number so that
157
  // it can be used to look up overlap information in the plotter.
158
  id_data_(y, x, 0) = OVERLAP - overlap_idx - 1;
365,772✔
159
  id_data_(y, x, 1) = OVERLAP;
365,772✔
160
  id_data_(y, x, 2) = OVERLAP;
365,772✔
161

162
  property_data_(y, x, 0) = OVERLAP;
365,772✔
163
  property_data_(y, x, 1) = OVERLAP;
365,772✔
164
}
365,772✔
165

166
//==============================================================================
167
// Global variables
168
//==============================================================================
169

170
namespace model {
171

172
std::unordered_map<int, int> plot_map;
173
vector<std::unique_ptr<PlottableInterface>> plots;
174
uint64_t plotter_seed = 1;
175

176
} // namespace model
177

178
//==============================================================================
179
// RUN_PLOT controls the logic for making one or many plots
180
//==============================================================================
181

182
extern "C" int openmc_plot_geometry()
121✔
183
{
184

185
  for (auto& pl : model::plots) {
407✔
186
    write_message(5, "Processing plot {}: {}...", pl->id(), pl->path_plot());
286✔
187
    pl->create_output();
286✔
188
  }
189

190
  return 0;
121✔
191
}
192

193
void PlottableInterface::write_image(const ImageData& data) const
231✔
194
{
195
#ifdef USE_LIBPNG
196
  output_png(path_plot(), data);
231✔
197
#else
198
  output_ppm(path_plot(), data);
199
#endif
200
}
231✔
201

202
void Plot::create_output() const
198✔
203
{
204
  if (PlotType::slice == type_) {
198✔
205
    // create 2D image
206
    ImageData image = create_image();
143✔
207
    write_image(image);
143✔
208
  } else if (PlotType::voxel == type_) {
198!
209
    // create voxel file for 3D viewing
210
    create_voxel();
55✔
211
  }
212
}
198✔
213

214
void Plot::print_info() const
154✔
215
{
216
  // Plot type
217
  if (PlotType::slice == type_) {
154✔
218
    fmt::print("Plot Type: Slice\n");
121✔
219
  } else if (PlotType::voxel == type_) {
33!
220
    fmt::print("Plot Type: Voxel\n");
33✔
221
  }
222

223
  // Plot parameters
224
  fmt::print("Origin: {} {} {}\n", origin_[0], origin_[1], origin_[2]);
154✔
225

226
  if (PlotType::slice == type_) {
154✔
227
    fmt::print("Width: {:4} {:4}\n", width_[0], width_[1]);
121✔
228
  } else if (PlotType::voxel == type_) {
33!
229
    fmt::print("Width: {:4} {:4} {:4}\n", width_[0], width_[1], width_[2]);
33✔
230
  }
231

232
  if (PlotColorBy::cells == color_by_) {
154✔
233
    fmt::print("Coloring: Cells\n");
88✔
234
  } else if (PlotColorBy::mats == color_by_) {
66!
235
    fmt::print("Coloring: Materials\n");
66✔
236
  }
237

238
  if (PlotType::slice == type_) {
154✔
239
    switch (basis_) {
121!
240
    case PlotBasis::xy:
77✔
241
      fmt::print("Basis: XY\n");
77✔
242
      break;
77✔
243
    case PlotBasis::xz:
22✔
244
      fmt::print("Basis: XZ\n");
22✔
245
      break;
22✔
246
    case PlotBasis::yz:
22✔
247
      fmt::print("Basis: YZ\n");
22✔
248
      break;
22✔
249
    }
250
    fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
121✔
251
  } else if (PlotType::voxel == type_) {
33!
252
    fmt::print("Voxels: {} {} {}\n", pixels()[0], pixels()[1], pixels()[2]);
33✔
253
  }
254
}
154✔
255

256
void read_plots_xml()
1,399✔
257
{
258
  // Check if plots.xml exists; this is only necessary when the plot runmode is
259
  // initiated. Otherwise, we want to read plots.xml because it may be called
260
  // later via the API. In that case, its ok for a plots.xml to not exist
261
  std::string filename = settings::path_input + "plots.xml";
1,399✔
262
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
1,399!
UNCOV
263
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
264
  }
265

266
  write_message("Reading plot XML file...", 5);
1,399✔
267

268
  // Parse plots.xml file
269
  pugi::xml_document doc;
1,399✔
270
  doc.load_file(filename.c_str());
1,399✔
271

272
  pugi::xml_node root = doc.document_element();
1,399✔
273

274
  read_plots_xml(root);
1,399✔
275
}
1,399✔
276

277
void read_plots_xml(pugi::xml_node root)
1,885✔
278
{
279
  for (auto node : root.children("plot")) {
2,855✔
280
    std::string plot_desc = "<auto>";
979✔
281
    if (check_for_node(node, "id")) {
979!
282
      plot_desc = get_node_value(node, "id", true);
979✔
283
    }
284

285
    if (check_for_node(node, "type")) {
979!
286
      std::string type_str = get_node_value(node, "type", true);
979✔
287
      if (type_str == "slice") {
979✔
288
        model::plots.emplace_back(
827✔
289
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,663✔
290
      } else if (type_str == "voxel") {
143✔
291
        model::plots.emplace_back(
55✔
292
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
110✔
293
      } else if (type_str == "wireframe_raytrace") {
88✔
294
        model::plots.emplace_back(
55✔
295
          std::make_unique<WireframeRayTracePlot>(node));
110✔
296
      } else if (type_str == "solid_raytrace") {
33!
297
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
33✔
298
      } else {
UNCOV
299
        fatal_error(fmt::format(
×
300
          "Unsupported plot type '{}' in plot {}", type_str, plot_desc));
301
      }
302
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
970✔
303
    } else {
970✔
UNCOV
304
      fatal_error(fmt::format("Must specify plot type in plot {}", plot_desc));
×
305
    }
306
  }
970✔
307
}
1,876✔
308

309
void free_memory_plot()
9,126✔
310
{
311
  model::plots.clear();
9,126✔
312
  model::plot_map.clear();
9,126✔
313
}
9,126✔
314

315
// creates an image based on user input from a plots.xml <plot>
316
// specification in the PNG/PPM format
317
ImageData Plot::create_image() const
143✔
318
{
319
  size_t width = pixels()[0];
143✔
320
  size_t height = pixels()[1];
143✔
321

322
  ImageData data({width, height}, not_found_);
143✔
323

324
  // generate ids for the plot
325
  auto ids = get_map<IdData>();
143✔
326

327
  // assign colors
328
  for (size_t y = 0; y < height; y++) {
30,063✔
329
    for (size_t x = 0; x < width; x++) {
7,622,120✔
330
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
7,592,200✔
331
      auto id = ids.data_(y, x, idx);
7,592,200✔
332
      // no setting needed if not found
333
      if (id == NOT_FOUND) {
7,592,200✔
334
        continue;
1,082,532✔
335
      }
336
      if (id == OVERLAP) {
6,537,916✔
337
        data(x, y) = overlap_color_;
28,248✔
338
        continue;
28,248✔
339
      }
340
      if (PlotColorBy::cells == color_by_) {
6,509,668✔
341
        data(x, y) = colors_[model::cell_map[id]];
3,011,668✔
342
      } else if (PlotColorBy::mats == color_by_) {
3,498,000!
343
        if (id == MATERIAL_VOID) {
3,498,000!
UNCOV
344
          data(x, y) = WHITE;
×
345
          continue;
×
346
        }
347
        data(x, y) = colors_[model::material_map[id]];
3,498,000✔
348
      } // color_by if-else
349
    }
350
  }
351

352
  // draw mesh lines if present
353
  if (index_meshlines_mesh_ >= 0) {
143✔
354
    draw_mesh_lines(data);
33✔
355
  }
356

357
  return data;
143✔
358
}
143✔
359

360
void PlottableInterface::set_id(pugi::xml_node plot_node)
979✔
361
{
362
  int id {C_NONE};
979✔
363
  if (check_for_node(plot_node, "id")) {
979!
364
    id = std::stoi(get_node_value(plot_node, "id"));
979✔
365
  }
366

367
  try {
979✔
368
    set_id(id);
979✔
UNCOV
369
  } catch (const std::runtime_error& e) {
×
370
    fatal_error(e.what());
×
371
  }
×
372
}
979✔
373

374
void PlottableInterface::set_id(int id)
990✔
375
{
376
  if (id < 0 && id != C_NONE) {
990!
UNCOV
377
    throw std::runtime_error {fmt::format("Invalid plot ID: {}", id)};
×
378
  }
379

380
  if (id == C_NONE) {
990✔
381
    id = 1;
11✔
382
    for (const auto& p : model::plots) {
22✔
383
      id = std::max(id, p->id() + 1);
22!
384
    }
385
  }
386

387
  if (id_ == id)
990!
388
    return;
389

390
  // Check to make sure this ID doesn't already exist
391
  if (model::plot_map.find(id) != model::plot_map.end()) {
990!
UNCOV
392
    throw std::runtime_error {
×
393
      fmt::format("Two or more plots use the same unique ID: {}", id)};
×
394
  }
395

396
  id_ = id;
990✔
397
}
398

399
// Checks if png or ppm is already present
400
bool file_extension_present(
970✔
401
  const std::string& filename, const std::string& extension)
402
{
403
  std::string file_extension_if_present =
970✔
404
    filename.substr(filename.find_last_of(".") + 1);
970✔
405
  if (file_extension_if_present == extension)
970✔
406
    return true;
55✔
407
  return false;
408
}
970✔
409

410
void Plot::set_output_path(pugi::xml_node plot_node)
891✔
411
{
412
  // Set output file path
413
  std::string filename;
891✔
414

415
  if (check_for_node(plot_node, "filename")) {
891✔
416
    filename = get_node_value(plot_node, "filename");
242✔
417
  } else {
418
    filename = fmt::format("plot_{}", id());
649✔
419
  }
420
  const std::string dir_if_present =
891✔
421
    filename.substr(0, filename.find_last_of("/") + 1);
891✔
422
  if (dir_if_present.size() > 0 && !dir_exists(dir_if_present)) {
891✔
423
    fatal_error(fmt::format("Directory '{}' does not exist!", dir_if_present));
9✔
424
  }
425
  // add appropriate file extension to name
426
  switch (type_) {
882!
427
  case PlotType::slice:
827✔
428
#ifdef USE_LIBPNG
429
    if (!file_extension_present(filename, "png"))
827!
430
      filename.append(".png");
827✔
431
#else
432
    if (!file_extension_present(filename, "ppm"))
433
      filename.append(".ppm");
434
#endif
435
    break;
436
  case PlotType::voxel:
55✔
437
    if (!file_extension_present(filename, "h5"))
55!
438
      filename.append(".h5");
55✔
439
    break;
440
  }
441

442
  path_plot_ = filename;
882✔
443

444
  // Copy plot pixel size
445
  vector<int> pxls = get_node_array<int>(plot_node, "pixels");
1,764✔
446
  if (PlotType::slice == type_) {
882✔
447
    if (pxls.size() == 2) {
827!
448
      pixels()[0] = pxls[0];
827✔
449
      pixels()[1] = pxls[1];
827✔
450
    } else {
UNCOV
451
      fatal_error(
×
452
        fmt::format("<pixels> must be length 2 in slice plot {}", id()));
×
453
    }
454
  } else if (PlotType::voxel == type_) {
55!
455
    if (pxls.size() == 3) {
55!
456
      pixels()[0] = pxls[0];
55✔
457
      pixels()[1] = pxls[1];
55✔
458
      pixels()[2] = pxls[2];
55✔
459
    } else {
UNCOV
460
      fatal_error(
×
461
        fmt::format("<pixels> must be length 3 in voxel plot {}", id()));
×
462
    }
463
  }
464
}
882✔
465

466
void PlottableInterface::set_bg_color(pugi::xml_node plot_node)
979✔
467
{
468
  // Copy plot background color
469
  if (check_for_node(plot_node, "background")) {
979✔
470
    vector<int> bg_rgb = get_node_array<int>(plot_node, "background");
44✔
471
    if (bg_rgb.size() == 3) {
44!
472
      not_found_ = bg_rgb;
44✔
473
    } else {
UNCOV
474
      fatal_error(fmt::format("Bad background RGB in plot {}", id()));
×
475
    }
476
  }
44✔
477
}
979✔
478

479
void Plot::set_basis(pugi::xml_node plot_node)
882✔
480
{
481
  // Copy plot basis
482
  if (PlotType::slice == type_) {
882✔
483
    std::string pl_basis = "xy";
827✔
484
    if (check_for_node(plot_node, "basis")) {
827!
485
      pl_basis = get_node_value(plot_node, "basis", true);
827✔
486
    }
487
    if ("xy" == pl_basis) {
827✔
488
      basis_ = PlotBasis::xy;
753✔
489
    } else if ("xz" == pl_basis) {
74✔
490
      basis_ = PlotBasis::xz;
22✔
491
    } else if ("yz" == pl_basis) {
52!
492
      basis_ = PlotBasis::yz;
52✔
493
    } else {
UNCOV
494
      fatal_error(
×
495
        fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id()));
×
496
    }
497
  }
827✔
498
}
882✔
499

500
void Plot::set_origin(pugi::xml_node plot_node)
882✔
501
{
502
  // Copy plotting origin
503
  auto pl_origin = get_node_array<double>(plot_node, "origin");
882✔
504
  if (pl_origin.size() == 3) {
882!
505
    origin_ = pl_origin;
882✔
506
  } else {
UNCOV
507
    fatal_error(fmt::format("Origin must be length 3 in plot {}", id()));
×
508
  }
509
}
882✔
510

511
void Plot::set_width(pugi::xml_node plot_node)
882✔
512
{
513
  // Copy plotting width
514
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
882✔
515
  if (PlotType::slice == type_) {
882✔
516
    if (pl_width.size() == 2) {
827!
517
      width_.x = pl_width[0];
827✔
518
      width_.y = pl_width[1];
827✔
519
      switch (basis_) {
827!
520
      case PlotBasis::xy:
753✔
521
        u_span_ = {width_.x, 0.0, 0.0};
753✔
522
        v_span_ = {0.0, width_.y, 0.0};
753✔
523
        break;
753✔
524
      case PlotBasis::xz:
22✔
525
        u_span_ = {width_.x, 0.0, 0.0};
22✔
526
        v_span_ = {0.0, 0.0, width_.y};
22✔
527
        break;
22✔
528
      case PlotBasis::yz:
52✔
529
        u_span_ = {0.0, width_.x, 0.0};
52✔
530
        v_span_ = {0.0, 0.0, width_.y};
52✔
531
        break;
52✔
UNCOV
532
      default:
×
533
        UNREACHABLE();
×
534
      }
535
    } else {
UNCOV
536
      fatal_error(
×
537
        fmt::format("<width> must be length 2 in slice plot {}", id()));
×
538
    }
539
  } else if (PlotType::voxel == type_) {
55!
540
    if (pl_width.size() == 3) {
55!
541
      pl_width = get_node_array<double>(plot_node, "width");
110✔
542
      width_ = pl_width;
55✔
543
    } else {
UNCOV
544
      fatal_error(
×
545
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
546
    }
547
  }
548
}
882✔
549

550
void PlottableInterface::set_universe(pugi::xml_node plot_node)
979✔
551
{
552
  // Copy plot universe level
553
  if (check_for_node(plot_node, "level")) {
979!
UNCOV
554
    level_ = std::stoi(get_node_value(plot_node, "level"));
×
555
    if (level_ < 0) {
×
556
      fatal_error(fmt::format("Bad universe level in plot {}", id()));
×
557
    }
558
  } else {
559
    level_ = PLOT_LEVEL_LOWEST;
979✔
560
  }
561
}
979✔
562

563
void PlottableInterface::set_color_by(pugi::xml_node plot_node)
979✔
564
{
565
  // Copy plot color type
566
  std::string pl_color_by = "cell";
979✔
567
  if (check_for_node(plot_node, "color_by")) {
979✔
568
    pl_color_by = get_node_value(plot_node, "color_by", true);
946✔
569
  }
570
  if ("cell" == pl_color_by) {
979✔
571
    color_by_ = PlotColorBy::cells;
287✔
572
  } else if ("material" == pl_color_by) {
692!
573
    color_by_ = PlotColorBy::mats;
692✔
574
  } else {
UNCOV
575
    fatal_error(fmt::format(
×
576
      "Unsupported plot color type '{}' in plot {}", pl_color_by, id()));
×
577
  }
578
}
979✔
579

580
void PlottableInterface::set_default_colors()
990✔
581
{
582
  // Copy plot color type and initialize all colors randomly
583
  if (PlotColorBy::cells == color_by_) {
990✔
584
    colors_.resize(model::cells.size());
287✔
585
  } else if (PlotColorBy::mats == color_by_) {
703!
586
    colors_.resize(model::materials.size());
703✔
587
  }
588

589
  for (auto& c : colors_) {
4,431✔
590
    c = random_color();
3,441✔
591
    // make sure we don't interfere with some default colors
592
    while (c == RED || c == WHITE) {
3,441!
UNCOV
593
      c = random_color();
×
594
    }
595
  }
596
}
990✔
597

598
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
979✔
599
{
600
  for (auto cn : plot_node.children("color")) {
1,166✔
601
    // Make sure 3 values are specified for RGB
602
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
187✔
603
    if (user_rgb.size() != 3) {
187!
UNCOV
604
      fatal_error(fmt::format("Bad RGB in plot {}", id()));
×
605
    }
606
    // Ensure that there is an id for this color specification
607
    int col_id;
187✔
608
    if (check_for_node(cn, "id")) {
187!
609
      col_id = std::stoi(get_node_value(cn, "id"));
374✔
610
    } else {
UNCOV
611
      fatal_error(fmt::format(
×
612
        "Must specify id for color specification in plot {}", id()));
×
613
    }
614
    // Add RGB
615
    if (PlotColorBy::cells == color_by_) {
187✔
616
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
88!
617
        col_id = model::cell_map[col_id];
88✔
618
        colors_[col_id] = user_rgb;
88✔
619
      } else {
UNCOV
620
        warning(fmt::format(
×
621
          "Could not find cell {} specified in plot {}", col_id, id()));
×
622
      }
623
    } else if (PlotColorBy::mats == color_by_) {
99!
624
      if (model::material_map.find(col_id) != model::material_map.end()) {
99!
625
        col_id = model::material_map[col_id];
99✔
626
        colors_[col_id] = user_rgb;
99✔
627
      } else {
UNCOV
628
        warning(fmt::format(
×
629
          "Could not find material {} specified in plot {}", col_id, id()));
×
630
      }
631
    }
632
  } // color node loop
187✔
633
}
979✔
634

635
void Plot::set_meshlines(pugi::xml_node plot_node)
882✔
636
{
637
  // Deal with meshlines
638
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
882✔
639

640
  if (!mesh_line_nodes.empty()) {
882✔
641
    if (PlotType::voxel == type_) {
33!
UNCOV
642
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
643
    }
644

645
    if (mesh_line_nodes.size() == 1) {
33!
646
      // Get first meshline node
647
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
33✔
648

649
      // Check mesh type
650
      std::string meshtype;
33✔
651
      if (check_for_node(meshlines_node, "meshtype")) {
33!
652
        meshtype = get_node_value(meshlines_node, "meshtype");
33✔
653
      } else {
UNCOV
654
        fatal_error(fmt::format(
×
655
          "Must specify a meshtype for meshlines specification in plot {}",
UNCOV
656
          id()));
×
657
      }
658

659
      // Ensure that there is a linewidth for this meshlines specification
660
      std::string meshline_width;
33✔
661
      if (check_for_node(meshlines_node, "linewidth")) {
33!
662
        meshline_width = get_node_value(meshlines_node, "linewidth");
33✔
663
        meshlines_width_ = std::stoi(meshline_width);
33✔
664
      } else {
UNCOV
665
        fatal_error(fmt::format(
×
666
          "Must specify a linewidth for meshlines specification in plot {}",
UNCOV
667
          id()));
×
668
      }
669

670
      // Check for color
671
      if (check_for_node(meshlines_node, "color")) {
33!
672
        // Check and make sure 3 values are specified for RGB
UNCOV
673
        vector<int> ml_rgb = get_node_array<int>(meshlines_node, "color");
×
674
        if (ml_rgb.size() != 3) {
×
675
          fatal_error(
×
676
            fmt::format("Bad RGB for meshlines color in plot {}", id()));
×
677
        }
UNCOV
678
        meshlines_color_ = ml_rgb;
×
679
      }
×
680

681
      // Set mesh based on type
682
      if ("ufs" == meshtype) {
33!
UNCOV
683
        if (!simulation::ufs_mesh) {
×
684
          fatal_error(
×
685
            fmt::format("No UFS mesh for meshlines on plot {}", id()));
×
686
        } else {
UNCOV
687
          for (int i = 0; i < model::meshes.size(); ++i) {
×
688
            if (const auto* m =
×
689
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
×
690
              if (m == simulation::ufs_mesh) {
×
691
                index_meshlines_mesh_ = i;
×
692
              }
693
            }
694
          }
UNCOV
695
          if (index_meshlines_mesh_ == -1)
×
696
            fatal_error("Could not find the UFS mesh for meshlines plot");
×
697
        }
698
      } else if ("entropy" == meshtype) {
33✔
699
        if (!simulation::entropy_mesh) {
22!
UNCOV
700
          fatal_error(
×
701
            fmt::format("No entropy mesh for meshlines on plot {}", id()));
×
702
        } else {
703
          for (int i = 0; i < model::meshes.size(); ++i) {
55✔
704
            if (const auto* m =
66✔
705
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
55!
706
              if (m == simulation::entropy_mesh) {
22!
707
                index_meshlines_mesh_ = i;
22✔
708
              }
709
            }
710
          }
711
          if (index_meshlines_mesh_ == -1)
22!
UNCOV
712
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
713
        }
714
      } else if ("tally" == meshtype) {
11!
715
        // Ensure that there is a mesh id if the type is tally
716
        int tally_mesh_id;
11✔
717
        if (check_for_node(meshlines_node, "id")) {
11!
718
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
22✔
719
        } else {
UNCOV
720
          std::stringstream err_msg;
×
721
          fatal_error(fmt::format("Must specify a mesh id for meshlines tally "
×
722
                                  "mesh specification in plot {}",
UNCOV
723
            id()));
×
724
        }
×
725
        // find the tally index
726
        int idx;
11✔
727
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
11✔
728
        if (err != 0) {
11!
UNCOV
729
          fatal_error(fmt::format("Could not find mesh {} specified in "
×
730
                                  "meshlines for plot {}",
UNCOV
731
            tally_mesh_id, id()));
×
732
        }
733
        index_meshlines_mesh_ = idx;
11✔
734
      } else {
UNCOV
735
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
736
      }
737
    } else {
33✔
UNCOV
738
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
739
    }
740
  }
741
}
882✔
742

743
void PlottableInterface::set_mask(pugi::xml_node plot_node)
979✔
744
{
745
  // Deal with masks
746
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
979✔
747

748
  if (!mask_nodes.empty()) {
979✔
749
    if (mask_nodes.size() == 1) {
33!
750
      // Get pointer to mask
751
      pugi::xml_node mask_node = mask_nodes[0].node();
33✔
752

753
      // Determine how many components there are and allocate
754
      vector<int> iarray = get_node_array<int>(mask_node, "components");
33✔
755
      if (iarray.size() == 0) {
33!
UNCOV
756
        fatal_error(
×
757
          fmt::format("Missing <components> in mask of plot {}", id()));
×
758
      }
759

760
      // First we need to change the user-specified identifiers to indices
761
      // in the cell and material arrays
762
      for (auto& col_id : iarray) {
99✔
763
        if (PlotColorBy::cells == color_by_) {
66!
764
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
765
            col_id = model::cell_map[col_id];
66✔
766
          } else {
UNCOV
767
            fatal_error(fmt::format("Could not find cell {} specified in the "
×
768
                                    "mask in plot {}",
UNCOV
769
              col_id, id()));
×
770
          }
UNCOV
771
        } else if (PlotColorBy::mats == color_by_) {
×
772
          if (model::material_map.find(col_id) != model::material_map.end()) {
×
773
            col_id = model::material_map[col_id];
×
774
          } else {
UNCOV
775
            fatal_error(fmt::format("Could not find material {} specified in "
×
776
                                    "the mask in plot {}",
UNCOV
777
              col_id, id()));
×
778
          }
779
        }
780
      }
781

782
      // Alter colors based on mask information
783
      for (int j = 0; j < colors_.size(); j++) {
132✔
784
        if (contains(iarray, j)) {
99✔
785
          if (check_for_node(mask_node, "background")) {
66!
786
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
66✔
787
            colors_[j] = bg_rgb;
66✔
788
          } else {
66✔
UNCOV
789
            colors_[j] = WHITE;
×
790
          }
791
        }
792
      }
793

794
    } else {
33✔
UNCOV
795
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
796
    }
797
  }
798
}
979✔
799

800
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
979✔
801
{
802
  color_overlaps_ = false;
979✔
803
  if (check_for_node(plot_node, "show_overlaps")) {
979✔
804
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
22✔
805
    // check for custom overlap color
806
    if (check_for_node(plot_node, "overlap_color")) {
22✔
807
      if (!color_overlaps_) {
11!
UNCOV
808
        warning(fmt::format(
×
809
          "Overlap color specified in plot {} but overlaps won't be shown.",
UNCOV
810
          id()));
×
811
      }
812
      vector<int> olap_clr = get_node_array<int>(plot_node, "overlap_color");
11✔
813
      if (olap_clr.size() == 3) {
11!
814
        overlap_color_ = olap_clr;
11✔
815
      } else {
UNCOV
816
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
817
      }
818
    }
11✔
819
  }
820

821
  // make sure we allocate the vector for counting overlap checks if
822
  // they're going to be plotted
823
  if (color_overlaps_ && settings::run_mode == RunMode::PLOTTING) {
979!
824
    settings::check_overlaps = true;
22✔
825
    model::overlap_check_count.resize(model::cells.size(), 0);
22✔
826
  }
827
}
979✔
828

829
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
979✔
830
{
831
  set_id(plot_node);
979✔
832
  set_bg_color(plot_node);
979✔
833
  set_universe(plot_node);
979✔
834
  set_color_by(plot_node);
979✔
835
  set_default_colors();
979✔
836
  set_user_colors(plot_node);
979✔
837
  set_mask(plot_node);
979✔
838
  set_overlap_color(plot_node);
979✔
839
}
979✔
840

841
Plot::Plot(pugi::xml_node plot_node, PlotType type)
891✔
842
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
891✔
843
{
844
  set_output_path(plot_node);
891✔
845
  set_basis(plot_node);
882✔
846
  set_origin(plot_node);
882✔
847
  set_width(plot_node);
882✔
848
  set_meshlines(plot_node);
882✔
849
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
882✔
850
  show_overlaps_ = color_overlaps_;
882✔
851
}
882✔
852

853
//==============================================================================
854
// OUTPUT_PPM writes out a previously generated image to a PPM file
855
//==============================================================================
856

UNCOV
857
void output_ppm(const std::string& filename, const ImageData& data)
×
858
{
859
  // Open PPM file for writing
UNCOV
860
  std::string fname = filename;
×
861
  fname = strtrim(fname);
×
862
  std::ofstream of;
×
863

UNCOV
864
  of.open(fname);
×
865

866
  // Write header
UNCOV
867
  of << "P6\n";
×
868
  of << data.shape(0) << " " << data.shape(1) << "\n";
×
869
  of << "255\n";
×
870
  of.close();
×
871

UNCOV
872
  of.open(fname, std::ios::binary | std::ios::app);
×
873
  // Write color for each pixel
UNCOV
874
  for (int y = 0; y < data.shape(1); y++) {
×
875
    for (int x = 0; x < data.shape(0); x++) {
×
876
      RGBColor rgb = data(x, y);
×
877
      of << rgb.red << rgb.green << rgb.blue;
×
878
    }
879
  }
UNCOV
880
  of << "\n";
×
881
}
×
882

883
//==============================================================================
884
// OUTPUT_PNG writes out a previously generated image to a PNG file
885
//==============================================================================
886

887
#ifdef USE_LIBPNG
888
void output_png(const std::string& filename, const ImageData& data)
231✔
889
{
890
  // Open PNG file for writing
891
  std::string fname = filename;
231✔
892
  fname = strtrim(fname);
231✔
893
  auto fp = std::fopen(fname.c_str(), "wb");
231✔
894

895
  // Initialize write and info structures
896
  auto png_ptr =
231✔
897
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
231✔
898
  auto info_ptr = png_create_info_struct(png_ptr);
231✔
899

900
  // Setup exception handling
901
  if (setjmp(png_jmpbuf(png_ptr)))
231!
UNCOV
902
    fatal_error("Error during png creation");
×
903

904
  png_init_io(png_ptr, fp);
231✔
905

906
  // Write header (8 bit colour depth)
907
  int width = data.shape(0);
231!
908
  int height = data.shape(1);
231!
909
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB,
231✔
910
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
911
  png_write_info(png_ptr, info_ptr);
231✔
912

913
  // Allocate memory for one row (3 bytes per pixel - RGB)
914
  std::vector<png_byte> row(3 * width);
231✔
915

916
  // Write color for each pixel
917
  for (int y = 0; y < height; y++) {
47,751✔
918
    for (int x = 0; x < width; x++) {
11,159,720✔
919
      RGBColor rgb = data(x, y);
11,112,200✔
920
      row[3 * x] = rgb.red;
11,112,200✔
921
      row[3 * x + 1] = rgb.green;
11,112,200✔
922
      row[3 * x + 2] = rgb.blue;
11,112,200✔
923
    }
924
    png_write_row(png_ptr, row.data());
47,520✔
925
  }
926

927
  // End write
928
  png_write_end(png_ptr, nullptr);
231✔
929

930
  // Clean up data structures
931
  std::fclose(fp);
231✔
932
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
231✔
933
  png_destroy_write_struct(&png_ptr, &info_ptr);
231✔
934
}
231✔
935
#endif
936

937
//==============================================================================
938
// DRAW_MESH_LINES draws mesh line boundaries on an image
939
//==============================================================================
940

941
void Plot::draw_mesh_lines(ImageData& data) const
33✔
942
{
943
  RGBColor rgb;
33!
944
  rgb = meshlines_color_;
33✔
945

946
  int ax1, ax2;
33✔
947
  Position expected_u {};
33✔
948
  Position expected_v {};
33✔
949
  switch (basis_) {
33!
950
  case PlotBasis::xy:
22✔
951
    ax1 = 0;
22✔
952
    ax2 = 1;
22✔
953
    expected_u = {width_[0], 0.0, 0.0};
22✔
954
    expected_v = {0.0, width_[1], 0.0};
22✔
955
    break;
22✔
956
  case PlotBasis::xz:
11✔
957
    ax1 = 0;
11✔
958
    ax2 = 2;
11✔
959
    expected_u = {width_[0], 0.0, 0.0};
11✔
960
    expected_v = {0.0, 0.0, width_[1]};
11✔
961
    break;
11✔
UNCOV
962
  case PlotBasis::yz:
×
963
    ax1 = 1;
×
964
    ax2 = 2;
×
965
    expected_u = {0.0, width_[0], 0.0};
×
966
    expected_v = {0.0, 0.0, width_[1]};
×
967
    break;
×
968
  default:
×
969
    UNREACHABLE();
×
970
  }
971

972
  // Meshlines rely on axis-aligned indexing in global coordinates.
973
  constexpr double rel_tol {1e-12};
33✔
974
  double span_tol = rel_tol * (1.0 + u_span_.norm() + v_span_.norm());
33✔
975
  if ((u_span_ - expected_u).norm() > span_tol ||
66!
976
      (v_span_ - expected_v).norm() > span_tol) {
33✔
UNCOV
977
    fatal_error("Meshlines are only supported for axis-aligned slice plots.");
×
978
  }
979

980
  Position ll_plot {origin_};
33✔
981
  Position ur_plot {origin_};
33✔
982

983
  ll_plot[ax1] -= width_[0] / 2.;
33✔
984
  ll_plot[ax2] -= width_[1] / 2.;
33✔
985
  ur_plot[ax1] += width_[0] / 2.;
33✔
986
  ur_plot[ax2] += width_[1] / 2.;
33✔
987

988
  Position width = ur_plot - ll_plot;
33✔
989

990
  // Find the (axis-aligned) lines of the mesh that intersect this plot.
991
  auto axis_lines =
33✔
992
    model::meshes[index_meshlines_mesh_]->plot(ll_plot, ur_plot);
33✔
993

994
  // Find the bounds along the second axis (accounting for low-D meshes).
995
  int ax2_min, ax2_max;
33✔
996
  if (axis_lines.second.size() > 0) {
33!
997
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
33✔
998
    ax2_min = (1.0 - frac) * pixels()[1];
33✔
999
    if (ax2_min < 0)
33✔
1000
      ax2_min = 0;
1001
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
33✔
1002
    ax2_max = (1.0 - frac) * pixels()[1];
33!
1003
    if (ax2_max > pixels()[1])
33!
UNCOV
1004
      ax2_max = pixels()[1];
×
1005
  } else {
UNCOV
1006
    ax2_min = 0;
×
1007
    ax2_max = pixels()[1];
×
1008
  }
1009

1010
  // Iterate across the first axis and draw lines.
1011
  for (auto ax1_val : axis_lines.first) {
187✔
1012
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
154✔
1013
    int ax1_ind = frac * pixels()[0];
154✔
1014
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
24,948✔
1015
      for (int plus = 0; plus <= meshlines_width_; plus++) {
49,588✔
1016
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
24,794!
1017
          data(ax1_ind + plus, ax2_ind) = rgb;
24,794✔
1018
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
24,794!
1019
          data(ax1_ind - plus, ax2_ind) = rgb;
24,794✔
1020
      }
1021
    }
1022
  }
1023

1024
  // Find the bounds along the first axis.
1025
  int ax1_min, ax1_max;
33✔
1026
  if (axis_lines.first.size() > 0) {
33!
1027
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
33✔
1028
    ax1_min = frac * pixels()[0];
33✔
1029
    if (ax1_min < 0)
33✔
1030
      ax1_min = 0;
1031
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
33✔
1032
    ax1_max = frac * pixels()[0];
33!
1033
    if (ax1_max > pixels()[0])
33!
UNCOV
1034
      ax1_max = pixels()[0];
×
1035
  } else {
UNCOV
1036
    ax1_min = 0;
×
1037
    ax1_max = pixels()[0];
×
1038
  }
1039

1040
  // Iterate across the second axis and draw lines.
1041
  for (auto ax2_val : axis_lines.second) {
209✔
1042
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
176✔
1043
    int ax2_ind = (1.0 - frac) * pixels()[1];
176✔
1044
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
28,336✔
1045
      for (int plus = 0; plus <= meshlines_width_; plus++) {
56,320✔
1046
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
28,160!
1047
          data(ax1_ind, ax2_ind + plus) = rgb;
28,160✔
1048
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
28,160!
1049
          data(ax1_ind, ax2_ind - plus) = rgb;
28,160✔
1050
      }
1051
    }
1052
  }
1053
}
33✔
1054

1055
/* outputs a binary file that can be input into silomesh for 3D geometry
1056
 * visualization.  It works the same way as create_image by dragging a particle
1057
 * across the geometry for the specified number of voxels. The first 3 int's in
1058
 * the binary are the number of x, y, and z voxels.  The next 3 double's are
1059
 * the widths of the voxels in the x, y, and z directions. The next 3 double's
1060
 * are the x, y, and z coordinates of the lower left point. Finally the binary
1061
 * is filled with entries of four int's each. Each 'row' in the binary contains
1062
 * four int's: 3 for x,y,z position and 1 for cell or material id.  For 1
1063
 * million voxels this produces a file of approximately 15MB.
1064
 */
1065
void Plot::create_voxel() const
55✔
1066
{
1067
  // compute voxel widths in each direction
1068
  array<double, 3> vox;
55✔
1069
  vox[0] = width_[0] / static_cast<double>(pixels()[0]);
55✔
1070
  vox[1] = width_[1] / static_cast<double>(pixels()[1]);
55✔
1071
  vox[2] = width_[2] / static_cast<double>(pixels()[2]);
55✔
1072

1073
  // initial particle position
1074
  Position ll = origin_ - width_ / 2.;
55✔
1075

1076
  // Open binary plot file for writing
1077
  std::ofstream of;
55✔
1078
  std::string fname = std::string(path_plot_);
55✔
1079
  fname = strtrim(fname);
55✔
1080
  hid_t file_id = file_open(fname, 'w');
55✔
1081

1082
  // write header info
1083
  write_attribute(file_id, "filetype", "voxel");
55✔
1084
  write_attribute(file_id, "version", VERSION_VOXEL);
55✔
1085
  write_attribute(file_id, "openmc_version", VERSION);
55✔
1086

1087
#ifdef GIT_SHA1
1088
  write_attribute(file_id, "git_sha1", GIT_SHA1);
1089
#endif
1090

1091
  // Write current date and time
1092
  write_attribute(file_id, "date_and_time", time_stamp().c_str());
110✔
1093
  array<int, 3> h5_pixels;
55✔
1094
  std::copy(pixels().begin(), pixels().end(), h5_pixels.begin());
55✔
1095
  write_attribute(file_id, "num_voxels", h5_pixels);
55✔
1096
  write_attribute(file_id, "voxel_width", vox);
55✔
1097
  write_attribute(file_id, "lower_left", ll);
55✔
1098

1099
  // Create dataset for voxel data -- note that the dimensions are reversed
1100
  // since we want the order in the file to be z, y, x
1101
  hsize_t dims[3];
55✔
1102
  dims[0] = pixels()[2];
55✔
1103
  dims[1] = pixels()[1];
55✔
1104
  dims[2] = pixels()[0];
55✔
1105
  hid_t dspace, dset, memspace;
55✔
1106
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
55✔
1107

1108
  SlicePlotBase pltbase;
55✔
1109
  pltbase.origin_ = origin_;
55✔
1110
  pltbase.u_span_ = {width_.x, 0.0, 0.0};
55✔
1111
  pltbase.v_span_ = {0.0, width_.y, 0.0};
55✔
1112
  pltbase.pixels() = pixels();
55✔
1113
  pltbase.show_overlaps_ = color_overlaps_;
55✔
1114

1115
  ProgressBar pb;
55✔
1116
  for (int z = 0; z < pixels()[2]; z++) {
4,785✔
1117
    // update z coordinate
1118
    pltbase.origin_.z = ll.z + z * vox[2];
4,730✔
1119

1120
    // generate ids using plotbase
1121
    IdData ids = pltbase.get_map<IdData>();
4,730✔
1122

1123
    // select only cell/material ID data and flip the y-axis
1124
    int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
4,730!
1125
    // Extract 2D slice at index idx from 3D data
1126
    size_t rows = ids.data_.shape(0);
4,730!
1127
    size_t cols = ids.data_.shape(1);
4,730!
1128
    tensor::Tensor<int32_t> data_slice({rows, cols});
4,730✔
1129
    for (size_t r = 0; r < rows; ++r)
912,230✔
1130
      for (size_t c = 0; c < cols; ++c)
179,382,500✔
1131
        data_slice(r, c) = ids.data_(r, c, idx);
178,475,000✔
1132
    tensor::Tensor<int32_t> data_flipped = data_slice.flip(0);
4,730✔
1133

1134
    // Write to HDF5 dataset
1135
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
4,730✔
1136

1137
    // update progress bar
1138
    pb.set_value(
4,730✔
1139
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
4,730✔
1140
  }
14,190✔
1141

1142
  voxel_finalize(dspace, dset, memspace);
55✔
1143
  file_close(file_id);
55✔
1144
}
55✔
1145

1146
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
55✔
1147
  hid_t* memspace)
1148
{
1149
  // Create dataspace/dataset for voxel data
1150
  *dspace = H5Screate_simple(3, dims, nullptr);
55✔
1151
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
55✔
1152
    H5P_DEFAULT, H5P_DEFAULT);
1153

1154
  // Create dataspace for a slice of the voxel
1155
  hsize_t dims_slice[2] {dims[1], dims[2]};
55✔
1156
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
55✔
1157

1158
  // Select hyperslab in dataspace
1159
  hsize_t start[3] {0, 0, 0};
55✔
1160
  hsize_t count[3] {1, dims[1], dims[2]};
55✔
1161
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
55✔
1162
}
55✔
1163

1164
void voxel_write_slice(
4,730✔
1165
  int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
1166
{
1167
  hssize_t offset[3] {x, 0, 0};
4,730✔
1168
  H5Soffset_simple(dspace, offset);
4,730✔
1169
  H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
4,730✔
1170
}
4,730✔
1171

1172
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
55✔
1173
{
1174
  H5Dclose(dset);
55✔
1175
  H5Sclose(dspace);
55✔
1176
  H5Sclose(memspace);
55✔
1177
}
55✔
1178

1179
RGBColor random_color(void)
3,441✔
1180
{
1181
  return {int(prn(&model::plotter_seed) * 255),
3,441✔
1182
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
3,441✔
1183
}
1184

1185
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
88✔
1186
{
1187
  set_look_at(node);
88✔
1188
  set_camera_position(node);
88✔
1189
  set_field_of_view(node);
88✔
1190
  set_pixels(node);
88✔
1191
  set_orthographic_width(node);
88✔
1192
  set_output_path(node);
88✔
1193

1194
  if (check_for_node(node, "orthographic_width") &&
99!
1195
      check_for_node(node, "field_of_view"))
11✔
UNCOV
1196
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1197
                "parameters.");
1198
}
88✔
1199

1200
void RayTracePlot::update_view()
110✔
1201
{
1202
  // Get centerline vector for camera-to-model. We create vectors around this
1203
  // that form a pixel array, and then trace rays along that.
1204
  auto up = up_ / up_.norm();
110✔
1205
  Direction looking_direction = look_at_ - camera_position_;
110✔
1206
  looking_direction /= looking_direction.norm();
110✔
1207
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
110!
UNCOV
1208
    fatal_error("Up vector cannot align with vector between camera position "
×
1209
                "and look_at!");
1210
  Direction cam_yaxis = looking_direction.cross(up);
110✔
1211
  cam_yaxis /= cam_yaxis.norm();
110✔
1212
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
110✔
1213
  cam_zaxis /= cam_zaxis.norm();
110✔
1214

1215
  // Cache the camera-to-model matrix
1216
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
110✔
1217
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
110✔
1218
    cam_yaxis.z, cam_zaxis.z};
110✔
1219
}
110✔
1220

1221
WireframeRayTracePlot::WireframeRayTracePlot(pugi::xml_node node)
55✔
1222
  : RayTracePlot(node)
55✔
1223
{
1224
  set_opacities(node);
55✔
1225
  set_wireframe_thickness(node);
55✔
1226
  set_wireframe_ids(node);
55✔
1227
  set_wireframe_color(node);
55✔
1228
  update_view();
55✔
1229
}
55✔
1230

1231
void WireframeRayTracePlot::set_wireframe_color(pugi::xml_node plot_node)
55✔
1232
{
1233
  // Copy plot wireframe color
1234
  if (check_for_node(plot_node, "wireframe_color")) {
55!
UNCOV
1235
    vector<int> w_rgb = get_node_array<int>(plot_node, "wireframe_color");
×
1236
    if (w_rgb.size() == 3) {
×
1237
      wireframe_color_ = w_rgb;
×
1238
    } else {
UNCOV
1239
      fatal_error(fmt::format("Bad wireframe RGB in plot {}", id()));
×
1240
    }
UNCOV
1241
  }
×
1242
}
55✔
1243

1244
void RayTracePlot::set_output_path(pugi::xml_node node)
88✔
1245
{
1246
  // Set output file path
1247
  std::string filename;
88✔
1248

1249
  if (check_for_node(node, "filename")) {
88✔
1250
    filename = get_node_value(node, "filename");
77✔
1251
  } else {
1252
    filename = fmt::format("plot_{}", id());
11✔
1253
  }
1254

1255
#ifdef USE_LIBPNG
1256
  if (!file_extension_present(filename, "png"))
88✔
1257
    filename.append(".png");
33✔
1258
#else
1259
  if (!file_extension_present(filename, "ppm"))
1260
    filename.append(".ppm");
1261
#endif
1262
  path_plot_ = filename;
176✔
1263
}
88✔
1264

1265
bool WireframeRayTracePlot::trackstack_equivalent(
3,041,159✔
1266
  const std::vector<TrackSegment>& track1,
1267
  const std::vector<TrackSegment>& track2) const
1268
{
1269
  if (wireframe_ids_.empty()) {
3,041,159✔
1270
    // Draw wireframe for all surfaces/cells/materials
1271
    if (track1.size() != track2.size())
2,545,070✔
1272
      return false;
1273
    for (int i = 0; i < track1.size(); ++i) {
6,707,954✔
1274
      if (track1[i].id != track2[i].id ||
4,236,771✔
1275
          track1[i].surface_index != track2[i].surface_index) {
4,236,639✔
1276
        return false;
1277
      }
1278
    }
1279
    return true;
1280
  } else {
1281
    // This runs in O(nm) where n is the intersection stack size
1282
    // and m is the number of IDs we are wireframing. A simpler
1283
    // algorithm can likely be found.
1284
    for (const int id : wireframe_ids_) {
986,194✔
1285
      int t1_i = 0;
496,089✔
1286
      int t2_i = 0;
496,089✔
1287

1288
      // Advance to first instance of the ID
1289
      while (t1_i < track1.size() && t2_i < track2.size()) {
562,430✔
1290
        while (t1_i < track1.size() && track1[t1_i].id != id)
392,832✔
1291
          t1_i++;
229,053✔
1292
        while (t2_i < track2.size() && track2[t2_i].id != id)
393,668✔
1293
          t2_i++;
229,889✔
1294

1295
        // This one is really important!
1296
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
163,779✔
1297
            (t1_i != track1.size() && t2_i == track2.size()))
162,096✔
1298
          return false;
3,718✔
1299
        if (t1_i == track1.size() && t2_i == track2.size())
160,061!
1300
          break;
1301
        // Check if surface different
1302
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
68,607✔
1303
          return false;
1304

1305
        // Pretty sure this should not be used:
1306
        // if (t2_i != track2.size() - 1 &&
1307
        //     t1_i != track1.size() - 1 &&
1308
        //     track1[t1_i+1].id != track2[t2_i+1].id) return false;
1309
        if (t2_i != 0 && t1_i != 0 &&
67,122✔
1310
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
53,944✔
1311
          return false;
1312

1313
        // Check if neighboring cells are different
1314
        // if (track1[t1_i ? t1_i - 1 : 0].id != track2[t2_i ? t2_i - 1 : 0].id)
1315
        // return false; if (track1[t1_i < track1.size() - 1 ? t1_i + 1 : t1_i
1316
        // ].id !=
1317
        //    track2[t2_i < track2.size() - 1 ? t2_i + 1 : t2_i].id) return
1318
        //    false;
1319
        t1_i++, t2_i++;
66,341✔
1320
      }
1321
    }
1322
    return true;
1323
  }
1324
}
1325

1326
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
3,521,056✔
1327
  int horiz, int vert) const
1328
{
1329
  // Compute field of view in radians
1330
  constexpr double DEGREE_TO_RADIAN = PI / 180.0;
3,521,056✔
1331
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
3,521,056✔
1332
  double p0 = static_cast<double>(pixels()[0]);
3,521,056✔
1333
  double p1 = static_cast<double>(pixels()[1]);
3,521,056✔
1334
  double vert_fov_radians = horiz_fov_radians * p1 / p0;
3,521,056✔
1335

1336
  // focal_plane_dist can be changed to alter the perspective distortion
1337
  // effect. This is in units of cm. This seems to look good most of the
1338
  // time. TODO let this variable be set through XML.
1339
  constexpr double focal_plane_dist = 10.0;
3,521,056✔
1340
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
3,521,056✔
1341
  const double dy = p1 / p0 * dx;
3,521,056✔
1342

1343
  std::pair<Position, Direction> result;
3,521,056✔
1344

1345
  // Generate the starting position/direction of the ray
1346
  if (orthographic_width_ == C_NONE) { // perspective projection
3,521,056✔
1347
    Direction camera_local_vec;
3,081,056✔
1348
    camera_local_vec.x = focal_plane_dist;
3,081,056✔
1349
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
3,081,056✔
1350
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
3,081,056✔
1351
    camera_local_vec /= camera_local_vec.norm();
3,081,056✔
1352

1353
    result.first = camera_position_;
3,081,056✔
1354
    result.second = camera_local_vec.rotate(camera_to_model_);
3,081,056✔
1355
  } else { // orthographic projection
1356

1357
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
440,000✔
1358
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
440,000✔
1359

1360
    result.first = camera_position_ +
440,000✔
1361
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
440,000✔
1362
                   camera_z_axis() * y_pix_coord * orthographic_width_;
440,000✔
1363
    result.second = camera_x_axis();
440,000✔
1364
  }
1365

1366
  return result;
3,521,056✔
1367
}
1368

1369
ImageData WireframeRayTracePlot::create_image() const
55✔
1370
{
1371
  size_t width = pixels()[0];
55✔
1372
  size_t height = pixels()[1];
55✔
1373
  ImageData data({width, height}, not_found_);
55✔
1374

1375
  // This array marks where the initial wireframe was drawn. We convolve it with
1376
  // a filter that gets adjusted with the wireframe thickness in order to
1377
  // thicken the lines.
1378
  tensor::Tensor<int> wireframe_initial(
55✔
1379
    {static_cast<size_t>(width), static_cast<size_t>(height)}, 0);
55✔
1380

1381
  /* Holds all of the track segments for the current rendered line of pixels.
1382
   * old_segments holds a copy of this_line_segments from the previous line.
1383
   * By holding both we can check if the cell/material intersection stack
1384
   * differs from the left or upper neighbor. This allows a robustly drawn
1385
   * wireframe. If only checking the left pixel (which requires substantially
1386
   * less memory), the wireframe tends to be spotty and be disconnected for
1387
   * surface edges oriented horizontally in the rendering.
1388
   *
1389
   * Note that a vector of vectors is required rather than a 2-tensor,
1390
   * since the stack size varies within each column.
1391
   */
1392
  const int n_threads = num_threads();
55✔
1393
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
55✔
1394
    n_threads);
55✔
1395
  for (int t = 0; t < n_threads; ++t) {
140✔
1396
    this_line_segments[t].resize(pixels()[0]);
85✔
1397
  }
1398

1399
  // The last thread writes to this, and the first thread reads from it.
1400
  std::vector<std::vector<TrackSegment>> old_segments(pixels()[0]);
55✔
1401

1402
#pragma omp parallel
30✔
1403
  {
25✔
1404
    const int n_threads = num_threads();
25✔
1405
    const int tid = thread_num();
25✔
1406

1407
    int vert = tid;
25✔
1408
    for (int iter = 0; iter <= pixels()[1] / n_threads; iter++) {
5,050✔
1409

1410
      // Save bottom line of current work chunk to compare against later. This
1411
      // used to be inside the below if block, but it causes a spurious line to
1412
      // be drawn at the bottom of the image. Not sure why, but moving it here
1413
      // fixes things.
1414
      if (tid == n_threads - 1)
5,025✔
1415
        old_segments = this_line_segments[n_threads - 1];
5,025✔
1416

1417
      if (vert < pixels()[1]) {
5,025✔
1418

1419
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
1,005,000✔
1420

1421
          // RayTracePlot implements camera ray generation
1422
          std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
1,000,000✔
1423

1424
          this_line_segments[tid][horiz].clear();
1,000,000✔
1425
          ProjectionRay ray(
1,000,000✔
1426
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
1,000,000✔
1427

1428
          ray.trace();
1,000,000✔
1429

1430
          // Now color the pixel based on what we have intersected...
1431
          // Loops backwards over intersections.
1432
          Position current_color(
1,000,000✔
1433
            not_found_.red, not_found_.green, not_found_.blue);
1,000,000✔
1434
          const auto& segments = this_line_segments[tid][horiz];
1,000,000✔
1435

1436
          // There must be at least two cell intersections to color, front and
1437
          // back of the cell. Maybe an infinitely thick cell could be present
1438
          // with no back, but why would you want to color that? It's easier to
1439
          // just skip that edge case and not even color it.
1440
          if (segments.size() <= 1)
1,000,000✔
1441
            continue;
616,655✔
1442

1443
          for (int i = segments.size() - 2; i >= 0; --i) {
1,072,335✔
1444
            int colormap_idx = segments[i].id;
688,990✔
1445
            RGBColor seg_color = colors_[colormap_idx];
688,990✔
1446
            Position seg_color_vec(
688,990✔
1447
              seg_color.red, seg_color.green, seg_color.blue);
688,990✔
1448
            double mixing =
688,990✔
1449
              std::exp(-xs_[colormap_idx] *
1,377,980✔
1450
                       (segments[i + 1].length - segments[i].length));
688,990✔
1451
            current_color =
688,990✔
1452
              current_color * mixing + (1.0 - mixing) * seg_color_vec;
688,990✔
1453
          }
1454

1455
          // save result converting from double-precision color coordinates to
1456
          // byte-sized
1457
          RGBColor result;
383,345✔
1458
          result.red = static_cast<uint8_t>(current_color.x);
383,345✔
1459
          result.green = static_cast<uint8_t>(current_color.y);
383,345✔
1460
          result.blue = static_cast<uint8_t>(current_color.z);
383,345✔
1461
          data(horiz, vert) = result;
383,345✔
1462

1463
          // Check to draw wireframe in horizontal direction. No inter-thread
1464
          // comm.
1465
          if (horiz > 0) {
383,345✔
1466
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
382,345✔
1467
                  this_line_segments[tid][horiz - 1])) {
382,345✔
1468
              wireframe_initial(horiz, vert) = 1;
15,710✔
1469
            }
1470
          }
1471
        }
1,000,000✔
1472
      } // end "if" vert in correct range
1473

1474
      // We require a barrier before comparing vertical neighbors' intersection
1475
      // stacks. i.e. all threads must be done with their line.
1476
#pragma omp barrier
1477

1478
      // Now that the horizontal line has finished rendering, we can fill in
1479
      // wireframe entries that require comparison among all the threads. Hence
1480
      // the omp barrier being used. It has to be OUTSIDE any if blocks!
1481
      if (vert < pixels()[1]) {
5,025✔
1482
        // Loop over horizontal pixels, checking intersection stack of upper
1483
        // neighbor
1484

1485
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
1486
        if (tid == 0)
1487
          top_cmp = &old_segments;
1488
        else
1489
          top_cmp = &this_line_segments[tid - 1];
1490

1491
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
1,005,000✔
1492
          if (!trackstack_equivalent(
1,000,000✔
1493
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
1,000,000✔
1494
            wireframe_initial(horiz, vert) = 1;
20,595✔
1495
          }
1496
        }
1497
      }
1498

1499
      // We need another barrier to ensure threads don't proceed to modify their
1500
      // intersection stacks on that horizontal line while others are
1501
      // potentially still working on the above.
1502
#pragma omp barrier
1503
      vert += n_threads;
5,025✔
1504
    }
1505
  } // end omp parallel
1506

1507
  // Now thicken the wireframe lines and apply them to our image
1508
  for (int vert = 0; vert < pixels()[1]; ++vert) {
11,055✔
1509
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
2,211,000✔
1510
      if (wireframe_initial(horiz, vert)) {
2,200,000✔
1511
        if (wireframe_thickness_ == 1)
70,983✔
1512
          data(horiz, vert) = wireframe_color_;
30,195✔
1513
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
195,723✔
1514
             ++i)
1515
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
546,876✔
1516
               ++j)
1517
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
422,136!
1518

1519
              // Check if wireframe pixel is out of bounds
1520
              int w_i = std::max(std::min(horiz + i, pixels()[0] - 1), 0);
422,136!
1521
              int w_j = std::max(std::min(vert + j, pixels()[1] - 1), 0);
422,268✔
1522
              data(w_i, w_j) = wireframe_color_;
422,136✔
1523
            }
1524
      }
1525
    }
1526
  }
1527

1528
  return data;
110✔
1529
}
110✔
1530

1531
void WireframeRayTracePlot::create_output() const
55✔
1532
{
1533
  ImageData data = create_image();
55✔
1534
  write_image(data);
55✔
1535
}
55✔
1536

1537
void RayTracePlot::print_info() const
88✔
1538
{
1539
  fmt::print("Camera position: {} {} {}\n", camera_position_.x,
176✔
1540
    camera_position_.y, camera_position_.z);
88✔
1541
  fmt::print("Look at: {} {} {}\n", look_at_.x, look_at_.y, look_at_.z);
88✔
1542
  fmt::print(
176✔
1543
    "Horizontal field of view: {} degrees\n", horizontal_field_of_view_);
88✔
1544
  fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
88✔
1545
}
88✔
1546

1547
void WireframeRayTracePlot::print_info() const
55✔
1548
{
1549
  fmt::print("Plot Type: Wireframe ray-traced\n");
55✔
1550
  RayTracePlot::print_info();
55✔
1551
}
55✔
1552

1553
void WireframeRayTracePlot::set_opacities(pugi::xml_node node)
55✔
1554
{
1555
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
55✔
1556

1557
  for (auto cn : node.children("color")) {
121✔
1558
    // Make sure 3 values are specified for RGB
1559
    double user_xs = std::stod(get_node_value(cn, "xs"));
132✔
1560
    int col_id = std::stoi(get_node_value(cn, "id"));
132✔
1561

1562
    // Add RGB
1563
    if (PlotColorBy::cells == color_by_) {
66!
1564
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
1565
        col_id = model::cell_map[col_id];
66✔
1566
        xs_[col_id] = user_xs;
66✔
1567
      } else {
UNCOV
1568
        warning(fmt::format(
×
1569
          "Could not find cell {} specified in plot {}", col_id, id()));
×
1570
      }
UNCOV
1571
    } else if (PlotColorBy::mats == color_by_) {
×
1572
      if (model::material_map.find(col_id) != model::material_map.end()) {
×
1573
        col_id = model::material_map[col_id];
×
1574
        xs_[col_id] = user_xs;
×
1575
      } else {
UNCOV
1576
        warning(fmt::format(
×
1577
          "Could not find material {} specified in plot {}", col_id, id()));
×
1578
      }
1579
    }
1580
  }
1581
}
55✔
1582

1583
void RayTracePlot::set_orthographic_width(pugi::xml_node node)
88✔
1584
{
1585
  if (check_for_node(node, "orthographic_width")) {
88✔
1586
    double orthographic_width =
11✔
1587
      std::stod(get_node_value(node, "orthographic_width", true));
11✔
1588
    if (orthographic_width < 0.0)
11!
UNCOV
1589
      fatal_error("Requires positive orthographic_width");
×
1590
    orthographic_width_ = orthographic_width;
11✔
1591
  }
1592
}
88✔
1593

1594
void WireframeRayTracePlot::set_wireframe_thickness(pugi::xml_node node)
55✔
1595
{
1596
  if (check_for_node(node, "wireframe_thickness")) {
55✔
1597
    int wireframe_thickness =
22✔
1598
      std::stoi(get_node_value(node, "wireframe_thickness", true));
22✔
1599
    if (wireframe_thickness < 0)
22!
UNCOV
1600
      fatal_error("Requires non-negative wireframe thickness");
×
1601
    wireframe_thickness_ = wireframe_thickness;
22✔
1602
  }
1603
}
55✔
1604

1605
void WireframeRayTracePlot::set_wireframe_ids(pugi::xml_node node)
55✔
1606
{
1607
  if (check_for_node(node, "wireframe_ids")) {
55✔
1608
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
11✔
1609
    // It is read in as actual ID values, but we have to convert to indices in
1610
    // mat/cell array
1611
    for (auto& x : wireframe_ids_)
22✔
1612
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
22!
UNCOV
1613
                                         : model::cell_map[x];
×
1614
  }
1615
  // We make sure the list is sorted in order to later use
1616
  // std::binary_search.
1617
  std::sort(wireframe_ids_.begin(), wireframe_ids_.end());
55✔
1618
}
55✔
1619

1620
void RayTracePlot::set_pixels(pugi::xml_node node)
88✔
1621
{
1622
  vector<int> pxls = get_node_array<int>(node, "pixels");
88✔
1623
  if (pxls.size() != 2)
88!
UNCOV
1624
    fatal_error(
×
1625
      fmt::format("<pixels> must be length 2 in projection plot {}", id()));
×
1626
  pixels()[0] = pxls[0];
88✔
1627
  pixels()[1] = pxls[1];
88✔
1628
}
88✔
1629

1630
void RayTracePlot::set_camera_position(pugi::xml_node node)
88✔
1631
{
1632
  vector<double> camera_pos = get_node_array<double>(node, "camera_position");
88✔
1633
  if (camera_pos.size() != 3) {
88!
UNCOV
1634
    fatal_error(fmt::format(
×
1635
      "camera_position element must have three floating point values"));
1636
  }
1637
  camera_position_.x = camera_pos[0];
88✔
1638
  camera_position_.y = camera_pos[1];
88✔
1639
  camera_position_.z = camera_pos[2];
88✔
1640
}
88✔
1641

1642
void RayTracePlot::set_look_at(pugi::xml_node node)
88✔
1643
{
1644
  vector<double> look_at = get_node_array<double>(node, "look_at");
88✔
1645
  if (look_at.size() != 3) {
88!
UNCOV
1646
    fatal_error("look_at element must have three floating point values");
×
1647
  }
1648
  look_at_.x = look_at[0];
88✔
1649
  look_at_.y = look_at[1];
88✔
1650
  look_at_.z = look_at[2];
88✔
1651
}
88✔
1652

1653
void RayTracePlot::set_field_of_view(pugi::xml_node node)
88✔
1654
{
1655
  // Defaults to 70 degree horizontal field of view (see .h file)
1656
  if (check_for_node(node, "horizontal_field_of_view")) {
88!
UNCOV
1657
    double fov =
×
1658
      std::stod(get_node_value(node, "horizontal_field_of_view", true));
×
1659
    if (fov < 180.0 && fov > 0.0) {
×
1660
      horizontal_field_of_view_ = fov;
×
1661
    } else {
UNCOV
1662
      fatal_error(fmt::format("Horizontal field of view for plot {} "
×
1663
                              "out-of-range. Must be in (0, 180) degrees.",
UNCOV
1664
        id()));
×
1665
    }
1666
  }
1667
}
88✔
1668

1669
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
33✔
1670
{
1671
  set_opaque_ids(node);
33✔
1672
  set_diffuse_fraction(node);
33✔
1673
  set_light_position(node);
33✔
1674
  update_view();
33✔
1675
}
33✔
1676

1677
void SolidRayTracePlot::print_info() const
33✔
1678
{
1679
  fmt::print("Plot Type: Solid ray-traced\n");
33✔
1680
  RayTracePlot::print_info();
33✔
1681
}
33✔
1682

1683
ImageData SolidRayTracePlot::create_image() const
55✔
1684
{
1685
  size_t width = pixels()[0];
55✔
1686
  size_t height = pixels()[1];
55✔
1687
  ImageData data({width, height}, not_found_);
55✔
1688

1689
#pragma omp parallel for schedule(dynamic) collapse(2)
30✔
1690
  for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
3,105✔
1691
    for (int vert = 0; vert < pixels()[1]; ++vert) {
603,560✔
1692
      // RayTracePlot implements camera ray generation
1693
      std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
600,480✔
1694
      PhongRay ray(ru.first, ru.second, *this);
600,480✔
1695
      ray.trace();
600,480✔
1696
      data(horiz, vert) = ray.result_color();
600,480✔
1697
    }
600,480✔
1698
  }
1699

1700
  return data;
55✔
1701
}
1702

1703
void SolidRayTracePlot::create_output() const
33✔
1704
{
1705
  ImageData data = create_image();
33✔
1706
  write_image(data);
33✔
1707
}
33✔
1708

1709
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
33✔
1710
{
1711
  if (check_for_node(node, "opaque_ids")) {
33!
1712
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
33✔
1713

1714
    // It is read in as actual ID values, but we have to convert to indices in
1715
    // mat/cell array
1716
    for (auto& x : opaque_ids_tmp)
99✔
1717
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
132!
UNCOV
1718
                                         : model::cell_map[x];
×
1719

1720
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
33✔
1721
  }
33✔
1722
}
33✔
1723

1724
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
33✔
1725
{
1726
  if (check_for_node(node, "light_position")) {
33✔
1727
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
11✔
1728

1729
    if (light_pos_tmp.size() != 3)
11!
UNCOV
1730
      fatal_error("Light position must be given as 3D coordinates");
×
1731

1732
    light_location_.x = light_pos_tmp[0];
11✔
1733
    light_location_.y = light_pos_tmp[1];
11✔
1734
    light_location_.z = light_pos_tmp[2];
11✔
1735
  } else {
11✔
1736
    light_location_ = camera_position();
22✔
1737
  }
1738
}
33✔
1739

1740
void SolidRayTracePlot::set_diffuse_fraction(pugi::xml_node node)
33✔
1741
{
1742
  if (check_for_node(node, "diffuse_fraction")) {
33✔
1743
    diffuse_fraction_ = std::stod(get_node_value(node, "diffuse_fraction"));
11✔
1744
    if (diffuse_fraction_ < 0.0 || diffuse_fraction_ > 1.0) {
11!
UNCOV
1745
      fatal_error("Must have 0 <= diffuse fraction <= 1");
×
1746
    }
1747
  }
1748
}
33✔
1749

1750
void ProjectionRay::on_intersection()
2,359,148✔
1751
{
1752
  // This records a tuple with the following info
1753
  //
1754
  // 1) ID (material or cell depending on color_by_)
1755
  // 2) Distance traveled by the ray through that ID
1756
  // 3) Index of the intersected surface (starting from 1)
1757

1758
  line_segments_.emplace_back(
2,359,148✔
1759
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
2,359,148✔
1760
      ? material()
545,919✔
1761
      : lowest_coord().cell(),
1,813,229✔
1762
    traversal_distance_, boundary().surface_index());
2,359,148✔
1763
}
2,359,148✔
1764

1765
void PhongRay::on_intersection()
905,971✔
1766
{
1767
  // Check if we hit an opaque material or cell
1768
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
905,971✔
1769
                 ? material()
905,971!
UNCOV
1770
                 : lowest_coord().cell();
×
1771

1772
  // If we are reflected and have advanced beyond the camera,
1773
  // the ray is done. This is checked here because we should
1774
  // kill the ray even if the material is not opaque.
1775
  if (reflected_ && (r() - plot_.camera_position()).dot(u()) >= 0.0) {
905,971!
UNCOV
1776
    stop();
×
1777
    return;
164,340✔
1778
  }
1779

1780
  // Anything that's not opaque has zero impact on the plot.
1781
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
905,971✔
1782
    return;
1783

1784
  if (!reflected_) {
741,631✔
1785
    // reflect the particle and set the color to be colored by
1786
    // the normal or the diffuse lighting contribution
1787
    reflected_ = true;
706,068✔
1788
    result_color_ = plot_.colors_[hit_id];
706,068✔
1789
    // The ray has been advanced slightly past the boundary. Use an
1790
    // approximation to the actual hit point for stable normal/lighting.
1791
    Position r_hit = r() - TINY_BIT * u();
706,068✔
1792
    Direction to_light = plot_.light_location_ - r_hit;
706,068✔
1793
    to_light /= to_light.norm();
706,068✔
1794

1795
    // TODO
1796
    // Not sure what can cause a surface token to be invalid here, although it
1797
    // sometimes happens for a few pixels. It's very very rare, so proceed by
1798
    // coloring the pixel with the overlap color. It seems to happen only for a
1799
    // few pixels on the outer boundary of a hex lattice.
1800
    //
1801
    // We cannot detect it in the outer loop, and it only matters here, so
1802
    // that's why the error handling is a little different than for a lost
1803
    // ray.
1804
    if (surface() == 0) {
706,068!
UNCOV
1805
      result_color_ = plot_.overlap_color_;
×
1806
      stop();
×
1807
      return;
×
1808
    }
1809

1810
    // Get surface pointer
1811
    const auto& surf = model::surfaces.at(surface_index());
706,068✔
1812

1813
    // The crossed surface may be on a higher coordinate level than the
1814
    // innermost local coordinates, so we check the surface's coordinate level
1815
    // to find the appropriate coordinate level to use for the normal
1816
    // calculation
1817
    int surf_level = boundary().coord_level() - 1;
706,068!
1818
    // ensure surface level is within bounds of current coordinate stack
1819
    surf_level = std::max(0, std::min(surf_level, n_coord() - 1));
706,068!
1820

1821
    Position r_hit_level =
706,068✔
1822
      coord(surf_level).r() - TINY_BIT * coord(surf_level).u();
706,068✔
1823
    Direction normal = surf->normal(r_hit_level);
706,068✔
1824
    normal /= normal.norm();
706,068✔
1825

1826
    // Need to apply rotations to find the normal vector in
1827
    // the base level universe's coordinate system.
1828
    for (int lev = surf_level - 1; lev >= 0; --lev) {
706,068!
UNCOV
1829
      if (coord(lev + 1).rotated()) {
×
1830
        const Cell& c {*model::cells[coord(lev).cell()]};
×
1831
        normal = normal.inverse_rotate(c.rotation_);
×
1832
      }
1833
    }
1834

1835
    // use the normal opposed to the ray direction
1836
    if (normal.dot(u()) > 0.0) {
706,068✔
1837
      normal *= -1.0;
63,789✔
1838
    }
1839

1840
    // Facing away from the light means no lighting
1841
    double dotprod = normal.dot(to_light);
706,068✔
1842
    dotprod = std::max(0.0, dotprod);
706,068✔
1843

1844
    double modulation =
706,068✔
1845
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
706,068✔
1846
    result_color_ *= modulation;
706,068✔
1847

1848
    // Now point the particle to the camera. We now begin
1849
    // checking to see if it's occluded by another surface
1850
    u() = to_light;
706,068✔
1851

1852
    orig_hit_id_ = hit_id;
706,068✔
1853

1854
    // OpenMC native CSG and DAGMC surfaces have some slight differences
1855
    // in how they interpret particles that are sitting on a surface.
1856
    // I don't know exactly why, but this makes everything work beautifully.
1857
    if (surf->geom_type() == GeometryType::DAG) {
706,068!
UNCOV
1858
      surface() = 0;
×
1859
    } else {
1860
      surface() = -surface(); // go to other side
706,068✔
1861
    }
1862

1863
    // Must fully restart coordinate search. Why? Not sure.
1864
    clear();
706,068✔
1865

1866
    // Note this could likely be faster if we cached the previous
1867
    // cell we were in before the reflection. This is the easiest
1868
    // way to fully initialize all the sub-universe coordinates and
1869
    // directions though.
1870
    bool found = exhaustive_find_cell(*this);
706,068✔
1871
    if (!found) {
706,068!
UNCOV
1872
      fatal_error("Lost particle after reflection.");
×
1873
    }
1874

1875
    // Must recalculate distance to boundary due to the
1876
    // direction change
1877
    compute_distance();
706,068✔
1878

1879
  } else {
1880
    // If it's not facing the light, we color with the diffuse contribution, so
1881
    // next we check if we're going to occlude the last reflected surface. if
1882
    // so, color by the diffuse contribution instead
1883

1884
    if (orig_hit_id_ == -1)
35,563!
UNCOV
1885
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1886

1887
    result_color_ = plot_.colors_[orig_hit_id_];
35,563✔
1888
    result_color_ *= plot_.diffuse_fraction_;
35,563✔
1889
    stop();
741,631✔
1890
  }
1891
}
1892

UNCOV
1893
extern "C" int openmc_id_map(const void* plot, int32_t* data_out)
×
1894
{
UNCOV
1895
  static bool warned {false};
×
1896
  if (!warned) {
×
1897
    warning("openmc_id_map is deprecated and will be removed in a future "
×
1898
            "release. Use openmc_slice_data.");
UNCOV
1899
    warned = true;
×
1900
  }
1901

UNCOV
1902
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1903
  if (!plt) {
×
1904
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1905
    return OPENMC_E_INVALID_ARGUMENT;
×
1906
  }
1907

UNCOV
1908
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1909
    model::overlap_check_count.resize(model::cells.size());
×
1910
  }
1911

UNCOV
1912
  auto ids = plt->get_map<IdData>();
×
1913

1914
  // write id data to array
UNCOV
1915
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
×
1916

UNCOV
1917
  return 0;
×
1918
}
×
1919

UNCOV
1920
extern "C" int openmc_property_map(const void* plot, double* data_out)
×
1921
{
UNCOV
1922
  static bool warned {false};
×
1923
  if (!warned) {
×
1924
    warning("openmc_property_map is deprecated and will be removed in a future "
×
1925
            "release. Use openmc_slice_data.");
UNCOV
1926
    warned = true;
×
1927
  }
1928

UNCOV
1929
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1930
  if (!plt) {
×
1931
    set_errmsg("Invalid slice pointer passed to openmc_property_map");
×
1932
    return OPENMC_E_INVALID_ARGUMENT;
×
1933
  }
1934

UNCOV
1935
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1936
    model::overlap_check_count.resize(model::cells.size());
×
1937
  }
1938

UNCOV
1939
  auto props = plt->get_map<PropertyData>();
×
1940

1941
  // write id data to array
UNCOV
1942
  std::copy(props.data_.begin(), props.data_.end(), data_out);
×
1943

UNCOV
1944
  return 0;
×
1945
}
×
1946

1947
extern "C" int openmc_slice_data(const double origin[3], const double u_span[3],
432✔
1948
  const double v_span[3], const size_t pixels[2], bool color_overlaps,
1949
  int level, int32_t filter_index, int32_t* geom_data, double* property_data)
1950
{
1951
  // Validate span vectors
1952
  Direction u_span_pos {u_span[0], u_span[1], u_span[2]};
432✔
1953
  Direction v_span_pos {v_span[0], v_span[1], v_span[2]};
432✔
1954
  double u_norm = u_span_pos.norm();
432✔
1955
  double v_norm = v_span_pos.norm();
432✔
1956
  if (u_norm == 0.0 || v_norm == 0.0) {
432!
UNCOV
1957
    set_errmsg("Slice span vectors must be non-zero.");
×
1958
    return OPENMC_E_INVALID_ARGUMENT;
×
1959
  }
1960

1961
  constexpr double ORTHO_REL_TOL = 1e-10;
432✔
1962
  double dot = u_span_pos.dot(v_span_pos);
432!
1963
  if (std::abs(dot) > ORTHO_REL_TOL * u_norm * v_norm) {
432!
UNCOV
1964
    set_errmsg("Slice span vectors must be orthogonal.");
×
1965
    return OPENMC_E_INVALID_ARGUMENT;
×
1966
  }
1967

1968
  // Validate filter index if provided
1969
  if (filter_index >= 0) {
432✔
1970
    if (int err = verify_filter(filter_index))
22!
1971
      return err;
1972
  }
1973

1974
  // Initialize overlap check vector if needed
1975
  if (color_overlaps && model::overlap_check_count.size() == 0) {
432!
1976
    model::overlap_check_count.resize(model::cells.size());
55✔
1977
  }
1978

1979
  try {
432✔
1980
    // Create a temporary SlicePlotBase object to reuse get_map logic
1981
    SlicePlotBase plot_params;
432✔
1982
    plot_params.origin_ = Position {origin[0], origin[1], origin[2]};
432✔
1983
    plot_params.u_span_ = u_span_pos;
432✔
1984
    plot_params.v_span_ = v_span_pos;
432✔
1985
    plot_params.pixels_[0] = pixels[0];
432✔
1986
    plot_params.pixels_[1] = pixels[1];
432✔
1987
    plot_params.show_overlaps_ = color_overlaps;
432✔
1988
    plot_params.slice_level_ = level;
432✔
1989

1990
    // Clear overlap data structures on new slice call
1991
    model::overlap_keys.clear();
432✔
1992
    model::overlap_key_index.clear();
432✔
1993

1994
    // Use get_map<RasterData> to generate data
1995
    auto data = plot_params.get_map<RasterData>(filter_index);
432✔
1996
    std::copy(data.id_data_.begin(), data.id_data_.end(), geom_data);
432✔
1997

1998
    // Copy property data if requested
1999
    if (property_data != nullptr) {
432✔
2000
      std::copy(
77✔
2001
        data.property_data_.begin(), data.property_data_.end(), property_data);
2002
    }
2003
  } catch (const std::exception& e) {
432!
UNCOV
2004
    set_errmsg(e.what());
×
2005
    return OPENMC_E_UNASSIGNED;
×
2006
  }
×
2007

2008
  return 0;
432✔
2009
}
2010

2011
// Gets the number of overlaps that we need data for
2012
extern "C" int openmc_slice_data_overlap_count(size_t* count)
22✔
2013
{
2014
  if (!count) {
22!
UNCOV
2015
    set_errmsg("Null pointer passed for overlap count.");
×
2016
    return OPENMC_E_INVALID_ARGUMENT;
×
2017
  }
2018
  *count = model::overlap_keys.size();
22✔
2019

2020
  return 0;
22✔
2021
}
2022

2023
// Plotter pre-allocates array size based on what is returned with
2024
// overlap_count; populates an array of size 3*count
2025
extern "C" int openmc_slice_data_overlap_info(
11✔
2026
  size_t count, int32_t* overlap_info)
2027
{
2028
  for (size_t i = 0; i < count; ++i) {
33✔
2029
    overlap_info[i * 3] = model::overlap_keys[i].universe_id;
22✔
2030
    overlap_info[i * 3 + 1] = model::overlap_keys[i].cell1_id;
22✔
2031
    overlap_info[i * 3 + 2] = model::overlap_keys[i].cell2_id;
22✔
2032
  }
2033

2034
  return 0;
11✔
2035
}
2036

2037
extern "C" int openmc_get_plot_index(int32_t id, int32_t* index)
22✔
2038
{
2039
  auto it = model::plot_map.find(id);
22!
2040
  if (it == model::plot_map.end()) {
22!
UNCOV
2041
    set_errmsg("No plot exists with ID=" + std::to_string(id) + ".");
×
2042
    return OPENMC_E_INVALID_ID;
×
2043
  }
2044

2045
  *index = it->second;
22✔
2046
  return 0;
22✔
2047
}
2048

2049
extern "C" int openmc_plot_get_id(int32_t index, int32_t* id)
55✔
2050
{
2051
  if (index < 0 || index >= model::plots.size()) {
55!
UNCOV
2052
    set_errmsg("Index in plots array is out of bounds.");
×
2053
    return OPENMC_E_OUT_OF_BOUNDS;
×
2054
  }
2055

2056
  *id = model::plots[index]->id();
55✔
2057
  return 0;
55✔
2058
}
2059

UNCOV
2060
extern "C" int openmc_plot_set_id(int32_t index, int32_t id)
×
2061
{
UNCOV
2062
  if (index < 0 || index >= model::plots.size()) {
×
2063
    set_errmsg("Index in plots array is out of bounds.");
×
2064
    return OPENMC_E_OUT_OF_BOUNDS;
×
2065
  }
2066

UNCOV
2067
  if (id < 0 && id != C_NONE) {
×
2068
    set_errmsg("Invalid plot ID.");
×
2069
    return OPENMC_E_INVALID_ARGUMENT;
×
2070
  }
2071

UNCOV
2072
  auto* plot = model::plots[index].get();
×
2073
  int32_t old_id = plot->id();
×
2074
  if (id == old_id)
×
2075
    return 0;
2076

UNCOV
2077
  model::plot_map.erase(old_id);
×
2078
  try {
×
2079
    plot->set_id(id);
×
2080
  } catch (const std::runtime_error& e) {
×
2081
    model::plot_map[old_id] = index;
×
2082
    set_errmsg(e.what());
×
2083
    return OPENMC_E_INVALID_ID;
×
2084
  }
×
2085
  model::plot_map[plot->id()] = index;
×
2086
  return 0;
×
2087
}
2088

2089
extern "C" size_t openmc_plots_size()
22✔
2090
{
2091
  return model::plots.size();
22✔
2092
}
2093

2094
int map_phong_domain_id(
55✔
2095
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2096
{
2097
  if (!plot || !index_out) {
55!
UNCOV
2098
    set_errmsg("Invalid plot pointer passed to map_phong_domain_id");
×
2099
    return OPENMC_E_INVALID_ARGUMENT;
×
2100
  }
2101

2102
  if (plot->color_by_ == PlottableInterface::PlotColorBy::mats) {
55!
2103
    auto it = model::material_map.find(id);
55!
2104
    if (it == model::material_map.end()) {
55!
UNCOV
2105
      set_errmsg("Invalid material ID for SolidRayTracePlot");
×
2106
      return OPENMC_E_INVALID_ID;
×
2107
    }
2108
    *index_out = it->second;
55✔
2109
    return 0;
55✔
2110
  }
2111

UNCOV
2112
  if (plot->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2113
    auto it = model::cell_map.find(id);
×
2114
    if (it == model::cell_map.end()) {
×
2115
      set_errmsg("Invalid cell ID for SolidRayTracePlot");
×
2116
      return OPENMC_E_INVALID_ID;
×
2117
    }
UNCOV
2118
    *index_out = it->second;
×
2119
    return 0;
×
2120
  }
2121

UNCOV
2122
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2123
  return OPENMC_E_INVALID_TYPE;
×
2124
}
2125

2126
int get_solidraytrace_plot_by_index(int32_t index, SolidRayTracePlot** plot)
308✔
2127
{
2128
  if (!plot) {
308!
UNCOV
2129
    set_errmsg("Null output pointer passed to get_solidraytrace_plot_by_index");
×
2130
    return OPENMC_E_INVALID_ARGUMENT;
×
2131
  }
2132

2133
  if (index < 0 || index >= model::plots.size()) {
308!
UNCOV
2134
    set_errmsg("Index in plots array is out of bounds.");
×
2135
    return OPENMC_E_OUT_OF_BOUNDS;
×
2136
  }
2137

2138
  auto* plottable = model::plots[index].get();
308!
2139
  auto* solid_plot = dynamic_cast<SolidRayTracePlot*>(plottable);
308!
2140
  if (!solid_plot) {
308!
UNCOV
2141
    set_errmsg("Plot at index=" + std::to_string(index) +
×
2142
               " is not a solid raytrace plot.");
UNCOV
2143
    return OPENMC_E_INVALID_TYPE;
×
2144
  }
2145

2146
  *plot = solid_plot;
308✔
2147
  return 0;
308✔
2148
}
2149

2150
extern "C" int openmc_solidraytrace_plot_create(int32_t* index)
11✔
2151
{
2152
  if (!index) {
11!
UNCOV
2153
    set_errmsg(
×
2154
      "Null output pointer passed to openmc_solidraytrace_plot_create");
UNCOV
2155
    return OPENMC_E_INVALID_ARGUMENT;
×
2156
  }
2157

2158
  try {
11✔
2159
    auto new_plot = std::make_unique<SolidRayTracePlot>();
11✔
2160
    new_plot->set_id();
11✔
2161
    int32_t new_plot_id = new_plot->id();
11✔
2162
#ifdef USE_LIBPNG
2163
    new_plot->path_plot() = fmt::format("plot_{}.png", new_plot_id);
11✔
2164
#else
2165
    new_plot->path_plot() = fmt::format("plot_{}.ppm", new_plot_id);
2166
#endif
2167
    int32_t new_plot_index = model::plots.size();
11✔
2168
    model::plots.emplace_back(std::move(new_plot));
11✔
2169
    model::plot_map[new_plot_id] = new_plot_index;
11✔
2170
    *index = new_plot_index;
11✔
2171
  } catch (const std::exception& e) {
11!
UNCOV
2172
    set_errmsg(e.what());
×
2173
    return OPENMC_E_ALLOCATE;
×
2174
  }
×
2175

2176
  return 0;
11✔
2177
}
2178

2179
extern "C" int openmc_solidraytrace_plot_get_pixels(
33✔
2180
  int32_t index, int32_t* width, int32_t* height)
2181
{
2182
  if (!width || !height) {
33!
UNCOV
2183
    set_errmsg(
×
2184
      "Invalid arguments passed to openmc_solidraytrace_plot_get_pixels");
UNCOV
2185
    return OPENMC_E_INVALID_ARGUMENT;
×
2186
  }
2187

2188
  SolidRayTracePlot* plt = nullptr;
33✔
2189
  int err = get_solidraytrace_plot_by_index(index, &plt);
33✔
2190
  if (err)
33!
2191
    return err;
2192

2193
  *width = plt->pixels()[0];
33✔
2194
  *height = plt->pixels()[1];
33✔
2195
  return 0;
33✔
2196
}
2197

2198
extern "C" int openmc_solidraytrace_plot_set_pixels(
11✔
2199
  int32_t index, int32_t width, int32_t height)
2200
{
2201
  if (width <= 0 || height <= 0) {
11!
UNCOV
2202
    set_errmsg(
×
2203
      "Invalid arguments passed to openmc_solidraytrace_plot_set_pixels");
UNCOV
2204
    return OPENMC_E_INVALID_ARGUMENT;
×
2205
  }
2206

2207
  SolidRayTracePlot* plt = nullptr;
11✔
2208
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2209
  if (err)
11!
2210
    return err;
2211

2212
  plt->pixels()[0] = width;
11✔
2213
  plt->pixels()[1] = height;
11✔
2214
  return 0;
11✔
2215
}
2216

2217
extern "C" int openmc_solidraytrace_plot_get_color_by(
11✔
2218
  int32_t index, int32_t* color_by)
2219
{
2220
  if (!color_by) {
11!
UNCOV
2221
    set_errmsg(
×
2222
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color_by");
UNCOV
2223
    return OPENMC_E_INVALID_ARGUMENT;
×
2224
  }
2225

2226
  SolidRayTracePlot* plt = nullptr;
11✔
2227
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2228
  if (err)
11!
2229
    return err;
2230

2231
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
11!
2232
    *color_by = 0;
11✔
UNCOV
2233
  } else if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2234
    *color_by = 1;
×
2235
  } else {
UNCOV
2236
    set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2237
    return OPENMC_E_INVALID_TYPE;
×
2238
  }
2239

2240
  return 0;
2241
}
2242

2243
extern "C" int openmc_solidraytrace_plot_set_color_by(
11✔
2244
  int32_t index, int32_t color_by)
2245
{
2246
  SolidRayTracePlot* plt = nullptr;
11✔
2247
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2248
  if (err)
11!
2249
    return err;
2250

2251
  if (color_by == 0) {
11!
2252
    plt->color_by_ = PlottableInterface::PlotColorBy::mats;
11✔
UNCOV
2253
  } else if (color_by == 1) {
×
2254
    plt->color_by_ = PlottableInterface::PlotColorBy::cells;
×
2255
  } else {
UNCOV
2256
    set_errmsg("Invalid color_by value for SolidRayTracePlot");
×
2257
    return OPENMC_E_INVALID_ARGUMENT;
×
2258
  }
2259

2260
  return 0;
2261
}
2262

2263
extern "C" int openmc_solidraytrace_plot_set_default_colors(int32_t index)
11✔
2264
{
2265
  SolidRayTracePlot* plt = nullptr;
11✔
2266
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2267
  if (err)
11!
2268
    return err;
2269

2270
  plt->set_default_colors();
11✔
2271
  return 0;
2272
}
2273

UNCOV
2274
extern "C" int openmc_solidraytrace_plot_set_all_opaque(int32_t index)
×
2275
{
UNCOV
2276
  SolidRayTracePlot* plt = nullptr;
×
2277
  int err = get_solidraytrace_plot_by_index(index, &plt);
×
2278
  if (err)
×
2279
    return err;
2280

UNCOV
2281
  plt->opaque_ids().clear();
×
2282
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
×
2283
    for (int32_t i = 0; i < model::materials.size(); ++i) {
×
2284
      plt->opaque_ids().insert(i);
×
2285
    }
UNCOV
2286
    return 0;
×
2287
  }
2288

UNCOV
2289
  if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2290
    for (int32_t i = 0; i < model::cells.size(); ++i) {
×
2291
      plt->opaque_ids().insert(i);
×
2292
    }
UNCOV
2293
    return 0;
×
2294
  }
2295

UNCOV
2296
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2297
  return OPENMC_E_INVALID_TYPE;
×
2298
}
2299

2300
extern "C" int openmc_solidraytrace_plot_set_opaque(
22✔
2301
  int32_t index, int32_t id, bool visible)
2302
{
2303
  SolidRayTracePlot* plt = nullptr;
22✔
2304
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2305
  if (err)
22!
2306
    return err;
2307

2308
  int32_t domain_index = -1;
22✔
2309
  err = map_phong_domain_id(plt, id, &domain_index);
22✔
2310
  if (err)
22!
2311
    return err;
2312

2313
  if (visible) {
22✔
2314
    plt->opaque_ids().insert(domain_index);
11✔
2315
  } else {
2316
    plt->opaque_ids().erase(domain_index);
11✔
2317
  }
2318

2319
  return 0;
2320
}
2321

2322
extern "C" int openmc_solidraytrace_plot_set_color(
22✔
2323
  int32_t index, int32_t id, uint8_t r, uint8_t g, uint8_t b)
2324
{
2325
  SolidRayTracePlot* plt = nullptr;
22✔
2326
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2327
  if (err)
22!
2328
    return err;
2329

2330
  int32_t domain_index = -1;
22✔
2331
  err = map_phong_domain_id(plt, id, &domain_index);
22✔
2332
  if (err)
22!
2333
    return err;
2334

2335
  if (domain_index < 0 ||
22!
2336
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
22!
UNCOV
2337
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2338
    return OPENMC_E_OUT_OF_BOUNDS;
×
2339
  }
2340

2341
  plt->colors_[domain_index] = RGBColor(r, g, b);
22✔
2342
  return 0;
22✔
2343
}
2344

2345
extern "C" int openmc_solidraytrace_plot_get_camera_position(
11✔
2346
  int32_t index, double* x, double* y, double* z)
2347
{
2348
  if (!x || !y || !z) {
11!
UNCOV
2349
    set_errmsg("Invalid arguments passed to "
×
2350
               "openmc_solidraytrace_plot_get_camera_position");
UNCOV
2351
    return OPENMC_E_INVALID_ARGUMENT;
×
2352
  }
2353

2354
  SolidRayTracePlot* plt = nullptr;
11✔
2355
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2356
  if (err)
11!
2357
    return err;
2358

2359
  const auto& camera_position = plt->camera_position();
11✔
2360
  *x = camera_position.x;
11✔
2361
  *y = camera_position.y;
11✔
2362
  *z = camera_position.z;
11✔
2363
  return 0;
11✔
2364
}
2365

2366
extern "C" int openmc_solidraytrace_plot_set_camera_position(
11✔
2367
  int32_t index, double x, double y, double z)
2368
{
2369
  SolidRayTracePlot* plt = nullptr;
11✔
2370
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2371
  if (err)
11!
2372
    return err;
2373

2374
  plt->camera_position() = {x, y, z};
11✔
2375
  return 0;
11✔
2376
}
2377

2378
extern "C" int openmc_solidraytrace_plot_get_look_at(
11✔
2379
  int32_t index, double* x, double* y, double* z)
2380
{
2381
  if (!x || !y || !z) {
11!
UNCOV
2382
    set_errmsg(
×
2383
      "Invalid arguments passed to openmc_solidraytrace_plot_get_look_at");
UNCOV
2384
    return OPENMC_E_INVALID_ARGUMENT;
×
2385
  }
2386

2387
  SolidRayTracePlot* plt = nullptr;
11✔
2388
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2389
  if (err)
11!
2390
    return err;
2391

2392
  const auto& look_at = plt->look_at();
11✔
2393
  *x = look_at.x;
11✔
2394
  *y = look_at.y;
11✔
2395
  *z = look_at.z;
11✔
2396
  return 0;
11✔
2397
}
2398

2399
extern "C" int openmc_solidraytrace_plot_set_look_at(
11✔
2400
  int32_t index, double x, double y, double z)
2401
{
2402
  SolidRayTracePlot* plt = nullptr;
11✔
2403
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2404
  if (err)
11!
2405
    return err;
2406

2407
  plt->look_at() = {x, y, z};
11✔
2408
  return 0;
11✔
2409
}
2410

2411
extern "C" int openmc_solidraytrace_plot_get_up(
11✔
2412
  int32_t index, double* x, double* y, double* z)
2413
{
2414
  if (!x || !y || !z) {
11!
UNCOV
2415
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_up");
×
2416
    return OPENMC_E_INVALID_ARGUMENT;
×
2417
  }
2418

2419
  SolidRayTracePlot* plt = nullptr;
11✔
2420
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2421
  if (err)
11!
2422
    return err;
2423

2424
  const auto& up = plt->up();
11✔
2425
  *x = up.x;
11✔
2426
  *y = up.y;
11✔
2427
  *z = up.z;
11✔
2428
  return 0;
11✔
2429
}
2430

2431
extern "C" int openmc_solidraytrace_plot_set_up(
11✔
2432
  int32_t index, double x, double y, double z)
2433
{
2434
  SolidRayTracePlot* plt = nullptr;
11✔
2435
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2436
  if (err)
11!
2437
    return err;
2438

2439
  plt->up() = {x, y, z};
11✔
2440
  return 0;
11✔
2441
}
2442

2443
extern "C" int openmc_solidraytrace_plot_get_light_position(
11✔
2444
  int32_t index, double* x, double* y, double* z)
2445
{
2446
  if (!x || !y || !z) {
11!
UNCOV
2447
    set_errmsg("Invalid arguments passed to "
×
2448
               "openmc_solidraytrace_plot_get_light_position");
UNCOV
2449
    return OPENMC_E_INVALID_ARGUMENT;
×
2450
  }
2451

2452
  SolidRayTracePlot* plt = nullptr;
11✔
2453
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2454
  if (err)
11!
2455
    return err;
2456

2457
  const auto& light_position = plt->light_location();
11✔
2458
  *x = light_position.x;
11✔
2459
  *y = light_position.y;
11✔
2460
  *z = light_position.z;
11✔
2461
  return 0;
11✔
2462
}
2463

2464
extern "C" int openmc_solidraytrace_plot_set_light_position(
11✔
2465
  int32_t index, double x, double y, double z)
2466
{
2467
  SolidRayTracePlot* plt = nullptr;
11✔
2468
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2469
  if (err)
11!
2470
    return err;
2471

2472
  plt->light_location() = {x, y, z};
11✔
2473
  return 0;
11✔
2474
}
2475

2476
extern "C" int openmc_solidraytrace_plot_get_fov(int32_t index, double* fov)
11✔
2477
{
2478
  if (!fov) {
11!
UNCOV
2479
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_fov");
×
2480
    return OPENMC_E_INVALID_ARGUMENT;
×
2481
  }
2482

2483
  SolidRayTracePlot* plt = nullptr;
11✔
2484
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2485
  if (err)
11!
2486
    return err;
2487

2488
  *fov = plt->horizontal_field_of_view();
11✔
2489
  return 0;
11✔
2490
}
2491

2492
extern "C" int openmc_solidraytrace_plot_set_fov(int32_t index, double fov)
11✔
2493
{
2494
  SolidRayTracePlot* plt = nullptr;
11✔
2495
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2496
  if (err)
11!
2497
    return err;
2498

2499
  plt->horizontal_field_of_view() = fov;
11✔
2500
  return 0;
11✔
2501
}
2502

2503
extern "C" int openmc_solidraytrace_plot_update_view(int32_t index)
22✔
2504
{
2505
  SolidRayTracePlot* plt = nullptr;
22✔
2506
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2507
  if (err)
22!
2508
    return err;
2509

2510
  plt->update_view();
22✔
2511
  return 0;
2512
}
2513

2514
extern "C" int openmc_solidraytrace_plot_create_image(
22✔
2515
  int32_t index, uint8_t* data_out, int32_t width, int32_t height)
2516
{
2517
  if (!data_out || width <= 0 || height <= 0) {
22!
UNCOV
2518
    set_errmsg(
×
2519
      "Invalid arguments passed to openmc_solidraytrace_plot_create_image");
UNCOV
2520
    return OPENMC_E_INVALID_ARGUMENT;
×
2521
  }
2522

2523
  SolidRayTracePlot* plt = nullptr;
22✔
2524
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2525
  if (err)
22!
2526
    return err;
2527

2528
  if (plt->pixels()[0] != width || plt->pixels()[1] != height) {
22!
UNCOV
2529
    set_errmsg(
×
2530
      "Requested image size does not match SolidRayTracePlot pixel settings");
UNCOV
2531
    return OPENMC_E_INVALID_SIZE;
×
2532
  }
2533

2534
  ImageData data = plt->create_image();
22✔
2535
  if (static_cast<int32_t>(data.shape()[0]) != width ||
22!
2536
      static_cast<int32_t>(data.shape()[1]) != height) {
22!
UNCOV
2537
    set_errmsg("Unexpected image size from SolidRayTracePlot create_image");
×
2538
    return OPENMC_E_INVALID_SIZE;
×
2539
  }
2540

2541
  for (int32_t y = 0; y < height; ++y) {
154✔
2542
    for (int32_t x = 0; x < width; ++x) {
1,188✔
2543
      const auto& color = data(x, y);
1,056✔
2544
      size_t idx = (static_cast<size_t>(y) * width + x) * 3;
1,056✔
2545
      data_out[idx + 0] = color.red;
1,056✔
2546
      data_out[idx + 1] = color.green;
1,056✔
2547
      data_out[idx + 2] = color.blue;
1,056✔
2548
    }
2549
  }
2550

2551
  return 0;
2552
}
22✔
2553

2554
extern "C" int openmc_solidraytrace_plot_get_color(
11✔
2555
  int32_t index, int32_t id, uint8_t* r, uint8_t* g, uint8_t* b)
2556
{
2557
  if (!r || !g || !b) {
11!
UNCOV
2558
    set_errmsg(
×
2559
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color");
UNCOV
2560
    return OPENMC_E_INVALID_ARGUMENT;
×
2561
  }
2562

2563
  SolidRayTracePlot* plt = nullptr;
11✔
2564
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2565
  if (err)
11!
2566
    return err;
2567

2568
  int32_t domain_index = -1;
11✔
2569
  err = map_phong_domain_id(plt, id, &domain_index);
11✔
2570
  if (err)
11!
2571
    return err;
2572

2573
  if (domain_index < 0 ||
11!
2574
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
11!
UNCOV
2575
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2576
    return OPENMC_E_OUT_OF_BOUNDS;
×
2577
  }
2578

2579
  const auto& color = plt->colors_[domain_index];
11✔
2580
  *r = color.red;
11✔
2581
  *g = color.green;
11✔
2582
  *b = color.blue;
11✔
2583
  return 0;
11✔
2584
}
2585

2586
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
11✔
2587
  int32_t index, double* diffuse_fraction)
2588
{
2589
  if (!diffuse_fraction) {
11!
UNCOV
2590
    set_errmsg("Invalid arguments passed to "
×
2591
               "openmc_solidraytrace_plot_get_diffuse_fraction");
UNCOV
2592
    return OPENMC_E_INVALID_ARGUMENT;
×
2593
  }
2594

2595
  SolidRayTracePlot* plt = nullptr;
11✔
2596
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2597
  if (err)
11!
2598
    return err;
2599

2600
  *diffuse_fraction = plt->diffuse_fraction();
11✔
2601
  return 0;
11✔
2602
}
2603

2604
extern "C" int openmc_solidraytrace_plot_set_diffuse_fraction(
11✔
2605
  int32_t index, double diffuse_fraction)
2606
{
2607
  SolidRayTracePlot* plt = nullptr;
11✔
2608
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2609
  if (err)
11!
2610
    return err;
2611

2612
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
11!
UNCOV
2613
    set_errmsg("Diffuse fraction must be between 0 and 1");
×
2614
    return OPENMC_E_INVALID_ARGUMENT;
×
2615
  }
2616

2617
  plt->diffuse_fraction() = diffuse_fraction;
11✔
2618
  return 0;
11✔
2619
}
2620

2621
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc