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

openmc-dev / openmc / 22500302709

27 Feb 2026 07:16PM UTC coverage: 81.512% (-0.3%) from 81.826%
22500302709

Pull #3830

github

web-flow
Merge 25fbb4266 into b3788f11e
Pull Request #3830: Parallelize sampling external sources and threadsafe rejection counters

17488 of 25193 branches covered (69.42%)

Branch coverage included in aggregate %.

59 of 66 new or added lines in 6 files covered. (89.39%)

841 existing lines in 44 files now uncovered.

57726 of 67081 relevant lines covered (86.05%)

44920080.48 hits per line

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

70.77
/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

37
namespace openmc {
38

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

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

47
IdData::IdData(size_t h_res, size_t v_res) : data_({v_res, h_res, 3}, NOT_FOUND)
5,140✔
48
{}
5,140✔
49

50
void IdData::set_value(size_t y, size_t x, const GeometryState& p, int level)
38,716,247✔
51
{
52
  // set cell data
53
  if (p.n_coord() <= level) {
38,716,247!
54
    data_(y, x, 0) = NOT_FOUND;
×
55
    data_(y, x, 1) = NOT_FOUND;
×
56
  } else {
57
    data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
38,716,247!
58
    data_(y, x, 1) = level == p.n_coord() - 1
38,716,247✔
59
                       ? p.cell_instance()
38,716,247!
60
                       : cell_instance_at_level(p, level);
×
61
  }
62

63
  // set material data
64
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
38,716,247✔
65
  if (p.material() == MATERIAL_VOID) {
38,716,247✔
66
    data_(y, x, 2) = MATERIAL_VOID;
29,804,276✔
67
    return;
29,804,276✔
68
  } else if (c->type_ == Fill::MATERIAL) {
8,911,971!
69
    Material* m = model::materials.at(p.material()).get();
8,911,971✔
70
    data_(y, x, 2) = m->id_;
8,911,971✔
71
  }
72
}
73

74
void IdData::set_overlap(size_t y, size_t x)
374,308✔
75
{
76
  for (size_t k = 0; k < data_.shape(2); ++k)
2,994,464!
77
    data_(y, x, k) = OVERLAP;
1,122,924✔
78
}
374,308✔
79

80
PropertyData::PropertyData(size_t h_res, size_t v_res)
11✔
81
  : data_({v_res, h_res, 2}, NOT_FOUND)
11✔
82
{}
11✔
83

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

95
void PropertyData::set_overlap(size_t y, size_t x)
×
96
{
97
  data_(y, x) = OVERLAP;
×
98
}
×
99

100
//==============================================================================
101
// Global variables
102
//==============================================================================
103

104
namespace model {
105

106
std::unordered_map<int, int> plot_map;
107
vector<std::unique_ptr<PlottableInterface>> plots;
108
uint64_t plotter_seed = 1;
109

110
} // namespace model
111

112
//==============================================================================
113
// RUN_PLOT controls the logic for making one or many plots
114
//==============================================================================
115

116
extern "C" int openmc_plot_geometry()
121✔
117
{
118

119
  for (auto& pl : model::plots) {
407✔
120
    write_message(5, "Processing plot {}: {}...", pl->id(), pl->path_plot());
286✔
121
    pl->create_output();
286✔
122
  }
123

124
  return 0;
121✔
125
}
126

127
void PlottableInterface::write_image(const ImageData& data) const
231✔
128
{
129
#ifdef USE_LIBPNG
130
  output_png(path_plot(), data);
462✔
131
#else
132
  output_ppm(path_plot(), data);
133
#endif
134
}
231✔
135

136
void Plot::create_output() const
198✔
137
{
138
  if (PlotType::slice == type_) {
198✔
139
    // create 2D image
140
    ImageData image = create_image();
143✔
141
    write_image(image);
143✔
142
  } else if (PlotType::voxel == type_) {
198!
143
    // create voxel file for 3D viewing
144
    create_voxel();
55✔
145
  }
146
}
198✔
147

148
void Plot::print_info() const
154✔
149
{
150
  // Plot type
151
  if (PlotType::slice == type_) {
154✔
152
    fmt::print("Plot Type: Slice\n");
121✔
153
  } else if (PlotType::voxel == type_) {
33!
154
    fmt::print("Plot Type: Voxel\n");
33✔
155
  }
156

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

160
  if (PlotType::slice == type_) {
154✔
161
    fmt::print("Width: {:4} {:4}\n", width_[0], width_[1]);
121✔
162
  } else if (PlotType::voxel == type_) {
33!
163
    fmt::print("Width: {:4} {:4} {:4}\n", width_[0], width_[1], width_[2]);
33✔
164
  }
165

166
  if (PlotColorBy::cells == color_by_) {
154✔
167
    fmt::print("Coloring: Cells\n");
88✔
168
  } else if (PlotColorBy::mats == color_by_) {
66!
169
    fmt::print("Coloring: Materials\n");
66✔
170
  }
171

172
  if (PlotType::slice == type_) {
154✔
173
    switch (basis_) {
121!
174
    case PlotBasis::xy:
77✔
175
      fmt::print("Basis: XY\n");
77✔
176
      break;
77✔
177
    case PlotBasis::xz:
22✔
178
      fmt::print("Basis: XZ\n");
22✔
179
      break;
22✔
180
    case PlotBasis::yz:
22✔
181
      fmt::print("Basis: YZ\n");
22✔
182
      break;
22✔
183
    }
184
    fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
121✔
185
  } else if (PlotType::voxel == type_) {
33!
186
    fmt::print("Voxels: {} {} {}\n", pixels()[0], pixels()[1], pixels()[2]);
33✔
187
  }
188
}
154✔
189

190
void read_plots_xml()
1,339✔
191
{
192
  // Check if plots.xml exists; this is only necessary when the plot runmode is
193
  // initiated. Otherwise, we want to read plots.xml because it may be called
194
  // later via the API. In that case, its ok for a plots.xml to not exist
195
  std::string filename = settings::path_input + "plots.xml";
1,339✔
196
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
1,339!
197
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
198
  }
199

200
  write_message("Reading plot XML file...", 5);
1,339✔
201

202
  // Parse plots.xml file
203
  pugi::xml_document doc;
1,339✔
204
  doc.load_file(filename.c_str());
1,339✔
205

206
  pugi::xml_node root = doc.document_element();
1,339✔
207

208
  read_plots_xml(root);
1,339✔
209
}
1,339✔
210

211
void read_plots_xml(pugi::xml_node root)
1,682✔
212
{
213
  for (auto node : root.children("plot")) {
2,509✔
214
    std::string plot_desc = "<auto>";
836✔
215
    if (check_for_node(node, "id")) {
836!
216
      plot_desc = get_node_value(node, "id", true);
836✔
217
    }
218

219
    if (check_for_node(node, "type")) {
836!
220
      std::string type_str = get_node_value(node, "type", true);
836✔
221
      if (type_str == "slice") {
836✔
222
        model::plots.emplace_back(
684✔
223
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,377✔
224
      } else if (type_str == "voxel") {
143✔
225
        model::plots.emplace_back(
55✔
226
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
110✔
227
      } else if (type_str == "wireframe_raytrace") {
88✔
228
        model::plots.emplace_back(
55✔
229
          std::make_unique<WireframeRayTracePlot>(node));
110✔
230
      } else if (type_str == "solid_raytrace") {
33!
231
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
33✔
232
      } else {
233
        fatal_error(fmt::format(
×
234
          "Unsupported plot type '{}' in plot {}", type_str, plot_desc));
235
      }
236
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
827✔
237
    } else {
827✔
238
      fatal_error(fmt::format("Must specify plot type in plot {}", plot_desc));
×
239
    }
240
  }
827✔
241
}
1,673✔
242

243
void free_memory_plot()
8,206✔
244
{
245
  model::plots.clear();
8,206✔
246
  model::plot_map.clear();
8,206✔
247
}
8,206✔
248

249
// creates an image based on user input from a plots.xml <plot>
250
// specification in the PNG/PPM format
251
ImageData Plot::create_image() const
143✔
252
{
253
  size_t width = pixels()[0];
143✔
254
  size_t height = pixels()[1];
143✔
255

256
  ImageData data({width, height}, not_found_);
143✔
257

258
  // generate ids for the plot
259
  auto ids = get_map<IdData>();
143✔
260

261
  // assign colors
262
  for (size_t y = 0; y < height; y++) {
30,063✔
263
    for (size_t x = 0; x < width; x++) {
7,622,120✔
264
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
7,592,200✔
265
      auto id = ids.data_(y, x, idx);
7,592,200✔
266
      // no setting needed if not found
267
      if (id == NOT_FOUND) {
7,592,200✔
268
        continue;
1,082,532✔
269
      }
270
      if (id == OVERLAP) {
6,537,916✔
271
        data(x, y) = overlap_color_;
28,248✔
272
        continue;
28,248✔
273
      }
274
      if (PlotColorBy::cells == color_by_) {
6,509,668✔
275
        data(x, y) = colors_[model::cell_map[id]];
3,011,668✔
276
      } else if (PlotColorBy::mats == color_by_) {
3,498,000!
277
        if (id == MATERIAL_VOID) {
3,498,000!
278
          data(x, y) = WHITE;
×
279
          continue;
×
280
        }
281
        data(x, y) = colors_[model::material_map[id]];
3,498,000✔
282
      } // color_by if-else
283
    }
284
  }
285

286
  // draw mesh lines if present
287
  if (index_meshlines_mesh_ >= 0) {
143✔
288
    draw_mesh_lines(data);
33✔
289
  }
290

291
  return data;
143✔
292
}
143✔
293

294
void PlottableInterface::set_id(pugi::xml_node plot_node)
836✔
295
{
296
  int id {C_NONE};
836✔
297
  if (check_for_node(plot_node, "id")) {
836!
298
    id = std::stoi(get_node_value(plot_node, "id"));
836✔
299
  }
300

301
  try {
836✔
302
    set_id(id);
836✔
303
  } catch (const std::runtime_error& e) {
×
304
    fatal_error(e.what());
×
305
  }
×
306
}
836✔
307

308
void PlottableInterface::set_id(int id)
847✔
309
{
310
  if (id < 0 && id != C_NONE) {
847!
311
    throw std::runtime_error {fmt::format("Invalid plot ID: {}", id)};
×
312
  }
313

314
  if (id == C_NONE) {
847✔
315
    id = 1;
11✔
316
    for (const auto& p : model::plots) {
22✔
317
      id = std::max(id, p->id() + 1);
22!
318
    }
319
  }
320

321
  if (id_ == id)
847!
322
    return;
323

324
  // Check to make sure this ID doesn't already exist
325
  if (model::plot_map.find(id) != model::plot_map.end()) {
847!
326
    throw std::runtime_error {
×
327
      fmt::format("Two or more plots use the same unique ID: {}", id)};
×
328
  }
329

330
  id_ = id;
847✔
331
}
332

333
// Checks if png or ppm is already present
334
bool file_extension_present(
827✔
335
  const std::string& filename, const std::string& extension)
336
{
337
  std::string file_extension_if_present =
827✔
338
    filename.substr(filename.find_last_of(".") + 1);
827✔
339
  if (file_extension_if_present == extension)
827✔
340
    return true;
55✔
341
  return false;
342
}
827✔
343

344
void Plot::set_output_path(pugi::xml_node plot_node)
748✔
345
{
346
  // Set output file path
347
  std::string filename;
748✔
348

349
  if (check_for_node(plot_node, "filename")) {
748✔
350
    filename = get_node_value(plot_node, "filename");
242✔
351
  } else {
352
    filename = fmt::format("plot_{}", id());
506✔
353
  }
354
  const std::string dir_if_present =
748✔
355
    filename.substr(0, filename.find_last_of("/") + 1);
748✔
356
  if (dir_if_present.size() > 0 && !dir_exists(dir_if_present)) {
748✔
357
    fatal_error(fmt::format("Directory '{}' does not exist!", dir_if_present));
9✔
358
  }
359
  // add appropriate file extension to name
360
  switch (type_) {
739!
361
  case PlotType::slice:
684✔
362
#ifdef USE_LIBPNG
363
    if (!file_extension_present(filename, "png"))
684!
364
      filename.append(".png");
684✔
365
#else
366
    if (!file_extension_present(filename, "ppm"))
367
      filename.append(".ppm");
368
#endif
369
    break;
370
  case PlotType::voxel:
55✔
371
    if (!file_extension_present(filename, "h5"))
55!
372
      filename.append(".h5");
55✔
373
    break;
374
  }
375

376
  path_plot_ = filename;
739✔
377

378
  // Copy plot pixel size
379
  vector<int> pxls = get_node_array<int>(plot_node, "pixels");
1,478✔
380
  if (PlotType::slice == type_) {
739✔
381
    if (pxls.size() == 2) {
684!
382
      pixels()[0] = pxls[0];
684✔
383
      pixels()[1] = pxls[1];
684✔
384
    } else {
385
      fatal_error(
×
386
        fmt::format("<pixels> must be length 2 in slice plot {}", id()));
×
387
    }
388
  } else if (PlotType::voxel == type_) {
55!
389
    if (pxls.size() == 3) {
55!
390
      pixels()[0] = pxls[0];
55✔
391
      pixels()[1] = pxls[1];
55✔
392
      pixels()[2] = pxls[2];
55✔
393
    } else {
394
      fatal_error(
×
395
        fmt::format("<pixels> must be length 3 in voxel plot {}", id()));
×
396
    }
397
  }
398
}
739✔
399

400
void PlottableInterface::set_bg_color(pugi::xml_node plot_node)
836✔
401
{
402
  // Copy plot background color
403
  if (check_for_node(plot_node, "background")) {
836✔
404
    vector<int> bg_rgb = get_node_array<int>(plot_node, "background");
44✔
405
    if (bg_rgb.size() == 3) {
44!
406
      not_found_ = bg_rgb;
44✔
407
    } else {
408
      fatal_error(fmt::format("Bad background RGB in plot {}", id()));
×
409
    }
410
  }
44✔
411
}
836✔
412

413
void Plot::set_basis(pugi::xml_node plot_node)
739✔
414
{
415
  // Copy plot basis
416
  if (PlotType::slice == type_) {
739✔
417
    std::string pl_basis = "xy";
684✔
418
    if (check_for_node(plot_node, "basis")) {
684!
419
      pl_basis = get_node_value(plot_node, "basis", true);
684✔
420
    }
421
    if ("xy" == pl_basis) {
684✔
422
      basis_ = PlotBasis::xy;
610✔
423
    } else if ("xz" == pl_basis) {
74✔
424
      basis_ = PlotBasis::xz;
22✔
425
    } else if ("yz" == pl_basis) {
52!
426
      basis_ = PlotBasis::yz;
52✔
427
    } else {
428
      fatal_error(
×
429
        fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id()));
×
430
    }
431
  }
684✔
432
}
739✔
433

434
void Plot::set_origin(pugi::xml_node plot_node)
739✔
435
{
436
  // Copy plotting origin
437
  auto pl_origin = get_node_array<double>(plot_node, "origin");
739✔
438
  if (pl_origin.size() == 3) {
739!
439
    origin_ = pl_origin;
739✔
440
  } else {
441
    fatal_error(fmt::format("Origin must be length 3 in plot {}", id()));
×
442
  }
443
}
739✔
444

445
void Plot::set_width(pugi::xml_node plot_node)
739✔
446
{
447
  // Copy plotting width
448
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
739✔
449
  if (PlotType::slice == type_) {
739✔
450
    if (pl_width.size() == 2) {
684!
451
      width_.x = pl_width[0];
684✔
452
      width_.y = pl_width[1];
684✔
453
    } else {
454
      fatal_error(
×
455
        fmt::format("<width> must be length 2 in slice plot {}", id()));
×
456
    }
457
  } else if (PlotType::voxel == type_) {
55!
458
    if (pl_width.size() == 3) {
55!
459
      pl_width = get_node_array<double>(plot_node, "width");
110✔
460
      width_ = pl_width;
55✔
461
    } else {
462
      fatal_error(
×
463
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
464
    }
465
  }
466
}
739✔
467

468
void PlottableInterface::set_universe(pugi::xml_node plot_node)
836✔
469
{
470
  // Copy plot universe level
471
  if (check_for_node(plot_node, "level")) {
836!
472
    level_ = std::stoi(get_node_value(plot_node, "level"));
×
473
    if (level_ < 0) {
×
474
      fatal_error(fmt::format("Bad universe level in plot {}", id()));
×
475
    }
476
  } else {
477
    level_ = PLOT_LEVEL_LOWEST;
836✔
478
  }
479
}
836✔
480

481
void PlottableInterface::set_color_by(pugi::xml_node plot_node)
836✔
482
{
483
  // Copy plot color type
484
  std::string pl_color_by = "cell";
836✔
485
  if (check_for_node(plot_node, "color_by")) {
836✔
486
    pl_color_by = get_node_value(plot_node, "color_by", true);
803✔
487
  }
488
  if ("cell" == pl_color_by) {
836✔
489
    color_by_ = PlotColorBy::cells;
287✔
490
  } else if ("material" == pl_color_by) {
549!
491
    color_by_ = PlotColorBy::mats;
549✔
492
  } else {
493
    fatal_error(fmt::format(
×
494
      "Unsupported plot color type '{}' in plot {}", pl_color_by, id()));
×
495
  }
496
}
836✔
497

498
void PlottableInterface::set_default_colors()
847✔
499
{
500
  // Copy plot color type and initialize all colors randomly
501
  if (PlotColorBy::cells == color_by_) {
847✔
502
    colors_.resize(model::cells.size());
287✔
503
  } else if (PlotColorBy::mats == color_by_) {
560!
504
    colors_.resize(model::materials.size());
560✔
505
  }
506

507
  for (auto& c : colors_) {
3,859✔
508
    c = random_color();
3,012✔
509
    // make sure we don't interfere with some default colors
510
    while (c == RED || c == WHITE) {
3,012!
511
      c = random_color();
×
512
    }
513
  }
514
}
847✔
515

516
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
836✔
517
{
518
  for (auto cn : plot_node.children("color")) {
1,023✔
519
    // Make sure 3 values are specified for RGB
520
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
187✔
521
    if (user_rgb.size() != 3) {
187!
522
      fatal_error(fmt::format("Bad RGB in plot {}", id()));
×
523
    }
524
    // Ensure that there is an id for this color specification
525
    int col_id;
187✔
526
    if (check_for_node(cn, "id")) {
187!
527
      col_id = std::stoi(get_node_value(cn, "id"));
374✔
528
    } else {
529
      fatal_error(fmt::format(
×
530
        "Must specify id for color specification in plot {}", id()));
×
531
    }
532
    // Add RGB
533
    if (PlotColorBy::cells == color_by_) {
187✔
534
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
88!
535
        col_id = model::cell_map[col_id];
88✔
536
        colors_[col_id] = user_rgb;
88✔
537
      } else {
538
        warning(fmt::format(
×
539
          "Could not find cell {} specified in plot {}", col_id, id()));
×
540
      }
541
    } else if (PlotColorBy::mats == color_by_) {
99!
542
      if (model::material_map.find(col_id) != model::material_map.end()) {
99!
543
        col_id = model::material_map[col_id];
99✔
544
        colors_[col_id] = user_rgb;
99✔
545
      } else {
546
        warning(fmt::format(
×
547
          "Could not find material {} specified in plot {}", col_id, id()));
×
548
      }
549
    }
550
  } // color node loop
187✔
551
}
836✔
552

553
void Plot::set_meshlines(pugi::xml_node plot_node)
739✔
554
{
555
  // Deal with meshlines
556
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
739✔
557

558
  if (!mesh_line_nodes.empty()) {
739✔
559
    if (PlotType::voxel == type_) {
33!
560
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
561
    }
562

563
    if (mesh_line_nodes.size() == 1) {
33!
564
      // Get first meshline node
565
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
33✔
566

567
      // Check mesh type
568
      std::string meshtype;
33✔
569
      if (check_for_node(meshlines_node, "meshtype")) {
33!
570
        meshtype = get_node_value(meshlines_node, "meshtype");
33✔
571
      } else {
572
        fatal_error(fmt::format(
×
573
          "Must specify a meshtype for meshlines specification in plot {}",
574
          id()));
×
575
      }
576

577
      // Ensure that there is a linewidth for this meshlines specification
578
      std::string meshline_width;
33✔
579
      if (check_for_node(meshlines_node, "linewidth")) {
33!
580
        meshline_width = get_node_value(meshlines_node, "linewidth");
33✔
581
        meshlines_width_ = std::stoi(meshline_width);
33✔
582
      } else {
583
        fatal_error(fmt::format(
×
584
          "Must specify a linewidth for meshlines specification in plot {}",
585
          id()));
×
586
      }
587

588
      // Check for color
589
      if (check_for_node(meshlines_node, "color")) {
33!
590
        // Check and make sure 3 values are specified for RGB
591
        vector<int> ml_rgb = get_node_array<int>(meshlines_node, "color");
×
592
        if (ml_rgb.size() != 3) {
×
593
          fatal_error(
×
594
            fmt::format("Bad RGB for meshlines color in plot {}", id()));
×
595
        }
596
        meshlines_color_ = ml_rgb;
×
597
      }
×
598

599
      // Set mesh based on type
600
      if ("ufs" == meshtype) {
33!
601
        if (!simulation::ufs_mesh) {
×
602
          fatal_error(
×
603
            fmt::format("No UFS mesh for meshlines on plot {}", id()));
×
604
        } else {
605
          for (int i = 0; i < model::meshes.size(); ++i) {
×
606
            if (const auto* m =
×
607
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
×
608
              if (m == simulation::ufs_mesh) {
×
609
                index_meshlines_mesh_ = i;
×
610
              }
611
            }
612
          }
613
          if (index_meshlines_mesh_ == -1)
×
614
            fatal_error("Could not find the UFS mesh for meshlines plot");
×
615
        }
616
      } else if ("entropy" == meshtype) {
33✔
617
        if (!simulation::entropy_mesh) {
22!
618
          fatal_error(
×
619
            fmt::format("No entropy mesh for meshlines on plot {}", id()));
×
620
        } else {
621
          for (int i = 0; i < model::meshes.size(); ++i) {
55✔
622
            if (const auto* m =
66✔
623
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
55!
624
              if (m == simulation::entropy_mesh) {
22!
625
                index_meshlines_mesh_ = i;
22✔
626
              }
627
            }
628
          }
629
          if (index_meshlines_mesh_ == -1)
22!
630
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
631
        }
632
      } else if ("tally" == meshtype) {
11!
633
        // Ensure that there is a mesh id if the type is tally
634
        int tally_mesh_id;
11✔
635
        if (check_for_node(meshlines_node, "id")) {
11!
636
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
22✔
637
        } else {
638
          std::stringstream err_msg;
×
639
          fatal_error(fmt::format("Must specify a mesh id for meshlines tally "
×
640
                                  "mesh specification in plot {}",
641
            id()));
×
642
        }
×
643
        // find the tally index
644
        int idx;
11✔
645
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
11✔
646
        if (err != 0) {
11!
647
          fatal_error(fmt::format("Could not find mesh {} specified in "
×
648
                                  "meshlines for plot {}",
649
            tally_mesh_id, id()));
×
650
        }
651
        index_meshlines_mesh_ = idx;
11✔
652
      } else {
653
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
654
      }
655
    } else {
33✔
656
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
657
    }
658
  }
659
}
739✔
660

661
void PlottableInterface::set_mask(pugi::xml_node plot_node)
836✔
662
{
663
  // Deal with masks
664
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
836✔
665

666
  if (!mask_nodes.empty()) {
836✔
667
    if (mask_nodes.size() == 1) {
33!
668
      // Get pointer to mask
669
      pugi::xml_node mask_node = mask_nodes[0].node();
33✔
670

671
      // Determine how many components there are and allocate
672
      vector<int> iarray = get_node_array<int>(mask_node, "components");
33✔
673
      if (iarray.size() == 0) {
33!
674
        fatal_error(
×
675
          fmt::format("Missing <components> in mask of plot {}", id()));
×
676
      }
677

678
      // First we need to change the user-specified identifiers to indices
679
      // in the cell and material arrays
680
      for (auto& col_id : iarray) {
99✔
681
        if (PlotColorBy::cells == color_by_) {
66!
682
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
683
            col_id = model::cell_map[col_id];
66✔
684
          } else {
685
            fatal_error(fmt::format("Could not find cell {} specified in the "
×
686
                                    "mask in plot {}",
687
              col_id, id()));
×
688
          }
689
        } else if (PlotColorBy::mats == color_by_) {
×
690
          if (model::material_map.find(col_id) != model::material_map.end()) {
×
691
            col_id = model::material_map[col_id];
×
692
          } else {
693
            fatal_error(fmt::format("Could not find material {} specified in "
×
694
                                    "the mask in plot {}",
695
              col_id, id()));
×
696
          }
697
        }
698
      }
699

700
      // Alter colors based on mask information
701
      for (int j = 0; j < colors_.size(); j++) {
132✔
702
        if (contains(iarray, j)) {
99✔
703
          if (check_for_node(mask_node, "background")) {
66!
704
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
66✔
705
            colors_[j] = bg_rgb;
66✔
706
          } else {
66✔
707
            colors_[j] = WHITE;
×
708
          }
709
        }
710
      }
711

712
    } else {
33✔
713
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
714
    }
715
  }
716
}
836✔
717

718
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
836✔
719
{
720
  color_overlaps_ = false;
836✔
721
  if (check_for_node(plot_node, "show_overlaps")) {
836✔
722
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
22✔
723
    // check for custom overlap color
724
    if (check_for_node(plot_node, "overlap_color")) {
22✔
725
      if (!color_overlaps_) {
11!
726
        warning(fmt::format(
×
727
          "Overlap color specified in plot {} but overlaps won't be shown.",
728
          id()));
×
729
      }
730
      vector<int> olap_clr = get_node_array<int>(plot_node, "overlap_color");
11✔
731
      if (olap_clr.size() == 3) {
11!
732
        overlap_color_ = olap_clr;
11✔
733
      } else {
734
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
735
      }
736
    }
11✔
737
  }
738

739
  // make sure we allocate the vector for counting overlap checks if
740
  // they're going to be plotted
741
  if (color_overlaps_ && settings::run_mode == RunMode::PLOTTING) {
836!
742
    settings::check_overlaps = true;
22✔
743
    model::overlap_check_count.resize(model::cells.size(), 0);
22✔
744
  }
745
}
836✔
746

747
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
836✔
748
{
749
  set_id(plot_node);
836✔
750
  set_bg_color(plot_node);
836✔
751
  set_universe(plot_node);
836✔
752
  set_color_by(plot_node);
836✔
753
  set_default_colors();
836✔
754
  set_user_colors(plot_node);
836✔
755
  set_mask(plot_node);
836✔
756
  set_overlap_color(plot_node);
836✔
757
}
836✔
758

759
Plot::Plot(pugi::xml_node plot_node, PlotType type)
748✔
760
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
748✔
761
{
762
  set_output_path(plot_node);
748✔
763
  set_basis(plot_node);
739✔
764
  set_origin(plot_node);
739✔
765
  set_width(plot_node);
739✔
766
  set_meshlines(plot_node);
739✔
767
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
739✔
768
  slice_color_overlaps_ = color_overlaps_;
739✔
769
}
739✔
770

771
//==============================================================================
772
// OUTPUT_PPM writes out a previously generated image to a PPM file
773
//==============================================================================
774

775
void output_ppm(const std::string& filename, const ImageData& data)
×
776
{
777
  // Open PPM file for writing
778
  std::string fname = filename;
×
779
  fname = strtrim(fname);
×
780
  std::ofstream of;
×
781

782
  of.open(fname);
×
783

784
  // Write header
785
  of << "P6\n";
×
786
  of << data.shape(0) << " " << data.shape(1) << "\n";
×
787
  of << "255\n";
×
788
  of.close();
×
789

790
  of.open(fname, std::ios::binary | std::ios::app);
×
791
  // Write color for each pixel
792
  for (int y = 0; y < data.shape(1); y++) {
×
793
    for (int x = 0; x < data.shape(0); x++) {
×
794
      RGBColor rgb = data(x, y);
×
795
      of << rgb.red << rgb.green << rgb.blue;
×
796
    }
797
  }
798
  of << "\n";
×
799
}
×
800

801
//==============================================================================
802
// OUTPUT_PNG writes out a previously generated image to a PNG file
803
//==============================================================================
804

805
#ifdef USE_LIBPNG
806
void output_png(const std::string& filename, const ImageData& data)
231✔
807
{
808
  // Open PNG file for writing
809
  std::string fname = filename;
231✔
810
  fname = strtrim(fname);
231✔
811
  auto fp = std::fopen(fname.c_str(), "wb");
231✔
812

813
  // Initialize write and info structures
814
  auto png_ptr =
231✔
815
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
231✔
816
  auto info_ptr = png_create_info_struct(png_ptr);
231✔
817

818
  // Setup exception handling
819
  if (setjmp(png_jmpbuf(png_ptr)))
231!
820
    fatal_error("Error during png creation");
×
821

822
  png_init_io(png_ptr, fp);
231✔
823

824
  // Write header (8 bit colour depth)
825
  int width = data.shape(0);
231!
826
  int height = data.shape(1);
231!
827
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB,
231✔
828
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
829
  png_write_info(png_ptr, info_ptr);
231✔
830

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

834
  // Write color for each pixel
835
  for (int y = 0; y < height; y++) {
47,751✔
836
    for (int x = 0; x < width; x++) {
11,159,720✔
837
      RGBColor rgb = data(x, y);
11,112,200✔
838
      row[3 * x] = rgb.red;
11,112,200✔
839
      row[3 * x + 1] = rgb.green;
11,112,200✔
840
      row[3 * x + 2] = rgb.blue;
11,112,200✔
841
    }
842
    png_write_row(png_ptr, row.data());
47,520✔
843
  }
844

845
  // End write
846
  png_write_end(png_ptr, nullptr);
231✔
847

848
  // Clean up data structures
849
  std::fclose(fp);
231✔
850
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
231✔
851
  png_destroy_write_struct(&png_ptr, &info_ptr);
231✔
852
}
231✔
853
#endif
854

855
//==============================================================================
856
// DRAW_MESH_LINES draws mesh line boundaries on an image
857
//==============================================================================
858

859
void Plot::draw_mesh_lines(ImageData& data) const
33✔
860
{
861
  RGBColor rgb;
33!
862
  rgb = meshlines_color_;
33✔
863

864
  int ax1, ax2;
33✔
865
  switch (basis_) {
33!
866
  case PlotBasis::xy:
867
    ax1 = 0;
868
    ax2 = 1;
869
    break;
870
  case PlotBasis::xz:
871
    ax1 = 0;
872
    ax2 = 2;
873
    break;
874
  case PlotBasis::yz:
875
    ax1 = 1;
876
    ax2 = 2;
877
    break;
878
  default:
×
879
    UNREACHABLE();
×
880
  }
881

882
  Position ll_plot {origin_};
33✔
883
  Position ur_plot {origin_};
33✔
884

885
  ll_plot[ax1] -= width_[0] / 2.;
33✔
886
  ll_plot[ax2] -= width_[1] / 2.;
33✔
887
  ur_plot[ax1] += width_[0] / 2.;
33✔
888
  ur_plot[ax2] += width_[1] / 2.;
33✔
889

890
  Position width = ur_plot - ll_plot;
33✔
891

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

896
  // Find the bounds along the second axis (accounting for low-D meshes).
897
  int ax2_min, ax2_max;
33✔
898
  if (axis_lines.second.size() > 0) {
33!
899
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
33✔
900
    ax2_min = (1.0 - frac) * pixels()[1];
33✔
901
    if (ax2_min < 0)
33✔
902
      ax2_min = 0;
903
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
33✔
904
    ax2_max = (1.0 - frac) * pixels()[1];
33!
905
    if (ax2_max > pixels()[1])
33!
906
      ax2_max = pixels()[1];
×
907
  } else {
908
    ax2_min = 0;
×
909
    ax2_max = pixels()[1];
×
910
  }
911

912
  // Iterate across the first axis and draw lines.
913
  for (auto ax1_val : axis_lines.first) {
187✔
914
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
154✔
915
    int ax1_ind = frac * pixels()[0];
154✔
916
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
24,948✔
917
      for (int plus = 0; plus <= meshlines_width_; plus++) {
49,588✔
918
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
24,794!
919
          data(ax1_ind + plus, ax2_ind) = rgb;
24,794✔
920
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
24,794!
921
          data(ax1_ind - plus, ax2_ind) = rgb;
24,794✔
922
      }
923
    }
924
  }
925

926
  // Find the bounds along the first axis.
927
  int ax1_min, ax1_max;
33✔
928
  if (axis_lines.first.size() > 0) {
33!
929
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
33✔
930
    ax1_min = frac * pixels()[0];
33✔
931
    if (ax1_min < 0)
33✔
932
      ax1_min = 0;
933
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
33✔
934
    ax1_max = frac * pixels()[0];
33!
935
    if (ax1_max > pixels()[0])
33!
936
      ax1_max = pixels()[0];
×
937
  } else {
938
    ax1_min = 0;
×
939
    ax1_max = pixels()[0];
×
940
  }
941

942
  // Iterate across the second axis and draw lines.
943
  for (auto ax2_val : axis_lines.second) {
209✔
944
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
176✔
945
    int ax2_ind = (1.0 - frac) * pixels()[1];
176✔
946
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
28,336✔
947
      for (int plus = 0; plus <= meshlines_width_; plus++) {
56,320✔
948
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
28,160!
949
          data(ax1_ind, ax2_ind + plus) = rgb;
28,160✔
950
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
28,160!
951
          data(ax1_ind, ax2_ind - plus) = rgb;
28,160✔
952
      }
953
    }
954
  }
955
}
33✔
956

957
/* outputs a binary file that can be input into silomesh for 3D geometry
958
 * visualization.  It works the same way as create_image by dragging a particle
959
 * across the geometry for the specified number of voxels. The first 3 int's in
960
 * the binary are the number of x, y, and z voxels.  The next 3 double's are
961
 * the widths of the voxels in the x, y, and z directions. The next 3 double's
962
 * are the x, y, and z coordinates of the lower left point. Finally the binary
963
 * is filled with entries of four int's each. Each 'row' in the binary contains
964
 * four int's: 3 for x,y,z position and 1 for cell or material id.  For 1
965
 * million voxels this produces a file of approximately 15MB.
966
 */
967
void Plot::create_voxel() const
55✔
968
{
969
  // compute voxel widths in each direction
970
  array<double, 3> vox;
55✔
971
  vox[0] = width_[0] / static_cast<double>(pixels()[0]);
55✔
972
  vox[1] = width_[1] / static_cast<double>(pixels()[1]);
55✔
973
  vox[2] = width_[2] / static_cast<double>(pixels()[2]);
55✔
974

975
  // initial particle position
976
  Position ll = origin_ - width_ / 2.;
55✔
977

978
  // Open binary plot file for writing
979
  std::ofstream of;
55✔
980
  std::string fname = std::string(path_plot_);
55✔
981
  fname = strtrim(fname);
55✔
982
  hid_t file_id = file_open(fname, 'w');
55✔
983

984
  // write header info
985
  write_attribute(file_id, "filetype", "voxel");
55✔
986
  write_attribute(file_id, "version", VERSION_VOXEL);
55✔
987
  write_attribute(file_id, "openmc_version", VERSION);
55✔
988

989
#ifdef GIT_SHA1
990
  write_attribute(file_id, "git_sha1", GIT_SHA1);
991
#endif
992

993
  // Write current date and time
994
  write_attribute(file_id, "date_and_time", time_stamp().c_str());
110✔
995
  array<int, 3> h5_pixels;
55✔
996
  std::copy(pixels().begin(), pixels().end(), h5_pixels.begin());
55✔
997
  write_attribute(file_id, "num_voxels", h5_pixels);
55✔
998
  write_attribute(file_id, "voxel_width", vox);
55✔
999
  write_attribute(file_id, "lower_left", ll);
55✔
1000

1001
  // Create dataset for voxel data -- note that the dimensions are reversed
1002
  // since we want the order in the file to be z, y, x
1003
  hsize_t dims[3];
55✔
1004
  dims[0] = pixels()[2];
55✔
1005
  dims[1] = pixels()[1];
55✔
1006
  dims[2] = pixels()[0];
55✔
1007
  hid_t dspace, dset, memspace;
55✔
1008
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
55✔
1009

1010
  SlicePlotBase pltbase;
55✔
1011
  pltbase.width_ = width_;
55✔
1012
  pltbase.origin_ = origin_;
55✔
1013
  pltbase.basis_ = PlotBasis::xy;
55✔
1014
  pltbase.pixels() = pixels();
55✔
1015
  pltbase.slice_color_overlaps_ = color_overlaps_;
55✔
1016

1017
  ProgressBar pb;
55✔
1018
  for (int z = 0; z < pixels()[2]; z++) {
4,785✔
1019
    // update z coordinate
1020
    pltbase.origin_.z = ll.z + z * vox[2];
4,730✔
1021

1022
    // generate ids using plotbase
1023
    IdData ids = pltbase.get_map<IdData>();
4,730✔
1024

1025
    // select only cell/material ID data and flip the y-axis
1026
    int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
4,730!
1027
    // Extract 2D slice at index idx from 3D data
1028
    size_t rows = ids.data_.shape(0);
4,730!
1029
    size_t cols = ids.data_.shape(1);
4,730!
1030
    tensor::Tensor<int32_t> data_slice({rows, cols});
4,730✔
1031
    for (size_t r = 0; r < rows; ++r)
912,230✔
1032
      for (size_t c = 0; c < cols; ++c)
179,382,500✔
1033
        data_slice(r, c) = ids.data_(r, c, idx);
178,475,000✔
1034
    tensor::Tensor<int32_t> data_flipped = data_slice.flip(0);
4,730✔
1035

1036
    // Write to HDF5 dataset
1037
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
4,730✔
1038

1039
    // update progress bar
1040
    pb.set_value(
4,730✔
1041
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
4,730✔
1042
  }
14,190✔
1043

1044
  voxel_finalize(dspace, dset, memspace);
55✔
1045
  file_close(file_id);
55✔
1046
}
55✔
1047

1048
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
55✔
1049
  hid_t* memspace)
1050
{
1051
  // Create dataspace/dataset for voxel data
1052
  *dspace = H5Screate_simple(3, dims, nullptr);
55✔
1053
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
55✔
1054
    H5P_DEFAULT, H5P_DEFAULT);
1055

1056
  // Create dataspace for a slice of the voxel
1057
  hsize_t dims_slice[2] {dims[1], dims[2]};
55✔
1058
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
55✔
1059

1060
  // Select hyperslab in dataspace
1061
  hsize_t start[3] {0, 0, 0};
55✔
1062
  hsize_t count[3] {1, dims[1], dims[2]};
55✔
1063
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
55✔
1064
}
55✔
1065

1066
void voxel_write_slice(
4,730✔
1067
  int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
1068
{
1069
  hssize_t offset[3] {x, 0, 0};
4,730✔
1070
  H5Soffset_simple(dspace, offset);
4,730✔
1071
  H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
4,730✔
1072
}
4,730✔
1073

1074
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
55✔
1075
{
1076
  H5Dclose(dset);
55✔
1077
  H5Sclose(dspace);
55✔
1078
  H5Sclose(memspace);
55✔
1079
}
55✔
1080

1081
RGBColor random_color(void)
3,012✔
1082
{
1083
  return {int(prn(&model::plotter_seed) * 255),
3,012✔
1084
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
3,012✔
1085
}
1086

1087
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
88✔
1088
{
1089
  set_look_at(node);
88✔
1090
  set_camera_position(node);
88✔
1091
  set_field_of_view(node);
88✔
1092
  set_pixels(node);
88✔
1093
  set_orthographic_width(node);
88✔
1094
  set_output_path(node);
88✔
1095

1096
  if (check_for_node(node, "orthographic_width") &&
99!
1097
      check_for_node(node, "field_of_view"))
11✔
1098
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1099
                "parameters.");
1100
}
88✔
1101

1102
void RayTracePlot::update_view()
110✔
1103
{
1104
  // Get centerline vector for camera-to-model. We create vectors around this
1105
  // that form a pixel array, and then trace rays along that.
1106
  auto up = up_ / up_.norm();
110✔
1107
  Direction looking_direction = look_at_ - camera_position_;
110✔
1108
  looking_direction /= looking_direction.norm();
110✔
1109
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
110!
1110
    fatal_error("Up vector cannot align with vector between camera position "
×
1111
                "and look_at!");
1112
  Direction cam_yaxis = looking_direction.cross(up);
110✔
1113
  cam_yaxis /= cam_yaxis.norm();
110✔
1114
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
110✔
1115
  cam_zaxis /= cam_zaxis.norm();
110✔
1116

1117
  // Cache the camera-to-model matrix
1118
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
110✔
1119
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
110✔
1120
    cam_yaxis.z, cam_zaxis.z};
110✔
1121
}
110✔
1122

1123
WireframeRayTracePlot::WireframeRayTracePlot(pugi::xml_node node)
55✔
1124
  : RayTracePlot(node)
55✔
1125
{
1126
  set_opacities(node);
55✔
1127
  set_wireframe_thickness(node);
55✔
1128
  set_wireframe_ids(node);
55✔
1129
  set_wireframe_color(node);
55✔
1130
  update_view();
55✔
1131
}
55✔
1132

1133
void WireframeRayTracePlot::set_wireframe_color(pugi::xml_node plot_node)
55✔
1134
{
1135
  // Copy plot wireframe color
1136
  if (check_for_node(plot_node, "wireframe_color")) {
55!
1137
    vector<int> w_rgb = get_node_array<int>(plot_node, "wireframe_color");
×
1138
    if (w_rgb.size() == 3) {
×
1139
      wireframe_color_ = w_rgb;
×
1140
    } else {
1141
      fatal_error(fmt::format("Bad wireframe RGB in plot {}", id()));
×
1142
    }
1143
  }
×
1144
}
55✔
1145

1146
void RayTracePlot::set_output_path(pugi::xml_node node)
88✔
1147
{
1148
  // Set output file path
1149
  std::string filename;
88✔
1150

1151
  if (check_for_node(node, "filename")) {
88✔
1152
    filename = get_node_value(node, "filename");
77✔
1153
  } else {
1154
    filename = fmt::format("plot_{}", id());
11✔
1155
  }
1156

1157
#ifdef USE_LIBPNG
1158
  if (!file_extension_present(filename, "png"))
88✔
1159
    filename.append(".png");
33✔
1160
#else
1161
  if (!file_extension_present(filename, "ppm"))
1162
    filename.append(".ppm");
1163
#endif
1164
  path_plot_ = filename;
176✔
1165
}
88✔
1166

1167
bool WireframeRayTracePlot::trackstack_equivalent(
3,041,159✔
1168
  const std::vector<TrackSegment>& track1,
1169
  const std::vector<TrackSegment>& track2) const
1170
{
1171
  if (wireframe_ids_.empty()) {
3,041,159✔
1172
    // Draw wireframe for all surfaces/cells/materials
1173
    if (track1.size() != track2.size())
2,545,070✔
1174
      return false;
1175
    for (int i = 0; i < track1.size(); ++i) {
6,707,954✔
1176
      if (track1[i].id != track2[i].id ||
4,236,771✔
1177
          track1[i].surface_index != track2[i].surface_index) {
4,236,639✔
1178
        return false;
1179
      }
1180
    }
1181
    return true;
1182
  } else {
1183
    // This runs in O(nm) where n is the intersection stack size
1184
    // and m is the number of IDs we are wireframing. A simpler
1185
    // algorithm can likely be found.
1186
    for (const int id : wireframe_ids_) {
986,194✔
1187
      int t1_i = 0;
496,089✔
1188
      int t2_i = 0;
496,089✔
1189

1190
      // Advance to first instance of the ID
1191
      while (t1_i < track1.size() && t2_i < track2.size()) {
562,430✔
1192
        while (t1_i < track1.size() && track1[t1_i].id != id)
392,832✔
1193
          t1_i++;
229,053✔
1194
        while (t2_i < track2.size() && track2[t2_i].id != id)
393,668✔
1195
          t2_i++;
229,889✔
1196

1197
        // This one is really important!
1198
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
163,779✔
1199
            (t1_i != track1.size() && t2_i == track2.size()))
162,096✔
1200
          return false;
3,718✔
1201
        if (t1_i == track1.size() && t2_i == track2.size())
160,061!
1202
          break;
1203
        // Check if surface different
1204
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
68,607✔
1205
          return false;
1206

1207
        // Pretty sure this should not be used:
1208
        // if (t2_i != track2.size() - 1 &&
1209
        //     t1_i != track1.size() - 1 &&
1210
        //     track1[t1_i+1].id != track2[t2_i+1].id) return false;
1211
        if (t2_i != 0 && t1_i != 0 &&
67,122✔
1212
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
53,944✔
1213
          return false;
1214

1215
        // Check if neighboring cells are different
1216
        // if (track1[t1_i ? t1_i - 1 : 0].id != track2[t2_i ? t2_i - 1 : 0].id)
1217
        // return false; if (track1[t1_i < track1.size() - 1 ? t1_i + 1 : t1_i
1218
        // ].id !=
1219
        //    track2[t2_i < track2.size() - 1 ? t2_i + 1 : t2_i].id) return
1220
        //    false;
1221
        t1_i++, t2_i++;
66,341✔
1222
      }
1223
    }
1224
    return true;
1225
  }
1226
}
1227

1228
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
3,521,056✔
1229
  int horiz, int vert) const
1230
{
1231
  // Compute field of view in radians
1232
  constexpr double DEGREE_TO_RADIAN = M_PI / 180.0;
3,521,056✔
1233
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
3,521,056✔
1234
  double p0 = static_cast<double>(pixels()[0]);
3,521,056✔
1235
  double p1 = static_cast<double>(pixels()[1]);
3,521,056✔
1236
  double vert_fov_radians = horiz_fov_radians * p1 / p0;
3,521,056✔
1237

1238
  // focal_plane_dist can be changed to alter the perspective distortion
1239
  // effect. This is in units of cm. This seems to look good most of the
1240
  // time. TODO let this variable be set through XML.
1241
  constexpr double focal_plane_dist = 10.0;
3,521,056✔
1242
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
3,521,056✔
1243
  const double dy = p1 / p0 * dx;
3,521,056✔
1244

1245
  std::pair<Position, Direction> result;
3,521,056✔
1246

1247
  // Generate the starting position/direction of the ray
1248
  if (orthographic_width_ == C_NONE) { // perspective projection
3,521,056✔
1249
    Direction camera_local_vec;
3,081,056✔
1250
    camera_local_vec.x = focal_plane_dist;
3,081,056✔
1251
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
3,081,056✔
1252
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
3,081,056✔
1253
    camera_local_vec /= camera_local_vec.norm();
3,081,056✔
1254

1255
    result.first = camera_position_;
3,081,056✔
1256
    result.second = camera_local_vec.rotate(camera_to_model_);
3,081,056✔
1257
  } else { // orthographic projection
1258

1259
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
440,000✔
1260
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
440,000✔
1261

1262
    result.first = camera_position_ +
440,000✔
1263
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
440,000✔
1264
                   camera_z_axis() * y_pix_coord * orthographic_width_;
440,000✔
1265
    result.second = camera_x_axis();
440,000✔
1266
  }
1267

1268
  return result;
3,521,056✔
1269
}
1270

1271
ImageData WireframeRayTracePlot::create_image() const
55✔
1272
{
1273
  size_t width = pixels()[0];
55✔
1274
  size_t height = pixels()[1];
55✔
1275
  ImageData data({width, height}, not_found_);
55✔
1276

1277
  // This array marks where the initial wireframe was drawn. We convolve it with
1278
  // a filter that gets adjusted with the wireframe thickness in order to
1279
  // thicken the lines.
1280
  tensor::Tensor<int> wireframe_initial(
55✔
1281
    {static_cast<size_t>(width), static_cast<size_t>(height)}, 0);
55✔
1282

1283
  /* Holds all of the track segments for the current rendered line of pixels.
1284
   * old_segments holds a copy of this_line_segments from the previous line.
1285
   * By holding both we can check if the cell/material intersection stack
1286
   * differs from the left or upper neighbor. This allows a robustly drawn
1287
   * wireframe. If only checking the left pixel (which requires substantially
1288
   * less memory), the wireframe tends to be spotty and be disconnected for
1289
   * surface edges oriented horizontally in the rendering.
1290
   *
1291
   * Note that a vector of vectors is required rather than a 2-tensor,
1292
   * since the stack size varies within each column.
1293
   */
1294
  const int n_threads = num_threads();
55✔
1295
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
55✔
1296
    n_threads);
55✔
1297
  for (int t = 0; t < n_threads; ++t) {
140✔
1298
    this_line_segments[t].resize(pixels()[0]);
85✔
1299
  }
1300

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

1304
#pragma omp parallel
30✔
1305
  {
25✔
1306
    const int n_threads = num_threads();
25✔
1307
    const int tid = thread_num();
25✔
1308

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

1312
      // Save bottom line of current work chunk to compare against later. This
1313
      // used to be inside the below if block, but it causes a spurious line to
1314
      // be drawn at the bottom of the image. Not sure why, but moving it here
1315
      // fixes things.
1316
      if (tid == n_threads - 1)
5,025✔
1317
        old_segments = this_line_segments[n_threads - 1];
5,025✔
1318

1319
      if (vert < pixels()[1]) {
5,025✔
1320

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

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

1326
          this_line_segments[tid][horiz].clear();
1,000,000✔
1327
          ProjectionRay ray(
1,000,000✔
1328
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
1,000,000✔
1329

1330
          ray.trace();
1,000,000✔
1331

1332
          // Now color the pixel based on what we have intersected...
1333
          // Loops backwards over intersections.
1334
          Position current_color(
1,000,000✔
1335
            not_found_.red, not_found_.green, not_found_.blue);
1,000,000✔
1336
          const auto& segments = this_line_segments[tid][horiz];
1,000,000✔
1337

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

1345
          for (int i = segments.size() - 2; i >= 0; --i) {
1,072,335✔
1346
            int colormap_idx = segments[i].id;
688,990✔
1347
            RGBColor seg_color = colors_[colormap_idx];
688,990✔
1348
            Position seg_color_vec(
688,990✔
1349
              seg_color.red, seg_color.green, seg_color.blue);
688,990✔
1350
            double mixing =
688,990✔
1351
              std::exp(-xs_[colormap_idx] *
1,377,980✔
1352
                       (segments[i + 1].length - segments[i].length));
688,990✔
1353
            current_color =
688,990✔
1354
              current_color * mixing + (1.0 - mixing) * seg_color_vec;
688,990✔
1355
          }
1356

1357
          // save result converting from double-precision color coordinates to
1358
          // byte-sized
1359
          RGBColor result;
383,345✔
1360
          result.red = static_cast<uint8_t>(current_color.x);
383,345✔
1361
          result.green = static_cast<uint8_t>(current_color.y);
383,345✔
1362
          result.blue = static_cast<uint8_t>(current_color.z);
383,345✔
1363
          data(horiz, vert) = result;
383,345✔
1364

1365
          // Check to draw wireframe in horizontal direction. No inter-thread
1366
          // comm.
1367
          if (horiz > 0) {
383,345✔
1368
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
382,345✔
1369
                  this_line_segments[tid][horiz - 1])) {
382,345✔
1370
              wireframe_initial(horiz, vert) = 1;
15,710✔
1371
            }
1372
          }
1373
        }
1,000,000✔
1374
      } // end "if" vert in correct range
1375

1376
      // We require a barrier before comparing vertical neighbors' intersection
1377
      // stacks. i.e. all threads must be done with their line.
1378
#pragma omp barrier
1379

1380
      // Now that the horizontal line has finished rendering, we can fill in
1381
      // wireframe entries that require comparison among all the threads. Hence
1382
      // the omp barrier being used. It has to be OUTSIDE any if blocks!
1383
      if (vert < pixels()[1]) {
5,025✔
1384
        // Loop over horizontal pixels, checking intersection stack of upper
1385
        // neighbor
1386

1387
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
1388
        if (tid == 0)
1389
          top_cmp = &old_segments;
1390
        else
1391
          top_cmp = &this_line_segments[tid - 1];
1392

1393
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
1,005,000✔
1394
          if (!trackstack_equivalent(
1,000,000✔
1395
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
1,000,000✔
1396
            wireframe_initial(horiz, vert) = 1;
20,595✔
1397
          }
1398
        }
1399
      }
1400

1401
      // We need another barrier to ensure threads don't proceed to modify their
1402
      // intersection stacks on that horizontal line while others are
1403
      // potentially still working on the above.
1404
#pragma omp barrier
1405
      vert += n_threads;
5,025✔
1406
    }
1407
  } // end omp parallel
1408

1409
  // Now thicken the wireframe lines and apply them to our image
1410
  for (int vert = 0; vert < pixels()[1]; ++vert) {
11,055✔
1411
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
2,211,000✔
1412
      if (wireframe_initial(horiz, vert)) {
2,200,000✔
1413
        if (wireframe_thickness_ == 1)
70,983✔
1414
          data(horiz, vert) = wireframe_color_;
30,195✔
1415
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
195,723✔
1416
             ++i)
1417
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
546,876✔
1418
               ++j)
1419
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
422,136!
1420

1421
              // Check if wireframe pixel is out of bounds
1422
              int w_i = std::max(std::min(horiz + i, pixels()[0] - 1), 0);
422,136!
1423
              int w_j = std::max(std::min(vert + j, pixels()[1] - 1), 0);
422,268✔
1424
              data(w_i, w_j) = wireframe_color_;
422,136✔
1425
            }
1426
      }
1427
    }
1428
  }
1429

1430
  return data;
110✔
1431
}
110✔
1432

1433
void WireframeRayTracePlot::create_output() const
55✔
1434
{
1435
  ImageData data = create_image();
55✔
1436
  write_image(data);
55✔
1437
}
55✔
1438

1439
void RayTracePlot::print_info() const
88✔
1440
{
1441
  fmt::print("Camera position: {} {} {}\n", camera_position_.x,
176✔
1442
    camera_position_.y, camera_position_.z);
88✔
1443
  fmt::print("Look at: {} {} {}\n", look_at_.x, look_at_.y, look_at_.z);
88✔
1444
  fmt::print(
176✔
1445
    "Horizontal field of view: {} degrees\n", horizontal_field_of_view_);
88✔
1446
  fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
88✔
1447
}
88✔
1448

1449
void WireframeRayTracePlot::print_info() const
55✔
1450
{
1451
  fmt::print("Plot Type: Wireframe ray-traced\n");
55✔
1452
  RayTracePlot::print_info();
55✔
1453
}
55✔
1454

1455
void WireframeRayTracePlot::set_opacities(pugi::xml_node node)
55✔
1456
{
1457
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
55✔
1458

1459
  for (auto cn : node.children("color")) {
121✔
1460
    // Make sure 3 values are specified for RGB
1461
    double user_xs = std::stod(get_node_value(cn, "xs"));
132✔
1462
    int col_id = std::stoi(get_node_value(cn, "id"));
132✔
1463

1464
    // Add RGB
1465
    if (PlotColorBy::cells == color_by_) {
66!
1466
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
1467
        col_id = model::cell_map[col_id];
66✔
1468
        xs_[col_id] = user_xs;
66✔
1469
      } else {
1470
        warning(fmt::format(
×
1471
          "Could not find cell {} specified in plot {}", col_id, id()));
×
1472
      }
1473
    } else if (PlotColorBy::mats == color_by_) {
×
1474
      if (model::material_map.find(col_id) != model::material_map.end()) {
×
1475
        col_id = model::material_map[col_id];
×
1476
        xs_[col_id] = user_xs;
×
1477
      } else {
1478
        warning(fmt::format(
×
1479
          "Could not find material {} specified in plot {}", col_id, id()));
×
1480
      }
1481
    }
1482
  }
1483
}
55✔
1484

1485
void RayTracePlot::set_orthographic_width(pugi::xml_node node)
88✔
1486
{
1487
  if (check_for_node(node, "orthographic_width")) {
88✔
1488
    double orthographic_width =
11✔
1489
      std::stod(get_node_value(node, "orthographic_width", true));
11✔
1490
    if (orthographic_width < 0.0)
11!
1491
      fatal_error("Requires positive orthographic_width");
×
1492
    orthographic_width_ = orthographic_width;
11✔
1493
  }
1494
}
88✔
1495

1496
void WireframeRayTracePlot::set_wireframe_thickness(pugi::xml_node node)
55✔
1497
{
1498
  if (check_for_node(node, "wireframe_thickness")) {
55✔
1499
    int wireframe_thickness =
22✔
1500
      std::stoi(get_node_value(node, "wireframe_thickness", true));
22✔
1501
    if (wireframe_thickness < 0)
22!
1502
      fatal_error("Requires non-negative wireframe thickness");
×
1503
    wireframe_thickness_ = wireframe_thickness;
22✔
1504
  }
1505
}
55✔
1506

1507
void WireframeRayTracePlot::set_wireframe_ids(pugi::xml_node node)
55✔
1508
{
1509
  if (check_for_node(node, "wireframe_ids")) {
55✔
1510
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
11✔
1511
    // It is read in as actual ID values, but we have to convert to indices in
1512
    // mat/cell array
1513
    for (auto& x : wireframe_ids_)
22✔
1514
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
22!
1515
                                         : model::cell_map[x];
×
1516
  }
1517
  // We make sure the list is sorted in order to later use
1518
  // std::binary_search.
1519
  std::sort(wireframe_ids_.begin(), wireframe_ids_.end());
55✔
1520
}
55✔
1521

1522
void RayTracePlot::set_pixels(pugi::xml_node node)
88✔
1523
{
1524
  vector<int> pxls = get_node_array<int>(node, "pixels");
88✔
1525
  if (pxls.size() != 2)
88!
1526
    fatal_error(
×
1527
      fmt::format("<pixels> must be length 2 in projection plot {}", id()));
×
1528
  pixels()[0] = pxls[0];
88✔
1529
  pixels()[1] = pxls[1];
88✔
1530
}
88✔
1531

1532
void RayTracePlot::set_camera_position(pugi::xml_node node)
88✔
1533
{
1534
  vector<double> camera_pos = get_node_array<double>(node, "camera_position");
88✔
1535
  if (camera_pos.size() != 3) {
88!
1536
    fatal_error(fmt::format(
×
1537
      "camera_position element must have three floating point values"));
1538
  }
1539
  camera_position_.x = camera_pos[0];
88✔
1540
  camera_position_.y = camera_pos[1];
88✔
1541
  camera_position_.z = camera_pos[2];
88✔
1542
}
88✔
1543

1544
void RayTracePlot::set_look_at(pugi::xml_node node)
88✔
1545
{
1546
  vector<double> look_at = get_node_array<double>(node, "look_at");
88✔
1547
  if (look_at.size() != 3) {
88!
1548
    fatal_error("look_at element must have three floating point values");
×
1549
  }
1550
  look_at_.x = look_at[0];
88✔
1551
  look_at_.y = look_at[1];
88✔
1552
  look_at_.z = look_at[2];
88✔
1553
}
88✔
1554

1555
void RayTracePlot::set_field_of_view(pugi::xml_node node)
88✔
1556
{
1557
  // Defaults to 70 degree horizontal field of view (see .h file)
1558
  if (check_for_node(node, "horizontal_field_of_view")) {
88!
UNCOV
1559
    double fov =
×
1560
      std::stod(get_node_value(node, "horizontal_field_of_view", true));
×
1561
    if (fov < 180.0 && fov > 0.0) {
×
1562
      horizontal_field_of_view_ = fov;
×
1563
    } else {
1564
      fatal_error(fmt::format("Horizontal field of view for plot {} "
×
1565
                              "out-of-range. Must be in (0, 180) degrees.",
1566
        id()));
×
1567
    }
1568
  }
1569
}
88✔
1570

1571
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
33✔
1572
{
1573
  set_opaque_ids(node);
33✔
1574
  set_diffuse_fraction(node);
33✔
1575
  set_light_position(node);
33✔
1576
  update_view();
33✔
1577
}
33✔
1578

1579
void SolidRayTracePlot::print_info() const
33✔
1580
{
1581
  fmt::print("Plot Type: Solid ray-traced\n");
33✔
1582
  RayTracePlot::print_info();
33✔
1583
}
33✔
1584

1585
ImageData SolidRayTracePlot::create_image() const
55✔
1586
{
1587
  size_t width = pixels()[0];
55✔
1588
  size_t height = pixels()[1];
55✔
1589
  ImageData data({width, height}, not_found_);
55✔
1590

1591
#pragma omp parallel for schedule(dynamic) collapse(2)
30✔
1592
  for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
3,105✔
1593
    for (int vert = 0; vert < pixels()[1]; ++vert) {
603,560✔
1594
      // RayTracePlot implements camera ray generation
1595
      std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
600,480✔
1596
      PhongRay ray(ru.first, ru.second, *this);
600,480✔
1597
      ray.trace();
600,480✔
1598
      data(horiz, vert) = ray.result_color();
600,480✔
1599
    }
600,480✔
1600
  }
1601

1602
  return data;
55✔
1603
}
1604

1605
void SolidRayTracePlot::create_output() const
33✔
1606
{
1607
  ImageData data = create_image();
33✔
1608
  write_image(data);
33✔
1609
}
33✔
1610

1611
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
33✔
1612
{
1613
  if (check_for_node(node, "opaque_ids")) {
33!
1614
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
33✔
1615

1616
    // It is read in as actual ID values, but we have to convert to indices in
1617
    // mat/cell array
1618
    for (auto& x : opaque_ids_tmp)
99✔
1619
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
132!
1620
                                         : model::cell_map[x];
×
1621

1622
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
33✔
1623
  }
33✔
1624
}
33✔
1625

1626
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
33✔
1627
{
1628
  if (check_for_node(node, "light_position")) {
33✔
1629
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
11✔
1630

1631
    if (light_pos_tmp.size() != 3)
11!
1632
      fatal_error("Light position must be given as 3D coordinates");
×
1633

1634
    light_location_.x = light_pos_tmp[0];
11✔
1635
    light_location_.y = light_pos_tmp[1];
11✔
1636
    light_location_.z = light_pos_tmp[2];
11✔
1637
  } else {
11✔
1638
    light_location_ = camera_position();
22✔
1639
  }
1640
}
33✔
1641

1642
void SolidRayTracePlot::set_diffuse_fraction(pugi::xml_node node)
33✔
1643
{
1644
  if (check_for_node(node, "diffuse_fraction")) {
33✔
1645
    diffuse_fraction_ = std::stod(get_node_value(node, "diffuse_fraction"));
11✔
1646
    if (diffuse_fraction_ < 0.0 || diffuse_fraction_ > 1.0) {
11!
1647
      fatal_error("Must have 0 <= diffuse fraction <= 1");
×
1648
    }
1649
  }
1650
}
33✔
1651

1652
void Ray::compute_distance()
3,014,638✔
1653
{
1654
  boundary() = distance_to_boundary(*this);
3,014,638✔
1655
}
3,014,638✔
1656

1657
void Ray::trace()
3,521,056✔
1658
{
1659
  // To trace the ray from its origin all the way through the model, we have
1660
  // to proceed in two phases. In the first, the ray may or may not be found
1661
  // inside the model. If the ray is already in the model, phase one can be
1662
  // skipped. Otherwise, the ray has to be advanced to the boundary of the
1663
  // model where all the cells are defined. Importantly, this is assuming that
1664
  // the model is convex, which is a very reasonable assumption for any
1665
  // radiation transport model.
1666
  //
1667
  // After phase one is done, we can starting tracing from cell to cell within
1668
  // the model. This step can use neighbor lists to accelerate the ray tracing.
1669

1670
  bool inside_cell;
3,521,056✔
1671
  // Check for location if the particle is already known
1672
  if (lowest_coord().cell() == C_NONE) {
3,521,056!
1673
    // The geometry position of the particle is either unknown or outside of the
1674
    // edge of the model.
1675
    if (lowest_coord().universe() == C_NONE) {
3,521,056!
1676
      // Attempt to initialize the particle. We may have to
1677
      // enter a loop to move it up to the edge of the model.
1678
      inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
3,521,056✔
1679
    } else {
1680
      // It has been already calculated that the current position is outside of
1681
      // the edge of the model.
1682
      inside_cell = false;
1683
    }
1684
  } else {
1685
    // Availability of the cell means that the particle is located inside the
1686
    // edge.
1687
    inside_cell = true;
1688
  }
1689

1690
  // Advance to the boundary of the model
1691
  while (!inside_cell) {
15,618,438!
1692
    advance_to_boundary_from_void();
15,618,438✔
1693
    inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
15,618,438✔
1694

1695
    // If true this means no surface was intersected. See cell.cpp and search
1696
    // for numeric_limits to see where we return it.
1697
    if (surface() == std::numeric_limits<int>::max()) {
15,618,438!
1698
      warning(fmt::format("Lost a ray, r = {}, u = {}", r(), u()));
×
UNCOV
1699
      return;
×
1700
    }
1701

1702
    // Exit this loop and enter into cell-to-cell ray tracing (which uses
1703
    // neighbor lists)
1704
    if (inside_cell)
15,618,438✔
1705
      break;
1706

1707
    // if there is no intersection with the model, we're done
1708
    if (boundary().surface() == SURFACE_NONE)
14,068,604✔
1709
      return;
1710

1711
    event_counter_++;
12,097,382✔
1712
    if (event_counter_ > MAX_INTERSECTIONS) {
12,097,382!
UNCOV
1713
      warning("Likely infinite loop in ray traced plot");
×
UNCOV
1714
      return;
×
1715
    }
1716
  }
1717

1718
  // Call the specialized logic for this type of ray. This is for the
1719
  // intersection for the first intersection if we had one.
1720
  if (boundary().surface() != SURFACE_NONE) {
1,549,834!
1721
    // set the geometry state's surface attribute to be used for
1722
    // surface normal computation
1723
    surface() = boundary().surface();
1,549,834✔
1724
    on_intersection();
1,549,834✔
1725
    if (stop_)
1,549,834!
1726
      return;
1727
  }
1728

1729
  // reset surface attribute to zero after the first intersection so that it
1730
  // doesn't perturb surface crossing logic from here on out
1731
  surface() = 0;
1,549,834✔
1732

1733
  // This is the ray tracing loop within the model. It exits after exiting
1734
  // the model, which is equivalent to assuming that the model is convex.
1735
  // It would be nice to factor out the on_intersection at the end of this
1736
  // loop and then do "while (inside_cell)", but we can't guarantee it's
1737
  // on a surface in that case. There might be some other way to set it
1738
  // up that is perhaps a little more elegant, but this is what works just
1739
  // fine.
1740
  while (true) {
2,308,570✔
1741

1742
    compute_distance();
2,308,570✔
1743

1744
    // There are no more intersections to process
1745
    // if we hit the edge of the model, so stop
1746
    // the particle in that case. Also, just exit
1747
    // if a negative distance was somehow computed.
1748
    if (boundary().distance() == INFTY || boundary().distance() == INFINITY ||
2,308,570!
1749
        boundary().distance() < 0) {
2,308,570!
1750
      return;
1751
    }
1752

1753
    // See below comment where call_on_intersection is checked in an
1754
    // if statement for an explanation of this.
1755
    bool call_on_intersection {true};
2,308,570✔
1756
    if (boundary().distance() < 10 * TINY_BIT) {
2,308,570✔
1757
      call_on_intersection = false;
593,285✔
1758
    }
1759

1760
    // DAGMC surfaces expect us to go a little bit further than the advance
1761
    // distance to properly check cell inclusion.
1762
    boundary().distance() += TINY_BIT;
2,308,570✔
1763

1764
    // Advance particle, prepare for next intersection
1765
    for (int lev = 0; lev < n_coord(); ++lev) {
4,617,140✔
1766
      coord(lev).r() += boundary().distance() * coord(lev).u();
2,308,570✔
1767
    }
1768
    surface() = boundary().surface();
2,308,570✔
1769
    // Initialize last cells from the current cell, because the cell() variable
1770
    // does not contain the data for the case of a single-segment ray
1771
    for (int j = 0; j < n_coord(); ++j) {
4,617,140✔
1772
      cell_last(j) = coord(j).cell();
2,308,570✔
1773
    }
1774
    n_coord_last() = n_coord();
2,308,570✔
1775
    n_coord() = boundary().coord_level();
2,308,570!
1776
    if (boundary().lattice_translation()[0] != 0 ||
2,308,570!
1777
        boundary().lattice_translation()[1] != 0 ||
2,308,570!
1778
        boundary().lattice_translation()[2] != 0) {
2,308,570!
UNCOV
1779
      cross_lattice(*this, boundary(), settings::verbosity >= 10);
×
1780
    }
1781

1782
    // Record how far the ray has traveled
1783
    traversal_distance_ += boundary().distance();
2,308,570✔
1784
    inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10);
2,308,570✔
1785

1786
    // Call the specialized logic for this type of ray. Note that we do not
1787
    // call this if the advance distance is very small. Unfortunately, it seems
1788
    // darn near impossible to get the particle advanced to the model boundary
1789
    // and through it without sometimes accidentally calling on_intersection
1790
    // twice. This incorrectly shades the region as occluded when it might not
1791
    // actually be. By screening out intersection distances smaller than a
1792
    // threshold 10x larger than the scoot distance used to advance up to the
1793
    // model boundary, we can avoid that situation.
1794
    if (call_on_intersection) {
2,308,570✔
1795
      on_intersection();
1,715,285✔
1796
      if (stop_)
1,715,285✔
1797
        return;
1798
    }
1799

1800
    if (!inside_cell)
2,273,007✔
1801
      return;
1802

1803
    event_counter_++;
758,736✔
1804
    if (event_counter_ > MAX_INTERSECTIONS) {
758,736!
UNCOV
1805
      warning("Likely infinite loop in ray traced plot");
×
UNCOV
1806
      return;
×
1807
    }
1808
  }
1809
}
1810

1811
void ProjectionRay::on_intersection()
2,359,148✔
1812
{
1813
  // This records a tuple with the following info
1814
  //
1815
  // 1) ID (material or cell depending on color_by_)
1816
  // 2) Distance traveled by the ray through that ID
1817
  // 3) Index of the intersected surface (starting from 1)
1818

1819
  line_segments_.emplace_back(
2,359,148✔
1820
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
2,359,148✔
1821
      ? material()
545,919✔
1822
      : lowest_coord().cell(),
1,813,229✔
1823
    traversal_distance_, boundary().surface_index());
2,359,148✔
1824
}
2,359,148✔
1825

1826
void PhongRay::on_intersection()
905,971✔
1827
{
1828
  // Check if we hit an opaque material or cell
1829
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
905,971✔
1830
                 ? material()
905,971!
UNCOV
1831
                 : lowest_coord().cell();
×
1832

1833
  // If we are reflected and have advanced beyond the camera,
1834
  // the ray is done. This is checked here because we should
1835
  // kill the ray even if the material is not opaque.
1836
  if (reflected_ && (r() - plot_.camera_position()).dot(u()) >= 0.0) {
905,971!
UNCOV
1837
    stop();
×
1838
    return;
164,340✔
1839
  }
1840

1841
  // Anything that's not opaque has zero impact on the plot.
1842
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
905,971✔
1843
    return;
1844

1845
  if (!reflected_) {
741,631✔
1846
    // reflect the particle and set the color to be colored by
1847
    // the normal or the diffuse lighting contribution
1848
    reflected_ = true;
706,068✔
1849
    result_color_ = plot_.colors_[hit_id];
706,068✔
1850
    Direction to_light = plot_.light_location_ - r();
706,068✔
1851
    to_light /= to_light.norm();
706,068✔
1852

1853
    // TODO
1854
    // Not sure what can cause a surface token to be invalid here, although it
1855
    // sometimes happens for a few pixels. It's very very rare, so proceed by
1856
    // coloring the pixel with the overlap color. It seems to happen only for a
1857
    // few pixels on the outer boundary of a hex lattice.
1858
    //
1859
    // We cannot detect it in the outer loop, and it only matters here, so
1860
    // that's why the error handling is a little different than for a lost
1861
    // ray.
1862
    if (surface() == 0) {
706,068!
UNCOV
1863
      result_color_ = plot_.overlap_color_;
×
UNCOV
1864
      stop();
×
UNCOV
1865
      return;
×
1866
    }
1867

1868
    // Get surface pointer
1869
    const auto& surf = model::surfaces.at(surface_index());
706,068✔
1870

1871
    Direction normal = surf->normal(r_local());
706,068✔
1872
    normal /= normal.norm();
706,068✔
1873

1874
    // Need to apply translations to find the normal vector in
1875
    // the base level universe's coordinate system.
1876
    for (int lev = n_coord() - 2; lev >= 0; --lev) {
706,068!
UNCOV
1877
      if (coord(lev + 1).rotated()) {
×
UNCOV
1878
        const Cell& c {*model::cells[coord(lev).cell()]};
×
UNCOV
1879
        normal = normal.inverse_rotate(c.rotation_);
×
1880
      }
1881
    }
1882

1883
    // use the normal opposed to the ray direction
1884
    if (normal.dot(u()) > 0.0) {
706,068✔
1885
      normal *= -1.0;
63,789✔
1886
    }
1887

1888
    // Facing away from the light means no lighting
1889
    double dotprod = normal.dot(to_light);
706,068✔
1890
    dotprod = std::max(0.0, dotprod);
706,068✔
1891

1892
    double modulation =
706,068✔
1893
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
706,068✔
1894
    result_color_ *= modulation;
706,068✔
1895

1896
    // Now point the particle to the camera. We now begin
1897
    // checking to see if it's occluded by another surface
1898
    u() = to_light;
706,068✔
1899

1900
    orig_hit_id_ = hit_id;
706,068✔
1901

1902
    // OpenMC native CSG and DAGMC surfaces have some slight differences
1903
    // in how they interpret particles that are sitting on a surface.
1904
    // I don't know exactly why, but this makes everything work beautifully.
1905
    if (surf->geom_type() == GeometryType::DAG) {
706,068!
UNCOV
1906
      surface() = 0;
×
1907
    } else {
1908
      surface() = -surface(); // go to other side
706,068✔
1909
    }
1910

1911
    // Must fully restart coordinate search. Why? Not sure.
1912
    clear();
706,068✔
1913

1914
    // Note this could likely be faster if we cached the previous
1915
    // cell we were in before the reflection. This is the easiest
1916
    // way to fully initialize all the sub-universe coordinates and
1917
    // directions though.
1918
    bool found = exhaustive_find_cell(*this);
706,068✔
1919
    if (!found) {
706,068!
UNCOV
1920
      fatal_error("Lost particle after reflection.");
×
1921
    }
1922

1923
    // Must recalculate distance to boundary due to the
1924
    // direction change
1925
    compute_distance();
706,068✔
1926

1927
  } else {
1928
    // If it's not facing the light, we color with the diffuse contribution, so
1929
    // next we check if we're going to occlude the last reflected surface. if
1930
    // so, color by the diffuse contribution instead
1931

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

1935
    result_color_ = plot_.colors_[orig_hit_id_];
35,563✔
1936
    result_color_ *= plot_.diffuse_fraction_;
35,563✔
1937
    stop();
741,631✔
1938
  }
1939
}
1940

1941
extern "C" int openmc_id_map(const void* plot, int32_t* data_out)
267✔
1942
{
1943

1944
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
267✔
1945
  if (!plt) {
267!
1946
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1947
    return OPENMC_E_INVALID_ARGUMENT;
×
1948
  }
1949

1950
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
267!
1951
    model::overlap_check_count.resize(model::cells.size());
22✔
1952
  }
1953

1954
  auto ids = plt->get_map<IdData>();
267✔
1955

1956
  // write id data to array
1957
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
267✔
1958

1959
  return 0;
267✔
1960
}
267✔
1961

1962
extern "C" int openmc_property_map(const void* plot, double* data_out)
11✔
1963
{
1964

1965
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
11✔
1966
  if (!plt) {
11!
1967
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
UNCOV
1968
    return OPENMC_E_INVALID_ARGUMENT;
×
1969
  }
1970

1971
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
11!
UNCOV
1972
    model::overlap_check_count.resize(model::cells.size());
×
1973
  }
1974

1975
  auto props = plt->get_map<PropertyData>();
11✔
1976

1977
  // write id data to array
1978
  std::copy(props.data_.begin(), props.data_.end(), data_out);
11✔
1979

1980
  return 0;
11✔
1981
}
11✔
1982

1983
extern "C" int openmc_get_plot_index(int32_t id, int32_t* index)
22✔
1984
{
1985
  auto it = model::plot_map.find(id);
22!
1986
  if (it == model::plot_map.end()) {
22!
1987
    set_errmsg("No plot exists with ID=" + std::to_string(id) + ".");
×
1988
    return OPENMC_E_INVALID_ID;
×
1989
  }
1990

1991
  *index = it->second;
22✔
1992
  return 0;
22✔
1993
}
1994

1995
extern "C" int openmc_plot_get_id(int32_t index, int32_t* id)
55✔
1996
{
1997
  if (index < 0 || index >= model::plots.size()) {
55!
1998
    set_errmsg("Index in plots array is out of bounds.");
×
1999
    return OPENMC_E_OUT_OF_BOUNDS;
×
2000
  }
2001

2002
  *id = model::plots[index]->id();
55✔
2003
  return 0;
55✔
2004
}
2005

2006
extern "C" int openmc_plot_set_id(int32_t index, int32_t id)
×
2007
{
2008
  if (index < 0 || index >= model::plots.size()) {
×
2009
    set_errmsg("Index in plots array is out of bounds.");
×
2010
    return OPENMC_E_OUT_OF_BOUNDS;
×
2011
  }
2012

UNCOV
2013
  if (id < 0 && id != C_NONE) {
×
UNCOV
2014
    set_errmsg("Invalid plot ID.");
×
UNCOV
2015
    return OPENMC_E_INVALID_ARGUMENT;
×
2016
  }
2017

UNCOV
2018
  auto* plot = model::plots[index].get();
×
UNCOV
2019
  int32_t old_id = plot->id();
×
UNCOV
2020
  if (id == old_id)
×
2021
    return 0;
2022

2023
  model::plot_map.erase(old_id);
×
2024
  try {
×
UNCOV
2025
    plot->set_id(id);
×
UNCOV
2026
  } catch (const std::runtime_error& e) {
×
UNCOV
2027
    model::plot_map[old_id] = index;
×
UNCOV
2028
    set_errmsg(e.what());
×
UNCOV
2029
    return OPENMC_E_INVALID_ID;
×
2030
  }
×
2031
  model::plot_map[plot->id()] = index;
×
UNCOV
2032
  return 0;
×
2033
}
2034

2035
extern "C" size_t openmc_plots_size()
22✔
2036
{
2037
  return model::plots.size();
22✔
2038
}
2039

2040
int map_phong_domain_id(
55✔
2041
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2042
{
2043
  if (!plot || !index_out) {
55!
2044
    set_errmsg("Invalid plot pointer passed to map_phong_domain_id");
×
UNCOV
2045
    return OPENMC_E_INVALID_ARGUMENT;
×
2046
  }
2047

2048
  if (plot->color_by_ == PlottableInterface::PlotColorBy::mats) {
55!
2049
    auto it = model::material_map.find(id);
55!
2050
    if (it == model::material_map.end()) {
55!
UNCOV
2051
      set_errmsg("Invalid material ID for SolidRayTracePlot");
×
UNCOV
2052
      return OPENMC_E_INVALID_ID;
×
2053
    }
2054
    *index_out = it->second;
55✔
2055
    return 0;
55✔
2056
  }
2057

UNCOV
2058
  if (plot->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2059
    auto it = model::cell_map.find(id);
×
2060
    if (it == model::cell_map.end()) {
×
UNCOV
2061
      set_errmsg("Invalid cell ID for SolidRayTracePlot");
×
UNCOV
2062
      return OPENMC_E_INVALID_ID;
×
2063
    }
UNCOV
2064
    *index_out = it->second;
×
UNCOV
2065
    return 0;
×
2066
  }
2067

2068
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
UNCOV
2069
  return OPENMC_E_INVALID_TYPE;
×
2070
}
2071

2072
int get_solidraytrace_plot_by_index(int32_t index, SolidRayTracePlot** plot)
308✔
2073
{
2074
  if (!plot) {
308!
UNCOV
2075
    set_errmsg("Null output pointer passed to get_solidraytrace_plot_by_index");
×
UNCOV
2076
    return OPENMC_E_INVALID_ARGUMENT;
×
2077
  }
2078

2079
  if (index < 0 || index >= model::plots.size()) {
308!
2080
    set_errmsg("Index in plots array is out of bounds.");
×
UNCOV
2081
    return OPENMC_E_OUT_OF_BOUNDS;
×
2082
  }
2083

2084
  auto* plottable = model::plots[index].get();
308!
2085
  auto* solid_plot = dynamic_cast<SolidRayTracePlot*>(plottable);
308!
2086
  if (!solid_plot) {
308!
UNCOV
2087
    set_errmsg("Plot at index=" + std::to_string(index) +
×
2088
               " is not a solid raytrace plot.");
UNCOV
2089
    return OPENMC_E_INVALID_TYPE;
×
2090
  }
2091

2092
  *plot = solid_plot;
308✔
2093
  return 0;
308✔
2094
}
2095

2096
extern "C" int openmc_solidraytrace_plot_create(int32_t* index)
11✔
2097
{
2098
  if (!index) {
11!
2099
    set_errmsg(
×
2100
      "Null output pointer passed to openmc_solidraytrace_plot_create");
UNCOV
2101
    return OPENMC_E_INVALID_ARGUMENT;
×
2102
  }
2103

2104
  try {
11✔
2105
    auto new_plot = std::make_unique<SolidRayTracePlot>();
11✔
2106
    new_plot->set_id();
11✔
2107
    int32_t new_plot_id = new_plot->id();
11✔
2108
#ifdef USE_LIBPNG
2109
    new_plot->path_plot() = fmt::format("plot_{}.png", new_plot_id);
11✔
2110
#else
2111
    new_plot->path_plot() = fmt::format("plot_{}.ppm", new_plot_id);
2112
#endif
2113
    int32_t new_plot_index = model::plots.size();
11✔
2114
    model::plots.emplace_back(std::move(new_plot));
11✔
2115
    model::plot_map[new_plot_id] = new_plot_index;
11✔
2116
    *index = new_plot_index;
11✔
2117
  } catch (const std::exception& e) {
11!
UNCOV
2118
    set_errmsg(e.what());
×
UNCOV
2119
    return OPENMC_E_ALLOCATE;
×
UNCOV
2120
  }
×
2121

2122
  return 0;
11✔
2123
}
2124

2125
extern "C" int openmc_solidraytrace_plot_get_pixels(
33✔
2126
  int32_t index, int32_t* width, int32_t* height)
2127
{
2128
  if (!width || !height) {
33!
2129
    set_errmsg(
×
2130
      "Invalid arguments passed to openmc_solidraytrace_plot_get_pixels");
UNCOV
2131
    return OPENMC_E_INVALID_ARGUMENT;
×
2132
  }
2133

2134
  SolidRayTracePlot* plt = nullptr;
33✔
2135
  int err = get_solidraytrace_plot_by_index(index, &plt);
33✔
2136
  if (err)
33!
2137
    return err;
2138

2139
  *width = plt->pixels()[0];
33✔
2140
  *height = plt->pixels()[1];
33✔
2141
  return 0;
33✔
2142
}
2143

2144
extern "C" int openmc_solidraytrace_plot_set_pixels(
11✔
2145
  int32_t index, int32_t width, int32_t height)
2146
{
2147
  if (width <= 0 || height <= 0) {
11!
2148
    set_errmsg(
×
2149
      "Invalid arguments passed to openmc_solidraytrace_plot_set_pixels");
UNCOV
2150
    return OPENMC_E_INVALID_ARGUMENT;
×
2151
  }
2152

2153
  SolidRayTracePlot* plt = nullptr;
11✔
2154
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2155
  if (err)
11!
2156
    return err;
2157

2158
  plt->pixels()[0] = width;
11✔
2159
  plt->pixels()[1] = height;
11✔
2160
  return 0;
11✔
2161
}
2162

2163
extern "C" int openmc_solidraytrace_plot_get_color_by(
11✔
2164
  int32_t index, int32_t* color_by)
2165
{
2166
  if (!color_by) {
11!
UNCOV
2167
    set_errmsg(
×
2168
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color_by");
UNCOV
2169
    return OPENMC_E_INVALID_ARGUMENT;
×
2170
  }
2171

2172
  SolidRayTracePlot* plt = nullptr;
11✔
2173
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2174
  if (err)
11!
2175
    return err;
2176

2177
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
11!
2178
    *color_by = 0;
11✔
2179
  } else if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
UNCOV
2180
    *color_by = 1;
×
2181
  } else {
2182
    set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
UNCOV
2183
    return OPENMC_E_INVALID_TYPE;
×
2184
  }
2185

2186
  return 0;
2187
}
2188

2189
extern "C" int openmc_solidraytrace_plot_set_color_by(
11✔
2190
  int32_t index, int32_t color_by)
2191
{
2192
  SolidRayTracePlot* plt = nullptr;
11✔
2193
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2194
  if (err)
11!
2195
    return err;
2196

2197
  if (color_by == 0) {
11!
2198
    plt->color_by_ = PlottableInterface::PlotColorBy::mats;
11✔
2199
  } else if (color_by == 1) {
×
UNCOV
2200
    plt->color_by_ = PlottableInterface::PlotColorBy::cells;
×
2201
  } else {
2202
    set_errmsg("Invalid color_by value for SolidRayTracePlot");
×
2203
    return OPENMC_E_INVALID_ARGUMENT;
×
2204
  }
2205

2206
  return 0;
2207
}
2208

2209
extern "C" int openmc_solidraytrace_plot_set_default_colors(int32_t index)
11✔
2210
{
2211
  SolidRayTracePlot* plt = nullptr;
11✔
2212
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2213
  if (err)
11!
2214
    return err;
2215

2216
  plt->set_default_colors();
11✔
2217
  return 0;
2218
}
2219

UNCOV
2220
extern "C" int openmc_solidraytrace_plot_set_all_opaque(int32_t index)
×
2221
{
2222
  SolidRayTracePlot* plt = nullptr;
×
UNCOV
2223
  int err = get_solidraytrace_plot_by_index(index, &plt);
×
UNCOV
2224
  if (err)
×
2225
    return err;
2226

UNCOV
2227
  plt->opaque_ids().clear();
×
UNCOV
2228
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
×
UNCOV
2229
    for (int32_t i = 0; i < model::materials.size(); ++i) {
×
UNCOV
2230
      plt->opaque_ids().insert(i);
×
2231
    }
UNCOV
2232
    return 0;
×
2233
  }
2234

UNCOV
2235
  if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2236
    for (int32_t i = 0; i < model::cells.size(); ++i) {
×
UNCOV
2237
      plt->opaque_ids().insert(i);
×
2238
    }
UNCOV
2239
    return 0;
×
2240
  }
2241

UNCOV
2242
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
UNCOV
2243
  return OPENMC_E_INVALID_TYPE;
×
2244
}
2245

2246
extern "C" int openmc_solidraytrace_plot_set_opaque(
22✔
2247
  int32_t index, int32_t id, bool visible)
2248
{
2249
  SolidRayTracePlot* plt = nullptr;
22✔
2250
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2251
  if (err)
22!
2252
    return err;
2253

2254
  int32_t domain_index = -1;
22✔
2255
  err = map_phong_domain_id(plt, id, &domain_index);
22✔
2256
  if (err)
22!
2257
    return err;
2258

2259
  if (visible) {
22✔
2260
    plt->opaque_ids().insert(domain_index);
11✔
2261
  } else {
2262
    plt->opaque_ids().erase(domain_index);
11✔
2263
  }
2264

2265
  return 0;
2266
}
2267

2268
extern "C" int openmc_solidraytrace_plot_set_color(
22✔
2269
  int32_t index, int32_t id, uint8_t r, uint8_t g, uint8_t b)
2270
{
2271
  SolidRayTracePlot* plt = nullptr;
22✔
2272
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2273
  if (err)
22!
2274
    return err;
2275

2276
  int32_t domain_index = -1;
22✔
2277
  err = map_phong_domain_id(plt, id, &domain_index);
22✔
2278
  if (err)
22!
2279
    return err;
2280

2281
  if (domain_index < 0 ||
22!
2282
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
22!
UNCOV
2283
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
UNCOV
2284
    return OPENMC_E_OUT_OF_BOUNDS;
×
2285
  }
2286

2287
  plt->colors_[domain_index] = RGBColor(r, g, b);
22✔
2288
  return 0;
22✔
2289
}
2290

2291
extern "C" int openmc_solidraytrace_plot_get_camera_position(
11✔
2292
  int32_t index, double* x, double* y, double* z)
2293
{
2294
  if (!x || !y || !z) {
11!
UNCOV
2295
    set_errmsg("Invalid arguments passed to "
×
2296
               "openmc_solidraytrace_plot_get_camera_position");
2297
    return OPENMC_E_INVALID_ARGUMENT;
×
2298
  }
2299

2300
  SolidRayTracePlot* plt = nullptr;
11✔
2301
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2302
  if (err)
11!
2303
    return err;
2304

2305
  const auto& camera_position = plt->camera_position();
11✔
2306
  *x = camera_position.x;
11✔
2307
  *y = camera_position.y;
11✔
2308
  *z = camera_position.z;
11✔
2309
  return 0;
11✔
2310
}
2311

2312
extern "C" int openmc_solidraytrace_plot_set_camera_position(
11✔
2313
  int32_t index, double x, double y, double z)
2314
{
2315
  SolidRayTracePlot* plt = nullptr;
11✔
2316
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2317
  if (err)
11!
2318
    return err;
2319

2320
  plt->camera_position() = {x, y, z};
11✔
2321
  return 0;
11✔
2322
}
2323

2324
extern "C" int openmc_solidraytrace_plot_get_look_at(
11✔
2325
  int32_t index, double* x, double* y, double* z)
2326
{
2327
  if (!x || !y || !z) {
11!
UNCOV
2328
    set_errmsg(
×
2329
      "Invalid arguments passed to openmc_solidraytrace_plot_get_look_at");
2330
    return OPENMC_E_INVALID_ARGUMENT;
×
2331
  }
2332

2333
  SolidRayTracePlot* plt = nullptr;
11✔
2334
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2335
  if (err)
11!
2336
    return err;
2337

2338
  const auto& look_at = plt->look_at();
11✔
2339
  *x = look_at.x;
11✔
2340
  *y = look_at.y;
11✔
2341
  *z = look_at.z;
11✔
2342
  return 0;
11✔
2343
}
2344

2345
extern "C" int openmc_solidraytrace_plot_set_look_at(
11✔
2346
  int32_t index, double x, double y, double z)
2347
{
2348
  SolidRayTracePlot* plt = nullptr;
11✔
2349
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2350
  if (err)
11!
2351
    return err;
2352

2353
  plt->look_at() = {x, y, z};
11✔
2354
  return 0;
11✔
2355
}
2356

2357
extern "C" int openmc_solidraytrace_plot_get_up(
11✔
2358
  int32_t index, double* x, double* y, double* z)
2359
{
2360
  if (!x || !y || !z) {
11!
UNCOV
2361
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_up");
×
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& up = plt->up();
11✔
2371
  *x = up.x;
11✔
2372
  *y = up.y;
11✔
2373
  *z = up.z;
11✔
2374
  return 0;
11✔
2375
}
2376

2377
extern "C" int openmc_solidraytrace_plot_set_up(
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->up() = {x, y, z};
11✔
2386
  return 0;
11✔
2387
}
2388

2389
extern "C" int openmc_solidraytrace_plot_get_light_position(
11✔
2390
  int32_t index, double* x, double* y, double* z)
2391
{
2392
  if (!x || !y || !z) {
11!
UNCOV
2393
    set_errmsg("Invalid arguments passed to "
×
2394
               "openmc_solidraytrace_plot_get_light_position");
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& light_position = plt->light_location();
11✔
2404
  *x = light_position.x;
11✔
2405
  *y = light_position.y;
11✔
2406
  *z = light_position.z;
11✔
2407
  return 0;
11✔
2408
}
2409

2410
extern "C" int openmc_solidraytrace_plot_set_light_position(
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->light_location() = {x, y, z};
11✔
2419
  return 0;
11✔
2420
}
2421

2422
extern "C" int openmc_solidraytrace_plot_get_fov(int32_t index, double* fov)
11✔
2423
{
2424
  if (!fov) {
11!
UNCOV
2425
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_fov");
×
UNCOV
2426
    return OPENMC_E_INVALID_ARGUMENT;
×
2427
  }
2428

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

2434
  *fov = plt->horizontal_field_of_view();
11✔
2435
  return 0;
11✔
2436
}
2437

2438
extern "C" int openmc_solidraytrace_plot_set_fov(int32_t index, double fov)
11✔
2439
{
2440
  SolidRayTracePlot* plt = nullptr;
11✔
2441
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2442
  if (err)
11!
2443
    return err;
2444

2445
  plt->horizontal_field_of_view() = fov;
11✔
2446
  return 0;
11✔
2447
}
2448

2449
extern "C" int openmc_solidraytrace_plot_update_view(int32_t index)
22✔
2450
{
2451
  SolidRayTracePlot* plt = nullptr;
22✔
2452
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2453
  if (err)
22!
2454
    return err;
2455

2456
  plt->update_view();
22✔
2457
  return 0;
2458
}
2459

2460
extern "C" int openmc_solidraytrace_plot_create_image(
22✔
2461
  int32_t index, uint8_t* data_out, int32_t width, int32_t height)
2462
{
2463
  if (!data_out || width <= 0 || height <= 0) {
22!
UNCOV
2464
    set_errmsg(
×
2465
      "Invalid arguments passed to openmc_solidraytrace_plot_create_image");
UNCOV
2466
    return OPENMC_E_INVALID_ARGUMENT;
×
2467
  }
2468

2469
  SolidRayTracePlot* plt = nullptr;
22✔
2470
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2471
  if (err)
22!
2472
    return err;
2473

2474
  if (plt->pixels()[0] != width || plt->pixels()[1] != height) {
22!
UNCOV
2475
    set_errmsg(
×
2476
      "Requested image size does not match SolidRayTracePlot pixel settings");
UNCOV
2477
    return OPENMC_E_INVALID_SIZE;
×
2478
  }
2479

2480
  ImageData data = plt->create_image();
22✔
2481
  if (static_cast<int32_t>(data.shape()[0]) != width ||
22!
2482
      static_cast<int32_t>(data.shape()[1]) != height) {
22!
2483
    set_errmsg("Unexpected image size from SolidRayTracePlot create_image");
×
UNCOV
2484
    return OPENMC_E_INVALID_SIZE;
×
2485
  }
2486

2487
  for (int32_t y = 0; y < height; ++y) {
154✔
2488
    for (int32_t x = 0; x < width; ++x) {
1,188✔
2489
      const auto& color = data(x, y);
1,056✔
2490
      size_t idx = (static_cast<size_t>(y) * width + x) * 3;
1,056✔
2491
      data_out[idx + 0] = color.red;
1,056✔
2492
      data_out[idx + 1] = color.green;
1,056✔
2493
      data_out[idx + 2] = color.blue;
1,056✔
2494
    }
2495
  }
2496

2497
  return 0;
2498
}
22✔
2499

2500
extern "C" int openmc_solidraytrace_plot_get_color(
11✔
2501
  int32_t index, int32_t id, uint8_t* r, uint8_t* g, uint8_t* b)
2502
{
2503
  if (!r || !g || !b) {
11!
UNCOV
2504
    set_errmsg(
×
2505
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color");
UNCOV
2506
    return OPENMC_E_INVALID_ARGUMENT;
×
2507
  }
2508

2509
  SolidRayTracePlot* plt = nullptr;
11✔
2510
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2511
  if (err)
11!
2512
    return err;
2513

2514
  int32_t domain_index = -1;
11✔
2515
  err = map_phong_domain_id(plt, id, &domain_index);
11✔
2516
  if (err)
11!
2517
    return err;
2518

2519
  if (domain_index < 0 ||
11!
2520
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
11!
UNCOV
2521
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
UNCOV
2522
    return OPENMC_E_OUT_OF_BOUNDS;
×
2523
  }
2524

2525
  const auto& color = plt->colors_[domain_index];
11✔
2526
  *r = color.red;
11✔
2527
  *g = color.green;
11✔
2528
  *b = color.blue;
11✔
2529
  return 0;
11✔
2530
}
2531

2532
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
11✔
2533
  int32_t index, double* diffuse_fraction)
2534
{
2535
  if (!diffuse_fraction) {
11!
UNCOV
2536
    set_errmsg("Invalid arguments passed to "
×
2537
               "openmc_solidraytrace_plot_get_diffuse_fraction");
2538
    return OPENMC_E_INVALID_ARGUMENT;
×
2539
  }
2540

2541
  SolidRayTracePlot* plt = nullptr;
11✔
2542
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2543
  if (err)
11!
2544
    return err;
2545

2546
  *diffuse_fraction = plt->diffuse_fraction();
11✔
2547
  return 0;
11✔
2548
}
2549

2550
extern "C" int openmc_solidraytrace_plot_set_diffuse_fraction(
11✔
2551
  int32_t index, double diffuse_fraction)
2552
{
2553
  SolidRayTracePlot* plt = nullptr;
11✔
2554
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2555
  if (err)
11!
2556
    return err;
2557

2558
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
11!
UNCOV
2559
    set_errmsg("Diffuse fraction must be between 0 and 1");
×
UNCOV
2560
    return OPENMC_E_INVALID_ARGUMENT;
×
2561
  }
2562

2563
  plt->diffuse_fraction() = diffuse_fraction;
11✔
2564
  return 0;
11✔
2565
}
2566

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

© 2026 Coveralls, Inc