<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
   */

#include <Modules/Visualization/ShowColorMapModule.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Algorithms/Visualization/DataConversions.h>
#include <Core/Datatypes/ColorMap.h>
#include <Core/Datatypes/Color.h>
#include <Core/GeometryPrimitives/Vector.h>

using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun;

ShowColorMapModule::ShowColorMapModule() : GeometryGeneratingModule(ModuleLookupInfo("ShowColorMap", "Visualization", "SCIRun"))
{
  INITIALIZE_PORT(ColorMapObject);
  INITIALIZE_PORT(GeometryOutput);
}

void ShowColorMapModule::setStateDefaults()
{
  auto state = get_state();
  state->setValue(DisplaySide, 0);
  state->setValue(DisplayLength, 0);
  state->setValue(TextSize, 2);
  state->setValue(TextRed, 1.);
  state->setValue(TextGreen, 1.);
  state->setValue(TextBlue, 1.);
  state->setValue(Labels, 10);
  state->setValue(Scale, 1.0);
  state->setValue(Units, std::string(""));
  state->setValue(SignificantDigits, 2);
  state->setValue(AddExtraSpace, false);
}

void ShowColorMapModule::execute()
{
  auto colorMap = getRequiredInput(ColorMapObject);
  if (needToExecute())
  {
    std::ostringstream ostr;
    ostr << get_id() << "_" <<
      colorMap->getColorMapInvert() << colorMap->getColorMapName() << colorMap->getColorMapRescaleScale() <<
      colorMap->getColorMapRescaleShift() << colorMap->getColorMapResolution() << colorMap.get() <<
      colorMap->getColorMapShift();
    GeometryHandle geom = buildGeometryObject(colorMap, get_state(), ostr.str());
    sendOutput(GeometryOutput, geom);
  }
}

GeometryHandle
ShowColorMapModule::buildGeometryObject(ColorMapHandle cm, ModuleStateHandle state, const std::string& id)
{
  std::vector<Vector> points;
  std::vector<ColorRGB> colors;
  std::vector<uint32_t> indices;
  int32_t numVBOElements = 0;
  ColorMap * map = cm.get();
  double resolution = 1. / static_cast<double>(map->getColorMapResolution());
  //show colormap does not rescale colors, so reset them. we want to see the whole colormap on the scale.
  ColorMap new_map(map->getColorMapName(),map->getColorMapResolution(),
                   map->getColorMapShift(),map->getColorMapInvert(), 1.,0.);
  for (double i = 0.; std::abs(i - 1.) > 0.000001; i += resolution) {
    ColorRGB col = new_map.valueToColor(i);
    uint32_t offset = (uint32_t)points.size();
    points.push_back(Vector(0., i, +0.001));
    colors.push_back(col);
    points.push_back(Vector(1., i, +0.001));
    colors.push_back(col);
    points.push_back(Vector(0., i + resolution, +0.001));
    colors.push_back(col);
    points.push_back(Vector(1., i + resolution, +0.001));
    colors.push_back(col);
    numVBOElements += 2;
    indices.push_back(offset + 0);
    indices.push_back(offset + 1);
    indices.push_back(offset + 3);
    indices.push_back(offset + 3);
    indices.push_back(offset + 2);
    indices.push_back(offset + 0);
  }

  // IBO/VBOs and sizes
  uint32_t iboSize = sizeof(uint32_t) * (uint32_t)indices.size();
  uint32_t vboSize = sizeof(float) * 7 * (uint32_t)points.size();

  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> iboBufferSPtr(
    new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));
  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> vboBufferSPtr(
    new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));

  CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer = iboBufferSPtr.get();
  CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer = vboBufferSPtr.get();

  for (auto a : indices) iboBuffer->write(a);

  for (size_t i = 0; i < points.size(); i++) {
    vboBuffer->write(static_cast<float>(points[i].x()));
    vboBuffer->write(static_cast<float>(points[i].y()));
    vboBuffer->write(static_cast<float>(points[i].z()));
    vboBuffer->write(static_cast<float>(colors[i].r()));
    vboBuffer->write(static_cast<float>(colors[i].g()));
    vboBuffer->write(static_cast<float>(colors[i].b()));
    vboBuffer->write(static_cast<float>(1.f));
  }

  //add the actual points and colors

  auto st = get_state();
  int sigdig = st->getValue(SignificantDigits).toInt();
  int numlabel = st->getValue(Labels).toInt();
  int txtsize = st->getValue(TextSize).toInt();
  double scale = st->getValue(Scale).toDouble();
  int displaySide = state->getValue(DisplaySide).toInt();
  float red = static_cast<float>(st->getValue(TextRed).toDouble());
  float green = static_cast<float>(st->getValue(TextGreen).toDouble());
  float blue = static_cast<float>(st->getValue(TextBlue).toDouble());
  std::stringstream ss;
  ss << resolution << sigdig << txtsize << numlabel << st->getValue(Units).toString() <<
    scale << displaySide << red << green << blue;

  std::string uniqueNodeID = id + "colorMapLegend" + ss.str();
  std::string vboName = uniqueNodeID + "VBO";
  std::string iboName = uniqueNodeID + "IBO";
  std::string passName = uniqueNodeID + "Pass";

  // NOTE: Attributes will depend on the color scheme. We will want to
  // normalize the colors if the color scheme is COLOR_IN_SITU.

  // Construct VBO.
  std::string shader = "Shaders/ColorMapLegend";
  std::vector<GeometryObject::SpireVBO::AttributeData> attribs;
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aPos", 3 * sizeof(float)));
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aColor", 4 * sizeof(float)));
  std::vector<GeometryObject::SpireSubPass::Uniform> uniforms;
  bool extraSpace = state->getValue(AddExtraSpace).toBool();
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uExtraSpace", extraSpace ? 1.f : 0.f));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplaySide", static_cast<float>(displaySide)));
  int displayLength = state->getValue(DisplayLength).toInt();
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplayLength", static_cast<float>(displayLength)));
  GeometryObject::SpireVBO geomVBO = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr,
    numVBOElements, Core::Geometry::BBox(), true);

  // Construct IBO.

  GeometryObject::SpireIBO geomIBO(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr);

  RenderState renState;
  renState.set(RenderState::IS_ON, true);
  renState.set(RenderState::HAS_DATA, true);

  GeometryObject::SpireSubPass pass(passName, vboName, iboName, shader,
    GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO, geomIBO);

  // Add all uniforms generated above to the pass.
  for (const auto& uniform : uniforms) { pass.addUniform(uniform); }

  Core::Datatypes::GeometryHandle geom(new Core::Datatypes::GeometryObject(nullptr, *this, "ShowColorMap"));

  geom->mColorMap = cm->getColorMapName();
  geom->mIBOs.push_back(geomIBO);
  geom->mVBOs.push_back(geomVBO);
  geom->mPasses.push_back(pass);
  //########################################
  // Now render the numbers for the scale bar

  char str2[128];
  std::stringstream sd;
  sd << "%." << sigdig << "f";
  points.clear();
  indices.clear();
  std::vector<Vector> txt_coords;
  numVBOElements = 0;
  uint32_t count = 0;
  double increment = 1. / static_cast<double>(numlabel - 1);
  double textSize = 10. * static_cast<double>(txtsize + 1) + 30.;

  for (double i = 0.; i <= 1.000000001; i += increment) {
    std::stringstream ss;
    sprintf(str2, sd.str().c_str(), i / cm->getColorMapRescaleScale() - cm->getColorMapRescaleShift());
    ss << str2 << " " << st->getValue(Units).toString();
    text_.reset(ss.str(), textSize, Vector((displaySide == 0) ? 80. : 1., (displaySide == 0) ? 0. : 40., i));
    std::vector<Vector> tmp;
    std::vector<Vector> coords;
    text_.getStringVerts(tmp, coords);
    if (displaySide != 0)
      text_.reset("|", 40., Vector(1., 0., i));
    else
      text_.reset("____", 20., Vector(10., 0., i));
    text_.getStringVerts(tmp, coords);
    for (auto a : tmp) {
      points.push_back(a);
      indices.push_back(count);
      count++;
    }
    for (auto a : coords)
      txt_coords.push_back(a);
  }
  numVBOElements = (uint32_t)points.size();

  // IBO/VBOs and sizes
  iboSize = sizeof(uint32_t) * (uint32_t)indices.size();
  vboSize = sizeof(float) * 5 * (uint32_t)points.size();

  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> iboBufferSPtr2(
    new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));
  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> vboBufferSPtr2(
    new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));

  CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer2 = iboBufferSPtr2.get();
  CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer2 = vboBufferSPtr2.get();

  for (auto a : indices) iboBuffer2->write(a);
  for (size_t i = 0; i < points.size(); i++) {
    vboBuffer2->write(static_cast<float>(points[i].x()));
    vboBuffer2->write(static_cast<float>(points[i].y()));
    vboBuffer2->write(static_cast<float>(points[i].z()));
    vboBuffer2->write(static_cast<float>(txt_coords[i].x()));
    vboBuffer2->write(static_cast<float>(txt_coords[i].y()));
  }

  //add the actual points and colors

  uniqueNodeID = id + "colorMapLegendTextFont" + ss.str();
  vboName = uniqueNodeID + "VBO";
  iboName = uniqueNodeID + "IBO";
  passName = uniqueNodeID + "Pass2";

  // NOTE: Attributes will depend on the color scheme. We will want to
  // normalize the colors if the color scheme is COLOR_IN_SITU.

  // Construct VBO.
  shader = "Shaders/ColorMapLegendText";
  attribs.clear();
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aPos", 3 * sizeof(float)));
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aTexCoord", 2 * sizeof(float)));
  uniforms.clear();
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uExtraSpace", extraSpace ? 1. : 0.));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplaySide", static_cast<float>(displaySide)));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplayLength", static_cast<float>(displayLength)));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uColor", glm::vec4(red,green,blue,1.0f)));
  GeometryObject::SpireVBO geomVBO2 = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr2,
    numVBOElements, Core::Geometry::BBox(), true);

  geom->mVBOs.push_back(geomVBO2);

  // Construct IBO.

  GeometryObject::SpireIBO geomIBO2(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr2);
  geom->mIBOs.push_back(geomIBO2);
  renState.set(RenderState::USE_COLORMAP, false);
  renState.set(RenderState::USE_TRANSPARENCY, true);
  GeometryObject::SpireSubPass pass2(passName, vboName, iboName, shader,
    GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO2, geomIBO2);

  // Add all uniforms generated above to the pass.
  for (const auto& uniform : uniforms) { pass2.addUniform(uniform); }

  geom->mPasses.push_back(pass2);

  return geom;
}

AlgorithmParameterName ShowColorMapModule::DisplaySide("DisplaySide");
AlgorithmParameterName ShowColorMapModule::DisplayLength("DisplayLength");
AlgorithmParameterName ShowColorMapModule::TextSize("TextSize");
AlgorithmParameterName ShowColorMapModule::TextColor("TextColor");
AlgorithmParameterName ShowColorMapModule::Labels("Labels");
AlgorithmParameterName ShowColorMapModule::Scale("Scale");
AlgorithmParameterName ShowColorMapModule::Units("Units");
AlgorithmParameterName ShowColorMapModule::SignificantDigits("SignificantDigits");
AlgorithmParameterName ShowColorMapModule::AddExtraSpace("AddExtraSpace");
AlgorithmParameterName ShowColorMapModule::TextRed("TextRed");
AlgorithmParameterName ShowColorMapModule::TextGreen("TextGreen");
AlgorithmParameterName ShowColorMapModule::TextBlue("TextBlue");
<commit_msg>Font geometry not added for now until debugged to work on windows.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
   */

#include <Modules/Visualization/ShowColorMapModule.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Algorithms/Visualization/DataConversions.h>
#include <Core/Datatypes/ColorMap.h>
#include <Core/Datatypes/Color.h>
#include <Core/GeometryPrimitives/Vector.h>

using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun;

ShowColorMapModule::ShowColorMapModule() : GeometryGeneratingModule(ModuleLookupInfo("ShowColorMap", "Visualization", "SCIRun"))
{
  INITIALIZE_PORT(ColorMapObject);
  INITIALIZE_PORT(GeometryOutput);
}

void ShowColorMapModule::setStateDefaults()
{
  auto state = get_state();
  state->setValue(DisplaySide, 0);
  state->setValue(DisplayLength, 0);
  state->setValue(TextSize, 2);
  state->setValue(TextRed, 1.);
  state->setValue(TextGreen, 1.);
  state->setValue(TextBlue, 1.);
  state->setValue(Labels, 10);
  state->setValue(Scale, 1.0);
  state->setValue(Units, std::string(""));
  state->setValue(SignificantDigits, 2);
  state->setValue(AddExtraSpace, false);
}

void ShowColorMapModule::execute()
{
  auto colorMap = getRequiredInput(ColorMapObject);
  if (needToExecute())
  {
    std::ostringstream ostr;
    ostr << get_id() << "_" <<
      colorMap->getColorMapInvert() << colorMap->getColorMapName() << colorMap->getColorMapRescaleScale() <<
      colorMap->getColorMapRescaleShift() << colorMap->getColorMapResolution() << colorMap.get() <<
      colorMap->getColorMapShift();
    GeometryHandle geom = buildGeometryObject(colorMap, get_state(), ostr.str());
    sendOutput(GeometryOutput, geom);
  }
}

GeometryHandle
ShowColorMapModule::buildGeometryObject(ColorMapHandle cm, ModuleStateHandle state, const std::string& id)
{
  std::vector<Vector> points;
  std::vector<ColorRGB> colors;
  std::vector<uint32_t> indices;
  int32_t numVBOElements = 0;
  ColorMap * map = cm.get();
  double resolution = 1. / static_cast<double>(map->getColorMapResolution());
  //show colormap does not rescale colors, so reset them. we want to see the whole colormap on the scale.
  ColorMap new_map(map->getColorMapName(),map->getColorMapResolution(),
                   map->getColorMapShift(),map->getColorMapInvert(), 1.,0.);
  for (double i = 0.; std::abs(i - 1.) > 0.000001; i += resolution) {
    ColorRGB col = new_map.valueToColor(i);
    uint32_t offset = (uint32_t)points.size();
    points.push_back(Vector(0., i, +0.001));
    colors.push_back(col);
    points.push_back(Vector(1., i, +0.001));
    colors.push_back(col);
    points.push_back(Vector(0., i + resolution, +0.001));
    colors.push_back(col);
    points.push_back(Vector(1., i + resolution, +0.001));
    colors.push_back(col);
    numVBOElements += 2;
    indices.push_back(offset + 0);
    indices.push_back(offset + 1);
    indices.push_back(offset + 3);
    indices.push_back(offset + 3);
    indices.push_back(offset + 2);
    indices.push_back(offset + 0);
  }

  // IBO/VBOs and sizes
  uint32_t iboSize = sizeof(uint32_t) * (uint32_t)indices.size();
  uint32_t vboSize = sizeof(float) * 7 * (uint32_t)points.size();

  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> iboBufferSPtr(
    new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));
  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> vboBufferSPtr(
    new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));

  CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer = iboBufferSPtr.get();
  CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer = vboBufferSPtr.get();

  for (auto a : indices) iboBuffer->write(a);

  for (size_t i = 0; i < points.size(); i++) {
    vboBuffer->write(static_cast<float>(points[i].x()));
    vboBuffer->write(static_cast<float>(points[i].y()));
    vboBuffer->write(static_cast<float>(points[i].z()));
    vboBuffer->write(static_cast<float>(colors[i].r()));
    vboBuffer->write(static_cast<float>(colors[i].g()));
    vboBuffer->write(static_cast<float>(colors[i].b()));
    vboBuffer->write(static_cast<float>(1.f));
  }

  //add the actual points and colors

  auto st = get_state();
  int sigdig = st->getValue(SignificantDigits).toInt();
  int numlabel = st->getValue(Labels).toInt();
  int txtsize = st->getValue(TextSize).toInt();
  double scale = st->getValue(Scale).toDouble();
  int displaySide = state->getValue(DisplaySide).toInt();
  float red = static_cast<float>(st->getValue(TextRed).toDouble());
  float green = static_cast<float>(st->getValue(TextGreen).toDouble());
  float blue = static_cast<float>(st->getValue(TextBlue).toDouble());
  std::stringstream ss;
  ss << resolution << sigdig << txtsize << numlabel << st->getValue(Units).toString() <<
    scale << displaySide << red << green << blue;

  std::string uniqueNodeID = id + "colorMapLegend" + ss.str();
  std::string vboName = uniqueNodeID + "VBO";
  std::string iboName = uniqueNodeID + "IBO";
  std::string passName = uniqueNodeID + "Pass";

  // NOTE: Attributes will depend on the color scheme. We will want to
  // normalize the colors if the color scheme is COLOR_IN_SITU.

  // Construct VBO.
  std::string shader = "Shaders/ColorMapLegend";
  std::vector<GeometryObject::SpireVBO::AttributeData> attribs;
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aPos", 3 * sizeof(float)));
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aColor", 4 * sizeof(float)));
  std::vector<GeometryObject::SpireSubPass::Uniform> uniforms;
  bool extraSpace = state->getValue(AddExtraSpace).toBool();
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uExtraSpace", extraSpace ? 1.f : 0.f));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplaySide", static_cast<float>(displaySide)));
  int displayLength = state->getValue(DisplayLength).toInt();
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplayLength", static_cast<float>(displayLength)));
  GeometryObject::SpireVBO geomVBO = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr,
    numVBOElements, Core::Geometry::BBox(), true);

  // Construct IBO.

  GeometryObject::SpireIBO geomIBO(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr);

  RenderState renState;
  renState.set(RenderState::IS_ON, true);
  renState.set(RenderState::HAS_DATA, true);

  GeometryObject::SpireSubPass pass(passName, vboName, iboName, shader,
    GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO, geomIBO);

  // Add all uniforms generated above to the pass.
  for (const auto& uniform : uniforms) { pass.addUniform(uniform); }

  Core::Datatypes::GeometryHandle geom(new Core::Datatypes::GeometryObject(nullptr, *this, "ShowColorMap"));

  geom->mColorMap = cm->getColorMapName();
  geom->mIBOs.push_back(geomIBO);
  geom->mVBOs.push_back(geomVBO);
  geom->mPasses.push_back(pass);
  //########################################
  // Now render the numbers for the scale bar

  char str2[128];
  std::stringstream sd;
  sd << "%." << sigdig << "f";
  points.clear();
  indices.clear();
  std::vector<Vector> txt_coords;
  numVBOElements = 0;
  uint32_t count = 0;
  double increment = 1. / static_cast<double>(numlabel - 1);
  double textSize = 10. * static_cast<double>(txtsize + 1) + 30.;

  for (double i = 0.; i <= 1.000000001; i += increment) {
    std::stringstream ss;
    sprintf(str2, sd.str().c_str(), i / cm->getColorMapRescaleScale() - cm->getColorMapRescaleShift());
    ss << str2 << " " << st->getValue(Units).toString();
    text_.reset(ss.str(), textSize, Vector((displaySide == 0) ? 80. : 1., (displaySide == 0) ? 0. : 40., i));
    std::vector<Vector> tmp;
    std::vector<Vector> coords;
    text_.getStringVerts(tmp, coords);
    if (displaySide != 0)
      text_.reset("|", 40., Vector(1., 0., i));
    else
      text_.reset("____", 20., Vector(10., 0., i));
    text_.getStringVerts(tmp, coords);
    for (auto a : tmp) {
      points.push_back(a);
      indices.push_back(count);
      count++;
    }
    for (auto a : coords)
      txt_coords.push_back(a);
  }
  numVBOElements = (uint32_t)points.size();

  // IBO/VBOs and sizes
  iboSize = sizeof(uint32_t) * (uint32_t)indices.size();
  vboSize = sizeof(float) * 5 * (uint32_t)points.size();

  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> iboBufferSPtr2(
    new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));
  std::shared_ptr<CPM_VAR_BUFFER_NS::VarBuffer> vboBufferSPtr2(
    new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));

  CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer2 = iboBufferSPtr2.get();
  CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer2 = vboBufferSPtr2.get();

  for (auto a : indices) iboBuffer2->write(a);
  for (size_t i = 0; i < points.size(); i++) {
    vboBuffer2->write(static_cast<float>(points[i].x()));
    vboBuffer2->write(static_cast<float>(points[i].y()));
    vboBuffer2->write(static_cast<float>(points[i].z()));
    vboBuffer2->write(static_cast<float>(txt_coords[i].x()));
    vboBuffer2->write(static_cast<float>(txt_coords[i].y()));
  }

  //add the actual points and colors

  uniqueNodeID = id + "colorMapLegendTextFont" + ss.str();
  vboName = uniqueNodeID + "VBO";
  iboName = uniqueNodeID + "IBO";
  passName = uniqueNodeID + "Pass2";

  // NOTE: Attributes will depend on the color scheme. We will want to
  // normalize the colors if the color scheme is COLOR_IN_SITU.

  // Construct VBO.
  shader = "Shaders/ColorMapLegendText";
  attribs.clear();
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aPos", 3 * sizeof(float)));
  attribs.push_back(GeometryObject::SpireVBO::AttributeData("aTexCoord", 2 * sizeof(float)));
  uniforms.clear();
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uExtraSpace", extraSpace ? 1. : 0.));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplaySide", static_cast<float>(displaySide)));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uDisplayLength", static_cast<float>(displayLength)));
  uniforms.push_back(GeometryObject::SpireSubPass::Uniform("uColor", glm::vec4(red,green,blue,1.0f)));
  GeometryObject::SpireVBO geomVBO2 = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr2,
    numVBOElements, Core::Geometry::BBox(), true);

  geom->mVBOs.push_back(geomVBO2);

  // Construct IBO.

  GeometryObject::SpireIBO geomIBO2(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr2);
  geom->mIBOs.push_back(geomIBO2);
  renState.set(RenderState::USE_COLORMAP, false);
  renState.set(RenderState::USE_TRANSPARENCY, true);
  GeometryObject::SpireSubPass pass2(passName, vboName, iboName, shader,
    GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO2, geomIBO2);

  // Add all uniforms generated above to the pass.
  for (const auto& uniform : uniforms) { pass2.addUniform(uniform); }
  /*******************************************************************************************
  // TODO we're not adding this geometry (font) until we debug for it to work on Windows.
  geom->mPasses.push_back(pass2);
  *******************************************************************************************/
  return geom;
}

AlgorithmParameterName ShowColorMapModule::DisplaySide("DisplaySide");
AlgorithmParameterName ShowColorMapModule::DisplayLength("DisplayLength");
AlgorithmParameterName ShowColorMapModule::TextSize("TextSize");
AlgorithmParameterName ShowColorMapModule::TextColor("TextColor");
AlgorithmParameterName ShowColorMapModule::Labels("Labels");
AlgorithmParameterName ShowColorMapModule::Scale("Scale");
AlgorithmParameterName ShowColorMapModule::Units("Units");
AlgorithmParameterName ShowColorMapModule::SignificantDigits("SignificantDigits");
AlgorithmParameterName ShowColorMapModule::AddExtraSpace("AddExtraSpace");
AlgorithmParameterName ShowColorMapModule::TextRed("TextRed");
AlgorithmParameterName ShowColorMapModule::TextGreen("TextGreen");
AlgorithmParameterName ShowColorMapModule::TextBlue("TextBlue");
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: javachild.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-03 16:05:04 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef SOLAR_JAVA
#include <jni.h>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#include <unohelp.hxx>
#include <rtl/process.h>
#include <rtl/ref.hxx>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#include <window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif
#include "javachild.hxx"
#include <svdata.hxx>
#include <sysdata.hxx>

using namespace ::com::sun::star;

// -------------------
// - JavaChildWindow -
// -------------------

JavaChildWindow::JavaChildWindow( Window* pParent, WinBits nStyle ) :
    SystemChildWindow( pParent, nStyle )
{
}

// -----------------------------------------------------------------------

JavaChildWindow::JavaChildWindow( Window* pParent, const ResId& rResId ) :
    SystemChildWindow( pParent, rResId )
{
}

// -----------------------------------------------------------------------

JavaChildWindow::~JavaChildWindow()
{
}

// -----------------------------------------------------------------------

void JavaChildWindow::implTestJavaException( void* pEnv )
{
#ifdef SOLAR_JAVA
    JNIEnv*     pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );
    jthrowable  jtThrowable = pJavaEnv->ExceptionOccurred();

    if( jtThrowable )
    { // is it a java exception ?
#if OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionDescribe();
#endif // OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionClear();

        jclass          jcThrowable = pJavaEnv->FindClass("java/lang/Throwable");
        jmethodID       jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, "getMessage", "()Ljava/lang/String;");
        jstring         jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);
        ::rtl::OUString ouMessage;

        if(jsMessage)
        {
            const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);
            ouMessage = ::rtl::OUString(jcMessage);
            pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);
        }

        throw uno::RuntimeException(ouMessage, uno::Reference<uno::XInterface>());
    }
#endif // SOLAR_JAVA
}

// -----------------------------------------------------------------------

sal_Int32 JavaChildWindow::getParentWindowHandleForJava()
{
    sal_Int32 nRet = 0;

#if defined WNT
    nRet = reinterpret_cast< sal_Int32 >( GetSystemData()->hWnd );
#elif defined UNX
#ifdef SOLAR_JAVA
    uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );

    if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )
    {
        JavaVM*                                         pJVM;
        ::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;
        uno::Reference< java::XJavaVM >                 xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), uno::UNO_QUERY );
        uno::Sequence< sal_Int8 >                       aProcessID( 17 );

        rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );
        aProcessID[ 16 ] = 0;
        OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), "Pointer cannot be represented as sal_Int64");
        sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));
        xJavaVM->getJavaVM(aProcessID) >>= nPointer;
        xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);

        if( xVM.is() )
        {
            try
            {
                ::jvmaccess::VirtualMachine::AttachGuard    aVMAttachGuard( xVM );
                JNIEnv*                                     pEnv = aVMAttachGuard.getEnvironment();

                jclass jcToolkit = pEnv->FindClass("java/awt/Toolkit");
                implTestJavaException(pEnv);

                jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, "getDefaultToolkit", "()Ljava/awt/Toolkit;" );
                implTestJavaException(pEnv);

                pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);
                implTestJavaException(pEnv);

                jclass jcMotifAppletViewer = pEnv->FindClass("sun/plugin/navig/motif/MotifAppletViewer");
                if( pEnv->ExceptionOccurred() )
                {
                    pEnv->ExceptionClear();

                    jcMotifAppletViewer = pEnv->FindClass( "sun/plugin/viewer/MNetscapePluginContext");
                    implTestJavaException(pEnv);
                }

                jclass jcClassLoader = pEnv->FindClass("java/lang/ClassLoader");
                implTestJavaException(pEnv);

                jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, "loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V");
                implTestJavaException(pEnv);

                jstring jsplugin = pEnv->NewStringUTF("javaplugin_jni");
                implTestJavaException(pEnv);

                pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);
                implTestJavaException(pEnv);

                jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, "getWidget", "(IIIII)I" );
                implTestJavaException(pEnv);

                const Size aSize( GetOutputSizePixel() );
                jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,
                                                            GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );
                implTestJavaException(pEnv);

                nRet = (sal_Int32) ji_widget;
            }
            catch( ::jvmaccess::VirtualMachine::AttachGuard::CreationException& )
            {
                throw uno::RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                    "JavaChildWindow::getJavaWindowHandle: Could not create jvmaccess::VirtualMachine::AttachGuard!")), 0);
            }
        }
    }
#endif // SOLAR_JAVA
#else // WNT || UNX
    // TBD
#endif

    return nRet;
}
<commit_msg>INTEGRATION: CWS jre5issues (1.3.24); FILE MERGED 2004/11/29 13:36:20 ka 1.3.24.1: #i37962#: added support for Java 1.5<commit_after>/*************************************************************************
 *
 *  $RCSfile: javachild.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-31 09:48:09 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef SOLAR_JAVA
#include <jni.h>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#include <unohelp.hxx>
#include <rtl/process.h>
#include <rtl/ref.hxx>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#include <window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif
#include "javachild.hxx"
#include <svdata.hxx>
#include <sysdata.hxx>

using namespace ::com::sun::star;

// -------------------
// - JavaChildWindow -
// -------------------

JavaChildWindow::JavaChildWindow( Window* pParent, WinBits nStyle ) :
    SystemChildWindow( pParent, nStyle )
{
}

// -----------------------------------------------------------------------

JavaChildWindow::JavaChildWindow( Window* pParent, const ResId& rResId ) :
    SystemChildWindow( pParent, rResId )
{
}

// -----------------------------------------------------------------------

JavaChildWindow::~JavaChildWindow()
{
}

// -----------------------------------------------------------------------

void JavaChildWindow::implTestJavaException( void* pEnv )
{
#ifdef SOLAR_JAVA
    JNIEnv*     pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );
    jthrowable  jtThrowable = pJavaEnv->ExceptionOccurred();

    if( jtThrowable )
    { // is it a java exception ?
#if OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionDescribe();
#endif // OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionClear();

        jclass          jcThrowable = pJavaEnv->FindClass("java/lang/Throwable");
        jmethodID       jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, "getMessage", "()Ljava/lang/String;");
        jstring         jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);
        ::rtl::OUString ouMessage;

        if(jsMessage)
        {
            const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);
            ouMessage = ::rtl::OUString(jcMessage);
            pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);
        }

        throw uno::RuntimeException(ouMessage, uno::Reference<uno::XInterface>());
    }
#endif // SOLAR_JAVA
}

// -----------------------------------------------------------------------

sal_Int32 JavaChildWindow::getParentWindowHandleForJava()
{
    sal_Int32 nRet = 0;

#if defined WNT
    nRet = reinterpret_cast< sal_Int32 >( GetSystemData()->hWnd );
#elif defined UNX
#ifdef SOLAR_JAVA
    uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );

    if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )
    {
        try
        {
            JavaVM*                                         pJVM;
            ::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;
            uno::Reference< java::XJavaVM >                 xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), uno::UNO_QUERY );
            uno::Sequence< sal_Int8 >                       aProcessID( 17 );

            rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );
            aProcessID[ 16 ] = 0;
            OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), "Pointer cannot be represented as sal_Int64");
            sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));
            xJavaVM->getJavaVM(aProcessID) >>= nPointer;
            xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);

            if( xVM.is() )
            {
                try
                {
                    ::jvmaccess::VirtualMachine::AttachGuard    aVMAttachGuard( xVM );
                    JNIEnv*                                     pEnv = aVMAttachGuard.getEnvironment();

                    jclass jcToolkit = pEnv->FindClass("java/awt/Toolkit");
                    implTestJavaException(pEnv);

                    jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, "getDefaultToolkit", "()Ljava/awt/Toolkit;" );
                    implTestJavaException(pEnv);

                    pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);
                    implTestJavaException(pEnv);

                    jclass jcMotifAppletViewer = pEnv->FindClass("sun/plugin/navig/motif/MotifAppletViewer");
                    if( pEnv->ExceptionOccurred() )
                    {
                        pEnv->ExceptionClear();

                        jcMotifAppletViewer = pEnv->FindClass( "sun/plugin/viewer/MNetscapePluginContext");
                        implTestJavaException(pEnv);
                    }

                    jclass jcClassLoader = pEnv->FindClass("java/lang/ClassLoader");
                    implTestJavaException(pEnv);

                    jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, "loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V");
                    implTestJavaException(pEnv);

                    jstring jsplugin = pEnv->NewStringUTF("javaplugin_jni");
                    implTestJavaException(pEnv);

                    pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);
                    implTestJavaException(pEnv);

                    jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, "getWidget", "(IIIII)I" );
                    implTestJavaException(pEnv);

                    const Size aSize( GetOutputSizePixel() );
                    jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,
                                                                GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );
                    implTestJavaException(pEnv);

                    nRet = static_cast< sal_Int32 >( ji_widget );
                }
                catch( uno::RuntimeException& )
                {
                }

                if( !nRet )
                    nRet = static_cast< sal_Int32 >( GetSystemData()->aWindow );
            }
        }
        catch( ... )
        {
        }
    }
#endif // SOLAR_JAVA
#else // WNT || UNX
    // TBD
#endif

    return nRet;
}
<|endoftext|>


<commit_before>#include "boost/filesystem.hpp"

#include <assert.h>
#include "itkCenteredSimilarity2DTransform.h"

// my files
#include "Stack.hpp"
#include "NormalizeImages.hpp"
#include "StackInitializers.hpp"
#include "RegistrationBuilder.hpp"
#include "StackAligner.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "StackTransforms.hpp"
#include "OptimizerConfig.hpp"
#include "Profiling.hpp"

void checkUsage(int argc, char const *argv[]) {
  if( argc < 3 )
  {
    cerr << "\nUsage: " << endl;
    cerr << argv[0] << " dataSet outputDir (slice)\n\n";
    exit(EXIT_FAILURE);
  }
}

int main(int argc, char const *argv[]) {
  using namespace boost::filesystem;

  // Verify the number of parameters in the command line
  checkUsage(argc, argv);

  // Process command line arguments
  Dirs::SetDataSet(argv[1]);
  Dirs::SetOutputDirName(argv[2]);
  vector< string > LoResFileNames, HiResFileNames;
  if( argc >= 4)
  {
    LoResFileNames.push_back(Dirs::BlockDir() + argv[3]);
    HiResFileNames.push_back(Dirs::SliceDir() + argv[3]);
  }
  else
  {
    LoResFileNames = getFilePaths(Dirs::BlockDir(), Dirs::SliceFile());
    HiResFileNames = getFilePaths(Dirs::SliceDir(), Dirs::SliceFile());
  }

  // initialise stack objects with correct spacings, sizes etc
  typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
  StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFileNames);
  StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFileNames);
  normalizeImages< StackType >(LoResImages);
  normalizeImages< StackType >(HiResImages);
  boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages);
  boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages);

  // Assert stacks have the same number of slices
  assert(LoResStack->GetSize() == HiResStack->GetSize());

  // initialize stacks' transforms so that 2D images line up at their centres.
  StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") );
  ApplyAdjustments( *LoResStack, LoResFileNames, Dirs::ConfigDir() + "LoRes_adjustments/");
  StackTransforms::InitializeToCommonCentre( *HiResStack );
  StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack );

  // create output dir before write operations
  create_directory( Dirs::ResultsDir() );

  // Generate fixed images to register against
  LoResStack->updateVolumes();
  if( argc < 4)
  {
    writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + "LoResStack.mha" );
  }

  // initialise registration framework
  typedef RegistrationBuilder< StackType > RegistrationBuilderType;
  RegistrationBuilderType registrationBuilder;
  RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();
  StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration);

  // Scale parameter space
  OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() );

  // Add time and memory probes
  itkProbesCreate();

  // perform centered rigid 2D registration on each pair of slices
  itkProbesStart( "Aligning stacks" );
  stackAligner.Update();
  itkProbesStop( "Aligning stacks" );

  // Report the time and memory taken by the registration
  itkProbesReport( std::cout );

  // write rigid transforms
  if( argc < 4)
  {
    HiResStack->updateVolumes();
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResRigidStack.mha" );
    // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResRigidMask.mha" );
  }
  StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack);

  // Scale parameter space
  OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() );

  // perform similarity rigid 2D registration
  stackAligner.Update();

  // write similarity transforms
  if(argc < 4)
  {
    HiResStack->updateVolumes();
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResSimilarityStack.mha" );
  }

  // repeat registration with affine transform
  StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack);
  OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );
  stackAligner.Update();

  if(argc < 4)
  {
    HiResStack->updateVolumes();
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResAffineStack.mha" );
    // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResAffineMask.mha" );
  }

  // Update LoRes as the masks might have shrunk
  LoResStack->updateVolumes();

  // persist mask numberOfTimesTooBig
  saveNumberOfTimesTooBig(*HiResStack, Dirs::ResultsDir() + "numberOfTimesTooBig.txt");

  // write transforms to directories labeled by both ds ratios
  create_directory(Dirs::LoResTransformsDir());
  create_directory(Dirs::HiResTransformsDir());
  Save(*LoResStack, LoResFileNames, Dirs::LoResTransformsDir());
  Save(*HiResStack, HiResFileNames, Dirs::HiResTransformsDir());

  return EXIT_SUCCESS;
}
<commit_msg>BuildVolumes uses boost::program_options.<commit_after>#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"

#include <assert.h>
#include "itkCenteredSimilarity2DTransform.h"

// my files
#include "Stack.hpp"
#include "NormalizeImages.hpp"
#include "StackInitializers.hpp"
#include "RegistrationBuilder.hpp"
#include "StackAligner.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "StackTransforms.hpp"
#include "OptimizerConfig.hpp"
#include "Profiling.hpp"

namespace po = boost::program_options;
using namespace boost::filesystem;

po::variables_map parse_arguments(int argc, char *argv[])
{
  // Declare the supported options.
  po::options_description opts("Options");
  opts.add_options()
      ("help,h", "produce help message")
      ("dataSet", po::value<string>(), "which rat to use")
      ("outputDir", po::value<string>(), "directory to place results")
      ("slice", po::value<string>(), "optional individual slice to register")
  ;

  po::positional_options_description p;
  p.add("dataSet", 1)
   .add("outputDir", 1)
   .add("slice", 1);

  // parse command line
  po::variables_map vm;
	try
	{
  po::store(po::command_line_parser(argc, argv)
            .options(opts)
            .positional(p)
            .run(),
            vm);
	}
	catch (std::exception& e)
	{
	  cerr << "caught command-line parsing error" << endl;
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
  po::notify(vm);

  // if help is specified, or positional args aren't present
  if (vm.count("help") || !vm.count("dataSet") || !vm.count("outputDir")) {
    cerr << "Usage: "
      << argv[0] << " [--dataSet=]RatX [--outputDir=]my_dir"
      << " [[--slice=]0530.bmp] [Options]"
      << endl << endl;
    cerr << opts << "\n";
    exit(EXIT_FAILURE);
  }

  return vm;
}

int main(int argc, char *argv[]) {

  // Parse command line arguments
  po::variables_map vm = parse_arguments(argc, argv);

  // Process command line arguments
  Dirs::SetDataSet( vm["dataSet"].as<string>() );
  Dirs::SetOutputDirName( vm["outputDir"].as<string>() );

  vector< string > LoResFileNames, HiResFileNames;
  if( vm.count("slice") )
  {
    LoResFileNames.push_back(Dirs::BlockDir() + vm["slice"].as<string>());
    HiResFileNames.push_back(Dirs::SliceDir() + vm["slice"].as<string>());
  }
  else
  {
    LoResFileNames = getFilePaths(Dirs::BlockDir(), Dirs::SliceFile());
    HiResFileNames = getFilePaths(Dirs::SliceDir(), Dirs::SliceFile());
  }

  // initialise stack objects with correct spacings, sizes etc
  typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
  StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFileNames);
  StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFileNames);
  normalizeImages< StackType >(LoResImages);
  normalizeImages< StackType >(HiResImages);
  boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages);
  boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages);

  // Assert stacks have the same number of slices
  assert(LoResStack->GetSize() == HiResStack->GetSize());

  // initialize stacks' transforms so that 2D images line up at their centres.
  StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") );
  ApplyAdjustments( *LoResStack, LoResFileNames, Dirs::ConfigDir() + "LoRes_adjustments/");
  StackTransforms::InitializeToCommonCentre( *HiResStack );
  StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack );

  // create output dir before write operations
  create_directory( Dirs::ResultsDir() );

  // Generate fixed images to register against
  LoResStack->updateVolumes();
  if( vm.count("slice") )
  {
    writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + "LoResStack.mha" );
  }

  // initialise registration framework
  typedef RegistrationBuilder< StackType > RegistrationBuilderType;
  RegistrationBuilderType registrationBuilder;
  RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();
  StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration);

  // Scale parameter space
  OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() );

  // Add time and memory probes
  itkProbesCreate();

  // perform centered rigid 2D registration on each pair of slices
  itkProbesStart( "Aligning stacks" );
  stackAligner.Update();
  itkProbesStop( "Aligning stacks" );

  // Report the time and memory taken by the registration
  itkProbesReport( std::cout );

  // write rigid transforms
  if( vm.count("slice") )
  {
    HiResStack->updateVolumes();
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResRigidStack.mha" );
    // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResRigidMask.mha" );
  }
  StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack);

  // Scale parameter space
  OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() );

  // perform similarity rigid 2D registration
  stackAligner.Update();

  // write similarity transforms
  if( vm.count("slice") )
  {
    HiResStack->updateVolumes();
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResSimilarityStack.mha" );
  }

  // repeat registration with affine transform
  StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack);
  OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );
  stackAligner.Update();

  if( vm.count("slice") )
  {
    HiResStack->updateVolumes();
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResAffineStack.mha" );
    // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResAffineMask.mha" );
  }

  // Update LoRes as the masks might have shrunk
  LoResStack->updateVolumes();

  // persist mask numberOfTimesTooBig
  saveNumberOfTimesTooBig(*HiResStack, Dirs::ResultsDir() + "numberOfTimesTooBig.txt");

  // write transforms to directories labeled by both ds ratios
  create_directory(Dirs::LoResTransformsDir());
  create_directory(Dirs::HiResTransformsDir());
  Save(*LoResStack, LoResFileNames, Dirs::LoResTransformsDir());
  Save(*HiResStack, HiResFileNames, Dirs::HiResTransformsDir());

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 * Copyright (C) 2015 Chris Waltrip <walt2178@vandals.uidaho.edu>
 *
 * This file is part of EvoComp-SantaFe
 *
 * EvoComp-SantaFe is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EvoComp-SantaFe is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with EvoComp-SantaFe.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Source file containing the overall execution of the genetic program.
 * Reads in command line arguments from the user including a map file to be
 * used as a test for the Ant.  It then creates a population of potential
 * solutions, runs the evolution process and writes the results to file.
 *
 * @file
 * @date 23 November 2015
 *
 * @todo	Determine how and where to store Ant's position data.
 */

#include <fstream>
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include "trail_map.h"
namespace po = boost::program_options;

/**
 * Reads command line arguments for the program.  Certain arguments will cause
 * the execution of the program to halt, e.g. `--help` or `--input` with an
 * an invalid filename.
 * @param[in]	argc	Number of items in argv.
 * @param[in]	argv	List of command line arguments.
 * @return	Returns the filenames as a `std::vector<std::string>`.
 * @todo	Allow for some maps to be withheld as a final test (after
 *			evolution is complete) to test the bias of the genetic program
 *			towards a specialized solution versus a generalized solution.
 */
 std::vector<std::string> ParseCommandLine(int argc, char **argv);
 /**
  * Returns the utility usage syntax.
  * @param[in]	program_name	Name of the exectued program (i.e, argv[0]).
  * @return	Returns a `std::string` of usage details with the name of the
  *			calling program inserted into the string.
  */
 std::string GetUsageString(std::string program_name);
 /**
  * Returns a vector of the lines in the given file.  This is passed to the
  * TrailMap to construct a new map object.
  * @param[in]	filename	Name of the file to parse.
  * @return	Returns a `std::vector<std::string>` containing the
  *			contents of the file read in.
  */
std::vector<std::string> ParseDataFile(std::string filename);
/**
 * Returns string representation of map.
 * @param[in]	map		Map to print.
 * @param[in]	latex	Add LaTeX wrappings or not.
 * @return	Returns a `std::string` containing contents of the map.
 */
std::string PrintMap(std::vector<std::vector<char>> map, bool latex);

int main(int argc, char **argv, char **envp) {
	/* Genetic Program Constants */
	const size_t kEvolutionCount = 1000;
	const size_t kElitismCount = 2;

	/* Map Constants */
	const size_t kStepLimit = 300;

	/* Population Constants */
	const size_t kPopulationSize = 100;
	const double kMutationRate = 0.03;
	const double kNonterminalCrossoverRate = 0.90;
	const size_t kTournamentSize = 3;

	/* Individual/Node Constants */
	const size_t kTreeDepthMin = 3;
	const size_t kTreeDepthMax = 6;

	std::vector<std::string> files = ParseCommandLine(argc, argv);
	for (std::string f : files) {
		TrailMap map(ParseDataFile(f), kStepLimit);
		std::cout << map.ToString(false) << std::endl << std::endl << std::endl;
	}

	return 0;
}
std::vector<std::string> ParseCommandLine(int argc, char **argv) {
	/* Vector to hold return values */
	std::vector<std::string> filenames;

	/* Parse Command Line arguments and return filename string */
	po::options_description opts("Options");
	opts.add_options()
		("help,h", "print this help and exit")
		("verbose,v", "print extra logging information")
		("input,i", po::value<std::vector<std::string>>(),
		 "specify input file(s)");
	po::positional_options_description positional_opts;
	positional_opts.add("input", -1);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(opts)
			  .positional(positional_opts).run(), vm);
	po::notify(vm);

	if (vm.count("help")) {
		std::cout << GetUsageString(std::string(argv[0])) << std::endl;
		std::cout << opts << std::endl;
		exit(EXIT_SUCCESS);
	}

	if (!vm.count("verbose")) {
		std::clog.rdbuf(nullptr);
	}

	if (vm.count("input")) {
		filenames = vm["input"].as<std::vector<std::string>>();
		for (auto fn : filenames) {
			if (!(std::ifstream(fn).good())) {
				std::cerr << fn << " not found!" << std::endl;
				exit(EXIT_FAILURE);
			}
		}
	} else {
		std::cerr << "Please specify input files" << std::endl;
		std::cerr << GetUsageString(std::string(argv[0])) << std::endl;
		std::cerr << opts << std::endl;
		exit(EXIT_FAILURE);
	}
	return filenames;
}
std::string GetUsageString(std::string program_name) {
	size_t found = program_name.find_last_of("/\\");
	std::string usage = "Usage: " + program_name.substr(found + 1);
	usage += " [options] input_file_1 [input_file_2...]";

	return usage;
}
std::vector<std::string> ParseDataFile(std::string filename) {
	std::ifstream inf;
	std::string line;
	std::vector<std::string> map_file_contents;

	inf.open(filename);
	if (!inf) {
		std::cerr << "Failed to open file: " << filename << std::endl;
		exit(EXIT_FAILURE);
	}

	/* Parse input file */
	while (std::getline(inf, line)) {
		map_file_contents.push_back(line);
	}
	return map_file_contents;
}
std::string PrintMap(TrailMap map, bool latex) {
	return map.ToString(latex);
}<commit_msg>Small meaningless changes to the main file.<commit_after>/*
 * main.cpp
 * Copyright (C) 2015 Chris Waltrip <walt2178@vandals.uidaho.edu>
 *
 * This file is part of EvoComp-SantaFe
 *
 * EvoComp-SantaFe is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EvoComp-SantaFe is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with EvoComp-SantaFe.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Source file containing the overall execution of the genetic program.
 * Reads in command line arguments from the user including a map file to be
 * used as a test for the Ant.  It then creates a population of potential
 * solutions, runs the evolution process and writes the results to file.
 *
 * @file
 * @date 23 November 2015
 *
 * @todo	Determine how and where to store Ant's position data.
 */

#include <fstream>
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include "trail_map.h"
namespace po = boost::program_options;

/**
 * Reads command line arguments for the program.  Certain arguments will cause
 * the execution of the program to halt, e.g. `--help` or `--input` with an
 * an invalid filename.
 * @param[in]	argc	Number of items in argv.
 * @param[in]	argv	List of command line arguments.
 * @return	Returns the filenames as a `std::vector<std::string>`.
 * @todo	Allow for some maps to be withheld as a final test (after
 *			evolution is complete) to test the bias of the genetic program
 *			towards a specialized solution versus a generalized solution.
 */
 std::vector<std::string> ParseCommandLine(int argc, char **argv);
 /**
  * Returns the utility usage syntax.
  * @param[in]	program_name	Name of the exectued program (i.e, argv[0]).
  * @return	Returns a `std::string` of usage details with the name of the
  *			calling program inserted into the string.
  */
 std::string GetUsageString(std::string program_name);
 /**
  * Returns a vector of the lines in the given file.  This is passed to the
  * TrailMap to construct a new map object.
  * @param[in]	filename	Name of the file to parse.
  * @return	Returns a `std::vector<std::string>` containing the
  *			contents of the file read in.
  */
std::vector<std::string> ParseDataFile(std::string filename);
/**
 * Returns string representation of map.
 * @param[in]	map		Map to print.
 * @param[in]	latex	Add LaTeX wrappings or not.
 * @return	Returns a `std::string` containing contents of the map.
 */
std::string PrintMap(std::vector<std::vector<char>> map, bool latex);

int main(int argc, char **argv, char **envp) {
	/* Genetic Program Constants */
	const size_t kEvolutionCount = 1000;
	const size_t kElitismCount = 2;

	/* Map Constants */
	const size_t kStepLimit = 400;

	/* Population Constants */
	const size_t kPopulationSize = 100;
	const double kMutationRate = 0.03;
	const double kNonterminalCrossoverRate = 0.90;
	const size_t kTournamentSize = 3;

	/* Individual/Node Constants */
	const size_t kTreeDepthMin = 3;
	const size_t kTreeDepthMax = 6;

	std::vector<std::string> files = ParseCommandLine(argc, argv);
	for (std::string f : files) {
		TrailMap map(ParseDataFile(f), kStepLimit);
		std::cout << PrintMap(map, false);
		std::cout << std::endl << std::endl;
	}

	return 0;
}
std::vector<std::string> ParseCommandLine(int argc, char **argv) {
	/* Vector to hold return values */
	std::vector<std::string> filenames;

	/* Parse Command Line arguments and return filename string */
	po::options_description opts("Options");
	opts.add_options()
		("help,h", "print this help and exit")
		("verbose,v", "print extra logging information")
		("input,i", po::value<std::vector<std::string>>(),
		 "specify input file(s)");
	po::positional_options_description positional_opts;
	positional_opts.add("input", -1);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(opts)
			  .positional(positional_opts).run(), vm);
	po::notify(vm);

	if (vm.count("help")) {
		std::cout << GetUsageString(std::string(argv[0])) << std::endl;
		std::cout << opts << std::endl;
		exit(EXIT_SUCCESS);
	}

	if (!vm.count("verbose")) {
		std::clog.rdbuf(nullptr);
	}

	if (vm.count("input")) {
		filenames = vm["input"].as<std::vector<std::string>>();
		for (auto fn : filenames) {
			if (!(std::ifstream(fn).good())) {
				std::cerr << fn << " not found!" << std::endl;
				exit(EXIT_FAILURE);
			}
		}
	} else {
		std::cerr << "Please specify input files" << std::endl;
		std::cerr << GetUsageString(std::string(argv[0])) << std::endl;
		std::cerr << opts << std::endl;
		exit(EXIT_FAILURE);
	}
	return filenames;
}
std::string GetUsageString(std::string program_name) {
	size_t found = program_name.find_last_of("/\\");
	std::string usage = "Usage: " + program_name.substr(found + 1);
	usage += " [options] input_file_1 [input_file_2...]";

	return usage;
}
std::vector<std::string> ParseDataFile(std::string filename) {
	std::ifstream inf;
	std::string line;
	std::vector<std::string> map_file_contents;

	inf.open(filename);
	if (!inf) {
		std::cerr << "Failed to open file: " << filename << std::endl;
		exit(EXIT_FAILURE);
	}

	/* Parse input file */
	while (std::getline(inf, line)) {
		map_file_contents.push_back(line);
	}
	return map_file_contents;
}
std::string PrintMap(TrailMap map, bool latex) {
	return map.ToString(latex);
}<|endoftext|>


<commit_before>#include "occaTools.hpp"
#include "occa.hpp"      // For kernelInfo

namespace occa {
  mutex_t::mutex_t(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    int error = pthread_mutex_init(&mutexHandle, NULL);

    if(error){
      std::cout << "Error initializing mutex\n";
      throw 1;
    }
#else
    mutexHandle = CreateMutex(NULL, FALSE, NULL);
#endif
  }

  void mutex_t::free(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    int error = pthread_mutex_destroy(&mutexHandle);

    if(error){
      std::cout << "Error freeing mutex\n";
      throw 1;
    }
#else
    CloseHandle(mutexHandle);
#endif
  }

  void mutex_t::lock(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    pthread_mutex_lock(&mutexHandle);
#else
    WaitForSingleObject(mutexHandle, INFINITE);
#endif
  }

  void mutex_t::unlock(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    pthread_mutex_unlock(&mutexHandle);
#else
    ReleaseMutex(mutexHandle);
#endif
  }

  double currentTime(){
#if OCCA_OS == LINUX_OS

    timespec ct;
    clock_gettime(CLOCK_MONOTONIC, &ct);

    return (double) (ct.tv_sec + (1.0e-9 * ct.tv_nsec));

#elif OCCA_OS == OSX_OS

    uint64_t ct;
    ct = mach_absolute_time();

    const Nanoseconds ct2 = AbsoluteToNanoseconds(*(AbsoluteTime *) &ct);

    return ((double) 1.0e-9) * ((double) ( *((uint64_t*) &ct2) ));

#elif OCCA_OS == WINDOWS_OS
    LARGE_INTEGER timestamp, timerfreq;

    QueryPerformanceFrequency(&timerfreq);
    QueryPerformanceCounter(&timestamp);

    return ((double) timestamp.QuadPart) / ((double) timerfreq.QuadPart);
#endif
  }

  std::string getFileExtension(const std::string &filename){
    const char *c = filename.c_str();
    const char *i = NULL;

    while(*c != '\0'){
      if(*c == '.')
        i = c;

      ++c;
    }

    if(i != NULL)
      return filename.substr(i - filename.c_str() + 1);

    return "";
  }

  void getFilePrefixAndName(const std::string &fullFilename,
                            std::string &prefix,
                            std::string &filename){
    int lastSlash = 0;
    const int chars = fullFilename.size();

#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    for(int i = 0; i < chars; ++i)
      if(fullFilename[i] == '/')
        lastSlash = i;
#else
    for(int i = 0; i < chars; ++i)
      if((fullFilename[i] == '/') ||
         (fullFilename[i] == '\\'))
        lastSlash = i;
#endif

    ++lastSlash;

    prefix   = fullFilename.substr(0, lastSlash);
    filename = fullFilename.substr(lastSlash, chars - lastSlash);
  }

  std::string getMidCachedBinaryName(const std::string &cachedBinary,
                                     const std::string &namePrefix){
    std::string prefix, name;
    getFilePrefixAndName(cachedBinary, prefix, name);

    return (prefix + namePrefix + "_" + name);
  }

  std::string getFileLock(const std::string &filename){
    std::string prefix, name;
    getFilePrefixAndName(filename, prefix, name);

    return (prefix + "._occa_dir_" + name);
  }

  bool haveFile(const std::string &filename){
    std::string lockDir = getFileLock(filename);
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    int mkdirStatus = mkdir(lockDir.c_str(), 0755);

    // Someone else is making it
    if(mkdirStatus && (errno == EEXIST))
      return false;

    return true;
#else
    LPCSTR lockDirStr = lockDir.c_str();
    BOOL mkdirStatus = CreateDirectoryA(lockDirStr, NULL);

    if( mkdirStatus == FALSE) {
      assert(GetLastError() == ERROR_ALREADY_EXISTS);
      return false;
    }
    return true;
#endif
  }

  void waitForFile(const std::string &filename){
    struct stat buffer;

    std::string lockDir   = getFileLock(filename);
    const char *c_lockDir = lockDir.c_str();

    while(stat(c_lockDir, &buffer) == 0)
      /* Do Nothing */;
  }

  void releaseFile(const std::string &filename){
    std::string lockDir = getFileLock(filename);
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    rmdir(lockDir.c_str());
#else
    BOOL retStatus = RemoveDirectoryA(lockDir.c_str());
    assert(retStatus == TRUE);
#endif
  }

  parsedKernelInfo parseFileForFunction(const std::string &filename,
                                        const std::string &cachedBinary,
                                        const std::string &functionName,
                                        const kernelInfo &info){
    const std::string iCachedBinary = getMidCachedBinaryName(cachedBinary, "i");
    const std::string pCachedBinary = getMidCachedBinaryName(cachedBinary, "p");

    parser fileParser;

    std::ofstream fs;
    fs.open(pCachedBinary.c_str());

    fs << info.header << readFile(filename);

    fs.close();
    fs.clear();

    fs.open(iCachedBinary.c_str());
    fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);

    fs.close();

    kernelInfoIterator kIt = fileParser.kernelInfoMap.find(functionName);

    if(kIt != fileParser.kernelInfoMap.end()){
      return parsedKernelInfo( *((kIt++)->second) );
    }

    std::cout << "Could not find function ["
              << functionName << "] in file ["
              << filename     << "].\n";
    throw 1;

    return parsedKernelInfo();
  }

  std::string fnv(const std::string &saltedString){
    const int len = saltedString.size();
    std::stringstream ss;

    int h[8] = {101527, 101531,
                101533, 101537,
                101561, 101573,
                101581, 101599};

    const int p[8] = {102679, 102701,
                      102761, 102763,
                      102769, 102793,
                      102797, 102811};

    for(int c = 0; c < len; ++c)
      for(int i = 0; i < 8; ++i)
        h[i] = (h[i] * p[i]) ^ saltedString[c];

    // int h2[8];

    // for(int i = 0; i < 8; ++i)
    //   h2[i] = ((h[0] & (0xFF << (8*i))) << (8*i + 0))
    //     |     ((h[1] & (0xFF << (8*i))) << (8*i + 1))
    //     |     ((h[2] & (0xFF << (8*i))) << (8*i + 2))
    //     |     ((h[3] & (0xFF << (8*i))) << (8*i + 3))
    //     |     ((h[4] & (0xFF << (8*i))) << (8*i + 4))
    //     |     ((h[5] & (0xFF << (8*i))) << (8*i + 5))
    //     |     ((h[6] & (0xFF << (8*i))) << (8*i + 6))
    //     |     ((h[7] & (0xFF << (8*i))) << (8*i + 7));

    for(int i = 0; i < 8; ++i)
      ss <<  std::hex << h[i];

    return ss.str();
  }

  bool fileExists(const std::string &filename){
    struct stat buffer;
    return (stat(filename.c_str(), &buffer) == 0);
  }

  std::string readFile(const std::string &filename){
    // NBN: handle EOL chars on Windows
    FILE *fp = fopen(filename.c_str(), "r");

    if(!fp){
      printf("Failed to open: %s\n", filename.c_str());
      throw 1;
    }

    struct stat statbuf;
    stat(filename.c_str(), &statbuf);

    const size_t nchars = statbuf.st_size;

    char *buffer = (char*) calloc(nchars + 1, sizeof(char));
    size_t nread = fread(buffer, sizeof(char), nchars, fp);

    buffer[nread] = '\0';

    fclose(fp);

    std::string contents(buffer, nread);

    free(buffer);

    return contents;
  }

  std::string getOCCADir(){
    char *c_occaPath = getenv("OCCA_DIR");

    if(c_occaPath != NULL)
      return c_occaPath;

    std::cout << "Environment variable [OCCA_DIR] is not set.\n";
    throw 1;

    return "";
  }

  std::string getCachePath(){
    char *c_cachePath = getenv("OCCA_CACHE_DIR");

    bool hasDir = false;

    std::string occaCachePath;

    if(c_cachePath != NULL)
      occaCachePath = c_cachePath;
    else{
      std::stringstream ss;
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
      char *c_home = getenv("HOME");
      ss << c_home << "/._occa";

      occaCachePath = ss.str();
#else
      char *c_home = getenv("USERPROFILE");

      ss << c_home << "\\AppData\\Local\\OCCA";

#  if OCCA_64_BIT
      ss << "_amd64";  // use different dir's fro 32 and 64 bit
#  else
      ss << "_x86";    // use different dir's fro 32 and 64 bit
#  endif

      occaCachePath = ss.str();
#endif
    }

    const int chars = occaCachePath.size();

    OCCA_CHECK(0 < chars);

#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    const char slashChar = '/';
#else
    const char slashChar = '\\';
#endif

    // Take out the pesky //'s
    int pos = 0;

    for(int i = 0; i < chars; ++i){
      if(occaCachePath[i] == slashChar)
        while(i < (chars - 1) && occaCachePath[i + 1] == slashChar)
          ++i;

      occaCachePath[pos++] = occaCachePath[i];
    }

    if(occaCachePath[pos - 1] != slashChar){
      if(pos != chars)
        occaCachePath[pos] = slashChar;
      else
        occaCachePath += slashChar;
    }

    if(!fileExists(occaCachePath)){
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
      mkdir(occaCachePath.c_str(), 0755);
#else
      LPCSTR w_occaCachePath = occaCachePath.c_str();
      BOOL mkdirStatus = CreateDirectoryA(w_occaCachePath, NULL);

      if(mkdirStatus == FALSE)
        assert(GetLastError() == ERROR_ALREADY_EXISTS);
#endif
    }

    return occaCachePath;
  }

  bool fileNeedsParser(const std::string &filename){
    std::string ext = getFileExtension(filename);

    return ((ext == "okl") ||
            (ext == "cl") ||
            (ext == "cu"));
  }

  std::string getCachedName(const std::string &filename,
                            const std::string &salt){

    std::string occaCachePath = getCachePath();
    //================================

    const std::string fileContents = readFile(filename);
    const std::string contentsSHA  = fnv(fileContents + salt);

    // Only taking the first 16 characters
    return occaCachePath + contentsSHA.substr(0, 16);
  }

  std::string createIntermediateSource(const std::string &filename,
                                       const std::string &cachedBinary,
                                       const kernelInfo &info){
    std::string prefix, name;
    getFilePrefixAndName(cachedBinary, prefix, name);

    const std::string iCachedBinary = prefix + "i_" + name;

    if(fileNeedsParser(filename)){
      const std::string pCachedBinary = prefix + "p_" + name;
      parser fileParser;

      std::ofstream fs;
      fs.open(pCachedBinary.c_str());

      fs << info.header << readFile(filename);

      fs.close();

      fs.open(iCachedBinary.c_str());
      fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);

      fs.close();
    }
    else{
      std::ofstream fs;
      fs.open(iCachedBinary.c_str());

      fs << info.occaKeywords << info.header << readFile(filename);

      fs.close();
    }

    return iCachedBinary;
  }
};
<commit_msg>[OCCA] Fixed file reading to include null-terminated chars (binaries)<commit_after>#include "occaTools.hpp"
#include "occa.hpp"      // For kernelInfo

namespace occa {
  mutex_t::mutex_t(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    int error = pthread_mutex_init(&mutexHandle, NULL);

    if(error){
      std::cout << "Error initializing mutex\n";
      throw 1;
    }
#else
    mutexHandle = CreateMutex(NULL, FALSE, NULL);
#endif
  }

  void mutex_t::free(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    int error = pthread_mutex_destroy(&mutexHandle);

    if(error){
      std::cout << "Error freeing mutex\n";
      throw 1;
    }
#else
    CloseHandle(mutexHandle);
#endif
  }

  void mutex_t::lock(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    pthread_mutex_lock(&mutexHandle);
#else
    WaitForSingleObject(mutexHandle, INFINITE);
#endif
  }

  void mutex_t::unlock(){
#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)
    pthread_mutex_unlock(&mutexHandle);
#else
    ReleaseMutex(mutexHandle);
#endif
  }

  double currentTime(){
#if OCCA_OS == LINUX_OS

    timespec ct;
    clock_gettime(CLOCK_MONOTONIC, &ct);

    return (double) (ct.tv_sec + (1.0e-9 * ct.tv_nsec));

#elif OCCA_OS == OSX_OS

    uint64_t ct;
    ct = mach_absolute_time();

    const Nanoseconds ct2 = AbsoluteToNanoseconds(*(AbsoluteTime *) &ct);

    return ((double) 1.0e-9) * ((double) ( *((uint64_t*) &ct2) ));

#elif OCCA_OS == WINDOWS_OS
    LARGE_INTEGER timestamp, timerfreq;

    QueryPerformanceFrequency(&timerfreq);
    QueryPerformanceCounter(&timestamp);

    return ((double) timestamp.QuadPart) / ((double) timerfreq.QuadPart);
#endif
  }

  std::string getFileExtension(const std::string &filename){
    const char *c = filename.c_str();
    const char *i = NULL;

    while(*c != '\0'){
      if(*c == '.')
        i = c;

      ++c;
    }

    if(i != NULL)
      return filename.substr(i - filename.c_str() + 1);

    return "";
  }

  void getFilePrefixAndName(const std::string &fullFilename,
                            std::string &prefix,
                            std::string &filename){
    int lastSlash = 0;
    const int chars = fullFilename.size();

#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    for(int i = 0; i < chars; ++i)
      if(fullFilename[i] == '/')
        lastSlash = i;
#else
    for(int i = 0; i < chars; ++i)
      if((fullFilename[i] == '/') ||
         (fullFilename[i] == '\\'))
        lastSlash = i;
#endif

    ++lastSlash;

    prefix   = fullFilename.substr(0, lastSlash);
    filename = fullFilename.substr(lastSlash, chars - lastSlash);
  }

  std::string getMidCachedBinaryName(const std::string &cachedBinary,
                                     const std::string &namePrefix){
    std::string prefix, name;
    getFilePrefixAndName(cachedBinary, prefix, name);

    return (prefix + namePrefix + "_" + name);
  }

  std::string getFileLock(const std::string &filename){
    std::string prefix, name;
    getFilePrefixAndName(filename, prefix, name);

    return (prefix + "._occa_dir_" + name);
  }

  bool haveFile(const std::string &filename){
    std::string lockDir = getFileLock(filename);
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    int mkdirStatus = mkdir(lockDir.c_str(), 0755);

    // Someone else is making it
    if(mkdirStatus && (errno == EEXIST))
      return false;

    return true;
#else
    LPCSTR lockDirStr = lockDir.c_str();
    BOOL mkdirStatus = CreateDirectoryA(lockDirStr, NULL);

    if( mkdirStatus == FALSE) {
      assert(GetLastError() == ERROR_ALREADY_EXISTS);
      return false;
    }
    return true;
#endif
  }

  void waitForFile(const std::string &filename){
    struct stat buffer;

    std::string lockDir   = getFileLock(filename);
    const char *c_lockDir = lockDir.c_str();

    while(stat(c_lockDir, &buffer) == 0)
      /* Do Nothing */;
  }

  void releaseFile(const std::string &filename){
    std::string lockDir = getFileLock(filename);
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    rmdir(lockDir.c_str());
#else
    BOOL retStatus = RemoveDirectoryA(lockDir.c_str());
    assert(retStatus == TRUE);
#endif
  }

  parsedKernelInfo parseFileForFunction(const std::string &filename,
                                        const std::string &cachedBinary,
                                        const std::string &functionName,
                                        const kernelInfo &info){
    const std::string iCachedBinary = getMidCachedBinaryName(cachedBinary, "i");
    const std::string pCachedBinary = getMidCachedBinaryName(cachedBinary, "p");

    parser fileParser;

    std::ofstream fs;
    fs.open(pCachedBinary.c_str());

    fs << info.header << readFile(filename);

    fs.close();
    fs.clear();

    fs.open(iCachedBinary.c_str());
    fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);

    fs.close();

    kernelInfoIterator kIt = fileParser.kernelInfoMap.find(functionName);

    if(kIt != fileParser.kernelInfoMap.end()){
      return parsedKernelInfo( *((kIt++)->second) );
    }

    std::cout << "Could not find function ["
              << functionName << "] in file ["
              << filename     << "].\n";
    throw 1;

    return parsedKernelInfo();
  }

  std::string fnv(const std::string &saltedString){
    const int len = saltedString.size();
    std::stringstream ss;

    int h[8] = {101527, 101531,
                101533, 101537,
                101561, 101573,
                101581, 101599};

    const int p[8] = {102679, 102701,
                      102761, 102763,
                      102769, 102793,
                      102797, 102811};

    for(int c = 0; c < len; ++c)
      for(int i = 0; i < 8; ++i)
        h[i] = (h[i] * p[i]) ^ saltedString[c];

    // int h2[8];

    // for(int i = 0; i < 8; ++i)
    //   h2[i] = ((h[0] & (0xFF << (8*i))) << (8*i + 0))
    //     |     ((h[1] & (0xFF << (8*i))) << (8*i + 1))
    //     |     ((h[2] & (0xFF << (8*i))) << (8*i + 2))
    //     |     ((h[3] & (0xFF << (8*i))) << (8*i + 3))
    //     |     ((h[4] & (0xFF << (8*i))) << (8*i + 4))
    //     |     ((h[5] & (0xFF << (8*i))) << (8*i + 5))
    //     |     ((h[6] & (0xFF << (8*i))) << (8*i + 6))
    //     |     ((h[7] & (0xFF << (8*i))) << (8*i + 7));

    for(int i = 0; i < 8; ++i)
      ss <<  std::hex << h[i];

    return ss.str();
  }

  bool fileExists(const std::string &filename){
    struct stat buffer;
    return (stat(filename.c_str(), &buffer) == 0);
  }

  std::string readFile(const std::string &filename){
    // NBN: handle EOL chars on Windows
    FILE *fp = fopen(filename.c_str(), "r");

    if(!fp){
      printf("Failed to open: %s\n", filename.c_str());
      throw 1;
    }

    struct stat statbuf;
    stat(filename.c_str(), &statbuf);

    const size_t nchars = statbuf.st_size;

    char *buffer = (char*) calloc(nchars + 1, sizeof(char));
    size_t nread = fread(buffer, sizeof(char), nchars, fp);

    buffer[nread] = '\0';

    fclose(fp);

    std::string contents(buffer, nread + 1);

    free(buffer);

    return contents;
  }

  std::string getOCCADir(){
    char *c_occaPath = getenv("OCCA_DIR");

    if(c_occaPath != NULL)
      return c_occaPath;

    std::cout << "Environment variable [OCCA_DIR] is not set.\n";
    throw 1;

    return "";
  }

  std::string getCachePath(){
    char *c_cachePath = getenv("OCCA_CACHE_DIR");

    bool hasDir = false;

    std::string occaCachePath;

    if(c_cachePath != NULL)
      occaCachePath = c_cachePath;
    else{
      std::stringstream ss;
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
      char *c_home = getenv("HOME");
      ss << c_home << "/._occa";

      occaCachePath = ss.str();
#else
      char *c_home = getenv("USERPROFILE");

      ss << c_home << "\\AppData\\Local\\OCCA";

#  if OCCA_64_BIT
      ss << "_amd64";  // use different dir's fro 32 and 64 bit
#  else
      ss << "_x86";    // use different dir's fro 32 and 64 bit
#  endif

      occaCachePath = ss.str();
#endif
    }

    const int chars = occaCachePath.size();

    OCCA_CHECK(0 < chars);

#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
    const char slashChar = '/';
#else
    const char slashChar = '\\';
#endif

    // Take out the pesky //'s
    int pos = 0;

    for(int i = 0; i < chars; ++i){
      if(occaCachePath[i] == slashChar)
        while(i < (chars - 1) && occaCachePath[i + 1] == slashChar)
          ++i;

      occaCachePath[pos++] = occaCachePath[i];
    }

    if(occaCachePath[pos - 1] != slashChar){
      if(pos != chars)
        occaCachePath[pos] = slashChar;
      else
        occaCachePath += slashChar;
    }

    if(!fileExists(occaCachePath)){
#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)
      mkdir(occaCachePath.c_str(), 0755);
#else
      LPCSTR w_occaCachePath = occaCachePath.c_str();
      BOOL mkdirStatus = CreateDirectoryA(w_occaCachePath, NULL);

      if(mkdirStatus == FALSE)
        assert(GetLastError() == ERROR_ALREADY_EXISTS);
#endif
    }

    return occaCachePath;
  }

  bool fileNeedsParser(const std::string &filename){
    std::string ext = getFileExtension(filename);

    return ((ext == "okl") ||
            (ext == "cl") ||
            (ext == "cu"));
  }

  std::string getCachedName(const std::string &filename,
                            const std::string &salt){

    std::string occaCachePath = getCachePath();
    //================================

    const std::string fileContents = readFile(filename);
    const std::string contentsSHA  = fnv(fileContents + salt);

    // Only taking the first 16 characters
    return occaCachePath + contentsSHA.substr(0, 16);
  }

  std::string createIntermediateSource(const std::string &filename,
                                       const std::string &cachedBinary,
                                       const kernelInfo &info){
    std::string prefix, name;
    getFilePrefixAndName(cachedBinary, prefix, name);

    const std::string iCachedBinary = prefix + "i_" + name;

    if(fileNeedsParser(filename)){
      const std::string pCachedBinary = prefix + "p_" + name;
      parser fileParser;

      std::ofstream fs;
      fs.open(pCachedBinary.c_str());

      fs << info.header << readFile(filename);

      fs.close();

      fs.open(iCachedBinary.c_str());
      fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);

      fs.close();
    }
    else{
      std::ofstream fs;
      fs.open(iCachedBinary.c_str());

      fs << info.occaKeywords << info.header << readFile(filename);

      fs.close();
    }

    return iCachedBinary;
  }
};
<|endoftext|>