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

openmc-dev / openmc / 28603943192

02 Jul 2026 04:00PM UTC coverage: 81.253% (-0.03%) from 81.281%
28603943192

Pull #3969

github

web-flow
Merge 72241c342 into f01852411
Pull Request #3969: Overlap detection for plotter

18177 of 26384 branches covered (68.89%)

Branch coverage included in aggregate %.

45 of 66 new or added lines in 5 files covered. (68.18%)

135 existing lines in 11 files now uncovered.

59312 of 68984 relevant lines covered (85.98%)

48347598.95 hits per line

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

69.06
/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, size_t /*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, size_t /*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)
399✔
107
  : id_data_({v_res, h_res, include_filter ? 4u : 3u}, NOT_FOUND),
776✔
108
    property_data_({v_res, h_res, 2}, static_cast<double>(NOT_FOUND)),
399✔
109
    include_filter_(include_filter)
399✔
110
{}
399✔
111

112
void RasterData::set_value(size_t y, size_t x, const Particle& p, int level,
3,615,654✔
113
  Filter* filter, FilterMatch* match)
114
{
115
  // set cell data
116
  if (p.n_coord() <= level) {
3,615,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,615,654!
121
    id_data_(y, x, 1) = level == p.n_coord() - 1
3,615,654✔
122
                          ? p.cell_instance()
3,615,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,615,654✔
128
  if (p.material() == MATERIAL_VOID) {
3,615,654✔
129
    id_data_(y, x, 2) = MATERIAL_VOID;
2,502,540✔
130
  } else if (c->type_ == Fill::MATERIAL) {
1,113,114!
131
    Material* m = model::materials.at(p.material()).get();
1,113,114✔
132
    id_data_(y, x, 2) = m->id_;
1,113,114✔
133
  }
134

135
  // set filter index (only if filter is being used)
136
  if (include_filter_ && filter) {
3,615,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,615,654✔
149

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

157
void RasterData::set_overlap(size_t y, size_t x, size_t overlap_idx)
346,060✔
158
{
159
  // Set cell, instance, and material to OVERLAP, but preserve filter bin
160
  id_data_(y, x, 0) = OVERLAP;
346,060✔
161
  id_data_(y, x, 1) = OVERLAP;
346,060✔
162
  id_data_(y, x, 2) = OVERLAP - overlap_idx - 1;
346,060✔
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;
346,060✔
167
  property_data_(y, x, 1) = OVERLAP;
346,060✔
168
}
346,060✔
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
std::unique_ptr<RasterData> last_slice_data;
181

182
} // namespace model
183

184
//==============================================================================
185
// RUN_PLOT controls the logic for making one or many plots
186
//==============================================================================
187

188
extern "C" int openmc_plot_geometry()
121✔
189
{
190

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

196
  return 0;
121✔
197
}
198

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

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

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

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

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

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

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

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

272
  write_message("Reading plot XML file...", 5);
1,399✔
273

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

278
  pugi::xml_node root = doc.document_element();
1,399✔
279

280
  read_plots_xml(root);
1,399✔
281
}
1,399✔
282

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

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

315
void free_memory_plot()
8,920✔
316
{
317
  model::plots.clear();
8,920✔
318
  model::plot_map.clear();
8,920✔
319
}
8,920✔
320

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

328
  ImageData data({width, height}, not_found_);
143✔
329

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

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

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

363
  return data;
143✔
364
}
143✔
365

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

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

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

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

393
  if (id_ == id)
990!
394
    return;
395

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

402
  id_ = id;
990✔
403
}
404

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

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

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

448
  path_plot_ = filename;
882✔
449

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

859
//==============================================================================
860
// OUTPUT_PPM writes out a previously generated image to a PPM file
861
//==============================================================================
862

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

870
  of.open(fname);
×
871

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

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

889
//==============================================================================
890
// OUTPUT_PNG writes out a previously generated image to a PNG file
891
//==============================================================================
892

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

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

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

910
  png_init_io(png_ptr, fp);
231✔
911

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

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

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

933
  // End write
934
  png_write_end(png_ptr, nullptr);
231✔
935

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

943
//==============================================================================
944
// DRAW_MESH_LINES draws mesh line boundaries on an image
945
//==============================================================================
946

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

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

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

986
  Position ll_plot {origin_};
33✔
987
  Position ur_plot {origin_};
33✔
988

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

994
  Position width = ur_plot - ll_plot;
33✔
995

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

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

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

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

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

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

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

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

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

1093
#ifdef GIT_SHA1
1094
  write_attribute(file_id, "git_sha1", GIT_SHA1);
1095
#endif
1096

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

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

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

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

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

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

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

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

1148
  voxel_finalize(dspace, dset, memspace);
55✔
1149
  file_close(file_id);
55✔
1150
}
55✔
1151

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1349
  std::pair<Position, Direction> result;
3,521,056✔
1350

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

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

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

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

1372
  return result;
3,521,056✔
1373
}
1374

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

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

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

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

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

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

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

1423
      if (vert < pixels()[1]) {
5,025✔
1424

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

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

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

1434
          ray.trace();
1,000,000✔
1435

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

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

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

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

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

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

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

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

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

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

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

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

1534
  return data;
110✔
1535
}
110✔
1536

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1706
  return data;
55✔
1707
}
1708

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

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

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

1726
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
33✔
1727
  }
33✔
1728
}
33✔
1729

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1858
    orig_hit_id_ = hit_id;
706,068✔
1859

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

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

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

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

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

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

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

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

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

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

1918
  auto ids = plt->get_map<IdData>();
×
1919

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

1923
  return 0;
×
1924
}
×
1925

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

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

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

1945
  auto props = plt->get_map<PropertyData>();
×
1946

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

1950
  return 0;
×
1951
}
×
1952

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

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

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

1980
  // Initialize overlap check vector if needed
1981
  if (color_overlaps && model::overlap_check_count.size() == 0) {
399!
1982
    model::overlap_check_count.resize(model::cells.size());
44✔
1983
  }
1984

1985
  if (color_overlaps) {
399✔
1986
    settings::check_overlaps = true;
44✔
1987
  }
1988

1989
  try {
399✔
1990
    // Create a temporary SlicePlotBase object to reuse get_map logic
1991
    SlicePlotBase plot_params;
399✔
1992
    plot_params.origin_ = Position {origin[0], origin[1], origin[2]};
399✔
1993
    plot_params.u_span_ = u_span_pos;
399✔
1994
    plot_params.v_span_ = v_span_pos;
399✔
1995
    plot_params.pixels_[0] = pixels[0];
399✔
1996
    plot_params.pixels_[1] = pixels[1];
399✔
1997
    plot_params.show_overlaps_ = color_overlaps;
399✔
1998
    plot_params.slice_level_ = level;
399✔
1999

2000
    // Clear overlap data structures on new slice call
2001
    model::overlap_keys.clear();
399✔
2002
    model::overlap_key_index.clear();
399✔
2003

2004
    // Use get_map<RasterData> to generate data
2005
    auto data = plot_params.get_map<RasterData>(filter_index);
399✔
2006
    std::copy(data.id_data_.begin(), data.id_data_.end(), geom_data);
399✔
2007

2008
    // Copy property data if requested
2009
    if (property_data != nullptr) {
399✔
2010
      std::copy(
66✔
2011
        data.property_data_.begin(), data.property_data_.end(), property_data);
2012
    }
2013

2014
  } catch (const std::exception& e) {
399!
2015
    set_errmsg(e.what());
×
2016
    return OPENMC_E_UNASSIGNED;
×
2017
  }
×
2018

2019
  return 0;
399✔
2020
}
2021

2022
// Gets the number of overlaps that we need data for
NEW
2023
extern "C" int openmc_slice_data_overlap_count(size_t* count)
×
2024
{
NEW
2025
  if (!count) {
×
NEW
2026
    set_errmsg("Null pointer passed for overlap count.");
×
NEW
2027
    return OPENMC_E_INVALID_ARGUMENT;
×
2028
  }
NEW
2029
  *count = model::overlap_keys.size();
×
2030

NEW
2031
  return 0;
×
2032
}
2033

2034
// Plotter pre-allocates array size based on what is returned with
2035
// overlap_count; populates an array of size 3*count
NEW
2036
extern "C" int openmc_slice_data_overlap_info(
×
2037
  size_t count, int32_t* overlap_info)
2038
{
NEW
2039
  for (size_t i = 0; i < count; ++i) {
×
NEW
2040
    overlap_info[i * 3] = model::overlap_keys[i].universe_id;
×
NEW
2041
    overlap_info[i * 3 + 1] = model::overlap_keys[i].cell1_id;
×
NEW
2042
    overlap_info[i * 3 + 2] = model::overlap_keys[i].cell2_id;
×
2043
  }
2044

NEW
2045
  return 0;
×
2046
}
2047

2048
extern "C" int openmc_get_plot_index(int32_t id, int32_t* index)
22✔
2049
{
2050
  auto it = model::plot_map.find(id);
22!
2051
  if (it == model::plot_map.end()) {
22!
2052
    set_errmsg("No plot exists with ID=" + std::to_string(id) + ".");
×
2053
    return OPENMC_E_INVALID_ID;
×
2054
  }
2055

2056
  *index = it->second;
22✔
2057
  return 0;
22✔
2058
}
2059

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

2067
  *id = model::plots[index]->id();
55✔
2068
  return 0;
55✔
2069
}
2070

2071
extern "C" int openmc_plot_set_id(int32_t index, int32_t id)
×
2072
{
2073
  if (index < 0 || index >= model::plots.size()) {
×
2074
    set_errmsg("Index in plots array is out of bounds.");
×
2075
    return OPENMC_E_OUT_OF_BOUNDS;
×
2076
  }
2077

2078
  if (id < 0 && id != C_NONE) {
×
2079
    set_errmsg("Invalid plot ID.");
×
2080
    return OPENMC_E_INVALID_ARGUMENT;
×
2081
  }
2082

2083
  auto* plot = model::plots[index].get();
×
2084
  int32_t old_id = plot->id();
×
2085
  if (id == old_id)
×
2086
    return 0;
2087

2088
  model::plot_map.erase(old_id);
×
2089
  try {
×
2090
    plot->set_id(id);
×
2091
  } catch (const std::runtime_error& e) {
×
2092
    model::plot_map[old_id] = index;
×
2093
    set_errmsg(e.what());
×
2094
    return OPENMC_E_INVALID_ID;
×
2095
  }
×
2096
  model::plot_map[plot->id()] = index;
×
2097
  return 0;
×
2098
}
2099

2100
extern "C" size_t openmc_plots_size()
22✔
2101
{
2102
  return model::plots.size();
22✔
2103
}
2104

2105
int map_phong_domain_id(
55✔
2106
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2107
{
2108
  if (!plot || !index_out) {
55!
2109
    set_errmsg("Invalid plot pointer passed to map_phong_domain_id");
×
2110
    return OPENMC_E_INVALID_ARGUMENT;
×
2111
  }
2112

2113
  if (plot->color_by_ == PlottableInterface::PlotColorBy::mats) {
55!
2114
    auto it = model::material_map.find(id);
55!
2115
    if (it == model::material_map.end()) {
55!
2116
      set_errmsg("Invalid material ID for SolidRayTracePlot");
×
2117
      return OPENMC_E_INVALID_ID;
×
2118
    }
2119
    *index_out = it->second;
55✔
2120
    return 0;
55✔
2121
  }
2122

2123
  if (plot->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2124
    auto it = model::cell_map.find(id);
×
2125
    if (it == model::cell_map.end()) {
×
2126
      set_errmsg("Invalid cell ID for SolidRayTracePlot");
×
2127
      return OPENMC_E_INVALID_ID;
×
2128
    }
2129
    *index_out = it->second;
×
2130
    return 0;
×
2131
  }
2132

2133
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2134
  return OPENMC_E_INVALID_TYPE;
×
2135
}
2136

2137
int get_solidraytrace_plot_by_index(int32_t index, SolidRayTracePlot** plot)
308✔
2138
{
2139
  if (!plot) {
308!
2140
    set_errmsg("Null output pointer passed to get_solidraytrace_plot_by_index");
×
2141
    return OPENMC_E_INVALID_ARGUMENT;
×
2142
  }
2143

2144
  if (index < 0 || index >= model::plots.size()) {
308!
2145
    set_errmsg("Index in plots array is out of bounds.");
×
2146
    return OPENMC_E_OUT_OF_BOUNDS;
×
2147
  }
2148

2149
  auto* plottable = model::plots[index].get();
308!
2150
  auto* solid_plot = dynamic_cast<SolidRayTracePlot*>(plottable);
308!
2151
  if (!solid_plot) {
308!
2152
    set_errmsg("Plot at index=" + std::to_string(index) +
×
2153
               " is not a solid raytrace plot.");
2154
    return OPENMC_E_INVALID_TYPE;
×
2155
  }
2156

2157
  *plot = solid_plot;
308✔
2158
  return 0;
308✔
2159
}
2160

2161
extern "C" int openmc_solidraytrace_plot_create(int32_t* index)
11✔
2162
{
2163
  if (!index) {
11!
2164
    set_errmsg(
×
2165
      "Null output pointer passed to openmc_solidraytrace_plot_create");
2166
    return OPENMC_E_INVALID_ARGUMENT;
×
2167
  }
2168

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

2187
  return 0;
11✔
2188
}
2189

2190
extern "C" int openmc_solidraytrace_plot_get_pixels(
33✔
2191
  int32_t index, int32_t* width, int32_t* height)
2192
{
2193
  if (!width || !height) {
33!
2194
    set_errmsg(
×
2195
      "Invalid arguments passed to openmc_solidraytrace_plot_get_pixels");
2196
    return OPENMC_E_INVALID_ARGUMENT;
×
2197
  }
2198

2199
  SolidRayTracePlot* plt = nullptr;
33✔
2200
  int err = get_solidraytrace_plot_by_index(index, &plt);
33✔
2201
  if (err)
33!
2202
    return err;
2203

2204
  *width = plt->pixels()[0];
33✔
2205
  *height = plt->pixels()[1];
33✔
2206
  return 0;
33✔
2207
}
2208

2209
extern "C" int openmc_solidraytrace_plot_set_pixels(
11✔
2210
  int32_t index, int32_t width, int32_t height)
2211
{
2212
  if (width <= 0 || height <= 0) {
11!
2213
    set_errmsg(
×
2214
      "Invalid arguments passed to openmc_solidraytrace_plot_set_pixels");
2215
    return OPENMC_E_INVALID_ARGUMENT;
×
2216
  }
2217

2218
  SolidRayTracePlot* plt = nullptr;
11✔
2219
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2220
  if (err)
11!
2221
    return err;
2222

2223
  plt->pixels()[0] = width;
11✔
2224
  plt->pixels()[1] = height;
11✔
2225
  return 0;
11✔
2226
}
2227

2228
extern "C" int openmc_solidraytrace_plot_get_color_by(
11✔
2229
  int32_t index, int32_t* color_by)
2230
{
2231
  if (!color_by) {
11!
2232
    set_errmsg(
×
2233
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color_by");
2234
    return OPENMC_E_INVALID_ARGUMENT;
×
2235
  }
2236

2237
  SolidRayTracePlot* plt = nullptr;
11✔
2238
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2239
  if (err)
11!
2240
    return err;
2241

2242
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
11!
2243
    *color_by = 0;
11✔
2244
  } else if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2245
    *color_by = 1;
×
2246
  } else {
2247
    set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2248
    return OPENMC_E_INVALID_TYPE;
×
2249
  }
2250

2251
  return 0;
2252
}
2253

2254
extern "C" int openmc_solidraytrace_plot_set_color_by(
11✔
2255
  int32_t index, int32_t color_by)
2256
{
2257
  SolidRayTracePlot* plt = nullptr;
11✔
2258
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2259
  if (err)
11!
2260
    return err;
2261

2262
  if (color_by == 0) {
11!
2263
    plt->color_by_ = PlottableInterface::PlotColorBy::mats;
11✔
2264
  } else if (color_by == 1) {
×
2265
    plt->color_by_ = PlottableInterface::PlotColorBy::cells;
×
2266
  } else {
2267
    set_errmsg("Invalid color_by value for SolidRayTracePlot");
×
2268
    return OPENMC_E_INVALID_ARGUMENT;
×
2269
  }
2270

2271
  return 0;
2272
}
2273

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

2281
  plt->set_default_colors();
11✔
2282
  return 0;
2283
}
2284

2285
extern "C" int openmc_solidraytrace_plot_set_all_opaque(int32_t index)
×
2286
{
2287
  SolidRayTracePlot* plt = nullptr;
×
2288
  int err = get_solidraytrace_plot_by_index(index, &plt);
×
2289
  if (err)
×
2290
    return err;
2291

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

2300
  if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2301
    for (int32_t i = 0; i < model::cells.size(); ++i) {
×
2302
      plt->opaque_ids().insert(i);
×
2303
    }
2304
    return 0;
×
2305
  }
2306

2307
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2308
  return OPENMC_E_INVALID_TYPE;
×
2309
}
2310

2311
extern "C" int openmc_solidraytrace_plot_set_opaque(
22✔
2312
  int32_t index, int32_t id, bool visible)
2313
{
2314
  SolidRayTracePlot* plt = nullptr;
22✔
2315
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2316
  if (err)
22!
2317
    return err;
2318

2319
  int32_t domain_index = -1;
22✔
2320
  err = map_phong_domain_id(plt, id, &domain_index);
22✔
2321
  if (err)
22!
2322
    return err;
2323

2324
  if (visible) {
22✔
2325
    plt->opaque_ids().insert(domain_index);
11✔
2326
  } else {
2327
    plt->opaque_ids().erase(domain_index);
11✔
2328
  }
2329

2330
  return 0;
2331
}
2332

2333
extern "C" int openmc_solidraytrace_plot_set_color(
22✔
2334
  int32_t index, int32_t id, uint8_t r, uint8_t g, uint8_t b)
2335
{
2336
  SolidRayTracePlot* plt = nullptr;
22✔
2337
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2338
  if (err)
22!
2339
    return err;
2340

2341
  int32_t domain_index = -1;
22✔
2342
  err = map_phong_domain_id(plt, id, &domain_index);
22✔
2343
  if (err)
22!
2344
    return err;
2345

2346
  if (domain_index < 0 ||
22!
2347
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
22!
2348
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2349
    return OPENMC_E_OUT_OF_BOUNDS;
×
2350
  }
2351

2352
  plt->colors_[domain_index] = RGBColor(r, g, b);
22✔
2353
  return 0;
22✔
2354
}
2355

2356
extern "C" int openmc_solidraytrace_plot_get_camera_position(
11✔
2357
  int32_t index, double* x, double* y, double* z)
2358
{
2359
  if (!x || !y || !z) {
11!
2360
    set_errmsg("Invalid arguments passed to "
×
2361
               "openmc_solidraytrace_plot_get_camera_position");
2362
    return OPENMC_E_INVALID_ARGUMENT;
×
2363
  }
2364

2365
  SolidRayTracePlot* plt = nullptr;
11✔
2366
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2367
  if (err)
11!
2368
    return err;
2369

2370
  const auto& camera_position = plt->camera_position();
11✔
2371
  *x = camera_position.x;
11✔
2372
  *y = camera_position.y;
11✔
2373
  *z = camera_position.z;
11✔
2374
  return 0;
11✔
2375
}
2376

2377
extern "C" int openmc_solidraytrace_plot_set_camera_position(
11✔
2378
  int32_t index, double x, double y, double z)
2379
{
2380
  SolidRayTracePlot* plt = nullptr;
11✔
2381
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2382
  if (err)
11!
2383
    return err;
2384

2385
  plt->camera_position() = {x, y, z};
11✔
2386
  return 0;
11✔
2387
}
2388

2389
extern "C" int openmc_solidraytrace_plot_get_look_at(
11✔
2390
  int32_t index, double* x, double* y, double* z)
2391
{
2392
  if (!x || !y || !z) {
11!
2393
    set_errmsg(
×
2394
      "Invalid arguments passed to openmc_solidraytrace_plot_get_look_at");
2395
    return OPENMC_E_INVALID_ARGUMENT;
×
2396
  }
2397

2398
  SolidRayTracePlot* plt = nullptr;
11✔
2399
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2400
  if (err)
11!
2401
    return err;
2402

2403
  const auto& look_at = plt->look_at();
11✔
2404
  *x = look_at.x;
11✔
2405
  *y = look_at.y;
11✔
2406
  *z = look_at.z;
11✔
2407
  return 0;
11✔
2408
}
2409

2410
extern "C" int openmc_solidraytrace_plot_set_look_at(
11✔
2411
  int32_t index, double x, double y, double z)
2412
{
2413
  SolidRayTracePlot* plt = nullptr;
11✔
2414
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2415
  if (err)
11!
2416
    return err;
2417

2418
  plt->look_at() = {x, y, z};
11✔
2419
  return 0;
11✔
2420
}
2421

2422
extern "C" int openmc_solidraytrace_plot_get_up(
11✔
2423
  int32_t index, double* x, double* y, double* z)
2424
{
2425
  if (!x || !y || !z) {
11!
2426
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_up");
×
2427
    return OPENMC_E_INVALID_ARGUMENT;
×
2428
  }
2429

2430
  SolidRayTracePlot* plt = nullptr;
11✔
2431
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2432
  if (err)
11!
2433
    return err;
2434

2435
  const auto& up = plt->up();
11✔
2436
  *x = up.x;
11✔
2437
  *y = up.y;
11✔
2438
  *z = up.z;
11✔
2439
  return 0;
11✔
2440
}
2441

2442
extern "C" int openmc_solidraytrace_plot_set_up(
11✔
2443
  int32_t index, double x, double y, double z)
2444
{
2445
  SolidRayTracePlot* plt = nullptr;
11✔
2446
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2447
  if (err)
11!
2448
    return err;
2449

2450
  plt->up() = {x, y, z};
11✔
2451
  return 0;
11✔
2452
}
2453

2454
extern "C" int openmc_solidraytrace_plot_get_light_position(
11✔
2455
  int32_t index, double* x, double* y, double* z)
2456
{
2457
  if (!x || !y || !z) {
11!
2458
    set_errmsg("Invalid arguments passed to "
×
2459
               "openmc_solidraytrace_plot_get_light_position");
2460
    return OPENMC_E_INVALID_ARGUMENT;
×
2461
  }
2462

2463
  SolidRayTracePlot* plt = nullptr;
11✔
2464
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2465
  if (err)
11!
2466
    return err;
2467

2468
  const auto& light_position = plt->light_location();
11✔
2469
  *x = light_position.x;
11✔
2470
  *y = light_position.y;
11✔
2471
  *z = light_position.z;
11✔
2472
  return 0;
11✔
2473
}
2474

2475
extern "C" int openmc_solidraytrace_plot_set_light_position(
11✔
2476
  int32_t index, double x, double y, double z)
2477
{
2478
  SolidRayTracePlot* plt = nullptr;
11✔
2479
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2480
  if (err)
11!
2481
    return err;
2482

2483
  plt->light_location() = {x, y, z};
11✔
2484
  return 0;
11✔
2485
}
2486

2487
extern "C" int openmc_solidraytrace_plot_get_fov(int32_t index, double* fov)
11✔
2488
{
2489
  if (!fov) {
11!
2490
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_fov");
×
2491
    return OPENMC_E_INVALID_ARGUMENT;
×
2492
  }
2493

2494
  SolidRayTracePlot* plt = nullptr;
11✔
2495
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2496
  if (err)
11!
2497
    return err;
2498

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

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

2510
  plt->horizontal_field_of_view() = fov;
11✔
2511
  return 0;
11✔
2512
}
2513

2514
extern "C" int openmc_solidraytrace_plot_update_view(int32_t index)
22✔
2515
{
2516
  SolidRayTracePlot* plt = nullptr;
22✔
2517
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2518
  if (err)
22!
2519
    return err;
2520

2521
  plt->update_view();
22✔
2522
  return 0;
2523
}
2524

2525
extern "C" int openmc_solidraytrace_plot_create_image(
22✔
2526
  int32_t index, uint8_t* data_out, int32_t width, int32_t height)
2527
{
2528
  if (!data_out || width <= 0 || height <= 0) {
22!
2529
    set_errmsg(
×
2530
      "Invalid arguments passed to openmc_solidraytrace_plot_create_image");
2531
    return OPENMC_E_INVALID_ARGUMENT;
×
2532
  }
2533

2534
  SolidRayTracePlot* plt = nullptr;
22✔
2535
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2536
  if (err)
22!
2537
    return err;
2538

2539
  if (plt->pixels()[0] != width || plt->pixels()[1] != height) {
22!
2540
    set_errmsg(
×
2541
      "Requested image size does not match SolidRayTracePlot pixel settings");
2542
    return OPENMC_E_INVALID_SIZE;
×
2543
  }
2544

2545
  ImageData data = plt->create_image();
22✔
2546
  if (static_cast<int32_t>(data.shape()[0]) != width ||
22!
2547
      static_cast<int32_t>(data.shape()[1]) != height) {
22!
2548
    set_errmsg("Unexpected image size from SolidRayTracePlot create_image");
×
2549
    return OPENMC_E_INVALID_SIZE;
×
2550
  }
2551

2552
  for (int32_t y = 0; y < height; ++y) {
154✔
2553
    for (int32_t x = 0; x < width; ++x) {
1,188✔
2554
      const auto& color = data(x, y);
1,056✔
2555
      size_t idx = (static_cast<size_t>(y) * width + x) * 3;
1,056✔
2556
      data_out[idx + 0] = color.red;
1,056✔
2557
      data_out[idx + 1] = color.green;
1,056✔
2558
      data_out[idx + 2] = color.blue;
1,056✔
2559
    }
2560
  }
2561

2562
  return 0;
2563
}
22✔
2564

2565
extern "C" int openmc_solidraytrace_plot_get_color(
11✔
2566
  int32_t index, int32_t id, uint8_t* r, uint8_t* g, uint8_t* b)
2567
{
2568
  if (!r || !g || !b) {
11!
2569
    set_errmsg(
×
2570
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color");
2571
    return OPENMC_E_INVALID_ARGUMENT;
×
2572
  }
2573

2574
  SolidRayTracePlot* plt = nullptr;
11✔
2575
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2576
  if (err)
11!
2577
    return err;
2578

2579
  int32_t domain_index = -1;
11✔
2580
  err = map_phong_domain_id(plt, id, &domain_index);
11✔
2581
  if (err)
11!
2582
    return err;
2583

2584
  if (domain_index < 0 ||
11!
2585
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
11!
2586
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2587
    return OPENMC_E_OUT_OF_BOUNDS;
×
2588
  }
2589

2590
  const auto& color = plt->colors_[domain_index];
11✔
2591
  *r = color.red;
11✔
2592
  *g = color.green;
11✔
2593
  *b = color.blue;
11✔
2594
  return 0;
11✔
2595
}
2596

2597
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
11✔
2598
  int32_t index, double* diffuse_fraction)
2599
{
2600
  if (!diffuse_fraction) {
11!
2601
    set_errmsg("Invalid arguments passed to "
×
2602
               "openmc_solidraytrace_plot_get_diffuse_fraction");
2603
    return OPENMC_E_INVALID_ARGUMENT;
×
2604
  }
2605

2606
  SolidRayTracePlot* plt = nullptr;
11✔
2607
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2608
  if (err)
11!
2609
    return err;
2610

2611
  *diffuse_fraction = plt->diffuse_fraction();
11✔
2612
  return 0;
11✔
2613
}
2614

2615
extern "C" int openmc_solidraytrace_plot_set_diffuse_fraction(
11✔
2616
  int32_t index, double diffuse_fraction)
2617
{
2618
  SolidRayTracePlot* plt = nullptr;
11✔
2619
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2620
  if (err)
11!
2621
    return err;
2622

2623
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
11!
2624
    set_errmsg("Diffuse fraction must be between 0 and 1");
×
2625
    return OPENMC_E_INVALID_ARGUMENT;
×
2626
  }
2627

2628
  plt->diffuse_fraction() = diffuse_fraction;
11✔
2629
  return 0;
11✔
2630
}
2631

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