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

openmc-dev / openmc / 34651633654

11 Sep 2026 09:54PM UTC coverage: 81.567% (+0.05%) from 81.519%
34651633654

Pull #3734

github

web-flow
Merge c6ad4e970 into 073c170cd
Pull Request #3734: Specify temperature from a field (structured mesh only)

19203 of 27733 branches covered (69.24%)

Branch coverage included in aggregate %.

293 of 311 new or added lines in 16 files covered. (94.21%)

317 existing lines in 10 files now uncovered.

61427 of 71118 relevant lines covered (86.37%)

49983235.31 hits per line

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

69.66
/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)
3,772,954 ✔
56
{
57
  double sqrtkT = p.sqrtkT();
3,772,954 ✔
58
  if (settings::temperature_field_on) {
3,772,954 ✔
59
    int bin = simulation::temperature_field.get_bin(p.r());
275 ✔
60
    if (bin != C_NONE)
275 !
61
      sqrtkT = simulation::temperature_field.get_sqrtkT(bin);
275 ✔
62
  }
63
  return (sqrtkT * sqrtkT) / K_BOLTZMANN;
3,772,954 ✔
64
}
65

66
} // namespace
67

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

72
void IdData::set_value(size_t y, size_t x, const Particle& p, int level,
35,403,192 ✔
73
  Filter* /*filter*/, FilterMatch* /*match*/)
74
{
75
  // set cell data
76
  if (p.n_coord() <= level) {
35,403,192 !
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_;
35,403,192 !
81
    data_(y, x, 1) = level == p.n_coord() - 1
35,403,192 ✔
82
                       ? p.cell_instance()
35,403,192 !
83
                       : cell_instance_at_level(p, level);
×
84
  }
85

86
  // set material data
87
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
35,403,192 ✔
88
  if (p.material() == MATERIAL_VOID) {
35,403,192 ✔
89
    data_(y, x, 2) = MATERIAL_VOID;
27,301,736 ✔
90
  } else if (c->type_ == Fill::MATERIAL) {
8,101,456 !
91
    Material* m = model::materials.at(p.material()).get();
8,101,456 ✔
92
    data_(y, x, 2) = m->id_;
8,101,456 ✔
93
  }
94
}
35,403,192 ✔
95

96
void IdData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
28,248 ✔
97
{
98
  for (size_t k = 0; k < data_.shape(2); ++k)
225,984 !
99
    data_(y, x, k) = OVERLAP;
84,744 ✔
100
}
28,248 ✔
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)
949 ✔
124
  : id_data_({v_res, h_res, include_filter ? 4u : 3u}, NOT_FOUND),
1,876 ✔
125
    property_data_({v_res, h_res, 2}, static_cast<double>(NOT_FOUND)),
949 ✔
126
    include_filter_(include_filter)
949 ✔
127
{}
949 ✔
128

129
void RasterData::set_value(size_t y, size_t x, const Particle& p, int level,
3,772,954 ✔
130
  Filter* filter, FilterMatch* match)
131
{
132
  // set cell data
133
  if (p.n_coord() <= level) {
3,772,954 !
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_;
3,772,954 !
138
    id_data_(y, x, 1) = level == p.n_coord() - 1
3,772,954 ✔
139
                          ? p.cell_instance()
3,772,954 !
140
                          : cell_instance_at_level(p, level);
×
141
  }
142

143
  // set material data
144
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
3,772,954 ✔
145
  if (p.material() == MATERIAL_VOID) {
3,772,954 ✔
146
    id_data_(y, x, 2) = MATERIAL_VOID;
2,573,050 ✔
147
  } else if (c->type_ == Fill::MATERIAL) {
1,199,904 !
148
    Material* m = model::materials.at(p.material()).get();
1,199,904 ✔
149
    id_data_(y, x, 2) = m->id_;
1,199,904 ✔
150
  }
151

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

164
  // set temperature (in K)
165
  property_data_(y, x, 0) = plot_temperature(p);
3,772,954 ✔
166

167
  // set density (g/cm³)
168
  if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) {
3,772,954 !
169
    Material* m = model::materials.at(p.material()).get();
1,199,904 ✔
170
    property_data_(y, x, 1) = c->density(p.cell_instance());
1,199,904 ✔
171
  }
172
}
3,772,954 ✔
173

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

183
  property_data_(y, x, 0) = OVERLAP;
365,794 ✔
184
  property_data_(y, x, 1) = OVERLAP;
365,794 ✔
185
}
365,794 ✔
186

187
//==============================================================================
188
// Global variables
189
//==============================================================================
190

191
namespace model {
192

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

197
} // namespace model
198

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

203
extern "C" int openmc_plot_geometry()
121 ✔
204
{
205

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

211
  return 0;
121 ✔
212
}
213

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

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

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

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

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

253
  if (PlotColorBy::cells == color_by_) {
154 ✔
254
    fmt::print("Coloring: Cells\n");
88 ✔
255
  } else if (PlotColorBy::mats == color_by_) {
66 !
256
    fmt::print("Coloring: Materials\n");
66 ✔
257
  }
258

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

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

287
  write_message("Reading plot XML file...", 5);
1,413 ✔
288

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

293
  pugi::xml_node root = doc.document_element();
1,413 ✔
294

295
  read_plots_xml(root);
1,413 ✔
296
}
1,413 ✔
297

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

306
    if (check_for_node(node, "type")) {
1,012 !
307
      std::string type_str = get_node_value(node, "type", true);
1,012 ✔
308
      if (type_str == "slice") {
1,012 ✔
309
        model::plots.emplace_back(
860 ✔
310
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,729 ✔
311
      } else if (type_str == "voxel") {
143 ✔
312
        model::plots.emplace_back(
55 ✔
313
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
110 ✔
314
      } else if (type_str == "wireframe_raytrace") {
88 ✔
315
        model::plots.emplace_back(
55 ✔
316
          std::make_unique<WireframeRayTracePlot>(node));
110 ✔
317
      } else if (type_str == "solid_raytrace") {
33 !
318
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
33 ✔
319
      } else {
320
        fatal_error(fmt::format(
×
321
          "Unsupported plot type '{}' in plot {}", type_str, plot_desc));
322
      }
323
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
1,003 ✔
324
    } else {
1,003 ✔
325
      fatal_error(fmt::format("Must specify plot type in plot {}", plot_desc));
×
326
    }
327
  }
1,003 ✔
328
}
1,923 ✔
329

330
void free_memory_plot()
9,768 ✔
331
{
332
  model::plots.clear();
9,768 ✔
333
  model::plot_map.clear();
9,768 ✔
334
}
9,768 ✔
335

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

343
  ImageData data({width, height}, not_found_);
143 ✔
344

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

348
  // assign colors
349
  for (size_t y = 0; y < height; y++) {
30,063 ✔
350
    for (size_t x = 0; x < width; x++) {
7,622,120 ✔
351
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
7,592,200 ✔
352
      auto id = ids.data_(y, x, idx);
7,592,200 ✔
353
      // no setting needed if not found
354
      if (id == NOT_FOUND) {
7,592,200 ✔
355
        continue;
1,082,532 ✔
356
      }
357
      if (id == OVERLAP) {
6,537,916 ✔
358
        data(x, y) = overlap_color_;
28,248 ✔
359
        continue;
28,248 ✔
360
      }
361
      if (PlotColorBy::cells == color_by_) {
6,509,668 ✔
362
        data(x, y) = colors_[model::cell_map[id]];
3,011,668 ✔
363
      } else if (PlotColorBy::mats == color_by_) {
3,498,000 !
364
        if (id == MATERIAL_VOID) {
3,498,000 !
365
          data(x, y) = WHITE;
×
366
          continue;
×
367
        }
368
        data(x, y) = colors_[model::material_map[id]];
3,498,000 ✔
369
      } // color_by if-else
370
    }
371
  }
372

373
  // draw mesh lines if present
374
  if (index_meshlines_mesh_ >= 0) {
143 ✔
375
    draw_mesh_lines(data);
33 ✔
376
  }
377

378
  return data;
143 ✔
379
}
143 ✔
380

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

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

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

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

408
  if (id_ == id)
1,023 !
409
    return;
410

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

417
  id_ = id;
1,023 ✔
418
}
419

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

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

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

463
  path_plot_ = filename;
915 ✔
464

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

815
    } else {
33 ✔
816
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
817
    }
818
  }
819
}
1,012 ✔
820

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

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

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

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

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

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

885
  of.open(fname);
×
886

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

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

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

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

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

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

925
  png_init_io(png_ptr, fp);
231 ✔
926

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

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

937
  // Write color for each pixel
938
  for (int y = 0; y < height; y++) {
47,751 ✔
939
    for (int x = 0; x < width; x++) {
11,159,720 ✔
940
      RGBColor rgb = data(x, y);
11,112,200 ✔
941
      row[3 * x] = rgb.red;
11,112,200 ✔
942
      row[3 * x + 1] = rgb.green;
11,112,200 ✔
943
      row[3 * x + 2] = rgb.blue;
11,112,200 ✔
944
    }
945
    png_write_row(png_ptr, row.data());
47,520 ✔
946
  }
947

948
  // End write
949
  png_write_end(png_ptr, nullptr);
231 ✔
950

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

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

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

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

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

1001
  Position ll_plot {origin_};
33 ✔
1002
  Position ur_plot {origin_};
33 ✔
1003

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

1009
  Position width = ur_plot - ll_plot;
33 ✔
1010

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

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

1031
  // Iterate across the first axis and draw lines.
1032
  for (auto ax1_val : axis_lines.first) {
187 ✔
1033
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
154 ✔
1034
    int ax1_ind = frac * pixels()[0];
154 ✔
1035
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
24,948 ✔
1036
      for (int plus = 0; plus <= meshlines_width_; plus++) {
49,588 ✔
1037
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
24,794 !
1038
          data(ax1_ind + plus, ax2_ind) = rgb;
24,794 ✔
1039
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
24,794 !
1040
          data(ax1_ind - plus, ax2_ind) = rgb;
24,794 ✔
1041
      }
1042
    }
1043
  }
1044

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

1061
  // Iterate across the second axis and draw lines.
1062
  for (auto ax2_val : axis_lines.second) {
209 ✔
1063
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
176 ✔
1064
    int ax2_ind = (1.0 - frac) * pixels()[1];
176 ✔
1065
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
28,336 ✔
1066
      for (int plus = 0; plus <= meshlines_width_; plus++) {
56,320 ✔
1067
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
28,160 !
1068
          data(ax1_ind, ax2_ind + plus) = rgb;
28,160 ✔
1069
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
28,160 !
1070
          data(ax1_ind, ax2_ind - plus) = rgb;
28,160 ✔
1071
      }
1072
    }
1073
  }
1074
}
33 ✔
1075

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

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

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

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

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

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

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

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

1136
  ProgressBar pb;
55 ✔
1137
  for (int z = 0; z < pixels()[2]; z++) {
4,785 ✔
1138
    // update z coordinate
1139
    pltbase.origin_.z = ll.z + z * vox[2];
4,730 ✔
1140

1141
    // generate ids using plotbase
1142
    IdData ids = pltbase.get_map<IdData>();
4,730 ✔
1143

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

1155
    // Write to HDF5 dataset
1156
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
4,730 ✔
1157

1158
    // update progress bar
1159
    pb.set_value(
4,730 ✔
1160
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
4,730 ✔
1161
  }
14,190 ✔
1162

1163
  voxel_finalize(dspace, dset, memspace);
55 ✔
1164
  file_close(file_id);
55 ✔
1165
}
55 ✔
1166

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

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

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

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

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

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

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

1215
  if (check_for_node(node, "orthographic_width") &&
99 !
1216
      check_for_node(node, "field_of_view"))
11 ✔
1217
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1218
                "parameters.");
1219
}
88 ✔
1220

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

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

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

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

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

1270
  if (check_for_node(node, "filename")) {
88 ✔
1271
    filename = get_node_value(node, "filename");
77 ✔
1272
  } else {
1273
    filename = fmt::format("plot_{}", id());
11 ✔
1274
  }
1275

1276
#ifdef USE_LIBPNG
1277
  if (!file_extension_present(filename, "png"))
88 ✔
1278
    filename.append(".png");
33 ✔
1279
#else
1280
  if (!file_extension_present(filename, "ppm"))
1281
    filename.append(".ppm");
1282
#endif
1283
  path_plot_ = filename;
176 ✔
1284
}
88 ✔
1285

1286
bool WireframeRayTracePlot::trackstack_equivalent(
3,041,159 ✔
1287
  const std::vector<TrackSegment>& track1,
1288
  const std::vector<TrackSegment>& track2) const
1289
{
1290
  if (wireframe_ids_.empty()) {
3,041,159 ✔
1291
    // Draw wireframe for all surfaces/cells/materials
1292
    if (track1.size() != track2.size())
2,545,070 ✔
1293
      return false;
1294
    for (int i = 0; i < track1.size(); ++i) {
6,707,954 ✔
1295
      if (track1[i].id != track2[i].id ||
4,236,771 ✔
1296
          track1[i].surface_index != track2[i].surface_index) {
4,236,639 ✔
1297
        return false;
1298
      }
1299
    }
1300
    return true;
1301
  } else {
1302
    // This runs in O(nm) where n is the intersection stack size
1303
    // and m is the number of IDs we are wireframing. A simpler
1304
    // algorithm can likely be found.
1305
    for (const int id : wireframe_ids_) {
986,194 ✔
1306
      int t1_i = 0;
496,089 ✔
1307
      int t2_i = 0;
496,089 ✔
1308

1309
      // Advance to first instance of the ID
1310
      while (t1_i < track1.size() && t2_i < track2.size()) {
562,430 ✔
1311
        while (t1_i < track1.size() && track1[t1_i].id != id)
392,832 ✔
1312
          t1_i++;
229,053 ✔
1313
        while (t2_i < track2.size() && track2[t2_i].id != id)
393,668 ✔
1314
          t2_i++;
229,889 ✔
1315

1316
        // This one is really important!
1317
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
163,779 ✔
1318
            (t1_i != track1.size() && t2_i == track2.size()))
162,096 ✔
1319
          return false;
3,718 ✔
1320
        if (t1_i == track1.size() && t2_i == track2.size())
160,061 !
1321
          break;
1322
        // Check if surface different
1323
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
68,607 ✔
1324
          return false;
1325

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

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

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

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

1364
  std::pair<Position, Direction> result;
3,521,056 ✔
1365

1366
  // Generate the starting position/direction of the ray
1367
  if (orthographic_width_ == C_NONE) { // perspective projection
3,521,056 ✔
1368
    Direction camera_local_vec;
3,081,056 ✔
1369
    camera_local_vec.x = focal_plane_dist;
3,081,056 ✔
1370
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
3,081,056 ✔
1371
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
3,081,056 ✔
1372
    camera_local_vec /= camera_local_vec.norm();
3,081,056 ✔
1373

1374
    result.first = camera_position_;
3,081,056 ✔
1375
    result.second = camera_local_vec.rotate(camera_to_model_);
3,081,056 ✔
1376
  } else { // orthographic projection
1377

1378
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
440,000 ✔
1379
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
440,000 ✔
1380

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

1387
  return result;
3,521,056 ✔
1388
}
1389

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

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

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

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

1423
#pragma omp parallel
30 ✔
1424
  {
25 ✔
1425
    const int n_threads = num_threads();
25 ✔
1426
    const int tid = thread_num();
25 ✔
1427

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

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

1438
      if (vert < pixels()[1]) {
5,025 ✔
1439

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

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

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

1449
          ray.trace();
1,000,000 ✔
1450

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

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

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

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

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

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

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

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

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

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

1528
  // Now thicken the wireframe lines and apply them to our image
1529
  for (int vert = 0; vert < pixels()[1]; ++vert) {
11,055 ✔
1530
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
2,211,000 ✔
1531
      if (wireframe_initial(horiz, vert)) {
2,200,000 ✔
1532
        if (wireframe_thickness_ == 1)
70,983 ✔
1533
          data(horiz, vert) = wireframe_color_;
30,195 ✔
1534
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
195,723 ✔
1535
             ++i)
1536
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
546,876 ✔
1537
               ++j)
1538
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
422,136 !
1539

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

1549
  return data;
110 ✔
1550
}
110 ✔
1551

1552
void WireframeRayTracePlot::create_output() const
55 ✔
1553
{
1554
  ImageData data = create_image();
55 ✔
1555
  write_image(data);
55 ✔
1556
}
55 ✔
1557

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

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

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

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

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

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

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

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

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

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

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

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

1690
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
33 ✔
1691
{
1692
  set_opaque_ids(node);
33 ✔
1693
  set_diffuse_fraction(node);
33 ✔
1694
  set_light_position(node);
33 ✔
1695
  update_view();
33 ✔
1696
}
33 ✔
1697

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

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

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

1721
  return data;
55 ✔
1722
}
1723

1724
void SolidRayTracePlot::create_output() const
33 ✔
1725
{
1726
  ImageData data = create_image();
33 ✔
1727
  write_image(data);
33 ✔
1728
}
33 ✔
1729

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

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

1741
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
33 ✔
1742
  }
33 ✔
1743
}
33 ✔
1744

1745
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
33 ✔
1746
{
1747
  if (check_for_node(node, "light_position")) {
33 ✔
1748
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
11 ✔
1749

1750
    if (light_pos_tmp.size() != 3)
11 !
1751
      fatal_error("Light position must be given as 3D coordinates");
×
1752

1753
    light_location_.x = light_pos_tmp[0];
11 ✔
1754
    light_location_.y = light_pos_tmp[1];
11 ✔
1755
    light_location_.z = light_pos_tmp[2];
11 ✔
1756
  } else {
11 ✔
1757
    light_location_ = camera_position();
22 ✔
1758
  }
1759
}
33 ✔
1760

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

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

1779
  line_segments_.emplace_back(
2,359,148 ✔
1780
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
2,359,148 ✔
1781
      ? material()
545,919 ✔
1782
      : lowest_coord().cell(),
1,813,229 ✔
1783
    traversal_distance_, boundary().surface_index());
2,359,148 ✔
1784
}
2,359,148 ✔
1785

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

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

1801
  // Anything that's not opaque has zero impact on the plot.
1802
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
905,971 ✔
1803
    return;
1804

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

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

1831
    // Get surface pointer
1832
    const auto& surf = model::surfaces.at(surface_index());
706,068 ✔
1833

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

1842
    Position r_hit_level =
706,068 ✔
1843
      coord(surf_level).r() - TINY_BIT * coord(surf_level).u();
706,068 ✔
1844
    Direction normal = surf->normal(r_hit_level);
706,068 ✔
1845
    normal /= normal.norm();
706,068 ✔
1846

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

1856
    // use the normal opposed to the ray direction
1857
    if (normal.dot(u()) > 0.0) {
706,068 ✔
1858
      normal *= -1.0;
63,789 ✔
1859
    }
1860

1861
    // Facing away from the light means no lighting
1862
    double dotprod = normal.dot(to_light);
706,068 ✔
1863
    dotprod = std::max(0.0, dotprod);
706,068 ✔
1864

1865
    double modulation =
706,068 ✔
1866
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
706,068 ✔
1867
    result_color_ *= modulation;
706,068 ✔
1868

1869
    // Now point the particle to the camera. We now begin
1870
    // checking to see if it's occluded by another surface
1871
    u() = to_light;
706,068 ✔
1872

1873
    orig_hit_id_ = hit_id;
706,068 ✔
1874

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

1884
    // Must fully restart coordinate search. Why? Not sure.
1885
    clear();
706,068 ✔
1886

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

1896
    // Must recalculate distance to boundary due to the
1897
    // direction change
1898
    compute_distance();
706,068 ✔
1899

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

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

1908
    result_color_ = plot_.colors_[orig_hit_id_];
35,563 ✔
1909
    result_color_ *= plot_.diffuse_fraction_;
35,563 ✔
1910
    stop();
741,631 ✔
1911
  }
1912
}
1913

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

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

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

1933
  auto ids = plt->get_map<IdData>();
×
1934

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

1938
  return 0;
×
1939
}
×
1940

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

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

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

1960
  auto props = plt->get_map<PropertyData>();
×
1961

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

1965
  return 0;
×
1966
}
×
1967

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

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

1989
  // Validate filter index if provided
1990
  if (filter_index >= 0) {
949 ✔
1991
    if (int err = verify_filter(filter_index))
22 !
1992
      return err;
1993
  }
1994

1995
  // Initialize overlap check vector if needed
1996
  if (color_overlaps && model::overlap_check_count.size() == 0) {
949 ✔
1997
    model::overlap_check_count.resize(model::cells.size());
132 ✔
1998
  }
1999

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

2011
    // Clear overlap data structures on new slice call
2012
    model::overlap_keys.clear();
949 ✔
2013
    model::overlap_key_index.clear();
949 ✔
2014

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

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

2029
  return 0;
949 ✔
2030
}
2031

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

2041
  return 0;
528 ✔
2042
}
2043

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

2055
  return 0;
33 ✔
2056
}
2057

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

2066
  *index = it->second;
22 ✔
2067
  return 0;
22 ✔
2068
}
2069

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

2077
  *id = model::plots[index]->id();
55 ✔
2078
  return 0;
55 ✔
2079
}
2080

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

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

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

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

2110
extern "C" size_t openmc_plots_size()
22 ✔
2111
{
2112
  return model::plots.size();
22 ✔
2113
}
2114

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

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

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

2143
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2144
  return OPENMC_E_INVALID_TYPE;
×
2145
}
2146

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

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

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

2167
  *plot = solid_plot;
308 ✔
2168
  return 0;
308 ✔
2169
}
2170

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

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

2197
  return 0;
11 ✔
2198
}
2199

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

2209
  SolidRayTracePlot* plt = nullptr;
33 ✔
2210
  int err = get_solidraytrace_plot_by_index(index, &plt);
33 ✔
2211
  if (err)
33 !
2212
    return err;
2213

2214
  *width = plt->pixels()[0];
33 ✔
2215
  *height = plt->pixels()[1];
33 ✔
2216
  return 0;
33 ✔
2217
}
2218

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

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

2233
  plt->pixels()[0] = width;
11 ✔
2234
  plt->pixels()[1] = height;
11 ✔
2235
  return 0;
11 ✔
2236
}
2237

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

2247
  SolidRayTracePlot* plt = nullptr;
11 ✔
2248
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2249
  if (err)
11 !
2250
    return err;
2251

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

2261
  return 0;
2262
}
2263

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

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

2281
  return 0;
2282
}
2283

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

2291
  plt->set_default_colors();
11 ✔
2292
  return 0;
2293
}
2294

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

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

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

2317
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2318
  return OPENMC_E_INVALID_TYPE;
2319
}
2320

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

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

2334
  if (visible) {
22 ✔
2335
    plt->opaque_ids().insert(domain_index);
11 ✔
2336
  } else {
2337
    plt->opaque_ids().erase(domain_index);
11 ✔
2338
  }
2339

2340
  return 0;
2341
}
2342

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

2351
  int32_t domain_index = -1;
22 ✔
2352
  err = map_phong_domain_id(plt, id, &domain_index);
22 ✔
2353
  if (err)
22 !
2354
    return err;
2355

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

2362
  plt->colors_[domain_index] = RGBColor(r, g, b);
22 ✔
2363
  return 0;
22 ✔
2364
}
2365

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

2375
  SolidRayTracePlot* plt = nullptr;
11 ✔
2376
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2377
  if (err)
11 !
2378
    return err;
2379

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

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

2395
  plt->camera_position() = {x, y, z};
11 ✔
2396
  return 0;
11 ✔
2397
}
2398

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

2408
  SolidRayTracePlot* plt = nullptr;
11 ✔
2409
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2410
  if (err)
11 !
2411
    return err;
2412

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

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

2428
  plt->look_at() = {x, y, z};
11 ✔
2429
  return 0;
11 ✔
2430
}
2431

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

2440
  SolidRayTracePlot* plt = nullptr;
11 ✔
2441
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2442
  if (err)
11 !
2443
    return err;
2444

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

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

2460
  plt->up() = {x, y, z};
11 ✔
2461
  return 0;
11 ✔
2462
}
2463

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

2473
  SolidRayTracePlot* plt = nullptr;
11 ✔
2474
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2475
  if (err)
11 !
2476
    return err;
2477

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

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

2493
  plt->light_location() = {x, y, z};
11 ✔
2494
  return 0;
11 ✔
2495
}
2496

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

2504
  SolidRayTracePlot* plt = nullptr;
11 ✔
2505
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2506
  if (err)
11 !
2507
    return err;
2508

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

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

2520
  plt->horizontal_field_of_view() = fov;
11 ✔
2521
  return 0;
11 ✔
2522
}
2523

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

2531
  plt->update_view();
22 ✔
2532
  return 0;
2533
}
2534

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

2544
  SolidRayTracePlot* plt = nullptr;
22 ✔
2545
  int err = get_solidraytrace_plot_by_index(index, &plt);
22 ✔
2546
  if (err)
22 !
2547
    return err;
2548

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

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

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

2572
  return 0;
2573
}
22 ✔
2574

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

2584
  SolidRayTracePlot* plt = nullptr;
11 ✔
2585
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2586
  if (err)
11 !
2587
    return err;
2588

2589
  int32_t domain_index = -1;
11 ✔
2590
  err = map_phong_domain_id(plt, id, &domain_index);
11 ✔
2591
  if (err)
11 !
2592
    return err;
2593

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

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

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

2616
  SolidRayTracePlot* plt = nullptr;
11 ✔
2617
  int err = get_solidraytrace_plot_by_index(index, &plt);
11 ✔
2618
  if (err)
11 !
2619
    return err;
2620

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

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

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

2638
  plt->diffuse_fraction() = diffuse_fraction;
11 ✔
2639
  return 0;
11 ✔
2640
}
2641

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