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

openmc-dev / openmc / 28811626106

06 Jul 2026 05:47PM UTC coverage: 81.283% (-0.006%) from 81.289%
28811626106

push

github

web-flow
Overlap detection for plotter (#3969)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

18193 of 26406 branches covered (68.9%)

Branch coverage included in aggregate %.

64 of 67 new or added lines in 5 files covered. (95.52%)

3 existing lines in 2 files now uncovered.

59362 of 69008 relevant lines covered (86.02%)

48656418.3 hits per line

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

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

3
#include <algorithm>
4
#define _USE_MATH_DEFINES // to make M_PI declared in Intel and MSVC compilers
5
#include <cmath>
6
#include <cstdio>
7
#include <fstream>
8
#include <sstream>
9

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

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

38
namespace openmc {
39

40
//==============================================================================
41
// Constants
42
//==============================================================================
43

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

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

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

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

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

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

86
void PropertyData::set_value(size_t y, size_t x, const Particle& p, int level,
×
87
  Filter* /*filter*/, FilterMatch* /*match*/)
88
{
89
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
×
90
  data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN;
×
91
  if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) {
×
92
    Material* m = model::materials.at(p.material()).get();
×
93
    data_(y, x, 1) = m->density_gpcc_;
×
94
  }
95
}
×
96

NEW
97
void PropertyData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
×
98
{
99
  data_(y, x) = OVERLAP;
×
100
}
×
101

102
//==============================================================================
103
// RasterData implementation
104
//==============================================================================
105

106
RasterData::RasterData(size_t h_res, size_t v_res, bool include_filter)
421 ✔
107
  : id_data_({v_res, h_res, include_filter ? 4u : 3u}, NOT_FOUND),
820 ✔
108
    property_data_({v_res, h_res, 2}, static_cast<double>(NOT_FOUND)),
421 ✔
109
    include_filter_(include_filter)
421 ✔
110
{}
421 ✔
111

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

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

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

147
  // set temperature (in K)
148
  property_data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN;
3,747,654 ✔
149

150
  // set density (g/cm³)
151
  if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) {
3,747,654 !
152
    Material* m = model::materials.at(p.material()).get();
1,199,530 ✔
153
    property_data_(y, x, 1) = m->density_gpcc_;
1,199,530 ✔
154
  }
155
}
3,747,654 ✔
156

157
void RasterData::set_overlap(size_t y, size_t x, int overlap_idx)
365,772 ✔
158
{
159
  // Set cell, instance, and material to OVERLAP, but preserve filter bin
160
  id_data_(y, x, 0) = OVERLAP;
365,772 ✔
161
  id_data_(y, x, 1) = OVERLAP;
365,772 ✔
162
  id_data_(y, x, 2) = OVERLAP - overlap_idx - 1;
365,772 ✔
163
  // Note: id_data_(y, x, 3) is NOT overwritten - preserves filter bin for tally
164
  // plotting
165

166
  property_data_(y, x, 0) = OVERLAP;
365,772 ✔
167
  property_data_(y, x, 1) = OVERLAP;
365,772 ✔
168
}
365,772 ✔
169

170
//==============================================================================
171
// Global variables
172
//==============================================================================
173

174
namespace model {
175

176
std::unordered_map<int, int> plot_map;
177
vector<std::unique_ptr<PlottableInterface>> plots;
178
uint64_t plotter_seed = 1;
179

180
} // namespace model
181

182
//==============================================================================
183
// RUN_PLOT controls the logic for making one or many plots
184
//==============================================================================
185

186
extern "C" int openmc_plot_geometry()
121 ✔
187
{
188

189
  for (auto& pl : model::plots) {
407 ✔
190
    write_message(5, "Processing plot {}: {}...", pl->id(), pl->path_plot());
286 ✔
191
    pl->create_output();
286 ✔
192
  }
193

194
  return 0;
121 ✔
195
}
196

197
void PlottableInterface::write_image(const ImageData& data) const
231 ✔
198
{
199
#ifdef USE_LIBPNG
200
  output_png(path_plot(), data);
231 ✔
201
#else
202
  output_ppm(path_plot(), data);
203
#endif
204
}
231 ✔
205

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

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

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

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

236
  if (PlotColorBy::cells == color_by_) {
154 ✔
237
    fmt::print("Coloring: Cells\n");
88 ✔
238
  } else if (PlotColorBy::mats == color_by_) {
66 !
239
    fmt::print("Coloring: Materials\n");
66 ✔
240
  }
241

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

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

270
  write_message("Reading plot XML file...", 5);
1,399 ✔
271

272
  // Parse plots.xml file
273
  pugi::xml_document doc;
1,399 ✔
274
  doc.load_file(filename.c_str());
1,399 ✔
275

276
  pugi::xml_node root = doc.document_element();
1,399 ✔
277

278
  read_plots_xml(root);
1,399 ✔
279
}
1,399 ✔
280

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

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

313
void free_memory_plot()
9,012 ✔
314
{
315
  model::plots.clear();
9,012 ✔
316
  model::plot_map.clear();
9,012 ✔
317
}
9,012 ✔
318

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

326
  ImageData data({width, height}, not_found_);
143 ✔
327

328
  // generate ids for the plot
329
  auto ids = get_map<IdData>();
143 ✔
330

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

356
  // draw mesh lines if present
357
  if (index_meshlines_mesh_ >= 0) {
143 ✔
358
    draw_mesh_lines(data);
33 ✔
359
  }
360

361
  return data;
143 ✔
362
}
143 ✔
363

364
void PlottableInterface::set_id(pugi::xml_node plot_node)
979 ✔
365
{
366
  int id {C_NONE};
979 ✔
367
  if (check_for_node(plot_node, "id")) {
979 !
368
    id = std::stoi(get_node_value(plot_node, "id"));
979 ✔
369
  }
370

371
  try {
979 ✔
372
    set_id(id);
979 ✔
373
  } catch (const std::runtime_error& e) {
×
374
    fatal_error(e.what());
×
375
  }
×
376
}
979 ✔
377

378
void PlottableInterface::set_id(int id)
990 ✔
379
{
380
  if (id < 0 && id != C_NONE) {
990 !
381
    throw std::runtime_error {fmt::format("Invalid plot ID: {}", id)};
×
382
  }
383

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

391
  if (id_ == id)
990 !
392
    return;
393

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

400
  id_ = id;
990 ✔
401
}
402

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

414
void Plot::set_output_path(pugi::xml_node plot_node)
891 ✔
415
{
416
  // Set output file path
417
  std::string filename;
891 ✔
418

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

446
  path_plot_ = filename;
882 ✔
447

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

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

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

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

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

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

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

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

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

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

639
void Plot::set_meshlines(pugi::xml_node plot_node)
882 ✔
640
{
641
  // Deal with meshlines
642
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
882 ✔
643

644
  if (!mesh_line_nodes.empty()) {
882 ✔
645
    if (PlotType::voxel == type_) {
33 !
646
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
647
    }
648

649
    if (mesh_line_nodes.size() == 1) {
33 !
650
      // Get first meshline node
651
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
33 ✔
652

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

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

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

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

747
void PlottableInterface::set_mask(pugi::xml_node plot_node)
979 ✔
748
{
749
  // Deal with masks
750
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
979 ✔
751

752
  if (!mask_nodes.empty()) {
979 ✔
753
    if (mask_nodes.size() == 1) {
33 !
754
      // Get pointer to mask
755
      pugi::xml_node mask_node = mask_nodes[0].node();
33 ✔
756

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

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

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

798
    } else {
33 ✔
799
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
800
    }
801
  }
802
}
979 ✔
803

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

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

833
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
979 ✔
834
{
835
  set_id(plot_node);
979 ✔
836
  set_bg_color(plot_node);
979 ✔
837
  set_universe(plot_node);
979 ✔
838
  set_color_by(plot_node);
979 ✔
839
  set_default_colors();
979 ✔
840
  set_user_colors(plot_node);
979 ✔
841
  set_mask(plot_node);
979 ✔
842
  set_overlap_color(plot_node);
979 ✔
843
}
979 ✔
844

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

857
//==============================================================================
858
// OUTPUT_PPM writes out a previously generated image to a PPM file
859
//==============================================================================
860

861
void output_ppm(const std::string& filename, const ImageData& data)
×
862
{
863
  // Open PPM file for writing
864
  std::string fname = filename;
×
865
  fname = strtrim(fname);
×
866
  std::ofstream of;
×
867

868
  of.open(fname);
×
869

870
  // Write header
871
  of << "P6\n";
×
872
  of << data.shape(0) << " " << data.shape(1) << "\n";
×
873
  of << "255\n";
×
874
  of.close();
×
875

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

887
//==============================================================================
888
// OUTPUT_PNG writes out a previously generated image to a PNG file
889
//==============================================================================
890

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

899
  // Initialize write and info structures
900
  auto png_ptr =
231 ✔
901
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
231 ✔
902
  auto info_ptr = png_create_info_struct(png_ptr);
231 ✔
903

904
  // Setup exception handling
905
  if (setjmp(png_jmpbuf(png_ptr)))
231 !
906
    fatal_error("Error during png creation");
×
907

908
  png_init_io(png_ptr, fp);
231 ✔
909

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

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

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

931
  // End write
932
  png_write_end(png_ptr, nullptr);
231 ✔
933

934
  // Clean up data structures
935
  std::fclose(fp);
231 ✔
936
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
231 ✔
937
  png_destroy_write_struct(&png_ptr, &info_ptr);
231 ✔
938
}
231 ✔
939
#endif
940

941
//==============================================================================
942
// DRAW_MESH_LINES draws mesh line boundaries on an image
943
//==============================================================================
944

945
void Plot::draw_mesh_lines(ImageData& data) const
33 ✔
946
{
947
  RGBColor rgb;
33 !
948
  rgb = meshlines_color_;
33 ✔
949

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

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

984
  Position ll_plot {origin_};
33 ✔
985
  Position ur_plot {origin_};
33 ✔
986

987
  ll_plot[ax1] -= width_[0] / 2.;
33 ✔
988
  ll_plot[ax2] -= width_[1] / 2.;
33 ✔
989
  ur_plot[ax1] += width_[0] / 2.;
33 ✔
990
  ur_plot[ax2] += width_[1] / 2.;
33 ✔
991

992
  Position width = ur_plot - ll_plot;
33 ✔
993

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

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

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

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

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

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

1077
  // initial particle position
1078
  Position ll = origin_ - width_ / 2.;
55 ✔
1079

1080
  // Open binary plot file for writing
1081
  std::ofstream of;
55 ✔
1082
  std::string fname = std::string(path_plot_);
55 ✔
1083
  fname = strtrim(fname);
55 ✔
1084
  hid_t file_id = file_open(fname, 'w');
55 ✔
1085

1086
  // write header info
1087
  write_attribute(file_id, "filetype", "voxel");
55 ✔
1088
  write_attribute(file_id, "version", VERSION_VOXEL);
55 ✔
1089
  write_attribute(file_id, "openmc_version", VERSION);
55 ✔
1090

1091
#ifdef GIT_SHA1
1092
  write_attribute(file_id, "git_sha1", GIT_SHA1);
1093
#endif
1094

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

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

1112
  SlicePlotBase pltbase;
55 ✔
1113
  pltbase.origin_ = origin_;
55 ✔
1114
  pltbase.u_span_ = {width_.x, 0.0, 0.0};
55 ✔
1115
  pltbase.v_span_ = {0.0, width_.y, 0.0};
55 ✔
1116
  pltbase.pixels() = pixels();
55 ✔
1117
  pltbase.show_overlaps_ = color_overlaps_;
55 ✔
1118

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

1124
    // generate ids using plotbase
1125
    IdData ids = pltbase.get_map<IdData>();
4,730 ✔
1126

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

1138
    // Write to HDF5 dataset
1139
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
4,730 ✔
1140

1141
    // update progress bar
1142
    pb.set_value(
4,730 ✔
1143
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
4,730 ✔
1144
  }
14,190 ✔
1145

1146
  voxel_finalize(dspace, dset, memspace);
55 ✔
1147
  file_close(file_id);
55 ✔
1148
}
55 ✔
1149

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

1158
  // Create dataspace for a slice of the voxel
1159
  hsize_t dims_slice[2] {dims[1], dims[2]};
55 ✔
1160
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
55 ✔
1161

1162
  // Select hyperslab in dataspace
1163
  hsize_t start[3] {0, 0, 0};
55 ✔
1164
  hsize_t count[3] {1, dims[1], dims[2]};
55 ✔
1165
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
55 ✔
1166
}
55 ✔
1167

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

1176
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
55 ✔
1177
{
1178
  H5Dclose(dset);
55 ✔
1179
  H5Sclose(dspace);
55 ✔
1180
  H5Sclose(memspace);
55 ✔
1181
}
55 ✔
1182

1183
RGBColor random_color(void)
3,441 ✔
1184
{
1185
  return {int(prn(&model::plotter_seed) * 255),
3,441 ✔
1186
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
3,441 ✔
1187
}
1188

1189
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
88 ✔
1190
{
1191
  set_look_at(node);
88 ✔
1192
  set_camera_position(node);
88 ✔
1193
  set_field_of_view(node);
88 ✔
1194
  set_pixels(node);
88 ✔
1195
  set_orthographic_width(node);
88 ✔
1196
  set_output_path(node);
88 ✔
1197

1198
  if (check_for_node(node, "orthographic_width") &&
99 !
1199
      check_for_node(node, "field_of_view"))
11 ✔
1200
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1201
                "parameters.");
1202
}
88 ✔
1203

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

1219
  // Cache the camera-to-model matrix
1220
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
110 ✔
1221
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
110 ✔
1222
    cam_yaxis.z, cam_zaxis.z};
110 ✔
1223
}
110 ✔
1224

1225
WireframeRayTracePlot::WireframeRayTracePlot(pugi::xml_node node)
55 ✔
1226
  : RayTracePlot(node)
55 ✔
1227
{
1228
  set_opacities(node);
55 ✔
1229
  set_wireframe_thickness(node);
55 ✔
1230
  set_wireframe_ids(node);
55 ✔
1231
  set_wireframe_color(node);
55 ✔
1232
  update_view();
55 ✔
1233
}
55 ✔
1234

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

1248
void RayTracePlot::set_output_path(pugi::xml_node node)
88 ✔
1249
{
1250
  // Set output file path
1251
  std::string filename;
88 ✔
1252

1253
  if (check_for_node(node, "filename")) {
88 ✔
1254
    filename = get_node_value(node, "filename");
77 ✔
1255
  } else {
1256
    filename = fmt::format("plot_{}", id());
11 ✔
1257
  }
1258

1259
#ifdef USE_LIBPNG
1260
  if (!file_extension_present(filename, "png"))
88 ✔
1261
    filename.append(".png");
33 ✔
1262
#else
1263
  if (!file_extension_present(filename, "ppm"))
1264
    filename.append(".ppm");
1265
#endif
1266
  path_plot_ = filename;
176 ✔
1267
}
88 ✔
1268

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

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

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

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

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

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

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

1347
  std::pair<Position, Direction> result;
3,521,056 ✔
1348

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

1357
    result.first = camera_position_;
3,081,056 ✔
1358
    result.second = camera_local_vec.rotate(camera_to_model_);
3,081,056 ✔
1359
  } else { // orthographic projection
1360

1361
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
440,000 ✔
1362
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
440,000 ✔
1363

1364
    result.first = camera_position_ +
440,000 ✔
1365
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
440,000 ✔
1366
                   camera_z_axis() * y_pix_coord * orthographic_width_;
440,000 ✔
1367
    result.second = camera_x_axis();
440,000 ✔
1368
  }
1369

1370
  return result;
3,521,056 ✔
1371
}
1372

1373
ImageData WireframeRayTracePlot::create_image() const
55 ✔
1374
{
1375
  size_t width = pixels()[0];
55 ✔
1376
  size_t height = pixels()[1];
55 ✔
1377
  ImageData data({width, height}, not_found_);
55 ✔
1378

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

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

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

1406
#pragma omp parallel
30 ✔
1407
  {
25 ✔
1408
    const int n_threads = num_threads();
25 ✔
1409
    const int tid = thread_num();
25 ✔
1410

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

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

1421
      if (vert < pixels()[1]) {
5,025 ✔
1422

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

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

1428
          this_line_segments[tid][horiz].clear();
1,000,000 ✔
1429
          ProjectionRay ray(
1,000,000 ✔
1430
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
1,000,000 ✔
1431

1432
          ray.trace();
1,000,000 ✔
1433

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

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

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

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

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

1478
      // We require a barrier before comparing vertical neighbors' intersection
1479
      // stacks. i.e. all threads must be done with their line.
1480
#pragma omp barrier
1481

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

1489
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
1490
        if (tid == 0)
1491
          top_cmp = &old_segments;
1492
        else
1493
          top_cmp = &this_line_segments[tid - 1];
1494

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

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

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

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

1532
  return data;
110 ✔
1533
}
110 ✔
1534

1535
void WireframeRayTracePlot::create_output() const
55 ✔
1536
{
1537
  ImageData data = create_image();
55 ✔
1538
  write_image(data);
55 ✔
1539
}
55 ✔
1540

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

1551
void WireframeRayTracePlot::print_info() const
55 ✔
1552
{
1553
  fmt::print("Plot Type: Wireframe ray-traced\n");
55 ✔
1554
  RayTracePlot::print_info();
55 ✔
1555
}
55 ✔
1556

1557
void WireframeRayTracePlot::set_opacities(pugi::xml_node node)
55 ✔
1558
{
1559
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
55 ✔
1560

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

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

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

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

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

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

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

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

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

1673
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
33 ✔
1674
{
1675
  set_opaque_ids(node);
33 ✔
1676
  set_diffuse_fraction(node);
33 ✔
1677
  set_light_position(node);
33 ✔
1678
  update_view();
33 ✔
1679
}
33 ✔
1680

1681
void SolidRayTracePlot::print_info() const
33 ✔
1682
{
1683
  fmt::print("Plot Type: Solid ray-traced\n");
33 ✔
1684
  RayTracePlot::print_info();
33 ✔
1685
}
33 ✔
1686

1687
ImageData SolidRayTracePlot::create_image() const
55 ✔
1688
{
1689
  size_t width = pixels()[0];
55 ✔
1690
  size_t height = pixels()[1];
55 ✔
1691
  ImageData data({width, height}, not_found_);
55 ✔
1692

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

1704
  return data;
55 ✔
1705
}
1706

1707
void SolidRayTracePlot::create_output() const
33 ✔
1708
{
1709
  ImageData data = create_image();
33 ✔
1710
  write_image(data);
33 ✔
1711
}
33 ✔
1712

1713
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
33 ✔
1714
{
1715
  if (check_for_node(node, "opaque_ids")) {
33 !
1716
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
33 ✔
1717

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

1724
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
33 ✔
1725
  }
33 ✔
1726
}
33 ✔
1727

1728
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
33 ✔
1729
{
1730
  if (check_for_node(node, "light_position")) {
33 ✔
1731
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
11 ✔
1732

1733
    if (light_pos_tmp.size() != 3)
11 !
1734
      fatal_error("Light position must be given as 3D coordinates");
×
1735

1736
    light_location_.x = light_pos_tmp[0];
11 ✔
1737
    light_location_.y = light_pos_tmp[1];
11 ✔
1738
    light_location_.z = light_pos_tmp[2];
11 ✔
1739
  } else {
11 ✔
1740
    light_location_ = camera_position();
22 ✔
1741
  }
1742
}
33 ✔
1743

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

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

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

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

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

1784
  // Anything that's not opaque has zero impact on the plot.
1785
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
905,971 ✔
1786
    return;
1787

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

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

1814
    // Get surface pointer
1815
    const auto& surf = model::surfaces.at(surface_index());
706,068 ✔
1816

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

1825
    Position r_hit_level =
706,068 ✔
1826
      coord(surf_level).r() - TINY_BIT * coord(surf_level).u();
706,068 ✔
1827
    Direction normal = surf->normal(r_hit_level);
706,068 ✔
1828
    normal /= normal.norm();
706,068 ✔
1829

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

1839
    // use the normal opposed to the ray direction
1840
    if (normal.dot(u()) > 0.0) {
706,068 ✔
1841
      normal *= -1.0;
63,789 ✔
1842
    }
1843

1844
    // Facing away from the light means no lighting
1845
    double dotprod = normal.dot(to_light);
706,068 ✔
1846
    dotprod = std::max(0.0, dotprod);
706,068 ✔
1847

1848
    double modulation =
706,068 ✔
1849
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
706,068 ✔
1850
    result_color_ *= modulation;
706,068 ✔
1851

1852
    // Now point the particle to the camera. We now begin
1853
    // checking to see if it's occluded by another surface
1854
    u() = to_light;
706,068 ✔
1855

1856
    orig_hit_id_ = hit_id;
706,068 ✔
1857

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

1867
    // Must fully restart coordinate search. Why? Not sure.
1868
    clear();
706,068 ✔
1869

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

1879
    // Must recalculate distance to boundary due to the
1880
    // direction change
1881
    compute_distance();
706,068 ✔
1882

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

1888
    if (orig_hit_id_ == -1)
35,563 !
1889
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1890

1891
    result_color_ = plot_.colors_[orig_hit_id_];
35,563 ✔
1892
    result_color_ *= plot_.diffuse_fraction_;
35,563 ✔
1893
    stop();
741,631 ✔
1894
  }
1895
}
1896

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

1906
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1907
  if (!plt) {
×
1908
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1909
    return OPENMC_E_INVALID_ARGUMENT;
×
1910
  }
1911

1912
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1913
    model::overlap_check_count.resize(model::cells.size());
×
1914
  }
1915

1916
  auto ids = plt->get_map<IdData>();
×
1917

1918
  // write id data to array
1919
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
×
1920

1921
  return 0;
×
1922
}
×
1923

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

1933
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1934
  if (!plt) {
×
1935
    set_errmsg("Invalid slice pointer passed to openmc_property_map");
×
1936
    return OPENMC_E_INVALID_ARGUMENT;
×
1937
  }
1938

1939
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1940
    model::overlap_check_count.resize(model::cells.size());
×
1941
  }
1942

1943
  auto props = plt->get_map<PropertyData>();
×
1944

1945
  // write id data to array
1946
  std::copy(props.data_.begin(), props.data_.end(), data_out);
×
1947

1948
  return 0;
×
1949
}
×
1950

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

1965
  constexpr double ORTHO_REL_TOL = 1e-10;
421 ✔
1966
  double dot = u_span_pos.dot(v_span_pos);
421 !
1967
  if (std::abs(dot) > ORTHO_REL_TOL * u_norm * v_norm) {
421 !
1968
    set_errmsg("Slice span vectors must be orthogonal.");
×
1969
    return OPENMC_E_INVALID_ARGUMENT;
×
1970
  }
1971

1972
  // Validate filter index if provided
1973
  if (filter_index >= 0) {
421 ✔
1974
    if (int err = verify_filter(filter_index))
22 !
1975
      return err;
1976
  }
1977

1978
  // Initialize overlap check vector if needed
1979
  if (color_overlaps && model::overlap_check_count.size() == 0) {
421 !
1980
    model::overlap_check_count.resize(model::cells.size());
55 ✔
1981
  }
1982

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

1994
    // Clear overlap data structures on new slice call
1995
    model::overlap_keys.clear();
421 ✔
1996
    model::overlap_key_index.clear();
421 ✔
1997

1998
    // Use get_map<RasterData> to generate data
1999
    auto data = plot_params.get_map<RasterData>(filter_index);
421 ✔
2000
    std::copy(data.id_data_.begin(), data.id_data_.end(), geom_data);
421 ✔
2001

2002
    // Copy property data if requested
2003
    if (property_data != nullptr) {
421 ✔
2004
      std::copy(
66 ✔
2005
        data.property_data_.begin(), data.property_data_.end(), property_data);
2006
    }
2007
  } catch (const std::exception& e) {
421 !
2008
    set_errmsg(e.what());
×
2009
    return OPENMC_E_UNASSIGNED;
×
2010
  }
×
2011

2012
  return 0;
421 ✔
2013
}
2014

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

2024
  return 0;
22 ✔
2025
}
2026

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

2038
  return 0;
11 ✔
2039
}
2040

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

2049
  *index = it->second;
22 ✔
2050
  return 0;
22 ✔
2051
}
2052

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

2060
  *id = model::plots[index]->id();
55 ✔
2061
  return 0;
55 ✔
2062
}
2063

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

2071
  if (id < 0 && id != C_NONE) {
×
2072
    set_errmsg("Invalid plot ID.");
×
2073
    return OPENMC_E_INVALID_ARGUMENT;
×
2074
  }
2075

2076
  auto* plot = model::plots[index].get();
×
2077
  int32_t old_id = plot->id();
×
2078
  if (id == old_id)
×
2079
    return 0;
2080

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

2093
extern "C" size_t openmc_plots_size()
22 ✔
2094
{
2095
  return model::plots.size();
22 ✔
2096
}
2097

2098
int map_phong_domain_id(
55 ✔
2099
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2100
{
2101
  if (!plot || !index_out) {
55 !
2102
    set_errmsg("Invalid plot pointer passed to map_phong_domain_id");
×
2103
    return OPENMC_E_INVALID_ARGUMENT;
×
2104
  }
2105

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

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

2126
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2127
  return OPENMC_E_INVALID_TYPE;
×
2128
}
2129

2130
int get_solidraytrace_plot_by_index(int32_t index, SolidRayTracePlot** plot)
308 ✔
2131
{
2132
  if (!plot) {
308 !
2133
    set_errmsg("Null output pointer passed to get_solidraytrace_plot_by_index");
×
2134
    return OPENMC_E_INVALID_ARGUMENT;
×
2135
  }
2136

2137
  if (index < 0 || index >= model::plots.size()) {
308 !
2138
    set_errmsg("Index in plots array is out of bounds.");
×
2139
    return OPENMC_E_OUT_OF_BOUNDS;
×
2140
  }
2141

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

2150
  *plot = solid_plot;
308 ✔
2151
  return 0;
308 ✔
2152
}
2153

2154
extern "C" int openmc_solidraytrace_plot_create(int32_t* index)
11 ✔
2155
{
2156
  if (!index) {
11 !
2157
    set_errmsg(
×
2158
      "Null output pointer passed to openmc_solidraytrace_plot_create");
2159
    return OPENMC_E_INVALID_ARGUMENT;
×
2160
  }
2161

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

2180
  return 0;
11 ✔
2181
}
2182

2183
extern "C" int openmc_solidraytrace_plot_get_pixels(
33 ✔
2184
  int32_t index, int32_t* width, int32_t* height)
2185
{
2186
  if (!width || !height) {
33 !
2187
    set_errmsg(
×
2188
      "Invalid arguments passed to openmc_solidraytrace_plot_get_pixels");
2189
    return OPENMC_E_INVALID_ARGUMENT;
×
2190
  }
2191

2192
  SolidRayTracePlot* plt = nullptr;
33 ✔
2193
  int err = get_solidraytrace_plot_by_index(index, &plt);
33 ✔
2194
  if (err)
33 !
2195
    return err;
2196

2197
  *width = plt->pixels()[0];
33 ✔
2198
  *height = plt->pixels()[1];
33 ✔
2199
  return 0;
33 ✔
2200
}
2201

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

2211
  SolidRayTracePlot* plt = nullptr;
11 ✔
2212
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2213
  if (err)
11 !
2214
    return err;
2215

2216
  plt->pixels()[0] = width;
11 ✔
2217
  plt->pixels()[1] = height;
11 ✔
2218
  return 0;
11 ✔
2219
}
2220

2221
extern "C" int openmc_solidraytrace_plot_get_color_by(
11 ✔
2222
  int32_t index, int32_t* color_by)
2223
{
2224
  if (!color_by) {
11 !
2225
    set_errmsg(
×
2226
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color_by");
2227
    return OPENMC_E_INVALID_ARGUMENT;
×
2228
  }
2229

2230
  SolidRayTracePlot* plt = nullptr;
11 ✔
2231
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2232
  if (err)
11 !
2233
    return err;
2234

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

2244
  return 0;
2245
}
2246

2247
extern "C" int openmc_solidraytrace_plot_set_color_by(
11 ✔
2248
  int32_t index, int32_t color_by)
2249
{
2250
  SolidRayTracePlot* plt = nullptr;
11 ✔
2251
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2252
  if (err)
11 !
2253
    return err;
2254

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

2264
  return 0;
2265
}
2266

2267
extern "C" int openmc_solidraytrace_plot_set_default_colors(int32_t index)
11 ✔
2268
{
2269
  SolidRayTracePlot* plt = nullptr;
11 ✔
2270
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2271
  if (err)
11 !
2272
    return err;
2273

2274
  plt->set_default_colors();
11 ✔
2275
  return 0;
2276
}
2277

2278
extern "C" int openmc_solidraytrace_plot_set_all_opaque(int32_t index)
×
2279
{
2280
  SolidRayTracePlot* plt = nullptr;
×
2281
  int err = get_solidraytrace_plot_by_index(index, &plt);
×
2282
  if (err)
×
2283
    return err;
2284

2285
  plt->opaque_ids().clear();
×
2286
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
×
2287
    for (int32_t i = 0; i < model::materials.size(); ++i) {
×
2288
      plt->opaque_ids().insert(i);
×
2289
    }
2290
    return 0;
×
2291
  }
2292

2293
  if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2294
    for (int32_t i = 0; i < model::cells.size(); ++i) {
×
2295
      plt->opaque_ids().insert(i);
×
2296
    }
2297
    return 0;
×
2298
  }
2299

2300
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2301
  return OPENMC_E_INVALID_TYPE;
×
2302
}
2303

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

2312
  int32_t domain_index = -1;
22 ✔
2313
  err = map_phong_domain_id(plt, id, &domain_index);
22 ✔
2314
  if (err)
22 !
2315
    return err;
2316

2317
  if (visible) {
22 ✔
2318
    plt->opaque_ids().insert(domain_index);
11 ✔
2319
  } else {
2320
    plt->opaque_ids().erase(domain_index);
11 ✔
2321
  }
2322

2323
  return 0;
2324
}
2325

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

2334
  int32_t domain_index = -1;
22 ✔
2335
  err = map_phong_domain_id(plt, id, &domain_index);
22 ✔
2336
  if (err)
22 !
2337
    return err;
2338

2339
  if (domain_index < 0 ||
22 !
2340
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
22 !
2341
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2342
    return OPENMC_E_OUT_OF_BOUNDS;
×
2343
  }
2344

2345
  plt->colors_[domain_index] = RGBColor(r, g, b);
22 ✔
2346
  return 0;
22 ✔
2347
}
2348

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

2358
  SolidRayTracePlot* plt = nullptr;
11 ✔
2359
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2360
  if (err)
11 !
2361
    return err;
2362

2363
  const auto& camera_position = plt->camera_position();
11 ✔
2364
  *x = camera_position.x;
11 ✔
2365
  *y = camera_position.y;
11 ✔
2366
  *z = camera_position.z;
11 ✔
2367
  return 0;
11 ✔
2368
}
2369

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

2378
  plt->camera_position() = {x, y, z};
11 ✔
2379
  return 0;
11 ✔
2380
}
2381

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

2391
  SolidRayTracePlot* plt = nullptr;
11 ✔
2392
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2393
  if (err)
11 !
2394
    return err;
2395

2396
  const auto& look_at = plt->look_at();
11 ✔
2397
  *x = look_at.x;
11 ✔
2398
  *y = look_at.y;
11 ✔
2399
  *z = look_at.z;
11 ✔
2400
  return 0;
11 ✔
2401
}
2402

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

2411
  plt->look_at() = {x, y, z};
11 ✔
2412
  return 0;
11 ✔
2413
}
2414

2415
extern "C" int openmc_solidraytrace_plot_get_up(
11 ✔
2416
  int32_t index, double* x, double* y, double* z)
2417
{
2418
  if (!x || !y || !z) {
11 !
2419
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_up");
×
2420
    return OPENMC_E_INVALID_ARGUMENT;
×
2421
  }
2422

2423
  SolidRayTracePlot* plt = nullptr;
11 ✔
2424
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2425
  if (err)
11 !
2426
    return err;
2427

2428
  const auto& up = plt->up();
11 ✔
2429
  *x = up.x;
11 ✔
2430
  *y = up.y;
11 ✔
2431
  *z = up.z;
11 ✔
2432
  return 0;
11 ✔
2433
}
2434

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

2443
  plt->up() = {x, y, z};
11 ✔
2444
  return 0;
11 ✔
2445
}
2446

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

2456
  SolidRayTracePlot* plt = nullptr;
11 ✔
2457
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2458
  if (err)
11 !
2459
    return err;
2460

2461
  const auto& light_position = plt->light_location();
11 ✔
2462
  *x = light_position.x;
11 ✔
2463
  *y = light_position.y;
11 ✔
2464
  *z = light_position.z;
11 ✔
2465
  return 0;
11 ✔
2466
}
2467

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

2476
  plt->light_location() = {x, y, z};
11 ✔
2477
  return 0;
11 ✔
2478
}
2479

2480
extern "C" int openmc_solidraytrace_plot_get_fov(int32_t index, double* fov)
11 ✔
2481
{
2482
  if (!fov) {
11 !
2483
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_fov");
×
2484
    return OPENMC_E_INVALID_ARGUMENT;
×
2485
  }
2486

2487
  SolidRayTracePlot* plt = nullptr;
11 ✔
2488
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2489
  if (err)
11 !
2490
    return err;
2491

2492
  *fov = plt->horizontal_field_of_view();
11 ✔
2493
  return 0;
11 ✔
2494
}
2495

2496
extern "C" int openmc_solidraytrace_plot_set_fov(int32_t index, double fov)
11 ✔
2497
{
2498
  SolidRayTracePlot* plt = nullptr;
11 ✔
2499
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2500
  if (err)
11 !
2501
    return err;
2502

2503
  plt->horizontal_field_of_view() = fov;
11 ✔
2504
  return 0;
11 ✔
2505
}
2506

2507
extern "C" int openmc_solidraytrace_plot_update_view(int32_t index)
22 ✔
2508
{
2509
  SolidRayTracePlot* plt = nullptr;
22 ✔
2510
  int err = get_solidraytrace_plot_by_index(index, &plt);
22 ✔
2511
  if (err)
22 !
2512
    return err;
2513

2514
  plt->update_view();
22 ✔
2515
  return 0;
2516
}
2517

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

2527
  SolidRayTracePlot* plt = nullptr;
22 ✔
2528
  int err = get_solidraytrace_plot_by_index(index, &plt);
22 ✔
2529
  if (err)
22 !
2530
    return err;
2531

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

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

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

2555
  return 0;
2556
}
22 ✔
2557

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

2567
  SolidRayTracePlot* plt = nullptr;
11 ✔
2568
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2569
  if (err)
11 !
2570
    return err;
2571

2572
  int32_t domain_index = -1;
11 ✔
2573
  err = map_phong_domain_id(plt, id, &domain_index);
11 ✔
2574
  if (err)
11 !
2575
    return err;
2576

2577
  if (domain_index < 0 ||
11 !
2578
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
11 !
2579
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2580
    return OPENMC_E_OUT_OF_BOUNDS;
×
2581
  }
2582

2583
  const auto& color = plt->colors_[domain_index];
11 ✔
2584
  *r = color.red;
11 ✔
2585
  *g = color.green;
11 ✔
2586
  *b = color.blue;
11 ✔
2587
  return 0;
11 ✔
2588
}
2589

2590
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
11 ✔
2591
  int32_t index, double* diffuse_fraction)
2592
{
2593
  if (!diffuse_fraction) {
11 !
2594
    set_errmsg("Invalid arguments passed to "
×
2595
               "openmc_solidraytrace_plot_get_diffuse_fraction");
2596
    return OPENMC_E_INVALID_ARGUMENT;
×
2597
  }
2598

2599
  SolidRayTracePlot* plt = nullptr;
11 ✔
2600
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2601
  if (err)
11 !
2602
    return err;
2603

2604
  *diffuse_fraction = plt->diffuse_fraction();
11 ✔
2605
  return 0;
11 ✔
2606
}
2607

2608
extern "C" int openmc_solidraytrace_plot_set_diffuse_fraction(
11 ✔
2609
  int32_t index, double diffuse_fraction)
2610
{
2611
  SolidRayTracePlot* plt = nullptr;
11 ✔
2612
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2613
  if (err)
11 !
2614
    return err;
2615

2616
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
11 !
2617
    set_errmsg("Diffuse fraction must be between 0 and 1");
×
2618
    return OPENMC_E_INVALID_ARGUMENT;
×
2619
  }
2620

2621
  plt->diffuse_fraction() = diffuse_fraction;
11 ✔
2622
  return 0;
11 ✔
2623
}
2624

2625
} // 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