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

openmc-dev / openmc / 43538648659

14 Nov 2026 01:07AM UTC coverage: 82.356% (+0.05%) from 82.304%
43538648659

push

github

web-flow
Specify temperature from a field (structured mesh only) (#3734)

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

20953 of 29717 branches covered (70.51%)

Branch coverage included in aggregate %.

320 of 342 new or added lines in 15 files covered. (93.57%)

64452 of 73985 relevant lines covered (87.11%)

42544112.91 hits per line

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

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

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

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

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

37
namespace openmc {
38

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

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

47
namespace {
48

49
//! Temperature in [K] to report for a plot pixel
50
//
51
//! Where a temperature field covers the position, the field takes precedence
52
//! over the cell/material temperature carried by the particle, matching how
53
//! temperatures are resolved during transport. Positions outside the field
54
//! mesh fall back to the particle's own temperature.
55
double plot_temperature(const Particle& p)
2,774,356 ✔
56
{
57
  double sqrtkT = p.sqrtkT();
2,774,356 ✔
58
  if (settings::temperature_field_on) {
2,774,356 ✔
59
    int bin = simulation::temperature_field.get_bin(p.r());
200 ✔
60
    if (bin != C_NONE)
200 !
61
      sqrtkT = simulation::temperature_field.get_sqrtkT(bin);
200 ✔
62
  }
63
  return (sqrtkT * sqrtkT) / K_BOLTZMANN;
2,774,356 ✔
64
}
65

66
} // namespace
67

68
IdData::IdData(size_t h_res, size_t v_res, bool /*include_filter*/)
3,544 ✔
69
  : data_({v_res, h_res, 3}, NOT_FOUND)
3,544 ✔
70
{}
3,544 ✔
71

72
void IdData::set_value(size_t y, size_t x, const Particle& p, int level,
25,747,776 ✔
73
  Filter* /*filter*/, FilterMatch* /*match*/)
74
{
75
  // set cell data
76
  if (p.n_coord() <= level) {
25,747,776 !
77
    data_(y, x, 0) = NOT_FOUND;
×
78
    data_(y, x, 1) = NOT_FOUND;
×
79
  } else {
80
    data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
25,747,776 !
81
    data_(y, x, 1) = level == p.n_coord() - 1
25,747,776 ✔
82
                       ? p.cell_instance()
25,747,776 !
83
                       : cell_instance_at_level(p, level);
×
84
  }
85

86
  // set material data
87
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
25,747,776 ✔
88
  if (p.material() == MATERIAL_VOID) {
25,747,776 ✔
89
    data_(y, x, 2) = MATERIAL_VOID;
19,855,808 ✔
90
  } else if (c->type_ == Fill::MATERIAL) {
5,891,968 !
91
    Material* m = model::materials.at(p.material()).get();
5,891,968 ✔
92
    data_(y, x, 2) = m->id_;
5,891,968 ✔
93
  }
94
}
25,747,776 ✔
95

96
void IdData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
20,544 ✔
97
{
98
  for (size_t k = 0; k < data_.shape(2); ++k)
164,352 !
99
    data_(y, x, k) = OVERLAP;
61,632 ✔
100
}
20,544 ✔
101

102
PropertyData::PropertyData(size_t h_res, size_t v_res, bool /*include_filter*/)
×
103
  : data_({v_res, h_res, 2}, NOT_FOUND)
×
104
{}
×
105

106
void PropertyData::set_value(size_t y, size_t x, const Particle& p, int level,
×
107
  Filter* /*filter*/, FilterMatch* /*match*/)
108
{
109
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
×
NEW
110
  data_(y, x, 0) = plot_temperature(p);
×
111
  data_(y, x, 1) = c->density(p.cell_instance());
×
112
}
×
113

114
void PropertyData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
×
115
{
116
  data_(y, x) = OVERLAP;
×
117
}
×
118

119
//==============================================================================
120
// RasterData implementation
121
//==============================================================================
122

123
RasterData::RasterData(size_t h_res, size_t v_res, bool include_filter)
691 ✔
124
  : id_data_({v_res, h_res, include_filter ? 4u : 3u}, NOT_FOUND),
1,366 ✔
125
    property_data_({v_res, h_res, 2}, static_cast<double>(NOT_FOUND)),
691 ✔
126
    include_filter_(include_filter)
691 ✔
127
{}
691 ✔
128

129
void RasterData::set_value(size_t y, size_t x, const Particle& p, int level,
2,774,356 ✔
130
  Filter* filter, FilterMatch* match)
131
{
132
  // set cell data
133
  if (p.n_coord() <= level) {
2,774,356 !
134
    id_data_(y, x, 0) = NOT_FOUND;
×
135
    id_data_(y, x, 1) = NOT_FOUND;
×
136
  } else {
137
    id_data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
2,774,356 !
138
    id_data_(y, x, 1) = level == p.n_coord() - 1
2,774,356 ✔
139
                          ? p.cell_instance()
2,774,356 !
140
                          : cell_instance_at_level(p, level);
×
141
  }
142

143
  // set material data
144
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
2,774,356 ✔
145
  if (p.material() == MATERIAL_VOID) {
2,774,356 ✔
146
    id_data_(y, x, 2) = MATERIAL_VOID;
1,893,952 ✔
147
  } else if (c->type_ == Fill::MATERIAL) {
880,404 !
148
    Material* m = model::materials.at(p.material()).get();
880,404 ✔
149
    id_data_(y, x, 2) = m->id_;
880,404 ✔
150
  }
151

152
  // set filter index (only if filter is being used)
153
  if (include_filter_ && filter) {
2,774,356 !
154
    filter->get_all_bins(p, TallyEstimator::COLLISION, *match);
40,000 ✔
155
    if (match->bins_.empty()) {
40,000 !
156
      id_data_(y, x, 3) = -1;
×
157
    } else {
158
      id_data_(y, x, 3) = match->bins_[0];
40,000 ✔
159
    }
160
    match->bins_.clear();
40,000 !
161
    match->weights_.clear();
40,000 !
162
  }
163

164
  // set temperature (in K)
165
  property_data_(y, x, 0) = plot_temperature(p);
2,774,356 ✔
166

167
  // set density (g/cm³)
168
  if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) {
2,774,356 !
169
    property_data_(y, x, 1) = c->density(p.cell_instance());
880,404 ✔
170
  }
171
}
2,774,356 ✔
172

173
void RasterData::set_overlap(size_t y, size_t x, int overlap_idx)
266,032 ✔
174
{
175
  // Set cell, instance, and material to OVERLAP, but preserve filter bin for
176
  // tally plotting. Cell encodes the overlap index as a negative number so that
177
  // it can be used to look up overlap information in the plotter.
178
  id_data_(y, x, 0) = OVERLAP - overlap_idx - 1;
266,032 ✔
179
  id_data_(y, x, 1) = OVERLAP;
266,032 ✔
180
  id_data_(y, x, 2) = OVERLAP;
266,032 ✔
181

182
  property_data_(y, x, 0) = OVERLAP;
266,032 ✔
183
  property_data_(y, x, 1) = OVERLAP;
266,032 ✔
184
}
266,032 ✔
185

186
//==============================================================================
187
// Global variables
188
//==============================================================================
189

190
namespace model {
191

192
std::unordered_map<int, int> plot_map;
193
vector<std::unique_ptr<PlottableInterface>> plots;
194
uint64_t plotter_seed = 1;
195

196
} // namespace model
197

198
//==============================================================================
199
// RUN_PLOT controls the logic for making one or many plots
200
//==============================================================================
201

202
extern "C" int openmc_plot_geometry()
88 ✔
203
{
204

205
  for (auto& pl : model::plots) {
296 ✔
206
    write_message(5, "Processing plot {}: {}...", pl->id(), pl->path_plot());
208 ✔
207
    pl->create_output();
208 ✔
208
  }
209

210
  return 0;
88 ✔
211
}
212

213
void PlottableInterface::write_image(const ImageData& data) const
168 ✔
214
{
215
#ifdef USE_LIBPNG
216
  output_png(path_plot(), data);
168 ✔
217
#else
218
  output_ppm(path_plot(), data);
219
#endif
220
}
168 ✔
221

222
void Plot::create_output() const
144 ✔
223
{
224
  if (PlotType::slice == type_) {
144 ✔
225
    // create 2D image
226
    ImageData image = create_image();
104 ✔
227
    write_image(image);
104 ✔
228
  } else if (PlotType::voxel == type_) {
144 !
229
    // create voxel file for 3D viewing
230
    create_voxel();
40 ✔
231
  }
232
}
144 ✔
233

234
void Plot::print_info() const
144 ✔
235
{
236
  // Plot type
237
  if (PlotType::slice == type_) {
144 ✔
238
    fmt::print("Plot Type: Slice\n");
88 ✔
239
  } else if (PlotType::voxel == type_) {
56 !
240
    fmt::print("Plot Type: Voxel\n");
56 ✔
241
  }
242

243
  // Plot parameters
244
  fmt::print("Origin: {} {} {}\n", origin_[0], origin_[1], origin_[2]);
144 ✔
245

246
  if (PlotType::slice == type_) {
144 ✔
247
    fmt::print("Width: {:4} {:4}\n", width_[0], width_[1]);
88 ✔
248
  } else if (PlotType::voxel == type_) {
56 !
249
    fmt::print("Width: {:4} {:4} {:4}\n", width_[0], width_[1], width_[2]);
56 ✔
250
  }
251

252
  if (PlotColorBy::cells == color_by_) {
144 ✔
253
    fmt::print("Coloring: Cells\n");
96 ✔
254
  } else if (PlotColorBy::mats == color_by_) {
48 !
255
    fmt::print("Coloring: Materials\n");
48 ✔
256
  }
257

258
  if (PlotType::slice == type_) {
144 ✔
259
    switch (basis_) {
88 !
260
    case PlotBasis::xy:
56 ✔
261
      fmt::print("Basis: XY\n");
56 ✔
262
      break;
56 ✔
263
    case PlotBasis::xz:
16 ✔
264
      fmt::print("Basis: XZ\n");
16 ✔
265
      break;
16 ✔
266
    case PlotBasis::yz:
16 ✔
267
      fmt::print("Basis: YZ\n");
16 ✔
268
      break;
16 ✔
269
    }
270
    fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
88 ✔
271
  } else if (PlotType::voxel == type_) {
56 !
272
    fmt::print("Voxels: {} {} {}\n", pixels()[0], pixels()[1], pixels()[2]);
56 ✔
273
  }
274
}
144 ✔
275

276
void read_plots_xml()
1,011 ✔
277
{
278
  // Check if plots.xml exists; this is only necessary when the plot runmode is
279
  // initiated. Otherwise, we want to read plots.xml because it may be called
280
  // later via the API. In that case, its ok for a plots.xml to not exist
281
  std::string filename = settings::path_input + "plots.xml";
1,011 ✔
282
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
1,011 !
283
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
284
  }
285

286
  write_message("Reading plot XML file...", 5);
1,011 ✔
287

288
  // Parse plots.xml file
289
  pugi::xml_document doc;
1,011 ✔
290
  doc.load_file(filename.c_str());
1,011 ✔
291

292
  pugi::xml_node root = doc.document_element();
1,011 ✔
293

294
  read_plots_xml(root);
1,011 ✔
295
}
1,011 ✔
296

297
void read_plots_xml(pugi::xml_node root)
1,444 ✔
298
{
299
  for (auto node : root.children("plot")) {
2,224 ✔
300
    std::string plot_desc = "<auto>";
787 ✔
301
    if (check_for_node(node, "id")) {
787 !
302
      plot_desc = get_node_value(node, "id", true);
787 ✔
303
    }
304

305
    if (check_for_node(node, "type")) {
787 !
306
      std::string type_str = get_node_value(node, "type", true);
787 ✔
307
      if (type_str == "slice") {
787 ✔
308
        model::plots.emplace_back(
636 ✔
309
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,279 ✔
310
      } else if (type_str == "voxel") {
144 ✔
311
        model::plots.emplace_back(
80 ✔
312
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
160 ✔
313
      } else if (type_str == "wireframe_raytrace") {
64 ✔
314
        model::plots.emplace_back(
40 ✔
315
          std::make_unique<WireframeRayTracePlot>(node));
80 ✔
316
      } else if (type_str == "solid_raytrace") {
24 !
317
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
24 ✔
318
      } else {
319
        fatal_error(fmt::format(
×
320
          "Unsupported plot type '{}' in plot {}", type_str, plot_desc));
321
      }
322
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
780 ✔
323
    } else {
780 ✔
324
      fatal_error(fmt::format("Must specify plot type in plot {}", plot_desc));
×
325
    }
326
  }
780 ✔
327
}
1,437 ✔
328

329
void free_memory_plot()
7,152 ✔
330
{
331
  model::plots.clear();
7,152 ✔
332
  model::plot_map.clear();
7,152 ✔
333
}
7,152 ✔
334

335
// creates an image based on user input from a plots.xml <plot>
336
// specification in the PNG/PPM format
337
ImageData Plot::create_image() const
104 ✔
338
{
339
  size_t width = pixels()[0];
104 ✔
340
  size_t height = pixels()[1];
104 ✔
341

342
  ImageData data({width, height}, not_found_);
104 ✔
343

344
  // generate ids for the plot
345
  auto ids = get_map<IdData>();
104 ✔
346

347
  // assign colors
348
  for (size_t y = 0; y < height; y++) {
21,864 ✔
349
    for (size_t x = 0; x < width; x++) {
5,543,360 ✔
350
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
5,521,600 ✔
351
      auto id = ids.data_(y, x, idx);
5,521,600 ✔
352
      // no setting needed if not found
353
      if (id == NOT_FOUND) {
5,521,600 ✔
354
        continue;
787,296 ✔
355
      }
356
      if (id == OVERLAP) {
4,754,848 ✔
357
        data(x, y) = overlap_color_;
20,544 ✔
358
        continue;
20,544 ✔
359
      }
360
      if (PlotColorBy::cells == color_by_) {
4,734,304 ✔
361
        data(x, y) = colors_[model::cell_map[id]];
2,190,304 ✔
362
      } else if (PlotColorBy::mats == color_by_) {
2,544,000 !
363
        if (id == MATERIAL_VOID) {
2,544,000 !
364
          data(x, y) = WHITE;
×
365
          continue;
×
366
        }
367
        data(x, y) = colors_[model::material_map[id]];
2,544,000 ✔
368
      } // color_by if-else
369
    }
370
  }
371

372
  // draw mesh lines if present
373
  if (index_meshlines_mesh_ >= 0) {
104 ✔
374
    draw_mesh_lines(data);
24 ✔
375
  }
376

377
  return data;
104 ✔
378
}
104 ✔
379

380
void PlottableInterface::set_id(pugi::xml_node plot_node)
787 ✔
381
{
382
  int id {C_NONE};
787 ✔
383
  if (check_for_node(plot_node, "id")) {
787 !
384
    id = std::stoi(get_node_value(plot_node, "id"));
787 ✔
385
  }
386

387
  try {
787 ✔
388
    set_id(id);
787 ✔
389
  } catch (const std::runtime_error& e) {
×
390
    fatal_error(e.what());
×
391
  }
×
392
}
787 ✔
393

394
void PlottableInterface::set_id(int id)
795 ✔
395
{
396
  if (id < 0 && id != C_NONE) {
795 !
397
    throw std::runtime_error {fmt::format("Invalid plot ID: {}", id)};
×
398
  }
399

400
  if (id == C_NONE) {
795 ✔
401
    id = 1;
8 ✔
402
    for (const auto& p : model::plots) {
16 ✔
403
      id = std::max(id, p->id() + 1);
16 !
404
    }
405
  }
406

407
  if (id_ == id)
795 !
408
    return;
409

410
  // Check to make sure this ID doesn't already exist
411
  if (model::plot_map.find(id) != model::plot_map.end()) {
795 !
412
    throw std::runtime_error {
×
413
      fmt::format("Two or more plots use the same unique ID: {}", id)};
×
414
  }
415

416
  id_ = id;
795 ✔
417
}
418

419
// Checks if png or ppm is already present
420
bool file_extension_present(
780 ✔
421
  const std::string& filename, const std::string& extension)
422
{
423
  std::string file_extension_if_present =
780 ✔
424
    filename.substr(filename.find_last_of(".") + 1);
780 ✔
425
  if (file_extension_if_present == extension)
780 ✔
426
    return true;
40 ✔
427
  return false;
428
}
780 ✔
429

430
void Plot::set_output_path(pugi::xml_node plot_node)
723 ✔
431
{
432
  // Set output file path
433
  std::string filename;
723 ✔
434

435
  if (check_for_node(plot_node, "filename")) {
723 ✔
436
    filename = get_node_value(plot_node, "filename");
171 ✔
437
  } else {
438
    filename = fmt::format("plot_{}", id());
552 ✔
439
  }
440
  const std::string dir_if_present =
723 ✔
441
    filename.substr(0, filename.find_last_of("/") + 1);
723 ✔
442
  if (dir_if_present.size() > 0 && !dir_exists(dir_if_present)) {
723 ✔
443
    fatal_error(fmt::format("Directory '{}' does not exist!", dir_if_present));
7 ✔
444
  }
445
  // add appropriate file extension to name
446
  switch (type_) {
716 !
447
  case PlotType::slice:
636 ✔
448
#ifdef USE_LIBPNG
449
    if (!file_extension_present(filename, "png"))
636 !
450
      filename.append(".png");
636 ✔
451
#else
452
    if (!file_extension_present(filename, "ppm"))
453
      filename.append(".ppm");
454
#endif
455
    break;
456
  case PlotType::voxel:
80 ✔
457
    if (!file_extension_present(filename, "h5"))
80 !
458
      filename.append(".h5");
80 ✔
459
    break;
460
  }
461

462
  path_plot_ = filename;
716 ✔
463

464
  // Copy plot pixel size
465
  vector<int> pxls = get_node_array<int>(plot_node, "pixels");
1,432 ✔
466
  if (PlotType::slice == type_) {
716 ✔
467
    if (pxls.size() == 2) {
636 !
468
      pixels()[0] = pxls[0];
636 ✔
469
      pixels()[1] = pxls[1];
636 ✔
470
    } else {
471
      fatal_error(
×
472
        fmt::format("<pixels> must be length 2 in slice plot {}", id()));
×
473
    }
474
  } else if (PlotType::voxel == type_) {
80 !
475
    if (pxls.size() == 3) {
80 !
476
      pixels()[0] = pxls[0];
80 ✔
477
      pixels()[1] = pxls[1];
80 ✔
478
      pixels()[2] = pxls[2];
80 ✔
479
    } else {
480
      fatal_error(
×
481
        fmt::format("<pixels> must be length 3 in voxel plot {}", id()));
×
482
    }
483
  }
484
}
716 ✔
485

486
void PlottableInterface::set_bg_color(pugi::xml_node plot_node)
787 ✔
487
{
488
  // Copy plot background color
489
  if (check_for_node(plot_node, "background")) {
787 ✔
490
    vector<int> bg_rgb = get_node_array<int>(plot_node, "background");
32 ✔
491
    if (bg_rgb.size() == 3) {
32 !
492
      not_found_ = bg_rgb;
32 ✔
493
    } else {
494
      fatal_error(fmt::format("Bad background RGB in plot {}", id()));
×
495
    }
496
  }
32 ✔
497
}
787 ✔
498

499
void Plot::set_basis(pugi::xml_node plot_node)
716 ✔
500
{
501
  // Copy plot basis
502
  if (PlotType::slice == type_) {
716 ✔
503
    std::string pl_basis = "xy";
636 ✔
504
    if (check_for_node(plot_node, "basis")) {
636 !
505
      pl_basis = get_node_value(plot_node, "basis", true);
636 ✔
506
    }
507
    if ("xy" == pl_basis) {
636 ✔
508
      basis_ = PlotBasis::xy;
584 ✔
509
    } else if ("xz" == pl_basis) {
52 ✔
510
      basis_ = PlotBasis::xz;
16 ✔
511
    } else if ("yz" == pl_basis) {
36 !
512
      basis_ = PlotBasis::yz;
36 ✔
513
    } else {
514
      fatal_error(
×
515
        fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id()));
×
516
    }
517
  }
636 ✔
518
}
716 ✔
519

520
void Plot::set_origin(pugi::xml_node plot_node)
716 ✔
521
{
522
  // Copy plotting origin
523
  auto pl_origin = get_node_array<double>(plot_node, "origin");
716 ✔
524
  if (pl_origin.size() == 3) {
716 !
525
    origin_ = pl_origin;
716 ✔
526
  } else {
527
    fatal_error(fmt::format("Origin must be length 3 in plot {}", id()));
×
528
  }
529
}
716 ✔
530

531
void Plot::set_width(pugi::xml_node plot_node)
716 ✔
532
{
533
  // Copy plotting width
534
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
716 ✔
535
  if (PlotType::slice == type_) {
716 ✔
536
    if (pl_width.size() == 2) {
636 !
537
      width_.x = pl_width[0];
636 ✔
538
      width_.y = pl_width[1];
636 ✔
539
      switch (basis_) {
636 !
540
      case PlotBasis::xy:
584 ✔
541
        u_span_ = {width_.x, 0.0, 0.0};
584 ✔
542
        v_span_ = {0.0, width_.y, 0.0};
584 ✔
543
        break;
584 ✔
544
      case PlotBasis::xz:
16 ✔
545
        u_span_ = {width_.x, 0.0, 0.0};
16 ✔
546
        v_span_ = {0.0, 0.0, width_.y};
16 ✔
547
        break;
16 ✔
548
      case PlotBasis::yz:
36 ✔
549
        u_span_ = {0.0, width_.x, 0.0};
36 ✔
550
        v_span_ = {0.0, 0.0, width_.y};
36 ✔
551
        break;
36 ✔
552
      default:
×
553
        UNREACHABLE();
×
554
      }
555
    } else {
556
      fatal_error(
×
557
        fmt::format("<width> must be length 2 in slice plot {}", id()));
×
558
    }
559
  } else if (PlotType::voxel == type_) {
80 !
560
    if (pl_width.size() == 3) {
80 !
561
      pl_width = get_node_array<double>(plot_node, "width");
160 ✔
562
      width_ = pl_width;
80 ✔
563
    } else {
564
      fatal_error(
×
565
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
566
    }
567
  }
568
}
716 ✔
569

570
void PlottableInterface::set_universe(pugi::xml_node plot_node)
787 ✔
571
{
572
  // Copy plot universe level
573
  if (check_for_node(plot_node, "level")) {
787 !
574
    level_ = std::stoi(get_node_value(plot_node, "level"));
×
575
    if (level_ < 0) {
×
576
      fatal_error(fmt::format("Bad universe level in plot {}", id()));
×
577
    }
578
  } else {
579
    level_ = PLOT_LEVEL_LOWEST;
787 ✔
580
  }
581
}
787 ✔
582

583
void PlottableInterface::set_color_by(pugi::xml_node plot_node)
787 ✔
584
{
585
  // Copy plot color type
586
  std::string pl_color_by = "cell";
787 ✔
587
  if (check_for_node(plot_node, "color_by")) {
787 ✔
588
    pl_color_by = get_node_value(plot_node, "color_by", true);
763 ✔
589
  }
590
  if ("cell" == pl_color_by) {
787 ✔
591
    color_by_ = PlotColorBy::cells;
246 ✔
592
  } else if ("material" == pl_color_by) {
541 !
593
    color_by_ = PlotColorBy::mats;
541 ✔
594
  } else {
595
    fatal_error(fmt::format(
×
596
      "Unsupported plot color type '{}' in plot {}", pl_color_by, id()));
×
597
  }
598
}
787 ✔
599

600
void PlottableInterface::set_default_colors()
795 ✔
601
{
602
  // Copy plot color type and initialize all colors randomly
603
  if (PlotColorBy::cells == color_by_) {
795 ✔
604
    colors_.resize(model::cells.size());
246 ✔
605
  } else if (PlotColorBy::mats == color_by_) {
549 !
606
    colors_.resize(model::materials.size());
549 ✔
607
  }
608

609
  for (auto& c : colors_) {
3,818 ✔
610
    c = random_color();
3,023 ✔
611
    // make sure we don't interfere with some default colors
612
    while (c == RED || c == WHITE) {
3,023 !
613
      c = random_color();
×
614
    }
615
  }
616
}
795 ✔
617

618
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
787 ✔
619
{
620
  for (auto cn : plot_node.children("color")) {
923 ✔
621
    // Make sure 3 values are specified for RGB
622
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
136 ✔
623
    if (user_rgb.size() != 3) {
136 !
624
      fatal_error(fmt::format("Bad RGB in plot {}", id()));
×
625
    }
626
    // Ensure that there is an id for this color specification
627
    int col_id;
136 ✔
628
    if (check_for_node(cn, "id")) {
136 !
629
      col_id = std::stoi(get_node_value(cn, "id"));
272 ✔
630
    } else {
631
      fatal_error(fmt::format(
×
632
        "Must specify id for color specification in plot {}", id()));
×
633
    }
634
    // Add RGB
635
    if (PlotColorBy::cells == color_by_) {
136 ✔
636
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
64 !
637
        col_id = model::cell_map[col_id];
64 ✔
638
        colors_[col_id] = user_rgb;
64 ✔
639
      } else {
640
        warning(fmt::format(
×
641
          "Could not find cell {} specified in plot {}", col_id, id()));
×
642
      }
643
    } else if (PlotColorBy::mats == color_by_) {
72 !
644
      if (model::material_map.find(col_id) != model::material_map.end()) {
72 !
645
        col_id = model::material_map[col_id];
72 ✔
646
        colors_[col_id] = user_rgb;
72 ✔
647
      } else {
648
        warning(fmt::format(
×
649
          "Could not find material {} specified in plot {}", col_id, id()));
×
650
      }
651
    }
652
  } // color node loop
136 ✔
653
}
787 ✔
654

655
void Plot::set_meshlines(pugi::xml_node plot_node)
716 ✔
656
{
657
  // Deal with meshlines
658
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
716 ✔
659

660
  if (!mesh_line_nodes.empty()) {
716 ✔
661
    if (PlotType::voxel == type_) {
24 !
662
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
663
    }
664

665
    if (mesh_line_nodes.size() == 1) {
24 !
666
      // Get first meshline node
667
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
24 ✔
668

669
      // Check mesh type
670
      std::string meshtype;
24 ✔
671
      if (check_for_node(meshlines_node, "meshtype")) {
24 !
672
        meshtype = get_node_value(meshlines_node, "meshtype");
24 ✔
673
      } else {
674
        fatal_error(fmt::format(
×
675
          "Must specify a meshtype for meshlines specification in plot {}",
676
          id()));
×
677
      }
678

679
      // Ensure that there is a linewidth for this meshlines specification
680
      std::string meshline_width;
24 ✔
681
      if (check_for_node(meshlines_node, "linewidth")) {
24 !
682
        meshline_width = get_node_value(meshlines_node, "linewidth");
24 ✔
683
        meshlines_width_ = std::stoi(meshline_width);
24 ✔
684
      } else {
685
        fatal_error(fmt::format(
×
686
          "Must specify a linewidth for meshlines specification in plot {}",
687
          id()));
×
688
      }
689

690
      // Check for color
691
      if (check_for_node(meshlines_node, "color")) {
24 !
692
        // Check and make sure 3 values are specified for RGB
693
        vector<int> ml_rgb = get_node_array<int>(meshlines_node, "color");
×
694
        if (ml_rgb.size() != 3) {
×
695
          fatal_error(
×
696
            fmt::format("Bad RGB for meshlines color in plot {}", id()));
×
697
        }
698
        meshlines_color_ = ml_rgb;
×
699
      }
×
700

701
      // Set mesh based on type
702
      if ("ufs" == meshtype) {
24 !
703
        if (!simulation::ufs_mesh) {
×
704
          fatal_error(
×
705
            fmt::format("No UFS mesh for meshlines on plot {}", id()));
×
706
        } else {
707
          for (int i = 0; i < model::meshes.size(); ++i) {
×
708
            if (const auto* m =
×
709
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
×
710
              if (m == simulation::ufs_mesh) {
×
711
                index_meshlines_mesh_ = i;
×
712
              }
713
            }
714
          }
715
          if (index_meshlines_mesh_ == -1)
×
716
            fatal_error("Could not find the UFS mesh for meshlines plot");
×
717
        }
718
      } else if ("entropy" == meshtype) {
24 ✔
719
        if (!simulation::entropy_mesh) {
16 !
720
          fatal_error(
×
721
            fmt::format("No entropy mesh for meshlines on plot {}", id()));
×
722
        } else {
723
          for (int i = 0; i < model::meshes.size(); ++i) {
40 ✔
724
            if (const auto* m =
48 ✔
725
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
40 !
726
              if (m == simulation::entropy_mesh) {
16 !
727
                index_meshlines_mesh_ = i;
16 ✔
728
              }
729
            }
730
          }
731
          if (index_meshlines_mesh_ == -1)
16 !
732
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
733
        }
734
      } else if ("tally" == meshtype) {
8 !
735
        // Ensure that there is a mesh id if the type is tally
736
        int tally_mesh_id;
8 ✔
737
        if (check_for_node(meshlines_node, "id")) {
8 !
738
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
16 ✔
739
        } else {
740
          std::stringstream err_msg;
×
741
          fatal_error(fmt::format("Must specify a mesh id for meshlines tally "
×
742
                                  "mesh specification in plot {}",
743
            id()));
×
744
        }
×
745
        // find the tally index
746
        int idx;
8 ✔
747
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
8 ✔
748
        if (err != 0) {
8 !
749
          fatal_error(fmt::format("Could not find mesh {} specified in "
×
750
                                  "meshlines for plot {}",
751
            tally_mesh_id, id()));
×
752
        }
753
        index_meshlines_mesh_ = idx;
8 ✔
754
      } else {
755
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
756
      }
757
    } else {
24 ✔
758
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
759
    }
760
  }
761
}
716 ✔
762

763
void PlottableInterface::set_mask(pugi::xml_node plot_node)
787 ✔
764
{
765
  // Deal with masks
766
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
787 ✔
767

768
  if (!mask_nodes.empty()) {
787 ✔
769
    if (mask_nodes.size() == 1) {
24 !
770
      // Get pointer to mask
771
      pugi::xml_node mask_node = mask_nodes[0].node();
24 ✔
772

773
      // Determine how many components there are and allocate
774
      vector<int> iarray = get_node_array<int>(mask_node, "components");
24 ✔
775
      if (iarray.size() == 0) {
24 !
776
        fatal_error(
×
777
          fmt::format("Missing <components> in mask of plot {}", id()));
×
778
      }
779

780
      // First we need to change the user-specified identifiers to indices
781
      // in the cell and material arrays
782
      for (auto& col_id : iarray) {
72 ✔
783
        if (PlotColorBy::cells == color_by_) {
48 !
784
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
48 !
785
            col_id = model::cell_map[col_id];
48 ✔
786
          } else {
787
            fatal_error(fmt::format("Could not find cell {} specified in the "
×
788
                                    "mask in plot {}",
789
              col_id, id()));
×
790
          }
791
        } else if (PlotColorBy::mats == color_by_) {
×
792
          if (model::material_map.find(col_id) != model::material_map.end()) {
×
793
            col_id = model::material_map[col_id];
×
794
          } else {
795
            fatal_error(fmt::format("Could not find material {} specified in "
×
796
                                    "the mask in plot {}",
797
              col_id, id()));
×
798
          }
799
        }
800
      }
801

802
      // Alter colors based on mask information
803
      for (int j = 0; j < colors_.size(); j++) {
96 ✔
804
        if (contains(iarray, j)) {
72 ✔
805
          if (check_for_node(mask_node, "background")) {
48 !
806
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
48 ✔
807
            colors_[j] = bg_rgb;
48 ✔
808
          } else {
48 ✔
809
            colors_[j] = WHITE;
×
810
          }
811
        }
812
      }
813

814
    } else {
24 ✔
815
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
816
    }
817
  }
818
}
787 ✔
819

820
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
787 ✔
821
{
822
  color_overlaps_ = false;
787 ✔
823
  if (check_for_node(plot_node, "show_overlaps")) {
787 ✔
824
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
16 ✔
825
    // check for custom overlap color
826
    if (check_for_node(plot_node, "overlap_color")) {
16 ✔
827
      if (!color_overlaps_) {
8 !
828
        warning(fmt::format(
×
829
          "Overlap color specified in plot {} but overlaps won't be shown.",
830
          id()));
×
831
      }
832
      vector<int> olap_clr = get_node_array<int>(plot_node, "overlap_color");
8 ✔
833
      if (olap_clr.size() == 3) {
8 !
834
        overlap_color_ = olap_clr;
8 ✔
835
      } else {
836
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
837
      }
838
    }
8 ✔
839
  }
840

841
  // make sure we allocate the vector for counting overlap checks if
842
  // they're going to be plotted
843
  if (color_overlaps_ && settings::run_mode == RunMode::PLOTTING) {
787 !
844
    settings::check_overlaps = true;
16 ✔
845
    model::overlap_check_count.resize(model::cells.size(), 0);
16 ✔
846
  }
847
}
787 ✔
848

849
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
787 ✔
850
{
851
  set_id(plot_node);
787 ✔
852
  set_bg_color(plot_node);
787 ✔
853
  set_universe(plot_node);
787 ✔
854
  set_color_by(plot_node);
787 ✔
855
  set_default_colors();
787 ✔
856
  set_user_colors(plot_node);
787 ✔
857
  set_mask(plot_node);
787 ✔
858
  set_overlap_color(plot_node);
787 ✔
859
}
787 ✔
860

861
Plot::Plot(pugi::xml_node plot_node, PlotType type)
723 ✔
862
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
723 ✔
863
{
864
  set_output_path(plot_node);
723 ✔
865
  set_basis(plot_node);
716 ✔
866
  set_origin(plot_node);
716 ✔
867
  set_width(plot_node);
716 ✔
868
  set_meshlines(plot_node);
716 ✔
869
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
716 ✔
870
  show_overlaps_ = color_overlaps_;
716 ✔
871
}
716 ✔
872

873
//==============================================================================
874
// OUTPUT_PPM writes out a previously generated image to a PPM file
875
//==============================================================================
876

877
void output_ppm(const std::string& filename, const ImageData& data)
×
878
{
879
  // Open PPM file for writing
880
  std::string fname = filename;
×
881
  fname = strtrim(fname);
×
882
  std::ofstream of;
×
883

884
  of.open(fname);
×
885

886
  // Write header
887
  of << "P6\n";
×
888
  of << data.shape(0) << " " << data.shape(1) << "\n";
×
889
  of << "255\n";
×
890
  of.close();
×
891

892
  of.open(fname, std::ios::binary | std::ios::app);
×
893
  // Write color for each pixel
894
  for (int y = 0; y < data.shape(1); y++) {
×
895
    for (int x = 0; x < data.shape(0); x++) {
×
896
      RGBColor rgb = data(x, y);
×
897
      of << rgb.red << rgb.green << rgb.blue;
×
898
    }
899
  }
900
  of << "\n";
×
901
}
×
902

903
//==============================================================================
904
// OUTPUT_PNG writes out a previously generated image to a PNG file
905
//==============================================================================
906

907
#ifdef USE_LIBPNG
908
void output_png(const std::string& filename, const ImageData& data)
168 ✔
909
{
910
  // Open PNG file for writing
911
  std::string fname = filename;
168 ✔
912
  fname = strtrim(fname);
168 ✔
913
  auto fp = std::fopen(fname.c_str(), "wb");
168 ✔
914

915
  // Initialize write and info structures
916
  auto png_ptr =
168 ✔
917
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
168 ✔
918
  auto info_ptr = png_create_info_struct(png_ptr);
168 ✔
919

920
  // Setup exception handling
921
  if (setjmp(png_jmpbuf(png_ptr)))
168 !
922
    fatal_error("Error during png creation");
×
923

924
  png_init_io(png_ptr, fp);
168 ✔
925

926
  // Write header (8 bit colour depth)
927
  int width = data.shape(0);
168 !
928
  int height = data.shape(1);
168 !
929
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB,
168 ✔
930
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
931
  png_write_info(png_ptr, info_ptr);
168 ✔
932

933
  // Allocate memory for one row (3 bytes per pixel - RGB)
934
  std::vector<png_byte> row(3 * width);
168 ✔
935

936
  // Write color for each pixel
937
  for (int y = 0; y < height; y++) {
34,728 ✔
938
    for (int x = 0; x < width; x++) {
8,116,160 ✔
939
      RGBColor rgb = data(x, y);
8,081,600 ✔
940
      row[3 * x] = rgb.red;
8,081,600 ✔
941
      row[3 * x + 1] = rgb.green;
8,081,600 ✔
942
      row[3 * x + 2] = rgb.blue;
8,081,600 ✔
943
    }
944
    png_write_row(png_ptr, row.data());
34,560 ✔
945
  }
946

947
  // End write
948
  png_write_end(png_ptr, nullptr);
168 ✔
949

950
  // Clean up data structures
951
  std::fclose(fp);
168 ✔
952
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
168 ✔
953
  png_destroy_write_struct(&png_ptr, &info_ptr);
168 ✔
954
}
168 ✔
955
#endif
956

957
//==============================================================================
958
// DRAW_MESH_LINES draws mesh line boundaries on an image
959
//==============================================================================
960

961
void Plot::draw_mesh_lines(ImageData& data) const
24 ✔
962
{
963
  RGBColor rgb;
24 !
964
  rgb = meshlines_color_;
24 ✔
965

966
  int ax1, ax2;
24 ✔
967
  Position expected_u {};
24 ✔
968
  Position expected_v {};
24 ✔
969
  switch (basis_) {
24 !
970
  case PlotBasis::xy:
16 ✔
971
    ax1 = 0;
16 ✔
972
    ax2 = 1;
16 ✔
973
    expected_u = {width_[0], 0.0, 0.0};
16 ✔
974
    expected_v = {0.0, width_[1], 0.0};
16 ✔
975
    break;
16 ✔
976
  case PlotBasis::xz:
8 ✔
977
    ax1 = 0;
8 ✔
978
    ax2 = 2;
8 ✔
979
    expected_u = {width_[0], 0.0, 0.0};
8 ✔
980
    expected_v = {0.0, 0.0, width_[1]};
8 ✔
981
    break;
8 ✔
982
  case PlotBasis::yz:
×
983
    ax1 = 1;
×
984
    ax2 = 2;
×
985
    expected_u = {0.0, width_[0], 0.0};
×
986
    expected_v = {0.0, 0.0, width_[1]};
×
987
    break;
×
988
  default:
×
989
    UNREACHABLE();
×
990
  }
991

992
  // Meshlines rely on axis-aligned indexing in global coordinates.
993
  constexpr double rel_tol {1e-12};
24 ✔
994
  double span_tol = rel_tol * (1.0 + u_span_.norm() + v_span_.norm());
24 ✔
995
  if ((u_span_ - expected_u).norm() > span_tol ||
48 !
996
      (v_span_ - expected_v).norm() > span_tol) {
24 ✔
997
    fatal_error("Meshlines are only supported for axis-aligned slice plots.");
×
998
  }
999

1000
  Position ll_plot {origin_};
24 ✔
1001
  Position ur_plot {origin_};
24 ✔
1002

1003
  ll_plot[ax1] -= width_[0] / 2.;
24 ✔
1004
  ll_plot[ax2] -= width_[1] / 2.;
24 ✔
1005
  ur_plot[ax1] += width_[0] / 2.;
24 ✔
1006
  ur_plot[ax2] += width_[1] / 2.;
24 ✔
1007

1008
  Position width = ur_plot - ll_plot;
24 ✔
1009

1010
  // Find the (axis-aligned) lines of the mesh that intersect this plot.
1011
  auto axis_lines =
24 ✔
1012
    model::meshes[index_meshlines_mesh_]->plot(ll_plot, ur_plot);
24 ✔
1013

1014
  // Find the bounds along the second axis (accounting for low-D meshes).
1015
  int ax2_min, ax2_max;
24 ✔
1016
  if (axis_lines.second.size() > 0) {
24 !
1017
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
24 ✔
1018
    ax2_min = (1.0 - frac) * pixels()[1];
24 ✔
1019
    if (ax2_min < 0)
24 ✔
1020
      ax2_min = 0;
1021
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
24 ✔
1022
    ax2_max = (1.0 - frac) * pixels()[1];
24 !
1023
    if (ax2_max > pixels()[1])
24 !
1024
      ax2_max = pixels()[1];
×
1025
  } else {
1026
    ax2_min = 0;
×
1027
    ax2_max = pixels()[1];
×
1028
  }
1029

1030
  // Iterate across the first axis and draw lines.
1031
  for (auto ax1_val : axis_lines.first) {
136 ✔
1032
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
112 ✔
1033
    int ax1_ind = frac * pixels()[0];
112 ✔
1034
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
18,144 ✔
1035
      for (int plus = 0; plus <= meshlines_width_; plus++) {
36,064 ✔
1036
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
18,032 !
1037
          data(ax1_ind + plus, ax2_ind) = rgb;
18,032 ✔
1038
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
18,032 !
1039
          data(ax1_ind - plus, ax2_ind) = rgb;
18,032 ✔
1040
      }
1041
    }
1042
  }
1043

1044
  // Find the bounds along the first axis.
1045
  int ax1_min, ax1_max;
24 ✔
1046
  if (axis_lines.first.size() > 0) {
24 !
1047
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
24 ✔
1048
    ax1_min = frac * pixels()[0];
24 ✔
1049
    if (ax1_min < 0)
24 ✔
1050
      ax1_min = 0;
1051
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
24 ✔
1052
    ax1_max = frac * pixels()[0];
24 !
1053
    if (ax1_max > pixels()[0])
24 !
1054
      ax1_max = pixels()[0];
×
1055
  } else {
1056
    ax1_min = 0;
×
1057
    ax1_max = pixels()[0];
×
1058
  }
1059

1060
  // Iterate across the second axis and draw lines.
1061
  for (auto ax2_val : axis_lines.second) {
152 ✔
1062
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
128 ✔
1063
    int ax2_ind = (1.0 - frac) * pixels()[1];
128 ✔
1064
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
20,608 ✔
1065
      for (int plus = 0; plus <= meshlines_width_; plus++) {
40,960 ✔
1066
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
20,480 !
1067
          data(ax1_ind, ax2_ind + plus) = rgb;
20,480 ✔
1068
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
20,480 !
1069
          data(ax1_ind, ax2_ind - plus) = rgb;
20,480 ✔
1070
      }
1071
    }
1072
  }
1073
}
24 ✔
1074

1075
/* outputs a binary file that can be input into silomesh for 3D geometry
1076
 * visualization.  It works the same way as create_image by dragging a particle
1077
 * across the geometry for the specified number of voxels. The first 3 int's in
1078
 * the binary are the number of x, y, and z voxels.  The next 3 double's are
1079
 * the widths of the voxels in the x, y, and z directions. The next 3 double's
1080
 * are the x, y, and z coordinates of the lower left point. Finally the binary
1081
 * is filled with entries of four int's each. Each 'row' in the binary contains
1082
 * four int's: 3 for x,y,z position and 1 for cell or material id.  For 1
1083
 * million voxels this produces a file of approximately 15MB.
1084
 */
1085
void Plot::create_voxel() const
40 ✔
1086
{
1087
  // compute voxel widths in each direction
1088
  array<double, 3> vox;
40 ✔
1089
  vox[0] = width_[0] / static_cast<double>(pixels()[0]);
40 ✔
1090
  vox[1] = width_[1] / static_cast<double>(pixels()[1]);
40 ✔
1091
  vox[2] = width_[2] / static_cast<double>(pixels()[2]);
40 ✔
1092

1093
  // initial particle position
1094
  Position ll = origin_ - width_ / 2.;
40 ✔
1095

1096
  // Open binary plot file for writing
1097
  std::ofstream of;
40 ✔
1098
  std::string fname = std::string(path_plot_);
40 ✔
1099
  fname = strtrim(fname);
40 ✔
1100
  hid_t file_id = file_open(fname, 'w');
40 ✔
1101

1102
  // write header info
1103
  write_attribute(file_id, "filetype", "voxel");
40 ✔
1104
  write_attribute(file_id, "version", VERSION_VOXEL);
40 ✔
1105
  write_attribute(file_id, "openmc_version", VERSION);
40 ✔
1106

1107
#ifdef GIT_SHA1
1108
  write_attribute(file_id, "git_sha1", GIT_SHA1);
1109
#endif
1110

1111
  // Write current date and time
1112
  write_attribute(file_id, "date_and_time", time_stamp().c_str());
80 ✔
1113
  array<int, 3> h5_pixels;
40 ✔
1114
  std::copy(pixels().begin(), pixels().end(), h5_pixels.begin());
40 ✔
1115
  write_attribute(file_id, "num_voxels", h5_pixels);
40 ✔
1116
  write_attribute(file_id, "voxel_width", vox);
40 ✔
1117
  write_attribute(file_id, "lower_left", ll);
40 ✔
1118

1119
  // Create dataset for voxel data -- note that the dimensions are reversed
1120
  // since we want the order in the file to be z, y, x
1121
  hsize_t dims[3];
40 ✔
1122
  dims[0] = pixels()[2];
40 ✔
1123
  dims[1] = pixels()[1];
40 ✔
1124
  dims[2] = pixels()[0];
40 ✔
1125
  hid_t dspace, dset, memspace;
40 ✔
1126
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
40 ✔
1127

1128
  SlicePlotBase pltbase;
40 ✔
1129
  pltbase.origin_ = origin_;
40 ✔
1130
  pltbase.u_span_ = {width_.x, 0.0, 0.0};
40 ✔
1131
  pltbase.v_span_ = {0.0, width_.y, 0.0};
40 ✔
1132
  pltbase.pixels() = pixels();
40 ✔
1133
  pltbase.show_overlaps_ = color_overlaps_;
40 ✔
1134

1135
  ProgressBar pb;
40 ✔
1136
  for (int z = 0; z < pixels()[2]; z++) {
3,480 ✔
1137
    // update z coordinate
1138
    pltbase.origin_.z = ll.z + z * vox[2];
3,440 ✔
1139

1140
    // generate ids using plotbase
1141
    IdData ids = pltbase.get_map<IdData>();
3,440 ✔
1142

1143
    // select only cell/material ID data and flip the y-axis
1144
    int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
3,440 !
1145
    // Extract 2D slice at index idx from 3D data
1146
    size_t rows = ids.data_.shape(0);
3,440 !
1147
    size_t cols = ids.data_.shape(1);
3,440 !
1148
    tensor::Tensor<int32_t> data_slice({rows, cols});
3,440 ✔
1149
    for (size_t r = 0; r < rows; ++r)
663,440 ✔
1150
      for (size_t c = 0; c < cols; ++c)
130,460,000 ✔
1151
        data_slice(r, c) = ids.data_(r, c, idx);
129,800,000 ✔
1152
    tensor::Tensor<int32_t> data_flipped = data_slice.flip(0);
3,440 ✔
1153

1154
    // Write to HDF5 dataset
1155
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
3,440 ✔
1156

1157
    // update progress bar
1158
    pb.set_value(
3,440 ✔
1159
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
3,440 ✔
1160
  }
10,320 ✔
1161

1162
  voxel_finalize(dspace, dset, memspace);
40 ✔
1163
  file_close(file_id);
40 ✔
1164
}
40 ✔
1165

1166
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
40 ✔
1167
  hid_t* memspace)
1168
{
1169
  // Create dataspace/dataset for voxel data
1170
  *dspace = H5Screate_simple(3, dims, nullptr);
40 ✔
1171
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
40 ✔
1172
    H5P_DEFAULT, H5P_DEFAULT);
1173

1174
  // Create dataspace for a slice of the voxel
1175
  hsize_t dims_slice[2] {dims[1], dims[2]};
40 ✔
1176
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
40 ✔
1177

1178
  // Select hyperslab in dataspace
1179
  hsize_t start[3] {0, 0, 0};
40 ✔
1180
  hsize_t count[3] {1, dims[1], dims[2]};
40 ✔
1181
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
40 ✔
1182
}
40 ✔
1183

1184
void voxel_write_slice(
3,440 ✔
1185
  int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
1186
{
1187
  hssize_t offset[3] {x, 0, 0};
3,440 ✔
1188
  H5Soffset_simple(dspace, offset);
3,440 ✔
1189
  H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
3,440 ✔
1190
}
3,440 ✔
1191

1192
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
40 ✔
1193
{
1194
  H5Dclose(dset);
40 ✔
1195
  H5Sclose(dspace);
40 ✔
1196
  H5Sclose(memspace);
40 ✔
1197
}
40 ✔
1198

1199
RGBColor random_color(void)
3,023 ✔
1200
{
1201
  return {int(prn(&model::plotter_seed) * 255),
3,023 ✔
1202
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
3,023 ✔
1203
}
1204

1205
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
64 ✔
1206
{
1207
  set_look_at(node);
64 ✔
1208
  set_camera_position(node);
64 ✔
1209
  set_field_of_view(node);
64 ✔
1210
  set_pixels(node);
64 ✔
1211
  set_orthographic_width(node);
64 ✔
1212
  set_output_path(node);
64 ✔
1213

1214
  if (check_for_node(node, "orthographic_width") &&
72 !
1215
      check_for_node(node, "field_of_view"))
8 ✔
1216
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1217
                "parameters.");
1218
}
64 ✔
1219

1220
void RayTracePlot::update_view()
80 ✔
1221
{
1222
  // Get centerline vector for camera-to-model. We create vectors around this
1223
  // that form a pixel array, and then trace rays along that.
1224
  auto up = up_ / up_.norm();
80 ✔
1225
  Direction looking_direction = look_at_ - camera_position_;
80 ✔
1226
  looking_direction /= looking_direction.norm();
80 ✔
1227
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
80 !
1228
    fatal_error("Up vector cannot align with vector between camera position "
×
1229
                "and look_at!");
1230
  Direction cam_yaxis = looking_direction.cross(up);
80 ✔
1231
  cam_yaxis /= cam_yaxis.norm();
80 ✔
1232
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
80 ✔
1233
  cam_zaxis /= cam_zaxis.norm();
80 ✔
1234

1235
  // Cache the camera-to-model matrix
1236
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
80 ✔
1237
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
80 ✔
1238
    cam_yaxis.z, cam_zaxis.z};
80 ✔
1239
}
80 ✔
1240

1241
WireframeRayTracePlot::WireframeRayTracePlot(pugi::xml_node node)
40 ✔
1242
  : RayTracePlot(node)
40 ✔
1243
{
1244
  set_opacities(node);
40 ✔
1245
  set_wireframe_thickness(node);
40 ✔
1246
  set_wireframe_ids(node);
40 ✔
1247
  set_wireframe_color(node);
40 ✔
1248
  update_view();
40 ✔
1249
}
40 ✔
1250

1251
void WireframeRayTracePlot::set_wireframe_color(pugi::xml_node plot_node)
40 ✔
1252
{
1253
  // Copy plot wireframe color
1254
  if (check_for_node(plot_node, "wireframe_color")) {
40 !
1255
    vector<int> w_rgb = get_node_array<int>(plot_node, "wireframe_color");
×
1256
    if (w_rgb.size() == 3) {
×
1257
      wireframe_color_ = w_rgb;
×
1258
    } else {
1259
      fatal_error(fmt::format("Bad wireframe RGB in plot {}", id()));
×
1260
    }
1261
  }
×
1262
}
40 ✔
1263

1264
void RayTracePlot::set_output_path(pugi::xml_node node)
64 ✔
1265
{
1266
  // Set output file path
1267
  std::string filename;
64 ✔
1268

1269
  if (check_for_node(node, "filename")) {
64 ✔
1270
    filename = get_node_value(node, "filename");
56 ✔
1271
  } else {
1272
    filename = fmt::format("plot_{}", id());
8 ✔
1273
  }
1274

1275
#ifdef USE_LIBPNG
1276
  if (!file_extension_present(filename, "png"))
64 ✔
1277
    filename.append(".png");
24 ✔
1278
#else
1279
  if (!file_extension_present(filename, "ppm"))
1280
    filename.append(".ppm");
1281
#endif
1282
  path_plot_ = filename;
128 ✔
1283
}
64 ✔
1284

1285
bool WireframeRayTracePlot::trackstack_equivalent(
2,211,752 ✔
1286
  const std::vector<TrackSegment>& track1,
1287
  const std::vector<TrackSegment>& track2) const
1288
{
1289
  if (wireframe_ids_.empty()) {
2,211,752 ✔
1290
    // Draw wireframe for all surfaces/cells/materials
1291
    if (track1.size() != track2.size())
1,850,960 ✔
1292
      return false;
1293
    for (int i = 0; i < track1.size(); ++i) {
4,878,512 ✔
1294
      if (track1[i].id != track2[i].id ||
3,081,288 ✔
1295
          track1[i].surface_index != track2[i].surface_index) {
3,081,192 ✔
1296
        return false;
1297
      }
1298
    }
1299
    return true;
1300
  } else {
1301
    // This runs in O(nm) where n is the intersection stack size
1302
    // and m is the number of IDs we are wireframing. A simpler
1303
    // algorithm can likely be found.
1304
    for (const int id : wireframe_ids_) {
717,232 ✔
1305
      int t1_i = 0;
360,792 ✔
1306
      int t2_i = 0;
360,792 ✔
1307

1308
      // Advance to first instance of the ID
1309
      while (t1_i < track1.size() && t2_i < track2.size()) {
409,040 ✔
1310
        while (t1_i < track1.size() && track1[t1_i].id != id)
285,696 ✔
1311
          t1_i++;
166,584 ✔
1312
        while (t2_i < track2.size() && track2[t2_i].id != id)
286,304 ✔
1313
          t2_i++;
167,192 ✔
1314

1315
        // This one is really important!
1316
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
119,112 ✔
1317
            (t1_i != track1.size() && t2_i == track2.size()))
117,888 ✔
1318
          return false;
2,704 ✔
1319
        if (t1_i == track1.size() && t2_i == track2.size())
116,408 !
1320
          break;
1321
        // Check if surface different
1322
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
49,896 ✔
1323
          return false;
1324

1325
        // Pretty sure this should not be used:
1326
        // if (t2_i != track2.size() - 1 &&
1327
        //     t1_i != track1.size() - 1 &&
1328
        //     track1[t1_i+1].id != track2[t2_i+1].id) return false;
1329
        if (t2_i != 0 && t1_i != 0 &&
48,816 ✔
1330
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
39,232 ✔
1331
          return false;
1332

1333
        // Check if neighboring cells are different
1334
        // if (track1[t1_i ? t1_i - 1 : 0].id != track2[t2_i ? t2_i - 1 : 0].id)
1335
        // return false; if (track1[t1_i < track1.size() - 1 ? t1_i + 1 : t1_i
1336
        // ].id !=
1337
        //    track2[t2_i < track2.size() - 1 ? t2_i + 1 : t2_i].id) return
1338
        //    false;
1339
        t1_i++, t2_i++;
48,248 ✔
1340
      }
1341
    }
1342
    return true;
1343
  }
1344
}
1345

1346
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
2,560,768 ✔
1347
  int horiz, int vert) const
1348
{
1349
  // Compute field of view in radians
1350
  constexpr double DEGREE_TO_RADIAN = PI / 180.0;
2,560,768 ✔
1351
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
2,560,768 ✔
1352
  double p0 = static_cast<double>(pixels()[0]);
2,560,768 ✔
1353
  double p1 = static_cast<double>(pixels()[1]);
2,560,768 ✔
1354

1355
  // focal_plane_dist can be changed to alter the perspective distortion
1356
  // effect. This is in units of cm. This seems to look good most of the
1357
  // time. TODO let this variable be set through XML.
1358
  constexpr double focal_plane_dist = 10.0;
2,560,768 ✔
1359
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
2,560,768 ✔
1360
  const double dy = p1 / p0 * dx;
2,560,768 ✔
1361

1362
  std::pair<Position, Direction> result;
2,560,768 ✔
1363

1364
  // Generate the starting position/direction of the ray
1365
  if (orthographic_width_ == C_NONE) { // perspective projection
2,560,768 ✔
1366
    Direction camera_local_vec;
2,240,768 ✔
1367
    camera_local_vec.x = focal_plane_dist;
2,240,768 ✔
1368
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
2,240,768 ✔
1369
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
2,240,768 ✔
1370
    camera_local_vec /= camera_local_vec.norm();
2,240,768 ✔
1371

1372
    result.first = camera_position_;
2,240,768 ✔
1373
    result.second = camera_local_vec.rotate(camera_to_model_);
2,240,768 ✔
1374
  } else { // orthographic projection
1375

1376
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
320,000 ✔
1377
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
320,000 ✔
1378

1379
    result.first = camera_position_ +
320,000 ✔
1380
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
320,000 ✔
1381
                   camera_z_axis() * y_pix_coord * orthographic_width_;
320,000 ✔
1382
    result.second = camera_x_axis();
320,000 ✔
1383
  }
1384

1385
  return result;
2,560,768 ✔
1386
}
1387

1388
ImageData WireframeRayTracePlot::create_image() const
40 ✔
1389
{
1390
  size_t width = pixels()[0];
40 ✔
1391
  size_t height = pixels()[1];
40 ✔
1392
  ImageData data({width, height}, not_found_);
40 ✔
1393

1394
  // This array marks where the initial wireframe was drawn. We convolve it with
1395
  // a filter that gets adjusted with the wireframe thickness in order to
1396
  // thicken the lines.
1397
  tensor::Tensor<int> wireframe_initial(
40 ✔
1398
    {static_cast<size_t>(width), static_cast<size_t>(height)}, 0);
40 ✔
1399

1400
  /* Holds all of the track segments for the current rendered line of pixels.
1401
   * old_segments holds a copy of this_line_segments from the previous line.
1402
   * By holding both we can check if the cell/material intersection stack
1403
   * differs from the left or upper neighbor. This allows a robustly drawn
1404
   * wireframe. If only checking the left pixel (which requires substantially
1405
   * less memory), the wireframe tends to be spotty and be disconnected for
1406
   * surface edges oriented horizontally in the rendering.
1407
   *
1408
   * Note that a vector of vectors is required rather than a 2-tensor,
1409
   * since the stack size varies within each column.
1410
   */
1411
  const int n_threads = num_threads();
40 ✔
1412
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
40 ✔
1413
    n_threads);
40 ✔
1414
  for (int t = 0; t < n_threads; ++t) {
95 ✔
1415
    this_line_segments[t].resize(pixels()[0]);
55 ✔
1416
  }
1417

1418
  // The last thread writes to this, and the first thread reads from it.
1419
  std::vector<std::vector<TrackSegment>> old_segments(pixels()[0]);
40 ✔
1420

1421
#pragma omp parallel
15 ✔
1422
  {
25 ✔
1423
    const int n_threads = num_threads();
25 ✔
1424
    const int tid = thread_num();
25 ✔
1425

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

1429
      // Save bottom line of current work chunk to compare against later. This
1430
      // used to be inside the below if block, but it causes a spurious line to
1431
      // be drawn at the bottom of the image. Not sure why, but moving it here
1432
      // fixes things.
1433
      if (tid == n_threads - 1)
5,025 ✔
1434
        old_segments = this_line_segments[n_threads - 1];
5,025 ✔
1435

1436
      if (vert < pixels()[1]) {
5,025 ✔
1437

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

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

1443
          this_line_segments[tid][horiz].clear();
1,000,000 ✔
1444
          ProjectionRay ray(
1,000,000 ✔
1445
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
1,000,000 ✔
1446

1447
          ray.trace();
1,000,000 ✔
1448

1449
          // Now color the pixel based on what we have intersected...
1450
          // Loops backwards over intersections.
1451
          Position current_color(
1,000,000 ✔
1452
            not_found_.red, not_found_.green, not_found_.blue);
1,000,000 ✔
1453
          const auto& segments = this_line_segments[tid][horiz];
1,000,000 ✔
1454

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

1462
          for (int i = segments.size() - 2; i >= 0; --i) {
1,072,335 ✔
1463
            int colormap_idx = segments[i].id;
688,990 ✔
1464
            RGBColor seg_color = colors_[colormap_idx];
688,990 ✔
1465
            Position seg_color_vec(
688,990 ✔
1466
              seg_color.red, seg_color.green, seg_color.blue);
688,990 ✔
1467
            double mixing =
688,990 ✔
1468
              std::exp(-xs_[colormap_idx] *
1,377,980 ✔
1469
                       (segments[i + 1].length - segments[i].length));
688,990 ✔
1470
            current_color =
688,990 ✔
1471
              current_color * mixing + (1.0 - mixing) * seg_color_vec;
688,990 ✔
1472
          }
1473

1474
          // save result converting from double-precision color coordinates to
1475
          // byte-sized
1476
          RGBColor result;
383,345 ✔
1477
          result.red = static_cast<uint8_t>(current_color.x);
383,345 ✔
1478
          result.green = static_cast<uint8_t>(current_color.y);
383,345 ✔
1479
          result.blue = static_cast<uint8_t>(current_color.z);
383,345 ✔
1480
          data(horiz, vert) = result;
383,345 ✔
1481

1482
          // Check to draw wireframe in horizontal direction. No inter-thread
1483
          // comm.
1484
          if (horiz > 0) {
383,345 ✔
1485
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
382,345 ✔
1486
                  this_line_segments[tid][horiz - 1])) {
382,345 ✔
1487
              wireframe_initial(horiz, vert) = 1;
15,710 ✔
1488
            }
1489
          }
1490
        }
1,000,000 ✔
1491
      } // end "if" vert in correct range
1492

1493
      // We require a barrier before comparing vertical neighbors' intersection
1494
      // stacks. i.e. all threads must be done with their line.
1495
#pragma omp barrier
1496

1497
      // Now that the horizontal line has finished rendering, we can fill in
1498
      // wireframe entries that require comparison among all the threads. Hence
1499
      // the omp barrier being used. It has to be OUTSIDE any if blocks!
1500
      if (vert < pixels()[1]) {
5,025 ✔
1501
        // Loop over horizontal pixels, checking intersection stack of upper
1502
        // neighbor
1503

1504
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
1505
        if (tid == 0)
1506
          top_cmp = &old_segments;
1507
        else
1508
          top_cmp = &this_line_segments[tid - 1];
1509

1510
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
1,005,000 ✔
1511
          if (!trackstack_equivalent(
1,000,000 ✔
1512
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
1,000,000 ✔
1513
            wireframe_initial(horiz, vert) = 1;
20,595 ✔
1514
          }
1515
        }
1516
      }
1517

1518
      // We need another barrier to ensure threads don't proceed to modify their
1519
      // intersection stacks on that horizontal line while others are
1520
      // potentially still working on the above.
1521
#pragma omp barrier
1522
      vert += n_threads;
5,025 ✔
1523
    }
1524
  } // end omp parallel
1525

1526
  // Now thicken the wireframe lines and apply them to our image
1527
  for (int vert = 0; vert < pixels()[1]; ++vert) {
8,040 ✔
1528
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
1,608,000 ✔
1529
      if (wireframe_initial(horiz, vert)) {
1,600,000 ✔
1530
        if (wireframe_thickness_ == 1)
51,624 ✔
1531
          data(horiz, vert) = wireframe_color_;
21,960 ✔
1532
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
142,344 ✔
1533
             ++i)
1534
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
397,728 ✔
1535
               ++j)
1536
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
307,008 !
1537

1538
              // Check if wireframe pixel is out of bounds
1539
              int w_i = std::clamp(horiz + i, 0, pixels()[0] - 1);
307,008 ✔
1540
              int w_j = std::clamp(vert + j, 0, pixels()[1] - 1);
307,008 ✔
1541
              data(w_i, w_j) = wireframe_color_;
307,008 ✔
1542
            }
1543
      }
1544
    }
1545
  }
1546

1547
  return data;
80 ✔
1548
}
80 ✔
1549

1550
void WireframeRayTracePlot::create_output() const
40 ✔
1551
{
1552
  ImageData data = create_image();
40 ✔
1553
  write_image(data);
40 ✔
1554
}
40 ✔
1555

1556
void RayTracePlot::print_info() const
64 ✔
1557
{
1558
  fmt::print("Camera position: {} {} {}\n", camera_position_.x,
128 ✔
1559
    camera_position_.y, camera_position_.z);
64 ✔
1560
  fmt::print("Look at: {} {} {}\n", look_at_.x, look_at_.y, look_at_.z);
64 ✔
1561
  fmt::print(
128 ✔
1562
    "Horizontal field of view: {} degrees\n", horizontal_field_of_view_);
64 ✔
1563
  fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
64 ✔
1564
}
64 ✔
1565

1566
void WireframeRayTracePlot::print_info() const
40 ✔
1567
{
1568
  fmt::print("Plot Type: Wireframe ray-traced\n");
40 ✔
1569
  RayTracePlot::print_info();
40 ✔
1570
}
40 ✔
1571

1572
void WireframeRayTracePlot::set_opacities(pugi::xml_node node)
40 ✔
1573
{
1574
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
40 ✔
1575

1576
  for (auto cn : node.children("color")) {
88 ✔
1577
    // Make sure 3 values are specified for RGB
1578
    double user_xs = std::stod(get_node_value(cn, "xs"));
96 ✔
1579
    int col_id = std::stoi(get_node_value(cn, "id"));
96 ✔
1580

1581
    // Add RGB
1582
    if (PlotColorBy::cells == color_by_) {
48 !
1583
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
48 !
1584
        col_id = model::cell_map[col_id];
48 ✔
1585
        xs_[col_id] = user_xs;
48 ✔
1586
      } else {
1587
        warning(fmt::format(
×
1588
          "Could not find cell {} specified in plot {}", col_id, id()));
×
1589
      }
1590
    } else if (PlotColorBy::mats == color_by_) {
×
1591
      if (model::material_map.find(col_id) != model::material_map.end()) {
×
1592
        col_id = model::material_map[col_id];
×
1593
        xs_[col_id] = user_xs;
×
1594
      } else {
1595
        warning(fmt::format(
×
1596
          "Could not find material {} specified in plot {}", col_id, id()));
×
1597
      }
1598
    }
1599
  }
1600
}
40 ✔
1601

1602
void RayTracePlot::set_orthographic_width(pugi::xml_node node)
64 ✔
1603
{
1604
  if (check_for_node(node, "orthographic_width")) {
64 ✔
1605
    double orthographic_width =
8 ✔
1606
      std::stod(get_node_value(node, "orthographic_width", true));
8 ✔
1607
    if (orthographic_width < 0.0)
8 !
1608
      fatal_error("Requires positive orthographic_width");
×
1609
    orthographic_width_ = orthographic_width;
8 ✔
1610
  }
1611
}
64 ✔
1612

1613
void WireframeRayTracePlot::set_wireframe_thickness(pugi::xml_node node)
40 ✔
1614
{
1615
  if (check_for_node(node, "wireframe_thickness")) {
40 ✔
1616
    int wireframe_thickness =
16 ✔
1617
      std::stoi(get_node_value(node, "wireframe_thickness", true));
16 ✔
1618
    if (wireframe_thickness < 0)
16 !
1619
      fatal_error("Requires non-negative wireframe thickness");
×
1620
    wireframe_thickness_ = wireframe_thickness;
16 ✔
1621
  }
1622
}
40 ✔
1623

1624
void WireframeRayTracePlot::set_wireframe_ids(pugi::xml_node node)
40 ✔
1625
{
1626
  if (check_for_node(node, "wireframe_ids")) {
40 ✔
1627
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
8 ✔
1628
    // It is read in as actual ID values, but we have to convert to indices in
1629
    // mat/cell array
1630
    for (auto& x : wireframe_ids_)
16 ✔
1631
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
16 !
1632
                                         : model::cell_map[x];
×
1633
  }
1634
  // We make sure the list is sorted in order to later use
1635
  // std::binary_search.
1636
  std::sort(wireframe_ids_.begin(), wireframe_ids_.end());
40 ✔
1637
}
40 ✔
1638

1639
void RayTracePlot::set_pixels(pugi::xml_node node)
64 ✔
1640
{
1641
  vector<int> pxls = get_node_array<int>(node, "pixels");
64 ✔
1642
  if (pxls.size() != 2)
64 !
1643
    fatal_error(
×
1644
      fmt::format("<pixels> must be length 2 in projection plot {}", id()));
×
1645
  pixels()[0] = pxls[0];
64 ✔
1646
  pixels()[1] = pxls[1];
64 ✔
1647
}
64 ✔
1648

1649
void RayTracePlot::set_camera_position(pugi::xml_node node)
64 ✔
1650
{
1651
  vector<double> camera_pos = get_node_array<double>(node, "camera_position");
64 ✔
1652
  if (camera_pos.size() != 3) {
64 !
1653
    fatal_error(fmt::format(
×
1654
      "camera_position element must have three floating point values"));
1655
  }
1656
  camera_position_.x = camera_pos[0];
64 ✔
1657
  camera_position_.y = camera_pos[1];
64 ✔
1658
  camera_position_.z = camera_pos[2];
64 ✔
1659
}
64 ✔
1660

1661
void RayTracePlot::set_look_at(pugi::xml_node node)
64 ✔
1662
{
1663
  vector<double> look_at = get_node_array<double>(node, "look_at");
64 ✔
1664
  if (look_at.size() != 3) {
64 !
1665
    fatal_error("look_at element must have three floating point values");
×
1666
  }
1667
  look_at_.x = look_at[0];
64 ✔
1668
  look_at_.y = look_at[1];
64 ✔
1669
  look_at_.z = look_at[2];
64 ✔
1670
}
64 ✔
1671

1672
void RayTracePlot::set_field_of_view(pugi::xml_node node)
64 ✔
1673
{
1674
  // Defaults to 70 degree horizontal field of view (see .h file)
1675
  if (check_for_node(node, "horizontal_field_of_view")) {
64 !
1676
    double fov =
×
1677
      std::stod(get_node_value(node, "horizontal_field_of_view", true));
×
1678
    if (fov < 180.0 && fov > 0.0) {
×
1679
      horizontal_field_of_view_ = fov;
×
1680
    } else {
1681
      fatal_error(fmt::format("Horizontal field of view for plot {} "
×
1682
                              "out-of-range. Must be in (0, 180) degrees.",
1683
        id()));
×
1684
    }
1685
  }
1686
}
64 ✔
1687

1688
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
24 ✔
1689
{
1690
  set_opaque_ids(node);
24 ✔
1691
  set_diffuse_fraction(node);
24 ✔
1692
  set_light_position(node);
24 ✔
1693
  update_view();
24 ✔
1694
}
24 ✔
1695

1696
void SolidRayTracePlot::print_info() const
24 ✔
1697
{
1698
  fmt::print("Plot Type: Solid ray-traced\n");
24 ✔
1699
  RayTracePlot::print_info();
24 ✔
1700
}
24 ✔
1701

1702
ImageData SolidRayTracePlot::create_image() const
40 ✔
1703
{
1704
  size_t width = pixels()[0];
40 ✔
1705
  size_t height = pixels()[1];
40 ✔
1706
  ImageData data({width, height}, not_found_);
40 ✔
1707

1708
#pragma omp parallel for schedule(dynamic) collapse(2)
15 ✔
1709
  for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
3,105 ✔
1710
    for (int vert = 0; vert < pixels()[1]; ++vert) {
603,560 ✔
1711
      // RayTracePlot implements camera ray generation
1712
      std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
600,480 ✔
1713
      PhongRay ray(ru.first, ru.second, *this);
600,480 ✔
1714
      ray.trace();
600,480 ✔
1715
      data(horiz, vert) = ray.result_color();
600,480 ✔
1716
    }
600,480 ✔
1717
  }
1718

1719
  return data;
40 ✔
1720
}
1721

1722
void SolidRayTracePlot::create_output() const
24 ✔
1723
{
1724
  ImageData data = create_image();
24 ✔
1725
  write_image(data);
24 ✔
1726
}
24 ✔
1727

1728
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
24 ✔
1729
{
1730
  if (check_for_node(node, "opaque_ids")) {
24 !
1731
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
24 ✔
1732

1733
    // It is read in as actual ID values, but we have to convert to indices in
1734
    // mat/cell array
1735
    for (auto& x : opaque_ids_tmp)
72 ✔
1736
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
96 !
1737
                                         : model::cell_map[x];
×
1738

1739
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
24 ✔
1740
  }
24 ✔
1741
}
24 ✔
1742

1743
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
24 ✔
1744
{
1745
  if (check_for_node(node, "light_position")) {
24 ✔
1746
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
8 ✔
1747

1748
    if (light_pos_tmp.size() != 3)
8 !
1749
      fatal_error("Light position must be given as 3D coordinates");
×
1750

1751
    light_location_.x = light_pos_tmp[0];
8 ✔
1752
    light_location_.y = light_pos_tmp[1];
8 ✔
1753
    light_location_.z = light_pos_tmp[2];
8 ✔
1754
  } else {
8 ✔
1755
    light_location_ = camera_position();
16 ✔
1756
  }
1757
}
24 ✔
1758

1759
void SolidRayTracePlot::set_diffuse_fraction(pugi::xml_node node)
24 ✔
1760
{
1761
  if (check_for_node(node, "diffuse_fraction")) {
24 ✔
1762
    diffuse_fraction_ = std::stod(get_node_value(node, "diffuse_fraction"));
8 ✔
1763
    if (diffuse_fraction_ < 0.0 || diffuse_fraction_ > 1.0) {
8 !
1764
      fatal_error("Must have 0 <= diffuse fraction <= 1");
×
1765
    }
1766
  }
1767
}
24 ✔
1768

1769
void ProjectionRay::on_intersection()
1,715,744 ✔
1770
{
1771
  // This records a tuple with the following info
1772
  //
1773
  // 1) ID (material or cell depending on color_by_)
1774
  // 2) Distance traveled by the ray through that ID
1775
  // 3) Index of the intersected surface (starting from 1)
1776

1777
  line_segments_.emplace_back(
1,715,744 ✔
1778
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
1,715,744 ✔
1779
      ? material()
397,032 ✔
1780
      : lowest_coord().cell(),
1,318,712 ✔
1781
    traversal_distance_, boundary().surface_index());
1,715,744 ✔
1782
}
1,715,744 ✔
1783

1784
void PhongRay::on_intersection()
658,888 ✔
1785
{
1786
  // Check if we hit an opaque material or cell
1787
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
658,888 ✔
1788
                 ? material()
658,888 !
1789
                 : lowest_coord().cell();
×
1790

1791
  // If we are reflected and have advanced beyond the camera,
1792
  // the ray is done. This is checked here because we should
1793
  // kill the ray even if the material is not opaque.
1794
  if (reflected_ && (r() - plot_.camera_position()).dot(u()) >= 0.0) {
658,888 !
1795
    stop();
×
1796
    return;
119,520 ✔
1797
  }
1798

1799
  // Anything that's not opaque has zero impact on the plot.
1800
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
658,888 ✔
1801
    return;
1802

1803
  if (!reflected_) {
539,368 ✔
1804
    // reflect the particle and set the color to be colored by
1805
    // the normal or the diffuse lighting contribution
1806
    reflected_ = true;
513,504 ✔
1807
    result_color_ = plot_.colors_[hit_id];
513,504 ✔
1808
    // The ray has been advanced slightly past the boundary. Use an
1809
    // approximation to the actual hit point for stable normal/lighting.
1810
    Position r_hit = r() - TINY_BIT * u();
513,504 ✔
1811
    Direction to_light = plot_.light_location_ - r_hit;
513,504 ✔
1812
    to_light /= to_light.norm();
513,504 ✔
1813

1814
    // TODO
1815
    // Not sure what can cause a surface token to be invalid here, although it
1816
    // sometimes happens for a few pixels. It's very very rare, so proceed by
1817
    // coloring the pixel with the overlap color. It seems to happen only for a
1818
    // few pixels on the outer boundary of a hex lattice.
1819
    //
1820
    // We cannot detect it in the outer loop, and it only matters here, so
1821
    // that's why the error handling is a little different than for a lost
1822
    // ray.
1823
    if (surface() == 0) {
513,504 !
1824
      result_color_ = plot_.overlap_color_;
×
1825
      stop();
×
1826
      return;
×
1827
    }
1828

1829
    // Get surface pointer
1830
    const auto& surf = model::surfaces.at(surface_index());
513,504 ✔
1831

1832
    // The crossed surface may be on a higher coordinate level than the
1833
    // innermost local coordinates, so we check the surface's coordinate level
1834
    // to find the appropriate coordinate level to use for the normal
1835
    // calculation
1836
    int surf_level = boundary().coord_level() - 1;
513,504 ✔
1837
    // ensure surface level is within bounds of current coordinate stack
1838
    surf_level = std::clamp(surf_level, 0, n_coord() - 1);
513,504 ✔
1839

1840
    Position r_hit_level =
513,504 ✔
1841
      coord(surf_level).r() - TINY_BIT * coord(surf_level).u();
513,504 ✔
1842
    Direction normal = surf->normal(r_hit_level);
513,504 ✔
1843
    normal /= normal.norm();
513,504 ✔
1844

1845
    // Need to apply rotations to find the normal vector in
1846
    // the base level universe's coordinate system.
1847
    for (int lev = surf_level - 1; lev >= 0; --lev) {
513,504 !
1848
      if (coord(lev + 1).rotated()) {
×
1849
        const Cell& c {*model::cells[coord(lev).cell()]};
×
1850
        normal = normal.inverse_rotate(c.rotation_);
×
1851
      }
1852
    }
1853

1854
    // use the normal opposed to the ray direction
1855
    if (normal.dot(u()) > 0.0) {
513,504 ✔
1856
      normal *= -1.0;
46,392 ✔
1857
    }
1858

1859
    // Facing away from the light means no lighting
1860
    double dotprod = normal.dot(to_light);
513,504 ✔
1861
    dotprod = std::max(0.0, dotprod);
513,504 ✔
1862

1863
    double modulation =
513,504 ✔
1864
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
513,504 ✔
1865
    result_color_ *= modulation;
513,504 ✔
1866

1867
    // Now point the particle to the camera. We now begin
1868
    // checking to see if it's occluded by another surface
1869
    u() = to_light;
513,504 ✔
1870

1871
    orig_hit_id_ = hit_id;
513,504 ✔
1872

1873
    // OpenMC native CSG and DAGMC surfaces have some slight differences
1874
    // in how they interpret particles that are sitting on a surface.
1875
    // I don't know exactly why, but this makes everything work beautifully.
1876
    if (surf->geom_type() == GeometryType::DAG) {
513,504 !
1877
      surface() = 0;
×
1878
    } else {
1879
      surface() = -surface(); // go to other side
513,504 ✔
1880
    }
1881

1882
    // Must fully restart coordinate search. Why? Not sure.
1883
    clear();
513,504 ✔
1884

1885
    // Note this could likely be faster if we cached the previous
1886
    // cell we were in before the reflection. This is the easiest
1887
    // way to fully initialize all the sub-universe coordinates and
1888
    // directions though.
1889
    bool found = exhaustive_find_cell(*this);
513,504 ✔
1890
    if (!found) {
513,504 !
1891
      fatal_error("Lost particle after reflection.");
×
1892
    }
1893

1894
    // Must recalculate distance to boundary due to the
1895
    // direction change
1896
    compute_distance();
513,504 ✔
1897

1898
  } else {
1899
    // If it's not facing the light, we color with the diffuse contribution, so
1900
    // next we check if we're going to occlude the last reflected surface. if
1901
    // so, color by the diffuse contribution instead
1902

1903
    if (orig_hit_id_ == -1)
25,864 !
1904
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1905

1906
    result_color_ = plot_.colors_[orig_hit_id_];
25,864 ✔
1907
    result_color_ *= plot_.diffuse_fraction_;
25,864 ✔
1908
    stop();
539,368 ✔
1909
  }
1910
}
1911

1912
extern "C" int openmc_id_map(const void* plot, int32_t* data_out)
×
1913
{
1914
  static bool warned {false};
×
1915
  if (!warned) {
×
1916
    warning("openmc_id_map is deprecated and will be removed in a future "
×
1917
            "release. Use openmc_slice_data.");
1918
    warned = true;
×
1919
  }
1920

1921
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1922
  if (!plt) {
×
1923
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1924
    return OPENMC_E_INVALID_ARGUMENT;
×
1925
  }
1926

1927
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1928
    model::overlap_check_count.resize(model::cells.size());
×
1929
  }
1930

1931
  auto ids = plt->get_map<IdData>();
×
1932

1933
  // write id data to array
1934
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
×
1935

1936
  return 0;
×
1937
}
×
1938

1939
extern "C" int openmc_property_map(const void* plot, double* data_out)
×
1940
{
1941
  static bool warned {false};
×
1942
  if (!warned) {
×
1943
    warning("openmc_property_map is deprecated and will be removed in a future "
×
1944
            "release. Use openmc_slice_data.");
1945
    warned = true;
×
1946
  }
1947

1948
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1949
  if (!plt) {
×
1950
    set_errmsg("Invalid slice pointer passed to openmc_property_map");
×
1951
    return OPENMC_E_INVALID_ARGUMENT;
×
1952
  }
1953

1954
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1955
    model::overlap_check_count.resize(model::cells.size());
×
1956
  }
1957

1958
  auto props = plt->get_map<PropertyData>();
×
1959

1960
  // write id data to array
1961
  std::copy(props.data_.begin(), props.data_.end(), data_out);
×
1962

1963
  return 0;
×
1964
}
×
1965

1966
extern "C" int openmc_slice_data(const double origin[3], const double u_span[3],
691 ✔
1967
  const double v_span[3], const size_t pixels[2], bool color_overlaps,
1968
  int level, int32_t filter_index, int32_t* geom_data, double* property_data)
1969
{
1970
  // Validate span vectors
1971
  Direction u_span_pos {u_span[0], u_span[1], u_span[2]};
691 ✔
1972
  Direction v_span_pos {v_span[0], v_span[1], v_span[2]};
691 ✔
1973
  double u_norm = u_span_pos.norm();
691 ✔
1974
  double v_norm = v_span_pos.norm();
691 ✔
1975
  if (u_norm == 0.0 || v_norm == 0.0) {
691 !
1976
    set_errmsg("Slice span vectors must be non-zero.");
×
1977
    return OPENMC_E_INVALID_ARGUMENT;
×
1978
  }
1979

1980
  constexpr double ORTHO_REL_TOL = 1e-10;
691 ✔
1981
  double dot = u_span_pos.dot(v_span_pos);
691 !
1982
  if (std::abs(dot) > ORTHO_REL_TOL * u_norm * v_norm) {
691 !
1983
    set_errmsg("Slice span vectors must be orthogonal.");
×
1984
    return OPENMC_E_INVALID_ARGUMENT;
×
1985
  }
1986

1987
  // Validate filter index if provided
1988
  if (filter_index >= 0) {
691 ✔
1989
    if (int err = verify_filter(filter_index))
16 !
1990
      return err;
1991
  }
1992

1993
  // Initialize overlap check vector if needed
1994
  if (color_overlaps && model::overlap_check_count.size() == 0) {
691 ✔
1995
    model::overlap_check_count.resize(model::cells.size());
96 ✔
1996
  }
1997

1998
  try {
691 ✔
1999
    // Create a temporary SlicePlotBase object to reuse get_map logic
2000
    SlicePlotBase plot_params;
691 ✔
2001
    plot_params.origin_ = Position {origin[0], origin[1], origin[2]};
691 ✔
2002
    plot_params.u_span_ = u_span_pos;
691 ✔
2003
    plot_params.v_span_ = v_span_pos;
691 ✔
2004
    plot_params.pixels_[0] = pixels[0];
691 ✔
2005
    plot_params.pixels_[1] = pixels[1];
691 ✔
2006
    plot_params.show_overlaps_ = color_overlaps;
691 ✔
2007
    plot_params.slice_level_ = level;
691 ✔
2008

2009
    // Clear overlap data structures on new slice call
2010
    model::overlap_keys.clear();
691 ✔
2011
    model::overlap_key_index.clear();
691 ✔
2012

2013
    // Use get_map<RasterData> to generate data
2014
    auto data = plot_params.get_map<RasterData>(filter_index);
691 ✔
2015
    std::copy(data.id_data_.begin(), data.id_data_.end(), geom_data);
691 ✔
2016

2017
    // Copy property data if requested
2018
    if (property_data != nullptr) {
691 ✔
2019
      std::copy(
64 ✔
2020
        data.property_data_.begin(), data.property_data_.end(), property_data);
2021
    }
2022
  } catch (const std::exception& e) {
691 !
2023
    set_errmsg(e.what());
×
2024
    return OPENMC_E_UNASSIGNED;
×
2025
  }
×
2026

2027
  return 0;
691 ✔
2028
}
2029

2030
// Gets the number of overlaps that we need data for
2031
extern "C" int openmc_slice_data_overlap_count(size_t* count)
384 ✔
2032
{
2033
  if (!count) {
384 !
2034
    set_errmsg("Null pointer passed for overlap count.");
×
2035
    return OPENMC_E_INVALID_ARGUMENT;
×
2036
  }
2037
  *count = model::overlap_keys.size();
384 ✔
2038

2039
  return 0;
384 ✔
2040
}
2041

2042
// Plotter pre-allocates array size based on what is returned with
2043
// overlap_count; populates an array of size 3*count
2044
extern "C" int openmc_slice_data_overlap_info(
24 ✔
2045
  size_t count, int32_t* overlap_info)
2046
{
2047
  for (size_t i = 0; i < count; ++i) {
56 ✔
2048
    overlap_info[i * 3] = model::overlap_keys[i].universe_id;
32 ✔
2049
    overlap_info[i * 3 + 1] = model::overlap_keys[i].cell1_id;
32 ✔
2050
    overlap_info[i * 3 + 2] = model::overlap_keys[i].cell2_id;
32 ✔
2051
  }
2052

2053
  return 0;
24 ✔
2054
}
2055

2056
extern "C" int openmc_get_plot_index(int32_t id, int32_t* index)
16 ✔
2057
{
2058
  auto it = model::plot_map.find(id);
16 !
2059
  if (it == model::plot_map.end()) {
16 !
2060
    set_errmsg("No plot exists with ID=" + std::to_string(id) + ".");
×
2061
    return OPENMC_E_INVALID_ID;
×
2062
  }
2063

2064
  *index = it->second;
16 ✔
2065
  return 0;
16 ✔
2066
}
2067

2068
extern "C" int openmc_plot_get_id(int32_t index, int32_t* id)
40 ✔
2069
{
2070
  if (index < 0 || index >= model::plots.size()) {
40 !
2071
    set_errmsg("Index in plots array is out of bounds.");
×
2072
    return OPENMC_E_OUT_OF_BOUNDS;
×
2073
  }
2074

2075
  *id = model::plots[index]->id();
40 ✔
2076
  return 0;
40 ✔
2077
}
2078

2079
extern "C" int openmc_plot_set_id(int32_t index, int32_t id)
×
2080
{
2081
  if (index < 0 || index >= model::plots.size()) {
×
2082
    set_errmsg("Index in plots array is out of bounds.");
×
2083
    return OPENMC_E_OUT_OF_BOUNDS;
×
2084
  }
2085

2086
  if (id < 0 && id != C_NONE) {
×
2087
    set_errmsg("Invalid plot ID.");
×
2088
    return OPENMC_E_INVALID_ARGUMENT;
×
2089
  }
2090

2091
  auto* plot = model::plots[index].get();
×
2092
  int32_t old_id = plot->id();
×
2093
  if (id == old_id)
×
2094
    return 0;
2095

2096
  model::plot_map.erase(old_id);
×
2097
  try {
×
2098
    plot->set_id(id);
×
2099
  } catch (const std::runtime_error& e) {
×
2100
    model::plot_map[old_id] = index;
×
2101
    set_errmsg(e.what());
×
2102
    return OPENMC_E_INVALID_ID;
×
2103
  }
×
2104
  model::plot_map[plot->id()] = index;
×
2105
  return 0;
×
2106
}
2107

2108
extern "C" size_t openmc_plots_size()
16 ✔
2109
{
2110
  return model::plots.size();
16 ✔
2111
}
2112

2113
int map_phong_domain_id(
40 ✔
2114
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2115
{
2116
  if (!plot || !index_out) {
40 !
2117
    set_errmsg("Invalid plot pointer passed to map_phong_domain_id");
×
2118
    return OPENMC_E_INVALID_ARGUMENT;
×
2119
  }
2120

2121
  if (plot->color_by_ == PlottableInterface::PlotColorBy::mats) {
40 !
2122
    auto it = model::material_map.find(id);
40 !
2123
    if (it == model::material_map.end()) {
40 !
2124
      set_errmsg("Invalid material ID for SolidRayTracePlot");
×
2125
      return OPENMC_E_INVALID_ID;
×
2126
    }
2127
    *index_out = it->second;
40 ✔
2128
    return 0;
40 ✔
2129
  }
2130

2131
  if (plot->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2132
    auto it = model::cell_map.find(id);
×
2133
    if (it == model::cell_map.end()) {
×
2134
      set_errmsg("Invalid cell ID for SolidRayTracePlot");
×
2135
      return OPENMC_E_INVALID_ID;
×
2136
    }
2137
    *index_out = it->second;
×
2138
    return 0;
×
2139
  }
2140

2141
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2142
  return OPENMC_E_INVALID_TYPE;
×
2143
}
2144

2145
int get_solidraytrace_plot_by_index(int32_t index, SolidRayTracePlot** plot)
224 ✔
2146
{
2147
  if (!plot) {
224 !
2148
    set_errmsg("Null output pointer passed to get_solidraytrace_plot_by_index");
×
2149
    return OPENMC_E_INVALID_ARGUMENT;
×
2150
  }
2151

2152
  if (index < 0 || index >= model::plots.size()) {
224 !
2153
    set_errmsg("Index in plots array is out of bounds.");
×
2154
    return OPENMC_E_OUT_OF_BOUNDS;
×
2155
  }
2156

2157
  auto* plottable = model::plots[index].get();
224 !
2158
  auto* solid_plot = dynamic_cast<SolidRayTracePlot*>(plottable);
224 !
2159
  if (!solid_plot) {
224 !
2160
    set_errmsg("Plot at index=" + std::to_string(index) +
×
2161
               " is not a solid raytrace plot.");
2162
    return OPENMC_E_INVALID_TYPE;
×
2163
  }
2164

2165
  *plot = solid_plot;
224 ✔
2166
  return 0;
224 ✔
2167
}
2168

2169
extern "C" int openmc_solidraytrace_plot_create(int32_t* index)
8 ✔
2170
{
2171
  if (!index) {
8 !
2172
    set_errmsg(
×
2173
      "Null output pointer passed to openmc_solidraytrace_plot_create");
2174
    return OPENMC_E_INVALID_ARGUMENT;
×
2175
  }
2176

2177
  try {
8 ✔
2178
    auto new_plot = std::make_unique<SolidRayTracePlot>();
8 ✔
2179
    new_plot->set_id();
8 ✔
2180
    int32_t new_plot_id = new_plot->id();
8 ✔
2181
#ifdef USE_LIBPNG
2182
    new_plot->path_plot() = fmt::format("plot_{}.png", new_plot_id);
8 ✔
2183
#else
2184
    new_plot->path_plot() = fmt::format("plot_{}.ppm", new_plot_id);
2185
#endif
2186
    int32_t new_plot_index = model::plots.size();
8 ✔
2187
    model::plots.emplace_back(std::move(new_plot));
8 ✔
2188
    model::plot_map[new_plot_id] = new_plot_index;
8 ✔
2189
    *index = new_plot_index;
8 ✔
2190
  } catch (const std::exception& e) {
8 !
2191
    set_errmsg(e.what());
×
2192
    return OPENMC_E_ALLOCATE;
×
2193
  }
×
2194

2195
  return 0;
8 ✔
2196
}
2197

2198
extern "C" int openmc_solidraytrace_plot_get_pixels(
24 ✔
2199
  int32_t index, int32_t* width, int32_t* height)
2200
{
2201
  if (!width || !height) {
24 !
2202
    set_errmsg(
×
2203
      "Invalid arguments passed to openmc_solidraytrace_plot_get_pixels");
2204
    return OPENMC_E_INVALID_ARGUMENT;
×
2205
  }
2206

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

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

2217
extern "C" int openmc_solidraytrace_plot_set_pixels(
8 ✔
2218
  int32_t index, int32_t width, int32_t height)
2219
{
2220
  if (width <= 0 || height <= 0) {
8 !
2221
    set_errmsg(
×
2222
      "Invalid arguments passed to openmc_solidraytrace_plot_set_pixels");
2223
    return OPENMC_E_INVALID_ARGUMENT;
×
2224
  }
2225

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

2231
  plt->pixels()[0] = width;
8 ✔
2232
  plt->pixels()[1] = height;
8 ✔
2233
  return 0;
8 ✔
2234
}
2235

2236
extern "C" int openmc_solidraytrace_plot_get_color_by(
8 ✔
2237
  int32_t index, int32_t* color_by)
2238
{
2239
  if (!color_by) {
8 !
2240
    set_errmsg(
×
2241
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color_by");
2242
    return OPENMC_E_INVALID_ARGUMENT;
×
2243
  }
2244

2245
  SolidRayTracePlot* plt = nullptr;
8 ✔
2246
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2247
  if (err)
8 !
2248
    return err;
2249

2250
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
8 !
2251
    *color_by = 0;
8 ✔
2252
  } else if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2253
    *color_by = 1;
×
2254
  } else {
2255
    set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2256
    return OPENMC_E_INVALID_TYPE;
×
2257
  }
2258

2259
  return 0;
2260
}
2261

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

2270
  if (color_by == 0) {
8 !
2271
    plt->color_by_ = PlottableInterface::PlotColorBy::mats;
8 ✔
2272
  } else if (color_by == 1) {
×
2273
    plt->color_by_ = PlottableInterface::PlotColorBy::cells;
×
2274
  } else {
2275
    set_errmsg("Invalid color_by value for SolidRayTracePlot");
×
2276
    return OPENMC_E_INVALID_ARGUMENT;
×
2277
  }
2278

2279
  return 0;
2280
}
2281

2282
extern "C" int openmc_solidraytrace_plot_set_default_colors(int32_t index)
8 ✔
2283
{
2284
  SolidRayTracePlot* plt = nullptr;
8 ✔
2285
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2286
  if (err)
8 !
2287
    return err;
2288

2289
  plt->set_default_colors();
8 ✔
2290
  return 0;
2291
}
2292

2293
extern "C" int openmc_solidraytrace_plot_set_all_opaque(int32_t index)
×
2294
{
2295
  SolidRayTracePlot* plt = nullptr;
×
2296
  int err = get_solidraytrace_plot_by_index(index, &plt);
×
2297
  if (err)
×
2298
    return err;
2299

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

2308
  if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2309
    for (int32_t i = 0; i < model::cells.size(); ++i) {
×
2310
      plt->opaque_ids().insert(i);
×
2311
    }
2312
    return 0;
×
2313
  }
2314

2315
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2316
  return OPENMC_E_INVALID_TYPE;
2317
}
2318

2319
extern "C" int openmc_solidraytrace_plot_set_opaque(
16 ✔
2320
  int32_t index, int32_t id, bool visible)
2321
{
2322
  SolidRayTracePlot* plt = nullptr;
16 ✔
2323
  int err = get_solidraytrace_plot_by_index(index, &plt);
16 ✔
2324
  if (err)
16 !
2325
    return err;
2326

2327
  int32_t domain_index = -1;
16 ✔
2328
  err = map_phong_domain_id(plt, id, &domain_index);
16 ✔
2329
  if (err)
16 !
2330
    return err;
2331

2332
  if (visible) {
16 ✔
2333
    plt->opaque_ids().insert(domain_index);
8 ✔
2334
  } else {
2335
    plt->opaque_ids().erase(domain_index);
8 ✔
2336
  }
2337

2338
  return 0;
2339
}
2340

2341
extern "C" int openmc_solidraytrace_plot_set_color(
16 ✔
2342
  int32_t index, int32_t id, uint8_t r, uint8_t g, uint8_t b)
2343
{
2344
  SolidRayTracePlot* plt = nullptr;
16 ✔
2345
  int err = get_solidraytrace_plot_by_index(index, &plt);
16 ✔
2346
  if (err)
16 !
2347
    return err;
2348

2349
  int32_t domain_index = -1;
16 ✔
2350
  err = map_phong_domain_id(plt, id, &domain_index);
16 ✔
2351
  if (err)
16 !
2352
    return err;
2353

2354
  if (domain_index < 0 ||
16 !
2355
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
16 !
2356
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2357
    return OPENMC_E_OUT_OF_BOUNDS;
×
2358
  }
2359

2360
  plt->colors_[domain_index] = RGBColor(r, g, b);
16 ✔
2361
  return 0;
16 ✔
2362
}
2363

2364
extern "C" int openmc_solidraytrace_plot_get_camera_position(
8 ✔
2365
  int32_t index, double* x, double* y, double* z)
2366
{
2367
  if (!x || !y || !z) {
8 !
2368
    set_errmsg("Invalid arguments passed to "
×
2369
               "openmc_solidraytrace_plot_get_camera_position");
2370
    return OPENMC_E_INVALID_ARGUMENT;
×
2371
  }
2372

2373
  SolidRayTracePlot* plt = nullptr;
8 ✔
2374
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2375
  if (err)
8 !
2376
    return err;
2377

2378
  const auto& camera_position = plt->camera_position();
8 ✔
2379
  *x = camera_position.x;
8 ✔
2380
  *y = camera_position.y;
8 ✔
2381
  *z = camera_position.z;
8 ✔
2382
  return 0;
8 ✔
2383
}
2384

2385
extern "C" int openmc_solidraytrace_plot_set_camera_position(
8 ✔
2386
  int32_t index, double x, double y, double z)
2387
{
2388
  SolidRayTracePlot* plt = nullptr;
8 ✔
2389
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2390
  if (err)
8 !
2391
    return err;
2392

2393
  plt->camera_position() = {x, y, z};
8 ✔
2394
  return 0;
8 ✔
2395
}
2396

2397
extern "C" int openmc_solidraytrace_plot_get_look_at(
8 ✔
2398
  int32_t index, double* x, double* y, double* z)
2399
{
2400
  if (!x || !y || !z) {
8 !
2401
    set_errmsg(
×
2402
      "Invalid arguments passed to openmc_solidraytrace_plot_get_look_at");
2403
    return OPENMC_E_INVALID_ARGUMENT;
×
2404
  }
2405

2406
  SolidRayTracePlot* plt = nullptr;
8 ✔
2407
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2408
  if (err)
8 !
2409
    return err;
2410

2411
  const auto& look_at = plt->look_at();
8 ✔
2412
  *x = look_at.x;
8 ✔
2413
  *y = look_at.y;
8 ✔
2414
  *z = look_at.z;
8 ✔
2415
  return 0;
8 ✔
2416
}
2417

2418
extern "C" int openmc_solidraytrace_plot_set_look_at(
8 ✔
2419
  int32_t index, double x, double y, double z)
2420
{
2421
  SolidRayTracePlot* plt = nullptr;
8 ✔
2422
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2423
  if (err)
8 !
2424
    return err;
2425

2426
  plt->look_at() = {x, y, z};
8 ✔
2427
  return 0;
8 ✔
2428
}
2429

2430
extern "C" int openmc_solidraytrace_plot_get_up(
8 ✔
2431
  int32_t index, double* x, double* y, double* z)
2432
{
2433
  if (!x || !y || !z) {
8 !
2434
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_up");
×
2435
    return OPENMC_E_INVALID_ARGUMENT;
×
2436
  }
2437

2438
  SolidRayTracePlot* plt = nullptr;
8 ✔
2439
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2440
  if (err)
8 !
2441
    return err;
2442

2443
  const auto& up = plt->up();
8 ✔
2444
  *x = up.x;
8 ✔
2445
  *y = up.y;
8 ✔
2446
  *z = up.z;
8 ✔
2447
  return 0;
8 ✔
2448
}
2449

2450
extern "C" int openmc_solidraytrace_plot_set_up(
8 ✔
2451
  int32_t index, double x, double y, double z)
2452
{
2453
  SolidRayTracePlot* plt = nullptr;
8 ✔
2454
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2455
  if (err)
8 !
2456
    return err;
2457

2458
  plt->up() = {x, y, z};
8 ✔
2459
  return 0;
8 ✔
2460
}
2461

2462
extern "C" int openmc_solidraytrace_plot_get_light_position(
8 ✔
2463
  int32_t index, double* x, double* y, double* z)
2464
{
2465
  if (!x || !y || !z) {
8 !
2466
    set_errmsg("Invalid arguments passed to "
×
2467
               "openmc_solidraytrace_plot_get_light_position");
2468
    return OPENMC_E_INVALID_ARGUMENT;
×
2469
  }
2470

2471
  SolidRayTracePlot* plt = nullptr;
8 ✔
2472
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2473
  if (err)
8 !
2474
    return err;
2475

2476
  const auto& light_position = plt->light_location();
8 ✔
2477
  *x = light_position.x;
8 ✔
2478
  *y = light_position.y;
8 ✔
2479
  *z = light_position.z;
8 ✔
2480
  return 0;
8 ✔
2481
}
2482

2483
extern "C" int openmc_solidraytrace_plot_set_light_position(
8 ✔
2484
  int32_t index, double x, double y, double z)
2485
{
2486
  SolidRayTracePlot* plt = nullptr;
8 ✔
2487
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2488
  if (err)
8 !
2489
    return err;
2490

2491
  plt->light_location() = {x, y, z};
8 ✔
2492
  return 0;
8 ✔
2493
}
2494

2495
extern "C" int openmc_solidraytrace_plot_get_fov(int32_t index, double* fov)
8 ✔
2496
{
2497
  if (!fov) {
8 !
2498
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_fov");
×
2499
    return OPENMC_E_INVALID_ARGUMENT;
×
2500
  }
2501

2502
  SolidRayTracePlot* plt = nullptr;
8 ✔
2503
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2504
  if (err)
8 !
2505
    return err;
2506

2507
  *fov = plt->horizontal_field_of_view();
8 ✔
2508
  return 0;
8 ✔
2509
}
2510

2511
extern "C" int openmc_solidraytrace_plot_set_fov(int32_t index, double fov)
8 ✔
2512
{
2513
  SolidRayTracePlot* plt = nullptr;
8 ✔
2514
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2515
  if (err)
8 !
2516
    return err;
2517

2518
  plt->horizontal_field_of_view() = fov;
8 ✔
2519
  return 0;
8 ✔
2520
}
2521

2522
extern "C" int openmc_solidraytrace_plot_update_view(int32_t index)
16 ✔
2523
{
2524
  SolidRayTracePlot* plt = nullptr;
16 ✔
2525
  int err = get_solidraytrace_plot_by_index(index, &plt);
16 ✔
2526
  if (err)
16 !
2527
    return err;
2528

2529
  plt->update_view();
16 ✔
2530
  return 0;
2531
}
2532

2533
extern "C" int openmc_solidraytrace_plot_create_image(
16 ✔
2534
  int32_t index, uint8_t* data_out, int32_t width, int32_t height)
2535
{
2536
  if (!data_out || width <= 0 || height <= 0) {
16 !
2537
    set_errmsg(
×
2538
      "Invalid arguments passed to openmc_solidraytrace_plot_create_image");
2539
    return OPENMC_E_INVALID_ARGUMENT;
×
2540
  }
2541

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

2547
  if (plt->pixels()[0] != width || plt->pixels()[1] != height) {
16 !
2548
    set_errmsg(
×
2549
      "Requested image size does not match SolidRayTracePlot pixel settings");
2550
    return OPENMC_E_INVALID_SIZE;
×
2551
  }
2552

2553
  ImageData data = plt->create_image();
16 ✔
2554
  if (static_cast<int32_t>(data.shape()[0]) != width ||
16 !
2555
      static_cast<int32_t>(data.shape()[1]) != height) {
16 !
2556
    set_errmsg("Unexpected image size from SolidRayTracePlot create_image");
×
2557
    return OPENMC_E_INVALID_SIZE;
2558
  }
2559

2560
  for (int32_t y = 0; y < height; ++y) {
112 ✔
2561
    for (int32_t x = 0; x < width; ++x) {
864 ✔
2562
      const auto& color = data(x, y);
768 ✔
2563
      size_t idx = (static_cast<size_t>(y) * width + x) * 3;
768 ✔
2564
      data_out[idx + 0] = color.red;
768 ✔
2565
      data_out[idx + 1] = color.green;
768 ✔
2566
      data_out[idx + 2] = color.blue;
768 ✔
2567
    }
2568
  }
2569

2570
  return 0;
2571
}
16 ✔
2572

2573
extern "C" int openmc_solidraytrace_plot_get_color(
8 ✔
2574
  int32_t index, int32_t id, uint8_t* r, uint8_t* g, uint8_t* b)
2575
{
2576
  if (!r || !g || !b) {
8 !
2577
    set_errmsg(
×
2578
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color");
2579
    return OPENMC_E_INVALID_ARGUMENT;
×
2580
  }
2581

2582
  SolidRayTracePlot* plt = nullptr;
8 ✔
2583
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2584
  if (err)
8 !
2585
    return err;
2586

2587
  int32_t domain_index = -1;
8 ✔
2588
  err = map_phong_domain_id(plt, id, &domain_index);
8 ✔
2589
  if (err)
8 !
2590
    return err;
2591

2592
  if (domain_index < 0 ||
8 !
2593
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
8 !
2594
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2595
    return OPENMC_E_OUT_OF_BOUNDS;
×
2596
  }
2597

2598
  const auto& color = plt->colors_[domain_index];
8 ✔
2599
  *r = color.red;
8 ✔
2600
  *g = color.green;
8 ✔
2601
  *b = color.blue;
8 ✔
2602
  return 0;
8 ✔
2603
}
2604

2605
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
8 ✔
2606
  int32_t index, double* diffuse_fraction)
2607
{
2608
  if (!diffuse_fraction) {
8 !
2609
    set_errmsg("Invalid arguments passed to "
×
2610
               "openmc_solidraytrace_plot_get_diffuse_fraction");
2611
    return OPENMC_E_INVALID_ARGUMENT;
×
2612
  }
2613

2614
  SolidRayTracePlot* plt = nullptr;
8 ✔
2615
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2616
  if (err)
8 !
2617
    return err;
2618

2619
  *diffuse_fraction = plt->diffuse_fraction();
8 ✔
2620
  return 0;
8 ✔
2621
}
2622

2623
extern "C" int openmc_solidraytrace_plot_set_diffuse_fraction(
8 ✔
2624
  int32_t index, double diffuse_fraction)
2625
{
2626
  SolidRayTracePlot* plt = nullptr;
8 ✔
2627
  int err = get_solidraytrace_plot_by_index(index, &plt);
8 ✔
2628
  if (err)
8 !
2629
    return err;
2630

2631
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
8 !
2632
    set_errmsg("Diffuse fraction must be between 0 and 1");
×
2633
    return OPENMC_E_INVALID_ARGUMENT;
×
2634
  }
2635

2636
  plt->diffuse_fraction() = diffuse_fraction;
8 ✔
2637
  return 0;
8 ✔
2638
}
2639

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

© 2026 Coveralls, Inc